RHYDOOR - Editorial

PROBLEM LINK:

Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4

Author: nikhil_010309
Tester: raysh07
Editorialist: iceknight1093

DIFFICULTY:

TBD

PREREQUISITES:

None

PROBLEM:

A door has two buttons, A and B.
You are given a sequence of button presses.

If the same button is pressed three consecutive times, the door opens once.
Pressing a different button resets the counter.
Find the number of times the door was opened.

EXPLANATION:

Simply simulate the process: store the current button being pressed and the number of presses, and update these appropriately with each new button press.

Whenever the counter hits 3, add 1 to the answer and reset the counter to 0.

TIME COMPLEXITY:

\mathcal{O}(N) per testcase.

CODE:

Editorialist's code (PyPy3)
for _ in range(int(input())):
    n = int(input())
    s = input()
    
    ans, cur, ct = 0, 'A', 0
    for c in s:
        if c == cur: ct += 1
        else:
            ct = 1
            cur = c
        
        if ct == 3:
            ans += 1
            ct = 0
    print(ans)