Reverse String II
💻 coding

Reverse String II

1 min read 222 words
1 min read
ShareWhatsAppPost on X
  • 1The algorithm reverses the first k characters for every 2k characters in a given string.
  • 2If fewer than k characters remain, all are reversed; if between k and 2k, only the first k are reversed.
  • 3The solution has a time complexity of O(n) and a space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The algorithm reverses the first k characters for every 2k characters in a given string."

Reverse String II

Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less 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 left the other as original.

Example:

Input: s = "abcdefg", k = 2

Output: "bacdfeg"

Restrictions:

The string consists of lower English letters only.

Length of the given string and k will in the range [1, 10000]

Solution:

using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode.AskGif.Easy.String
{
 public class ReverseStrSoln
 {
 public string ReverseStr(string s, int k)
 {
 var count = Math.Ceiling((double)s.Length / k);
 bool rev = true;
 if (k >= s.Length)
 {
 k = s.Length;
 }

 var str = new StringBuilder();
 for (int i = 0; i < count; i++)
 {
 rev = i % 2 == 0; //reverse for odd position
 for (int j = k-1, x = 0; j >= 0; j--,x++)
 { 
 if (rev)
 {
 if ((i * k) + j > s.Length - 1) continue;
 str.Append(s[(i * k)+j]);
 }
 else
 {
 if((i * k) + x > s.Length - 1) break;
 str.Append(s[(i * k)+x]);
 }
 }
 }

 return str.ToString();
 }
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 11 May 2020 · 1 min read · 222 words

Part of AskGif Blog · coding

You might also like