Skip to content
Streak:0Loading your progress…Sign in

Module 3 · Lesson 2 of 2

Sliding window, stacks & binary search

Three more patterns that cover a large share of coding screens. ~40 min

Lesson notes

Sliding window: for "longest/shortest substring/subarray such that…" keep a window [left, right], expand right, and shrink left while the window is invalid.

Stack: for matching brackets, undo, "next greater element". Python lists are stacks: append() and pop() are O(1).

Binary search template — halve the search space each step, O(log n)
def bisect_left(xs, target):
    lo, hi = 0, len(xs)
    while lo < hi:
        mid = (lo + hi) // 2
        if xs[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

Practice

  1. 1. Longest substring without repeats

    medium25 XP

    Return the length of the longest substring of s with no repeated characters. O(n) please.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor

  2. 2. Valid brackets

    easy10 XP

    Write is_valid(s) returning True if every (, [, { is closed by the matching bracket in the right order. Other characters are ignored.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor

  3. 3. Search a rotated sorted array

    hard50 XP

    A sorted list of unique ints was rotated (e.g. [4,5,6,7,0,1,2]). Return the index of target or -1, in O(log n).

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor