Problem solution · Python

Earliest Second to Mark Indices II

Earliest Second to Mark Indices II: a Python solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Sliding window or two pointers
Source
walkccc LeetCode Solutions
Length
61 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Earliest Second to Mark Indices II, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 61 lines of Python from the credited upstream file 3049.py.
  • The implementation visibly relies on sequence storage, hash lookup, work queue.
  • No explicit loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeEarliest Second to Mark Indices II · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def earliestSecondToMarkIndices(      self,      nums: list[int],      changeIndices: list[int],  ) -> int:    # {the second: the index of nums can be zeroed at the current second}    secondToIndex = self._getSecondToIndex(nums, changeIndices)    numsSum = sum(nums)     def canMark(maxSecond: int) -> bool:      """      Returns True if all indices of `nums` can be marked within `maxSecond`.      """      # Use a min-heap to greedily pop out the minimum number, which yields the      # least saving.      minHeap = []      marks = 0       for second in range(maxSecond - 1, -1, -1):        if second in secondToIndex:          # The number mapped by the index is a candidate to be zeroed out.          index = secondToIndex[second]          heapq.heappush(minHeap, nums[index])          if marks == 0:            # Running out of marks, so need to pop out the minimum number.            # So, the current second will be used to mark an index.            heapq.heappop(minHeap)            marks += 1          else:            # There're enough marks.            # So, the current second will be used to zero out a number.            marks -= 1        else:          # There's no candidate to be zeroed out.          # So, the current second will be used to mark an index.          marks += 1       decrementAndMarkCost = ((numsSum - sum(minHeap)) +                              (len(nums) - len(minHeap)))      zeroAndMarkCost = len(minHeap) + len(minHeap)      return decrementAndMarkCost + zeroAndMarkCost <= maxSecond     l = 0    r = len(changeIndices) + 1    ans = bisect.bisect_left(range(l, r), True, key=canMark) + l    return ans if ans <= len(changeIndices) else -1   def _getSecondToIndex(      self,      nums: list[int],      changeIndices: list[int],  ) -> dict[int, int]:    # {the `index` of nums: the earliest second to zero out nums[index]}    indexToFirstSecond = {}    for zeroIndexedSecond, oneIndexedIndex in enumerate(changeIndices):      index = oneIndexedIndex - 1  # Convert to 0-indexed.      if nums[index] > 0 and index not in indexToFirstSecond:        indexToFirstSecond[index] = zeroIndexedSecond    return {second: index for index, second in indexToFirstSecond.items()} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