Coding Interview Examples With Solutions and Complexity

The coding interview examples that appear most often are Two Sum, Valid Parentheses, Reverse Linked List, Merge Sorted Lists, LRU Cache, Word Ladder and Longest Substring Without Repeating Characters. This guide walks through each one: what the problem asks, the approach interviewers expect, the time and space complexity, and how to talk through it. Code is in Python, but the reasoning carries over to any language.
TL;DR
- Most coding interviews draw on a small core of data structures: arrays, hash tables, linked lists, stacks, queues, trees, heaps and graphs.
- Each example below pairs a problem with one pattern: hash map, pointers, stack, sliding window, breadth-first search or a hash map combined with a linked list.
- State a simple solution first, then improve it and name the trade-off between time and space.
- Explaining your reasoning, edge cases and complexity matters as much as the final code.
- Practise ten problems well rather than hundreds superficially.
Table of Contents
- Which coding interview examples are worth practising
- Example 1: Two Sum
- Example 2: Valid Parentheses
- Example 3: Reverse a linked list
- Example 4: Merge two sorted lists
- Example 5: LRU Cache
- Example 6: Longest substring without repeating characters
- Example 7: Word Ladder
- Example 8: Fibonacci and the cost of recursion
- How the data structure changes the problem
- How to explain your solution in the interview
- A practice plan that fits around a job
- Our perspective: preparation needs applications to prepare for
- Let Appliqu handle the applications while you practise
- FAQ
- Sources
Which coding interview examples are worth practising
Public problem banks are large. LeetCode's problem list numbers Two Sum as problem 1 (Easy), Longest Substring Without Repeating Characters as problem 3 (Medium), Valid Parentheses as problem 20 and Merge k Sorted Lists as problem 23 (Hard). A book such as Elements of Programming Interviews covers 300 problems across primitive types, arrays, strings, linked lists, stacks, queues, binary trees, heaps, searching, hash tables, sorting, graphs and design.
That volume is not what you need. Crackr's 2026 guide groups 47 common problems into ten families: arrays and hashing, two pointers, sliding window, stacks, binary search, linked lists, trees, dynamic programming, graphs, and intervals or greedy. Learn one representative problem per family and you can recognise most variations.
The ten examples below are chosen for that reason.
| Example | Pattern | Typical time | Typical space |
|---|---|---|---|
| Two Sum | Hash map | O(n) | O(n) |
| Valid Parentheses | Stack | O(n) | O(n) |
| Reverse a linked list | Pointer rewiring | O(n) | O(1) |
| Merge two sorted lists | Two pointers | O(n + m) | O(1) |
| LRU Cache | Hash map plus doubly linked list | O(1) per operation | O(n) |
| Longest substring without repeats | Sliding window | O(n) | O(k) |
| Word Ladder | Breadth-first search | See below | O(N) |
| Fibonacci | Recursion, memoisation, iteration | O(n) | O(1) |
Here n is the input size, m the length of the second list, k the size of the character set and N the number of words.
Example 1: Two Sum
The task: given an array of numbers and a target, return the positions of the two numbers that add up to the target.
Brute force: check every pair. According to Built In's explanation, this takes O(n²) time and O(1) extra space.
Better: scan the array once and keep a hash map from each value seen to its index. For each number, check whether the target minus that number is already in the map. If it is, return both indices. This takes O(n) time and O(n) space.
def two_sum(nums, target): seen = {} for i, value in enumerate(nums): need = target - value if need in seen: return [seen[need], i] seen[value] = i return []
Check the complement before inserting the current value. Otherwise an element can pair with itself, which fails for input such as [3, 2, 4] with target 6.
Say aloud: "The brute force is quadratic. I can trade memory for speed with a hash map." That sentence is the trade-off interviewers listen for.
Example 2: Valid Parentheses
The task: given a string of brackets, braces and parentheses, decide whether each opener is closed by the right closer in the right order.
Approach: push every opener onto a stack. When a closer arrives, the top of the stack must be its matching opener, otherwise the string is invalid. At the end, the stack must be empty. Interview Cake lists bracket validation among its standard challenges.
def is_valid(s): pairs = {')': '(', ']': '[', '}': '{'} stack = [] for ch in s: if ch in pairs: if not stack or stack.pop() != pairs[ch]: return False else: stack.append(ch) return not stack
Time is O(n) and space is O(n) in the worst case, for example a string made only of openers.
Edge cases to test: the empty string, a single closer, "([)]" (balanced counts, wrong order) and "((" (openers left over).
Example 3: Reverse a linked list
The task: reverse a singly linked list in place and return the new head. HackerRank's version of the challenge states that the head may be null.
Approach: walk the list with three references (previous, current, next). At each node, save the next node, point the current node backwards, then advance. Interview Cake describes this as O(n) time and O(1) space, because only the pointers change.
def reverse(head): prev = None while head: nxt = head.next head.next = prev prev = head head = nxt return prev
Linked-list problems reward careful pointer handling. Draw three nodes on paper or a whiteboard and trace the loop before you declare it finished. The same fast and slow pointer idea extends to cycle detection and finding the middle node.
Example 4: Merge two sorted lists
The task: combine two sorted linked lists into one sorted list.
Approach: keep a pointer to the end of the result. Repeatedly attach the smaller of the two current nodes. When one list runs out, attach the remainder of the other. Because you rewire existing nodes instead of creating new ones, the extra space is O(1) and the time is O(n + m).
def merge(a, b): dummy = tail = ListNode(0) while a and b: if a.val <= b.val: tail.next, a = a, a.next else: tail.next, b = b, b.next tail = tail.next tail.next = a or b return dummy.next
The dummy head removes the special case of an empty result. It is a small habit that keeps code short and reads well to an interviewer. The harder variant, Merge k Sorted Lists, keeps the current head of each list in a min-heap.
Example 5: LRU Cache
The task: design a cache with a fixed capacity. get(key) and put(key, value) must both be fast, and when the cache is full the least recently used entry is evicted.
Approach: combine two structures. A hash map gives fast lookup from key to node. A doubly linked list keeps entries in order of use, most recent at the front. Interview Cake's walkthrough describes it this way: every access moves the entry to the most recently used position, and eviction removes the entry at the other end. Each operation takes O(1) on average, and space is O(n), where n is the capacity.
In Python you can show the idea with OrderedDict, then offer to write the linked list by hand if the interviewer asks:
from collections import OrderedDict class LRUCache: def __init__(self, capacity): self.cap = capacity self.data = OrderedDict() def get(self, key): if key not in self.data: return -1 self.data.move_to_end(key) return self.data[key] def put(self, key, value): self.data[key] = value self.data.move_to_end(key) if len(self.data) > self.cap: self.data.popitem(last=False)
The lesson reaches beyond caches: when one structure gives fast lookup and another gives cheap ordered updates, combine them.
Example 6: Longest substring without repeating characters
The task: given a string, return the length of the longest substring in which no character appears twice. For "abcabcbb" the answer is 3.
Brute force: start at every index and extend until a repeat appears. GeeksforGeeks gives this as the naive approach with O(n²) time.
Sliding window: keep a window with two ends and a map from each character to its last seen position. When the next character already sits inside the window, move the left end just past its previous position. Each character is visited a constant number of times, so time is O(n).
def longest_unique(s): last = {} start = best = 0 for i, ch in enumerate(s): if ch in last and last[ch] >= start: start = last[ch] + 1 last[ch] = i best = max(best, i - start + 1) return best
The condition last[ch] >= start is the usual bug. Without it, a character seen long before the window began wrongly shrinks the window.
Example 7: Word Ladder
The task: given a start word, an end word and a list of valid words, find the length of the shortest chain in which each step changes exactly one letter and every word is in the list.
Approach: treat words as nodes in a graph, with an edge between words that differ by one letter. Breadth-first search explores level by level, so the first time it reaches the end word, the chain is the shortest. One worked solution, published by Talent D, builds the graph explicitly in O(N² × L) time, then shows the usual improvement: generate neighbours on the fly by trying each letter in each position, which runs in about O(N × L × 26) time. Here N is the number of words and L is their length.
from collections import deque def ladder_length(begin, end, words): words = set(words) if end not in words: return 0 queue = deque([(begin, 1)]) while queue: word, steps = queue.popleft() if word == end: return steps for i in range(len(word)): for c in 'abcdefghijklmnopqrstuvwxyz': nxt = word[:i] + c + word[i + 1:] if nxt in words: words.remove(nxt) queue.append((nxt, steps + 1)) return 0
Removing a word from the set when you first reach it doubles as the visited check. Mention that choice out loud.
The skill being tested is recognition: a problem about transformations and shortest paths is a graph problem, even when no graph is drawn.

Example 8: Fibonacci and the cost of recursion
The task: return the n-th Fibonacci number.
This problem shows how one question can be answered at three levels. Naive recursion recomputes the same values and grows exponentially. Memoisation stores results and cuts time to O(n) with O(n) space. A loop that keeps only the last two values is O(n) time and O(1) space.

def fib(n): a, b = 0, 1 for _ in range(n): a, b = b, a + b return a
Interviewers often use it as a warm-up for dynamic programming: coin change, climbing stairs and edit distance rest on the same idea of reusing sub-results.
How the data structure changes the problem
The examples above differ less in difficulty than in what they test.
- Linked lists test pointer manipulation, often with O(1) space techniques such as reversal or fast and slow pointers.
- Stacks and queues test last-in-first-out and first-in-first-out thinking. Valid Parentheses is the classic stack case.
- Heaps keep a minimum or maximum ready, which suits top-K and merge-k problems.
- Hash tables turn repeated scans into constant-time lookups, at the cost of memory.
Interview Cake's overview of data structures lists the same core set: arrays, hash tables, linked lists, stacks and queues, trees, heaps and graphs. Difficulty rises when a problem forces you to combine structures, as LRU Cache does, or to optimise space as well as time.
How to explain your solution in the interview
A correct answer delivered in silence scores worse than a nearly correct answer explained well. Educative's interview guide describes a sequence that works for any problem:
- Restate the task and confirm inputs, outputs and constraints.
- Describe a simple approach first, even if it is slow.
- Improve it and name what you trade away.
- Test examples and edge cases: empty input, one element, duplicates, very large values.
- State time and space complexity and say what you would change under different constraints.
The same guide asks for sensible names, manageable functions and clear control flow. For complexity, Educative's course material defines time complexity as how runtime grows with input size and space complexity as the memory used beyond the input. It also shows the standard trade-off: replacing repeated scans with a hash table can turn O(n²) time and O(1) space into O(n) time and O(n) space. Two Sum is that sentence in practice.
A practice plan that fits around a job
- Pick one example per pattern from the table above.
- Solve it without hints for 25 minutes, then compare with a reference solution.
- Re-solve it from memory two days later.
- Say the explanation aloud, including complexity, as if an interviewer were present.
- Add variations: sorted Two Sum, 3Sum, cycle detection, Merge k Sorted Lists.
Technical rounds are one stage of a longer process. The questions that come before and after them are covered in our guide to 20 interview questions you will be asked.
Our perspective: preparation needs applications to prepare for
We see two failure modes among people preparing for technical interviews. Some practise problems for months and apply to very few roles. Others send dozens of generic applications and arrive at interviews unprepared for the specific role. Both leave the most useful preparation signal unused: a real job posting tells you which languages, systems and seniority level to practise for.
We think the sensible order is to decide on a focused set of roles, read what each one asks for, and practise the patterns those postings imply. Our article on a market driven job search describes why a small number of well-matched applications serves you better than a large number of loose ones.
The hours spent on searching, rewriting a CV and drafting cover letters are hours not spent on Two Sum and graph search. Appliqu takes that work over, so your evenings go to preparation. Every application stays individual, and you choose how much control you keep.
Niclas Fischell
Let Appliqu handle the applications while you practise
Appliqu searches more than 1.5 million jobs from over 500 sources, including company career pages, and scores every role against your profile. It writes a tailored cover letter for each role, adapts your CV and applies in the employer's own application form. It also connects to your inbox, detects replies and interview invitations and keeps every application in one place.
You choose the mode: in approval mode you approve each application yourself, and on Autopilot Appliqu applies on its own. The Explorer plan is free forever and Appliqu writes 5 applications there. Sending applications starts with Core at €29.90 per month for 100 applications. Pro is €69.90 per month for 300 applications plus the Appliqu Job Board, and Concierge is €199.00 per month with unlimited applications and a senior consultant session.

