Bird
Raised Fist0
Interview Preptwo-pointersmediumAmazonGoogle

4Sum

Choose your preparation mode4 modes available
📋
Problem

Imagine you are a treasure hunter trying to find four unique gems whose combined value matches exactly a target sum, but you only have a list of gem values.

Given an array nums of n integers and an integer target, return all unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that: 0 <= a, b, c, d < n, a, b, c, and d are distinct indices, and nums[a] + nums[b] + nums[c] + nums[d] == target. The solution set must not contain duplicate quadruplets.

1 ≤ nums.length ≤ 10^5-10^9 ≤ nums[i] ≤ 10^9-10^9 ≤ target ≤ 10^9
Edge cases: Empty array → []Array with less than 4 elements → []All elements are the same and sum matches target → one quadruplet
</>
IDE
def fourSum(nums: list[int], target: int) -> list[list[int]]:public List<List<Integer>> fourSum(int[] nums, int target)vector<vector<int>> fourSum(vector<int>& nums, int target)function fourSum(nums, target)
def fourSum(nums, target):
    # Write your solution here
    pass
class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
        // Write your solution here
        return new ArrayList<>();
    }
}
#include <vector>
using namespace std;

vector<vector<int>> fourSum(vector<int>& nums, int target) {
    // Write your solution here
    return {};
}
function fourSum(nums, target) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: [[1, 0, 0, -1], [-2, -1, 1, 2]]Not sorting input or not sorting quadruplets before adding, causing duplicates or missing quadruplets.✅ Sort input array first and sort quadruplets before adding to result; skip duplicates in loops and pointers.
Wrong: [[2, 2, 2, 2], [2, 2, 2, 2]]Not skipping duplicates properly, resulting in repeated quadruplets.✅ Add duplicate skipping conditions in all loops and pointer movements.
Wrong: [[1, 2, 3, 4]]Returning quadruplets that do not sum to target due to incorrect sum check or off-by-one errors.✅ Verify sum equals target exactly before adding quadruplet.
Wrong: Timeout or no outputUsing brute force O(n^4) approach on large inputs causing TLE.✅ Implement sorting + two pointers with deduplication to achieve O(n^3) time complexity.
✓
Test Cases
t1_01basic
Input{"nums":[1,0,-1,0,-2,2],"target":0}
Expected[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]

After sorting, we find all quadruplets that sum to zero without duplicates.

t1_02basic
Input{"nums":[2,2,2,2,2],"target":8}
Expected[[2,2,2,2]]

All elements are 2 and sum to 8 with quadruplet [2,2,2,2]. Only one unique quadruplet.

t2_01edge
Input{"nums":[],"target":0}
Expected[]

Empty input array returns empty list as no quadruplets exist.

t2_02edge
Input{"nums":[1,2,3],"target":6}
Expected[]

Array length less than 4 means no quadruplets possible.

t2_03edge
Input{"nums":[0,0,0,0],"target":0}
Expected[[0,0,0,0]]

All elements zero and sum zero, only one quadruplet possible.

t3_01corner
Input{"nums":[1,0,-1,0,-2,2],"target":1}
Expected[[-2,0,1,2],[-1,0,0,2]]

Target 1 requires careful pointer movement; greedy approach fails here.

t3_02corner
Input{"nums":[1,1,1,1,2,2,2,2],"target":6}
Expected[[1,1,2,2]]

Tests correct handling of duplicates and exact boundary sums.

t3_03corner
Input{"nums":[1,2,3,4,5,6,7,8],"target":26}
Expected[[5,6,7,8]]

Tests off-by-one errors and correct pointer boundaries.

t4_01performance
Input{"nums":[-50000,-49999,-49998,-49997,-49996,-49995,-49994,-49993,-49992,-49991,-49990,-49989,-49988,-49987,-49986,-49985,-49984,-49983,-49982,-49981,-49980,-49979,-49978,-49977,-49976,-49975,-49974,-49973,-49972,-49971,-49970,-49969,-49968,-49967,-49966,-49965,-49964,-49963,-49962,-49961,-49960,-49959,-49958,-49957,-49956,-49955,-49954,-49953,-49952,-49951,-49950,-49949,-49948,-49947,-49946,-49945,-49944,-49943,-49942,-49941,-49940,-49939,-49938,-49937,-49936,-49935,-49934,-49933,-49932,-49931,-49930,-49929,-49928,-49927,-49926,-49925,-49924,-49923,-49922,-49921,-49920,-49919,-49918,-49917,-49916,-49915,-49914,-49913,-49912,-49911,-49910,-49909,-49908,-49907,-49906,-49905,-49904,-49903,-49902,-49901],"target":-199800}
⏱ Performance - must finish in 2000ms

Large input n=100 tests O(n^3) complexity; must complete within 2 seconds.

Practice

(1/5)
1. You are given an integer array and asked to find all unique triplets that sum to zero. Which approach guarantees an optimal solution in terms of time complexity and handles duplicates efficiently?
easy
A. Sort the array, fix one element, and use a two-pointer approach to find pairs that sum to the negative of the fixed element, skipping duplicates.
B. Use a greedy approach by sorting and picking the smallest and largest elements to form triplets.
C. Use dynamic programming to build up solutions for smaller subsets and combine them to find triplets.
D. Use three nested loops to check all triplets and store unique sorted triplets in a set.

Solution

  1. Step 1: Understand problem constraints

    We need all unique triplets summing to zero, efficiently handling duplicates.
  2. Step 2: Identify approach that handles duplicates and optimizes search

    Sorting and fixing one element allows using a two-pointer approach to find pairs summing to the complement, skipping duplicates efficiently.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sorting + two-pointer approach is O(n^2) and handles duplicates [OK]
Hint: Sorting + two-pointer handles duplicates and runs in O(n²) [OK]
Common Mistakes:
  • Thinking brute force is optimal
  • Using DP which doesn't fit this problem
  • Greedy approach misses some triplets
2. What is the time complexity of the optimal two-pointer approach for the 3Sum Smaller problem when the input array has length n?
medium
A. O(n^2) because the outer loop runs n times and the inner two-pointer scan runs in O(n)
B. O(n^3) because of the nested loops
C. O(n log n) due to sorting dominating the complexity
D. O(n^2 log n) because each two-pointer step involves a binary search

Solution

  1. Step 1: Identify loops and sorting cost

    Sorting takes O(n log n). The main loop runs O(n) times.
  2. Step 2: Analyze inner two-pointer loop

    For each i, two pointers scan the remaining array once, total O(n) per i.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Overall time is O(n log n + n^2) -> O(n^2) dominates [OK]
Hint: Two pointers scan each element once per outer iteration [OK]
Common Mistakes:
  • Confusing two-pointer scan as O(n^2) per iteration
  • Ignoring sorting cost or assuming it dominates
  • Assuming binary search is used inside two-pointer
3. What is the time complexity of the binary search based algorithm for counting pairs with absolute difference at most K in a sorted array of length n?
medium
A. O(n²)
B. O(n log n)
C. O(n)
D. O(log n)

Solution

  1. Step 1: Identify outer loop complexity

    The algorithm iterates over each element once, so outer loop is O(n).
  2. Step 2: Identify inner operation complexity

    For each element, a binary search (bisect_right) is performed in O(log n) time.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Overall complexity is O(n) * O(log n) = O(n log n) [OK]
Hint: Binary search inside a loop yields O(n log n) [OK]
Common Mistakes:
  • Assuming O(n) because binary search is fast
  • Mistaking nested loops for O(n²)
  • Ignoring binary search cost
4. The following code attempts to find the minimum difference between k closest elements but contains a subtle bug. Identify the bug.
medium
A. Not sorting the array before sliding window causes incorrect results.
B. Using max and min inside the loop is inefficient but not a bug.
C. The loop boundary should be len(arr) - k instead of len(arr) - k + 1.
D. The initial value of min_diff should be 0 instead of infinity.

Solution

  1. Step 1: Analyze the approach

    The code uses a sliding window but does not sort the array first.
  2. Step 2: Understand impact of missing sort

    Without sorting, the window elements are not guaranteed to be contiguous in sorted order, so max-min difference may not be minimal.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Sorting is essential before sliding window to ensure correctness [OK]
Hint: Always sort before sliding window for min difference [OK]
Common Mistakes:
  • Ignoring sorting leads to wrong min difference
  • Confusing inefficiency with correctness
  • Off-by-one loop boundary errors
5. What is the time complexity of the optimal two-pointer approach for removing duplicates from a sorted array of length n?
medium
A. O(n) because each element is visited at most twice
B. O(n log n) due to sorting overhead
C. O(n²) due to nested comparisons
D. O(1) since it modifies the array in-place

Solution

  1. Step 1: Identify loops and operations

    The algorithm uses a single for loop iterating over n elements once, with constant time operations inside.
  2. Step 2: Confirm no nested loops or sorting

    No nested loops or sorting steps; each element is compared once or twice, so total time is linear.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Linear scan with two pointers yields O(n) time [OK]
Hint: Single pass over array means O(n) time [OK]
Common Mistakes:
  • Confusing with brute force O(n²)
  • Thinking in-place means O(1) time
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard