AceYourInterviews
Checking sign-in…

1. Two Sum

EasyHash lookup with index ownership

Given an integer array nums and a target, return the indices of the two different elements whose sum equals target. Exactly one pair exists. Either index order is accepted.

Return positions, not the two values. The same position cannot be used twice.

Example 1

Input

nums = [4,8,1,6], target = 10

Output

[0,3]

Explanation: The values at positions 0 and 3 are 4 and 6; their sum is 10.

Example 2

Input

nums = [5,5], target = 10

Output

[0,1]

Explanation: The two equal values occupy different positions. Neither position is reused.

Constraints

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Exactly one pair of distinct indices sums to target. Return its indices in either order.

Follow-up: Can you solve this in less than O(n2) time?

Hints
Hint 1

Fix the larger index. What value must appear earlier?

Hint 2

Store a location for each processed value.

Hint 3

Check the complement before insertion; return the earlier index and current index.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Find a complement

[3,2,4]
6
[1,2]