Official

B - 変わらなかった時間 / Steady Hours Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

We compare adjacent characters in the string \(S\) and count the number of positions where adjacent characters are identical.

Analysis

Since the state of the light is represented by o or x, the state being the same as the previous hour means that the corresponding character is equal to the character immediately before it. Therefore, both oo and xx should be counted.

For example, when \(S =\) oooxx, comparing adjacent characters in order gives the following:

  • \(1\)st and \(2\)nd characters: o and o, so they are the same
  • \(2\)nd and \(3\)rd characters: o and o, so they are the same
  • \(3\)rd and \(4\)th characters: o and x, so they are different
  • \(4\)th and \(5\)th characters: x and x, so they are the same

Thus, the answer is \(3\).

A naive approach that checks all adjacent characters is fast enough. However, counting the number of contiguous blocks of the same character will result in an incorrect answer. For example, in ooo, there is \(1\) contiguous block, but there are \(2\) times when the state was the same as the preceding hour.

Algorithm

  1. Read \(N\) and \(S\).
  2. For \(i = 1, 2, \ldots, N-1\) (using 0-based indexing as in Python), compare s[i] and s[i - 1].
  3. Add \(1\) whenever they are equal, and output the total sum.

In the code, this operation is carried out using the following expression:

ans = sum(1 for i in range(1, n) if s[i] == s[i - 1])

By checking each of the target hours from the \(2\)nd hour to the \(N\)-th hour once and counting only when the state matches the preceding hour, we obtain the required answer.

Complexity

  • Time complexity: \(O(N)\). We perform \(N-1\) comparisons of adjacent characters.
  • Space complexity: \(O(N)\). Required to store the input string. The additional space complexity excluding the input is \(O(1)\).

Implementation Notes

  • Since string indexing in Python starts at \(0\), the index corresponding to the \(2\)nd hour is \(1\).

  • The \(1\)st hour has no preceding record to compare against, so we iterate using range(1, n).

  • When \(N = 1\), there is nothing to compare. In this case, sum results in \(0\), so no special case handling is needed.

  • Since a generator expression is passed to sum, there is no need to store the values to be summed in a list.

    Source Code

n = int(input())
s = input()
ans = sum(1 for i in range(1, n) if s[i] == s[i - 1])
print(ans)

This editorial was generated by gpt-6-astra-medium.

posted:
last update: