Find the smallest non-negative index whose digit sum equals the index itself.
Problem
Given an integer array nums, return the smallest index i such that the sum of the decimal digits of nums[i] is equal to i.
If no such index exists, return -1.
The digit sum of a non-negative integer is the sum of all digits in its decimal representation.
Intuition
You only need to inspect each element once and compare its digit sum with its position.
Input Format
- A single integer array
nums. - Indices are zero-based.
Output Format
- Return the smallest index
isuch thatdigitSum(nums[i]) == i. - If no index satisfies the condition, return
-1.
Constraints
1 <= nums.length.- Each
nums[i]is a non-negative integer. - The intended solution is linear in the array length, with digit-sum computation per element.
Example 1
Input
nums = [0, 10, 123, 4, 40]
Output
0
Explanation
At index 0, the digit sum of nums[0] = 0 is 0, so the answer is 0.
Example 2
Input
nums = [5, 11, 20, 3]
Output
1
Explanation
digitSum(5)=5, digitSum(11)=2, digitSum(20)=2, digitSum(3)=3. The first matching index is 1? No. Index 2 also does not match. Index 3 matches because digitSum(3)=3, so the correct answer is 3.
Show 1 more example
Example 3
Input
nums = [1, 2, 3]
Output
-1
Explanation
No element has a digit sum equal to its index.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.