algoadvance

Leetcode 2057. Smallest Index With Equal Value

Problem Statement:

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.

Clarifying Questions:

  1. What are the constraints on the input array?
    • Typically, for problems like this, the array length can be up to 10^5 and the elements can range from 0 to 10^9.
  2. Is there any specific requirement on the time complexity?
    • While not explicitly stated, ideally, the solution should operate in linear time, O(n).
  3. Can the elements in the array be negative?
    • Based on the problem description, it seems the elements are non-negative integers (although typically the constraints should be checked in the problem statement).

Strategy:

  1. Iterate through the array:
    • Loop through each index i of the array.
  2. Check for the condition:
    • For each index i, check if i % 10 == nums[i].
  3. Return the index:
    • As soon as you find the first index that satisfies the condition, return that index.
    • If you complete the loop without finding any such index, return -1.

This approach checks each index exactly once, making it an O(n) solution, where n is the length of the array.

Code:

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);
    }
}

Time Complexity:

This solution is efficient and follows a straightforward approach to solve the problem within the given constraints.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI