DEV Community

Cover image for Whiteboard Coding Interview Questions Tips + Examples and Solutions
karlybl
karlybl

Posted on • Updated on • Originally published at remotesoftwareengineeringjobs.com

Whiteboard Coding Interview Questions Tips + Examples and Solutions

whiteboard coding interview meme

Whiteboard coding interview questions come in different flavors, from algorithmic problems to more practical design questions.

These interviews can be intimidating, but practicing beforehand and learning some tips and strategies can help you overcome these notorious whiteboard interviews.

In this article, we'll dive deeper into whiteboard coding interviews, talk about their different types, provide some tips, and go over common whiteboard interview questions with explanations on how to solve them.

Different Types of Whiteboard Coding Interview Questions

During a whiteboard coding interview, the interviewer will often present different types of problems to assess your programming skills. Below are some examples of the most common types of whiteboard coding interview questions:

1. Algorithmic questions

These types of questions test your problem-solving skills and your ability to think on your feet. They may require you to devise a unique solution or use an existing algorithm to solve a specific problem. Examples may include sorting algorithms, graph traversals, or building data structures.

2. Language-specific questions

These types of questions test your proficiency in specific programming languages like Java, Python, C++ and others. Such questions can range from simple language features to more complex ones, such as inheritance, higher-order functions, or memory management.

3. System design questions

These types of questions assess your abilities to design and implement software solutions that are scalable and maintainable. They may require you to design a system for a given scenario or optimize an existing one. Examples could include designing social media network APIs, designing algorithms for image processing, or designing components for a web application.

It's important to note that each company may have its own approach to whiteboard coding interviews, and therefore, the structure of questions may differ. Knowing the different types of problems you might encounter, though, can help you to be ready for whiteboard coding interviews.

Tips for Doing Well in a Whiteboard Coding Interview

Whiteboard coding interviews can be intimidating, but with the right preparation and approach, you can navigate them with confidence. Here are some whiteboard coding interview tips to help you excel in your next interview:

1. Practice, practice, practice

Practicing coding problems is key to success in whiteboard coding interviews. Before your interview, try to solve as many coding problems as possible, especially ones that are similar to the types of questions that you expect to encounter in the interview. Use online resources, such as HackerRank, LeetCode or CodeSignal, to find practice problems.

2. Stay Organized

Make sure you keep your code organized and clean. Use clear variable names and keep your code well-structured. Use pseudo-code or draw diagrams to help you stay organized during the coding process. Be mindful of the time, and try to use the time allocated in such a manner that it reflects your skills and clarity of thought process.

3. Communicate Your Thought Process

Your interviewer doesn't just want to see your final solution, they're interested in how you think through problems. Talk through your approach to the problem, and explain your thought process as you work through the problem. Don't be afraid to ask questions, and communicate in a clear and concise manner about your thought process.

We explained this more on Whiteboard Interview Mistakes To Avoid and why not communicating during the whiteboard interview is a big mistake that might cause you to fail the interview.

4. Be Mindful of Your Time

One of the challenges of whiteboard coding interviews is time management. Make sure you're keeping track of the clock, set a timer and aim to finish the interview within the stipulated duration. If you get stuck, don't waste too much time on a single problem. Instead, explain your thought process to the interviewer and move on to the next question.

Remember, good communication and excellent time management skills are as important as your problem-solving ability when it comes to acing whiteboard coding interviews.

How To Answer Any Whiteboard Problem

Before we go through our example questions and solutions, watch this helpful resource on the 6-step process to solve any whiteboard problem:

Watch the video

The video is by David Yang, CEO and co-founder of Fullstack Academy. In summary, here's how you can solve any problem in whiteboard coding interviews:

1. Repeat the question

This step is important because it helps you understand the problem better and ensures that you don’t miss any important details. You can also ask clarifying questions if needed.

Here are some examples of clarifying questions:

  • Can you give me an example of what you mean?
  • Can you explain this part in more detail?
  • Do you want me to consider edge cases?
  • Is there a time or space complexity requirement?
  • Can I assume that the input is valid?

2. Write out examples

This step helps you understand the problem better by breaking it down into smaller parts. You can start with simple examples and then move on to more complex ones. You can also use examples to test your code later.

Here are some examples of examples to write:

  • If the problem involves an array, you can write out different arrays with different lengths and values.
  • If the problem involves a string, you can write out different strings with different lengths and characters.
  • If the problem involves a tree or graph, you can draw out different trees or graphs with different structures and values.
  • The goal is to break down the problem into smaller parts and understand how it works. You can also use these examples to test your code later.

3. Describe your approaches

This step is where you explain your thought process and how you plan to solve the problem. You can talk about different approaches and explain why you chose a particular one. You can also discuss trade-offs between different approaches.

Here are some examples:

  • Brute force approach: This is the simplest approach that solves the problem but may not be the most efficient.
  • Greedy approach: This approach makes the locally optimal choice at each step with the hope of finding a global optimum.
  • Divide and conquer approach: This approach breaks down the problem into smaller subproblems and solves them recursively.
  • Dynamic programming approach: This approach breaks down the problem into smaller subproblems and stores the solutions to these subproblems to avoid redundant computations.

You can also discuss trade-offs between different approaches and explain why you chose a particular one.

4. Write your code

This step is where you actually write the code to solve the problem. You can start with a simple solution and then optimize it later. You should also write clean and readable code.

5. Test the code

This step is where you test your code to make sure it works as expected. You can test it with different inputs and edge cases.

Here are some examples of different inputs and edge cases to test:

  • Empty input
  • Large input
  • Small input
  • Input with negative numbers
  • Input with decimal numbers
  • Input with duplicates
  • Input with all the same numbers
  • Input with all the numbers in ascending order
  • Input with all the numbers in descending order

You should also check for errors and bugs.

6. Optimization

This step is where you optimize your code to make it more efficient. You can look for ways to reduce time complexity or space complexity.

Here are some examples:

  • Use a more efficient data structure
  • Reduce time complexity by using a better algorithm
  • Reduce space complexity by using less memory
  • Use memoization to avoid redundant computations
  • Use dynamic programming to avoid redundant computations
  • Use binary search to reduce time complexity

You should also consider trade-offs between efficiency and readability.

Whiteboard Coding Interview Question Examples

Now that we got that out of the way, we can proceed with more examples.

Here are some examples of whiteboard coding interview questions and explanations of how to solve them:

1. Reverse a string

Problem: Write a function that reverses a string. For example, “hello” should become “olleh”.

Solution: There are many ways to reverse a string. In Python, the most efficient way is by using slicing. Slice the input string with a step of -1, which starts from the end of the string and goes backwards

def reverse_slicing(s):
    return s[::-1]
Enter fullscreen mode Exit fullscreen mode

Time complexity: The time complexity of the Python code above is O(n), where n is the length of the string.

Although the code itself appears to be a one-liner, slicing the string actually creates a new copy of the original string. As a result, the time complexity of the operation is proportional to the length of the string being reversed. So, the time complexity of this approach is linear, making it an efficient way to reverse a string.

You can also use other approaches to reverse a string, but slicing is the fastest one.

2. Palindrome

Problem: Determine if a string is a palindrome. A string is a palindrome if it reads the same backward as forward. For example, "madam" and "racecar" is a palindrome, while "banana" is not.

Solution: Check if the input string is the same forwards and backwards by comparing the original string to its reverse.

def is_palindrome(s):
    return s == s[::-1]
Enter fullscreen mode Exit fullscreen mode

Time complexity: The time complexity of this solution is also O(n).

3. FizzBuzz

Problem: Write a function that prints the numbers from 1 to 100. For multiples of three, print "Fizz" instead of the number. For multiples of five, print "Buzz" instead of the number. For numbers which are multiples of both three and five, print "FizzBuzz" instead of the number.

Solution:

for i in range(1, 101):
    if i % 15 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
Enter fullscreen mode Exit fullscreen mode

Time complexity: O(n)

4. First non-repeating character

Problem: Find the first non-repeating character in a string

Solution: Loop through each character in the input string and check if its count is equal to 1. The first character that satisfies this condition is returned.

def first_non_repeating_char(s):
    for char in s:
        if s.count(char) == 1:
            return char
    return None
Enter fullscreen mode Exit fullscreen mode

Time complexity: The time complexity of this solution is O(n^2) in the worst case where n is the length of the string.

5. Find the missing number

Problem: Given an array of n-1 integers in the range of 1 to n, find the missing number.

Solution: Write a function that finds the missing number in an array that should contain all integers from 1 to n, where n is the length of the array plus one. Inside the function, you have to do three steps:

First, calculate the expected sum of all integers from 1 to n using the formula total_sum = n*(n+1)/2. This is because the sum of integers from 1 to n can be expressed as n*(n+1)/2.

Then, calculate the actual sum of the numbers in the input array arr using the built-in sum() function in Python.

Finally, the function subtracts the actual sum arr_sum from the expected sum total_sum to find the missing number in the array, and returns it.

def find_missing_number(arr):
    n = len(arr) + 1
    total_sum = n*(n+1)/2
    arr_sum = sum(arr)
    return total_sum - arr_sum
Enter fullscreen mode Exit fullscreen mode

Time complexity: O(n), where n is the number of elements in the input list arr. This is because the algorithm performs constant time operations to calculate the total sum of all numbers from 1 to n and the sum of all numbers in the input list. Since there is only one loop that iterates over the elements in the input list, the time complexity of the algorithm is O(n).

6. Counting duplicates

Problem: Given a string, return the count of the number of duplicates.

This is a tricky one, but not for the reason you think.

Take this string, for example: "abcdeaa”. The correct output of your solution should be 1. Here’s why:

Only the letter ”a” is found more than once so your solution should return 1. Even though there are three ”a” characters in the string, the goal of the function isn’t to count the number of repeat characters but to count the number of characters that have duplicates.

And that’s why it’s very important to make sure you understand the problem first, and be very clear about what your interviewer wants from you for each problem.

Solution: One way to solve this problem is to use a for-in-loop for each character in the string.

