Explorer
JavaScript

Write a function `reverseString(str)` that returns the reversed version of the input string.

Problem Statement

<p>Write a function <code>reverseString(str)</code> that returns the reversed version of the input string.</p>

Examples

Input: str = "hello"

Output: "olleh"

Explanation: Characters are reversed.

Input: str = "JavaScript"

Output: "tpircSavaJ"

Explanation: Case is preserved while order is reversed.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Strings can be split into arrays of characters using split(""). šŸ’” Hint 2: Arrays have a reverse() method that reverses them in place. šŸ’” Hint 3: Use split, reverse, and join together.

Editorial & Approach

Problem Overview & Intuition

To solve Reverse a String, we consider the execution characteristics of JavaScript engines. Write a function `reverseString(str)` that returns the reversed version of the input string. By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (strings can be split into arrays of characters using split("")).
  3. Implement Logic: Handle state and transformations efficiently (arrays have a reverse() method that reverses them in place).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function reverseString(str) {
  return str.split("").reverse().join("");
}

Complexity Analysis

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Reverse a String

Easy

Write a function reverseString(str) that returns the reversed version of the input string.

Example Scenarios
1Example 1
Input: str = "hello"
Output: "olleh"
Explanation:

Characters are reversed.

2Example 2
Input: str = "JavaScript"
Output: "tpircSavaJ"
Explanation:

Case is preserved while order is reversed.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
["olleh","tpircSavaJ",""]