BackmediumTwo Pointers Salesforce Microsoft

Triplet Zero Sum Solution

Problem Statement

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).

Example 1
Input
[0, -2, 2, -3, 3]
Output
4

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.

Example 2
Input
[0, 0, 0]
Output
1

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.

Constraints

  • 3 <= n <= 3000
  • -10^5 <= arr[i] <= 10^5
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free