- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 41 lines of Java from the credited upstream file 3431.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 minUnlockedIndices(int[] nums, int[] locked) {3 final int first2 = findFirstIndex(nums, 2);4 final int first3 = findFirstIndex(nums, 3);5 final int last1 = findLastIndex(nums, 1);6 final int last2 = findLastIndex(nums, 2);7 if (first3 != -1 && last1 != -1 && first3 < last1)8 return -1;9 10 int ans = 0;11 12 13 if (first2 != -1 && last1 != -1)14 for (int i = first2; i < last1; ++i)15 if (locked[i] == 1)16 ++ans;17 18 19 if (first3 != -1 && last2 != -1)20 for (int i = first3; i < last2; i++)21 if (locked[i] == 1)22 ++ans;23 24 return ans;25 }26 27 private int findFirstIndex(int[] nums, int target) {28 for (int i = 0; i < nums.length; ++i)29 if (nums[i] == target)30 return i;31 return -1;32 }33 34 private int findLastIndex(int[] nums, int target) {35 for (int i = nums.length - 1; i >= 0; i--)36 if (nums[i] == target)37 return i;38 return -1;39 }40}41