LeetCode 2738: Count Occurrences in Text Solution

Master LeetCode problem 2738 (Count Occurrences in Text), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2738. Count Occurrences in Text

Medium

Problem Explanation

Explanation

To solve this problem, we can iterate through the input text and count the occurrences of each word. We can use a hashmap to store the count of each word. We will split the text into words using whitespace as a delimiter. Before counting the occurrences, we can normalize the words by converting them to lowercase to ensure case-insensitive counting.

Algorithm

  1. Initialize an empty hashmap to store word counts.
  2. Split the input text into words using whitespace as a delimiter.
  3. Normalize each word by converting it to lowercase.
  4. Iterate through each word:
    • If the word is already in the hashmap, increment its count.
    • If the word is not in the hashmap, add it with a count of 1.
  5. Return the hashmap containing word counts.

Time Complexity

  • We iterate through each word in the input text once, so the time complexity is O(n), where n is the number of words in the text.

Space Complexity

  • The space complexity is O(m), where m is the number of unique words in the text (worst-case scenario).

Solution Code

import java.util.*;

class Solution {
    public Map<String, Integer> countOccurrences(String text) {
        Map<String, Integer> wordCount = new HashMap<>();
        
        String[] words = text.split("\\s+");
        
        for (String word : words) {
            word = word.toLowerCase();
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }
        
        return wordCount;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2738 (Count Occurrences in Text)?

This page provides optimized solutions for LeetCode problem 2738 (Count Occurrences in Text) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2738 (Count Occurrences in Text)?

The time complexity for LeetCode 2738 (Count Occurrences in Text) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2738 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2738 in Java, C++, or Python.

Back to LeetCode Solutions