Accenture Coding Question | Frequency Count | CodeWindow

Frequency Count

Given a string, find the frequencies of each of the characters in it.
The input string contains only lowercase letters. The output string should contain a letter followed by its frequency, in the alphabetical order (from a to z).

Input specification:
Input 1: The input string.

Output Specification:
Return a string representing the frequency counts of characters in the input string.

Example 1:
Input 1: babdc

Output: a1b2c1d1
Explanation:
In the input string, ‘a’ appears once, ‘b’ appears twice, ‘c’ and ‘d’ appear once.

Solution in Python 3:

s=input()
s=list(s)
no_rep = sorted(list(set(s)))
for i in no_rep:
    print(i,end="")
    print(s.count(i),end="")
    
#join Telegram @codewindow

Alternative Method

x1=input()
x=sorted(set(x1))
for i in x:
    print(i,end=str(x1.count(i)))
    
#join Telegram @codewindow

Solution in C :

//https://codewindow.in
//join our telegram channel @codewindow

#include <stdio.h>
#include <string.h>

void printFrequency(int freq[])
{
    for (int i = 0; i < 26; i++) {
        if (freq[i] != 0) {
            printf("%c%d",i+'a', freq[i]);
        }
    }
}

void findFrequncy(char S[])
{
    int i = 0;
    int freq[26] = { 0 };
    while (S[i] != '\0') {
        freq[S[i] - 'a']++;
        i++;
    }
    printFrequency(freq);
}

int main()
{
    char S[100];
    scanf("%s",S);
    findFrequncy(S);
}

Solution in C++ :

//https://codewindow.in
//join our telegram channel @codewindow

#include <iostream>
#include <string.h>

using namespace std;

void printFrequency(int freq[])
{
    for (int i = 0; i < 26; i++) {
        if (freq[i] != 0) {
            cout << (char)(i+'a')<< freq[i];
        }
    }
}

void findFrequncy(char S[])
{
    int i = 0;
    int freq[26] = { 0 };
    while (S[i] != '\0') {
        freq[S[i] - 'a']++;
        i++;
    }
    printFrequency(freq);
}

int main()
{
    char S[100];
    cin >> S;
    findFrequncy(S);
}

Solution in JAVA :

//https://codewindow.in
//join our telegram channel @codewindow

import java.util.*;

class CodeWindow {
    static void printFrequency(int freq[])
    {
        for (int i = 0; i < 26; i++) {
            if (freq[i] != 0) {
                System.out.print((char)(i+'a')+""+freq[i]);
            }
        }
    }

    static void findFrequency(char []S)
    {
        int i = 0;
        int freq[] = new int[26];
        for(int j=0;j<26;j++)
            freq[j] = 0;
        while (i != S.length) {
            freq[S[i] - 'a']++;
            i++;
        }
        printFrequency(freq);
    }
    
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        findFrequency(s.toCharArray());
    }
}

Output:

babdc
a1b2c1d1
Recent Posts

Leave a Comment

Your email address will not be published. Required fields are marked *