[LeetCode] Smallest Index With Digit Sum Equal to Index

3550. Smallest Index With Digit Sum Equal to Index

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func smallestIndex(nums []int) int {
sumDigits := func(x int) int {
s := 0
for x > 0 {
s += x % 10
x /= 10
}
return s
}
for i, v := range nums {
if sumDigits(v) == i {
return i
}
}
return -1
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/05/18/PS/LeetCode/smallest-index-with-digit-sum-equal-to-index/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.