Reverse String II
Reverse String II is a Easy Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Two Pointers pattern, in the String Reversal subpattern.
Problem statement
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 less than 2k but greater than or equal to k characters, then reverse the first k characters and leave the other as original.
Example 1:
Input: s = "abcdefg", k = 2 Output: "bacdfeg"
Example 2:
Input: s = "abcd", k = 2 Output: "bacd"
Constraints:
- 1 <= s.length <= 104
- s consists of only lowercase English letters.
- 1 <= k <= 104
Topics and companies
Topics: Two Pointers, String.
Reported in interviews at Apple.
How to practise Reverse String II on Thita.ai
Starter code is provided in C, C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(n) time and O(1) space.
Open Reverse String II in the code editor, or read the Reverse String II editorial for a worked solution with its approach and complexity analysis.
Where Reverse String II sits in the DSA pattern sheet
- Two Pointers pattern guide
- String Reversal subpattern
- The full DSA patterns sheet
- All coding practice problems
Problems related to Reverse String II
Other problems that use the same String Reversal and Two Pointers techniques:
- Reverse String — Easy, same subpattern
- Reverse Vowels of a String — Easy, same subpattern
- Reverse Words in a String — Medium, same subpattern
- Backspace String Compare — Easy, same pattern
- Boats to Save People — Medium, same pattern
- Container With Most Water — Medium, same pattern
Preparing your workspace
Progress is saved as you study.