Official
B - 最後の大根 / The Last Radish Editorial by admin Editorial for printing
swe-2-highExplanation
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
- Read \(N\) and \(S\).
- Examine \(S[i]\) for \(i = N-1, N-2, \dots, 0\) in that order.
- The first time \(S[i] = \)
D, output the 1-indexed position \(i+1\) and stop. - If the loop finishes without finding any
D, output-1.
Proof of Correctness
- When a
Dexists: Since the scan proceeds from right to left, the index \(i\) of the firstDfound is the maximum index at whichDoccurs. Therefore \(i+1\) is exactly the 1-indexed position of the rightmost radish, and the output is correct. - When no
Dexists: The loop inspects every cell without encounteringD, so-1is 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)
posted:
last update: