Algorithm interview questions: the patterns behind coding rounds

Algorithm interview questions test whether you can spot the pattern behind a problem (binary search, two pointers, sliding window, backtracking, greedy, dynamic programming or graph search) and justify its time and space cost. Interviewers care less about whether you have seen the exact problem and more about how you get from a brute force idea to an efficient one, out loud, with a correctness argument. Learn a small set of patterns well instead of memorizing hundreds of solutions.

By Published 12 min read

How algorithm questions show up in interviews

Most software engineering loops include one or more coding rounds of 45 to 60 minutes, often preceded by an online assessment with a timer and hidden test cases. Each round usually holds one medium problem or two smaller ones. A typical flow: you restate the problem, ask about input size and edge cases, propose an approach, agree on it, write code, then trace an example and state the complexity. Fresher and campus rounds lean on classic algorithm theory (sorting stability, recursion, Big O of standard algorithms). Experienced rounds assume the theory and judge how quickly you find the right pattern, how clean the code is, and whether you test it without being asked.

Signals in the problem statement and the pattern they usually point to
If the problem says...Try firstTypical cost
The input is sorted, or the answer is a number in a rangeBinary search (on the index or on the answer)O(log n) or O(n log range)
Pairs or triples in a sorted array, or reversing in placeTwo pointers from both endsO(n) after an O(n log n) sort
Longest or shortest contiguous subarray or substringSliding windowO(n)
All subsets, permutations or placementsBacktrackingExponential, pruned
Count the ways, or the minimum or maximum cost of a sequence of choicesDynamic programmingStates times transitions
Schedule the most intervals, or pick the locally best item repeatedlyGreedy, usually after sortingO(n log n)
Fewest steps in a grid or unweighted networkBreadth-first searchO(V + E)
Tasks with prerequisitesTopological sortO(V + E)
Cheapest path with non-negative weightsDijkstra's algorithm with a priority queueO((V + E) log V)
Signals in the problem statement and the pattern they usually point to. Scroll sideways on a small screen.

Complexity analysis questions

  • What does O(n log n) mean, in plain words? The work grows a little faster than the input: doubling n slightly more than doubles the time. Mention that Big O is an upper bound on growth, and that constants and memory access patterns still matter for real inputs.
  • How do you find the complexity of a recursive function? Write the recurrence. Merge sort is T(n) = 2T(n/2) + O(n), which solves to O(n log n); naive Fibonacci branches twice per call, which is exponential. The recursion tree picture is usually enough in an interview.
  • What is amortized complexity? The average cost per operation over a worst-case sequence. A dynamic array append is O(1) amortized even though an individual resize costs O(n).
  • Does recursion use extra space? Yes, one stack frame per level. A depth-first search on a path-shaped graph of a million nodes can overflow the default stack in Python or Java, which is a good reason to mention an iterative version.
  • What input size does each complexity allow? A rough rule many candidates use: around 10 to the 8 simple operations per second. So n up to about 10 to the 5 needs O(n log n) or better, while n of 20 allows O(2 to the n). Asking for the constraints early tells you which pattern the interviewer expects.
  • Best, average and worst case of quicksort? O(n log n) on average, O(n squared) in the worst case when pivots split badly, for example a first-element pivot on sorted input. Random pivots make the bad case very unlikely.

Sorting and searching

Sorting and searching questions
QuestionWhat it testsWhat a strong answer shows
Compare merge sort, quicksort and heapsort.Trade-offsMerge sort is stable and O(n log n) always but needs O(n) extra memory. Quicksort is in place and fast in practice with an O(n squared) worst case. Heapsort is in place and O(n log n) always but not stable and less cache friendly.
What is a stable sort and when does it matter?DefinitionsEqual keys keep their original order. It matters when you sort by one field after another, such as by date and then by customer.
Can you sort faster than O(n log n)?Lower boundsNot with comparisons alone. Counting sort and radix sort beat it when keys are small integers or fixed-width strings.
Find the kth largest element without sorting everything.SelectionQuickselect averages O(n); a size-k heap gives O(n log k). Say which you would choose for a stream.
Find the first position where a condition becomes true.Binary search templateA half-open lo/hi search with a clear invariant, and care with the midpoint and the loop end.
Search in a rotated sorted array.Binary search variantsOne half is always sorted; check whether the target lies in that half and discard the other.
Find the smallest capacity that ships all packages in D days.Binary search on the answerFeasibility is monotonic in the capacity, so search the range of capacities with a greedy check.
Merge k sorted lists.Combining patternsA min-heap of the current heads gives O(N log k); merging pairwise also works.
Sorting and searching questions. Scroll sideways on a small screen.
def ship_within_days(weights, days):
    def fits(capacity):
        used, load = 1, 0
        for w in weights:
            if load + w > capacity:
                used, load = used + 1, 0
            load += w
        return used <= days

    lo, hi = max(weights), sum(weights)   # the answer lies in [lo, hi]
    while lo < hi:
        mid = (lo + hi) // 2
        if fits(mid):
            hi = mid          # mid works; try smaller
        else:
            lo = mid + 1      # mid fails; go bigger
    return lo


