Skip to content
Advertisement

Given a sum of two elements in an int array, how to find their smallest indexes?

I want to return an array of 2 integers, containing the indexes of a pair of integers in the array whose sum is k.

JavaScript

I have done this method :

JavaScript

With previous array and sum it works & returns:

JavaScript

For example with this:

JavaScript

I should have:

JavaScript

How can I, in case there are several possible pairs whose sum is equal to the target, return the pair with the lowest left index?

And in the case of 2 pairs with the same left index, go for the pair with the lowest right index?

Many thanks in advance

Advertisement

Answer

Assume a return of [n,m] is an valid output where n<>m and m > 0. Assume a return of [0,0] is an exception output indicates the pair is not found.

There are some mistake in your function:

JavaScript

Firstly, if you want to find the smallest index, once you found a matched pair, you could break the for-loop. Since you start searching from the left, the first match must be the smallest. No matter now hard the program try, the next result is not the smallest.

Secondly, I think you try to set a false case condition to return [0,0] if no pair is found. However, the condition is contradict to its outer if condition. That is a unreachable statement. You can put that at the very end of the function since when we reach that part, the searching is already completed. I modified the function as:

JavaScript

the main()

JavaScript

console output

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