Blogs Hub

Reverse String II - MiniTV

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)