Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1543. Fix Product Name Format - Leetcode Solution

Problem Description

The "Fix Product Name Format" problem asks you to reformat a given product name string so that it follows a specific capitalization rule. The rules are:

  • Each word in the product name should have its first letter capitalized (uppercase), and the rest of the letters should be lowercase.
  • Words are separated by a single space.
  • There may be extra spaces at the beginning, end, or between the words in the input string.

For example, given the input string " aPpLe iPhOne 13 pro ", the output should be "Apple Iphone 13 Pro".

The key constraints are:

  • There will always be at least one word in the input string.
  • There may be multiple spaces between words, and leading/trailing spaces.

Thought Process

When approaching this problem, the first thought might be to manually scan each character and capitalize letters as needed. However, this can become cumbersome and error-prone, especially when dealing with multiple spaces and mixed cases.

A more systematic approach is to:

  • Split the input string into words, ignoring extra spaces.
  • Process each word to ensure the correct capitalization.
  • Join the words back together with single spaces.

This leverages built-in string manipulation functions, making the code cleaner and more reliable. The main challenge is handling the capitalization correctly and ensuring that all extra spaces are removed.

Solution Approach

Let's break down the solution step by step:

  1. Trim and Split: Remove any leading or trailing spaces from the input string, then split the string into words using whitespace as the delimiter. This automatically handles multiple spaces between words.
  2. Capitalize Each Word: For each word in the list, capitalize the first letter and convert the rest of the letters to lowercase. This can be done using string manipulation functions like capitalize() in Python, or by combining toUpperCase() and toLowerCase() in other languages.
  3. Rejoin Words: Join the capitalized words back together with a single space between each word.

This approach is efficient and easy to understand. We use built-in functions because they are optimized and less error-prone than manual character manipulation.

Example Walkthrough

Let's walk through the example input: " aPpLe iPhOne 13 pro "

  1. Trim and Split: After trimming and splitting, we get the list: ["aPpLe", "iPhOne", "13", "pro"]
  2. Capitalize Each Word:
    • "aPpLe" → "Apple"
    • "iPhOne" → "Iphone"
    • "13" → "13" (no letters to capitalize)
    • "pro" → "Pro"
  3. Rejoin Words: Joining the words with spaces gives: "Apple Iphone 13 Pro"

This matches the expected output.

Time and Space Complexity

Brute-force Approach:

  • If you manually scan each character and build the output, the time complexity is O(n), where n is the length of the input string. Space complexity is also O(n) for the output string.
Optimized Approach (using split and join):
  • Splitting the string and capitalizing each word both take O(n) time.
  • Joining the words into the output string also takes O(n) time.
  • So, the overall time complexity is O(n), and space complexity is O(n) to store the list of words and the final output.

Both approaches are linear in time and space, but using built-in functions is more concise and less error-prone.

Summary

In summary, the problem is about normalizing the capitalization and spacing of a product name string. The most elegant solution leverages string splitting, word-wise capitalization, and joining, all using built-in functions. This approach is both efficient and readable, making it ideal for production code. The key insight is to break the problem into manageable steps and use the right tools for each part.

Code Implementation

def fixProductName(name: str) -> str:
    words = name.strip().split()
    fixed_words = [w.capitalize() for w in words]
    return ' '.join(fixed_words)
      
#include <string>
#include <vector>
#include <sstream>
#include <cctype>
using namespace std;

string fixProductName(string name) {
    istringstream iss(name);
    string word, result;
    while (iss >> word) {
        if (!word.empty()) {
            word[0] = toupper(word[0]);
            for (int i = 1; i < word.size(); ++i) {
                word[i] = tolower(word[i]);
            }
            if (!result.empty()) result += " ";
            result += word;
        }
    }
    return result;
}
      
public class Solution {
    public String fixProductName(String name) {
        String[] words = name.trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < words.length; ++i) {
            if (words[i].length() == 0) continue;
            sb.append(Character.toUpperCase(words[i].charAt(0)));
            if (words[i].length() > 1) {
                sb.append(words[i].substring(1).toLowerCase());
            }
            if (i != words.length - 1) sb.append(" ");
        }
        return sb.toString();
    }
}
      
function fixProductName(name) {
    return name.trim().split(/\s+/).map(word => 
        word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
    ).join(' ');
}