DSA interview question
A chemistry simulator models particles with integer charges and wants every group of three particles whose charges cancel to zero, reported as sets of values with no repeats. Checking all triples is O(n³), and even with a hash set it's awkward to avoid listing the same triplet several times. The standard answer sorts first, fixes one value, and solves a two-pointer two-sum on the rest, skipping duplicate values at every level. The result is O(n²) with no duplicate triplets.
Example: [-1, 0, 1, 2, -1, -4] → [[-1, -1, 2], [-1, 0, 1]].
vector<vector<int>> threeSum(vector<int> nums); // unique triplets (as sorted value lists) summing to 0
Input nums | Output | Explanation |
|---|---|---|
[-1, 0, 1, 2, -1, -4] | [[-1, -1, 2], [-1, 0, 1]] | The two -1s produce each triplet only once |
[0, 1, 1] | [] | |
[0, 0, 0] | [[0, 0, 0]] | |
[-2, 0, 0, 2, 2] | [[-2, 0, 2]] | Duplicates skipped on both pointers |
[1, 2, -2, -1] | [] |
(Confirm: triplets use three different indices; each distinct triplet of values appears once; output sorted.)
On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in