
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}.
- The string "hello" is processed character by character.
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.
- The string "Programming" contains both uppercase and lowercase letters.
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
Editorial
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. |
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