Saturday, 3 January 2026

Given a string, find the frequency of each character present in it.

Frequency Count of Characters in a String (Java)

In this post, we will learn how to find the frequency of each character present in a string using Java.


Problem Statement

Given a string, print the frequency of every character present in it.

Input:

java2bigdatablogspotdotcom

Approach

  • The string contains alphabets and digits.
  • So, we cannot use a frequency array of size 26.
  • We use an array of size 256 to store ASCII character frequencies.
  • Each character’s ASCII value is used as an index.

Java Code Implementation


public class FreqStringCount {

    public static void main(String[] args) {

        String stg = "java2bigdatablogspotdotcom";
        int[] count = new int[256]; // ASCII size

        // Count frequency of each character
        for (int i = 0; i < stg.length(); i++) {
            count[stg.charAt(i)]++;
        }

        // Print character frequencies
        for (int i = 0; i < 256; i++) {
            if (count[i] > 0) {
                System.out.println((char) i + " " + count[i]);
            }
        }
    }
}


Explanation

  1. We create an integer array of size 256 to cover all ASCII characters.
  2. We traverse the string character by character.
  3. Each character is converted to its ASCII value automatically.
  4. The frequency is increased using the ASCII value as the index.

Example:

'j' → ASCII 106 → count[106]++
'2' → ASCII 50  → count[50]++

Sample Output (Partial)

j 1
a 4
v 1
2 1
b 2
g 2
d 2
o 4
t 4
c 1
m 1

Time & Space Complexity

  • Time Complexity: O(n)
  • Space Complexity: O(1) (Fixed size array of 256)

Optimization Note

Note: If the string contains only lowercase alphabets (a to z), we can optimize the solution by using a count array of size 26 instead of 256.


Category: Strings
Difficulty: Easy
Concept: Character Frequency Count

No comments:

Post a Comment