#927
Three Equal Parts
HardArrayMathHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the fact that all three parts must have the same number of 1s. By counting the total number of 1s and ensuring they can be evenly divided into three parts, we can efficiently find the split points.
⚙️
Algorithm
3 steps- 1Step 1: Count the total number of 1s in the array. If it's not divisible by 3, return [-1, -1].
- 2Step 2: Identify the starting indices of each of the three parts based on the positions of the 1s.
- 3Step 3: Compare the three parts starting from their respective indices to ensure they are equal, adjusting for any trailing zeros.
solution.py24 lines
1# Full working Python code
2
3def threeEqualParts(arr):
4 total_ones = sum(arr)
5 if total_ones % 3 != 0:
6 return [-1, -1]
7 if total_ones == 0:
8 return [0, 2]
9 first, second, third = -1, -1, -1
10 count = 0
11 for i in range(len(arr)):
12 if arr[i] == 1:
13 count += 1
14 if count == 1:
15 first = i
16 elif count == total_ones // 3 + 1:
17 second = i
18 elif count == 2 * (total_ones // 3) + 1:
19 third = i
20 while third < len(arr) and arr[first] == arr[second] == arr[third]:
21 first += 1
22 second += 1
23 third += 1
24 return [first - 1, second] if first > second else [-1, -1]ℹ
Complexity note: The time complexity is O(n) because we make a single pass through the array to count the 1s and another pass to find the split points. The space complexity is O(1) since we only use a few variables to store indices.
- 1The total number of 1s must be divisible by 3 to split the array into three equal parts.
- 2Trailing zeros in the parts can be ignored as they do not affect the binary value.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.