Problem 220

Abstract / Summary

Check if any two numbers in an array are within a given value and at most a certain index distance apart.

Note

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

C++ 0220.cpp

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int indexDiff, int valueDiff) {
        // see 219
        map<int, int> last;

        // faster for test cases ...
        reverse(nums.begin(), nums.end());

        for (int i = 0; i < nums.size(); i++)
        {
            auto current = nums[i];
            auto mid = last.lower_bound(current);

            auto check = mid;
            // scan right
            while (check != last.end())
            {
                if (abs(check->first - current) > valueDiff)
                    break;

                if (abs(check->second - i)      <= indexDiff)
                    return true;

                check++;
            }

            // scan left
            check = mid;
            while (check != last.begin())
            {
                check--;

                if (abs(check->first - current) > valueDiff)
                    break;

                if (abs(check->second - i)      <= indexDiff)
                    return true;
            }

            // add
            last[current] = i;
        }

        return false;
    }
};
47 lines | 1192 bytes | submitted August 9, 2023 | GitHub   15% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 25% (1+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Bucket Sort
  • Ordered Set
  • Sliding Window
  • Sorting
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 containsNearbyAlmostDuplicate method determines whether an array contains two distinct elements whose indices differ by at most indexDiff and whose values differ by at most valueDiff. It processes the input in reverse order and uses an ordered map to keep track of previously seen values together with their positions.

Key Steps

Reverse the input sequence

Before the main loop the vector is reversed so that later indices correspond to earlier positions in the original order. This allows the algorithm to treat the current index as the most recent occurrence while still satisfying the distance constraint.

reverse(nums.begin(), nums.end());

Iterate over each element

A simple for loop walks through the reversed vector, exposing the current value and its index in the reversed order.

for (int i = 0; i < nums.size(); i++) {
    auto current = nums[i];
    // …
}

Locate the insertion point with lower_bound

The ordered map last stores value-to-index pairs. lower_bound finds the first entry whose key is not less than the current value, providing a pivot for scanning both directions.

auto mid = last.lower_bound(current);

Scan to the right of the pivot

Starting from mid, the algorithm walks forward through the map. It stops as soon as the absolute difference between the candidate key and current exceeds valueDiff, because the map is ordered and further keys will only increase the difference. For each candidate that satisfies the value condition, the index distance is checked against indexDiff.

auto check = mid;
while (check != last.end()) {
    if (abs(check->first - current) > valueDiff)
        break;
    if (abs(check->second - i) <= indexDiff)
        return true;
    check++;
}

Scan to the left of the pivot

A symmetric scan moves backward from mid. The loop decrements the iterator before testing, ensuring that the element at mid itself is not examined twice. The same early-break condition based on value difference is applied.

check = mid;
while (check != last.begin()) {
    check--;
    if (abs(check->first - current) > valueDiff)
        break;
    if (abs(check->second - i) <= indexDiff)
        return true;
}

Record the current element

After both directional scans, the current value and its reversed index are inserted into the map, making it available for subsequent iterations.

last[current] = i;

Edge Cases Handled

When the input vector is empty, the loop body never executes and the function returns false. A single-element vector also yields false because no distinct pair exists.

If valueDiff is zero, the algorithm still works because the scans compare absolute differences and will only succeed when identical values appear within the allowed index distance.

When indexDiff is zero, the index check abs(check->second - i) <= indexDiff forces the two indices to be identical, which cannot happen for distinct elements, so the function correctly returns false.

The use of abs on both value and index differences ensures that negative numbers in the array are treated correctly, and the ordered map guarantees that the scanning logic respects the monotonic increase of keys regardless of sign.

Large valueDiff values effectively disable the early-break condition, causing the scans to traverse all entries in the map; the algorithm still produces the correct answer because every possible pair is examined.

Performance Optimizations

Reversing the vector at the start reduces the number of map insertions that would otherwise need to be removed when the sliding window moves forward; the map only grows, avoiding costly deletions.

The ordered map provides logarithmic lookup for lower_bound, establishing a natural pivot point that limits the search space.

Both rightward and leftward scans incorporate an early-exit condition based on the value difference. Because the map is sorted by key, once the absolute difference exceeds valueDiff the loop can safely terminate, preventing unnecessary comparisons.

Storing only the most recent index for each distinct value (last[current] = i) keeps the map size bounded by the number of unique values encountered, which helps maintain fast iteration during scans.

The combination of these techniques yields a solution that quickly discards irrelevant candidates and focuses computation on the subset of elements that could satisfy both the index and value constraints.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of numbered toy blocks. Your job is to look at each block one by one and figure out if there is another block nearby that has a very similar number written on it.

To keep track of where everything is, there is a special notebook called a map. Every time you pick up a block, you look in the notebook to see if you have already seen a number that is close to the one in your hand.

You look at the numbers in the notebook that are slightly bigger than the one you have, and then you look at the numbers that are slightly smaller. For each one, you check two things. First, you see if the numbers are close enough in value to count as almost the same. Second, you check if the blocks were found close enough to each other in the row.

If you find a match, you have finished the puzzle perfectly. If you finish looking at all the blocks and never find a match, then the blocks are all different enough that you do not need to worry. After you check each block, you write down its number and its position in the notebook so that the other blocks you find later can check against it. You keep doing this until you have looked at every single block in the line.

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 = 4 | μ = 4.85 | σ = 1.76

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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
FelixFan1122 Java
fpdjsns C++
gaosq0604 Python
halfrost Go
haoel Python
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
qiyuangong Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java, Python
leetcode.ca C++, C#, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
FelixFan1122 Java
fpdjsns C++
gaosq0604 Python
halfrost Go
haoel Python
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
qiyuangong Python
ruoru Rust
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
wisdompeak C++
yuanliu666 Kotlin
YuriSpiridonov Python
46 links | 31 authors | 10 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

10 easy 2 medium 15 hard
28 solutions   August 9, 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