algoadvance

Given a string s and an integer k, you need to perform the following action on the string:

Example 1:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Example 2:

Input: s = "abcd", k = 2
Output: "bacd"

Clarifying Questions

  1. Q: Can s contain any type of character (e.g., numbers, punctuation)? A: Yes, s can contain any type of character.

  2. Q: Is the given string s guaranteed to be non-empty? A: Typically, Yes, but if an empty string is provided, the output should also be an empty string.

  3. Q: Can the integer k be greater than the length of the string? A: Yes, the integer k might be greater than the length of the string, and it should handle this situation gracefully.

Strategy

  1. Iterate over the string in segments of 2k.
  2. For each segment, first reverse the first k characters.
  3. If fewer than k characters are left in any remaining segment, reverse all of those characters.

Code

def reverseStr(s: str, k: int) -> str:
    s = list(s)  # Convert to list for mutability
    for i in range(0, len(s), 2 * k):
        s[i:i+k] = reversed(s[i:i+k])
    return "".join(s)

Time Complexity

This solution ensures each segment is handled correctly according to the given rules and efficiently processes the string in linear time.

Try our interview co-pilot at AlgoAdvance.com