Official

B - 最後の大根 / The Last Radish Editorial by admin Editorial for printing

gpt-6-astra-medium

Overview

Find the position of the rightmost D in the string \(S\). The position is \(1\)-indexed from the left, and if there is no D, output -1.

Analysis

The rightmost radish corresponds to the first D found when scanning the string from the right end.

In Python, you can find the index of the rightmost D using the string method rfind('D'). However, because Python uses \(0\)-based indexing, you must add \(1\) to convert it to the \(1\)-based position (“how many-th from the left”) required by the problem.

For example, when \(S=\) D..D., the index of the rightmost D is \(3\), so the answer is \(4\).

On the other hand, if D does not exist, rfind('D') returns -1. If you simply add \(1\) in this case, it becomes 0, which is incorrect. Therefore, the code first checks whether a radish exists using 'D' in s.

Additionally, since \(N \leq 100\), a naive approach that checks all cells one by one is fast enough to pass well within the time limit. Rather than focusing on speed, the key points are handling the \(1\)-based indexing and dealing with the case when there is no radish.

Algorithm

  1. Read \(N\) and the string \(S\).
  2. Check whether D exists using 'D' in s.
  3. If it exists, find the index of the rightmost D using s.rfind('D'), add \(1\), and output it.
  4. If it does not exist, output -1.

Complexity

  • Time complexity: \(O(N)\)
    • Checking the existence of D and executing rfind both inspect the entire string in the worst case. Together, this takes \(O(N)\) time.
  • Space complexity: \(O(N)\)
    • Storing the input string takes \(O(N)\) space. Excluding the input storage, the auxiliary space complexity is \(O(1)\).

Implementation Notes

  • rfind returns the index of the rightmost match. Since find returns the index of the leftmost match, it does not serve the purpose for this problem.

  • Indices are \(0\)-based while the output position is \(1\)-based, so add \(1\) when D exists.

  • Using the conditional expression A if condition else B, output the position if D exists, and -1 otherwise.

    Source Code

# 問題文から独立に実装
n = int(input())
s = input().strip()
print(s.rfind('D') + 1 if 'D' in s else -1)

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

posted:
last update: