2Sum and nSum Flashcards

(9 cards)

1
Q

What is the 2Sum problem?

A

You’re given an array nums and a target value. The goal is to find two numbers that add up to the target. This can be solved either to find just one valid pair or all unique pairs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What’s the most efficient way to solve 2Sum if I only need one pair?

A

Use a HashMap.

def twoSum(nums, target):
seen = {}
for i, num in enumerate(nums):
diff = target - num
if diff in seen:
return [seen[diff], i]
seen[num] = i

This gives you one valid pair in O(n) time and O(n) space.

Great for unsorted arrays.

Doesn’t give you all combinations or handle duplicates cleanly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do I find all unique 2Sum pairs (combinations) instead of just one?

A

Sort the array and use the two-pointer approach.

def twoSumAll(nums, target):
nums.sort()
res = []
left, right = 0, len(nums) - 1

while left < right:
    total = nums[left] + nums[right]
    if total == target:
        res.append([nums[left], nums[right]])
        while left < right and nums[left] == nums[left + 1]: left += 1
        while left < right and nums[right] == nums[right - 1]: right -= 1
        left += 1
        right -= 1
    elif total < target:
        left += 1
    else:
        right -= 1

return res

Requires sorting, but allows duplicate skipping.

Scales to 3Sum, 4Sum, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the nSum (or kSum) problem?

A

It’s a generalized version of 2Sum. You’re trying to find all unique combinations of n numbers that add up to a given target.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What strategy is used to solve nSum problems like 3Sum, 4Sum, etc.?

A

Use a recursive approach where:

You sort the array first.

At each recursive level, you fix one number.

Reduce the problem to (n - 1)Sum on the rest of the array.

Base case is 2Sum, which is solved with the two-pointer method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why do we sort the array first?

A

Sorting allows you to:

Use two-pointer logic in the 2Sum base case.

Easily skip over duplicate numbers.

Prune early if the smallest or largest possible sums can’t reach the target.

Ensure your results are in non-decreasing order so combinations aren’t repeated in different orders.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the start parameter in recursive nSum?

A

It tracks the current scan position so that:

No number is reused in the same combination.

You always move forward in the array.

You can compare nums[i] == nums[i - 1] to skip duplicates cleanly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the full recursive nSum solution look like?

A

Here’s the complete version using recursion and the two-pointer base case:

class Solution:
def nSum(self, nums, target, n):
nums.sort()
return self.kSum(nums, target, n, 0)

def kSum(self, nums, target, k, start):
    res = []
    if start >= len(nums) or k < 2:
        return res

    if k == 2:
        left, right = start, len(nums) - 1
        while left < right:
            total = nums[left] + nums[right]
            if total == target:
                res.append([nums[left], nums[right]])
                while left < right and nums[left] == nums[left + 1]: left += 1
                while left < right and nums[right] == nums[right - 1]: right -= 1
                left += 1
                right -= 1
            elif total < target:
                left += 1
            else:
                right -= 1
    else:
        for i in range(start, len(nums) - k + 1):
            if i > start and nums[i] == nums[i - 1]:
                continue
            if nums[i] * k > target:
                break
            if nums[-1] * k < target:
                break
            for subset in self.kSum(nums, target - nums[i], k - 1, i + 1):
                res.append([nums[i]] + subset)
    return res
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

When should I use HashMap vs Two-Pointer for sum problems?

A

Use HashMap for quick, single-pair lookups in 2Sum.

Use Two-Pointer + Sorting when you need:

All combinations

Duplicate-skipping

Recursive extension to nSum problems

How well did you know this?
1
Not at all
2
3
4
5
Perfectly