Earliest Second to Mark Indices I - Problem
You are given two 1-indexed integer arrays, nums and changeIndices, having lengths n and m, respectively.
Initially, all indices in nums are unmarked. Your task is to mark all indices in nums.
In each second s, in order from 1 to m (inclusive), you can perform one of the following operations:
- Choose an index
iin the range[1, n]and decrementnums[i]by 1. - If
nums[changeIndices[s]]is equal to 0, mark the indexchangeIndices[s]. - Do nothing.
Return an integer denoting the earliest second in the range [1, m] when all indices in nums can be marked by choosing operations optimally, or -1 if it is impossible.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,2,0], changeIndices = [2,2,2,2,3,2,2,2]
›
Output:
8
💡 Note:
We need to decrement nums[0] twice, nums[1] twice, and mark all indices. Index 3 appears first at position 5, so we need at least 8 seconds to complete all operations.
Example 2 — Impossible Case
$
Input:
nums = [1,0,1,0], changeIndices = [1,2]
›
Output:
-1
💡 Note:
changeIndices only covers indices 1 and 2, but we need to mark indices 1,2,3,4. Since indices 3 and 4 never appear, it's impossible.
Example 3 — All Zeros
$
Input:
nums = [0,1,0], changeIndices = [1,2,3]
›
Output:
3
💡 Note:
nums[1] needs 1 decrement. All indices appear exactly once, so we need 3 seconds: decrement nums[1], mark index 2, mark index 3, then we can mark index 1.
Constraints
- 1 ≤ nums.length ≤ 5000
- 0 ≤ nums[i] ≤ 109
- 1 ≤ changeIndices.length ≤ 5000
- 1 ≤ changeIndices[i] ≤ nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
nums array and changeIndices schedule
2
Process
Decrement values and mark when they reach 0
3
Output
Minimum time to mark all indices
Key Takeaway
🎯 Key Insight: Binary search on time, then check if we have enough operations to decrement and mark all indices
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code