A financial analyst has a list of net profit/loss values. Find the count of unique triplets from the list that perfectly cancel each other out (sum to zero).
Explanation: Step-by-step: with input [0, -2, 2, -3, 3], we sort the array to get [-3, -2, 0, 2, 3]. Then we initialize three pointers, left = 0, mid = 1, right = 4. We move the mid pointer to find a pair that sums up to the negation of the leftmost element. If we find a pair, we increment the count and move the left pointer to find another triplet. If we don't find a pair, we move the right pointer to find another pair. Finally, we return the count.
Explanation: Step-by-step: with input [0, 0, 0], we sort the array to get [0, 0, 0]. Then we initialize three pointers, left = 0, mid = 1, right = 2. We move the mid pointer to find a pair that sums up to the negation of the leftmost element. If we find a pair, we increment the count and move the left pointer to find another triplet. If we don't find a pair, we move the right pointer to find another pair. Finally, we return the count.
Analyze constraints and compute optimal solutions step-by-step.
No dry run loaded.
🚀 Practice this problem
Run code, get AI hints & track streak