How do you find all unique triplets summing to zero in O(n^2) time without using extra hash set memory? | A1LabDavid to DSAEnglish • 17 hours ago

How do you find all unique triplets summing to zero in O(n^2) time without using extra hash set memory?

message-square
0
1
How do you find all unique triplets summing to zero in O(n^2) time without using extra hash set memory?
How do you find all unique triplets summing to zero in O(n^2) time without using extra hash set memory? | A1LabDavid to DSAEnglish • 17 hours ago

The 3Sum Problem: $O(n^2)$ Time and $O(1)$ Auxiliary Space

To find all unique triplets $[a, b, c]$ such that $a + b + c = 0$ without using an auxiliary hash set to track duplicates, sort the array first and combine a fixed anchor pointer with a two-pointer sweep. Duplicates are bypassed directly in-place by skipping adjacent identical values.


Algorithmic Strategy

  1. Sort the Array: Sorting takes $O(n \log n)$ time and brings identical elements together, which enables trivial in-place duplicate filtering.
  2. Anchor Outer Loop (i): Iterate from index 0 up to n - 3. If arr[i] > 0, terminate early because the remaining sorted elements cannot sum to zero. Skip iteration if arr[i] == arr[i - 1] to prevent duplicate triplets from the same anchor.
  3. Two-Pointer Search (left & right): Set left = i + 1 and right = n - 1. Calculate sum = arr[i] + arr[left] + arr[right]:
    • If sum == 0: Record the triplet. Advance left while arr[left] == arr[left + 1] and retreat right while arr[right] == arr[right - 1] to purge duplicate components, then move both pointers inward once more.
    • If sum < 0: Increment left to increase the total sum.
    • If sum > 0: Decrement right to decrease the total sum.

Complexity Analysis

Metric Complexity Explanation
Time Complexity $O(n^2)$ Sorting takes $O(n \log n)$. The outer loop runs $n$ times; each iteration executes a linear two-pointer scan taking $O(n)$. Thus, $O(n \log n) + O(n^2) = O(n^2)$.
Auxiliary Space $O(1)$ No hash sets or lookup buffers are created. Only pointers and loop index primitives are stored (excluding the return output and sorting stack space).

Complete Implementation (C++ & Python)

C++ Implementation

#include <vector>
#include <algorithm>

std::vector<std::vector<int>> threeSum(std::vector<int>& nums) {
    std::vector<std::vector<int>> result;
    int n = nums.size();
    if (n < 3) return result;

    // In-place sort to enable two-pointer traversal
    std::sort(nums.begin(), nums.end());

    for (int i = 0; i < n - 2; ++i) {
        // Optimization: Smallest element > 0 means sum cannot be 0
        if (nums[i] > 0) break;

        // Skip duplicates for the anchor element
        if (i > 0 && nums[i] == nums[i - 1]) continue;

        int left = i + 1;
        int right = n - 1;

        while (left < right) {
            int sum = nums[i] + nums[left] + nums[right];

            if (sum == 0) {
                result.push_back({nums[i], nums[left], nums[right]});

                // Skip duplicates for left pointer
                while (left < right && nums[left] == nums[left + 1]) left++;
                // Skip duplicates for right pointer
                while (left < right && nums[right] == nums[right - 1]) right--;

                left++;
                right--;
            } else if (sum < 0) {
                left++;
            } else {
                right--;
            }
        }
    }
    return result;
}

Python Implementation

def three_sum(nums: list[int]) -> list[list[int]]:
    nums.sort()
    result = []
    n = len(nums)

    for i in range(n - 2):
        # Optimization: sorted list with anchor > 0 cannot yield sum == 0
        if nums[i] > 0:
            break

        # Skip duplicate anchor elements
        if i > 0 and nums[i] == nums[i - 1]:
            continue

        left, right = i + 1, n - 1

        while left < right:
            total = nums[i] + nums[left] + nums[right]

            if total == 0:
                result.append([nums[i], nums[left], nums[right]])

                # Skip adjacent duplicates without hash sets
                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 < 0:
                left += 1
            else:
                right -= 1

    return result

Critical In-Place Deduplication Logic

  • Anchor check: nums[i] == nums[i - 1] ensures the first appearance of a number handles all possible pairings; subsequent identical numbers are ignored.
  • Inner check: After finding a match, the while loops move past all identical values for both left and right. Advancing both pointers once more guarantees the next pair inspected consists of distinct values without allocating secondary tracking sets.