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 <= 104s consists of only lowercase English letters.1 <= k <= 104In this approach, we directly manipulate the string representation by considering it as a character array (or list in some languages) for in-place modification. We handle the string in chunks of 2k and reverse the first k characters of each chunk.
This C program utilizes a function reverseString which modifies the string s in place. It processes segments of length 2k, reversing the first k characters within each segment. The main function demonstrates an example with s = "abcdefg" and k = 2.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as we are reversing in place.
In this approach, we use a StringBuilder (or equivalent structure in the respective programming languages) to construct the final output. This approach is effective because handling mutable strings directly supports efficient character manipulation operations.
This C solution defines a helper function reverseSubString to serve reversal needs within the limits of given indices. The main logic within reverseString iterates over character chunks and utilizes this helper for targeted manipulation.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1) as we operate directly on the input array.
| Approach | Complexity |
|---|---|
| Approach 1: In-place String Modification | Time Complexity: O(n), where n is the length of the string. |
| Approach 2: String Builder for Efficiency | Time Complexity: O(n), where n is the length of the string. |
Reverse Linked List II - Leetcode 92 - Python • NeetCode • 99,168 views views
Watch 9 more video solutions →Practice Reverse String II with our built-in code editor and test cases.
Practice on FleetCode