Explorer
JavaScript

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

  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 (split the string into words using split(" ")).
  3. Implement Logic: Handle state and transformations efficiently (for each word, capitalize the first character and append the rest).
  4. 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.

Capitalize First Letter

Easy

Write a function capitalize(str) that capitalizes the first letter of each word in the string.

Example Scenarios
1Example 1
Input: str = "hello world"
Output: "Hello World"
Explanation:

First letter of each word is capitalized.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
["Hello World","Javascript Is Awesome"]