TExcelTAD
Home › Data Structures & Algorithms › DSA Exercises

DSA Exercises

Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" line. Try for a few minutes before opening the solution.

# Exercise Topics
1 Second largest arrays, one pass
2 Sort by insertion insertion sort
3 First and last position binary search
4 Reverse a linked list linked lists
5 Valid brackets stacks
6 First unique character hash maps
7 Tree height and sum binary trees, recursion
8 Islands on a map graph traversal (BFS/DFS)
9 Cheapest flight Dijkstra
10 Minimum path sum dynamic programming

1. Second largest

Write second_largest(values) that returns the second largest distinct value in one pass, without sorting. Return None if there isn't one.

Expected: second_largest([12, 45, 2, 41, 45]) == 41, second_largest([7, 7]) is None.

python · try it yourself
def second_largest(values):
    # TODO: track the largest and second largest values in one loop
    return None

print(second_largest([12, 45, 2, 41, 45]))
print(second_largest([7, 7]))
None
None
Show solution
python
def second_largest(values):
    first = second = None
    for v in values:
        if first is None or v > first:
            first, second = v, first
        elif v != first and (second is None or v > second):
            second = v
    return second

print(second_largest([12, 45, 2, 41, 45]))   # 41
print(second_largest([7, 7]))                # None

2. Sort by insertion

Implement insertion sort that sorts in descending order and counts how many values were shifted.

Expected: ([9, 7, 5, 3, 1], 7) for [3, 1, 9, 5, 7]. The number of shifts equals the number of pairs that are in ascending order (wrong for a descending sort).

python · try it yourself
def insertion_sort_desc(arr):
    shifts = 0
    # TODO: insertion sort with the comparison reversed; count the shifts
    return arr, shifts

print(insertion_sort_desc([3, 1, 9, 5, 7]))
([3, 1, 9, 5, 7], 0)
Show solution
python
def insertion_sort_desc(arr):
    shifts = 0
    for i in range(1, len(arr)):
        key, j = arr[i], i - 1
        while j >= 0 and arr[j] < key:     # < instead of > gives descending order
            arr[j + 1] = arr[j]
            shifts += 1
            j -= 1
        arr[j + 1] = key
    return arr, shifts

print(insertion_sort_desc([3, 1, 9, 5, 7]))   # ([9, 7, 5, 3, 1], 7)

3. First and last position

In a sorted list, find the first and the last index of target with two binary searches (O(log n)), or (-1, -1) if it is missing.

Expected: (2, 5) for target 8 in [1, 4, 8, 8, 8, 8, 10, 12].

python · try it yourself
def find_range(arr, target):
    # TODO: one binary search for the leftmost position, one for the rightmost
    return (-1, -1)

data = [1, 4, 8, 8, 8, 8, 10, 12]
print(find_range(data, 8))
print(find_range(data, 5))
(-1, -1)
(-1, -1)
Show solution
python
def bound(arr, target, leftmost):
    lo, hi, found = 0, len(arr) - 1, -1
    while lo <= hi:
        mid = (lo + hi) // 2
        if arr[mid] == target:
            found = mid
            if leftmost: hi = mid - 1      # keep looking left
            else:        lo = mid + 1      # keep looking right
        elif arr[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return found

def find_range(arr, target):
    return bound(arr, target, True), bound(arr, target, False)

data = [1, 4, 8, 8, 8, 8, 10, 12]
print(find_range(data, 8))   # (2, 5)
print(find_range(data, 5))   # (-1, -1)

4. Reverse a linked list

Complete reverse(head) so it reverses the list in place and returns the new head.

Expected: 4 -> 3 -> 2 -> 1.

python · try it yourself
class Node:
    def __init__(self, value, next=None):
        self.value, self.next = value, next

def reverse(head):
    # TODO: turn every next pointer around
    return head

def show(head):
    out = []
    while head:
        out.append(str(head.value))
        head = head.next
    return " -> ".join(out)

print(show(reverse(Node(1, Node(2, Node(3, Node(4)))))))
1 -> 2 -> 3 -> 4
Show solution
python
def reverse(head):
    prev = None
    while head:
        head.next, prev, head = prev, head, head.next
    return prev

5. Valid brackets

Return the index of the first bracket that makes the text unbalanced, or -1 if it is balanced. For an unclosed opening bracket, return its index.

Expected: -1 for "f(a[1], {b})", 2 for "(a]" (the ] doesn't match the () and 0 for "(()" (the first ( is never closed).

python · try it yourself
PAIRS = {")": "(", "]": "[", "}": "{"}

def first_error(text):
    # TODO: push (char, index) of openers on a stack
    return -1

for t in ["f(a[1], {b})", "(a]", "(()"]:
    print(t, first_error(t))
f(a[1], {b}) -1
(a] -1
(() -1
Show solution
python
def first_error(text):
    stack = []
    for i, ch in enumerate(text):
        if ch in "([{":
            stack.append((ch, i))
        elif ch in PAIRS:
            if not stack or stack[-1][0] != PAIRS[ch]:
                return i
            stack.pop()
    return stack[0][1] if stack else -1

# f(a[1], {b}) -1,  (a] 2,  (() 0

6. First unique character

Return the first character that occurs exactly once in a string, using a hash map (two passes, O(n)). Return None if there is none.

Expected: "j" for "javascript", None for "aabbcc" and "w" for "swiss".

python · try it yourself
def first_unique(text):
    # TODO: count characters, then scan again
    return None

for word in ["javascript", "aabbcc", "swiss"]:
    print(word, first_unique(word))
javascript None
aabbcc None
swiss None
Show solution
python
from collections import Counter

def first_unique(text):
    counts = Counter(text)
    for ch in text:
        if counts[ch] == 1:
            return ch
    return None

# javascript j,  aabbcc None,  swiss w

7. Tree height and sum

Write recursive height(node) (a single node has height 0, an empty tree -1) and total(node) (sum of all values).

Expected: height 3, total 140 for the tree below.

python · try it yourself
class Node:
    def __init__(self, value, left=None, right=None):
        self.value, self.left, self.right = value, left, right

root = Node(40, Node(22, Node(15), Node(30, Node(27))), Node(6))

def height(node):
    return 0   # TODO

def total(node):
    return 0   # TODO

print("height", height(root), "total", total(root))
height 0 total 0
Show solution
python
def height(node):
    return -1 if node is None else 1 + max(height(node.left), height(node.right))

def total(node):
    return 0 if node is None else node.value + total(node.left) + total(node.right)

8. Islands on a map

Count the islands (groups of # cells connected up, down, left or right) on a map, using BFS or DFS from every unvisited land cell.

Expected: 3.

python · try it yourself
world = [
    "##..#",
    "#...#",
    "..#..",
    ".###.",
]

def count_islands(grid):
    # TODO: for each unvisited "#", flood-fill its island and count it
    return 0

print(count_islands(world))
0
Show solution
python
def count_islands(grid):
    rows, cols = len(grid), len(grid[0])
    seen, islands = set(), 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "#" and (r, c) not in seen:
                islands += 1
                stack = [(r, c)]
                seen.add((r, c))
                while stack:
                    y, x = stack.pop()
                    for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                        if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == "#" and (ny, nx) not in seen:
                            seen.add((ny, nx))
                            stack.append((ny, nx))
    return islands

9. Cheapest flight

Flights are directed edges with prices. Use Dijkstra's algorithm with heapq to return the cheapest price and route from src to dst.

Expected: (330, ['LIS', 'MAD', 'PAR', 'BER']).

python · try it yourself
import heapq

flights = {
    "LIS": {"MAD": 60, "PAR": 210},
    "MAD": {"PAR": 90, "BER": 320},
    "PAR": {"BER": 180},
    "BER": {},
}

def cheapest(graph, src, dst):
    # TODO: Dijkstra with a heap of (price, city, route)
    return None

print(cheapest(flights, "LIS", "BER"))
None
Show solution
python
def cheapest(graph, src, dst):
    heap, done = [(0, src, [src])], set()
    while heap:
        price, city, route = heapq.heappop(heap)
        if city == dst:
            return price, route
        if city in done:
            continue
        done.add(city)
        for nxt, p in graph[city].items():
            if nxt not in done:
                heapq.heappush(heap, (price + p, nxt, route + [nxt]))
    return None

10. Minimum path sum

A robot moves from the top-left to the bottom-right of a grid, only right or down, paying the number in each cell it enters (including the start). Find the cheapest total with tabulation.

Expected: 7 (path 1 → 3 → 1 → 1 → 1).

python · try it yourself
grid = [
    [1, 3, 1],
    [1, 5, 1],
    [4, 2, 1],
]

def min_path_sum(grid):
    # TODO: best[r][c] = grid[r][c] + min(best from above, best from the left)
    return 0

print(min_path_sum(grid))
0
Show solution
python
def min_path_sum(grid):
    rows, cols = len(grid), len(grid[0])
    best = [[0] * cols for _ in range(rows)]
    for r in range(rows):
        for c in range(cols):
            if r == 0 and c == 0:
                best[r][c] = grid[0][0]
            else:
                up = best[r - 1][c] if r > 0 else float("inf")
                left = best[r][c - 1] if c > 0 else float("inf")
                best[r][c] = grid[r][c] + min(up, left)
    return best[-1][-1]

print(min_path_sum(grid))   # 7

Check your solutions together

This playground runs all reference solutions at once, so you can compare with your own results:

python · try it yourself
import heapq
from collections import Counter

def second_largest(values):
    first = second = None
    for v in values:
        if first is None or v > first:
            first, second = v, first
        elif v != first and (second is None or v > second):
            second = v
    return second

def first_unique(text):
    counts = Counter(text)
    return next((ch for ch in text if counts[ch] == 1), None)

def count_islands(grid):
    rows, cols = len(grid), len(grid[0])
    seen, islands = set(), 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "#" and (r, c) not in seen:
                islands += 1
                stack = [(r, c)]
                seen.add((r, c))
                while stack:
                    y, x = stack.pop()
                    for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                        if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == "#" and (ny, nx) not in seen:
                            seen.add((ny, nx))
                            stack.append((ny, nx))
    return islands

def cheapest(graph, src, dst):
    heap, done = [(0, src, [src])], set()
    while heap:
        price, city, route = heapq.heappop(heap)
        if city == dst:
            return price, route
        if city in done:
            continue
        done.add(city)
        for nxt, p in graph[city].items():
            if nxt not in done:
                heapq.heappush(heap, (price + p, nxt, route + [nxt]))

def min_path_sum(grid):
    rows, cols = len(grid), len(grid[0])
    best = [[0] * cols for _ in range(rows)]
    for r in range(rows):
        for c in range(cols):
            if r == 0 and c == 0:
                best[r][c] = grid[0][0]
            else:
                up = best[r - 1][c] if r > 0 else float("inf")
                left = best[r][c - 1] if c > 0 else float("inf")
                best[r][c] = grid[r][c] + min(up, left)
    return best[-1][-1]

print(1, second_largest([12, 45, 2, 41, 45]), second_largest([7, 7]))
print(6, [first_unique(w) for w in ["javascript", "aabbcc", "swiss"]])
print(8, count_islands(["##..#", "#...#", "..#..", ".###."]))
flights = {"LIS": {"MAD": 60, "PAR": 210}, "MAD": {"PAR": 90, "BER": 320}, "PAR": {"BER": 180}, "BER": {}}
print(9, cheapest(flights, "LIS", "BER"))
print(10, min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))
1 41 None
6 ['j', None, 'w']
8 3
9 (330, ['LIS', 'MAD', 'PAR', 'BER'])
10 7

Test yourself

Which data structure is the natural fit for checking balanced brackets?

  1. Queue
  2. Stack
  3. Hash set
  4. Heap

Counting islands on a grid is an example of which algorithm?

  1. Binary search
  2. Connected components with BFS/DFS
  3. Sorting
  4. Dynamic programming