Return List of Uncommon Words
As I continue to practice for technical interviews, I’ve added problem to my solution pile! My latest conquer:
Given two sentences, return a list of uncommon words. An uncommon word is a word that appears exactly once in one sentence but not in the other. You must return a list, but it can be in any order. (Tests set difference)
Input:
A= This fruit is a banana.
B= This fruit is a grapefruit, which is a fruit.
Output:
Result = [banana, grapefruit, which]
As always, I started with pseudocode.
- Split both strings into an array
- Create a new array for the results.
3. Iterate through stringOne
. If !stringTwo.includes?
a word from stringOne
, push the word into the result
array
4. Iterate through stringTwo
. If !stringOne.includes?
a word from stringTwo
, push the word into the result array.
I perform the last two steps for each string to ensure that all uncommon words are accounted for, even if one string is longer than the other.
Now that I have an idea of the code flow and have accounted for edge cases, I could go ahead and write the solution!
function uniqueWords(stringOne, stringTwo) { const result = [] const stringOneArray = stringOne.split(/\W+/) const stringTwoArray = stringTwo.split(/\W+/)
for (let i = 0; i < stringOneArray.length; i++) { if (!stringTwoArray.includes(stringOneArray[i])) { result.push(stringOneArray[i]) } } for (let j = 0; j < stringTwoArray.length; j++) { if (!stringOneArray.includes(stringTwoArray[j])) { result.push(stringTwoArray[j]) } } return result}
There you have it. Could you come up with a more efficient solution?