3550. Smallest Index With Digit Sum Equal to Index
Description
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
.
Example 1:
Input: nums = [1,3,2]
Output: 2
Explanation:
- For
nums[2] = 2
, the sum of digits is 2, which is equal to indexi = 2
. Thus, the output is 2.
Example 2:
Input: nums = [1,10,11]
Output: 1
Explanation:
- For
nums[1] = 10
, the sum of digits is1 + 0 = 1
, which is equal to indexi = 1
. - For
nums[2] = 11
, the sum of digits is1 + 1 = 2
, which is equal to indexi = 2
. - Since index 1 is the smallest, the output is 1.
Example 3:
Input: nums = [1,2,3]
Output: -1
Explanation:
- Since no index satisfies the condition, the output is -1.
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 1000
Solutions
Solution 1: Enumeration + Digit Sum
We can start from index $i = 0$ and iterate through each element $x$ in the array, calculating the digit sum $s$ of $x$. If $s = i$, return the index $i$. If no such index is found after traversing all elements, return -1.
The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$, as only constant extra space is used.
Python3
class Solution:
def smallestIndex(self, nums: List[int]) -> int:
for i, x in enumerate(nums):
s = 0
while x:
s += x % 10
x //= 10
if s == i:
return i
return -1
Java
class Solution {
public int smallestIndex(int[] nums) {
for (int i = 0; i < nums.length; ++i) {
int s = 0;
while (nums[i] != 0) {
s += nums[i] % 10;
nums[i] /= 10;
}
if (s == i) {
return i;
}
}
return -1;
}
}
C++
class Solution {
public:
int smallestIndex(vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i) {
int s = 0;
while (nums[i]) {
s += nums[i] % 10;
nums[i] /= 10;
}
if (s == i) {
return i;
}
}
return -1;
}
};
Go
func smallestIndex(nums []int) int {
for i, x := range nums {
s := 0
for ; x > 0; x /= 10 {
s += x % 10
}
if s == i {
return i
}
}
return -1
}
TypeScript
function smallestIndex(nums: number[]): number {
for (let i = 0; i < nums.length; ++i) {
let s = 0;
for (; nums[i] > 0; nums[i] = Math.floor(nums[i] / 10)) {
s += nums[i] % 10;
}
if (s === i) {
return i;
}
}
return -1;
}