B - 変わらなかった時間 / Steady Hours Editorial by admin Editorial for printing
swe-2-highExplanation
Problem Summary
We are given a string \(S\) of length \(N\). The \(i\)-th character of \(S\) (1-indexed) represents the state of the light during hour \(i\): o means on and x means off. We must count, among hours \(2\) through \(N\), how many had the same state as the previous hour.
Algorithm
For each \(i\) (\(2 \leq i \leq N\)), check whether the \(i\)-th and \((i-1)\)-th characters of \(S\) are equal, and increment the answer if they are. Using 0-indexed access, we simply compare S[i] and S[i-1] for \(1 \leq i < N\).
Proof of Correctness
The desired quantity is the size of the set \(T = \{ i \mid 2 \leq i \leq N,\ S_i = S_{i-1} \}\), where \(S_i\) denotes the \(i\)-th character of \(S\). The algorithm iterates over every \(i = 2, 3, \dots, N\) exactly once and increments the counter precisely when \(S_i = S_{i-1}\) holds. Therefore the final counter value equals \(|T|\). Since every index in the range is examined exactly once, no index is missed or double-counted.
Complexity
- Time: \(O(N)\) — one constant-time comparison per position, for \(N-1\) positions.
- Space: Apart from the input string it is \(O(1)\), but this implementation stores \(S\), so it uses \(O(N)\) auxiliary space including the input.
Tie-breaking
The problem asks for a single integer, so no tie-breaking is involved.
posted:
last update: