879214. Capitalize and Count

Easy

Capitalize and Count

Summary

The problem, "Capitalize and Count", involves processing a given string by capitalizing each word and counting the total number of occurrences. This task requires applying basic string manipulation techniques and practicing attention to detail.

Detailed Explanation

To solve this problem, we can start by splitting the input string into individual words using whitespace as the delimiter. We then iterate through each word, converting it to uppercase using Python's built-in upper() method or Java's toUpperCase() method. This process effectively capitalizes each word in the original string.

Next, we count the total number of occurrences by keeping a running tally of unique words. Since we're capitalizing each word, identical words become distinct after conversion (e.g., "hello" and "Hello" are counted separately). To maintain efficiency, we can use a dictionary or hash set to keep track of encountered words.

Here's a step-by-step breakdown:

  1. Split the input string into individual words using whitespace as the delimiter.
  2. Iterate through each word and convert it to uppercase using upper() (Python) or toUpperCase() (Java).
  3. Count the total number of occurrences by maintaining a running tally of unique words.

Time Complexity: O(n), where n is the length of the input string, as we iterate through each character once. Space Complexity: O(m), where m is the number of unique words in the input string, since we store these words in a dictionary or hash set.

Optimized Solutions

Java

View on GeeksforGeeks
public int capitalizeAndCount(String s) {
    String[] words = s.split("\\s+");
    Set<String> uniqueWords = new HashSet<>();
    
    for (String word : words) {
        String capitalizedWord = word.toUpperCase();
        if (!uniqueWords.add(capitalizedWord)) {
            return -1; // or handle this situation as desired
        }
    }
    
    return uniqueWords.size();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.