Data Structures & Algorithms · Module 13 · Lesson 21 min read

Practice Problems

The problems (try each before reading the code)

  1. Valid anagram (hashing): are two words made of the same letters? → compare Counters. O(n).
  2. Best time to buy and sell stock (one pass / greedy): track the lowest price so far and the best profit. O(n), O(1) space.
  3. Valid parentheses (stack): push openers and match closers. O(n).
  4. Search in a rotated sorted array (binary search): at each step, one half is sorted; check whether the target is in it. O(log n).
  5. Number of islands (BFS/DFS): flood-fill each new piece of land. O(rows × cols).

For each, practise saying

  • the pattern you spotted and why,
  • the brute force and its Big O,
  • the optimised approach and its Big O (time and space),
  • edge cases: empty input, one item, all the same, negatives.

Where to practise next

LeetCode (search "Blind 75" or "NeetCode 150"), HackerRank and Codeforces. Aim for consistency: 2–3 problems a day beats 20 on a weekend.

💡 After solving a problem, look at other solutions; you'll often learn a cleaner trick.

Example

Python
from collections import Counter

def valid_anagram(a, b):
    return Counter(a) == Counter(b)

def max_profit(prices):
    lowest, best = float("inf"), 0
    for p in prices:
        lowest = min(lowest, p)
        best = max(best, p - lowest)
    return best

def valid_parentheses(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

def search_rotated(nums, target):
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if nums[mid] == target:
            return mid
        if nums[lo] <= nums[mid]:                    # left half sorted
            if nums[lo] <= target < nums[mid]:
                hi = mid - 1
            else:
                lo = mid + 1
        else:                                        # right half sorted
            if nums[mid] < target <= nums[hi]:
                lo = mid + 1
            else:
                hi = mid - 1
    return -1

def num_islands(grid):
    rows, cols = len(grid), len(grid[0])
    def sink(r, c):
        if 0 <= r < rows and 0 <= c < cols and grid[r][c] == "1":
            grid[r][c] = "0"
            sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1)
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1":
                count += 1
                sink(r, c)
    return count

print(valid_anagram("listen", "silent"))            # True
print(max_profit([7, 1, 5, 3, 6, 4]))               # 5
print(valid_parentheses("()[]{}"), valid_parentheses("(]"))   # True False
print(search_rotated([4, 5, 6, 7, 0, 1, 2], 0))     # 4
print(num_islands([list("11000"), list("11000"),
                   list("00100"), list("00011")]))  # 3