How to Beat 5 Common JavaScript Interview Challenges

article
#1

Originally published at: https://www.sitepoint.com/5-common-coding-interview-challenges/

The ways tech interviews are being carried out has been at the center of much controversy for a while now. It’s a sensitive topic, especially when it comes to coding challenges.

Not all companies use the same screening process, but for the most part, expect to be asked to solve a coding challenge, either on a suitable platform or on the dreaded whiteboard.

One complaint that’s usually made against coding challenges is that they’re mostly irrelevant to the day-to-day tasks the actual job requires. Especially when it comes to front-end interview questions, sometimes it’s curious how what’s missing in the interview are just front-end-related questions on things like browser compatibility, layout methods and DOM events. While this can be true, those who favor this approach and are responsible for hiring in these companies often say something like this:

I’d rather hire a smart person and teach them X than hire someone who knows everything about X but lacks creativity, logic, and reasoning. — Interviewing as a Front-End Engineer in San Francisco

Whatever we feel about the way candidates are screened for dev jobs, at the time of writing, coding challenges are still a big part of the interview process.

In this article, I’m going to show how you can tackle five common coding challenges you might be asked when interviewing for a JavaScript or front-end Junior Developer position. They’re not among the hardest ones you could come across in the interview process, but the way you approach each of them could make the difference between success and failure.

Pointers on Tackling Coding Challenges for Your Tech Interview

Before diving into the challenges, let’s go through some tips about how you could approach your tech interview.

  • Put in the time to prepare. Make your priority to research, learn less familiar topics, and practice a lot. If you haven’t got a Computer Science background, make sure you get familiar with some fundamental topics related to algorithms and data structures. There are online platforms, both free and paid, that offer great ways to practice your interview skills. GeeksforGeeks, Pramp, Interviewing.io, and CodeSignal are just a few of my favorite resources.
  • Practice thinking aloud when you’re trying to come up with a solution. In fact, talking through your thought process in an interview setting is preferable to spending all the available time writing down your solution in total silence. Your words will give the interviewer a chance to help you if you’re about to take a wrong turn. It also highlights your communication skills.
  • Understand the problem before starting to code. This is important. Otherwise, you might be wasting time thinking about the wrong problem. Also, it forces you to think about questions you may ask your interviewer, like edge cases, the data type of inputs/outputs, etc.
  • Practice writing code by hand. This helps you get familiar with the whiteboard scenario. A whiteboard doesn’t provide the kind of help that your code editor provides — such as shortcuts, autocomplete, formatting, and so on. When preparing, try writing down your code on a piece of paper or on a whiteboard instead of thinking it all up in your head.

Common Coding JavaScript Challenges

It’s likely that you’ve come across one or more of the challenges I’ve listed below, either during a job interview or while practicing your JavaScript skills. What better reason is there for getting really good at solving them?

Let’s get cracking!

#1 Palindrome

A palindrome is a word, sentence or other type of character sequence which reads the same backward as forward. For example, “racecar” and “Anna” are palindromes. “Table” and “John” aren’t palindromes, because they don’t read the same from left to right and from right to left.

Understanding the challenge

The problem can be stated along the following lines: given a string, return true if the string is a palindrome and false if it isn’t. Include spaces and punctuation in deciding if the string is a palindrome. For example:

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

Reasoning about the challenge

This challenge revolves around the idea of reversing a string. If the reversed string is the same as the original input string, then you have a palindrome and your function should return true. Conversely, if the reversed string isn’t the same as the original input string, the latter is not a palindrome and your function is expected to return false.

Solution

Here’s one way you can solve the palindrome challenge:

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('')
}

Start by turning your input string into lower case letters. Since you know you’re going to compare each character in this string to each corresponding character in the reversed string, having all the characters either in lower or upper case will ensure the comparison will leave out this aspect of the characters and just focus on the characters themselves.

Next, reverse the input string. You can do so by turning the string into an array using the String’s .split() method, then applying the Array’s .reverse() method and finally turning the reversed array back into a string with the Array’s .join() method. I’ve chained all these methods above so the code looks cleaner.

Finally, compare the reversed string with the original input and return the result — which will be true or false according to whether the two are exactly the same or not.

#2 FizzBuzz

This is a super popular coding challenge — the one question I couldn’t possibly leave out. Here’s how you can state the problem.

Understanding the challenge

The FizzBuzz challenge goes something like this. 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

Example:

fizzBuzz(5)

Result:

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

Reasoning about the challenge

One important point about FizzBuzz relates to how you can find multiples of a number in JavaScript. You do this using the modulo or remainder operator, which looks like this: %. This operator returns the remainder after a division between two numbers. A remainder of 0 indicates that the first number is a multiple of the second number:

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

If you divide 12 by 5, the result is 2 with a remainder of 2. If you divide 12 by 3, the result is 4 with a remainder of 0. In the first example, 12 is not a multiple of 5, while in the second example, 12 is a multiple of 3.

With this information, cracking FizzBuzz is a matter of using the appropriate conditional logic that will lead to printing the expected output.

Solution

Here’s one solution you can try out for the FizzBuzz challenge:

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 above simply makes the required tests using conditional statements and logs out the expected output. 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.

1 Like

#2

Minor correction on that FizzBuzz example. The last conditional statement should output i as opposed to outputting the num parameter.

3 Likes

#3

Fixed, thank you so much for pointing this out :slightly_smiling_face:

0 Likes

#4

The irony is not lost on an article providing guidance on properly passing tests that itself is incorrect. Incorrect on one of the most basic, trivial interview questions.

0 Likes

#5

Though it does tie back into the reasoning behind the question - not necessarily to produce flawless code first time, but to show that the coder is capable of understanding a problem, and plotting out a strategy for solving it.

Debugging has a name for a reason.

1 Like

#6

So I take it you think it is proper to release code without implementing the most basic of quality gates? The intent of the article is to provide a working solution to a common problem.

0 Likes

#7

No, what i’m saying is that in a time-pressured situation, that i’d rather see a fully fleshed out idea with a syntax error than let x = "I'm a turnip" written flawlessly.

Noone was talking about releasing code, the post is NOT ‘to provide a working solution’, it’s to talk about common code challenges in an interview. A time-specific challenge that isnt going to production…

0 Likes

#8

but isn’t it though in a way. I mean in this context this is code that you are submitting for a job interview. Shouldn’t that code be of highest quality possible?

0 Likes

#9

So what you’re telling me is that you always write code completely perfectly and never ever have a problem that you later have to correct. Or a syntax error that you miss when you have exactly X minutes to work on it and no time more.

The code should be of the highest quality possible. But if your thought is incomplete because you ran out of time then w

0 Likes

#10

When the code that is being submitted is for a job interview or tech screen that is correct.

It is up to the interviewer to decide how to proceed with the applicant.

I haven’t been asked to many questions like this in an interview. Typically there is a phone and online exercise tech screen before the in person interview process. A lot of companies use the online testing tools to screen candidates before anything.

0 Likes

#11

Then I applaud you for being such an excellent coder that no coding challenge can ever stump you or not be completeable by you in a fixed and small time frame. You are truly a wonder the likes of which any company in the world should hire immediately because you can create an entire project flawlessly in the blink of an eye.

Or you could realize that this thread wasnt directed to you, it was directed towards people applying for junior positions who haven’t got your gift of genius, and let it go.

Good day.

0 Likes

#12

These are not projects they are simple, trivial problems for one. Second I never said I pass ever screen and have been hired by every company that I’ve ever interviewed with.

0 Likes

#13

Nice article. Very much appreciated. Thank you.
I have a different solution for anagram one though, what do you think?

const anagram = (x = '', y = '') => {
	const xLen = x.length, yLen = y.length;
	if (xLen && yLen && xLen === yLen) {
		return x.toLowerCase().split('').sort().join('') === y.toLowerCase().split('').sort().join('');
	} else {
		return false;
	}
}
2 Likes

#14

Fibonacci recursive implementation has O(2^n) time complexity (exponential). You may just try it on num=50 input. Any interviewer will not accept that as well as implementation with the unused array. Why do you storing in memory all previous number if you need only 2 last for each iteration?

1 Like

#16

My personal one-liner approach to anagram case. Shortly speaking, it transforms both words to arrays to sort them lexically and compare them via toString method

const anagram = (a,b)=>[...a.toLowerCase()].sort().toString()==[...b.toLowerCase()].sort().toString()

0 Likes

#17

Thoughts on this one?

const fibonacci = n => { let a=0, b=1, i=2; for(; i<=n; i++) { [a, b] = [b, a+b]; } return a + b; }

0 Likes

#18

Yes, this works well.

0 Likes