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

DSA
Medium
Google
83.5K views

Direct Answer

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…

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

Sound confident on this question in 5 minutes

Answer once and get a 30-second AI critique of your structure, content, and delivery. First attempt is free — no signup needed.

Try it free

Related Interview Questions

Browse all 127 DSA questionsBrowse all 145 Google questions