See the plans and prices on Appliqu and start with Explorer. If you want to see what a tailored letter looks like first, the cover letter examples with the job ad show three full ones.
FAQ
How many coding interview examples should I practise?
Quality matters more than count. Covering one or two problems per pattern (hash map, two pointers, sliding window, stack, linked list, tree, graph, dynamic programming) prepares you for most variations. Re-solving a problem from memory teaches more than reading ten new solutions.
Do I need to know Big O notation for a coding interview?
Yes. Interviewers routinely ask for the time and space complexity of your solution, and for how it changes if the input grows. You should be able to explain why a nested loop is O(n²), why a hash table can reduce it to O(n), and what memory that costs.
Which programming language should I use?
Use the language you are most fluent in, unless the job posting requires a specific one. Python and Java are common choices because their standard libraries include hash maps, queues and heaps. Fluency with your chosen language's built-in structures saves time during the interview.
What if I cannot find the optimal solution?
Say so and deliver the working solution first. State the brute force, give its complexity, and describe the direction you would take to improve it. A clear, correct, slower answer with honest reasoning usually serves you better than a half-finished optimal one.
Sources
- Problems, LeetCode
- Elements of Programming Interviews, ACM Digital Library
- 47 Coding Interview Examples With Solutions, Crackr
- How to Solve the Two-Sum Problem, Built In
- All Coding Interview Questions and Topics, Interview Cake
- Reverse a linked list, HackerRank
- LRU Cache Data Structure and Implementation, Interview Cake
- Longest Substring Without Repeating Characters, GeeksforGeeks
- Word Ladder solution and explanation, Talent D
- Data Structures for Coding Interviews, Interview Cake
- Google DeepMind Software Engineer interview guide, Educative
- Algorithm Analysis for Coding Interviews, Educative