No menu items!

Solving Leetcode 38. Count and Say

In Leetcode 38: Count and Say, we are given a string of letters and we need to count how many times each letter appears and say it out loud. This problem can be solved in a few different ways, but we will code two different solutions here. First, we will solve it with JavaScript and then with Java. Let’s get started!

Explaining the Question

Leetcode 38: Count and Say is asking us to take a string of letters and count the number of times each letter appears. We need to return the sequence, saying out loud the numbers each time a letter appears in order.

For example, let’s say our input is “abc”. In this case, we would say “1a1b1c” as the output. This means that our string contains one ‘a’, one ‘b’, and one ‘c’.

Ways to solve Leetcode 38

To solve the Leetcode 38 problem in JavaScript, we can use a combination of for-loops and objects to keep track of how many times each letter appears. We will create an empty object and then use a for-loop to iterate over each character in the string. If the character exists in the object, we will increment its value by one, otherwise we will set it to 1. After our loop is complete, we can build up our string saying out loud each time a letter appears by accessing the object properties.

To solve Leetcode 38 in Java, we can use a HashMap to keep track of how many times each letter appears. We will iterate over the string, and if the character already exists in our HashMap, then we will increment its value by one. Otherwise, we will set it to one. After the loop is complete, we can build up our output string saying out loud each time a letter appears by accessing the Map entries.

Most Optimal Solution

The most optimal solution for Leetcode 38 is to use a HashMap in Java. This is because HashMaps are faster than objects when it comes to searching and inserting values, making them better suited for this task. We can also do this in JavaScript by using an object, or built in Map data structures.

Coding in JavaScript using Map():

var countAndSay = function(n) {
    let map = new Map()
    map.set(1, "1")
    map.set(2, "11")
    map.set(3, "21")
    map.set(4, "1211")
    map.set(5, "111221")

    if (n <= 5) {
        return map.get(n)
    }

    for (let i = 6; i <= n; i++) {
        let prev = map.get(i - 1)
        let newNum = ""
        let count = 1
        for (let j = 0; j < prev.length; j++) {
            if (prev[j] === prev[j + 1]) {
                count += 1
            } else {
                newNum += `${count}${prev[j]}`
                count = 1
            }
        }
        map.set(i, newNum)
    }
    return map.get(n)
    
};

Code in Java using HashMap:

public String countAndSay(int n) {
               //edge case
       if(n <= 0){
           return "";
       }
       //use hashmap to store the previous result
       HashMap<Integer, String> map = new HashMap<>();
       // put the first result in the hashmap
       map.put(1, "1");
       
       //start from 2 because we already put 1 in the map
       for(int i = 2; i <= n; i++){
           //get the previous result from the map
           String prev = map.get(i - 1);
           //the current result
           String curr = "";
           //the count of the current digit
           int count = 1;
           //the current digit
           char say = prev.charAt(0);
           
           for(int j = 1; j < prev.length(); j++){
               //if the current digit is equal to the previous digit, increment the count
               if(prev.charAt(j) == say){
                   count++;
               }else{
                   //if the current digit is not equal to the previous digit,
                   //append the count of the previous digit and the digit to the current result
                   curr += count;
                   curr += say;
                   //set say to be the current digit
                   say = prev.charAt(j);
                   //reset the count
                   count = 1;
               }
           }
           // append the last digit
           curr += count;
           curr += say;
           // put the current result in the map
           map.put(i, curr);
       }
       
       //return the result
       return map.get(n);
   }
       

In Leetcode 38: Count and Say, we are given a string of letters and asked to count how many times each letter appears in the string. We can solve this problem in JavaScript with objects or with Java using HashMaps. The most optimal solution is to use a HashMap as it is faster than an object when searching for and inserting values.

After understanding the question and coding the solution in either JavaScript or Java, Leetcode 38: Count and Say can be solved!

Related

Meta Introduces V-JEPA

The V-JEPA model, proposed by Yann LeCun, is a...

Mistral Large is Officially Released – Partners With Microsoft

Mistral has finally released their largest model to date,...

A Guide to Stable Diffusion Inpainting

Have you ever stared at a beautiful image, wishing...

Phind AI Releases Their 70B Model

Phind AI has released their Phind-70B model, which is...

Stable Diffusion 3 is Here

Stable Diffusion 3 is a new text-to-image model by...

Subscribe to our AI newsletter. Get the latest on news, models, open source and trends.
Don't worry, we won't spam. 😎

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Lusera will use the information you provide on this form to be in touch with you and to provide updates and marketing.