Skip to main content

Reverse a String

Reverses a string, returning the characters in opposite order

Problem Overview

📝 The Text Processing Building Block
String reversal is a fundamental text manipulation operation that appears in countless programming scenarios! From palindrome checking to cryptography, this simple operation forms the foundation for more complex string algorithms.

🧠 The Reversal Challenge:

  • Character Order: Transform "abc" → "cba" by reversing character sequence
  • Preserve Content: All characters remain, only order changes
  • Handle Edge Cases: Empty strings, single characters, special symbols
  • Memory Consideration: Balance between simplicity and efficiency
  • Two Classic Approaches:
  • Built-in Methods: Leverage JavaScript's split/reverse/join - concise and readable
  • Manual Loop: Character-by-character reversal - educational and explicit
  • Real-World Applications:
  • Palindrome Detection: Check if text reads the same forwards and backwards
  • Cryptography: Simple text obfuscation and encoding schemes
  • Data Processing: Reversing sequences in data transformation pipelines
  • Algorithm Building: Foundation for more complex string manipulation
  • Text Effects: Creating mirror text for UI animations and effects
💡 Learning Value:
  • String immutability concepts in JavaScript
  • Array manipulation and method chaining
  • Loop design and index management
  • Trade-offs between readability and performance

Concepts

string manipulationarray iterationbuilt-in methods

Complexity Analysis

Time:O(n)
Space:O(n)
Performance Notes:

- Time: O(n) - must process every character once - Space: O(n) - creating new string with same length

Solutions

reverseString

Time: O(n) | Space: O(n)
export function reverseString(str: string): string {
  if (typeof str !== 'string') throw new Error("Input must be a string");
  return str.split('').reverse().join('');
}

Examples & Test Cases

#1Basic reversal
Input:hello
Output:olleh
#2Empty string
Input:
Output:
#3Single character
Input:a
Output:a
#4Numeric string
Input:12345
Output:54321
#5Special characters
Input:!@#
Output:#@!
#6With spaces
Input:Hello World
Output:dlroW olleH