Find Indices With Index and Value Difference I - Problem

Imagine you're a data analyst looking for two specific data points in a dataset that satisfy both positional and value-based criteria!

Given a 0-indexed integer array nums of length n, along with two threshold values:

  • indexDifference - minimum distance between positions
  • valueDifference - minimum difference between values

Your mission: Find two indices i and j (both in range [0, n-1]) such that:

  1. Position constraint: abs(i - j) >= indexDifference
  2. Value constraint: abs(nums[i] - nums[j]) >= valueDifference

Return: An array [i, j] if such indices exist, otherwise [-1, -1]

Note: Multiple valid pairs may exist - return any one of them. The indices i and j can be equal.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [5,1,4,1], indexDifference = 2, valueDifference = 4
โ€บ Output: [0,3]
๐Ÿ’ก Note: Indices 0 and 3 satisfy both conditions: |0-3| = 3 โ‰ฅ 2 (index difference) and |5-1| = 4 โ‰ฅ 4 (value difference)
example_2.py โ€” No Valid Pair
$ Input: nums = [2,1], indexDifference = 0, valueDifference = 2
โ€บ Output: [-1,-1]
๐Ÿ’ก Note: No pair of indices satisfies the value difference requirement: |2-1| = 1 < 2, and |1-2| = 1 < 2
example_3.py โ€” Same Index Valid
$ Input: nums = [1,2,3], indexDifference = 0, valueDifference = 0
โ€บ Output: [0,0]
๐Ÿ’ก Note: Since both differences can be 0, any index paired with itself works. Index 0 with itself: |0-0| = 0 โ‰ฅ 0 and |1-1| = 0 โ‰ฅ 0

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • -50 โ‰ค nums[i] โ‰ค 50
  • 0 โ‰ค indexDifference โ‰ค nums.length
  • 0 โ‰ค valueDifference โ‰ค 100

Visualization

Tap to expand
๐Ÿข Security Camera NetworkHallway๐Ÿ“น5pos 0๐Ÿ“น1pos 1๐Ÿ“น4pos 2๐Ÿ“น1pos 3Distance: |3-0| = 3 โ‰ฅ 2 โœ“Reading Diff: |1-5| = 4 โ‰ฅ 4 โœ“๐Ÿ’ก Key InsightInstead of checking all pairs (O(nยฒ)), use sliding window:โ€ข Track min/max readings from cameras far enough awayโ€ข For each new camera, check against tracked extremesโ€ข Time: O(n), Space: O(1) - Much more efficient!๐ŸŽฏ Result: Found cameras at positions [0, 3]This approach scales well for large security networks!
Understanding the Visualization
1
Setup
Place cameras along a hallway at positions 0, 1, 2, 3... with sensor readings
2
Distance Rule
Cameras must be at least 'indexDifference' positions apart
3
Reading Rule
Camera readings must differ by at least 'valueDifference'
4
Find Pair
Locate any two cameras satisfying both distance and reading requirements
Key Takeaway
๐ŸŽฏ Key Insight: By tracking extremes (min/max) in valid ranges, we avoid checking all pairs and achieve optimal O(n) time complexity.
Asked in
Microsoft 25 Amazon 18 Google 12 Meta 8
26.8K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen