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: 2
💡 Note: Check indices: digit_sum(10)=1 ≠ 0, digit_sum(20)=2 ≠ 1, digit_sum(11)=2 = 2. Return index 2 as it's the first match.

Constraints

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

Visualization

Tap to expand
Smallest Index With Digit Sum Equal to Index INPUT nums array: i=0 i=1 i=2 i=3 i=4 18 43 29 5 37 Digit Sums: 18: 1+8 = 9 43: 4+3 = 7 29: 2+9 = 11 5: 5 = 5 37: 3+7 = 10 Index vs Digit Sum: Index Sum Match? 0 9 NO 1 7 NO 2 11 NO 3 5 NO 4 10 NO ALGORITHM STEPS 1 Initialize Loop through each index i 2 Calculate Digit Sum Sum digits using mod/div while (num > 0): sum += num % 10 num = num / 10 return sum 3 Compare Check if digitSum == i if (digitSum(nums[i]) == i) return i // Found! else continue... 4 No Match Found Return -1 if loop ends return -1 // No index found FINAL RESULT All comparisons checked: i=0: 9 != 0 i=1: 7 != 1 i=2: 11 != 2 i=3: 5 != 3 i=4: 10 != 4 Output: -1 No index i exists where digitSum(nums[i]) == i Result: -1 (not found) Key Insight: Optimized digit sum uses modulo (%) to extract last digit and integer division (/) to remove it. This avoids string conversion overhead. Early termination returns first valid index immediately, giving O(n * d) time complexity where d is the average number of digits per element. TutorialsPoint - Smallest Index With Digit Sum Equal to Index | Optimized Digit Sum Calculation
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