Gabe avatar

JavaScript interview questions [with solutions]

gaottantacinque

Published: 21 Dec 2019 › Updated: 21 Dec 2019JavaScript interview questions [with solutions]

JavaScript interview questions [with solutions]


I have been a software engineer for almost 5 years now but (for one reason or another) only today for the first time I interviewed another developer for a position in my company.

Here is the simple exercise that I asked the (junior) candidate to solve:

Write a function that given 2 arrays of characters returns
whether the 2 arrays contain an acronym.

  Eg.

  [ 'b', 'i', 'n', 'a', 'r', 'y' ]
  [ 'b', 'r', 'a', 'i', 'n', 'y' ]
  => TRUE

  [ 'b', 'o', 'a', 't' ]
  [ 't', 'a', 'b', 'o', 'o' ]
   => FALSE



Here are a couple of simple solutions:

Solution 1:

var isAcronym = () => {
    if (!arr1.length || arr1.length != arr2.length) return false;
    arr1.forEach((el) => {
     const id = arr2.indexOf(el);
     if (id == -1) return false;
     arr2[id] = null;
    });
    return arr2.filter(el => !!el).length === 0;
}

var arr1 = ['b','a','g','r','e','i','e','l'];
var arr2 = ['g','a','b','r','i','e','l','e'];

console.log('Is Acronym: ', isAcronym(arr1, arr2));
  • Complexity: O(N)
  • Optimization: length check, best case: O(1)
  • Spatial complexity: in loco



Solution 2:

var isAcronym = () => {
    if (!arr1.length || arr1.length != arr2.length) return false;
    const count = {};
    arr1.forEach(el => {
     if (count[el]) count[el] += 1;
     else count[el] = 1;
    });
    arr2.forEach(el => {
     count[el] -= 1;
    });
    return Object.values(count).filter(res => res !== 0).length === 0;
};

var arr1 = ['g','a','b','i','r','e','l','e'];
var arr2 = ['g','a','b','r','i','e','l','e'];

console.log('Is Acronym: ', isAcronym(arr1, arr2));
  • Complexity: O(N)
  • Optimization: length check, best case: O(1)
  • Spatial complexity: O(N)


Did I miss any bugs? =)

Leave JavaScript interview questions [with solutions] to:

Written by

Founder of @cryptoshots.nft, @keys-defender, @marcocasario, @karina.gpt, ...

Read more #stem posts


Best Posts From Gabe

We have not curated any of gaottantacinque's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Gabe