- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 52 lines of C++ from the credited upstream file 927.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
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 vector<int> threeEqualParts(vector<int>& arr) {4 const int ones = ranges::count_if(arr, [](int a) { return a == 1; });5 6 if (ones == 0)7 return {0, static_cast<int>(arr.size()) - 1};8 if (ones % 3 != 0)9 return {-1, -1};10 11 int k = ones / 3;12 int i;13 int j;14 int first;15 int second;16 int third;17 18 for (i = 0; i < arr.size(); ++i)19 if (arr[i] == 1) {20 first = i;21 break;22 }23 24 int gapOnes = k;25 26 for (j = i + 1; j < arr.size(); ++j)27 if (arr[j] == 1 && --gapOnes == 0) {28 second = j;29 break;30 }31 32 gapOnes = k;33 34 for (i = j + 1; i < arr.size(); ++i)35 if (arr[i] == 1 && --gapOnes == 0) {36 third = i;37 break;38 }39 40 while (third < arr.size() && arr[first] == arr[second] &&41 arr[second] == arr[third]) {42 ++first;43 ++second;44 ++third;45 }46 47 if (third == arr.size())48 return {first - 1, second};49 return {-1, -1};50 }51};52