easy +8 pts

Rotate String Right

Rotate a string to the right by k characters with wrap-around.

Write a function `rotate_right(s: str, k: int) -> str` that returns a new string which is the original string `s` rotated to the right by `k` positions. A right rotation by 1 moves the last character to the front. For example, `rotate_right('abc', 1)` returns `'cab'`. If `s` is empty, return an empty string. The value of `k` is a non-negative integer and may be larger than the length of `s`. You must handle wrapping correctly (i.e., treat `k` modulo the length of the string).

Constraints

- `0 <= len(s) <= 1000` - `0 <= k <= 10^9` - Time complexity: O(n), where n is the length of `s`. Space: O(n) for the result.

Example

>>> rotate_right('abc', 1)
'cab'
>>> rotate_right('abc', 2)
'bca'
>>> rotate_right('abc', 3)
'abc'
>>> rotate_right('hello world', 5)
'worldhello '
>>> rotate_right('', 5)
''
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

If `s` is empty, return `s` directly.
Use the modulo operator to reduce `k` to less than `len(s)`.
Think about splitting the string into two parts: the last `k` characters and the rest.
Use string slicing to concatenate the parts in the new order.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.