So I was recently given a coding assignment from a large financial firm, and I thought of two ways to solve the problem. One of the ways involved 1 outer for loop and 1 inner for loop. In this case, the code would be relatively easy to understand, and I saw this method as a more "obvious" solution.
However, I thought of another way that used 4 out for loops consecutively. I'm no expert in Big O, but my understanding is that, asymptotically speaking, 4 outer for loops is O(n) and 1 outer and 1 inner for loop is O(n^2). However, the 4 outer for loops method was definitely a bit harder to understand and less obvious.
I was wondering from a coding assignment question, which method is seen as better? And then in a broader perspective, which one is better? Since I'm still sort of new to the idea of professional coding (I did a lot of casual coding when I was younger) I know there's an idea of balance between readability and efficiency. I was wondering what the balance is in this case.
Sometimes a company has clear preferences for the one or the other; sometimes the development team has preferences.
If you are free to decide, think about the relevance of the performance in this area:
Either way, make sure that your prediction is real (=> measure!). Nothing is worse than a complicated solution that is slower.
If this wasn't an assignment, you could relatively easily guess which one of the solutions is better here.
In most cases, it would be the first one.
In some rare cases (and the fact that you're talking about the financial sector means that you shouldn't ignore this possibility), performance would be key (either because the piece of code will be run hundreds of times per second on thousands of machines, or because saving milliseconds would mean that traders will have a competitive advantage). But:
The goal of an assignment is to see how you will react faced to a given problem. You may:
Find the simple solution and miss the optimized one,
Find the optimized solution and miss the simple one,
Spot both solutions and understand the benefits and drawbacks of each, including how much your second alternative is faster than the first one, why is it more difficult to understand, what can potentially be done to make it easier to understand without sacrificing its performance and what are the drawbacks of the potential change.
You cannot guess (otherwise you wouldn't be asking this question in the first place). Therefore, to be safe, just show that you found both solutions and are ready to suggest the one or the other after you get more information about the actual needs in terms of performance vs. maintainability.