Editorial for Two Sum


Approach

Scan left to right while storing previously seen values in a hashmap:

  • At index j, the needed partner value is target - a[j].
  • If that value is already in the hashmap at index i, output i + 1 and j + 1.
  • Otherwise, store a[j] with its index and continue.

Because each lookup and insert is O(1)O(1) on average, total time complexity is O(n)O(n).

Solution (Python)

Code 1
n, target = (int(x) for x in input().split())
a = [int(x) for x in input().split()]

seen: dict[int, int] = {}

for i in range(n):
    need = target - a[i]
    if need in seen:
        print(seen[need] + 1, i + 1)
        break
    seen[a[i]] = i

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.