Earliest Second to Mark Indices I - Problem

You're given two arrays: nums and changeIndices. Your goal is to mark all indices in the nums array by strategically choosing operations over time.

The Rules:

  • Each second s (from 1 to m), you can perform one of these operations:
  • πŸ”½ Decrement: Choose any index i and reduce nums[i] by 1
  • βœ… Mark: If nums[changeIndices[s]] == 0, mark index changeIndices[s]
  • ⏸️ Do nothing: Skip the second

The catch? You can only mark an index when its value reaches exactly 0, and only when changeIndices[s] points to that index.

Return: The earliest second when all indices can be marked, or -1 if impossible.

Example: If nums = [2,2,0] and changeIndices = [2,2,2,2,3,2,1,1], you need to reduce nums[1] and nums[2] to 0, then mark them when changeIndices allows.

Input & Output

example_1.py β€” Basic Case
$ Input: nums = [2,2,0], changeIndices = [2,2,2,2,3,2,1,1]
β€Ί Output: 8
πŸ’‘ Note: We need to reduce nums[0] and nums[1] to 0, then mark all indices. The optimal strategy uses all 8 seconds: decrement operations followed by marking when changeIndices allows.
example_2.py β€” Quick Success
$ Input: nums = [1,1,1], changeIndices = [1,2,3,1,2,3]
β€Ί Output: 6
πŸ’‘ Note: Each index needs 1 decrement + 1 mark operation. With 6 seconds and good changeIndices coverage, we can complete all operations by second 6.
example_3.py β€” Impossible Case
$ Input: nums = [0,1], changeIndices = [2,2,2]
β€Ί Output: -1
πŸ’‘ Note: Index 1 (0-based index 0) never appears in changeIndices, so it can never be marked. Therefore, it's impossible to mark all indices.

Constraints

  • 1 ≀ n, m ≀ 5000
  • 0 ≀ nums[i] ≀ 109
  • 1 ≀ changeIndices[i] ≀ n
  • All arrays are 1-indexed in the problem statement

Visualization

Tap to expand
Factory Production LineProduct 1Needs: 2 opsProduct 2Needs: 2 opsProduct 3Ready: 0 opsConveyor Belt Schedule222321t=1t=2t=3t=4t=5t=6Binary Search + Greedy StrategyπŸ” Binary Search: Try different time limits (1, 2, 4, 6, 8...)πŸ“‹ For each time limit:β€’ Find last shipping opportunity for each productβ€’ Check if all products can be shippedβ€’ Verify total operations fit within time limit⚑ Result: Minimum time = 8 seconds
Understanding the Visualization
1
Setup Production
Each product needs specific processing time (nums[i] decrements)
2
Conveyor Belt
changeIndices tells us when each product can be shipped
3
Optimize Schedule
Binary search finds minimum time needed for all products
4
Greedy Verification
Check if we can fit all operations within the time limit
Key Takeaway
🎯 Key Insight: Binary search on time + greedy verification gives us O(m log m) complexity, much better than brute force simulation.
Asked in
Google 45 Amazon 32 Meta 28 Microsoft 25
20.9K Views
Medium Frequency
~35 min Avg. Time
892 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