progress

~/problems / Two pointers

Three positions with a target sum

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min

Write three_values(nums: list[int], target: int) -> list[int] | None.

Find three different positions i, j, k (0-based) such that nums[i] + nums[j] + nums[k] == target, and return them as a list of three indexes (any order). If there are several answers, any one is fine. If none exist, return None.

Example: nums = [2, 7, 5, 1], target = 8 could return [0, 2, 3] (2 + 5 + 1). Equal values at different positions are allowed: nums = [3, 3, 3], target = 9 returns some ordering of [0, 1, 2]. nums = [1, 1, 1], target = 10 returns None.

Constraints: 1 <= len(nums) <= 1200, 1 <= nums[i], target <= 10^9.

⭐ Bonus: the O(n³) triple loop still passes; the speed test earns a star in O(n²).

Show hint

sorting helps, but you must still report original positions, so sort something that remembers them. With the first element fixed, the remaining pair can be found in one linear pass over the sorted rest.

Topic: Two pointers. Sorted input + moving ends inward; skip duplicates; pairs and triples.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc