Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #927: Three Equal Parts

In this guide, we solve Leetcode #927 Three Equal Parts in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Array, Math

Intuition

There is a mathematical invariant or formula that directly leads to the result.

Using math avoids unnecessary loops and reduces complexity.

Approach

Derive the formula or update rule, then compute the answer directly.

Handle edge cases like overflow or zero carefully.

Steps:

  • Identify the math relationship.
  • Compute the result with a loop or formula.
  • Handle edge cases.

Example

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

Python Solution

class Solution: def threeEqualParts(self, arr: List[int]) -> List[int]: def find(x): s = 0 for i, v in enumerate(arr): s += v if s == x: return i n = len(arr) cnt, mod = divmod(sum(arr), 3) if mod: return [-1, -1] if cnt == 0: return [0, n - 1] i, j, k = find(1), find(cnt + 1), find(cnt * 2 + 1) while k < n and arr[i] == arr[j] == arr[k]: i, j, k = i + 1, j + 1, k + 1 return [i - 1, j] if k == n else [-1, -1]

Complexity

The time complexity is O(n)O(n)O(n), where nnn is the length of arr. The space complexity is O(1)O(1)O(1).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy