01. Reverse a String

Difficulty:EasyPattern:String TraversalTime:O(n)Space:O(n)

Reverse a given input string.

How It Works & Algorithmic Design

Strings can be processed using either Built-In Language Methods or an In-Place Two-Pointer Character Array Swap:

  1. Two-Pointer Approach: Convert the string into a mutable character array. Place left = 0 and right = length - 1. Swap characters while incrementing left and decrementing right until they meet in the middle.
  2. Language Idioms: Languages like Python (s[::-1]) or Java (StringBuilder.reverse()) offer optimized native operations.

Why This Approach Works Best

Both methods run in linear time $O(n)$. Understanding the manual pointer-swap mechanism is essential for interviews, especially when working with languages that treat strings as immutable.

Example Walkthrough

Input String

"hello"

5-character string.

Reversal Steps

'h' <-> 'o' => "oellh" -> 'e' <-> 'l' => "olleh"

Swaps characters from outside inward.

Output String

"olleh"

Reversed string.

Answer: Reverse string implementations

function reverseString(s) {
  return s.split('').reverse().join('');
}

Demonstrates built-in helpers and low-level character array transformations.

Key Takeaways
  • String immutability in languages like Java, JS, and Python requires allocating a new string ($O(n)$ space).

  • The underlying algorithm relies on the converging two-pointer swap pattern.

  • Linear time complexity $O(n)$ is needed to process all $n$ characters.