Skip to main content

Reverse String II

LeetCode 541 | Difficulty: Easy​

Easy

Problem Description​

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 <= 10^4`

- `s` consists of only lowercase English letters.

- `1 <= k <= 10^4`

Topics: Two Pointers, String


Approach​

Direct Approach​

This problem can typically be solved with straightforward iteration or simple data structure usage. Focus on correctness first, then optimize.

When to use

Basic problems that test fundamental programming skills.


Solutions​

Solution 1: C# (Best: 104 ms)​

MetricValue
Runtime104 ms
MemoryN/A
Date2018-04-04
Solution
public class Solution {
public string ReverseStr(string s, int k) {
char[] sArray = s.ToCharArray();
int n = s.Length;
int i=0;
while(i<n)
{
int j = Math.Min(i+k-1,n-1);
swap(sArray,i,j);
i=i+2*k;
}
return new string(sArray);

}

void swap(char[] ar, int l, int r)
{
while(l<r)
{
char temp = ar[l];
ar[l] = ar[r];
ar[r] = temp;
l++;
r--;
}
}
}

Complexity Analysis​

ApproachTimeSpace
Two Pointers$O(n)$$O(1)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.