LeetCode 3048: Earliest Second to Mark Indices I Solution

Master LeetCode problem 3048 (Earliest Second to Mark Indices I), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3048. Earliest Second to Mark Indices I

Problem Explanation

Explanation

To solve this problem, we can simulate the process of marking all indices in the given arrays. We iterate through the changeIndices array, updating the nums array accordingly. At each step, we check if all indices in the nums array have been marked. If so, we return the current second. If we reach the end of the changeIndices array without marking all indices, we return -1.

The time complexity of this solution is O(m) where m is the length of the changeIndices array. The space complexity is O(n) where n is the length of the nums array.

Solution Code

class Solution {
    public int earliestSecondToMarkIndices(int[] nums, int[] changeIndices) {
        int n = nums.length;
        int m = changeIndices.length;
        
        boolean[] marked = new boolean[n];
        
        for (int s = 0; s < m; s++) {
            int index = changeIndices[s] - 1;
            nums[index]--;
            if (nums[index] == 0) {
                marked[index] = true;
            }
            
            boolean allMarked = true;
            for (boolean isMarked : marked) {
                if (!isMarked) {
                    allMarked = false;
                    break;
                }
            }
            
            if (allMarked) {
                return s + 1;
            }
        }
        
        return -1;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3048 (Earliest Second to Mark Indices I)?

This page provides optimized solutions for LeetCode problem 3048 (Earliest Second to Mark Indices I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3048 (Earliest Second to Mark Indices I)?

The time complexity for LeetCode 3048 (Earliest Second to Mark Indices I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3048 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3048 in Java, C++, or Python.

Back to LeetCode Solutions