#3049

Earliest Second to Mark Indices II

Hard
ArrayBinary SearchGreedyHeap (Priority Queue)Binary SearchGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log(n))
Space
O(1)
O(n)
💡

Intuition

Time O(n log(n))Space O(n)

The optimal solution leverages binary search to find the earliest second where all indices can be marked. We calculate if it's possible to mark all indices by a certain second using a greedy approach.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a function to check if all indices can be marked by a given second.
  2. 2Step 2: Use binary search on the range [n, sum(nums) + n] to find the earliest second.
  3. 3Step 3: For each mid-point in the binary search, simulate the marking process and check if all indices can be marked.
solution.py27 lines
1# Full working Python code
2
3def can_mark_all(nums, changeIndices, second):
4    n = len(nums)
5    marked = [False] * n
6    available = 0
7    for s in range(second):
8        idx = changeIndices[s] - 1
9        nums[idx] = 0
10        available += 1
11        for i in range(n):
12            if nums[i] == 0 and not marked[i]:
13                marked[i] = True
14                available -= 1
15    return all(marked) and available >= 0
16
17
18def earliest_second(nums, changeIndices):
19    left, right = len(nums), sum(nums) + len(nums)
20    while left < right:
21        mid = (left + right) // 2
22        if can_mark_all(nums[:], changeIndices, mid):
23            right = mid
24        else:
25            left = mid + 1
26    return left if can_mark_all(nums[:], changeIndices, left) else -1
27

Complexity note: The time complexity is O(n log(n)) due to the binary search over the seconds (log(n)) and checking the marking process (O(n)).

  • 1We need at least n seconds to mark all indices, as each index must be marked once.
  • 2The maximum possible seconds needed is sum(nums) + n, as we need to decrement values before marking.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.