Smallest Index With Digit Sum Equal to Index - Problem
You are given an integer array nums. Your task is to find the smallest index i such that the sum of the digits of nums[i] equals the index i itself.
For example, if nums = [18, 7, 23, 4]:
- At index 0:
nums[0] = 18, digit sum =1 + 8 = 9, but9 ≠ 0 - At index 1:
nums[1] = 7, digit sum =7, but7 ≠ 1 - At index 2:
nums[2] = 23, digit sum =2 + 3 = 5, but5 ≠ 2 - At index 3:
nums[3] = 4, digit sum =4, but4 ≠ 3
If no such index exists, return -1.
Note: The digit sum is calculated by adding all individual digits of a number. For instance, the digit sum of 1234 is 1 + 2 + 3 + 4 = 10.
Input & Output
example_1.py — Basic Example
$
Input:
nums = [18, 7, 23, 4]
›
Output:
-1
💡 Note:
Index 0: digit sum of 18 = 1+8 = 9 ≠ 0. Index 1: digit sum of 7 = 7 ≠ 1. Index 2: digit sum of 23 = 2+3 = 5 ≠ 2. Index 3: digit sum of 4 = 4 ≠ 3. No valid index found.
example_2.py — Match Found
$
Input:
nums = [10, 1, 23, 6]
›
Output:
1
💡 Note:
Index 0: digit sum of 10 = 1+0 = 1 ≠ 0. Index 1: digit sum of 1 = 1 = 1 ✓. Found match at index 1, which is the smallest valid index.
example_3.py — Multiple Matches
$
Input:
nums = [0, 1, 5, 12]
›
Output:
0
💡 Note:
Index 0: digit sum of 0 = 0 = 0 ✓. Found match at index 0, which is the smallest possible index, so we return 0 immediately.
Constraints
- 1 ≤ nums.length ≤ 104
- 0 ≤ nums[i] ≤ 109
- nums[i] consists of positive integers only
Visualization
Tap to expand
Understanding the Visualization
1
Initialize scanner
Start checking from index 0, moving left to right
2
Calculate digit sum
For each number, add up all its individual digits
3
Compare with index
Check if the digit sum equals the current index position
4
Return or continue
Return index if match found, otherwise move to next position
Key Takeaway
🎯 Key Insight: Since we need the smallest index with the matching condition, we must scan the array sequentially from left to right and return immediately when we find the first valid match.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code