#3048

Earliest Second to Mark Indices I

Medium
ArrayBinary SearchHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n + m log m)Space O(n)

This approach uses binary search to efficiently determine the earliest second when all indices can be marked. We can mark indices as late as possible, leveraging the last occurrence of each index in changeIndices.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a last occurrence array to store the last index where each index in nums can be marked.
  2. 2Step 2: For each index in nums, find the last occurrence in changeIndices using binary search.
  3. 3Step 3: Check if the last occurrence is valid and return the maximum of these values.
solution.py13 lines
1def earliest_time_to_mark(nums, changeIndices):
2    from bisect import bisect_right
3    n = len(nums)
4    last_occurrence = [-1] * n
5    for second in range(len(changeIndices)):
6        idx = changeIndices[second] - 1
7        last_occurrence[idx] = second
8    max_time = 0
9    for i in range(n):
10        if nums[i] > last_occurrence[i] + 1:
11            return -1
12        max_time = max(max_time, last_occurrence[i] + 1 - nums[i])
13    return max_time

Complexity note: The time complexity is O(n + m log m) due to the need to fill the last occurrence array and check conditions, while the space complexity is O(n) for storing the last occurrences.

  • 1Understanding the last occurrence of indices helps optimize marking.
  • 2Binary search can be a powerful tool for efficiently finding positions in sorted data.

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