DEV Community

Gilfoyle
Gilfoyle

Posted on

3 1

How to Find The Frequency of Characters in a String or Array

In this post I am going to tech you how to find the frequency of characters in a string or array. This is a common question in interviews. I will be explaining the code in Java and JavaScript.

Question prompt

Write a function, charFrequency, that takes in a string/array as an argument. The function should return the the frequency of each character in the string/array then return the answer as map or dictionary.

You can assume that the input string is non-empty.

example_00

mostFrequentChar('david'); -> Map={ 'd' => 2, 'a' => 1, 'v' => 1, 'i' => 1 } 
Enter fullscreen mode Exit fullscreen mode

example_01:

mostFrequentChar('bookeeper'); // -> Map= { 'b' => 1, 'o' => 2, 'k' => 1, 'e' => 3, 'p' => 1, 'r' => 1 } 
Enter fullscreen mode Exit fullscreen mode

JavaScript Solution

const charFrequency = (str) => {

  //create a map to save the characters and save the frequency of each character
  const frequencyMap = new Map();
  //go through each character in the string 'str' 
  for(let char of str)
    {
      //check if our map doesn't contain the current character we are going through
      if(!frequencyMap.has(char))
        {
          //if our map doesn't contain the character we add it and assign the frequency to 1      
          frequencyMap.set(char,1);
        }
      //check if our map does contain the current character 
      else
        {
          // if our map contains the current character we are going to add 1 to the character frequency value
          //example, if we had 'd' => 1, we are going to get the value of 'd' and add 1 to it
          // so 'd' frequency value beacomes 2 
          frequencyMap.set(char,frequencyMap.get(char)+1);
        }
    }

  //return the frequencyMap we created 
  return frequencyMap;
}

Enter fullscreen mode Exit fullscreen mode

Java Solution

public String frequencySort(String str) {
  //create a map to save the characters and save the frequency of each character
  HashMap<Character,Integer> frequencyMap = new HashMap();
  //go through the string 'str' 
  for(char ch : str.toCharArray())
    {
      //check if our map contains the current character we are going through
      if(!frequencyMap.containsKey(ch))
        {
          //if our map doesn't contain the character we add it and assign the frequency to 1      
          frequencyMap.put(ch,1);
        }
      //check if our map does contain the current character 
      else
        {
          // if our map contains the current character we are going to add 1 to the character frequency value
          //example, if we had 'd' => 1, we are going to get the value of 'd' and add 1 to it
          // so 'd' frequency value beacomes 2 
          frequencyMap.put(ch,frequencyMap.get(ch)+1);
        }
    }

  //return the frequencyMap we created 
  return frequencyMap;
}

Enter fullscreen mode Exit fullscreen mode

This is how we get the frequency of characters in a string or array. If you have any questions, please let me know in the comments section. Also consider following me on Twitter if you want more content like this.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️