Leetcode 2057. Smallest Index With Equal Value
Given a 0-indexed integer array nums
, return the smallest index i
of nums
such that i % 10 == nums[i]
. Return -1
if no such index exists.
i
of the array.i
, check if i % 10 == nums[i]
.-1
.This approach checks each index exactly once, making it an O(n) solution, where n is the length of the array.
public class SmallestIndexWithEqualValue {
public static int smallestEqual(int[] nums) {
for (int i = 0; i < nums.length; i++) {
if (i % 10 == nums[i]) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
// Example usage:
int[] nums1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int res1 = smallestEqual(nums1); // Should return 0
int[] nums2 = {4, 3, 2, 1};
int res2 = smallestEqual(nums2); // Should return 2
int[] nums3 = {1, 3, 2, 4, 1, 3, 1, 8, 9, 0};
int res3 = smallestEqual(nums3); // Should return -1
System.out.println(res1);
System.out.println(res2);
System.out.println(res3);
}
}
This solution is efficient and follows a straightforward approach to solve the problem within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?