Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Counting the number of redundant characters in a string - JavaScript
We are required to write a JavaScript function that takes in a string and returns the count of redundant characters in the string. A redundant character is any character that appears more than once, where all duplicate occurrences (except the last one) are considered redundant.
For example ? If the string is ?
const str = 'abcde'
Then the output should be 0 because each character appears only once.
If the string is ?
const str = 'aaacbfsc';
Then the output should be 3 because 'a' appears 3 times (2 redundant), 'c' appears 2 times (1 redundant), totaling 3 redundant characters.
How It Works
The algorithm checks each character's position against its last occurrence in the string. If the current position is not the last occurrence, it's counted as redundant.
Example
Following is the code ?
const str = 'aaacbfsc';
const countRedundant = str => {
let count = 0;
for(let i = 0; i
Output
Following is the output in the console ?
3
Alternative Approach Using Character Frequency
Here's another method that counts character frequencies first:
const str = 'aaacbfsc';
const countRedundantFreq = str => {
const freq = {};
let redundantCount = 0;
// Count frequency of each character
for(let char of str) {
freq[char] = (freq[char] || 0) + 1;
}
// Sum up redundant occurrences (frequency - 1 for each character)
for(let char in freq) {
redundantCount += freq[char] - 1;
}
return redundantCount;
};
console.log(countRedundantFreq(str));
3
Comparison
| Method | Time Complexity | Space Complexity | Approach |
|---|---|---|---|
| lastIndexOf() | O(n²) | O(1) | Check last occurrence for each character |
| Frequency Count | O(n) | O(k) | Count frequencies, then sum redundancies |
Conclusion
Both methods effectively count redundant characters. The frequency approach is more efficient for larger strings, while the lastIndexOf method is simpler to understand and requires no extra space.
