Write a function `reverseString(str)` that returns the reversed version of the input string.
Problem Statement
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
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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (strings can be split into arrays of characters using split("")).
- Implement Logic: Handle state and transformations efficiently (arrays have a reverse() method that reverses them in place).
- 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
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.