Tutorialspoint
Problem
Solution
Submissions

Characters in a String

Certification: Basic Level Accuracy: 85.71% Submissions: 7 Points: 5

Write a Java program that counts the frequency of each character in a given string. Return a HashMap where keys are characters and values are their frequencies. Ignore spaces, and case is sensitive.

Example 1
  • Input: s = "Hello World"
  • Output: {H=1, e=1, l=3, o=2, W=1, r=1, d=1}
  • Explanation:
    • Spaces ignored, counts reflect correct frequencies
Example 2
  • Input: s = "programming"
  • Output: {p=1, r=1, o=1, g=2, a=1, m=2, i=1, n=1}
Constraints
  • 1 ≤ s.length ≤ 10^5
  • Ignore space character, preserve case
  • Time Complexity: O(n)
  • Space Complexity: O(k), k = unique characters
StringsCognizantDeloitte
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a HashMap to store characters as keys and their frequencies as values.
  • Iterate through each character in the string.
  • Skip space characters.
  • For each non-space character, update its frequency in the HashMap.
  • Return the resulting HashMap.

Steps to solve by this approach:

 Step 1: Create an empty HashMap to store character frequencies.

 Step 2: Iterate through each character in the input string.
 Step 3: Check if the current character is a space; if so, skip it.
 Step 4: If the character is not a space, add it to the map or update its count.
 Step 5: Use getOrDefault() to handle both new characters and updates efficiently.
 Step 6: Return the completed HashMap with all character frequencies.
 Step 7: The output will show each character and its frequency in the string.

Submitted Code :