- 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
- 38 lines of C++ from the credited upstream file 3431.cpp.
- The implementation visibly relies on sequence storage.
- 2 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:3 int minUnlockedIndices(vector<int>& nums, vector<int>& locked) {4 const auto first2It = ranges::find(nums, 2);5 const auto first3It = ranges::find(nums, 3);6 const auto last1It = ranges::find_last(nums, 1);7 const auto last2It = ranges::find_last(nums, 2);8 const int first2 =9 first2It == nums.cend() ? -1 : distance(nums.begin(), first2It);10 const int first3 =11 first3It == nums.cend() ? -1 : distance(nums.begin(), first3It);12 const int last1 = last1It.begin() == nums.cend()13 ? -114 : distance(nums.begin(), last1It.begin());15 const int last2 = last2It.begin() == nums.cend()16 ? -117 : distance(nums.begin(), last2It.begin());18 if (first3 != -1 && last1 != -1 && first3 < last1)19 return -1;20 21 int ans = 0;22 23 24 if (first2 != -1 && last1 != -1)25 for (int i = first2; i < last1; ++i)26 if (locked[i] == 1)27 ++ans;28 29 30 if (first3 != -1 && last2 != -1)31 for (int i = first3; i < last2; ++i)32 if (locked[i] == 1)33 ++ans;34 35 return ans;36 }37};38