Return List of Uncommon Words

Chindalath Traymany
2 min readMar 1, 2021

--

Photo by Lauren Peng on Unsplash

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.

  1. Split both strings into an array
  2. 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?

--

--

Chindalath Traymany
Chindalath Traymany

Written by Chindalath Traymany

Laotian-American woman pursuing my passion for mentally stimulating and complex problem-solving through programming.

No responses yet