Coding interview questions

140 questions, easy to hard. Read one, then answer it out loud: an AI interviewer follows up, hints when you're stuck and grades your answer.

Coding interviews test data structures and algorithms: arrays and hashing, two pointers, trees, graphs, dynamic programming and the Big-O reasoning behind each solution.

Big-O Basics

  1. The coach plays a junior developer who keeps hearing about big-O. Explain what it tells you about an algorithm, and why constants and smaller terms are dropped.

  2. Talk through how to work out the time complexity of code built from loops: one loop over the input, two loops one after the other, one loop inside another, and a loop that halves its counter each time.

  3. Put the common complexity classes in order from fastest to slowest, namely constant, logarithmic, linear, linearithmic, quadratic, exponential and factorial, and give a typical algorithm for each.

  4. Explain how to work out the time complexity of a recursive function, using naive Fibonacci, binary search and merge sort as your examples.

  5. A dynamic array, such as a Python list or a Java ArrayList, grows its capacity by a constant factor, often doubling, when it fills up. Explain why appending is said to take constant time even though some appends copy everything.

  6. Explain what space complexity measures and how to work it out, including the memory used by recursion and whether the input and output count.

  7. Hash map lookups are usually described as constant time. Explain why that's an average rather than a guarantee, and what can make them slow.

Arrays & Hashing

  1. You're given a list of integers and a target number. Find two different positions in the list whose values add up to the target, and return those two positions. You can assume exactly one such pair exists.

    What a strong answer covers
    • The obvious solution first, and what it costs as the list grows.
    • A faster idea that remembers what you've already seen.
    • The time and memory the faster version needs.
    • An edge case with repeated values.

    Common mistake: Jumping straight to code without saying why the simple version is slow, or pairing a number with itself.

  2. Given a list of integers, decide whether any value appears more than once. Explain the fastest approach you can think of, its cost in time and memory, and an alternative that uses less memory.

  3. Given two lowercase words, decide whether one is an anagram of the other, meaning they use exactly the same letters the same number of times. Explain your approach and its cost.

  4. You're given a list of lowercase words. Group together the words that are anagrams of each other — words made of exactly the same letters in a different order — and return the groups in any order.

  5. Given a list of integers and a number k, return the k values that appear most often. Explain how to do it faster than sorting all the counts, and the cost of each approach.

  6. Given a list of integers, build a new list where each position holds the product of all the other numbers, without using division. Explain how to do it in linear time.

  7. Given an unsorted list of integers, find the length of the longest run of consecutive values, such as four, five, six and seven, which may appear in any order in the list. Explain how to do it in linear time.

  8. Given a list of integers, which may include negatives, and a target, count how many contiguous stretches of the list add up exactly to the target. Explain why a sliding window doesn't work here, and what does.

  9. Given an unsorted list of integers, find the smallest positive integer that does not appear in it. Do it in linear time using only constant extra memory, and explain your approach.

Two Pointers

  1. Given a sentence, decide whether it reads the same forwards and backwards, ignoring case, spaces and punctuation. For example, "A man, a plan, a canal: Panama" counts as a palindrome. Explain your approach and its cost.

  2. Given a list of integers sorted in ascending order and a target, find two numbers that add up to the target using only constant extra memory. Explain why your approach never misses the answer.

  3. Given a sorted list of integers, remove the repeated values in place so each value appears once at the front of the list, and return how many unique values there are. Explain your approach and its cost.

  4. Given a list of integers, move all the zeros to the end while keeping the other numbers in their original order, changing the list in place. Explain your approach and its cost.

  5. You're given a row of vertical lines of different heights, evenly spaced. Pick two lines that, together with the ground, hold the most water. The water level is limited by the shorter line, and the width is the distance between them. Explain how to find the best pair faster than trying every pair.

  6. A list contains only the values zero, one and two, standing for three colours. Sort it in place in a single pass using constant extra memory, and explain how your pointers move.

  7. Given a list of integers, find every distinct group of three numbers that adds up to zero. The same group must not be reported twice, even if the list contains repeated values. Explain your approach, how you avoid duplicates, and its cost.

  8. Given a row of bars of different heights, work out how much rainwater would be trapped between them after it rains. Explain a linear-time approach and how to get it down to constant extra memory.

