How do you find all triplets with zero sum in an array?

DSA
Medium
Google
83.4K views

This problem asks candidates to identify three numbers in an array that add up to zero. It tests proficiency in sorting, two-pointer techniques, and handling duplicate elements efficiently.

Why Interviewers Ask This

Interviewers ask this to evaluate a candidate's ability to optimize brute-force solutions from O(n^3) to O(n^2). They want to see if the candidate can recognize when to use sorting and the two-pointer approach to reduce complexity. Additionally, it assesses attention to detail regarding edge cases like duplicate triplets and ensuring the solution is robust against various input scenarios.

How to Answer This Question

Start by explaining the brute-force O(n^3) approach to set a baseline. Then, propose sorting the array first, which allows for the two-pointer technique. Explain how fixing one element and using two pointers on the remaining subarray reduces the time complexity. Discuss how to handle duplicates by skipping identical values during iteration. Finally, walk through a concrete example step-by-step to demonstrate the logic clearly.

Key Points to Cover

  • Sort the array to enable two-pointer optimization
  • Fix one element and search for the other two dynamically
  • Handle duplicate triplets by skipping repeated values
  • Achieve O(n^2) time complexity instead of O(n^3)

Sample Answer

To solve this efficiently, I would first sort the array in ascending order. Then, I iterate through the array, fixing one element at index i. For the remaining elements, I use two pointers, left and right, initialized to i+1 and n-1 respectively. If the sum of arr[i], arr[left], and arr[right] is zero, I record the triplet and move both pointers inward, skipping duplicates. If the sum is less than zero, I increment the left pointer; if greater, I decrement the right pointer. This approach ensures an O(n^2) time complexity while correctly identifying all unique triplets.

Common Mistakes to Avoid

  • Failing to skip duplicate elements leading to redundant results
  • Not considering the sorted property for optimization
  • Incorrectly handling boundary conditions for pointers

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 35 DSA questionsBrowse all 109 Google questions