Smallest Index With Equal Value - Problem

Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist.

x mod y denotes the remainder when x is divided by y.

Input & Output

Example 1 — Found Match
$ Input: nums = [0,1,2,3,4,5,6,7,8,9]
Output: 0
💡 Note: At index 0: 0 % 10 = 0 and nums[0] = 0, so return 0
Example 2 — Later Match
$ Input: nums = [4,3,2,1]
Output: 2
💡 Note: At index 2: 2 % 10 = 2 and nums[2] = 2, so return 2
Example 3 — Double Digit Index
$ Input: nums = [1,2,3,4,5,6,7,8,9,0,1,2,3]
Output: -1
💡 Note: No index i satisfies i % 10 == nums[i]. Checking all indices: 0≠1, 1≠2, 2≠3, etc. No match found.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 9

Visualization

Tap to expand
Smallest Index With Equal Value INPUT nums array (0-indexed) i=0 0 i=1 1 i=2 2 i=3 3 i=4 4 i=5 5 i=6 6 i=7 7 i=8 8 i=9 9 Find smallest i where: i mod 10 == nums[i] Example checks: i=0: 0 mod 10 = 0 nums[0] = 0 0 == 0 ? YES! ALGORITHM STEPS 1 Initialize Start from index i = 0 2 Check Condition Is i mod 10 == nums[i]? 3 If True Return current index i 4 If False Move to next index (i++) Execution Trace: i=0: 0 % 10 = 0 nums[0]=0 OK Match found at i=0! Return immediately (smallest index) FINAL RESULT Output: 0 Smallest valid index = 0 Verification: i = 0 0 mod 10 = 0 nums[0] = 0 MATCH FOUND Time: O(n) | Space: O(1) Best case: O(1) Key Insight: The condition i mod 10 == nums[i] means we're checking if the last digit of the index equals the value at that index. In this example, every index satisfies the condition (0-9), but we return 0 as it's the smallest. Early termination when a match is found ensures optimal performance for finding the minimum index. TutorialsPoint - Smallest Index With Equal Value | Optimal Solution
Asked in
Google 15 Amazon 12
12.0K Views
Low Frequency
~5 min Avg. Time
234 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