Bird
Raised Fist0
DSA Cprogramming~5 mins

Four Sum Problem All Unique Quadruplets in DSA C - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Four Sum Problem All Unique Quadruplets
O(n³)
Understanding Time Complexity

We want to understand how the time needed to find all unique sets of four numbers that add up to a target grows as the input list grows.

How does the work increase when the list gets bigger?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


void fourSum(int* nums, int numsSize, int target) {
    qsort(nums, numsSize, sizeof(int), compare);
    for (int i = 0; i < numsSize - 3; i++) {
        if (i > 0 && nums[i] == nums[i-1]) continue;
        for (int j = i + 1; j < numsSize - 2; j++) {
            if (j > i + 1 && nums[j] == nums[j-1]) continue;
            int left = j + 1, right = numsSize - 1;
            while (left < right) {
                int sum = nums[i] + nums[j] + nums[left] + nums[right];
                if (sum == target) {
                    // store quadruplet
                    left++; right--;
                    while (left < right && nums[left] == nums[left-1]) left++;
                    while (left < right && nums[right] == nums[right+1]) right--;
                } else if (sum < target) {
                    left++;
                } else {
                    right--;
                }
            }
        }
    }
}
    

This code finds all unique groups of four numbers in a sorted array that add up to the target value.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Nested loops and two-pointer traversal inside the while loop.
  • How many times: Outer loop runs about n times, second loop about n times, and the two-pointer while loop runs up to n times in total for each pair.
How Execution Grows With Input

As the list size grows, the number of operations grows roughly by the cube of the input size.

Input Size (n)Approx. Operations
10About 1,000
100About 1,000,000
1000About 1,000,000,000

Pattern observation: When input size increases 10 times, operations increase about 1000 times, showing cubic growth.

Final Time Complexity

Time Complexity: O(n³)

This means the time needed grows roughly with the cube of the input size, so doubling the input makes the work about eight times bigger.

Common Mistake

[X] Wrong: "The time complexity is O(n⁴) because there are four nested loops."

[OK] Correct: The innermost two-pointer loop does not run n times for each iteration; it moves pointers inward, so total work inside is linear, not quadratic, reducing complexity to O(n³).

Interview Connect

Understanding this time complexity helps you explain how nested loops and two-pointer techniques combine, a common pattern in coding problems.

Self-Check

"What if we changed the problem to find unique triplets instead of quadruplets? How would the time complexity change?"

Practice

(1/5)
1. What is the main goal of the Four Sum Problem in data structures and algorithms?
easy
A. Find the maximum element in the array
B. Sort the array in ascending order
C. Find all unique quadruplets in an array that sum up to a target value
D. Count the number of pairs with a given sum

Solution

  1. Step 1: Understand the problem statement

    The Four Sum Problem asks to find four numbers in an array whose sum equals a target value.
  2. Step 2: Identify the expected output

    We want all unique sets of four numbers (quadruplets) that add up to the target.
  3. Final Answer:

    Find all unique quadruplets in an array that sum up to a target value -> Option C
  4. Quick Check:

    Four Sum = unique quadruplets with target sum [OK]
Hint: Look for four numbers adding to target, not just pairs [OK]
Common Mistakes:
  • Confusing with two or three sum problems
  • Ignoring uniqueness of quadruplets
  • Trying to find maximum or minimum instead of sum
2. Which of the following code snippets correctly initializes the array and target for the Four Sum problem in C?
easy
A. int nums[] = [1, 0, -1, 0, -2, 2]; int target = 0;
B. int nums = {1, 0, -1, 0, -2, 2}; int target = 0;
C. int nums[] = (1, 0, -1, 0, -2, 2); int target = 0;
D. int nums[] = {1, 0, -1, 0, -2, 2}; int target = 0;

Solution

  1. Step 1: Check array initialization syntax in C

    Arrays in C are initialized with curly braces {} and square brackets [] for declaration.
  2. Step 2: Validate each option

    int nums[] = {1, 0, -1, 0, -2, 2}; int target = 0; uses correct syntax: int nums[] = { ... }; int nums = {1, 0, -1, 0, -2, 2}; int target = 0; misses brackets, C uses parentheses, D uses square brackets incorrectly.
  3. Final Answer:

    int nums[] = {1, 0, -1, 0, -2, 2}; int target = 0; -> Option D
  4. Quick Check:

    Correct C array syntax = int nums[] = {1, 0, -1, 0, -2, 2}; int target = 0; [OK]
