Skip to content

ORIGINAL CODING QUESTION

Longest balanced flag span

Return the longest contiguous span containing equally many zeros and ones.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n integer values. Print one integer as described.

Constraints

1 ≤ n ≤ 200; flags are 0 or 1.

Example 1

Input

4 0 1 0 1

Output

4

The entire array is balanced.

Example 2

Input

3 1 1 1

Output

0

No nonempty balanced span exists.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Treat zero as -1 and one as +1.

Hint 2

Equal prefix balances identify a balanced span.

Hint 3

Keep the earliest index for every balance.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →