Skip to content

Latest commit

 

History

History

927

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

You are given an array arr which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value.

If it is possible, return any [i, j] with i + 1 < j, such that:

  • arr[0], arr[1], ..., arr[i] is the first part,
  • arr[i + 1], arr[i + 2], ..., arr[j - 1] is the second part, and
  • arr[j], arr[j + 1], ..., arr[arr.length - 1] is the third part.
  • All three parts have equal binary values.

If it is not possible, return [-1, -1].

Note that the entire part is used when considering what binary value it represents. For example, [1,1,0] represents 6 in decimal, not 3. Also, leading zeros are allowed, so [0,1,1] and [1,1] represent the same value.

 

Example 1:

Input: arr = [1,0,1,0,1]
Output: [0,3]

Example 2:

Input: arr = [1,1,0,1,1]
Output: [-1,-1]

Example 3:

Input: arr = [1,1,0,0,1]
Output: [0,2]

 

Constraints:

  • 3 <= arr.length <= 3 * 104
  • arr[i] is 0 or 1

Companies:
Hotstar

Related Topics:
Array, Math

Solution 1.

// OJ: https://leetcode.com/problems/three-equal-parts/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    vector<int> threeEqualParts(vector<int>& A) {
        int sum = accumulate(begin(A), end(A), 0);
        if (sum % 3) return {-1,-1};
        if (sum == 0) return {0, (int)A.size() - 1};
        sum /= 3; 
        int last = A.size() - 1;
        while (A[last] == 0) --last;
        int trailingZeros = A.size() - last - 1, firstBegin = 0;
        while (A[firstBegin] == 0) ++firstBegin;
        int firstEnd = firstBegin, cnt = 0;
        while (cnt < sum) cnt += A[firstEnd++];
        for (int i = 0; i < trailingZeros; ++i, ++firstEnd);
        int j = firstEnd, i = firstBegin;
        while (A[j] == 0) ++j;
        while (i < firstEnd && A[i] == A[j]) ++i, ++j;
        if (i < firstEnd) return {-1, -1};
        int secondEnd = j;
        while (A[j] == 0) ++j;
        i = firstBegin;
        while (i < firstEnd && A[i] == A[j]) ++i, ++j;
        if (i < firstEnd) return {-1, -1};
        return {firstEnd - 1, secondEnd};
    }
};