def duplicate_count(text):
    found = []
    for char in text:
        if char.lower() not in found and text.count(char) > 1:
            found.append(char.lower())
    return len(found)
Enter fullscreen mode Exit fullscreen mode

Time complexity: the time complexity of this solution is O(n^2), where n is the length of the string. It traverses the entire string to check for each character's count and membership in the found list, which takes O(n) time in the worst case, as it needs to traverse the entire list to check for membership. The count() function is called on the string for each character, which itself takes O(n) time. This is because the count() function needs to traverse the entire string to count the number of occurrences of a character.

Since both of these operations are performed for each character in the string, the overall time complexity of the code is O(n^2), which is not very efficient for large inputs.

7. Fibonacci sequence

Problem: Write a function that calculates the nth Fibonacci number. Fibonacci is a sequence of numbers where each number is the sum of the two preceding numbers, starting from 0 and 1. The sequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on. In this problem, you should return the nth number in the Fibonacci sequence. So if the input is 1, the output should be 0, because 0 is the first number in the Fibonacci sequence.

Solution: One way to solve this problem is to use arrays. This is more efficient than the recursive approach for large values of n.

def fibonacci(n):
    if n <= 0:
        return "Incorrect Output"
    data = [0, 1]
    if n > 2:
        for i in range(2, n):
            data.append(data[i-1] + data[i-2])
    return data[n-1]
Enter fullscreen mode Exit fullscreen mode

Time complexity: O(n), because it only needs to calculate each Fibonacci number once and store the previous results in an array. Then, accessing the previously calculated Fibonacci numbers from the array takes constant time.

8. Two Sum

Problem: Given an array of integers, return indices of the two numbers such that they add up to a specific target.

Example input: nums = [2, 7, 11, 15], target = 9

Expected output: [0, 1]

In this example, nums[0] + nums[1] = 2 + 7 = 9, so the indices 0 and 1 are returned.

Solution: One way to solve this problem is to use a dictionary to store the values and their indices. Then, iterate through the list and check if the target minus the current value is in the dictionary.

def two_sum(nums, target):
  d = {}
  for i, num in enumerate(nums):
      if target - num in d:
          return [d[target - num], i]
      else:
          d[num] = i
Enter fullscreen mode Exit fullscreen mode

Time complexity: O(n), where n is the number of elements in the input list nums. This is because the algorithm uses a dictionary d to store previously seen elements of nums, which allows for constant time lookups in the dictionary (assuming a reasonable hash function). The for loop runs once over each element in the input list, resulting in a total time complexity of O(n).

9. Armstrong

Problem: Write a function that determines if a number is an Armstrong number - the sum of each digit raised to the number's length is equal to the number itself.

Solution: To determine if a number is an Armstrong number, we first convert the number to a string to determine its length. We then initialize a variable sum_of_powers to 0, which will be used to store the sum of the power of each digit. We iterate over each digit in the number, convert it to an integer, raise it to the power of the length of the number, and add it to sum_of_powers. Finally, we check if sum_of_powers is equal to the original number and return the result.

def is_armstrong_number(num):
    # convert number to string to determine its length
    num_str = str(num)
    n = len(num_str)

    # initialize the sum of the power of each digit
    sum_of_powers = 0

    # calculate the sum of the power of each digit
    for digit in num_str:
        sum_of_powers += int(digit) ** n

    # check if the sum of powers is equal to the original number
    return sum_of_powers == num
Enter fullscreen mode Exit fullscreen mode

Time complexity: The time complexity of this algorithm is O(n), where n is the number of digits in the input number. Since the number of digits in a number is typically much smaller than the number itself, this algorithm runs in linear time and is very efficient.

10. Remove duplicates

Problem: Remove duplicate members of an array.

Solution: Convert the input array into a set using the set() function, which automatically removes any duplicates in the array since sets cannot have duplicate elements. Finally, we convert the set back to a list using the list() function and return it as the output.

def remove_duplicates(arr):
    return list(set(arr))
Enter fullscreen mode Exit fullscreen mode

Time complexity: The set() function has a time complexity of O(n) where n is the size of the input array, since it needs to iterate over all the elements of the array to create the set. The list() function also has a time complexity of O(n) since it needs to iterate over all the elements of the set to create a new list. Therefore, the overall time complexity of this function is O(n).

A word of caution

There are literally thousands of possible whiteboard coding interview questions that you might be asked to solve during your interview. That's why it's important not to focus on memorizing solutions, but on honing your problem-solving skills instead.

Remember, the purpose of whiteboard coding interviews is to test your problem-solving skills, reasoning, and communication skills. Sharpen these skills by practicing and building a strong foundation in algorithms. Moreover, stay flexible and adaptable in the face of the challenges presented by the interview problems. With these key elements in mind, you'll be ready to tackle whatever problem the interviewer throws your way!

Just be sure to keep practicing solving some of the common questions and how to approach them, so you can gain an edge in your job search and stand out as a strong candidate for software engineering positions. Don't hesitate to take advantage of online resources and practice problems like the ones above.

Most of all, don’t hesitate to take advantage of the remote programming jobs we have on our platform to find new opportunities.

Good luck with your job search!

Top comments (0)