Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Problem Statement
2.1.
Input
2.2.
Output
2.3.
Explanation
3.
Solution
3.1.
Method 1 (Using a Loop)
3.1.1.
Algorithm
3.1.2.
Code
3.1.3.
Output
3.1.4.
Explanation
3.1.5.
Time Complexity
3.1.6.
Space Complexity
3.2.
Method 2 (Using map data structure)
3.2.1.
Algorithm
3.2.2.
Code
3.2.3.
Output
3.2.4.
Explanation
3.2.5.
Time Complexity
3.2.6.
Space Complexity
4.
Frequently Asked Questions
4.1.
What are the different ways to calculate the count of repeating letters in javascript?
4.2.
How can we handle a string containing a mix of uppercase and lowercase letters?
4.3.
Can I count symbols other than letters in JavaScript?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

JavaScript Count Repeating Letter

Author Aayush Sharma
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Hello Ninjas!
This blog is going to be very interesting for you. This article will discuss how to count repeating letters in JavaScript.

javaScript Count Repeating Letter

We will discuss various methods to approach this problem and analyze their time and space complexities. The approaches will be explained along with their javascript implementation and outputs.

Problem Statement

In this problem, we are given a string of characters consisting only of lowercase letters. We need to find the number of occurrences of each character in the string and print it.

Let's understand the problem setter in a better way using the help of an example.

Input

helloninja

Output

a occurs 1 times.
e occurs 1 times.
h occurs 1 times.
i occurs 1 times.
j occurs 1 times.
l occurs 2 times.
n occurs 2 times.
o occurs 1 times.

Explanation

In the above input, the given string is "helloninja". As we can see, the letter 'a' appears once, 'e' appears once, 'h' appears once, 'i' appears once, 'j' appears once, 'l' appears twice, 'n' appears twice, and 'o' appears once. Hence the given output is printed.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Solution

Method 1 (Using a Loop)

Algorithm

  • Take a string as the input.
  • Use an outer loop to iterate on characters from 'a' to 'z.'
  • Use an inner loop to iterate through the string from beginning to end.
  • Initialize a counter with zero.
  • In the inner loop, if the string character is equal to the character in the outer loop, increase the counter by one.
  • At the end of each inner loop, print the count of each letter if it is greater than zero.
     

Code

function countRepeating(str) {
	// empty string
	if(str.length === 0){
		console.log("String is empty");
		return;
  	}

  	// outer loop to iterate over all letters from a to z
	for(let i=97 ;i<=122 ;i++) {
		//converting into character from the ASCII code
 		let ch=String.fromCharCode(i);

  		// initializing a counter variable with 0
		let count=0;

  		// inner loop to iterate on the string
		for(let j=0;j<str.length;j++) {
  			//incrementing the count if the current string character is equal to ch
			if(str[j]===ch) {
				count++;
			}
		}
		
		// printing the count of the character if it is greater than 0
		if(count>0) {
			console.log(`${ch} occurs ${count} times.`);
		}
  	}
}

// taking the string as input
let input_string= "helloninja";

// calling the function which will count repeating letters.
countRepeating(input_string);

Output

output of code

Explanation

In the above code, we take the input string in the variable input_string. Then we declare a function countRepeating which will count the repeating letters in the string.

In the countRepeating function, firstly, we check if the string is empty. If the string is not empty, then we declare an outer loop that traverses all the lowercase letters from 'a' to 'z'. Javascript compares characters based on their unicode. Hence we need to iterate from 97 (unicode of 'a') up to 122 (unicode of 'z'). Then we can convert this unicode into the character inside the outer loop.

After this, we declare a count variable for the number of occurrences. We declare an inner loop that iterates on the whole string. If the current character in the string is equal to the character which we are searching, we increment the count by one. After the inner loop finishes, we print the character count only if it is present at least once.

Time Complexity

We have declared an outer loop that runs for all characters from 'a' to 'z' and an inner loop that runs for the whole string. Hence the time complexity is O(26*n), where n is the length of the input string.

Space Complexity

We are only taking an extra count variable to count the number of occurrences of each character. Hence, we only use constant space, and our complexity is O(1).

Method 2 (Using map data structure)

Algorithm

  • Take input as the string.
  • Declare a map data structure with keys as the characters from 'a' to 'z' and their values 0 (initial occurrence).
  • Iterate over the string and increment the count as we encounter each character.
  • Print the key-value pairs.
     

Code

function countRepeating(str) {
	// empty string
	if (str.length === 0) {
		console.log("String is empty");
		return;
	}

  	// creating a new map
  	let mp = new Map();
  	for (let i = 0; i < str.length; i++) {
		mp.set(str[i], 0);
	}

	// iterate on the whole string and update the count of each character
	for (let i = 0; i < str.length; i++) {
		let curr_count = mp.get(str[i]);
		mp.set(str[i], curr_count + 1);
  	}

  	// printing the count of each character
  	for (let [key, value] of mp) {
		console.log(`${key} occurs ${value} times.`);
  	}
}

// taking the string as input
let input_string = "helloninja";

// calling the function which will count repeating letters.
countRepeating(input_string);

Output

output of code

Explanation

In the above code, first, take a string as an input. Then we call the countRepeating function, which will count the number of occurrences of each character in the string.

In the countRepeating, firstly, we check if the string is not empty. If the string is not empty, we declare a new map called mp. Initially, we set the count of each character in the string to zero.

Then we iterate on the whole string and update the count of each character as we encounter it. After the entire string is traversed, we finally print all the key-value pairs present in the string, which denote the letters present in the string and their corresponding counts.

Time Complexity

We have only used a single loop to iterate on the string twice. Hence our time complexity comes out to be O(n).

Space Complexity

We have used an extra map to keep the count of each character. Since there are only 26 characters, we are only using constant space. Hence our space complexity is also O(1).

Frequently Asked Questions

What are the different ways to calculate the count of repeating letters in javascript?

We can calculate the letters count by iterating on all the characters using an outer loop and then using an inner loop to iterate on the string. Another method is to use a map to store each letter and its occurrence in a key-value pair.

How can we handle a string containing a mix of uppercase and lowercase letters?

We can handle a mix of lowercase and uppercase letters using toLowerCase() or toUpperCase() methods. We can either convert all uppercase letters to lowercase or vice-versa. After that, we can use the normal approaches to calculate the solution.

Can I count symbols other than letters in JavaScript?

Yes, we can calculate characters other than letters. But the first method will not work in this case as it only works for lowercase letters. But we can use the map to calculate the count of each character.

Conclusion

In this article, we discussed the javaScript count repeating letters problem. We first understood the problem statement using an example. Then we discussed two approaches with their codes, outputs, explanations, and time and space complexities. So now that you have learned how to solve the JavaScript Count repeating letter problem, you can also refer to similar articles.

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSA, Competitive Programming, System Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninja!

Previous article
Math min() JavaScript Function
Next article
onChange Javascript
Live masterclass