Write a function `capitalize(str)` that capitalizes the first letter of each word in the string.
Problem Statement
<p>Write a function <code>capitalize(str)</code> that capitalizes the first letter of each word in the string.</p>
Examples
Input: str = "hello world"
Output: "Hello World"
Explanation: First letter of each word is capitalized.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
Split the string into words using split(" ").
š” Hint 2:
For each word, capitalize the first character and append the rest.
š” Hint 3:
Use map: words.map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(" ")
Editorial & Approach
Problem Overview & Intuition
To solve Capitalize First Letter, we consider the execution characteristics of JavaScript engines. Write a function `capitalize(str)` that capitalizes the first letter of each word in the 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 (split the string into words using split(" ")).
- Implement Logic: Handle state and transformations efficiently (for each word, capitalize the first character and append the rest).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function capitalize(str) {
return str.split(" ").map(w => w.charAt(0).toUpperCase() + w.slice(1)).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.