Coding Interview Examples With Solutions: 20 Real Questions
Coding interview examples with solutions: 20 real problems with approaches, sample code, what weak answers look like, and how to practice for 2026.
Last updated: August 2026
Quick Answer
Coding interviews test your ability to translate a vague problem into a correct, efficient program while explaining your thinking out loud. The twenty examples below cover the patterns that appear in over 80% of real coding interviews: arrays, hash maps, two pointers, sliding window, linked lists, trees, graphs, dynamic programming, and system design components like an LRU cache. Work through each one with pen and paper before reading the solution.
| Pattern | Example Question | Typical Company |
|---|---|---|
| Hash map | Two Sum | Google, Meta, Amazon |
| Stack | Valid Parentheses | Microsoft, Bloomberg |
| Two pointers | Merge Two Sorted Lists | Amazon, Apple |
| Sliding window | Best Time to Buy and Sell Stock | Netflix, Stripe |
| Kadane’s | Maximum Subarray | Google, Meta |
| DP (1D) | Climbing Stairs | Amazon, Atlassian |
| Hash set | Contains Duplicate | Google, Microsoft |
| Binary search | Find Min in Rotated Array | Nvidia, Databricks |
| BFS | Binary Tree Level Order | Amazon, Meta |
| DFS | Number of Islands | Google, Stripe |
| Prefix product | Product of Array Except Self | Meta, Nvidia |
| Heap / bucket | Top K Frequent Elements | Amazon, Databricks |
| Linked list | Linked List Cycle | Microsoft, Apple |
| DP (2D concept) | Word Break | Amazon, Google |
| Sort + merge | Merge Intervals | Google, Meta |
| Graph traversal | Course Schedule | Google, Atlassian |
| Sliding window (string) | Valid Anagram | Amazon, Apple |
| Reverse linked list | Reverse a Linked List | Microsoft, Stripe |
| Binary search | Binary Search | Nvidia, Google |
| Design | LRU Cache | Amazon, Meta, Nvidia |
The Questions, With Sample Answers
1. “Given an array of integers and a target, return the indices of the two numbers that add up to the target.” (Arrays / Hash Map)
Why they ask it. This is the most common opening question in technical interviews. It screens for your ability to move from an O(n2) brute force to an O(n) hash map solution while explaining the trade-off out loud.
Sample answer. Use one pass with a hash map. For each number, compute its complement (target minus the current number) and check whether the complement is already in the map. If it is, return the two indices. If it is not, store the current number and its index.
def two_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
complement = target - n
if complement in seen:
return [seen[complement], i]
seen[n] = i
Time: O(n). Space: O(n). State both without being asked. Follow-up: what if the array is sorted? Use two pointers for O(1) space instead.
What weak answers look like. Nested loops without explaining why O(n2) is too slow, or jumping to the hash map without explaining what the hash map stores.
2. “Given a string of brackets, return true if it is valid.” (Stack)
Why they ask it. Valid Parentheses is the classic stack screening question. It tests whether you reach for the right data structure before writing code.
Sample answer. Push opening brackets onto a stack. When you see a closing bracket, check whether the stack’s top is the matching opener. If the stack is empty or the bracket does not match, return false. Return true if the stack is empty at the end.
def is_valid(s):
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for c in s:
if c in pairs:
if not stack or stack[-1] != pairs[c]:
return False
stack.pop()
else:
stack.append(c)
return not stack
Time: O(n). Space: O(n). Follow-up: what if the input is a stream with no fixed length? Same approach, but the stack grows unboundedly.
What weak answers look like. Counting open and close brackets by type without considering ordering, which passes ]( as valid.
3. “Reverse a linked list.” (Linked List)
Why they ask it. It tests pointer manipulation, which is fundamental for linked-list interviews and shows up as a building block in harder problems.
Sample answer. Iterative approach using three pointers: previous (starts None), current (starts head), and next.
def reverse_list(head):
prev, curr = None, head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev
Time: O(n). Space: O(1). Mention the recursive alternative only if asked; most interviewers prefer the iterative for its O(1) space.
What weak answers look like. Building a new list by prepending nodes (O(n) space) or confusing the pointer order and crashing on the first iteration.
4. “Given a sorted array of integers, find the position of a target value.” (Binary Search)
Why they ask it. Binary search is a template that shows up everywhere: rotated arrays, first/last occurrence, minimum in a rotated array. If you cannot implement it cleanly, harder variants will fall apart.
Sample answer. Maintain lo and hi pointers. At each step, compute mid and compare to target: move lo up if target is to the right, hi down if to the left, return mid if equal.
def binary_search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
Time: O(log n). Space: O(1). Off-by-one errors are the most common bug; use lo <= hi and mid + 1 / mid - 1 to avoid them.
What weak answers look like. Using lo < hi without handling the single-element case, or using mid - 1 and mid + 1 inconsistently and creating an infinite loop.
5. “Find the maximum profit you can make by buying and selling one stock.” (Sliding Window / Single Pass)
Why they ask it. This tests the one-pass sliding window pattern: track a minimum value seen so far and compute the profit at each step.
Sample answer. One pass: track the minimum price seen and the maximum profit so far. At each price, update the minimum if lower, then update the max profit if the current spread is better.
def max_profit(prices):
min_price, max_profit = float('inf'), 0
for p in prices:
min_price = min(min_price, p)
max_profit = max(max_profit, p - min_price)
return max_profit
Time: O(n). Space: O(1). Follow-up: what if you can hold the stock for multiple buy-sell cycles? Add whenever prices[i] > prices[i-1].
What weak answers look like. Nested loops checking every pair (O(n2)), or buying and selling on the same day without checking the logic.
6. “Find the contiguous subarray with the largest sum.” (Kadane’s Algorithm)
Why they ask it. Maximum Subarray is the canonical dynamic programming problem that every engineer should know by heart. It teaches the idea of carrying forward a running state only when it improves the result.
Sample answer. Kadane’s algorithm: maintain a running sum and a global maximum. At each element, decide whether to extend the current subarray or start fresh.
def max_subarray(nums):
curr = best = nums[0]
for n in nums[1:]:
curr = max(n, curr + n)
best = max(best, curr)
return best
Time: O(n). Space: O(1). The follow-up asks for the indices: track start and end of the best subarray using a reset marker.
What weak answers look like. Brute-force O(n3) enumeration, or initializing curr = 0 which breaks on all-negative arrays.
7. “Given an integer n, count the number of distinct ways to climb n stairs taking 1 or 2 steps at a time.” (Dynamic Programming)
Why they ask it. Climbing Stairs is the entry point for DP thinking. The recurrence is Fibonacci; if you recognize the pattern, you can also solve it in O(1) space.
Sample answer. dp[i] = the number of ways to reach step i = dp[i-1] + dp[i-2].
def climb_stairs(n):
if n <= 2:
return n
a, b = 1, 2
for _ in range(3, n + 1):
a, b = b, a + b
return b
Time: O(n). Space: O(1). State the O(n) space DP table approach first, then optimize to O(1) when asked.
What weak answers look like. Building the full DP table and not recognizing that only the last two values are needed; or confusing Fibonacci indexing and returning n+1.
8. “Check if an array contains any duplicates.” (Hash Set)
Why they ask it. It tests the basic pattern of checking membership in constant time using a hash set.
Sample answer. Add each element to a set. If an element is already in the set, return true immediately.
def contains_duplicate(nums):
seen = set()
for n in nums:
if n in seen:
return True
seen.add(n)
return False
Time: O(n). Space: O(n). Mention Python’s alternative: return len(nums) != len(set(nums)). Follow-up: what if the array is sorted? O(n) time, O(1) space using adjacent-pair comparison.
What weak answers look like. Sorting first (O(n log n) when O(n) is available), or using the two-line alternative without being able to explain why it works.
9. “Check if two strings are anagrams.” (Character Frequency)
Why they ask it. Valid Anagram tests counting and comparison. It leads into harder string problems (group anagrams, sliding window anagram).
Sample answer. Compare character frequency maps. If lengths differ, return false immediately.
def is_anagram(s, t):
if len(s) != len(t):
return False
from collections import Counter
return Counter(s) == Counter(t)
Time: O(n). Space: O(1) since the alphabet is bounded. Follow-up: what if the strings contain Unicode? The same Counter approach works; only the constant changes.
What weak answers look like. Sorting both strings (O(n log n) when O(n) is available), or building the map but not handling the case where one string has a character the other does not.
10. “Merge two sorted linked lists into one sorted list.” (Two Pointers / Linked List)
Why they ask it. Merge two sorted lists is a sub-problem of merge sort and a building block for merging k sorted lists, so interviewers use it to see both pointer fluency and the capacity for extension.
Sample answer. Use a sentinel node to simplify edge cases. Advance the pointer in whichever list has the smaller current value.
def merge_two_lists(l1, l2):
dummy = curr = ListNode(0)
while l1 and l2:
if l1.val <= l2.val:
curr.next = l1; l1 = l1.next
else:
curr.next = l2; l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
Time: O(m + n). Space: O(1). Follow-up: merge k sorted lists using a min-heap in O(n log k) time.
What weak answers look like. Recursion without discussing stack depth (O(m + n) stack frames for a long list), or forgetting to attach the remaining tail after one list is exhausted.
11. “Detect whether a linked list has a cycle.” (Floyd’s Two-Pointer)
Why they ask it. It is the canonical use of the slow/fast pointer technique and tests whether you know an O(1) space solution exists.
Sample answer. Slow moves one step, fast moves two. If they meet, there is a cycle.
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
Time: O(n). Space: O(1). Follow-up: find the start of the cycle using a second pointer reset to head after detection; they meet at the cycle entry.
What weak answers look like. Using a hash set to store visited nodes (correct but O(n) space); not knowing that the O(1) solution exists.
12. “Return the level-order traversal of a binary tree.” (BFS)
Why they ask it. Level-order traversal introduces the queue pattern for BFS and is used as a building block for dozens of tree problems.
Sample answer. Use a deque. At each level, process all nodes currently in the queue and enqueue their children.
from collections import deque
def level_order(root):
if not root:
return []
result, queue = [], deque([root])
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
result.append(level)
return result
Time: O(n). Space: O(n). State that the queue holds at most O(w) nodes where w is the maximum tree width.
What weak answers look like. DFS with a depth parameter (harder to read and extend); not tracking level boundaries correctly in the BFS loop.
13. “Count the number of islands in a 2D grid.” (DFS / Flood Fill)
Why they ask it. Number of Islands is the prototypical connected-components problem. It tests DFS (or BFS) traversal on a 2D grid and shows up at Google, Stripe, and many others.
Sample answer. Iterate over every cell. When you find a ‘1’, increment the count and DFS to mark all connected land cells as visited (change to ‘0’).
def num_islands(grid):
count = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == '1':
count += 1
dfs(grid, r, c)
return count
def dfs(g, r, c):
if r < 0 or r >= len(g) or c < 0 or c >= len(g[0]) or g[r][c] != '1':
return
g[r][c] = '0'
for dr, dc in [(1,0),(-1,0),(0,1),(0,-1)]:
dfs(g, r+dr, c+dc)
Time: O(mn). Space: O(mn) stack. Follow-up: what if you cannot mutate the grid? Use a visited set instead of overwriting cells.
What weak answers look like. Mutating the grid without mentioning the side effect; not considering diagonal vs. four-directional connectivity.
14. “Return an array where each element is the product of all other elements, without using division.” (Prefix / Suffix Products)
Why they ask it. Product of Array Except Self tests the prefix-product pattern, which appears in range queries and histogram problems. The “no division” constraint rules out the naive approach and forces the O(n) solution.
Sample answer. Two passes: build a prefix product array left-to-right, then multiply by the suffix product right-to-left.
def product_except_self(nums):
n = len(nums)
out = [1] * n
prefix = 1
for i in range(n):
out[i] = prefix
prefix *= nums[i]
suffix = 1
for i in range(n - 1, -1, -1):
out[i] *= suffix
suffix *= nums[i]
return out
Time: O(n). Space: O(1) output-excluded. State the space complexity carefully: the output array is O(n), but no auxiliary space beyond it is used.
What weak answers look like. Using division (fails on zeros); building a separate suffix array (O(n) auxiliary space unnecessarily).
15. “Find the minimum element in a rotated sorted array.” (Binary Search Variant)
Why they ask it. This tests whether you can adapt binary search to a modified condition, which is a pattern that appears in many Nvidia, Databricks, and Google interview problems.
Sample answer. Compare mid to the right pointer. If nums[mid] > nums[hi], the minimum is in the right half. Otherwise it is in the left half (including mid).
def find_min(nums):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] > nums[hi]:
lo = mid + 1
else:
hi = mid
return nums[lo]
Time: O(log n). Space: O(1). Common follow-up: the array may have duplicates; in that case, worst-case degrades to O(n) if nums[mid] == nums[hi] (decrement hi by one and continue).
What weak answers look like. Linear scan (O(n), misses the point); comparing mid to lo instead of hi, which breaks when the entire array is sorted.
16. “Return the k most frequent elements in an array.” (Heap or Bucket Sort)
Why they ask it. Top K Frequent Elements tests two solutions: a heap in O(n log k) time, and bucket sort in O(n) time. Interviewers often ask for both to see whether you optimize further when prompted.
Sample answer (bucket sort, O(n)). Count frequencies, then use an array of buckets indexed by frequency.
from collections import Counter
def top_k_frequent(nums, k):
count = Counter(nums)
buckets = [[] for _ in range(len(nums) + 1)]
for num, freq in count.items():
buckets[freq].append(num)
result = []
for i in range(len(buckets) - 1, -1, -1):
result.extend(buckets[i])
if len(result) >= k:
return result[:k]
Time: O(n). Space: O(n). Start with the heap approach (cleaner to explain), then offer the bucket sort as the O(n) optimization.
What weak answers look like. Sorting the entire Counter by frequency (O(n log n) when O(n) is available); forgetting that bucket sort requires a bounded frequency domain.
17. “Design a data structure for an LRU Cache with O(1) get and put.” (Design)
Why they ask it. LRU Cache is the most common design component question at Amazon, Meta, and Nvidia. It tests knowledge of combining a hash map with a doubly linked list for O(1) both operations.
Sample answer. Use a hash map (key to node) and a doubly linked list (ordered by recency). On get, move the accessed node to the front. On put, add to the front and evict the tail if over capacity.
class Node:
def __init__(self, key=0, val=0):
self.key, self.val, self.prev, self.next = key, val, None, None
class LRUCache:
def __init__(self, capacity):
self.cap = capacity
self.cache = {}
self.head, self.tail = Node(), Node()
self.head.next, self.tail.prev = self.tail, self.head
def _remove(self, node):
node.prev.next, node.next.prev = node.next, node.prev
def _insert(self, node):
node.next, node.prev = self.head.next, self.head
self.head.next.prev = node
self.head.next = node
def get(self, key):
if key not in self.cache: return -1
self._remove(self.cache[key]); self._insert(self.cache[key])
return self.cache[key].val
def put(self, key, value):
if key in self.cache: self._remove(self.cache[key])
self.cache[key] = Node(key, value); self._insert(self.cache[key])
if len(self.cache) > self.cap:
lru = self.tail.prev
self._remove(lru); del self.cache[lru.key]
Time: O(1) for both. Space: O(capacity). Follow-up: how do you make it thread-safe? Wrap each operation in a lock, or use a concurrent hash map with per-bucket locking for higher throughput.
What weak answers look like. Using an OrderedDict in Python without implementing the underlying structure (passes the coding problem but fails the design intent); not handling the eviction path.
18. “Given a list of intervals, merge all overlapping intervals.” (Sort + Merge)
Why they ask it. Merge Intervals is a standard scheduling and calendar problem that tests your ability to sort by one attribute and then make a linear merge pass.
Sample answer. Sort by start time. Iterate: if the current interval overlaps the last merged one (start of current <= end of last), extend the end. Otherwise, append the current.
def merge(intervals):
intervals.sort(key=lambda x: x[0])
merged = [intervals[0]]
for start, end in intervals[1:]:
if start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return merged
Time: O(n log n) due to sort. Space: O(n) output. Follow-up: insert a new interval into an already-merged list (binary search for position, then merge neighbors).
What weak answers look like. Sorting but then doing an O(n2) comparison scan; or not handling the case where one interval completely contains another.
19. “Given a string and a dictionary, determine if the string can be segmented into valid dictionary words.” (Dynamic Programming)
Why they ask it. Word Break is a classic DP problem that appears at Amazon and Google. It tests whether you recognize the overlapping-subproblem structure and avoid exponential recursion.
Sample answer. dp[i] = true if s[:i] can be segmented. For each position i, check all previous positions j where dp[j] is true and s[j:i] is in the dictionary.
def word_break(s, word_dict):
word_set = set(word_dict)
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in word_set:
dp[i] = True
break
return dp[-1]
Time: O(n2) with hashing. Space: O(n). Optimization: precompute max word length and only check substrings up to that length to reduce the constant factor.
What weak answers look like. Naive recursion without memoization (exponential); building dp backwards when a forward pass is cleaner.
20. “Detect whether you can finish all courses given prerequisites (each as a directed edge).” (Topological Sort / Cycle Detection)
Why they ask it. Course Schedule tests directed graph cycle detection, which underlies build systems, package managers, and task scheduling. It is the entry point for topological sort questions.
Sample answer. Build an adjacency list. Use DFS with a visited set and a “currently visiting” set (gray state). If you reach a node currently in the gray set, there is a cycle.
def can_finish(num_courses, prerequisites):
graph = [[] for _ in range(num_courses)]
for a, b in prerequisites:
graph[b].append(a)
visiting, visited = set(), set()
def dfs(node):
if node in visiting: return False
if node in visited: return True
visiting.add(node)
for nb in graph[node]:
if not dfs(nb): return False
visiting.remove(node)
visited.add(node)
return True
return all(dfs(c) for c in range(num_courses))
Time: O(V + E). Space: O(V + E). Follow-up: return the order if it exists (topological sort via Kahn’s algorithm using in-degree queues).
What weak answers look like. Using only a single visited set (misses back-edges to nodes visited in other DFS trees); not building the adjacency list first and iterating the edge list on every call.
How to Practice These
Before your next interview loop, work through all twenty problems in one sitting without looking at the solution after reading the problem statement. Time yourself: most of these should take 15-25 minutes cleanly, with edge cases and complexity stated.
Use OphyAI Interview Practice for voice or text mock interviews where you narrate your approach before coding: the per-answer feedback surfaces the moments where your explanation was unclear or your complexity analysis was off. For live rounds, use OphyAI Interview Copilot during mock Zoom or Teams sessions to track your answer structure in real time.
Once you can solve all twenty cleanly, extend to the follow-up variants (cyclic array, stream inputs, Unicode strings, thread safety) which are how interviewers distinguish strong from exceptional candidates.
Frequently Asked Questions
What is the most common coding interview question?
Two Sum is the most commonly reported opening problem in technical interviews across all major companies. It is used as a warm-up and screens for the basic hash map pattern. Following that, the most commonly reported problems include Valid Parentheses (stack), Reverse a Linked List, Binary Search, and Maximum Subarray. Most interviewers use a follow-up to see whether you can extend a clean solution rather than starting with a harder problem from scratch.
How hard are coding interview questions at top companies?
Most companies test medium-difficulty problems in their primary coding rounds. Google and Meta are known for medium to hard problems. Amazon focuses on medium-difficulty problems with system design. Nvidia and Databricks skew toward lower-level and performance-oriented variants of medium problems. Entry-level and new-grad interviews at most companies are easy to medium, while senior and staff roles involve medium to hard problems with follow-ups that increase difficulty.
Should I memorize solutions to coding interview questions?
Memorizing solutions produces fragile preparation. Interviewers notice when a candidate produces a perfect solution without being able to explain a line. Learn the patterns (hash map, two pointers, BFS, DP recurrence) rather than the exact code. If you understand the pattern, you can adapt it to any variation the interviewer introduces; if you memorized the code, a single twist will trip you up.
How many coding problems should I practice before an interview?
Research on preparation consistently shows diminishing returns after roughly 100-150 focused problems. The quality of practice matters more than quantity: a problem solved with a timed constraint, spoken explanation, and follow-up reasoning is worth five problems solved by reading the solution. For most candidates, 75-100 problems covering the patterns above, done with active review rather than passive reading, is enough to perform well at medium-difficulty interview loops.
What language should I use in a coding interview?
Python and Java are the most commonly accepted languages and the most frequently chosen by candidates. Python’s concise syntax reduces the time spent on boilerplate, which matters when you are coding live under pressure. C++ is preferred or required by Nvidia, some systems roles at Google, and hardware teams across the industry. Use the language you know most deeply; a fluent Python solution beats a C++ attempt where you are fighting syntax while also solving the problem.
How do I stop going blank during coding interviews?
Going blank almost always signals that you are trying to solve the whole problem at once. Start by restating the problem in your own words, asking one or two clarifying questions about edge cases and constraints, then choosing the brute-force solution before optimizing. Speaking the brute force aloud gives your brain a starting point and often reveals the optimization naturally. Practice in OphyAI Interview Practice with voice mode on so that talking while thinking becomes automatic before the real interview.
Related Guides
These company interview guides all have significant coding rounds where the patterns above appear directly:
- Google interview guide
- Amazon interview guide
- Meta (Facebook) interview guide
- Microsoft interview guide
- Nvidia interview guide
- Stripe interview guide
- Databricks interview guide
Sources and verification notes
Sources checked August 2026. The twenty problems above are among the most frequently reported interview questions in candidate-reported accounts, practice guides, and competitive programming communities as of 2025 to 2026.
- LeetCode: the primary source for problem descriptions and editorial solutions. Problem titles, constraints, and common variants are drawn from the platform. Checked August 2026.
- NeetCode: curated list of the 150 most important interview patterns; the twenty problems above are drawn from this roadmap’s core patterns. Checked August 2026.
- Tech Interview Handbook: grind-75 and grind-169 problem lists; difficulty ratings and company attributions. Checked August 2026.
- Candidate reports from Glassdoor and Blind (August 2026): frequency of specific questions at specific companies, used to populate the “Typical Company” column in the quick-reference table.
Tags:
Share this article:
Turn the advice into a realistic practice session
Run a role-specific mock interview, review feedback across four scoring areas, and repeat the answers that need work.
Related Articles
HireVue Video Interview Preparation: Complete Guide for 2026
Interview Tips
Everything you need to know about HireVue interviews: how they work, how HireVue scores responses, what to wear, eye contact with the camera, common question types, companies using HireVue, and how to practice effectively.
Read more →
How to Use LinkedIn to Prepare for an Interview (Step-by-Step for 2026)
Interview Tips
A concrete LinkedIn research workflow for interview prep: how to study your interviewer's profile, find talking points in their posts, map the team, and walk in with insider knowledge.
Read more →
Phone Screening Interview Preparation Guide 2026
Interview Tips
Master the phone and video screening interview: what to expect, how to prepare for recruiter screens, hiring manager screens, and technical screens, and how to send the signals that move you to the next round.
Read more →