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.
Problem summary: 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Two Pointers
Example 1
"abcdefg"
2
Example 2
"abcd"
2
Related Problems
Reverse String (reverse-string)
Reverse Words in a String III (reverse-words-in-a-string-iii)
Faulty Keyboard (faulty-keyboard)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Upper-end input sizes
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #541: Reverse String II
class Solution {
public String reverseStr(String s, int k) {
char[] cs = s.toCharArray();
int n = cs.length;
for (int i = 0; i < n; i += k * 2) {
for (int l = i, r = Math.min(i + k - 1, n - 1); l < r; ++l, --r) {
char t = cs[l];
cs[l] = cs[r];
cs[r] = t;
}
}
return new String(cs);
}
}
// Accepted solution for LeetCode #541: Reverse String II
func reverseStr(s string, k int) string {
cs := []byte(s)
n := len(cs)
for i := 0; i < n; i += 2 * k {
for l, r := i, min(i+k-1, n-1); l < r; l, r = l+1, r-1 {
cs[l], cs[r] = cs[r], cs[l]
}
}
return string(cs)
}
# Accepted solution for LeetCode #541: Reverse String II
class Solution:
def reverseStr(self, s: str, k: int) -> str:
cs = list(s)
for i in range(0, len(cs), 2 * k):
cs[i : i + k] = reversed(cs[i : i + k])
return "".join(cs)
// Accepted solution for LeetCode #541: Reverse String II
struct Solution;
impl Solution {
fn rev_half(s: &mut [char], k: usize) -> &[char] {
if s.len() <= k {
s.reverse();
} else {
let half = &mut s[0..k];
half.reverse();
}
s
}
fn reverse_str(s: String, k: i32) -> String {
let k: usize = k as usize;
let mut s: Vec<char> = s.chars().collect();
let n = s.len();
let mut i = 0;
while i * 2 * k < n {
let r = (i + 1) * 2 * k;
if r < n {
let ss = &mut s[i * 2 * k..r];
Self::rev_half(ss, k);
} else {
let ss = &mut s[i * 2 * k..n];
Self::rev_half(ss, k);
}
i += 1;
}
s.iter().collect()
}
}
#[test]
fn test() {
let s = "abcdefg".to_string();
let k = 2;
let t = "bacdfeg".to_string();
assert_eq!(Solution::reverse_str(s, k), t);
}
// Accepted solution for LeetCode #541: Reverse String II
function reverseStr(s: string, k: number): string {
const n = s.length;
const cs = s.split('');
for (let i = 0; i < n; i += 2 * k) {
for (let l = i, r = Math.min(i + k - 1, n - 1); l < r; l++, r--) {
[cs[l], cs[r]] = [cs[r], cs[l]];
}
}
return cs.join('');
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n)
Space
O(n)
Approach Breakdown
BRUTE FORCE
O(n²) time
O(1) space
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
TWO POINTERS
O(n) time
O(1) space
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Shortcut: Two converging pointers on sorted data → O(n) time, O(1) space.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
Moving both pointers on every comparison
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.