DEV Community

Gabs
Gabs

Posted on

[Leetcode] 541. Reverse String II

Exercise 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.

Solution proposal:
Inside a string we can have multiple sub-strings, but we need a way to know which sub-string must be reversed to concatenate to the new string.

We can start by having two variables, it will store two pointers, one for the begging of the string and the other at the end, with this will be able to have the middle of them:
l, r = 0, k

Now we can iterate over the string until it has reached the end. We can know this while the left pointer has not reached the end:
while r <= len(s):

But how do we know if the substring that we're processing must be reversed or not? We can create a boolean variable before the while loop. It will store whether the substring should be reversed or skipped. While iterating, we can apply the logic accordingly.
l, r = 0, k

Now we can iterate over the string until it has reached the end. We can determine this while the left pointer has not reached the end:
while r <= len(s):

But how do we know if the substring that we're processing must be reversed or not? We can create a boolean variable before the while loop. It will store whether the substring should be reversed or skipped, and while iterating, we can apply the logic accordingly:

skip = False       
while r <= len(s):
    if skip:
        res += s[l:r]
        skip = False
    else:
        res += s[l:r][::-1]
        skip = True

    l += k
    r += k
Enter fullscreen mode Exit fullscreen mode

Now our string will be partially inverted, except for the last part. Before returning the result variable, we should check if there is a remaining part to process. This is easy to fix, just copy and paste the logic to run one last time

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        res = ''
        l, r = 0, k

        if k > len(s):
            return s[::-1]

        skip = False
        while r <= len(s):
            if skip:
                res += s[l:r]
                skip = False
            else:
                res += s[l:r][::-1]
                skip = True

            l += k
            r += k

        if skip:
            res += s[l:r]
        else:
            res += s[l:r][::-1]

        return res
Enter fullscreen mode Exit fullscreen mode

Top comments (0)