Proficient Level

Implement the threeSumTripletCount method that counts unique triplets whose sum is zero.

The input contains an integer array nums and its length size. Your task is to count how many unique triplets have a sum equal to 0.

A triplet uses three different indexes. Duplicate triplets with the same values should be counted only once.

For example, in [-1,0,1,2,-1,-4], the unique zero-sum triplets are [-1,-1,2] and [-1,0,1], so the answer is 2.

Example 1
Input:
nums (int[]) = [-1,0,1,2,-1,-4]
size (int) = 6
Return:
(int) 2
Example 2
Input:
nums (int[]) = [0,0,0]
size (int) = 3
Return:
(int) 1
Example 3
Input:
nums (int[]) = [1,2,-2,-1]
size (int) = 4
Return:
(int) 0

Sort the array first so duplicate values can be skipped easily.

Fix one number at a time, then use two pointers to find pairs on the right side whose sum completes 0. If a valid triplet is found, increase the count and move both pointers while skipping duplicate values.

Sorting also helps decide whether to move the left pointer or right pointer based on whether the current sum is too small or too large.

Pseudocode:

function threeSumTripletCount(nums, size):
    sort nums
    count = 0
    for i from 0 to size - 3:
        if i > 0 and nums[i] == nums[i - 1]:
            continue
        left = i + 1
        right = size - 1
        while left < right:
            sum = nums[i] + nums[left] + nums[right]
            if sum == 0:
                count++
                move left forward while duplicate values continue
                move right backward while duplicate values continue
                left++
                right--
            else if sum < 0:
                left++
            else:
                right--
    return count
Run your code to see the result.