Question

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

This is atwo_pointers question.

Idea

  • Sort input array
  • Iterate through input array
    • Establish l, r pointers
    • If i > 0, check if our current num is the same as the last index, then skip if true to avoid duplicates While our pointers do not overlap
      • Sum current a value with b and c from l, and r
      • Check value, if greater than 0, reduce r, if less than 0, increment l,
      • Else:
        • Add combination to res, increment l to try to find another combination
        • While our new nums[l] is the same as our old nums[l] and l < r, increment l to prevent duplicates
  • Return res

Solution