Your task is to implement function that accepts two strings (s1 and s2) and returns…
- User
Your task is to implement function that accepts two strings (s1 and s2) and returns number of common characters between them. Write in JS.
For example:
getCommonCharacterCount('aabcc', 'adcaa') => 3
Assistant
Here is the implementation of getCommonCharacterCount function in JavaScript:
function getCommonCharacterCount(s1, s2) { let count = 0; const s1Chars = new Set(s1.split('')); for (let char of s2) { if (s1Chars.has(char)) { count++; s1Chars.delete(char); } } return count; }The key steps are:
- Split s1 into an array of characters using split('')
- Create a Set from this array to get unique characters
- Loop through s2
- Check if each character of s2 is present in the Set
- If yes, increment count and remove that character from Set
- Return final count
This avoids nested loops and gives O(n+m) time complexity where n and m are lengths of two strings.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.