Magicsheet logo

Earliest Second to Mark Indices I

Medium
88.9%
Updated 6/1/2025

Asked by 1 Company

Earliest Second to Mark Indices I

What is this problem about?

The Earliest Second to Mark Indices I coding problem involves an array nums and an array changeIndices. You start at second 1. Each second, you can do one of three things: decrease a value in nums by 1, mark an index as "complete" if its value is 0 and it's currently the second specified by changeIndices, or do nothing. You want to find the earliest second at which all indices can be marked as complete.

Why is this asked in interviews?

Companies like MathWorks ask this to test a candidate's ability to combine binary search interview pattern with greedy validation. It’s a "Medium" difficulty problem that requires checking if a specific time T is sufficient to complete the task. This pattern of "finding the minimum threshold" is extremely common in technical interviews.

Algorithmic pattern used

The problem is solved using Binary Search on the Answer.

  1. The possible answer range is [1, total_seconds].
  2. For a given time T, check if it's possible to mark all indices using a greedy strategy:
    • Identify the last available second for each index within the range [1, T].
    • Sort these last-available seconds.
    • For each index, you must have enough prior seconds to reduce its nums[i] value to 0 before its last-available second.
  3. If T works, try a smaller time; otherwise, try a larger time.

Example explanation

Suppose nums = [2, 2] and changeIndices = [1, 2, 1, 2]. Check T = 4:

  1. Last second for index 1: second 3.
  2. Last second for index 2: second 4.
  3. To mark index 1 at second 3, we need 2 seconds to reduce nums[0] to 0. Seconds 1 and 2 are available. (Possible).
  4. After marking index 1, we move to index 2. We need 2 more seconds. But only second 4 is left. (Impossible). Try T = 6 (if changeIndices was longer): With more time, we can fulfill the requirements.

Common mistakes candidates make

  • Greedy logic error: Not identifying that an index should always be marked at its last possible occurrence in the allowed time window to leave more room for operations.
  • Not using Binary Search: Trying to simulate every possible second linearly, which is too slow.
  • Incorrect Bounds: Setting the binary search range incorrectly, potentially missing the actual minimum second.

Interview preparation tip

Whenever a problem asks for the "earliest," "minimum," or "smallest" value such that a condition is met, and the condition is monotonic (if it works for T, it works for T+1), think of Binary Search on the answer.

Similar Questions