Smallest Index With Digit Sum Equal to Index (LeetCode 3550): Solution and Explanation

Easy
Array
Math

Given an integer array nums, return the smallest index i whose value nums[i] has a digit sum equal to i, or -1 if there is none.

Intuition

We want the smallest qualifying index, so scanning from index 0 upward and stopping at the first hit gives it for free.

Each check needs the digit sum of one number. x % 10 is its last digit and x // 10 removes that digit, so a short loop adds every digit.

Values are at most 1000, so a digit sum is at most 27. Indices above 27 can never match, but the plain scan is already fast enough that this pruning is optional.

Approach: Linear scan with digit sums

  1. For each index i with value x = nums[i], set s = 0.
  2. While x > 0, add x % 10 to s and divide x by 10.
  3. If s == i, return i immediately.
  4. If the loop ends with no match, return -1.

Step-by-step example

nums = [1,3,2]
  1. i = 0: the digit sum of 1 is 1, and 1 is not 0.
  2. i = 1: the digit sum of 3 is 3, and 3 is not 1.
  3. i = 2: the digit sum of 2 is 2, which equals the index.
  4. Index 2 is the first match, so return 2.

Code: Python, Java, C++

1class Solution:
2    def smallestIndex(self, nums: List[int]) -> int:
3        for i, x in enumerate(nums):
4            s = 0
5            while x > 0:
6                s += x % 10
7                x //= 10
8            if s == i:
9                return i
10        return -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log M)

Each of the n values is visited once, and summing its digits takes one step per digit, about log10(M) for the largest value M.

Space

O(1)

Only the loop index and the running sum are stored.

Other approaches

String digits (time O(n log M), space O(log M))

Convert each value to a string and sum its characters as integers. Same complexity, a little more allocation.

Scan only the first 28 indices (time O(min(n, 28) log M), space O(1))

Since a digit sum is at most 27 under the constraints, stop the scan at index 27. It is a nice observation but saves little for n up to 100.

Common mistakes

  • Forgetting that 0 has digit sum 0, so nums[0] = 0 is a valid match at index 0.
  • Collecting every match and returning the last one instead of returning the first.
  • Dividing with / in JavaScript without Math.floor, which never reaches 0 cleanly.

Frequently asked questions

Why does returning on the first match give the smallest index?

The scan visits indices in increasing order, so the first index that passes has no smaller passing index before it.

What is the digit sum of 1000?

1 + 0 + 0 + 0 = 1, so 1000 at index 1 is a match.

Can the answer be larger than 27?

Not under these constraints. The largest digit sum of a value up to 1000 is 9 + 9 + 9 = 27, from 999.