DEV Community

Discussion on: Two Sum Solution in JavaScript

Collapse
lukaszahradnik profile image
Lukáš Zahradník

The most important thing is in this scenario the Time Complexity is O(n), which is half of the previous one.

This is not true. The time complexity of the second approach is still O(n^2) as indexOf has to still go through whole array - separating inner loop into new function will not reduce the algorithm time complexity.
Also O(n) isn't "half of" the previous one (O(n^2)).

In the first example you should return the result when you find the indices, otherwise you can have array with length > 2.

Collapse
abmsourav profile image
Keramot UL Islam Author • Edited on
  1. In the second function all happening in one loop, so time complexity is O(n). indexOf is an API method. It's way faster than a loop.
  2. Please run the first example and check the output.
Collapse
lukaszahradnik profile image
Lukáš Zahradník
  1. It's happening in two loops - one in your function and the second one in the indexOf. It is still O(n^2).
  2. Try out twoSum([2,4,6,5,6], 8) for both of your solution and you will see the inconsistency of outputs.