JavaScript interview questions [with solutions]
(Edited)
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? =)
0
0
0.000
This post is promoted by @tipU voting service under #newsteem rules funded by marcocasario :)
The upvotes are not profitable and 50% of the payment is donated to @steempeak and other steem projects.
This post has received a 34.4 % upvote from @boomerang.