Hint: Use curly braces {} to initialize arrays in C [OK]
Common Mistakes:
  • Using parentheses () instead of braces {}
  • Missing square brackets [] in declaration
  • Using square brackets [] for initialization
3. Given the following C code snippet, what will be the printed output for the quadruplets found?
int nums[] = {1, 0, -1, 0, -2, 2};
int target = 0;
// Assume function fourSum returns all unique quadruplets
// and prints them as quadruplets separated by spaces
// Output format: a b c d\n for each quadruplet
fourSum(nums, 6, target);
medium
A. 1 0 -1 0 -2 2 0 0 -1 1 0 0
B. -2 -1 1 2 -2 0 0 2 -1 0 0 1
C. -2 -1 0 1 -2 0 0 2 -1 0 1 2
D. No quadruplets found

Solution

  1. Step 1: Sort the array

    Sorted nums = [-2, -1, 0, 0, 1, 2]
  2. Step 2: Find all unique quadruplets summing to 0

    Quadruplets are [-2, -1, 1, 2], [-2, 0, 0, 2], and [-1, 0, 0, 1].
  3. Final Answer:

    -2 -1 1 2 -2 0 0 2 -1 0 0 1 -> Option B
  4. Quick Check:

    Sum of each quadruplet = 0 [OK]
Hint: Sort array first, then use two pointers for pairs [OK]
Common Mistakes:
  • Not sorting array before processing
  • Including duplicate quadruplets
  • Incorrect sum calculation
4. Identify the bug in the following C code snippet for the Four Sum problem:
void fourSum(int* nums, int numsSize, int target) {
    for (int i = 0; i < numsSize - 3; i++) {
        for (int j = i + 1; j < numsSize - 2; j++) {
            int left = j + 1, right = numsSize - 1;
            while (left < right) {
                int sum = nums[i] + nums[j] + nums[left] + nums[right];
                if (sum == target) {
                    printf("%d %d %d %d\n", nums[i], nums[j], nums[left], nums[right]);
                    left++;
                    right--;
                } else if (sum < target) {
                    left++;
                } else {
                    right--;
                }
            }
        }
    }
}
medium
A. No check to skip duplicate quadruplets causing repeated outputs
B. Incorrect initialization of left and right pointers
C. Wrong loop ranges causing out-of-bounds access
D. Missing return statement in void function

Solution

  1. Step 1: Analyze duplicate handling

    The code prints quadruplets but does not skip duplicates, so repeated quadruplets appear.
  2. Step 2: Check other parts

    Left and right pointers are correctly initialized; loop ranges are valid; return statement is not needed in void function.
  3. Final Answer:

    No check to skip duplicate quadruplets causing repeated outputs -> Option A
  4. Quick Check:

    Duplicates not skipped = No check to skip duplicate quadruplets causing repeated outputs [OK]
Hint: Skip duplicates after finding quadruplets to avoid repeats [OK]
Common Mistakes:
  • Not skipping duplicates for i, j, left, right
  • Incorrect pointer updates causing infinite loops
  • Accessing array out of bounds
5. You are given an array nums = {2, 2, 2, 2, 2} and target 8. How many unique quadruplets sum to the target, and what are they?
hard
A. 1 quadruplet: [2, 2, 2, 2]
B. 5 quadruplets: all combinations of 2's
C. 0 quadruplets: no unique quadruplets
D. 4 quadruplets: different indices but same values

Solution

  1. Step 1: Understand array and target

    All elements are 2, target is 8, so quadruplet sum must be 2+2+2+2=8.
  2. Step 2: Count unique quadruplets

    Even though multiple indices exist, the quadruplet values are the same, so only one unique quadruplet exists: [2, 2, 2, 2].
  3. Final Answer:

    1 quadruplet: [2, 2, 2, 2] -> Option A
  4. Quick Check:

    Sum 2+2+2+2=8 unique quadruplet [OK]
Hint: Same values quadruplet counts as one unique quadruplet [OK]
Common Mistakes:
  • Counting quadruplets by indices, not unique values
  • Assuming multiple quadruplets due to duplicates
  • Ignoring uniqueness condition
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