AAlgoLoopSpaced repetition for LeetCode
EASYStringLeetCode ↗

Reverse String II

The key idea

Walk the string in strides of 2k. At every stride, unconditionally reverse just the first k characters of that window and leave the next k untouched. Python slicing handles the short tail automatically: s[i:i+k] clips when fewer than k characters remain.

Problem

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are at least k but fewer than 2k characters, then reverse the first k characters and leave the rest as they are.

Constraints

Examples

Input: s = "abcdefg", k = 2 Output: "bacdfeg"
Input: s = "abcd", k = 2 Output: "bacd"

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More String problems