Ctrl K

Ahead After the Handoff

Medium
Two players go through a chain of n stages. The array stages describes them: stages[i] == 1 means the stage can be cleared, stages[i] == 0 means nobody can clear it. A player earns 1 point for each stage cleared and loses 1 point for each stage failed. The first player plays some number of stages in a row starting from stage 0, then the second player plays all the remaining ones. Each player must play at least one stage. Both play their best, so every clearable stage gets cleared. Return the smallest number of stages the first player should take to finish with strictly more points than the second. If that is impossible, return -1.
Example 1
stages=[0, 1, 1, 0, 1] → 3

Taking 1 stage gives -1 against 1 + 1 - 1 + 1 = 2. Taking 2 gives 0 against 1. Taking 3 gives 1 against 0, the first time the first player is ahead. The answer is 3.

Example 2
stages=[1, 1] → -1

Each player can take only one stage, so the score is 1 to 1 and nobody gets ahead.

Example 3
stages=[1, 0, 0] → 1

After a single stage the score is already 1 to -2.

Constraints
  • 2 ≤ len(stages) ≤ 10⁵
  • stages[i] is 0 or 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShortest Stretch to the Goal MediumProduct of All the Others MediumStudios for Recording Sessions MediumLongest Run with a Given Sum MediumBatch of Segment Adjustments Medium
loading Python…
Input
stages=[0, 1, 1, 0, 1]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 117 tests on the server, hidden ones included.