5 Common JavaScript Interview Problems: Analysis and Solutions

5 Common JavaScript Interview Problems: Analysis and Solutions

From the translator: published an article for you Maria Antonietta Perna, who talks about typical JavaScript tasks, most often offered to applicants-developers at interviews. The article will be useful, first of all, to novice programmers.

Interviews in technology companies have long been the talk of the town. This is not surprising - the successful completion of the interview makes it possible to get a good job. But this is not so easy, because often it is necessary to solve complex problems.

Moreover, most often most of these tasks are not related to the work that the applicant will perform, but they still need to be solved. Sometimes you have to do it on the board, without checking with Google or any other source. Yes, the situation is gradually changing, and in some companies they refuse such interviews, but many employers still adhere to this tradition. This article is devoted to the analysis of typical JavaScript tasks that are often used as tasks for applicants.

We remind you: for all readers of "Habr" - a discount of 10 rubles when enrolling in any Skillbox course using the "Habr" promotional code.

Skillbox recommends: Practical course "Mobile Developer PRO".

The main thing is to carefully prepare for your interview.

Yes, before we start breaking down the tasks, let's look at some general tips for preparing for an interview.

The main thing is to prepare in advance. Check how well you remember algorithms and data structures, and improve your knowledge in areas that you are not very familiar with. There are many online platforms to help you prepare for interviews. We advise Geeks for Geeks, Pram, Interviewing.io и CodeSignal.

It is worth learning to pronounce the decision out loud. It is advisable to tell applicants what you are doing, and not just write on the board (or type code on the computer, also silently). Thus, if you make a mistake in the code, but the solution is generally correct, you can increase your chances of success.

The problem needs to be understood before the solution can be started. In some cases, you can superficially understand the task and then go down the wrong path. It may be worth asking a few clarifying questions to the interviewer.

You need to practice writing code by hand, not on a PC. It happens that at interviews the applicant is given a marker and a board where there are no tips or automatic formatting. When looking for a solution, write down your code on a piece of paper or right on the board. If you keep everything in your head, you can forget something important.

Template Tasks in JavaScript

You are probably already familiar with some of these tasks. You either took interviews where you had to solve something similar, or practiced on them while learning JavaScript. Well, now it's time to solve them again, and with a detailed explanation of the process.

Palindrome

A palindrome is a word, sentence or sequence of characters that reads exactly the same way both in the usual direction and in the opposite direction. For example, "Anna" is a palindrome, but "table" and "John" are not.

Production

Given a string; you need to write a function that allows you to return true if the string is a palindrome, and false otherwise. In this case, spaces and punctuation marks must be taken into account.

palindrome('racecar') === true
palindrome('table') === false

Parsing the task

The main idea here is to flip the string backwards. If the "reverse" string is completely identical to the original one, then we got a palindrome and the function should return true. If not, false.

Solution

Here is the code that allows you to solve the palindrome.

const palindrome = str => {
  // turn the string to lowercase
  str = str.toLowerCase()
  // reverse input string and return the result of the
  // comparisong
  return str === str.split('').reverse().join('')
}

The first step is to convert the input string characters to lower case. This is a guarantee that the program will compare exactly the characters themselves, and not case or something else.

The second step is the reverse of the line. This is easy to do: you need to convert it to an array using the .split() method (String library). Then we reverse the array using .reverse() (Array library). The last step is to convert the reverse array to a string using .join() (Array library).

Now all that is needed is to compare the “reverse” string with the original one, returning the result true or false.

fizzbuzz

One of the most popular job interviews.

Production

It is required to write a function that displays numbers from 1 to n to the console, where n is an integer that the function takes as a parameter, with the following conditions:

  • output fizz instead of multiples of 3;
  • buzz output instead of multiples of 5;
  • fizzbuzz output instead of multiples of both 3 and 5.

Example

Fizzbuzz(5)

Experience the Power of Effective Results

/ / 1
/ / 2
// fizz
/ / 4
//buzz

Parsing the task

The main thing here is the way to find multiples using JavaScript. It can be implemented using the modulus operator or the remainder -%, which allows you to show the remainder when dividing two numbers. If the remainder is 0, it means that the first number is a multiple of the second.

12% 5 // 2 -> 12 is not a multiple of 5
12% 3 // 0 -> 12 is multiple of 3

So, if we divide 12 by 5, we get 2 with a remainder of 2. If we divide 12 by 3, then we get 4 with a remainder of 0. In the first case, 12 is not a multiple of 5, in the second, 12 is a multiple of 3.

Solution

The best solution would be the following code:

const fizzBuzz = num => {
  for(let i = 1; i <= num; i++) {
    // check if the number is a multiple of 3 and 5
    if(i % 3 === 0 && i % 5 === 0) {
      console.log('fizzbuzz')
    } // check if the number is a multiple of 3
      else if(i % 3 === 0) {
      console.log('fizz')
    } // check if the number is a multiple of 5
      else if(i % 5 === 0) {
      console.log('buzz')
    } else {
      console.log(i)
    }
  }
}

The function performs the necessary checks using conditional statements and produces the result required by the user. In the task, it is worth paying attention to the order of the if...else statements: starting with a double condition (&&) and ending with the case when multiple numbers could not be found. As a result, we cover all options.

Anagram

This is the name of a word that contains all the letters of another word in the same number, but in a different order.

Production

We need to write a function that checks if two strings are anagrams, and the case of letters does not matter. Only characters count; spaces or punctuation marks are not taken into account.

anagram('finder', 'Friend') --> true
anagram('hello', 'bye') --> false

Parsing the task

Here it is important to consider that it is necessary to check each letter in two input lines and their number in each line.

finder -> f: 1 friend -> f: 1
i: 1 r: 1
n: 1 i: 1
d: 1 e: 1
e: 1 n: 1
r:1 d:1

For storing anagram data, you should choose a structure such as a JavaScript object literal. The key in this case is the character of the letter, the value is the number of repetitions of it in the current line.

There are other conditions as well:

  • You need to make sure that the case of letters is not taken into account when comparing. Just convert both strings to lowercase or uppercase.
  • We exclude all non-characters from the comparison. Best to work with regular expressions.

Solution

// helper function that builds the
// object to store the data
const buildCharObject = str => {
  const charObj = {}
  for(let char of str.replace(/[^w]/g).toLowerCase()) {
    // if the object has already a key value pair
    // equal to the value being looped over,
    // increase the value by 1, otherwise add
    // the letter being looped over as key and 1 as its value
    charObj[char] = charObj[char] + 1 || 1
  }
  return charObj
}
 
// main function
const anagram = (strA, strB) => {
  // build the object that holds strA data
  const aCharObject = buildCharObject(strA)
  // build the object that holds strB data
  const bCharObject = buildCharObject(strB)
 
  // compare number of keys in the two objects
  // (anagrams must have the same number of letters)
  if(Object.keys(aCharObject).length !== Object.keys(bCharObject).length) {
    return false
  }
  // if both objects have the same number of keys
  // we can be sure that at least both strings
  // have the same number of characters
  // now we can compare the two objects to see if both
  // have the same letters in the same amount
  for(let char in aCharObject) {
    if(aCharObject[char] !== bCharObject[char]) {
      return false
    }
  }
  // if both the above checks succeed,
  // you have an anagram: return true
  return true
}

Pay attention to the use Object.keys () in the snippet above. This method returns an array containing the names or keys in the same order as they appear in the object. In this case, the array will be like this:

['f', 'i', 'n', 'd', 'e', ​​'r']

This way we get the properties of the object without having to do a big loop. In a task, you can use this method with the .length property - to check whether both strings have the same number of characters - this is an important feature of anagrams.

Vowel search

A fairly simple task that often comes across in interviews.

Production

You need to write a function that takes a string as an argument and returns the number of vowels that the string contains.
The vowels are "a", "e", "i", "o", "u".

Example:

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

Solution

Here is the easiest option:

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

It is important to pay attention to the use of the .includes() method. It is available for both strings and arrays. It should be used to find out if an array contains a certain value. This method returns true if the array contains the specified value and false otherwise.

There is also a shorter solution to the problem:

const findVowels = str => {
  const matched = str.match(/[aeiou]/gi)
  return matched ? matches.length : 0
}

The .match() method is used here, which allows you to implement an efficient search. If a regular expression as a method argument is found within the specified string, then the return value is an array of matching characters. Well, if there are no matches, then .match() returns null.

Fibonacci

A classic task that can be met at interviews of various levels. It is worth recalling that the Fibonacci sequence is a series of numbers, where each subsequent one is the sum of the previous two. So, the first ten numbers look like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

Production

You need to write a function that returns the nth record in a certain sequence, and n is a number that is passed as an argument to the function.

fibonacci(3) // --> 2

This task involves looping through the number of times specified in the argument, returning the value at the appropriate position. This way of setting the problem requires the use of loops. If you use recursion instead, the interviewer might like it and give you a few extra points.

Solution

const fibonacci = num => {
  // store the Fibonacci sequence you're going
  // to generate inside an array and
  // initialize the array with the first two
  // numbers of the sequence
  const result = [0, 1]
 
  for(let i = 2; i <= num; i++) {
    // push the sum of the two numbers
    // preceding the position of i in the result array
    // at the end of the result array
    const prevNum1 = result[i - 1]
    const prevNum2 = result[i - 2]
    result.push(prevNum1 + prevNum2)
  }
  // return the last value in the result array
  return result[num]
}

In the result array, the first two numbers are contained in a row because each entry in the sequence consists of the sum of the previous two numbers. There are no two numbers at the very beginning that can be taken to get the next number, so the loop cannot generate them automatically. But, as we know, the first two numbers are always 0 and 1. Therefore, you can initialize the result array manually.

As for recursion, everything is simpler and more complicated at the same time:

const fibonacci = num => {
  // if num is either 0 or 1 return num
  if(num < 2) {
    return num
  }
  // recursion here
  return fibonacci(num - 1) + fibonacci(num - 2)
}

We keep calling fibonacci(), passing in smaller and smaller numbers as arguments. We stop when the passed argument is 0 or 1.

Hack and predictor Aviator

Most likely, you have already faced any of these tasks if you were interviewing for a front-end or JavaScript developer job (especially if it is a junior level). But if you didn’t come across them, they may come in handy in the future - at least for general development.

Skillbox recommends:

Source: habr.com

Add a comment