Python Coding Problem

Problem: Unique Triplets

You are given a list of integers nums containing distinct elements. Your task is to find all unique triplets (a, b, c) in the list such that a + b + c = 0. Return a list of lists containing these unique triplets. The solution set must not contain duplicate triplets.

Note:

  • The order of the triplets does not matter. For example, (1, 2, -3) and (-3, 2, 1) are considered the same triplet.
  • Each triplet within the solution set must be sorted in non-decreasing order.

Write a function find_triplets(nums) that takes in the list nums and returns a list of lists representing the unique triplets that sum to zero.

Example:

nums = [-1, 0, 1, 2, -1, -4]
print(find_triplets(nums))

Output:

[[-1, -1, 2], [-1, 0, 1]]

1 Like