10 common JavaScript interview Challenges.

Rahmatuzzaman sojib
7 min readMay 16, 2020

--

If you want to crack a coding interview, you should check out this 10 common JavaScript coding challenges. These are the most common and some of them are mostly asked interview challenges. So, without further delay, let’s jump into it.

#1 Palindrome

definition:- Palindrome is a word, sentence or character sequence which reads the same as we reverse it. Like- “mam”, “racecar” etc.

PROBLEM:- Write a function that will check the string is a palindrome or not.

Solution: It could be done with the help of “for loop” but there is another solution with less code. We will show the precise way to do this.

function isPalindrome(str) {  
str = str.toLowerCase();
return str === str.split('').reverse().join('');
}
isPalindrome('racecar') // true;isPalindrome('car') // false

Here we use the build-in “reverse” method which makes the code precise and readable.

#2 Fibonacci

Definition:- Fibonacci sequence is basically a sequence of number where every number in the sequence is the sum of the two previous one. A Fibonacci sequence is something look like this — 0,1,1,2,3,5,8,13,21,….

PROBLEM:- write a function that returns the nth entry in the Fibonacci sequence, where n is a number you pass in as an argument to the function.

Solution:- First we have to generate the sequence and then we have to find out the nth value of the sequence.

function fibonacci(num) {
let result = [ 0, 1 ];
for(let i=2; i<=num; i++){ let prevNum1 = result[i-1];
let prevNum2 = result[i-2];
result.push( prevNum1 + prevNum2);
}
return result[num];
}

first, we declare an array with the first two-element or number because it is possible to generate numbers if there is no previous element. we use the normal “for loop” for this. then we define the two previous number and push to the “result array”.

second approach:- you can use the recursive to solve this. This would precise your code and that could a way to impress the interviewer.

function fibonacci(num) {
if(num < 2){
return num;
}
return fibonacci(num-1) + fibonacci(num-2);
}

#3 FizzBuzz

It is the most popular challenge in a coding interview. So, before going for an interview you should check this out.

PROBLEM:- Write a function that does the following:

  • console logs the numbers from 1 to n, where n is the integer the function takes as its parameter
  • logs fizz instead of the number for multiples of 3
  • logs buzz instead of the number for multiples of 5
  • logs fizzbuzz for numbers that are multiples of both 3 and 5

solution:- The main point of this challenge is how you find the multiples of a number. Here you can use the remainder operator to find the multiples of 3 and 5.

function fizzbuzz(n) {
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log('fizzbuzz')
}
else if (i % 3 === 0) {
console.log('fizz')
}
else if (i % 5 === 0) {
console.log('buzz')
}
else {
console.log(i)
}
}
}
fizzbuzz(20)

What you need to pay attention to in this challenge is the order of the if … else statements. Start with the double condition first (&&) and end with the case where no multiples are found. This way, you’ll be able to cover all bases.

#4 Anagram

Definition:- A word is an anagram of another word if they are using the same letters with the same quantity, but arranged differently.

PROBLEM:- write a function that checks if two provided strings are anagrams of each other; letter casing shouldn’t matter. Also, consider only characters, not spaces or punctuation. For Example:

anagram('fried','fired') // true;
anagram('gainly', 'lying') //true;
anagram('listen', 'bye') // false;

Solution:- In this challenge, you have to compare both words not only in length but the letters as well. one way is to store them in object and then compare them.

const buildCharObject = str => {
const charObj = {}
for (let char of str.replace(/[^\w]/g).toLowerCase()) {
charObj[char] = charObj[char] + 1 || 1
}
return charObj
}
const anagram = (strA, strB) => {
const aCharObject = buildCharObject(strA)
const bCharObject = buildCharObject(strB)
if (Object.keys(aCharObject).length !== Object.keys(bCharObject).length) {
return false
}
for (let char in aCharObject) {
if (aCharObject[char] !== bCharObject[char]) {
return false
}
}
return true
}

First, we are trying to make a function where we can store a string as an object and then in the main function with the help of the previous function we try to compare both strings. Here, we use the “Object.keys()” method which returns the keys or property of an object.

#5 Find the Vowels

It’s not that kind of challenging compared to others. but that doesn’t detract from the fact that you could come across it during a job interview.

PROBLEM:- write a function that takes a string as an argument and returns the number of vowels contained in that string.

