Problem 1521

Abstract / Summary

Given a function and a target, find the function value closest to the target.

Note

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

Python 1521.py

class Solution:
    def closestToTarget(self, arr: List[int], target: int) -> int:
        result = +inf

        seen = set()
        for a in arr:
            # start new sequence
            next = set([ a ])
            result = min(result, abs(a - target))

            # append to sequence
            for s in seen:
                more = a & s

                result = min(result, abs(more - target))
                if result == 0:
                    return 0 # early exit

                # nice trick I saw in other solutions after submitting mine:
                # a & s <= a
                # therefore if "a" is already smaller than target
                # then there is no way it can contribute to a better result
                if more > target:
                    next.add(more)

            # prepare next round
            seen = next

        return result
29 lines | 912 bytes | submitted June 13, 2024 | GitHub   50% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (30k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Bit Manipulation
  • Segment Tree
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 problem of finding the smallest absolute difference between a given target value and any possible result of a bitwise AND operation applied to a contiguous subsequence of the input list arr. The algorithm proceeds in a single left-to-right pass, maintaining a dynamic collection of AND results that can be obtained from subsequences ending at the current element. At each step it updates the best distance found so far and employs a few pruning tricks to keep the work bounded.

Core Logic

The algorithm starts by initializing the answer with positive infinity, guaranteeing that any concrete distance will replace it.

result = +inf

A set called seen is created to hold the distinct AND values that can be produced by subsequences ending at the previous index.

seen = set()

The outer loop iterates over each integer a in arr. For every element the algorithm treats it as the start of a new subsequence and also attempts to extend all previously recorded subsequences.

for a in arr:
    # start new sequence
    next = set([a])
    result = min(result, abs(a - target))

The inner loop walks through each value s stored in seen. For each such value the algorithm computes the AND of the current element with the previous subsequence result.

    for s in seen:
        more = a & s
        result = min(result, abs(more - target))

If the distance becomes zero, the function returns immediately, because no better answer exists.

        if result == 0:
            return 0  # early exit

A key pruning step follows. Because a bitwise AND can only stay the same or become smaller, any intermediate result that is already less than or equal to the target cannot lead to a better distance in the future. The code therefore discards such values and only keeps results that are strictly greater than the target.

        if more > target:
            next.add(more)

After processing all previously seen values, the set seen is replaced with the newly built next set, ready for the next iteration.

    seen = next

When the loop finishes, the best distance discovered is returned.

return result

Edge Cases Handled

The implementation explicitly evaluates the distance for each single element (a) before attempting any extensions. This ensures that cases where the optimal answer is obtained from a subsequence of length one are correctly captured.

The early-exit condition (if result == 0) handles the situation where an exact match to target is found at any point, allowing the function to stop processing further elements.

The pruning condition (if more > target) implicitly deals with scenarios where the AND result drops below the target early in the computation. By not propagating such values forward, the algorithm avoids unnecessary work while still preserving correctness, because any further AND operations can only decrease the value further away from the target.

Performance Optimizations

The code leverages the monotonic nature of the bitwise AND operation: once a value falls below the target it can never increase again. By filtering out those values (more > target) the algorithm reduces the size of the seen set dramatically, especially for inputs containing large numbers with many set bits.

Using a Python set for seen and next eliminates duplicate AND results that would otherwise cause redundant calculations. This deduplication keeps the number of inner-loop iterations small, even when many different subsequences produce the same AND value.

The early-return on a zero distance prevents the algorithm from traversing the remainder of the array once an optimal solution is identified, saving time in best-case scenarios.

Overall, the combination of set-based deduplication, value pruning based on the target, and an early exit strategy yields an implementation that processes the input efficiently while maintaining a clear and straightforward structure.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big box of colorful building blocks, and each block has a secret number hidden inside. The goal is to find a way to combine these blocks to get a total that is as close as possible to a special target number.

This code starts by looking at the very first block and deciding how far away it is from the goal. It keeps a small notebook to remember the combinations it has already tried so it does not have to do the same work twice. Then, it picks up the next block and sees what happens if it is joined with all the previous combinations.

When two numbers are combined in this way, the total often gets smaller. The code checks every single new combination it makes to see if it is a better match for the target than what it found before. If it ever finds a combination that exactly matches the target, it stops right away because the job is done perfectly.

As it keeps going through the pile of blocks, it ignores combinations that are already too small to be useful. It keeps the best results in its memory until it has looked at every possible path, finding the one that lands closest to the target number.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.56 | σ = 1.87

Complexity Analysis

not analyzed yet

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 C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Go Python TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
FelixFan1122 Java
fsq C++
JoshCrozier JS
keineahnung2345 C++
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
FelixFan1122 Java
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
suxrobGM C#
wisdompeak C++
24 links | 13 authors | 7 languages

Videos

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

Solved On The Same Day

7 solutions   June 13, 2024

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