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, but 9 ≠ 0
  • At index 1: nums[1] = 7, digit sum = 7, but 7 ≠ 1
  • At index 2: nums[2] = 23, digit sum = 2 + 3 = 5, but 5 ≠ 2
  • At index 3: nums[3] = 4, digit sum = 4, but 4 ≠ 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
Digital Address Matching ProcessArray: [18, 7, 23, 4]18i=07i=123i=24i=3Digit Sum Calculations:Index 0: 18 → 1+8 = 9 ≠ 0 ❌Index 1: 7 → 7 ≠ 1 ❌Index 2: 23 → 2+3 = 5 ≠ 2 ❌Index 3: 4 → 4 ≠ 3 ❌Result: -1No match foundAlgorithm Steps1. Start from index 02. Calculate digit sum of current element3. Compare digit sum with index4. If equal, return index5. If not equal, move to next index6. If no match found, return -1
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.
Asked in
Google 23 Amazon 18 Microsoft 15 Meta 12
24.7K 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