Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

4 Sum Problem
Optimal Solution using Two Pointers



Problem Statement

Given an array of integers arr and an integer target, find all unique quadruplets (four numbers) in the array that sum up to the given target value.

If no such quadruplets exist, return an empty list.

Examples

Input ArrayTargetQuadrupletsDescription
[1, 0, -1, 0, -2, 2]0[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]Three unique quadruplets sum to 0
[2, 2, 2, 2, 2]8[[2, 2, 2, 2]]Duplicates allowed in input, but result is unique
[1, 2, 3, 4]50[]No combination of four elements adds to 50
[0, 0, 0, 0]0[[0, 0, 0, 0]]All elements are zero and they form one valid result
[1, -2, -5, -4, -3, 3, 3, 5]-11[[-5, -4, -3, 1]]Only one valid quadruplet with negative target
[1, 2, 3]6[]Less than 4 elements; no quadruplet is possible
[]0[]Empty input array returns an empty list

Solution

The 4 Sum problem asks us to find sets of four numbers in an array that add up to a given target. A brute force method would try every possible combination of four numbers, but this becomes inefficient very quickly as the array grows. Instead, we use a more optimal and structured approach.

Understanding the Problem

We are given an array that may contain positive, negative, or duplicate numbers. We need to find all unique sets of four numbers (quadruplets) such that their sum equals the given target. The key challenge is not just finding these combinations, but doing so efficiently while avoiding duplicates in the result.

How the Efficient Approach Works

First, we sort the array. Sorting helps in two ways:

  • It lets us skip duplicate numbers easily
  • It enables the use of the two-pointer technique

We fix the first two numbers using two nested loops. For each pair, we use two pointers — left and right — to find the remaining two numbers that make the total sum equal to the target.

Handling Duplicates

Since the array can contain duplicates, we must make sure that we don’t return the same set more than once. To handle this:

  • We skip duplicate elements while selecting the first and second numbers in the outer loops.
  • We also skip duplicates while moving the left and right pointers after finding a valid quadruplet.

What Happens in Special Cases?

  • Empty array: No elements means no quadruplets can be formed → return [].
  • Fewer than 4 elements: Again, not enough numbers → return [].
  • All elements are the same: If four or more elements match the target when summed, return one quadruplet only.
  • No valid combination exists: If no group of 4 numbers can meet the target, return an empty list.

Why This Works

The sorted array and two-pointer technique ensure that we don’t waste time checking every possible combination. This reduces the time complexity to O(n3), which is significantly better than the naive O(n4) approach.

By combining sorting, nested loops, and careful duplicate skipping, we ensure the solution is both efficient and accurate.

Algorithm Steps

  1. Given an array arr of size n and a target value target.
  2. Sort the array in ascending order.
  3. Fix the first element with index i (0 to n-4).
  4. Fix the second element with index j (i+1 to n-3).
  5. Use two pointers left = j+1 and right = n-1 to find two other numbers.
  6. If the sum of the four elements equals target, store the quadruplet.
  7. Move pointers intelligently while skipping duplicates to find all unique quadruplets.

Code

Python
JavaScript
Java
C++
C
def four_sum(arr, target):
    arr.sort()
    n = len(arr)
    res = []

    for i in range(n-3):
        if i > 0 and arr[i] == arr[i-1]:
            continue
        for j in range(i+1, n-2):
            if j > i+1 and arr[j] == arr[j-1]:
                continue
            left, right = j+1, n-1
            while left < right:
                total = arr[i] + arr[j] + arr[left] + arr[right]
                if total == target:
                    res.append([arr[i], arr[j], arr[left], arr[right]])
                    left += 1
                    right -= 1
                    while left < right and arr[left] == arr[left-1]:
                        left += 1
                    while left < right and arr[right] == arr[right+1]:
                        right -= 1
                elif total < target:
                    left += 1
                else:
                    right -= 1
    return res

# Sample Input
arr = [1, 0, -1, 0, -2, 2]
target = 0
print("Quadruplets:", four_sum(arr, target))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n^3)Even in the best case, we use two nested loops and a two-pointer approach, leading to cubic time complexity when scanning all possible quadruplets.
Average CaseO(n^3)For each pair of the first two elements (i and j), we use a two-pointer scan through the remaining array. This results in O(n³) combinations on average.
Average CaseO(n^3)The algorithm always uses two nested loops plus a two-pointer traversal, so the worst-case complexity remains cubic.

Space Complexity

O(1) (excluding output)

Explanation: Only a few pointers and loop variables are used for the computation. However, the space needed to store the resulting quadruplets depends on the number of valid combinations found.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M