Skip to content

2057. Smallest Index With Equal Value

Description

Given a 0-indexed integer array nums, return the smallest index i of nums such that i mod 10 == nums[i], or -1 if such index does not exist.

x mod y denotes the remainder when x is divided by y.

 

Example 1:

Input: nums = [0,1,2]
Output: 0
Explanation: 
i=0: 0 mod 10 = 0 == nums[0].
i=1: 1 mod 10 = 1 == nums[1].
i=2: 2 mod 10 = 2 == nums[2].
All indices have i mod 10 == nums[i], so we return the smallest index 0.

Example 2:

Input: nums = [4,3,2,1]
Output: 2
Explanation: 
i=0: 0 mod 10 = 0 != nums[0].
i=1: 1 mod 10 = 1 != nums[1].
i=2: 2 mod 10 = 2 == nums[2].
i=3: 3 mod 10 = 3 != nums[3].
2 is the only index which has i mod 10 == nums[i].

Example 3:

Input: nums = [1,2,3,4,5,6,7,8,9,0]
Output: -1
Explanation: No index satisfies i mod 10 == nums[i].

 

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 9

Solutions

Solution 1: Traversal

We directly traverse the array. For each index $i$, we check if it satisfies $i \bmod 10 = \textit{nums}[i]$. If it does, we return the current index $i$.

If we traverse the entire array and do not find a satisfying index, we return $-1$.

The time complexity is $O(n)$, where $n$ is the length of the array. The space complexity is $O(1)$.

1
2
3
4
5
6
class Solution:
    def smallestEqual(self, nums: List[int]) -> int:
        for i, x in enumerate(nums):
            if i % 10 == x:
                return i
        return -1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public int smallestEqual(int[] nums) {
        for (int i = 0; i < nums.length; ++i) {
            if (i % 10 == nums[i]) {
                return i;
            }
        }
        return -1;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
public:
    int smallestEqual(vector<int>& nums) {
        for (int i = 0; i < nums.size(); ++i) {
            if (i % 10 == nums[i]) {
                return i;
            }
        }
        return -1;
    }
};
1
2
3
4
5
6
7
8
func smallestEqual(nums []int) int {
    for i, x := range nums {
        if i%10 == x {
            return i
        }
    }
    return -1
}
1
2
3
4
5
6
7
8
function smallestEqual(nums: number[]): number {
    for (let i = 0; i < nums.length; ++i) {
        if (i % 10 === nums[i]) {
            return i;
        }
    }
    return -1;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
impl Solution {
    pub fn smallest_equal(nums: Vec<i32>) -> i32 {
        for (i, &x) in nums.iter().enumerate() {
            if i % 10 == x as usize {
                return i as i32;
            }
        }
        -1
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    func smallestEqual(nums: Array<Int64>): Int64 {
        for (i in 0..nums.size) {
            if (i % 10 == nums[i]) {
                return i
            }
        }
        -1
    }
}

Comments