Sliding Window

  1. You're given a stock's price for each day. You may buy once and sell once on a later day. Find the largest profit you could make, or zero if prices only fall. Explain your approach and its cost.

  2. Given a list of numbers and a block length k, find the contiguous block of exactly k numbers with the highest average. Explain how to avoid adding up every block from scratch.

  3. Given a string, find the length of the longest stretch of consecutive characters in which no character appears twice. For example, in "abcabcbb" the answer is three. Explain your approach and its cost.

  4. Given a string of capital letters and a number k, you may change up to k letters to any other letter. Find the length of the longest stretch of a single repeated letter you could make, and explain when your window must shrink.

  5. Given two strings, decide whether the second contains a contiguous stretch that is a rearrangement of the first. Explain how to check every candidate stretch efficiently.

  6. Given a list of positive integers and a target, find the length of the shortest contiguous stretch whose sum is at least the target, or zero if there is none. Explain your approach and why it matters that the numbers are positive.

  7. Given a long text and a short pattern, find the shortest stretch of the text that contains every character of the pattern, including repeats. For example, if the pattern has two a's, the stretch needs at least two a's. Explain your approach and its cost.

  8. Given a list of numbers and a window size k, report the largest number in every window of k consecutive numbers as the window slides from left to right. Explain how to do it in linear time.

Stack

  1. Given a string made of round, square and curly brackets, decide whether every opening bracket is closed by the same kind of bracket, in the right order. For example, round-square-close-square-close-round is fine, but round-square-close-round-close-square is not. Explain your approach.

  2. Build a first-in, first-out queue using only two stacks. Explain how adding and removing work, and why each operation costs constant time on average.

  3. Design a stack that supports push, pop, reading the top, and returning the smallest value currently in the stack, all in constant time. Explain how you'd store the data and keep the minimum correct after pops.

  4. You're given daily temperatures. For each day, work out how many days you'd wait until a warmer day, or zero if none comes. Explain an approach faster than checking every later day for each day.

  5. You're given an arithmetic expression in reverse Polish notation, where each operator comes after its two operands, as a list of tokens that are numbers or the four basic operators. Work out its value and explain how a stack does it.

  6. Given an absolute Unix-style file path that may contain repeated slashes, single dots meaning the current folder and double dots meaning the parent folder, reduce it to its simplest form. Explain how a stack helps.

  7. A string is encoded so that a number followed by some text in square brackets means that text repeated that many times, and brackets can be nested. Decode it, and explain how you handle the nesting.

  8. Given the heights of bars in a histogram, each one unit wide, find the area of the largest rectangle that fits entirely within the bars. Explain how to do it in linear time.

Linked Lists

  1. Given the head of a singly linked list, reverse the list and return its new head. Explain how you'd do it in place, and what it costs.

  2. Given the heads of two linked lists, each already sorted in ascending order, merge them into one sorted list by relinking their nodes. Explain your approach and its cost.

  3. Given the head of a linked list, decide whether following the next pointers ever loops back to a node you've already seen. Explain a solution that uses constant extra space.

  4. Given the head of a linked list, return its middle node in a single pass, without first counting the nodes. If there are two middle nodes, return the second one.

  5. Given the head of a linked list and a number n, remove the nth node counting from the end and return the head. Explain how to do it in one pass.

  6. Two non-negative whole numbers are stored as linked lists, one digit per node, with the ones digit first. Return their sum as a linked list in the same form, and explain how you handle carries.

  7. Each node in a linked list has a next pointer and a random pointer that can point to any node in the list or to nothing. Make a deep copy of the list, and explain how you wire up the copied random pointers.

  8. Design a cache with a fixed capacity that supports getting and putting values by key, both in constant time. When it's full, putting a new key must evict the least recently used one.

  9. Given a linked list and a number k, reverse the nodes in each consecutive group of k, and leave any final group shorter than k as it is. Explain how you reconnect the groups.

Binary Search

  1. Given a sorted list of numbers and a target, return the target's position, or minus one if it isn't there. Explain an approach faster than checking each number, how you keep the bounds right, and its cost.

  2. Given a sorted list of distinct integers and a target, return the target's position if it's present, or the position where it would be inserted to keep the list sorted. Explain your approach and how you avoid off-by-one mistakes.

  3. Given a non-negative integer, return its square root rounded down, without using any built-in power or square-root function. Explain how binary search applies when there's no list to search.

  4. Given a sorted list that may contain repeats and a target value, find the first and last positions where the target appears, or report that it's missing. Explain how to do it in logarithmic time.

  5. A sorted list of distinct numbers has been rotated at some unknown point, so it may start part-way through and wrap around. Find the smallest number in logarithmic time, and explain how you decide which half to discard.

  6. A sorted list of distinct numbers has been rotated at an unknown point, so it might look like four, five, six, seven, zero, one, two. Find a target's position in logarithmic time, or return minus one. Explain how binary search still works.

  7. A grid of integers is sorted so that each row runs from smallest to largest, and the first number of each row is larger than the last number of the row above. Decide whether a target is in the grid, and explain how to search it in logarithmic time.

  8. A panda has several piles of bamboo and a number of hours. Each hour it picks one pile and eats a fixed number of stalks from it, leaving the rest of the hour idle if the pile runs out. Find the slowest eating speed that finishes all the piles within the hours. Explain your approach and its cost.

  9. Given two sorted lists, find the median of all their numbers combined, faster than merging them. Explain how a binary search over where to cut the lists works.

Sorting

  1. Explain how merge sort orders a list of numbers, step by step. Then say what it costs in time and memory, and why.

  2. Explain how insertion sort works, and why it can beat a faster-sounding sort when the list is already almost in order.

  3. Explain how quicksort orders a list, how the pivot is chosen, and what happens in the worst case. Say how real implementations avoid that worst case.

  4. Explain what it means for a sorting algorithm to be stable, and give a practical situation where it matters. Say which common sorts are stable and which aren't.

  5. Comparison sorts can't beat n log n in the worst case. Explain why, and how counting sort and radix sort get around that limit for some kinds of data.

  6. Given an unsorted list and a number k, find the kth largest element without fully sorting the list. Explain quickselect and compare it with using a heap.

  7. Given a list of non-negative integers, arrange them so that writing them one after another forms the largest possible number, and return it as text. Explain how you'd decide the order.

  8. An inversion is a pair of positions where the earlier element is larger than the later one. Count the inversions in a list faster than checking every pair.

Trees

  1. Given a binary tree, find its depth: the number of nodes on the longest path from the root down to a leaf. Explain a recursive approach and an iterative one.

  2. Given a binary tree, flip it into its mirror image so that every node's left and right children are swapped. Explain a recursive approach and its cost.

  3. Given two binary trees, decide whether they are identical, meaning the same shape with the same value at every position. Explain your approach and when you can stop early.

  4. Given a binary tree, return its values grouped by level: the root's level, then the next level from left to right, and so on. Explain your approach and its cost.

  5. Imagine standing to the right of a binary tree. Return the values of the nodes you can see, from top to bottom, and explain your traversal.

  6. Given a binary tree, decide whether it's a valid binary search tree: every node's value must be greater than all values in its left subtree and less than all values in its right subtree. Explain why only comparing each node with its children isn't enough, and how you'd check it properly.

  7. Given a binary search tree and two of its nodes, find their lowest common ancestor: the deepest node that has both as descendants, where a node counts as its own descendant. Explain how the ordering helps.

  8. Given a binary search tree and a number k, find the kth smallest value in it. Explain your traversal, and how you'd keep repeated queries fast if the tree changes often.

  9. Given a binary tree, find its diameter: the number of edges on the longest path between any two nodes, which may or may not pass through the root. Explain how to do it in a single traversal.

  10. Each node of a binary tree holds an integer, possibly negative. Find the largest sum of values along any path, where a path follows edges, visits each node at most once and need not pass through the root. Explain your recursion.

Tries

  1. Design a prefix tree, also called a trie, that can add a word, check whether a whole word was added, and check whether any added word starts with a given prefix. Explain how it's laid out and what each operation costs.

  2. You have a list of product names, and a user types a search word one letter at a time. After each letter, suggest up to three product names that start with what's been typed, in alphabetical order. Explain how you'd do it.

  3. Design a word dictionary that supports adding words and searching for a pattern, where the pattern may contain a wildcard character that matches any single letter. Explain how the search handles the wildcard and what it costs.

  4. You're given a dictionary of word roots and a sentence. Replace each word in the sentence with the shortest root that it starts with, leaving words with no matching root unchanged. Explain your approach and its cost.

  5. You're given a grid of letters and a list of words. Find every word that can be spelled by moving between horizontally or vertically adjacent cells, using each cell at most once per word. Explain how to do this faster than searching for each word separately.

  6. Given a list of non-negative integers, find the largest value you can get by taking the bitwise exclusive or of any two of them. Explain how to beat checking every pair.

Heaps & Priority Queues

  1. Explain how a binary min-heap works: how it's stored, how you add an item and remove the smallest, and what each operation costs.

  2. You have a pile of stones with different weights. Each turn you smash the two heaviest together: if they're equal both are destroyed, otherwise the lighter one is destroyed and the heavier loses that much weight. Return the weight of the last stone, or zero if none are left.

  3. Numbers arrive one at a time, and after each one you must report the kth largest number seen so far. Explain which structure you'd keep and why.

  4. Given a list of points on a flat plane and a number k, return the k points closest to the origin. Explain your approach and its cost.

  5. A processor runs tasks labelled with letters, one per time unit, and between two runs of the same letter there must be at least a given number of cooldown units, during which it may run other tasks or sit idle. Given the tasks and the cooldown, find the fewest time units needed to finish them all.

  6. Given k linked lists, each sorted in ascending order, merge them into a single sorted list. Explain how to do it efficiently when k is large.

  7. Numbers arrive one at a time, and at any moment you must be able to report the median of everything seen so far. Explain a design that keeps each step fast.

Graphs

  1. A picture is a grid of coloured pixels. Given a starting pixel and a new colour, repaint the starting pixel and every pixel connected to it, up, down, left or right, that had the same original colour, like a paint bucket tool. Explain your approach.

  2. You're given an undirected graph as a number of nodes and a list of edges, plus a start node and an end node. Decide whether you can travel from the start to the end, and explain how you'd store the graph and search it.

  3. A map is a grid of land and water squares. An island is a group of land squares connected up, down, left or right. Count the islands. Explain your approach and its cost.

  4. Clone a Graph
    • medium
    • Pro

    Given one node of a connected undirected graph, where each node has a value and a list of neighbours, build a deep copy of the whole graph. Explain how you avoid copying a node twice or looping forever.

  5. Rotting Fruit
    • medium
    • Pro

    A grid holds empty cells, fresh fruit and rotten fruit. Each minute, every fresh fruit directly above, below, left or right of a rotten one becomes rotten. Find how many minutes pass until no fresh fruit remains, or report that it never happens.

  6. There are a number of courses, and some must be taken before others: for example, Algebra before Calculus. Given the list of these prerequisite pairs, decide whether it's possible to take every course, and if so, give a valid order. Explain your approach.

  7. You must take a set of courses, and some courses must be taken before others. Produce an order in which you can take them all, or report that it's impossible. Explain the algorithm and how it detects the impossible case.

  8. A network started as a tree, then one extra connection was added, creating exactly one cycle. Given the connections in the order they were added, find one you can remove to make it a tree again, and explain how union-find helps.

  9. A signal is sent from one node of a network whose one-way connections each take a known, non-negative time to cross. Find how long it takes until every node has received it, or report that some never will, and explain the algorithm you'd use.

  10. Given a start word, an end word and a dictionary, find the fewest words in a chain from start to end, where each step changes exactly one letter and every word is in the dictionary. Explain how you'd model and search it efficiently.

Backtracking

  1. Given a list of distinct numbers, list every possible subset, including the empty one and the whole list. Explain how you'd generate them and how many there are.

  2. Given a list of distinct numbers, return every possible ordering of them. Explain how your recursion builds each ordering and what it costs.

  3. On an old phone keypad, each digit from two to nine maps to three or four letters. Given a string of such digits, return every letter combination it could spell.

  4. Given a list of distinct positive numbers and a target, find every combination that adds up to the target, where each number may be used any number of times. The same combination in a different order counts only once.

  5. Given a list of numbers that may contain repeats, list every distinct subset, with no subset appearing twice. Explain how you avoid the duplicates without storing and checking every result.

  6. Given a grid of letters and a word, decide whether the word can be traced through the grid by moving between horizontally or vertically adjacent cells, without using any cell twice.

  7. Place n chess queens on an n by n board so that no two attack each other, and count how many such arrangements exist. Explain how you prune the search.

  8. Given a partly filled nine by nine sudoku grid, fill the empty cells so that every row, column and three by three box contains each digit from one to nine exactly once. Explain your search and how you keep it fast.

Greedy

  1. Each child has a minimum cookie size that will satisfy them, and you have cookies of various sizes. Each child gets at most one cookie. Find the largest number of children you can satisfy.

  2. Given a share's price on each day, find the most profit you can make if you may buy and sell as many times as you like, but hold at most one share at a time.

  3. Given a list of integers, some negative, find the largest sum of any run of consecutive numbers. The run must contain at least one number. Explain an approach faster than checking every run.

  4. You start at the first position of a list, and each number says the furthest you may jump forward from that position. Decide whether you can reach the last position.

  5. You start at the first position of a list, and each number says the furthest you may jump forward from there. Assuming the end is always reachable, find the fewest jumps needed to get there.

  6. Petrol stations stand around a circular road. Each gives a certain amount of fuel, and driving to the next one costs a certain amount. Find a station you could start from with an empty tank and drive all the way round, or say it's impossible.

  7. Split a string into as many parts as possible so that each letter appears in at most one part, and report the length of each part.

  8. Children stand in a row, each with a rating. Every child must get at least one sweet, and a child with a higher rating than a neighbour must get more sweets than that neighbour. Find the fewest sweets needed.

Intervals

  1. You're given a list of meetings, each with a start time and an end time. Decide whether one person could attend all of them without any two overlapping. Explain your approach and its cost.

  2. You're given a list of time ranges in no particular order. Merge every group of overlapping ranges into one, and return the merged ranges. Explain your approach, its cost and the tricky cases.

  3. You have a list of non-overlapping time ranges, already sorted by start. Insert one new range, merging it with any it overlaps, so the list stays sorted and non-overlapping. Explain how to do it in a single pass.

  4. You're given a list of time ranges. Find the smallest number you must remove so that none of the remaining ranges overlap. Explain your strategy and why it's right.

  5. You're given a list of meetings with start and end times. Work out the smallest number of rooms needed so every meeting has a room. Explain your approach and its cost.

  6. Two people each give you a sorted list of non-overlapping free time ranges. Find every range of time when both are free. Explain how to do it without comparing every pair.

  7. Several employees each have a sorted list of busy time ranges. Find the gaps when nobody is busy, ignoring the open time before the first meeting and after the last. Explain your approach and its cost.

Bit Manipulation

  1. Given a non-negative integer, count how many ones there are in its binary form. Explain a simple way, then a trick that only does as many steps as there are ones.

  2. In a list of integers, every value appears exactly twice except one, which appears once. Find that one in linear time using only a constant amount of extra memory.

  3. Given an integer, decide whether it's a power of two, without loops or recursion. Explain the bit pattern you rely on and the edge cases.

  4. A list holds n distinct numbers taken from zero up to n, so exactly one number in that range is missing. Find it in linear time and constant extra space.

  5. For every integer from zero up to n, count the ones in its binary form, and return all the counts. Explain how to do it in linear time overall, rather than counting each number from scratch.

  6. Add two integers without using the plus or minus operators. Explain how bitwise operations can do the job, and what changes for negative numbers.

  7. In a list of integers, every value appears exactly three times except one, which appears once. Find that one in linear time and constant extra space, and explain why plain XOR no longer works.

  8. Given a list of distinct items, list every possible subset without using recursion. Explain how counting through integers can do it and what it costs.

Dynamic Programming

  1. You climb a staircase of n steps, taking either one or two steps at a time. How many different ways can you reach the top? Explain how you'd work it out, why the plain recursive solution is slow, and how to fix it.

  2. Each step of a staircase has a cost you pay when you stand on it, and you may climb one or two steps at a time, starting from either the first or the second step. Find the minimum cost to reach the top, just past the last step, and explain your recurrence.

  3. A burglar plans to rob houses along a street, each holding some amount of money. Robbing two neighbouring houses sets off an alarm. Find the most money they can take. Explain how you'd define the subproblem and build the answer.

  4. A robot starts in the top-left corner of a grid and can only move right or down. How many different paths lead to the bottom-right corner? Explain a dynamic programming solution and any shortcut.

  5. Letters are encoded as numbers, with A as one up to Z as twenty-six, and a message arrives as a string of digits. Count how many ways it can be decoded back into letters, and explain your recurrence and the tricky cases.

  6. Given coin values, such as one, three and four, and an amount, find the fewest coins that add up to the amount, using as many of each coin as you like, or say it's impossible. Explain why always taking the largest coin can fail, and how you'd solve it.

  7. Given a string with no spaces and a dictionary of words, decide whether the string can be split into a sequence of dictionary words. Explain your dynamic programming table.

  8. Given a list of integers, find the length of the longest subsequence whose values strictly increase, where a subsequence keeps the original order but may skip elements. Explain a quadratic solution and how to make it faster.

  9. Given two strings, find the length of the longest sequence of characters that appears in both in the same order, though not necessarily side by side. For example, "ace" is common to "abcde" and "ace". Explain how you'd set up the table and fill it.

  10. Find the minimum number of single-letter insertions, deletions and substitutions needed to turn one word into another. Explain your table and what each cell means.

Questions about practising

How should I prepare for coding interview questions?
Practise answering them out loud, not just reading them. Explaining an answer under follow-up questions is what interviews test. Work through the 140 questions here from easy to hard, and revisit the ones you struggle with.
Can I practise coding interview questions with an AI?
Yes. Open any question and start a voice session: an AI interviewer asks it, follows up on your answer, gives hints when you're stuck and grades your answer with written feedback when the call ends.
Are these coding interview questions free?
5 of the 140 questions are free to practise. Sign in with Google, no card needed. Pro unlocks the rest, plus practice calls to your phone.