We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Capitalize the Title

Number: 2235

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given a string title consisting of one or more words separated by a single space, update the capitalization of each word based on its length. If a word’s length is 1 or 2, convert it entirely to lowercase. Otherwise, convert the first letter to uppercase and the remaining letters to lowercase. Return the modified string.


Key Insights

  • Split the input string into words using the space as a delimiter.
  • Process each word individually:
    • For words with length 1 or 2, change to all lowercase.
    • For longer words, capitalize the first character and convert the remaining characters to lowercase.
  • Join the processed words back together with a space.

Space and Time Complexity

Time Complexity: O(n), where n is the number of characters in the title.
Space Complexity: O(n), for storing the split words and the final result.


Solution

The solution uses a simple iterative approach. First, the string is split into individual words. Each word is processed based on its length using string manipulation functions. For words longer than 2 characters, we modify just the first character to uppercase and ensure the rest are in lowercase. Finally, the words are concatenated back into a single string with spaces. This approach uses basic string operations and avoids extra data structures beyond what is necessary for processing the words.


Code Solutions

# Function to capitalize the title based on the rules
def capitalizeTitle(title):
    # Split the title into words by space
    words = title.split(" ")
    result = []
    # Process each word individually
    for word in words:
        # If word length is 1 or 2, convert the entire word to lowercase
        if len(word) <= 2:
            result.append(word.lower())
        else:
            # Otherwise, capitalize the first letter and convert the rest to lowercase
            result.append(word[0].upper() + word[1:].lower())
    # Join the processed words with a space and return the result
    return " ".join(result)

# Example usage:
if __name__ == "__main__":
    test_title = "capiTalIze tHe titLe"
    print(capitalizeTitle(test_title))
← Back to All Questions