公式

B - 最後の大根 / The Last Radish 解説 by admin

swe-2-high

Explanation

Approach

We want the position of the rightmost radish, so we scan the string \(S\) from right to left and answer with the position of the first D we find. If no D is found, we print -1.

Scanning from the left and remembering the last D seen would give the same answer, but scanning from the right is more natural because we can stop as soon as we find one.

Algorithm

  1. Read \(N\) and \(S\).
  2. Examine \(S[i]\) for \(i = N-1, N-2, \dots, 0\) in that order.
  3. The first time \(S[i] = \) D, output the 1-indexed position \(i+1\) and stop.
  4. If the loop finishes without finding any D, output -1.

Proof of Correctness

  • When a D exists: Since the scan proceeds from right to left, the index \(i\) of the first D found is the maximum index at which D occurs. Therefore \(i+1\) is exactly the 1-indexed position of the rightmost radish, and the output is correct.
  • When no D exists: The loop inspects every cell without encountering D, so -1 is printed, as required.

Complexity

  • Time: \(O(N)\) (each cell is inspected at most once)
  • Space: \(O(1)\) auxiliary space besides the input string (\(O(N)\) including input storage)