Card 1 / 15
Given an array of integers nums and an integer target, return the indices [i, j] (with i < j) of the two numbers that add up to target. Exactly one such pair exists, and the same index may not be used twice.
nums |
target |
result | why |
|---|---|---|---|
[2, 7, 11, 15] |
9 |
[0, 1] |
2 + 7 = 9 |
[3, 2, 4] |
6 |
[1, 2] |
3 + 3 would reuse index 0 |
[3, 3] |
6 |
[0, 1] |
equal values at distinct indices |
One pass with a hash map from value to index: for each x, look up target - x before storing x, so an index is never paired with itself. time instead of the scan over all pairs.
def two_sum(nums, target):
"""Return the indices [i, j] (i < j) of the two numbers that sum to target.
Exactly one such pair exists."""
seen = {} # value -> index
for j, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], j]
seen[x] = j
return []Card 2 / 15
Given two strings s and t of lowercase letters, return true if t is an anagram of s — the same letters with the same counts, in any order. Two empty strings count as anagrams.