﻿ Finding the Most Frequent Character in a String - ITCodar

# Finding the Most Frequent Character in a String

## Finding the most frequent character in a string

There are many ways to do this shorter. For example, you can use the `Counter` class (in Python 2.7 or later):

``import collectionss = "helloworld"print(collections.Counter(s).most_common(1))``

If you don't have that, you can do the tally manually (2.5 or later has `defaultdict`):

``d = collections.defaultdict(int)for c in s:    d[c] += 1print(sorted(d.items(), key=lambda x: x, reverse=True))``

Having said that, there's nothing too terribly wrong with your implementation.

## Finding the most frequent character in a string using binary search

As your characters are grouped the problem is reduced to finding longest sequence of consequent letters...

So yes you can use binary search to find the size of each sequence which is `O(m.log(n))` where `m<=n` is the number of sequences (distinct letters). As you stated `m<=26` you can consider it as constant leading to `O(log(n))`

The algo would be something like this:

1. consider your string is `char s[n];` and result `int l=0;`

2. `for (i=0;i<n;)`

3. binary search `j` position

of last character the where `s[i]==s[j]` where `i <= j < n`

4. remember max `l=max(l , j+1-i)`

5. `i=j+1`

6. `continue` the loop from #2

However note that any letter can have only single sequence so strings like `abaaaaaa` will not work.

## Finding the most frequent character in a string javascript

This will loop over every character in the string and keep track of each character's count and the character with the maximum count:

``var exp = '3553853335' ;var expCounts = {};var maxKey = '';for(var i = 0; i < exp.length; i++){    var key = exp[i];    if(!expCounts[key]){     expCounts[key] = 0;    }    expCounts[key]++;    if(maxKey == '' || expCounts[key] > expCounts[maxKey]){        maxKey = key;    }}console.debug(maxKey + ":" + expCounts[maxKey]);``

Update:
Here is an ES6 version that will handle strings where multiple character have the same max count

``function maxCount(input) {    const {max, ...counts} = (input || "").split("").reduce(    (a, c) => {        a[c] = a[c] ? a[c] + 1 : 1;        a.max = a.max < a[c] ? a[c] : a.max;        return a;    },    { max: 0 }    );    return Object.entries(counts).filter(([k, v]) => v === max);}``

Example (please excuse the crude output):

``maxCount('--aaaa1111--').join(' | ').replace(/,/g, ':');``

outputs `1:4 | -:4 | a:4`

## Finding the most repeated character in a string in R

Using base R, we can separate every character and calculate their occurrence using `table` and return the one with max frequency.

``most_repeated_character <- function(x) {  tab <- table(strsplit(x, '')[])  names(tab)[tab == max(tab)]}most_repeated_character('apple')# "p"most_repeated_character('potato')# "o" "t"``

## Javascript get all the most frequent characters in a string

Get the `highest_num` and then again iterate through object and get those letters for which count is equal to `highest_num`

``function mostCommonCharacter(str) {  const charHolder = {}; // { a: 1, b: 3, c: 1, d: 2, e: 1, f: 3, g: 1 }  str    .toLowerCase()    .split("")    .forEach(char => {      if (char != " ") {        if (charHolder[char] == null) {          charHolder[char] = 1;        } else {          charHolder[char] += 1;        }      }    });  let highest_num = 0;  for (const key in charHolder) {    if (charHolder[key] > highest_num) {      highest_num = charHolder[key];    }  }  let res = '';  for(let k in charHolder){    if(charHolder[k] === highest_num){      res += k;    }  }  return res;}console.log(mostCommonCharacter("abbbcddefffg"))``

## Counting most frequent character in a string

I assume that you have a string that follows ASCII. In this way, there are 256 possible values for each char. Thus we count the frequency of each and return the largest one.

``int most_frequent(char *string){     int count = {0}; // Assum char is ASCII     int max = 0;     int i;     for(i=0; i < strlen(string) ;i++) {         count[(unsigned char)(string[i])] ++;     }     for(i=0; i < 256 ;i++) {         if (count[i] > max)              max = count[i];     }     return max; }``

## Find the most occurring character in a string

Here's a way that creates a reverse frequency dictionary. I also made the creation of the frequency dictionary and its reverse fairly succinct by using a dictionary comprehension:

``def most_frequent_letter(s):    st = s.lower().replace(' ', '')    frequencies = {}    frequencies = {item: frequencies.setdefault(item, 0) + 1 for item in st}    rev_freq = {count: key for key, count in frequencies.items()}    return rev_freq[max(rev_freq)]print(most_frequent_letter('nnmmmaaa'))  # -> a``

## How to get the most frequent character within a character string?

We can use `scan` to read the string as a vector of individual elements by splitting at the space, get the frequency count with `table`, return the named index that have the max count (`which.count`), get its `name`

``extract_most_frequent_character <- function(x) {     names(which.max(table(scan(text = x, what = '', quiet = TRUE))))}``

-testing

``extract_most_frequent_character(test_string) "C"``

Or with `strsplit`

``extract_most_frequent_character <- function(x) {     names(which.max(table(unlist(strsplit(x, "\\s+")))))}``

## How to find the second most frequent character in java?

Find the second maximum just like you've found the maximum.

``int max2 = 0;for(int i = 0; i < array.length; i++) {    if(array[i] > max2 && array[i] < max) {         max2 = array[i];     }}``

Then get the result string whose frequency is same as the second maximum.

``String result = "";for(int i = 0; i < array.length; i++) {    if(array[i] == max2) {         result += (i + 'a');     }}``

## How to find the most frequently occurring character in a string with Java?

It's a most easy way I can imagine.

``import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class MaximumOccurringChar {    static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!";    public static void main(String[] args) {        MaximumOccurringChar test = new MaximumOccurringChar();        List<Character> result = test.maximumOccurringChars(TEST_CASE_1, true);        System.out.println(result);    }    public List<Character> maximumOccurringChars(String str) {        return maximumOccurringChars(str, false);    }    // set skipSpaces true if you want to skip spaces    public List<Character> maximumOccurringChars(String str, Boolean skipSpaces) {        Map<Character, Integer> map = new HashMap<>();        List<Character> occurrences = new ArrayList<>();        int maxOccurring = 0;        // creates map of all characters        for (int i = 0; i < str.length(); i++) {            char ch = str.charAt(i);            if (skipSpaces && ch == ' ')      // skips spaces if needed                continue;            if (map.containsKey(ch)) {                map.put(ch, map.get(ch) + 1);            } else {                map.put(ch, 1);            }            if (map.get(ch) > maxOccurring) {                maxOccurring = map.get(ch);         // saves max occurring            }        }        // finds all characters with maxOccurring and adds it to occurrences List        for (Map.Entry<Character, Integer> entry : map.entrySet()) {            if (entry.getValue() == maxOccurring) {                occurrences.add(entry.getKey());            }        }        return occurrences;    }}``