Python 2903.py
class Solution:
def findIndices(self, nums: List[int], indexDifference: int, valueDifference: int) -> List[int]:
# brute force
size = len(nums)
for i in range(size):
for j in range(i + indexDifference, size):
if abs(nums[i] - nums[j]) >= valueDifference:
return [ i, j ]
return [ -1, -1 ]
Difficulty
and has an acceptance rate of about 60% (80k+ submissions).
Typical patterns to solve this problem:
- Array
- Two Pointers
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 provided implementation defines a method that searches a numeric array for a pair of positions satisfying two constraints: the distance between the positions must be at least a given index difference, and the absolute difference between the values at those positions must meet or exceed a specified value difference. The method returns the first qualifying pair it encounters, or a sentinel pair [-1, -1] when no such pair exists.
Key Steps
The algorithm begins by determining the length of the input array.
size = len(nums)
It then iterates over each possible first index i using an outer loop.
for i in range(size):
For each i, a nested loop enumerates candidate second indices j. The start of this inner loop is deliberately offset by the required index difference, guaranteeing that any examined pair respects the minimum separation constraint.
for j in range(i + indexDifference, size):
Within the inner loop, the method evaluates the absolute difference between the two values. If this difference satisfies the required threshold, the method immediately returns the current pair of indices.
if abs(nums[i] - nums[j]) >= valueDifference:
return [ i, j ]
If the loops complete without finding a qualifying pair, the method falls back to returning a sentinel indicating failure.
return [ -1, -1 ]
Edge Cases Handled
The code gracefully handles an empty input array because the outer loop range becomes zero, causing the method to skip directly to the final return of [-1, -1]. A single-element array follows the same path, as there is no second index j that can satisfy the required separation, leading again to the sentinel result.
When the supplied indexDifference exceeds the length of the array, the inner loop’s start index i + indexDifference is always beyond the array bounds, so the inner loop never executes. The method therefore returns [-1, -1] without error.
A valueDifference of zero is effectively a no-op for the absolute-difference check; any pair that meets the index separation will satisfy abs(nums[i] - nums[j]) >= 0. The algorithm will thus return the first pair that respects the index gap, demonstrating correct handling of a zero threshold.
The use of abs ensures that the method works correctly for negative numbers and mixed sign values, as the absolute magnitude of the difference is compared against the threshold regardless of sign.
Performance Optimizations
Although the algorithm employs a brute-force double loop, it incorporates an early-exit strategy. As soon as a qualifying pair is found, the method returns immediately, preventing unnecessary examination of remaining index combinations. This early return can dramatically reduce work in cases where a valid pair appears early in the search space.
The inner loop’s lower bound i + indexDifference eliminates the need to test pairs that cannot possibly satisfy the index-difference requirement. By starting the search at the minimal permissible second index, the algorithm avoids a whole class of invalid comparisons, reducing the total number of iterations relative to an unrestricted nested loop.
ELI5 - Simplified Explanation
Imagine a long row of numbered toy boxes lined up on the floor. Each box has a different number written on it. The goal is to find two boxes that are special in two ways. First, the boxes must be far enough apart so they are not too close to each other. The distance between them must be at least the amount specified by indexDifference. Second, the numbers inside the boxes must be different enough from each other, at least by the amount specified by valueDifference.
To solve this, the code starts at the very first box and looks at it. Then, it walks down the row and checks every other box that is far enough away. It subtracts the number in the first box from the number in the second box to see if the difference is big enough. If the numbers are far enough apart in distance and also different enough in value, it remembers those two boxes. If the search reaches the end of the row and no pair of boxes fits the rules, it reports that no such pair could be found.
Code Quality
Complexity Analysis
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
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 | Python | Java | C++ | TS | |||
| WalkCCC | Python | Java | C++ | |||||
| leetcode.ca | Python | Java | C++ | Go | Rust | TS | ||
| Progiez | Python | Java | C++ | |||||
| github | chandansgowda | Python | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| chandansgowda | Python | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript |
Videos
Similar Problems
Solved On The Same Day
- problem 2917: Find the K-or of an Array
- problem 2904: Shortest and Lexicographically Smallest Beautiful String
- problem 2909: Minimum Sum of Mountain Triplets II
- problem 2918: Minimum Equal Sum of Two Arrays After Replacing Zeros
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