print(ship_within_days([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5))  # 15
print(ship_within_days([3, 2, 2, 4, 1, 4], 3))                # 6
Binary search on the answer: the smallest ship capacity that moves all weights, in order, within the given days. O(n log(sum of weights)).

Two pointers and sliding window

  • Given a sorted array, find two numbers that sum to a target in O(1) extra space. Start one pointer at each end; move the left one right if the sum is too small and the right one left if it is too big. Each step discards one candidate for good.
  • Find all unique triplets that sum to zero. Sort, fix one element, run the two-pointer pass on the rest, and skip duplicates on both the fixed element and the pointers. O(n squared) overall.
  • Remove duplicates from a sorted array in place. A slow write pointer and a fast read pointer. The slow pointer marks the end of the clean prefix.
  • Container with the most water. Two pointers from both ends; always move the shorter wall, because keeping it can never produce a larger area.
  • Longest substring without repeating characters. A window that grows on the right and shrinks on the left when a repeat appears. Storing each character's last index lets the left edge jump instead of crawl.
  • Smallest subarray with a sum of at least k (positive numbers). Grow until the sum reaches k, then shrink while it still holds, recording the length. Explain why the window fails with negative numbers and what replaces it (prefix sums with a monotonic deque).
  • Count subarrays that sum exactly to k, negatives allowed. Not a window: use a running prefix sum and a hash map of how often each prefix appeared.
def longest_unique(s: str) -> int:
    last_seen = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1      # jump past the earlier copy
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best


print(longest_unique("abcabcbb"), longest_unique("bbbb"), longest_unique("pwwkew"))  # 3 1 3
Sliding window: the length of the longest substring with no repeated character. Each index enters and leaves the window once, so O(n).

Recursion and backtracking

  • What are the two parts of every recursive function? A base case that stops, and a step that moves strictly toward it. Most recursion bugs are a missing base case or a step that does not shrink the problem.
  • Generate all subsets of a set. Either include or skip each element: 2 to the n subsets, each up to n long. Show the choose, explore, unchoose shape.
  • Generate all permutations. Swap or mark-used at each position; n factorial results. Ask whether the input has duplicates, since that needs sorting and a skip rule.
  • Solve N-Queens or a Sudoku. Backtracking with pruning: keep sets of used columns and diagonals so each check is O(1), and stop exploring a branch as soon as it breaks a rule.
  • Combination sum: pick numbers that add to a target, reuse allowed. Recurse with a start index so you never produce the same combination in a different order.
  • When would you turn recursion into iteration? When depth can be large enough to overflow the stack, or when the language lacks tail call optimization (Python and Java both lack it).
def combination_sum(candidates, target):
    candidates = sorted(candidates)
    out, path = [], []

    def walk(start, remaining):
        if remaining == 0:
            out.append(path[:])
            return
        for i in range(start, len(candidates)):
            c = candidates[i]
            if c > remaining:
                break                 # sorted, so nothing later fits either
            path.append(c)            # choose
            walk(i, remaining - c)    # explore (i, not i + 1: reuse allowed)
            path.pop()                # unchoose

    walk(0, target)
    return out


print(combination_sum([2, 3, 6, 7], 7))  # [[2, 2, 3], [7]]
Backtracking: every combination of candidates that sums to the target, each number usable more than once.

Greedy algorithms

Greedy questions and the argument the interviewer wants
QuestionGreedy choiceWhy it is safe (or not)
Pick the most non-overlapping meetings.Sort by end time; take each meeting that starts after the last chosen end.Finishing earliest leaves the most room. An exchange argument shows any optimal schedule can swap in this choice.
Minimum meeting rooms for a list of meetings.Sort starts and ends separately and sweep, or keep a min-heap of end times.The answer is the maximum overlap at any instant.
Can you reach the last index of a jump array?Track the farthest index reachable so far.If the current index is ever beyond the farthest reach, you are stuck.
Make change with the fewest coins.Largest coin first works for some coin systems only.With coins 1, 3 and 4, making 6 greedily gives 4 + 1 + 1, but 3 + 3 is better. That is the cue to switch to dynamic programming.
Assign cookies to children to satisfy the most.Sort both; give each child the smallest cookie that is big enough.Using a larger cookie than needed can only hurt later children.
Greedy questions and the argument the interviewer wants. Scroll sideways on a small screen.

Dynamic programming

Dynamic programming questions frighten people more than they should. The method is the same every time: define what one state means in a sentence, write how a state is built from smaller states, set the base cases, choose the order to fill them, then decide whether you can keep only the last row. Start top-down with memoization if that is easier to reason about, and convert to a table if the interviewer asks about stack depth.

  • How do you know a problem needs dynamic programming? It asks for a count, a minimum or a maximum over choices, and smaller versions of the problem repeat (overlapping subproblems) and combine into the answer (optimal substructure).
  • Memoization or tabulation? Memoization is recursion plus a cache and only visits the states you need. Tabulation fills a table in order, avoids recursion depth limits and makes space optimization easier.
  • Climbing stairs, house robber, decode ways. One-dimensional state: the answer at position i depends on i - 1 and i - 2. Each can run in O(1) space.
  • Longest common subsequence or edit distance. Two-dimensional state over prefixes of both strings, O(m times n). Be ready to rebuild the actual sequence by walking the table backward.
  • 0/1 knapsack. State is items considered and capacity used. Iterating capacity downward in a one-row table stops an item from being used twice.
  • Longest increasing subsequence. O(n squared) with a simple table, O(n log n) with the patience-sorting trick and binary search over tails.
  • Coin change: fewest coins for an amount. State is the amount; each amount tries every coin. This is the fix for the greedy failure in the table above.
def fewest_coins(coins, amount):
    INF = amount + 1
    best = [0] + [INF] * amount          # best[a] = fewest coins that make a
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and best[a - c] + 1 < best[a]:
                best[a] = best[a - c] + 1
    return best[amount] if best[amount] != INF else -1


print(fewest_coins([1, 3, 4], 6))   # 2  (3 + 3, where greedy would use 3 coins)
print(fewest_coins([2], 3))         # -1 (impossible)
Coin change by tabulation: fewest coins for each amount up to the target, O(amount times coins) time and O(amount) space.

Graph traversal

  • BFS or DFS? BFS explores level by level and finds the fewest edges to every node in an unweighted graph. DFS goes deep first and suits cycle detection, connected components, topological order and backtracking-style searches.
  • Count islands in a grid. Treat each land cell as a node with up to four neighbors, start a flood fill from every unvisited land cell, and count the starts. O(rows times columns).
  • Detect a cycle in a directed graph. DFS with three colors (unvisited, on the current path, finished). Meeting a node that is still on the path means a cycle.
  • Course schedule: can every course be finished? Build edges from prerequisite to course and run Kahn's algorithm; if fewer nodes come out than went in, there is a cycle.
  • Why does Dijkstra fail with negative edges? It finalizes a node the first time it is popped, assuming no later path can be cheaper. A negative edge breaks that assumption; Bellman-Ford handles it in O(V times E).
  • Shortest path in a grid where some moves cost 0 and others 1. A 0-1 BFS with a deque: push 0-cost moves to the front and 1-cost moves to the back.
  • Find the minimum spanning tree. Kruskal sorts edges and joins components with union-find; Prim grows a tree from one node with a priority queue.
from collections import deque


def task_order(n, prereqs):
    after = [[] for _ in range(n)]
    indegree = [0] * n
    for before, task in prereqs:          # before must finish first
        after[before].append(task)
        indegree[task] += 1

    ready = deque(i for i in range(n) if indegree[i] == 0)
    order = []
    while ready:
        t = ready.popleft()
        order.append(t)
        for nxt in after[t]:
            indegree[nxt] -= 1
            if indegree[nxt] == 0:
                ready.append(nxt)
    return order if len(order) == n else []


print(task_order(4, [(0, 1), (0, 2), (1, 3), (2, 3)]))  # [0, 1, 2, 3]
print(task_order(2, [(0, 1), (1, 0)]))                  # [] (cycle)
Kahn's algorithm: a valid order of tasks, or an empty list if the prerequisites contain a cycle.

Senior and scenario questions

Questions where the follow-up is the real test
QuestionWhat it testsWhat a strong answer shows
Your O(n log n) solution is too slow for a billion items. What now?Scale thinkingThe data no longer fits in memory: external merge sort in chunks, streaming with bounded memory, or splitting the work across machines.
The input arrives as a stream and you cannot store it.Online algorithmsSingle-pass ideas: running aggregates, a heap of the top k, reservoir sampling for a uniform sample.
How would you test this function?Engineering habitEmpty input, one element, duplicates, all equal, negative numbers, the largest allowed size, and a brute force version to compare against on random inputs.
Your recursive solution crashes on large input.Practical limitsStack depth: convert to an explicit stack or a bottom-up table, and say what the language's default limit roughly is.
Two solutions have the same Big O. How do you choose?JudgmentConstant factors, memory use, cache behavior, readability and how easy each is to get right under time pressure.
Questions where the follow-up is the real test. Scroll sideways on a small screen.

Fictional example

Talking through "minimum number of meeting rooms"
Interviewer
You get a list of meetings as start and end times. How many rooms do you need so none overlap in the same room?
Candidate
Brute force: for every meeting, count how many others overlap its start time and take the maximum. That is O(n squared). The bottleneck is recounting overlaps, so I will keep the active meetings ordered by end time. I sort meetings by start, then keep a min-heap of end times for rooms in use. For each meeting, if the earliest ending room is free by its start, I pop it and reuse it; either way I push the new end time. The heap's largest size is the answer. Sorting is O(n log n) and each heap operation is O(log n), so O(n log n) total and O(n) space. One edge case to confirm: if a meeting ends at 10 and another starts at 10, I treat the room as free, so the check is end less than or equal to start. I will test with no meetings, one meeting, fully nested meetings and back-to-back meetings.

A practice plan for algorithm rounds

  1. Learn the patterns in orderBinary search and two pointers first, then sliding window, recursion and backtracking, BFS and DFS, greedy, and dynamic programming last. Each one leans on the ones before it.
  2. Do a few problems per pattern, then mixFive to eight problems per pattern build recognition. After that, practice from a shuffled list so you have to name the pattern yourself, which is what the real round asks.
  3. Write the brute force firstSay it, state its cost, and name the repeated work. That sentence is usually where the efficient solution comes from.
  4. Trace and test by handBefore saying "done", run a small example through the code line by line and try the edge cases from the table above.
  5. Time yourself and talkAim for a working medium problem in about 25 to 30 minutes while explaining every step aloud. Silence is the most common reason a correct solution still scores poorly.

Algorithm rounds connect to the rest of a technical loop. The software engineer interview questions page shows how coding fits next to design and behavioral rounds, operating system interview questions covers scheduling algorithms such as round robin and shortest job first from the kernel side, and multithreading interview questions is where parallel versions of these problems usually lead.

Practice is where most of the progress happens, and Natively can help there. It is an AI interview assistant for Mac and Windows that reads a coding problem from a screenshot and can suggest a pattern, an approach and its complexity, while transcribing your mock round so you can see afterwards where you went quiet or skipped the brute force. With Pro or the free trial it can also use your résumé and the job description you add. Each session's transcript and notes stay available for review.

Questions people ask

What algorithms should I know for coding interviews?

Binary search, sorting and selection, two pointers, sliding window, recursion and backtracking, greedy algorithms, dynamic programming, BFS and DFS, topological sort and Dijkstra's algorithm. Knowing when each applies matters more than memorizing problems.

How do I recognize which algorithm a problem needs?

Read the constraints and the wording. Sorted input suggests binary search or two pointers, contiguous ranges suggest a sliding window, counting ways or minimum cost suggests dynamic programming, and fewest steps suggests BFS.

How do I answer an algorithm question I have never seen?

Restate it, ask about input size and edge cases, give a brute force with its cost, then remove the repeated work. Interviewers grade that reasoning even when the final code is not perfect.

How long does it take to prepare for algorithm interviews?

It depends on your starting point. A common plan is a few weeks per group of patterns, five to eight problems each, then mixed timed practice while explaining your steps aloud.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP