Notes

Personal notes on various topics

View on GitHub

Three Sum

Problem Statement

Given an integer array nums, find all unique triplets [nums[i], nums[j], nums[k]] such that:

Examples

Example 1

Input: nums = [-1, 0, 1, 2, -1, -4]
Output: [[-1, -1, 2], [-1, 0, 1]]
Explanation:
- (-1) + 0 + 1 = 0
- 0 + 1 + (-1) = 0
- (-1) + 2 + (-1) = 0
Distinct triplets are [-1, 0, 1] and [-1, -1, 2].
Order of output and triplets does not matter.

Example 2

Input: nums = [0, 1, 1]
Output: []
Explanation: No triplet sums to 0.

Example 3

Input: nums = [0, 0, 0]
Output: [[0, 0, 0]]
Explanation: Only one triplet sums to 0.

Constraints

Code Template

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        # Write your code here
        pass

Solutions

Back to Problem List Back to Categories