DEV Community

Discussion on: Breaking Down JavaScript Solutions To Common Algorithmic Questions (Part 1)

Collapse
 
worsnupd profile image
Daniel Worsnup • Edited

Unless I'm mistaken (please correct me if I'm wrong), the complexity is O(N) for all 6 solutions, where N is the number of letters in the reversed string, the number of letters in the sentence (because of String#split), and the total number of elements in all the arrays. I definitely apologize for being nitpicky here, but my concern is that newer developers will read this and misunderstand what you mean by "optimize" the solution. In this case you're optimizing readability, which is great, but the algorithmic complexity is unchanged.

Thread Thread
 
emmabostian profile image
Emma Bostian ✨

I’m not positive how Math.max works and if the last example functions as a double nested loop. The last example wouldn’t necessarily be O(n) as input size grew and varied (but I’m not sure as to specifics). So the first 2 I believe are O(n) while the last one is probably O(n) given that the sub arrays have a finite set of elements, but for growing and variable input could creep up to O(2) But agreed I should change the wording from optimized.

Thread Thread
 
worsnupd profile image
Daniel Worsnup

Ahh I understand the confusion now. The last example is definitely tricky because it's easy to read it as one loop. In actuality, Math.max has to iterate over the full argument list in order to produce the maximum, making the last example O(N) if you consider N to be the total number of elements across all of the arrays. You could also say the last example is O(N * M) where N is the number of arrays and M is the number of elements in each array, but this assumes that each array has the same length, which may not be the case.