Skip to content
Advertisement

Two sum return statement returns nothing

I’m trying to attempt a problem where I must add two elements in an array to equal a target integer value. I think my code is correct and will return the desired target however the return statement is not returning any value. why is this and how can I fix it?

Thanks

JavaScript

Advertisement

Answer

break is wrongly used. Also, you have to return result. I’m not sure if this code compiles. Is it? You have to call method twoSum(...), too. I see that your array is sorted, which means you can actually solve the problem in O(n) time by using two pointers: left and right, like follows:

JavaScript

Another solution, useful for unsorted arrays, would be to use a hashset -> O(n) time, O(n) space.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement