DSA in Python Interviews Checkpoint
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Put the whole module together: say your approach in order, match the clue to a pattern, solve a tree, graph or DP question, and handle a follow-up. Finish the checkpoint without notes, then pick problems from the Python DSA 150 sheet at /learn/python/dsa-sheet and say your answer aloud.
Say it in order
A strong answer has the same shape every time: restate, brute force with cost, repeated work, better idea, code, test, final cost. Revise: Explaining your approach and its cost (opens in a new tab)
def has_pair(sorted_nums, target): left, right = 0, len(sorted_nums) - 1 while left < right: total = sorted_nums[left] + sorted_nums[right] if total == target: return True if total < target: left += 1 else: right -= 1 return FalseExample 1 · Longest consecutive sequence: brute force, then a set
def longest_brute(nums): # Sort first: O(n log n). best = run = 0 previous = None for value in sorted(set(nums)): run = run + 1 if previous is not None and value == previous + 1 else 1 best = max(best, run) previous = value return best
def longest_set(nums): # O(n): only start counting at the beginning of a run. values = set(nums) best = 0 for value in values: if value - 1 not in values: length = 1 while value + length in values: length += 1 best = max(best, length) return best
nums = [100, 4, 200, 1, 3, 2]print(longest_brute(nums), longest_set(nums))print(longest_brute([]), longest_set([]))4 4 0 0
What this code does
- Sorting works in O(n log n). The set version starts counting only from a value with no smaller neighbour, so each value is visited at most twice: O(n).
- Test the empty list. Say that duplicates are harmless because of the set.
Say: "The list is sorted, so a too-small sum moves the left pointer and a too-big sum moves the right one. Each step discards a value: O(n) time, O(1) space."
Pick the pattern and the tool from the clue
Name the clue first, then the pattern. Revise any of them in the previous lessons. Revise: Common pattern and data structure questions (opens in a new tab)
- Sorted pair: two pointers. Window with a condition: sliding window. Range sums: prefix sums.
- Counting or 'seen before': dict, Counter or set. Top k: heap. Next greater: monotonic stack.
- Fewest edges: BFS. Explore or count regions: DFS with a visited set. Order with prerequisites: topological sort.
- Best value or count with repeated subproblems: DP, with state, base case and transition.
Example 2 · Right side view of a tree, then house robber with O(1) space
class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right
from collections import deque
def right_view(root): view = [] queue = deque([root] if root else []) while queue: view.append(queue[-1].val) for _ in range(len(queue)): node = queue.popleft() for child in (node.left, node.right): if child: queue.append(child) return view
def rob(houses): skip, take = 0, 0 for money in houses: skip, take = max(skip, take), skip + money return max(skip, take)
root = TreeNode(1, TreeNode(2, None, TreeNode(5)), TreeNode(3, None, TreeNode(4)))print(right_view(root))print(rob([2, 7, 9, 3, 1]))[1, 3, 4] 12
What this code does
- The last node in the queue at the start of a level is the rightmost one. This is level order with one extra line, O(n) time.
- House robber needs only the best with and without the previous house, so two variables replace a table: O(n) time, O(1) space.
Follow-ups: say what breaks
For each change in the problem, name the assumption it breaks. Huge input means a stream and a small state. Many queries mean preprocessing. Less memory means in place or two pointers. Revise: Following up on your solution (opens in a new tab)
Example 3 · A follow-up: the same stream, bounded memory
import heapq
def top_two_in_stream(stream): heap = [] for value in stream: heapq.heappush(heap, value) if len(heap) > 2: heapq.heappop(heap) return sorted(heap, reverse=True)
print(top_two_in_stream(iter([4, 9, 1, 7, 3])))[9, 7]
What this code does
- The function accepts any iterator, so it works on a file or generator that cannot be stored. Memory stays at two items.
- If the interviewer says the input is huge, this is the one-sentence answer: time O(n log k), space O(k).
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Print the 1-based positions of the two numbers in the sorted list [2, 7, 11, 15] that add up to 9, using two pointers.
1 2
Exercise 2· Easy
Move all zeros of [0, 1, 0, 3, 12] to the end in place, keeping the order of the others, with a read and a write pointer. Print the list.
[1, 3, 12, 0, 0]
Exercise 3· Easy
Print whether [1, 2, 3, 1] with k = 3, [1, 2, 3, 1, 2, 3] with k = 2 contain two equal values at most k positions apart. Use a dict of last positions.
True False
Exercise 4· Medium
Print the length of the longest run of consecutive integers in [100, 4, 200, 1, 3, 2], and in the empty list, in O(n) with a set.
4 0
Exercise 5· Medium
Print the right side view (the rightmost value of every level) of the tree 1 -> (2, 3) where 2 has a right child 5 and 3 has a right child 4.
[1, 3, 4]
Exercise 6· Medium
Print the 2 most frequent numbers in [1, 1, 1, 2, 2, 3] with a Counter and heapq.nlargest.
[1, 2]
Exercise 7· Hard
Print the most money that can be taken from houses [2, 7, 9, 3, 1] without taking two neighbours, then from [1, 2, 3, 1]. Use O(1) space.
12 4
Exercise 8· Hard
Print the fewest steps from S to E in the grid ["S.#.", "..#E", "...."] where # is a wall and you move up, down, left or right. Print -1 for the grid ["S#E"].
6 -1
Interview questions
Questions interviewers ask on this topic.
What's next
You finished the preview of DSA in Python Interviews
Python Programming has 21 sections, 110 modules and 609 lessons. An account opens every lesson and saves your progress.
Finish up
Mark complete & continue
Next: Mock interview 1: Python basics and an easy problem