LeetCode Solutions
927. Three Equal Parts
Time: Space:
class Solution {
public:
vector<int> threeEqualParts(vector<int>& A) {
int ones = count_if(begin(A), end(A), [](int a) { return a == 1; });
if (ones == 0)
return {0, A.size() - 1};
if (ones % 3 != 0)
return {-1, -1};
int k = ones / 3;
int i;
int j;
int first;
int second;
int third;
for (i = 0; i < A.size(); ++i)
if (A[i] == 1) {
first = i;
break;
}
int gapOnes = k;
for (j = i + 1; j < A.size(); ++j)
if (A[j] == 1 && --gapOnes == 0) {
second = j;
break;
}
gapOnes = k;
for (i = j + 1; i < A.size(); ++i)
if (A[i] == 1 && --gapOnes == 0) {
third = i;
break;
}
while (third < A.size() && A[first] == A[second] && A[second] == A[third]) {
++first;
++second;
++third;
}
if (third == A.size())
return {first - 1, second};
return {-1, -1};
}
};
class Solution {
public int[] threeEqualParts(int[] A) {
int ones = 0;
for (int a : A)
if (a == 1)
++ones;
if (ones == 0)
return new int[] {0, A.length - 1};
if (ones % 3 != 0)
return new int[] {-1, -1};
int k = ones / 3;
int i = 0;
int j = 0;
int first = 0;
int second = 0;
int third = 0;
for (i = 0; i < A.length; ++i)
if (A[i] == 1) {
first = i;
break;
}
int gapOnes = k;
for (j = i + 1; j < A.length; ++j)
if (A[j] == 1 && --gapOnes == 0) {
second = j;
break;
}
gapOnes = k;
for (i = j + 1; i < A.length; ++i)
if (A[i] == 1 && --gapOnes == 0) {
third = i;
break;
}
while (third < A.length && A[first] == A[second] && A[second] == A[third]) {
++first;
++second;
++third;
}
if (third == A.length)
return new int[] {first - 1, second};
return new int[] {-1, -1};
}
}
class Solution:
def threeEqualParts(self, A: List[int]) -> List[int]:
ones = sum(a == 1 for a in A)
if ones == 0:
return [0, len(A) - 1]
if ones % 3 != 0:
return [-1, -1]
k = ones // 3
i = 0
for i in range(len(A)):
if A[i] == 1:
first = i
break
gapOnes = k
for j in range(i + 1, len(A)):
if A[j] == 1:
gapOnes -= 1
if gapOnes == 0:
second = j
break
gapOnes = k
for i in range(j + 1, len(A)):
if A[i] == 1:
gapOnes -= 1
if gapOnes == 0:
third = i
break
while third < len(A) and A[first] == A[second] == A[third]:
first += 1
second += 1
third += 1
if third == len(A):
return [first - 1, second]
return [-1, -1]