LeetCode 3049: Earliest Second to Mark Indices II Solution
Master LeetCode problem 3049 (Earliest Second to Mark Indices II), a hard 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.
3049. Earliest Second to Mark Indices II
Problem Explanation
Explanation
To solve this problem, we need to simulate the marking process according to the given rules. We can iterate through each second, perform the operations as described, and keep track of the indices that have been marked. If at any point all indices are marked, we return the current second. If after all seconds, we still have unmarked indices, then it is impossible to mark all indices.
Algorithm:
- Initialize a set to keep track of marked indices.
- Iterate through each second from 1 to m.
- Perform the operations based on the rules:
- If nums[changeIndices[s]] > 0, decrement the value at that index by 1.
- If nums[changeIndices[s]] == 0, mark the index if there is any unmarked index with value 0.
- Check if all indices are marked, return the current second.
- If after all seconds, some indices remain unmarked, return -1.
Time Complexity: The time complexity of this algorithm is O(m*n), where m is the number of seconds and n is the length of the nums array.
Space Complexity: The space complexity is O(n) to store the set of marked indices.
Solution Code
class Solution {
public int earliestSecondToMarkIndices(int[] nums, int[] changeIndices) {
int n = nums.length;
Set<Integer> marked = new HashSet<>();
for (int s = 1; s <= changeIndices.length; s++) {
if (nums[changeIndices[s - 1]] > 0) {
nums[changeIndices[s - 1]]--;
} else {
boolean markedZero = false;
for (int i = 0; i < n; i++) {
if (nums[i] == 0 && !marked.contains(i)) {
marked.add(i);
markedZero = true;
break;
}
}
if (!markedZero) {
return s;
}
}
if (marked.size() == n) {
return s;
}
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3049 (Earliest Second to Mark Indices II)?
This page provides optimized solutions for LeetCode problem 3049 (Earliest Second to Mark Indices II) 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 3049 (Earliest Second to Mark Indices II)?
The time complexity for LeetCode 3049 (Earliest Second to Mark Indices II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3049 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3049 in Java, C++, or Python.