Tutorialspoint
Problem
Solution
Submissions

Count Characters in a String

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to count the frequency of each character in a given string. The function should return an object where keys are characters and values are their frequencies. Consider both uppercase and lowercase letters as different characters.

Example 1
  • Input: str = "hello"
  • Output: {h: 1, e: 1, l: 2, o: 1}
  • Explanation:
    • The string "hello" is processed character by character.
    • 'h' appears 1 time, 'e' appears 1 time, 'l' appears 2 times, 'o' appears 1 time.
    • Therefore, the character count is {h: 1, e: 1, l: 2, o: 1}.
Example 2
  • Input: str = "Programming"
  • Output: {P: 1, r: 2, o: 1, g: 2, a: 1, m: 2, i: 1, n: 1}
  • Explanation:
    • The string "Programming" contains both uppercase and lowercase letters.
    • Each character is counted separately: P=1, r=2, o=1, g=2, a=1, m=2, i=1, n=1.
    • Case sensitivity is maintained in the character counting.
Constraints
  • 0 ≤ str.length ≤ 1000
  • str consists of printable ASCII characters
  • Time Complexity: O(n)
  • Space Complexity: O(k) where k is the number of unique characters
StringsEYSnowflake
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

  • Initialize an empty object to store character frequencies
  • Iterate through each character in the string using a loop
  • For each character, check if it already exists in the frequency object
  • If it exists, increment its count; if not, initialize it to 1
  • Return the frequency object after processing all characters

Steps to solve by this approach:

 Step 1: Initialize an empty object to store character frequency mappings
 Step 2: Create a loop to iterate through each character in the input string
 Step 3: For each character, check if it already exists as a key in the object
 Step 4: If the character exists, increment its value by 1
 Step 5: If the character doesn't exist, create a new key-value pair with count 1
 Step 6: Continue iteration until all characters have been processed
 Step 7: Return the completed character frequency object

Submitted Code :