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
/** * Given two strings, find the number of common characters between them. * * @param {string} s1 The first string. * @param {string} s2 The second string. * @returns {number} The number of common characters. * * For example: * getCommonCharacterCount('aabcc', 'adcaa') => 3 */ const getCommonCharacterCount = (s1, s2) => { // Create a map to store the frequency of characters in s1. const charMap = {}; for (let i = 0; i < s1.length; i++) { const char = s1[i]; if (charMap[char]) { charMap[char]++; } else { charMap[char] = 1; } } // Iterate over s2 and count the number of characters that are present in charMap. let commonCount = 0; for (let i = 0; i < s2.length; i++) { const char = s2[i]; if (charMap[char]) { commonCount++; charMap[char]--; if (charMap[char] === 0) { delete charMap[char]; } } } return commonCount; };
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.