⌘K
Flycodx

3Sum

3Sum

MediumArrays16% accepted

Given an integer array nums, return all unique triplets [nums[i], nums[j], nums[k]] such that i, j, k are distinct indices and nums[i] + nums[j] + nums[k] = 0. The solution must not contain duplicate triplets. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=6, nums=[-1 0 1 2 -1 -4] → triplets: "-1 -1 2" and "-1 0 1"

Input format — only if your code reads from stdin

Input format (stdin): - First line: integer n (array size) - Second line: n space-separated integers Output: each valid triplet on its own line, sorted in non-decreasing order, with values space-separated. Print triplets in sorted order. Print "none" if no triplets exist.

Approach

Sort the array. For each index i (skip duplicates), use two pointers left=i+1 and right=n-1 to find pairs summing to -nums[i]. Advance left or right based on comparison, skipping duplicate values.

Input

6 -1 0 1 2 -1 -4

Output

-1 -1 2 -1 0 1
  • •3 ≤ n ≤ 3000, -10^5 ≤ nums[i] ≤ 10^5
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3