The vowels are “a”, “e”, “i”, “o”, “u”.

Examples:

findVowels('hello') // --> 2
findVowels('why') // --> 0

Solution:-

const findVowel = (str) => {
let count = 0;
let vowel = ['a', 'e', 'i', 'o', 'u'];
for (let char of str.toLowerCase()) {
if (vowel.includes(char)) {
count++;
}
}
return count;
}

Point to be noted that we use “includes()” method which is applicable both in string and array. Its return true or false base of the character.

#6 String Reverse

PROBLEM:- Write a function that takes a string as an argument and return a reverse version of the given string. Example:-

reverse("Hello") --> olleh

Solution:- This is quite easy compared to other challenges. You have already use the method in the Palindrome. Now you have implemented in this problem. You can do it with as usual for loop but you become more precise in coding. So, you should use less code.

const reverse = str => {
str = str.toLowerCase();
return str.split('').reverse().join('');
}

#7 Title Case a String

PROBLEM:- Write a function which takes a string of two or more word and capitalize the first letter of each word.

Solution:- You can solve this in many ways. The better way would be creating a function that covert the first letter of a string into upperCase. Let’s do this first.

function upperCaseFirst(str) {
let valueOfFirstChar = str.charCodeAt(0);
console.log(valueOfFirstChar);
let upperCaseLetter = String.fromCharCode(valueOfFirstChar - 32);
console.log(upperCaseLetter)
let restOfString = str.slice(1);
console.log(restOfString);
let finalResult = upperCaseLetter + restOfString;
console.log(finalResult);
return finalResult;
}

Now you can create the main function that will capitalize each of the first letters. That is easy to do because now you have to convert the string into an array with split(‘ ’) and then apply the map all the element. Let’s see in practice.

function titleCase(inputStr) {
let token = inputStr.split(' ');
let upperCaseToken = token.map(x => upperCaseFirst(x));
let result = upperCaseToken.join(' ');
console.log(result)
}

Here we use the white space in the join() method because we are making every single word as our array element, not every single letter.

#8 Replace One Character With Another

PROBLEM:- Replace every occurrence of a given character in a string with another. For Example-

Replace "l" with "X"
'hello world' ---> 'heXXo worXd'

Solution:- We won’t get through each and every step in detail.

function replaceChar(inputStr, replaceThis, withThis) {
let retVal = [];
for (let i = 0; i < inputStr.length; i++) {
if (inputStr[i] === replaceThis) {
retVal.push(withThis)
}
else {
retVal.push(inputStr[i])
}
}
return retVal.join('')
}

Our function takes three parameters whose purpose should be self-explanatory from their names. A variable to hold the intermediate result is created called retval, which stands for the return value.

We then loop through the provided string one character at a time, pushing the replacement character withThis into retval if it matches replaceThis. Otherwise, we retain the original character and add it to retval.

Finally, we call join on retval to produce a string and return it.

#9 Remove all duplicates from an array of integers

PROBLEM:- write a function that will return an array without duplicate values in the array.

Solution:- We can take the for loop approach to solve this but we are taking some librate in this. We are going to use the built-in method.

function removeDuplicate(arr) {
let result = [...new Set(arr)];
return result;
}

We are using the “new Set()” method for making our code smaller.

#10 Find all pairs in an array of integers whose sum is equal to a given number

PROBLEM:- Write a function that will pair up the array element whose sum is equal to a given number.

Solution:- To simplify, the input array will not have duplicates. However, there will be negative and positive numbers. For the solution,we will use a lookup hash.

let arr = [1,5,6,1,0,1];const findSumPairs = (arr, value) => {
let sumsLookup = {};
let output = [];

for(let i = 0; i < arr.length; i++) {
let targetVal = value - arr[i];

if(sumsLookup[targetVal]) {
output.push([arr[i], targetVal]);
}

sumsLookup[arr[i]] = true;
}

return output;
}
console.log(findSumPairs(arr, 6));

Conclusion

The above solutions show how you can use simple concepts to solve many common problems with one pass, linear solutions. There must be other solutions that can do better than linear complexity, but I will leave it to you to think about it and propose some ideas! Happy coding.

--

--

Rahmatuzzaman sojib

Electrical Engineer by Certificate | Self-learn front-end designer | Try to make myself as a writer | Want to work for myself