#3794

Reverse String Prefix

Easy
Two PointersStringTwo PointersString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of creating a new string multiple times, we can reverse the first k characters in place and then concatenate the rest, which is more efficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert the string to a list of characters for mutability.
  2. 2Step 2: Use two pointers to swap characters in the first k positions.
  3. 3Step 3: Convert the list back to a string and return it.
solution.py4 lines
1def reversePrefix(s, k):
2    s = list(s)
3    s[:k] = s[:k][::-1]
4    return ''.join(s)

Complexity note: The algorithm runs in linear time as we only traverse the first k characters once.

  • 1Reversing a substring can be done in place for efficiency.
  • 2Using two pointers is a common technique for swapping elements.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.