3Sum

Python data engineering interview problem. Difficulty: beginner. Pattern: Two Pointers. About 10 minutes. Free to practice.

All unique triplets that sum to zero, sorted. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A data report may contain several groups of three numbers that balance to zero. The report should list each valid group once, even when the input repeats a value. Find every different triplet of numbers whose sum is zero. Sort the three numbers inside each triplet, then sort the outer list. The input may be in any order, and repeated values must not create repeated triplets. Write the function three_sum(nums: list) -> list. For [-1, 0, 1, 2, -1, -4], [-1, -1, 2] and [-1, 0, 1] are the two unique answers. The starter file already has the function name and the harness print lines. Keep them, and fill only the function body.

Requirements

  • Return only triplets whose 3 values add to 0.
  • Sort every triplet in ascending order.
  • Remove duplicate triplets and return the outer list in sorted order.

Constraints

  • nums can be unsorted and can contain repeated values.
  • Return a list of lists, and a value may be used twice only when it appears twice in the input.

Examples

Input: three_sum([-1, 0, 1, 2, -1, -4]) Output: [[-1, -1, 2], [-1, 0, 1]] Two distinct triplets.

Topics: lakebench, python, triplets, sorted.

More Python interview questions · All interview problems · Learn data engineering

beginner

3Sum

Interview-style drill: All unique triplets that sum to zero, sorted.

Implement `three_sum(nums: list) -> list` returning unique triplets that sum to 0. Each triplet sorted ascending; outer list sorted. Example: `[-1, 0, 1, 2, -1, -4]` → `[[-1, -1, 2], [-1, 0, 1]]`. Keep the harness.