0

Leetcode Question

I have analyzed the answer for the Leetcode question and am asking for whether my reasoning is correct. I tried analyzing when num = 2 and when num = 7. The analyses are separated by //.

function twoSum(nums, target) {
  var result = []
  nums.forEach(function(num, i) {
    var diff = target - num
    var k = nums.indexOf(diff)
    if (k > -1 && k !== i) {
       result[0] = i
       result[1] = k
    }
  })
  return result
}
twoSum([2,7,11,15], 9)
var diff = target - num

For 2, diff = 9 - 2 = 7. // For 7, diff = 9 - 7 = 2

var k = nums.indexOf(diff)

indexOf(7) = 1 → k = 1. // indexOf(2) = 0 → k = 0.

if (k > -1 && k !== i)

1 > -1 && 1 !== 0. // 0 > -1 && 0 !== 1.

result[0] = i

result[0] = 0. // result[0] = 1

result[1] = k

result[1] = 1. // result[1] = 0

return result

[0,1] // [1, 0]

So the answer is supposed to be [0,1] but when num = 7 I get [1,0] and was wondering why the function is accepted as the correct answer when I get both [0,1] and [1,0].

2 Answers 2

4

Because your answer doesn't need to be sorted. both [0,1] and [1,0] are correct.

Sign up to request clarification or add additional context in comments.

Comments

0

You can return the answer with any order.

see the leetcode description

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.