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 i in the range [1, n] and decrement nums[i] by 1.
  • If nums[changeIndices[s]] is equal to 0, mark the index changeIndices[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
Earliest Second to Mark Indices Problemnums = [2, 2, 0]220Index 1Index 2Index 3changeIndices = [2,2,2,2,3,2,2,2]22223222s=1s=2s=3s=4s=5s=6s=7s=8Process: Decrement nums values, mark when 0Operations Needed:• 2 decrements for nums[0]• 2 decrements for nums[1]• 0 decrements for nums[2]• 3 marking operationsConstraints:• All indices must appear• Mark only when value = 0• Index 3 first appears at s=5Answer: 8
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
Asked in
Google 15 Meta 12 Amazon 8
12.4K Views
Medium Frequency
~35 min Avg. Time
445 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen