# STOPCOUNT - Editorial

**URL:** <https://discuss.codechef.com/t/stopcount-editorial/124743>\
**Category:** editorial\
**Tags:** cakewalk, editorial, start218\
**Created:** [December 24, 2025, 4:30pm UTC](https://discuss.codechef.com/t/stopcount-editorial/124743 "2025-12-24T16:30:22Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![iceknight1093](https://www.codechef.com/sites/all/themes/abessive/images/user_default_thumb.jpg) [@iceknight1093](https://discuss.codechef.com/u/iceknight1093)\
**Post date:** [December 24, 2025, 4:30pm UTC](https://discuss.codechef.com/t/stopcount-editorial/124743/1 "2025-12-24T16:30:22Z")

</div>

# PROBLEM LINK:

[Practice](https://www.codechef.com/problems/STOPCOUNT)  
[Contest: Division 1](https://www.codechef.com/START218A/problems/STOPCOUNT)  
[Contest: Division 2](https://www.codechef.com/START218B/problems/STOPCOUNT)  
[Contest: Division 3](https://www.codechef.com/START218C/problems/STOPCOUNT)  
[Contest: Division 4](https://www.codechef.com/START218D/problems/STOPCOUNT)

_ **Author:** _ [raysh07](https://www.codechef.com/users/raysh07)  
_ **Tester:** _ [sushil2006](https://www.codechef.com/users/sushil2006)  
_ **Editorialist:** _ [iceknight1093](https://www.codechef.com/users/iceknight1093)

# DIFFICULTY:

Cakewalk

# PREREQUISITES:

None

# PROBLEM:

An election is held. N people vote, person i votes for Chef if and only if S\_i = 1.  
At how many points can Chef stop the count and be declared the winner, with no tie?

# EXPLANATION:

For Chef to win after i votes have been counted, strictly more people must have voted for him among people 1, 2, \ldots, i.  
So, for each i = 1, 2, 3, \ldots, N,

- Let x denote the number of people who voted for Chef among these people.  
That is, x equals the count of indices j satisfying 1 \le j \le i and S\_j = 1.
- Let y denote the number of people who didn’t vote for Chef among these people.  
That is, y equals the count of indices j satisfying 1 \le j \le i and S\_j = 0.
- Then, this is a valid stopping point if and only if x \gt y.

This condition can easily be checked for each i in linear time, for \mathcal{O}(N^2) overall.  
This is fast enough for the limits in this problem.

It’s possible to optimize this to \mathcal{O}(N) as well; simply store running counts for x and y instead of recomputing them every time.

# TIME COMPLEXITY:

\mathcal{O}(N) per testcase.

# CODE:

[details = Editorialist’s code (PyPy3)]

```python
for _ in range(int(input())):
    n = int(input())
    s = input()
    
    chef, antichef = 0, 0
    ans = 0
    for i in range(n):
        if s[i] == '1': chef += 1
        else: antichef += 1
        
        if chef > antichef: ans += 1
    print(ans)

```

[/details]
