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
Selected Reading
Count and return the number of characters of str1 that makes appearances in str2 using JavaScript
We need to write a JavaScript function that takes two strings as parameters and counts how many characters from the first string appear in the second string, including duplicate occurrences.
Problem Statement
Given two strings str1 and str2, count how many characters from str1 also appear in str2. If a character appears multiple times in str2, count each occurrence separately.
Example:
-
str1 = 'Kk'contains characters 'K' and 'k' -
str2 = 'klKKkKsl'contains: k(1), l(1), K(2), K(3), k(4), K(5), s(6), l(7) - Characters from
str1found instr2: k, K, K, k, K = 5 matches
Solution
const str1 = 'Kk';
const str2 = 'klKKkKsl';
var countAppearances = (str1 = '', str2 = '') => {
const map = {};
// Create a map of characters in str1
for(let c of str1) {
map[c] = true;
}
let count = 0;
// Check each character in str2
for(let c of str2) {
if(map[c]) {
count += 1;
}
}
return count;
};
console.log(countAppearances(str1, str2));
5
How It Works
The algorithm works in two steps:
-
Create a character map: Store all unique characters from
str1in an object for quick lookup -
Count matches: Iterate through
str2and increment the counter whenever we find a character that exists in our map
Alternative Approach Using includes()
const countAppearancesSimple = (str1, str2) => {
let count = 0;
for(let char of str2) {
if(str1.includes(char)) {
count++;
}
}
return count;
};
console.log(countAppearancesSimple('Kk', 'klKKkKsl'));
5
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Object Map | O(n + m) | O(k) | Large strings with many unique characters |
| includes() Method | O(n × m) | O(1) | Small strings, simple implementation |
Where n = length of str2, m = length of str1, k = unique characters in str1
Conclusion
The object map approach is more efficient for larger strings as it provides O(1) character lookup. For smaller strings, the simpler includes() method offers cleaner code with acceptable performance.
Advertisements
