Smallest Index With Digit Sum Equal to Index - Problem

You are given an integer array nums. Return the smallest index i such that the sum of the digits of nums[i] is equal to i. If no such index exists, return -1.

The sum of digits of a number is calculated by adding all its individual digits together. For example, the sum of digits of 123 is 1 + 2 + 3 = 6.

Input & Output

Example 1 — Basic Case
$ Input: nums = [18, 43, 29, 5, 37]
Output: -1
💡 Note: Check each index: digit_sum(18)=9 ≠ 0, digit_sum(43)=7 ≠ 1, digit_sum(29)=11 ≠ 2, digit_sum(5)=5 ≠ 3, digit_sum(37)=10 ≠ 4. No match found.
Example 2 — Found Match
$ Input: nums = [0, 1, 2, 3, 4, 5]
Output: 0
💡 Note: At index 0: digit_sum(0) = 0, which equals the index 0. Return 0 as it's the smallest matching index.
Example 3 — Later Match
$ Input: nums = [10, 20, 11, 3]
Output: 3
💡 Note: Check indices: digit_sum(10)=1 ≠ 0, digit_sum(20)=2 ≠ 1, digit_sum(11)=2 ≠ 2, digit_sum(3)=3 = 3. Return index 3.

Constraints

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

Visualization

Tap to expand
Find Smallest Index: Digit Sum = IndexInput: [18, 43, 29, 5, 37]184329537index 0index 1index 2index 3index 41+8=94+3=72+9=1153+7=109 ≠ 0 ✗7 ≠ 1 ✗11 ≠ 2 ✗5 ≠ 3 ✗10 ≠ 4 ✗Output: -1No index found where digit sum equals index
Understanding the Visualization
1
Input
Array of integers with indices 0, 1, 2, ...
2
Process
Calculate digit sum for each number and compare with index
3
Output
Return smallest matching index or -1 if none
Key Takeaway
🎯 Key Insight: We must scan linearly since we need the smallest matching index - no optimization can skip elements
Asked in
Google 12 Microsoft 8
12.4K Views
Medium Frequency
~15 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