Problem

Given a 0-indexed integer array nums, return thesmallest index i ofnums such thati mod 10 == nums[i], or-1 if such index does not exist.

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

Examples

Example 1

1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
8
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

1
2
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

Solution

Method 1 – Simple Linear Scan

Intuition

We just need to check for each index if i mod 10 == nums[i]. Return the first such index, or -1 if none exists.

Approach

  1. Loop through the array.
  2. For each index i, check if i % 10 == nums[i].
  3. Return the first such index, or -1 if not found.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <vector>
using namespace std;
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
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
class Solution:
    def smallestEqual(self, nums):
        for i, x in enumerate(nums):
            if i % 10 == x:
                return i
        return -1

Complexity

  • ⏰ Time complexity: O(n) — Single pass through the array.
  • 🧺 Space complexity: O(1) — No extra space used.