Problem 16

Abstract / Summary

Given an array and a target value find three numbers whose sum is closest to the target.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0016.py

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()

        max1 = nums[len(nums) - 1]
        max2 = nums[len(nums) - 2]

        limit = 10**5
        high = +limit
        low  = -limit

        for i in range(len(nums)):
            # optimization
            if nums[i] + max2 + max1 <= low:
                continue

            for j in range(i+1, len(nums)):
                # optimization
                if nums[i] + nums[j] + max1 <= low:
                    continue

                for k in range(j+1, len(nums)):
                    sum = nums[i] + nums[j] + nums[k]
                    if high > sum and sum >= target:
                        high = sum
                    if low  < sum and sum <= target:
                        low = sum

                    # optimization
                    if sum >= target:
                        break

        diffHigh = abs(high - target)
        diffLow  = abs(low  - target)
        if diffHigh < diffLow:
            return high
        else:
            return low
38 lines | 1121 bytes | submitted August 15, 2023 | GitHub   10% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (3+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Sorting
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the “three-sum closest” problem: given an integer array nums and a target value target, it returns the sum of three distinct elements whose total is nearest to target. The algorithm begins by sorting the input, then iterates through all possible triples using three nested loops. Throughout the loops it maintains two candidate sums-high and low-that bound the target from above and below, respectively. After the enumeration finishes, the function selects the candidate whose absolute difference to target is smaller.

Key Steps

The first logical step is to sort the array, which enables early termination checks later in the loops.

nums.sort()

The algorithm records the two largest values in the sorted list for use in pruning.

max1 = nums[len(nums) - 1]
max2 = nums[len(nums) - 2]

Two sentinel variables, high and low, are initialized to extreme values that will be tightened as better candidates are discovered.

limit = 10**5
high = +limit
low  = -limit

The outermost loop selects the first element of the triple.

for i in range(len(nums)):
    # optimization
    if nums[i] + max2 + max1 <= low:
        continue

Inside the outer loop, the second loop picks the middle element.

    for j in range(i+1, len(nums)):
        # optimization
        if nums[i] + nums[j] + max1 <= low:
            continue

The innermost loop chooses the third element and computes the current sum.

        for k in range(j+1, len(nums)):
            sum = nums[i] + nums[j] + nums[k]
            if high > sum and sum >= target:
                high = sum
            if low  < sum and sum <= target:
                low = sum

            # optimization
            if sum >= target:
                break

After all triples have been examined, the algorithm compares the distances of high and low from the target and returns the closer one.

diffHigh = abs(high - target)
diffLow  = abs(low  - target)
if diffHigh < diffLow:
    return high
else:
    return low

Edge Cases Handled

When the array contains fewer than three elements, the loops never execute, leaving high and low at their sentinel values. The final comparison still yields a deterministic result based on the initial limits.

If all possible triples produce sums that are either all greater than or all less than the target, the pruning conditions (if nums[i] + max2 + max1 <= low and if nums[i] + nums[j] + max1 <= low) ensure that the algorithm does not discard any viable candidate, because low will be updated only when a sum not exceeding the target is found.

The inner break (if sum >= target: break) handles the situation where the current sum meets or exceeds the target; because the array is sorted, any subsequent k values would only increase the sum, so the loop can safely stop without missing a closer lower bound.

The use of max1 and max2 guarantees that the algorithm correctly evaluates the maximum possible sum for any given i or j, which is essential when the target is far larger than any achievable sum.

Performance Optimizations

The most noticeable optimization is the early-exit checks that skip entire iterations of the outer loops. By comparing the current partial sum with the best lower bound (low), the code avoids exploring triples that cannot improve the result.

if nums[i] + max2 + max1 <= low:
    continue

and

if nums[i] + nums[j] + max1 <= low:
    continue

These conditions rely on the sorted order and the pre-computed maximum elements to quickly determine that any continuation would stay below the current best lower bound, allowing the loops to move on.

Within the innermost loop, the break statement

if sum >= target:
    break

leverages the monotonic increase of the sum as k advances. Once the sum reaches or exceeds the target, further increments of k can only produce larger sums, which would not improve the lower-bound candidate and would be unnecessary for the upper-bound candidate because high is already being updated when a sum is greater than or equal to the target but still less than the current high.

The initialization of high and low with a large positive and negative sentinel (10**5) provides a simple bound that does not require additional data structures, keeping the memory footprint minimal.

Overall, the combination of sorting, pre-computed maximum values, and conditional skips reduces the number of examined triples compared with a naïve triple-nested enumeration, leading to a more efficient execution while preserving correctness.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big box filled with numbered blocks. The goal is to pick three of these blocks and add their numbers together. You want the total to be as close as possible to a special number called the target.

First, all the blocks are lined up from smallest to largest so they are easy to look at. Think of this like putting your toys in a neat row. Two extra large numbers from the end of the row are held aside to help make quick guesses later.

The computer starts a game of hide and seek with these blocks. It uses three tiny helpers to pick different blocks one by one. The helpers go through the line and try out all sorts of combinations. Every time they pick three blocks, they add up the numbers to see what they get.

Sometimes, the helpers know right away that a group of blocks will be too small to be the answer, so they skip those ones to save time. Other times, if they find a group that is already big enough, they move on to look at others. They keep track of two special values throughout the game. One value is the smallest total they found that is still bigger than the target, and the other is the largest total they found that is smaller than the target.

Once all the combinations have been checked, the helpers compare these two special values. They figure out which one is closer to the target number, almost like measuring how many short hops it takes to reach a finish line.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 28 | median = 4 | μ = 4.29 | σ = 1.60

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python C++ Java TS
WalkCCC Python C++ Java
leetcode.ca Python C++ C# JS C Java Go PHP TS
LeetcodeHelp Python C++ Java
MemoryLimitExceeded Python C++
Progiez Python C++ Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
chandansgowda Python
everthis JS
fartem Ruby
fengvyi C++
gaosq0604 Python
Garvit244 Python
halfrost Go
JoshCrozier JS
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
qiyuangong Python
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
vli02 C
vthwang Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, C#, Go, Java, JavaScript, PHP, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
chandansgowda Python
everthis JavaScript
fartem Ruby
fengvyi C++
gaosq0604 Python
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
linouk23 C++
lkwq007 Python
MacJim C++
martianoff Scala
qiyuangong Python
Shamik07 Dart
shreymehul C#
sonugiri1043 C++
suxrobGM C#
vli02 C
vthwang Java
wisdompeak C++
YuriSpiridonov Python
48 links | 30 authors | 13 languages

Videos

20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality