← Whiteboard questions

Find two numbers that add up to a target

DSA, Easy

Which structure or algorithm, and what does it cost.

You get a list of integers nums and an integer target. Return the positions [i, j] of two different elements whose values add up to target. If no such pair exists, return []. If several pairs exist, return any one. You may not use the same position twice, but two equal values at different positions are allowed.

Examples

Input nums = [2, 7, 11, 15], target = 9
Output [0, 1]
Why because 2 + 7 = 9.
Input nums = [3, 3], target = 6
Output [0, 1]
Why because the two 3s are at different positions.
Input nums = [3, 2, 4], target = 6
Output [1, 2]
Why Position 0 alone does not count: 3 + 3 would reuse it.

Constraints

Your answer must contain

Find two numbers that add up to a target · OpsKarma