0

I was asked this question in an interview where I failed to answer.

Here's my try:

str1 = "This is string 1";
str2 = "This is string 2";
let similarWords = [];
splittedStr1 = str1.split(" ");
splittedStr2 = str2.split(" ");
console.log(splittedStr1);
console.log(splittedStr2);
for (i = 0; i < splittedStr1.length; i++) {
  for (j = i; j < splittedStr2.length; j++) {
    if (splittedStr1[i] = splittedStr2[j]) {
      similarWords.push(splittedStr1[i]);
    }
  }
}
console.log(similarWords);

This outputs:

[
    "This",
    "is",
    "string",
    "2",
    "is",
    "string",
    "2",
    "string",
    "2",
    "2"
]

I'm wondering what did I miss?

I've shown what I tried above.

2 Answers 2

3

The problem with the code is that in the inner for loop, you are using the assignment operator (=) instead of the comparison operator (== or ===) when checking if splittedStr1[i] is equal to splittedStr2[j].

To do this, you should change the assignment operator to a comparison operator. And then you also need to check if the word is already added in the similarWords array before adding it again.

Try this.

let str1 = "This is string 1";
let str2 = "This is string 2";
let similarWords = [];
let splittedStr1 = str1.split(" ");
let splittedStr2 = str2.split(" ");

for (i = 0; i < splittedStr1.length; i++) {
  for (j = 0; j < splittedStr2.length; j++) {
    if (splittedStr1[i] === splittedStr2[j] && !similarWords.includes(splittedStr1[i])) {
      similarWords.push(splittedStr1[i]);
    }
  }
}
console.log(similarWords);

Sign up to request clarification or add additional context in comments.

1 Comment

Just to be safe, this check prevents adding the same word multiple times in the array.
1

Maybe they wanted something like this.

const str1 = "This is string 1";
const str2 = "This is string 2";
const words = new Set(str1.split(' ')); // Set(4) {'This', 'is', 'string', '1'}
str2.split(' ') // ['This', 'is', 'string', '2']
  .filter(word => words.has(word)); // Only keep the words from str2 that are also in str1

2 Comments

i've hard time understanding code that uses es6 concepts even though I'm aware of them...any tips?
Hmm, good question. Just try and wrap your head around filter and map first and look for opportunities to use them. Also, interviewers would love it if you could tell them why you would or wouldn't use Set. The set's word.has looks up in constant O(1) time, whereas array.includes is linear O(n) time. For tiny sets, it really doesn't matter, though the array is probably faster for small enough sets. But as the sets get bigger, Set will scale better. That's the kind of thing an interviewer would be interested to hear you talk about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.