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;
}
};
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
Other Solutions
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 |
Videos
Similar Problems
- problem 219: Contains Duplicate II
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
Extra
- 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