Approach
Breadth-first search
For Earliest Second to Mark Indices II, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 81 lines of Java from the credited upstream file 3049.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup, work queue.
- 5 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int earliestSecondToMarkIndices(int[] nums, int[] changeIndices) {3 final long numsSum = Arrays.stream(nums).asLongStream().sum();4 5 Map<Integer, Integer> secondToIndex = getSecondToIndex(nums, changeIndices);6 int l = 0;7 int r = changeIndices.length + 1;8 9 while (l < r) {10 final int m = (l + r) / 2;11 if (canMark(nums, secondToIndex, m))12 r = m;13 else14 l = m + 1;15 }16 17 return l <= changeIndices.length ? l : -1;18 }19 20 21 private boolean canMark(int[] nums, Map<Integer, Integer> secondToIndex, int maxSecond,22 final long numsSum) {23 24 25 Queue<Integer> minHeap = new PriorityQueue<>();26 int marks = 0;27 28 for (int second = maxSecond - 1; second >= 0; --second) {29 if (secondToIndex.containsKey(second)) {30 31 final int index = secondToIndex.get(second);32 minHeap.offer(nums[index]);33 if (marks == 0) {34 35 36 minHeap.poll();37 ++marks;38 } else {39 40 41 --marks;42 }43 } else {44 45 46 ++marks;47 }48 }49 50 final int heapSize = minHeap.size();51 final long decrementAndMarkCost = numsSum - getHeapSum(minHeap) + (nums.length - heapSize);52 final long zeroAndMarkCost = heapSize + heapSize;53 return decrementAndMarkCost + zeroAndMarkCost <= maxSecond;54 }55 56 private long getHeapSum(Queue<Integer> minHeap) {57 long sum = 0;58 while (!minHeap.isEmpty())59 sum += minHeap.poll();60 return sum;61 }62 63 private Map<Integer, Integer> getSecondToIndex(int[] nums, int[] changeIndices) {64 65 Map<Integer, Integer> indexToFirstSecond = new HashMap<>();66 Map<Integer, Integer> secondToIndex = new HashMap<>();67 for (int zeroIndexedSecond = 0; zeroIndexedSecond < changeIndices.length; ++zeroIndexedSecond) {68 69 final int index = changeIndices[zeroIndexedSecond] - 1;70 if (nums[index] > 0)71 indexToFirstSecond.putIfAbsent(index, zeroIndexedSecond);72 }73 for (Map.Entry<Integer, Integer> entry : indexToFirstSecond.entrySet()) {74 final int index = entry.getKey();75 final int second = entry.getValue();76 secondToIndex.put(second, index);77 }78 return secondToIndex;79 }80}81