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.
We count the number of 1s in the array. If not divisible by 3, return [-1, -1]. Otherwise, we find the starting index of each part so that the binary values match, including trailing zeros. We compare the three parts for equality.
from typing import List
classSolution:
defthreeEqualParts(self, arr: List[int]) -> List[int]:
n = len(arr)
ones = sum(arr)
if ones ==0:
return [0, n-1]
if ones %3!=0:
return [-1, -1]
k = ones //3 i1 = i2 = i3 = cnt =0for i, x in enumerate(arr):
if x ==1:
cnt +=1if cnt ==1: i1 = i
if cnt == k+1: i2 = i
if cnt ==2*k+1: i3 = i
l = n - i3
if i1+l <= i2 and i2+l <= i3:
if arr[i1:i1+l] == arr[i2:i2+l] == arr[i3:i3+l]:
return [i1+l-1, i2+l]
return [-1, -1]