927. Three Equal Parts
Description
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, andarr[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]
is0
or1
Solutions
Solution: Simulation
- Time complexity: O(n)
- Space complexity: O(1)
JavaScript
js
/**
* @param {number[]} arr
* @return {number[]}
*/
const threeEqualParts = function (arr) {
const n = arr.length;
const ones = arr.reduce((total, value) => total + value);
if (!ones) return [0, n - 1];
if (ones % 3) return [-1, -1];
const preOnes = ones / 3;
let start = 0;
let mid = 0;
let end = 0;
let currentOnes = 0;
for (let index = 0; index < n; index++) {
const value = arr[index];
if (!value) continue;
if (!currentOnes) start = index;
currentOnes += 1;
if (currentOnes === preOnes + 1) {
mid = index;
}
if (currentOnes === preOnes * 2 + 1) {
end = index;
}
}
while (end < n && arr[start] === arr[mid] && arr[mid] === arr[end]) {
start += 1;
mid += 1;
end += 1;
}
if (end === n) return [start - 1, mid];
return [-1, -1];
};