Jc-alt logo
jc
LeetCode: Design

LeetCode: Design

··
122 min read
·data structures and algorithms

Design Intro:

What Is It

Design problems ask you to build a small class where every method has a target time complexity. The class is almost never one data structure, it is usually 1 or 2 data structures that each cover one weakness of the other.

The fastest way to solve one is to work backwards from the operations:

  1. Which operation must be O(1) or O(log n)?
  2. Do I need order (oldest, newest, smallest, most frequent)?
  3. Do I need lookup by key, by index, or by value?
  4. Whatever one structure can't do, which second structure covers it?

Quick Pick: Need -> Structure

I need...Reach forWhy
Lookup / exists / count by keyHashmap / HashsetO(1) average get, put, delete
Lookup by small fixed integer indexArrayDirect O(1) index, no hashing (carType 1,2,3 -> slots[0,1,2])
Newest first, undo, "most recent"StackLIFO, O(1) push and pop at the top
Oldest first, process in arrival orderQueue / DequeFIFO, O(1) at both ends with a deque
Smallest / largest / top k, changing over timeHeapO(log n) push and pop, O(1) peek at the min or max
Insert or delete in the middle, given the nodeDoubly Linked ListO(1) rewire using prev and next
Insert or delete at the headSingly Linked ListO(1), no shifting like an array
Recency order + O(1) lookupHashmap + Doubly Linked ListMap finds the node, list reorders it (LRU style)
Recency order + O(1) lookup, less codeOrderedDictHashmap + doubly linked list built in, popitem(last=False)
Fixed capacity that wraps aroundArray as a ring bufferhead + size, modulo capacity
Running min / max / count while pushingExtra value stored with each itemStore a tuple (val, min so far) so pop is free
Win check without storing the boardCountersOne signed counter per line instead of scanning

Data Structure Breakdown

Hashmap / Hashset

  • Use when: you need to find, count, or dedupe by key in O(1)
  • Signals: "exists", "already seen", "how many times", "map X to Y", "duplicate"
  • Watch out: no order, and not safe to mutate while iterating
  • Variations:
    • Frequency map: value -> count
    • Reverse map: a second hashmap going the other direction (url -> code)
    • Pattern map: a key built from the data (wildcard "h*llo" -> count)
    • Group map: key -> list / stack / OrderedDict (frequency -> stack of values)
  • Problems in this section:
ProblemHow the hashmap is used
170. Two Sum IIIvalue -> count, look up complement (value - num)
535. TinyURLcode -> url to decode, url -> code to catch duplicates
676. Magic Dictionarywildcard pattern -> count of words that make it
705 / 706. HashSet / HashMapbuckets of chains, key % size picks the bucket
895. Max Frequency Stackval -> freq, and freq -> stack of vals
460. LFU Cachekey -> val, key -> freq, freq -> OrderedDict of keys
432. All O(1)key -> the bucket node it currently lives in
353. Snake Gameset of occupied cells for O(1) self collision

Array

  • Use when: indices are small, fixed, and known, or you need random access
  • Signals: "fixed number of types", "k slots", "index", "shuffle", "swap positions"
  • Watch out: insert or delete in the middle is O(n) because everything shifts
  • Problems in this section:
ProblemHow the array is used
1603. Parking Systemslots[carType - 1], direct index beats branching
384. Shuffle an ArrayFisher Yates, swap nums[i] with random j in [i, n - 1]
622. Circular Queuefixed array reused as a ring, (head + size) % k
348. Tic Tac Toerows[] and cols[] counters, one per line

Stack (LIFO)

  • Use when: the newest item must come out first, or you need to remember state to restore it
  • Signals: "undo", "top", "most recent", "nested", "matching", "backtrack"
  • Watch out: only the top is accessible, anything deeper needs popping
  • Trick: store extra state alongside each item so a pop restores it for free
  • Problems in this section:
ProblemHow the stack is used
155. Min Stackpush (val, min so far), pop automatically restores the old min
895. Max Frequency Stackone stack per frequency, ties broken by recency for free
232. Queue using Stacksin stack + out stack, transfer only when out is empty

Queue / Deque (FIFO)

  • Use when: oldest first, or you need both ends
  • Signals: "in order of arrival", "first in first out", "sliding window", "drop the oldest"
  • Watch out: list.pop(0) is O(n), use collections.deque for O(1) popleft
  • Trick: deque(maxlen=k) drops the oldest item automatically on append
  • Problems in this section:
ProblemHow the queue / deque is used
225. Stack using Queuesafter each push, rotate older items behind the new one
355. Design Twitterper-user deque of (time, tweetId), or maxlen=10
353. Snake Gamebody deque, append new head, popleft old tail

Heap (Priority Queue)

  • Use when: you repeatedly need the smallest or largest item while items keep arriving
  • Signals: "smallest available", "top k", "most recent k", "merge k sorted", "next best"
  • Watch out: heapq is a min heap only, negate values (-time) for a max heap and heap items are compared left to right, so a unique first field avoids comparing objects
  • Watch out: no fast removal of arbitrary items or fast search
  • Problems in this section:
ProblemHow the heap is used
355. Design Twittermerge k sorted tweet lists, max heap of each user's newest tweet
1845. Seat Reservationmin heap of free seats, pop gives the smallest seat number

Singly Linked List

  • Use when: O(1) insert or delete at the head, and you never need to walk backwards
  • Signals: "prepend", "newest first", "chain", "each item points to the next"
  • Watch out: no index access, deleting a node needs its previous node
  • Problems in this section:
ProblemHow the list is used
355. Twitter (Sol 2)per-user list, head is the newest tweet, prepend is O(1)

Doubly Linked List

  • Use when: you already hold a node and need to remove it, move it, or insert next to it in O(1)
  • Signals: "move to front", "evict", "remove from the middle", "order changes constantly"
  • Watch out: pointer bugs, use dummy head and dummy tail sentinels to remove edge cases
  • Pairs with: a hashmap key -> node, so you find the node in O(1)
  • Problems in this section:
ProblemHow the doubly linked list is used
707. Design Linked Listsentinels, walk from the nearer end
432. All O(1)list of count buckets sorted ascending, min at one end, max at the other
460. LFU Cachefrequency buckets, here via OrderedDict instead of a hand built list

Counters

  • Use when: you only need to know whether a total reaches a target, not the full state
  • Signals: "n in a row", "win condition", "balanced", "how many so far"
  • Problems in this section: 348. Tic Tac Toe, signed counter, +1 for player 1 and -1 for player 2, win at +n or -n

Combos: Most Design Problems Use Two

ComboWhat each half doesProblems
Hashmap + HashmapOne per direction, or one for lookup and one for count535 TinyURL, 460 LFU
Hashmap + StackGroup key -> stack, most recent per group on top895 Freq Stack
Hashmap + HeapMap stores the data, heap orders the next pick355 Twitter (followees + heap)
Hashmap + Doubly Linked ListMap finds the node, list holds the order432 All O(1), LRU / LFU style
Hashmap + OrderedDictShorthand for the combo above460 LFU
Deque + HashsetDeque holds order, set gives O(1) membership353 Snake Game
Stack + StackFlip order twice to turn LIFO into FIFO232 Queue using Stacks
Array + ModuloRing buffer, wraps without shifting622 Circular Queue
Stack + Extra Value Per ItemEach item carries the answer at that depth155 Min Stack

Signal Phrase -> Structure

If the problem says...Think
"return in O(1)" for min, max, or most frequentStore the answer alongside the data, or bucket by it
"least recently used", "evict"Hashmap + doubly linked list / OrderedDict
"least frequently used", "most frequent"Hashmap of frequency -> group, plus a tracked min or max frequency
"k most recent", "top k", "merge k lists"Heap over the heads of k sorted sources
"stream of numbers", "add then query"Hashmap of counts, or a sorted structure
"without using built-in hash table / queue"Buckets of lists, or an array plus pointers
"all permutations equally likely"Fisher Yates on an array
"same input must give the same output"Reverse map to detect a repeat
"fixed capacity, reuse space"Ring buffer, track head and size
"check win / rule in O(1) per move"Maintain counters, never rescan

Common Design Tricks

  • Dummy sentinels: dummy head and tail nodes remove empty list and end of list edge cases
  • Lazy transfer: delay expensive work until needed, it is amortized O(1) over many calls (232)
  • Carry state in the tuple: (val, min so far), (-time, tweetId, userId, idx)
  • Track size, not just tail: head == tail cannot tell empty from full in a ring buffer (622)
  • Track min or max incrementally: frequencies move by 1, so the new max or min is max - 1 or min + 1, no scan (895, 460)
  • Negate to flip a min heap into a max heap: push -time, pop the most recent
  • Copy on reset: keep the original untouched, shuffle a working copy (384)
  • Use a global counter for ordering: time += 1 gives a unique, sortable timestamp (355)
  • Bound memory when the output is bounded: a feed shows 10 tweets, so storing 10 per user is enough (355 Sol 3)

Complexity Quick Reference

StructureAccessSearchInsertDeleteBest at
ArrayO(1)O(n)O(n) mid, O(1) endO(n) mid, O(1) endIndexed access
Hashmap / HashsetO(1) avgO(1) avgO(1) avgO(1) avgLookup by key
Stacktop O(1)O(n)O(1)O(1)Newest first
Queue / Dequeends O(1)O(n)O(1) at endsO(1) at endsOldest first
Heappeek O(1)O(n)O(log n)O(log n) topMin or max of changing data
Singly Linked ListO(n)O(n)O(1) headO(1) headPrepend
Doubly Linked ListO(n)O(n)O(1) given nodeO(1) given nodeReordering with a known node
OrderedDictO(1)O(1)O(1)O(1)Key lookup + order

Problem Index

#ProblemCore structure(s)
170Two Sum IIIHashmap of counts
1603Design Parking SystemArray indexed by type
384Shuffle an ArrayArray + Fisher Yates
535Encode and Decode TinyURLTwo hashmaps + counter or random code
355Design TwitterHashmap + heap merge (deque, list, or bounded deque)
225Implement Stack using QueuesOne deque with rotation
232Implement Queue using StacksTwo stacks, lazy transfer
622Design Circular QueueArray ring buffer
155Min StackStack of (val, min so far)
895Maximum Frequency StackHashmap + stack per frequency
705Design HashSetArray of bucket chains
706Design HashMapArray of bucket chains
676Implement Magic DictionaryLength groups, or wildcard pattern hashmap
707Design Linked ListDoubly linked list + sentinels
1845Seat Reservation ManagerMin heap
460LFU CacheHashmaps + OrderedDict frequency buckets
432All O(1) Data StructureDoubly linked list of count buckets + hashmap
348Design Tic Tac ToeSigned row, column, diagonal counters
353Design Snake GameDeque + hashset

170. Two Sum III - Data structure design ::1:: - Easy

Topics: Array, Hash Table, Two Pointers, Data Stream, Premium

Intro

Design a data structure that can accept a stream of integers and check if any pair of integers in the structure sum up to a given target value. The data structure should support two operations: Adding numbers: You can add integers one at a time to the data structure. The same number can be added multiple times. Finding a pair sum: Given a target value, you need to check if there exist any two numbers in the current data structure that add up to this target. The two numbers can be: Two different numbers (e.g., 3 + 5 = 8) The same number used twice, but only if that number was added at least twice (e.g., if 4 was added twice, then 4 + 4 = 8 is valid)

Example InputOutput
[1, 3, 5], find(4)True
[3, 3], find(6)True
[3], find(6)False

Constraints:

something!

Abstraction

Two Sum but with a data structure

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Frequency Hashmap Complement Lookup [TC Opt] - Hashmap/Design

from collections import defaultdict

class TwoSum:

    # Note:
    # - store each number with its count of occurrences
    # - find: for each distinct number, look up its complement (value - num)
    # - if complement differs from num, any occurrence of it forms a pair
    # - if complement equals num (e.g., 4 + 4 = 8), the number must appear at least twice
    #   this is why counts are stored instead of just a set
    # - tradeoff: add is O(1) but find scans every distinct number
    #   a sorted list with two pointers flips this, cheap find but O(n) add

    # overall: sc O(n) for n distinct numbers
    def __init__(self):

        self.count = defaultdict(int)

    # overall: tc O(1)
    # overall: sc O(1)
    def add(self, number: int) -> None:

        # tc: O(1)
        self.count[number] += 1

    # overall: tc O(n) for n distinct numbers
    # overall: sc O(1)
    def find(self, value: int) -> bool:

        # tc: O(n)
        for num in self.count:
            complement = value - num

            # Same number used twice, needs at least two occurrences
            # tc: O(1)
            if complement == num:
                if self.count[num] > 1:
                    return True

            # Different number, any occurrence of it completes the pair
            # get does not insert missing keys into the defaultdict
            # tc: O(1)
            elif self.count.get(complement, 0) > 0:
                return True

        return False

1603. Design Parking System ::1:: - Easy

Topics: Hash Table, String, Design, Hash Function

Intro

Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the ParkingSystem class: ParkingSystem(int big, int medium, int small) Initializes object of the ParkingSystem class. The number of slots for each parking space are given as part of the constructor. bool addCar(int carType) Checks whether there is a parking space of carType for the car that wants to get into the parking lot. carType can be of three kinds: big, medium, or small, which are represented by 1, 2, and 3 respectively. A car can only park in a parking space of its carType. If there is no space available, return false, else park the car in that size space and return true.

Example InputOutput
["ParkingSystem", "addCar", "addCar", "addCar", "addCar"] [[1, 1, 0], [1], [2], [3], [1]][null, true, true, false, false]

Constraints:

0 ≤ big, medium, small ≤ 1000

carType is 1, 2, or 3

At most 1000 calls will be made to addCar

Abstraction

Parking lot!

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Remaining Slots Array Indexed By Car Type [TC Opt] - Array/Design

class ParkingSystem:

    # Note:
    # - only the count of free slots per type matters, no need to track individual cars
    # - store remaining slots in an array indexed by carType - 1
    #   (carType 1, 2, 3 maps to index 0, 1, 2)
    # - addCar checks the count, decrements it if positive, and returns whether a slot was free
    # - array of fixed size 3 gives direct O(1) access, no hashing or branching needed

    # overall: sc O(1) fixed array of 3
    def __init__(self, big: int, medium: int, small: int):

        self.slots = [big, medium, small]

    # overall: tc O(1)
    # overall: sc O(1)
    def addCar(self, carType: int) -> bool:

        # No free slot of this type
        if self.slots[carType - 1] == 0:
            return False

        # Park the car, use up one slot
        self.slots[carType - 1] -= 1

        return True

2043. Simple Bank System ::1:: - Medium

Topics: Array, Hash Table, Design, Simulation

Intro

The bank has n accounts numbered from 1 to n. The initial balance of the (i + 1)th account is balance[i]. A transaction is valid if:

  • The given account number(s) are between 1 and n, and
  • The amount withdrawn or transferred from is less than or equal to the balance of the account. Implement transfer, deposit, and withdraw, each returning true if the transaction was successful, false otherwise.
Example InputOutput
["Bank", "withdraw", "transfer", "deposit", "transfer", "withdraw"], [[[10, 100, 20, 50, 30]], [3, 10], [5, 1, 20], [5, 20], [3, 4, 15], [10, 50]][null, true, true, true, false, false]

Constraints:

n == balance.length

1 ≤ n, account, account1, account2 ≤ 10^5

0 ≤ balance[i], money ≤ 10^12

At most 10^4 calls will be made to each function transfer, deposit, withdraw

Abstraction

Store account balances in an array and apply each transaction only if all of its validity checks pass.

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Interview Walkthrough

  1. Main Answer: Solution 1 (OOP)

    • Account owns its balance and rules (deposit, validate_withdrawal, withdraw)
    • Bank owns lookups (_get_account) and coordination (transfer)
    • Bank never edits a balance directly (encapsulation)
    • All operations O(1), the win is design: follow-ups touch only one class
      • ex: transaction history, withdrawal limits, account types
  2. Extension: Solution 2 (Thread Safe, Lock in Bank)

    • Problem: check-then-act race
      • ex: two threads withdraw $80 from $100, both pass the check -> -$60
    • Lock per account, so unrelated accounts run in parallel (a global lock works but serializes every transaction)
    • Bank holds the lock across the whole transaction
    • Transfer needs two locks -> deadlock risk
      • ex: (1, 2) holds 1 waits on 2, (2, 1) holds 2 waits on 1
      • Fix: always lock the lower account id first
    • Account methods don't lock (Lock isn't reentrant, would deadlock)
    • Edge case: transfer to the same account, take its one lock only
  3. Safest: Solution 3 (Thread Safe, RLock in Bank + Account)

    • RLock is reentrant, the thread holding it can take it again
    • Two layers: Bank locks per request, Account locks per step
    • Account methods are safe even if a caller forgets to lock
    • Same-account transfer needs no special case
    • Tradeoff: slightly slower, more locking to reason about
  4. Production: Solution 4 (Database Transactions)

    • "In production, I'd move this into database transactions so it works across multiple servers and survives crashes, but the reasoning about check-then-act and lock ordering stays the same"
    • Row locks replace account locks, one transaction replaces Bank's lock
    • Failure = rollback, nothing changes
  5. If Asked: Follow-ups

    • "No imports": assume a Lock interface with acquire / release, design doesn't change, a real lock needs an atomic test-and-set from hardware
    • "What if a lock hangs?": timeout, fail cleanly without partial changes, retry with backoff, log it, keep locked sections small

Solution 1: [OOP] OOP With Account Class - Design/Object Oriented

class Account:

    # Each account has ownership over its own data, bank sends requests to account
    #   - Bank never edits directly (encapsulation)
    #   - Allows for later extension: owner, history, account type, etc.
    def __init__(self, account_id: int, balance: int):
        self.account_id = account_id
        self.balance = balance

    # Account is always allowed to deposit
    # tc: O(1)
    def deposit(self, money: int) -> None:
        self.balance += money

    # Check if balance is greater than request
    # tc: O(1)
    def validate_withdrawal(self, money: int) -> bool:
        return money <= self.balance

    # Validate balance then withdraw
    # tc: O(1)
    def withdraw(self, money: int) -> bool:

        # Balance validation failed
        if not self.validate_withdrawal(money):
            return False

        # Withdraw the money and return success
        self.balance -= money
        return True


class Bank:

    # Mock database for accounts
    #   - Init accounts with their starting balances
    #   - Init list is 0 indexed so we + 1 for future account references
    #     which are 1 indexed
    # sc: O(n)
    def __init__(self, balance: List[int]):

        # Dict of account_ids => Account()
        #   - ex: {1: Account(1, 10), 2: Account(2, 100)}
        self.accounts = {}

        # Init list 0 indexed + 1 for future account references
        for i, money in enumerate(balance):
            self.accounts[i+1] = Account(i+1, money)

    # Lookup() account by id:
    #   - dict returns None if the account doesn't exist
    # tc: O(1)
    def _get_account(self, account_id: int) -> Optional[Account]:
        return self.accounts.get(account_id)

    # Transfer between accounts:
    #   - Validate both accounts exists
    #   - Validate sender balance 
    #   - Transfer funds
    # tc: O(1)
    def transfer(self, account1: int, account2: int, money: int) -> bool:

        # Look up accounts
        sender = self._get_account(account1)
        receiver = self._get_account(account2)
        if sender is None or receiver is None:
            return False

        # Not enough balance
        if not sender.validate_withdrawal(money):
            return False

        # Transfer between accounts and return success
        sender.withdraw(money)
        receiver.deposit(money)
        return True

    # Deposit into account:
    #   - Validate account exists
    #   - Add to balance
    # tc: O(1)
    def deposit(self, account: int, money: int) -> bool:

        # Look up account
        acct = self._get_account(account)
        if acct == None:
            return False

        # Add to balance and return success
        acct.deposit(money)
        return True

    # Take from balance:
    #   - Validate account exists
    #   - Validate balance
    #   - Take funds from balance
    # tc: O(1)
    def withdraw(self, account: int, money: int) -> bool:

        # Look up account
        acct = self._get_account(account)
        if acct == None:
            return False

        # Take from balance and return success/failure
        return acct.withdraw(money)

Solution 2: [OOP] Thread Safe OOP With Per Account Locks - Design/Concurrency

from threading import Lock

class Account:

    # Each account has ownership over its own data, bank sends requests to account
    #   - Bank never edits directly (encapsulation)
    #   - Allows for later extension: owner, history, account type, etc.
    
    # Per account lock:
    #   - Only one thread can access this account's balance at a time
    #   - Unrelated accounts never block each other
    #   - Bank locks around any type of request (deposit, withdraw, transfer)
    
    # Locking Strategies:
    #   1. Bank only, Lock: correct (this solution)
    #      - Bank knows every step of a transaction, so it locks around each of them
    #   2. Account only, Lock: incorrect, race between steps from different requests
    #      - ex: transfer thread 1 checks funds, different withdraw thread 2 takes funds,
    #            transfer thread 1's withdraw step fails, but its deposit still happens
    #            (transfer already passed its check, so it doesn't stop)
    #   3. Bank + Account, Lock: incorrect, deadlock within a single withdraw request
    #      - Lock is just held or free, and can't stack for inner locks
    #      - ex: withdraw thread 1 takes the lock in Bank.withdraw,
    #            then Account.withdraw tries to take the same lock on the step level,
    #            but it cant since lock is taken by bank level, so thread 1 waits forever
    #   4. Bank + Account, RLock: correct, safest (Solution 3)
    def __init__(self, account_id: int, balance: int):
        self.account_id = account_id
        self.balance = balance
        self.lock = Lock()

    # Account is always allowed to deposit
    #   - caller must hold self.lock
    # tc: O(1)
    def deposit(self, money: int) -> None:
        self.balance += money

    # Check if balance is greater than request
    #   - caller must hold self.lock
    # tc: O(1)
    def validate_withdrawal(self, money: int) -> bool:
        return money <= self.balance

    # Validate balance then withdraw
    #   - caller must hold self.lock
    # tc: O(1)
    def withdraw(self, money: int) -> bool:

        # Balance validation failed
        if not self.validate_withdrawal(money):
            return False

        # Withdraw the money and return success
        self.balance -= money
        return True


class Bank:

    # Mock database for accounts
    #   - Init accounts with their starting balances
    #   - Init list is 0 indexed so we + 1 for future account references
    #     which are 1 indexed
    #   - Dict never changes after init, so lookups don't need a lock
    # sc: O(n)
    def __init__(self, balance: List[int]):

        # Dict of account_ids => Account()
        #   - ex: {1: Account(1, 10), 2: Account(2, 100)}
        self.accounts = {}

        # Init list 0 indexed + 1 for future account references
        for i, money in enumerate(balance):
            self.accounts[i+1] = Account(i+1, money)

    # Lookup() account by id:
    #   - dict returns None if the account doesn't exist
    # tc: O(1)
    def _get_account(self, account_id: int) -> Optional[Account]:
        return self.accounts.get(account_id)

    # Transfer between accounts:
    #   - Validate both accounts exist
    #   - Lock both accounts in id order
    #   - Validate sender balance
    #   - Transfer funds
    # tc: O(1) plus lock wait time
    def transfer(self, account1: int, account2: int, money: int) -> bool:

        # Look up accounts
        sender = self._get_account(account1)
        receiver = self._get_account(account2)
        if sender is None or receiver is None:
            return False

        # Same account:
        #   - question doesn't forbid transfers to the same account,
        #   - only return if the balance would cover it, no actual transfer needed
        if sender is receiver:

            # Lock to ensure no other thread changes balance mid check
            with sender.lock:
                return sender.validate_withdrawal(money)

        # Lock ordering: 
        #   - Prevent deadlock from opposite transfer but locking the lower id first
        #   - ex: transfer(1, 2) locks 1 and waits on 2, 
        #         but transfer(2, 1) locks 2 and waits on 1, deadlock.
        #         Instead, we keep the transfer the same, but just lock from low to high
        if sender.account_id < receiver.account_id:
            first, second = sender, receiver
        else:
            first, second = receiver, sender

        # Lock both accounts across transfer request
        with first.lock, second.lock:

            # Not enough balance
            if not sender.validate_withdrawal(money):
                return False

            # Transfer between accounts and return success
            sender.withdraw(money)
            receiver.deposit(money)
            return True

    # Deposit into account:
    #   - Validate account exists
    #   - Lock account, add to balance
    #   - += is a read then a write, not atomic, so it needs the lock
    # tc: O(1) plus lock wait time
    def deposit(self, account: int, money: int) -> bool:

        # Look up account
        acct = self._get_account(account)
        if acct is None:
            return False

        # Add to balance and return success
        with acct.lock:
            acct.deposit(money)
        return True

    # Take from balance:
    #   - Validate account exists
    #   - Lock account across check + withdraw
    #   - Without the lock, two withdrawals could both pass the check -> overdraw
    # tc: O(1) plus lock wait time
    def withdraw(self, account: int, money: int) -> bool:

        # Look up account
        acct = self._get_account(account)
        if acct is None:
            return False

        # Take from balance and return success/failure
        with acct.lock:
            return acct.withdraw(money)

Solution 3: [OOP] Thread Safe OOP With Reentrant Per Account Locks - Design/Concurrency

from threading import RLock

class Account:

    # Each account has ownership over its own data, bank sends requests to account
    #   - Bank never edits directly (encapsulation)
    #   - Allows for later extension: owner, history, account type, etc.
    
    # Bank + Account both lock (Locking Strategy 4, safest):
    #   - Account methods lock themselves, safe even if a caller forgets to lock
    #   - Bank still locks around the whole transaction, so no thread
    #     can slip in between steps (ex: transfer = check + withdraw + deposit)
    
    # RLock (reentrant lock):
    #   - Thread can layer the lock on outer and inner layers
    #   - ex: Bank.withdraw takes acct.lock, Account.withdraw takes it again -> allowed
    def __init__(self, account_id: int, balance: int):
        self.account_id = account_id
        self.balance = balance
        self.lock = RLock()

    # Account is always allowed to deposit
    #   - balance += money looks like one step, but it's actually three (not atomic):
    #       1. read self.balance
    #       2. add money to it
    #       3. write the result back to self.balance
    #   - without the lock, another thread could run between these steps
    #     ex: two deposits both read $100, the second write overwrites the first
    # tc: O(1)
    def deposit(self, money: int) -> None:

        # Lock on step level
        #   - grab balance and update
        with self.lock:
            self.balance += money

    # Check if balance is greater than request
    #   - locks itself, so balance can't change mid read
    # tc: O(1)
    def validate_withdrawal(self, money: int) -> bool:

        # Lock on step level:
        #   - validate withdraw balance
        with self.lock:
            return money <= self.balance

    # Validate balance then withdraw
    #   - locks itself across check + withdraw
    #   - validate_withdrawal takes the lock again, allowed (RLock)
    # tc: O(1)
    def withdraw(self, money: int) -> bool:

        # Lock on step level:
        #   - validate withdraw steps
        with self.lock:

            # Balance validation failed
            if not self.validate_withdrawal(money):
                return False

            # Withdraw the money and return success
            self.balance -= money
            return True


class Bank:

    # Mock database for accounts
    #   - Init accounts with their starting balances
    #   - Init list is 0 indexed so we + 1 for future account references
    #     which are 1 indexed
    #   - Dict never changes after init, so lookups don't need a lock
    # sc: O(n)
    def __init__(self, balance: List[int]):

        # Dict of account_ids => Account()
        #   - ex: {1: Account(1, 10), 2: Account(2, 100)}
        self.accounts = {}

        # Init list 0 indexed + 1 for future account references
        for i, money in enumerate(balance):
            self.accounts[i+1] = Account(i+1, money)

    # Lookup() account by id:
    #   - dict returns None if the account doesn't exist
    # tc: O(1)
    def _get_account(self, account_id: int) -> Optional[Account]:
        return self.accounts.get(account_id)

    # Transfer between accounts:
    #   - Validate both accounts exist
    #   - Lock both accounts in id order
    #   - Validate sender balance
    #   - Transfer funds
    # tc: O(1) plus lock wait time
    def transfer(self, account1: int, account2: int, money: int) -> bool:

        # Look up accounts
        sender = self._get_account(account1)
        receiver = self._get_account(account2)
        if sender is None or receiver is None:
            return False

        # Lock ordering: 
        #   - Prevent deadlock from opposite transfer but locking the lower id first
        #   - ex: transfer(1, 2) locks 1 and waits on 2, 
        #         but transfer(2, 1) locks 2 and waits on 1, deadlock.
        #         Instead, we keep the transfer the same, but just lock from low to high
        if sender.account_id < receiver.account_id:
            first, second = sender, receiver
        else:
            first, second = receiver, sender

        # Lock accounts on Bank level:
        #   - validate transfer steps
        with first.lock, second.lock:

            # Not enough balance
            if not sender.validate_withdrawal(money):
                return False

            # Transfer between accounts and return success
            sender.withdraw(money)
            receiver.deposit(money)
            return True

    # Deposit into account:
    #   - Validate account exists
    #   - Lock account, add to balance
    # tc: O(1) plus lock wait time
    def deposit(self, account: int, money: int) -> bool:

        # Look up account
        acct = self._get_account(account)
        if acct is None:
            return False

        # Lock account on Bank level:
        #   - Add to balance and return success
        with acct.lock:
            acct.deposit(money)
        return True

    # Take from balance:
    #   - Validate account exists
    #   - Lock account across check + withdraw
    # tc: O(1) plus lock wait time
    def withdraw(self, account: int, money: int) -> bool:

        # Look up account
        acct = self._get_account(account)
        if acct is None:
            return False

        # Lock account on Bank level:
        #   - Take from balance and return success/failure
        with acct.lock:
            return acct.withdraw(money)

Solution 4: [Database] Production Design With Database Transactions - Design/Concurrency

# Production Design:
#   - In production, move this into database transactions so it works
#     across multiple servers and survives crashes
#   - The reasoning about check-then-act and lock ordering stays the same

# Why Solutions 2 / 3 aren't enough in production:
#   - In-memory locks only coordinate threads inside ONE program,
#     real banks run many servers, so a lock on one server means nothing to the others
#   - In-memory balances are lost if the program crashes
#   - No record of what happened, banks need an audit trail of every transaction

# How the database replaces each piece:
#   - Account lock          -> database locks that account's row
#   - Bank locks whole txn  -> one database transaction around all the steps
#                              (begin -> check -> withdraw -> deposit -> commit)
#   - Lock ordering by id   -> still lock rows in id order to prevent deadlock
#   - Early return False    -> rollback, the database undoes every step,
#                              nothing changes
#   - Lock wait / timeout   -> database lock timeout, then rollback
#   - Audit trail           -> insert a record of each transaction
#                              in the same database transaction

# ACID guarantees the database provides:
#   - Atomicity:   all steps of a transaction happen together or not at all
#   - Consistency: rules hold before and after (ex: balance never negative)
#   - Isolation:   concurrent transactions can't see each other half done
#   - Durability:  once committed, a transaction survives crashes

# Bonus: single step check-then-act
#   - A withdrawal can be one conditional update:
#     "subtract money only if balance >= money"
#   - The check and the update happen in one atomic database operation,
#     so no other request can run between them
#   - If nothing was updated -> account missing or not enough money -> return False

2502. Design Memory Allocator ::3:: - Medium

Topics: Array, Hash Table, Design, Simulation

Intro

You are given an integer n representing the size of a 0-indexed memory array. All memory units are initially free. allocate(size, mID): find the leftmost block of size consecutive free units, assign it to mID, and return its first index, or -1 if no such block exists. freeMemory(mID): free all units with id mID (even across multiple blocks), and return the number of units freed.

Example InputOutput
["Allocator","allocate","allocate","allocate","freeMemory","allocate","allocate","allocate","freeMemory","allocate","freeMemory"] [[10],[1,1],[1,2],[1,3],[2],[3,4],[1,1],[1,1],[1],[10,2],[7]][null,0,1,2,1,3,1,6,3,-1,0]

Constraints:

1 ≤ n, size, mID ≤ 1000

At most 1000 calls will be made to allocate and freeMemory

Abstraction

Maintain a memory layout that supports finding the leftmost free run of a given length, and releasing every unit owned by an id.

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: [Simulation] Array Simulation - Design/Simulation Linear Scan

class Allocator:

    # Memory array, one slot per unit:
    #   - memory[i] == 0   -> unit is free
    #   - memory[i] == mID -> unit is owned by mID
    #   - constraints guarantee mID >= 1, so 0 is a safe free marker
    # sc: O(n)
    def __init__(self, n: int):
        self.n = n
        self.memory = [0] * n

    # Find leftmost run of size free units, assign it to mID:
    #   - scan left to right, so the first run found is the leftmost
    #   - count consecutive free units, reset on an allocated unit
    #   - once count reaches size, the run ends at i
    # tc: O(n)
    def allocate(self, size: int, mID: int) -> int:

        count = 0
        for i in range(self.n):

            # Extend run if free, reset if allocated
            if self.memory[i] == 0:
                count += 1
            else:
                count = 0

            # Found leftmost run, spans [i - size + 1, i]
            #   - ex: i = 5, size = 3 -> start = 3, run is 3, 4, 5
            if count == size:
                start = i - size + 1

                # Assign every unit in the run and return its start
                for j in range(start, i + 1):
                    self.memory[j] = mID
                return start

        # No run of length size exists
        return -1

    # Free every unit owned by mID:
    #   - mID may own several blocks, so scan all of memory
    # tc: O(n)
    def freeMemory(self, mID: int) -> int:

        # Clear each unit owned by mID and count it
        freed = 0
        for i in range(self.n):
            if self.memory[i] == mID:
                self.memory[i] = 0
                freed += 1

        return freed

Solution 2: [OOP] OOP Free List With Block Class - Design/Intervals Merge

from bisect import bisect_left
from collections import defaultdict
from dataclasses import dataclass


# Contiguous run of memory units [start, start + size):
#   - @dataclass generates the boilerplate from the field list:
#       __init__  => Block(3, 3) sets start = 3, size = 3
#       __repr__  => prints as Block(start=3, size=3) for debugging
#       __eq__    => blocks with the same start and size are equal
#   - order=True: generates <, <=, >, >= comparing (start, size),
#     needed by bisect to keep free_blocks sorted
#   - frozen=True: immutable, block stored in allocated can't be changed
@dataclass(frozen=True, order=True)
class Block:
    start: int
    size: int

    # One past the last unit (exclusive)
    #   - ex: Block(3, 3) covers units 3, 4, 5 -> end = 6
    @property
    def end(self) -> int:
        return self.start + self.size


class Allocator:

    # Free blocks + allocated blocks:
    #   - free_blocks: sorted by start, disjoint, never touching (always merged),
    #     starts as one block covering all of memory
    #   - allocated: mID -> every block it owns
    # sc: O(k + b), k = free blocks, b = allocated blocks, both <= n
    def __init__(self, n: int):
        self.free_blocks = [Block(0, n)]
        self.allocated = defaultdict(list)

    # ---------- Public API ----------

    # Allocate a block for mID:
    #   - find leftmost free block that fits
    #   - carve the requested size off it
    #   - record ownership for freeMemory
    # tc: O(k)
    def allocate(self, size: int, mID: int) -> int:

        # No free block is large enough
        index = self._find_first_fit(size)
        if index == -1:
            return -1

        # Carve the block, record its owner, return its start
        block = self._carve(index, size)
        self.allocated[mID].append(block)
        return block.start

    # Free every block owned by mID:
    #   - return each block to the free list, merging with neighbors
    # tc: O(r * k), r = blocks released
    def freeMemory(self, mID: int) -> int:

        # Remove all of mID's blocks, empty list if it owns nothing
        blocks = self.allocated.pop(mID, [])

        # Release each block and count its units
        freed = 0
        for block in blocks:
            freed += block.size
            self._release(block)

        return freed

    # ---------- Helpers ----------

    # First fit: index of the leftmost free block with enough room
    #   - free_blocks is sorted by start, so the first fit is leftmost
    # tc: O(k)
    def _find_first_fit(self, size: int) -> int:
        for i, block in enumerate(self.free_blocks):
            if block.size >= size:
                return i
        return -1

    # Carve size units off the front of free_blocks[index]:
    #   - ex: Block(6, 4), size 1 -> carved Block(6, 1), leftover Block(7, 3)
    # tc: O(k) for list pop
    def _carve(self, index: int, size: int) -> Block:

        free = self.free_blocks[index]
        carved = Block(free.start, size)

        # Free block fully used, remove it
        # Free block partly used, replace with what's left
        if free.size == size:
            self.free_blocks.pop(index)
        else:
            self.free_blocks[index] = Block(free.start + size, free.size - size)

        return carved

    # Put a block back in the free list, merging with neighbors:
    #   - insert in sorted position (starts are unique)
    #   - merge right first, then left, so a block touching
    #     both sides collapses all three into one
    # tc: O(k) for list insert / pop
    def _release(self, block: Block) -> None:

        # Insert in sorted position
        i = bisect_left(self.free_blocks, block)
        self.free_blocks.insert(i, block)

        # Merge with right neighbor if touching
        #   - ex: Block(1, 1) + Block(2, 3) -> Block(1, 4)
        if i + 1 < len(self.free_blocks):
            current, right = self.free_blocks[i], self.free_blocks[i + 1]
            if current.end == right.start:
                self.free_blocks[i] = Block(current.start, current.size + right.size)
                self.free_blocks.pop(i + 1)

        # Merge with left neighbor if touching
        #   - ex: Block(0, 1) + Block(1, 4) -> Block(0, 5)
        if i > 0:
            left, current = self.free_blocks[i - 1], self.free_blocks[i]
            if left.end == current.start:
                self.free_blocks[i - 1] = Block(left.start, left.size + current.size)
                self.free_blocks.pop(i)

Solution 3: [OOP] Thread Safe OOP Free List - Design/Concurrency

from bisect import bisect_left
from collections import defaultdict
from dataclasses import dataclass
from threading import Lock


# Contiguous run of memory units [start, start + size):
#   - same as Solution 2
#   - frozen=True: immutable, replaced instead of changed
#   - order=True: compares by (start, size), so blocks can stay sorted with bisect
@dataclass(frozen=True, order=True)
class Block:
    start: int
    size: int

    # One past the last unit (exclusive)
    #   - ex: Block(3, 3) covers units 3, 4, 5 -> end = 6
    @property
    def end(self) -> int:
        return self.start + self.size


class Allocator:

    # Thread safe allocator:
    #   - allocate is check-then-act on the free list:
    #     find a free block (check), then carve it (act)
    #   - ex: two threads both find Block(0, 10) free,
    #         both carve index 0, both get address 0 -> same memory given out twice
    #   - one lock for the whole allocator:
    #     every operation reads and changes the shared free list,
    #     so there's no smaller piece to lock separately
    #     (unlike the bank, where each account is independent)
    #   - public methods hold the lock, helpers assume it's held
    # sc: O(k + b), k = free blocks, b = allocated blocks, both <= n
    def __init__(self, n: int):
        self.free_blocks = [Block(0, n)]
        self.allocated = defaultdict(list)
        self.lock = Lock()

    # ---------- Public API ----------

    # Allocate a block for mID while holding the lock:
    #   - no other thread can change the free list
    #     between finding a block and carving it
    # tc: O(k) plus lock wait time
    def allocate(self, size: int, mID: int) -> int:
        with self.lock:

            # No free block is large enough
            index = self._find_first_fit(size)
            if index == -1:
                return -1

            # Carve the block, record its owner, return its start
            block = self._carve(index, size)
            self.allocated[mID].append(block)
            return block.start

    # Free every block owned by mID while holding the lock:
    #   - no other thread can allocate from the free list
    #     while blocks are being merged back in
    # tc: O(r * k) plus lock wait time, r = blocks released
    def freeMemory(self, mID: int) -> int:
        with self.lock:

            # Remove all of mID's blocks, empty list if it owns nothing
            blocks = self.allocated.pop(mID, [])

            # Release each block and count its units
            freed = 0
            for block in blocks:
                freed += block.size
                self._release(block)

            return freed

    # ---------- Helpers (caller must hold self.lock) ----------

    # First fit: index of the leftmost free block with enough room
    #   - free_blocks is sorted by start, so the first fit is leftmost
    # tc: O(k)
    def _find_first_fit(self, size: int) -> int:
        for i, block in enumerate(self.free_blocks):
            if block.size >= size:
                return i
        return -1

    # Carve size units off the front of free_blocks[index]:
    #   - ex: Block(6, 4), size 1 -> carved Block(6, 1), leftover Block(7, 3)
    # tc: O(k) for list pop
    def _carve(self, index: int, size: int) -> Block:

        free = self.free_blocks[index]
        carved = Block(free.start, size)

        # Free block fully used, remove it
        # Free block partly used, replace with what's left
        if free.size == size:
            self.free_blocks.pop(index)
        else:
            self.free_blocks[index] = Block(free.start + size, free.size - size)

        return carved

    # Put a block back in the free list, merging with neighbors:
    #   - insert in sorted position (starts are unique)
    #   - merge right first, then left, so a block touching
    #     both sides collapses all three into one
    # tc: O(k) for list insert / pop
    def _release(self, block: Block) -> None:

        # Insert in sorted position
        i = bisect_left(self.free_blocks, block)
        self.free_blocks.insert(i, block)

        # Merge with right neighbor if touching
        #   - ex: Block(1, 1) + Block(2, 3) -> Block(1, 4)
        if i + 1 < len(self.free_blocks):
            current, right = self.free_blocks[i], self.free_blocks[i + 1]
            if current.end == right.start:
                self.free_blocks[i] = Block(current.start, current.size + right.size)
                self.free_blocks.pop(i + 1)

        # Merge with left neighbor if touching
        #   - ex: Block(0, 1) + Block(1, 4) -> Block(0, 5)
        if i > 0:
            left, current = self.free_blocks[i - 1], self.free_blocks[i]
            if left.end == current.start:
                self.free_blocks[i - 1] = Block(left.start, left.size + current.size)
                self.free_blocks.pop(i)

1166. Design File System ::2:: - Medium

Topics: Hash Table, String, Design, Trie

Intro

Design a file system that allows you to create new paths and associate them with different values. A path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters. ex: "/leetcode" and "/leetcode/problems" are valid, "" and "/" are not. createPath(path, value): create path with value and return true, or return false if the path already exists or its parent doesn't exist. get(path): return the value at path, or -1 if it doesn't exist.

Example InputOutput
["FileSystem","createPath","get"] [[],["/a",1],["/a"]][null,true,1]
["FileSystem","createPath","createPath","get","createPath","get"] [[],["/leet",1],["/leet/code",2],["/leet/code"],["/c/d",1],["/c"]][null,true,true,2,false,-1]

Constraints:

2 ≤ path.length ≤ 100

1 ≤ value ≤ 10^9

Each path is valid and consists of lowercase English letters and '/'

At most 10^4 calls in total will be made to createPath and get

Abstraction

Store paths and their values so that a path can only be created when its immediate parent already exists.

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: [Hash Map] Hash Map of Full Paths - Design/Hash Map

class FileSystem:

    def __init__(self):

        # Full Path -> Value
        #   - ex: {"/leet": 1, "/leet/code": 2}
        # sc: O(total length of all created paths)
        self.paths = {}

    def createPath(self, path: str, value: int) -> bool:

        # Check 1: path doesn't already exist
        # tc: O(L) to hash the path
        if path in self.paths:
            return False

        # Find the parent path
        #   - Parent is everything before the last '/'
        #   - ex: "/leet/code" -> rfind('/') = 5 -> parent = "/leet"
        #   - ex: "/leet"      -> rfind('/') = 0 -> parent = ""
        # tc: O(L)
        parent = path[:path.rfind('/')]

        # Check 2: parent exists
        #   - parent == "" means path is top level,
        #     its parent is the root, which always exists
        if parent != "" and parent not in self.paths:
            return False

        # All checks passed, create the path
        self.paths[path] = value

        # tc: O(L)
        return True

    def get(self, path: str) -> int:

        # Return value, or -1 if path doesn't exist

        # overall: tc O(L) per createPath / get, L = path length
        # overall: sc O(total length of all created paths)
        return self.paths.get(path, -1)

Solution 2: [Trie] Trie of Path Components - Design/Trie

class TrieNode:

    def __init__(self, value: int = -1):

        # Child folders, keyed by folder name
        #   - ex: node for "/leet" has children {"code": TrieNode(2)}
        self.children = {}

        # Value stored at this path
        #   - Root keeps -1, since "/" is not a valid path
        self.value = value


class FileSystem:

    def __init__(self):

        # Trie Root:
        #   - Represents the empty root, parent of every top-level path
        #   - Each node below it is one created path
        #   - Mirrors a real file system's directory tree
        # sc: O(total number of path components)
        self.root = TrieNode()

    def createPath(self, path: str, value: int) -> bool:

        # Split path into folder names
        #   - Leading '/' produces an empty first entry, skip it
        #   - ex: "/leet/code".split('/') = ["", "leet", "code"]
        #         [1:]                    = ["leet", "code"]
        # tc: O(L)
        parts = path.split('/')[1:]

        # Start at the root
        node = self.root

        # Walk down to the parent folder
        #   - Every folder except the last must already exist
        #   - ex: "/c/d" -> walk ["c"], then create "d"
        # tc: O(L)
        for part in parts[:-1]:

            # Check 1: parent chain exists
            #   - ex: creating "/c/d" when "/c" doesn't exist -> False
            if part not in node.children:
                return False

            # Step into child folder
            node = node.children[part]

        # Name of the new folder
        name = parts[-1]

        # Check 2: path doesn't already exist
        if name in node.children:
            return False

        # All checks passed, create the new folder under its parent
        node.children[name] = TrieNode(value)

        # tc: O(L)
        return True

    def get(self, path: str) -> int:

        # Split path into folder names
        # tc: O(L)
        parts = path.split('/')[1:]

        # Start at the root
        node = self.root

        # Walk the full path
        # tc: O(L)
        for part in parts:

            # Folder missing, path doesn't exist
            if part not in node.children:
                return -1

            # Step into child folder
            node = node.children[part]

        # Reached the node for this path
        #   - Every node in the trie was created by createPath
        #     (parents are never auto-created), so it always has a real value

        # overall: tc O(L) per createPath / get, L = path length
        # overall: sc O(total number of path components)
        return node.value

146. LRU Cache ::1:: - Medium

Topics: Hash Table, Linked List, Design, Doubly Linked List

Intro

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache. Implement the LRUCache class: LRUCache(int capacity) Initialize the LRU cache with positive size capacity. int get(int key) Return the value of the key if the key exists, otherwise return -1. void put(int key, int value) Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key. The functions get and put must each run in O(1) average time complexity.

Example InputOutput
nums = [1,3,4,2,2]2
nums = [3,1,3,4,2]3
nums = [3,3,3,3,3]3

Constraints:

1 ≤ capacity ≤ 3000

0 ≤ key ≤ 104

0 ≤ value ≤ 105

At most 2 * 105 calls will be made to get and put.

Abstraction

Design an efficient LRU cache using linked lists.

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: [Doubly Linked List] Doubly Linked List + Hashmap For Node Insertion, Removal, or Shifting - Linked List/Simple Traversal

class Node:
    def __init__(self, key: int, val: int):

        # Key -> Value Node:
        self.key = key
        self.val = val

        # Doubly Linked Pointers:
        self.prev = None
        self.next = None


class LRUCache:

    # Strategy:
    #   The two structures each cover the other's weakness:
    #
    #   HashMap: responsible for FINDING
    #     - key -> node lookup in O(1)
    #     - lacks ordering, so it cannot track which key is least recently used
    #
    #   Doubly Linked List: responsible for ORDERING and MOVING
    #     - prev/next pointers let us unlink, insert, and shift a node in O(1),
    #       as long as we already hold the node
    #     - lacks fast search, finding a key by walking the list is O(n)
    #
    #   Together: the map hands us the node in O(1),
    #   and the list rewires around it in O(1) using node.prev and node.next.

    # Ordering Convention:
    # dummyHead <-> MRU <-> ... <-> LRU <-> dummyTail

    # Sentinels:
    # dummyHead/dummyTail always exist, so inserting or removing at the ends
    # never needs None checks

    # Primitives (both O(1)):
    # _remove_node(node): unlink the node from its current position
    # _push_MRU(node):    insert the node just after dummyHead

    # get(key):
    #   1. Map finds the node
    #   2. List moves it: _remove_node, then _push_MRU

    # put(key, val):
    #   1. Map finds the node if the key exists
    #   2. List moves or inserts it at the MRU position
    #   3. If over capacity, list evicts LRU (dummyTail.prev),
    #      and map deletes that node's key (so the node must store its key)

    def __init__(self, capacity: int):

        # Capacity of cache
        self.capacity = capacity

        # Node Cache:
        # key -> node, for O(1) lookup
        self.cache = {}

        # MRU dummyHead / LRU dummyTail:
        # list starts empty, connect dummyHead <-> dummyTail
        self.dummyHead = Node(0, 0)
        self.dummyTail = Node(0, 0)
        self.dummyHead.next = self.dummyTail
        self.dummyTail.prev = self.dummyHead

    # All functions have:
    # tc: O(1)
    # sc: O(1)

    # Both get() and put() need to do the exact same 4 line pointer shift
    # to insert the new node after dummyHead as the new MRU,
    # so we put that logic into 2 private functions to avoid duplicating logic across 2 functions

    # Remove provided node by connecting neighboring nodes to each other
    def _remove_node(self, node: Node):

        # Grab neighbor nodes
        prev, next = node.prev, node.next

        # Connect neighbors to each other
        prev.next = next
        next.prev = prev


    # Insert node in front of dummyHead, becomes the new MRU
    def _push_MRU(self, node: Node):

         # Place new MRU after dummyHead
        node.next = self.dummyHead.next
        node.prev = self.dummyHead

        # Point dummyHead to new MRU
        self.dummyHead.next = node

        # point prev of old MRU to new MRU
        node.next.prev = node

    # Return node if it exists
    def get(self, key: int) -> int:

        # Miss:
        if key not in self.cache:
            return -1

        # Hit:
        # Grab node
        node = self.cache[key]

        # Remove old location
        self._remove_node(node)

        # Node becomes new MRU
        self._push_MRU(node)

        # return grabbed val
        return node.val

    # Insert node
    def put(self, key: int, value: int) -> None:

        # If node already exists in cache, remove from list to avoid duplicates
        if key in self.cache:
            node = self.cache[key]
            self._remove_node(node)
            node.val = value

        # Create new node and add to cache
        else:
            node = Node(key, value)
            self.cache[key] = node

        # New node becomes new MRU
        self._push_MRU(node)

        # If list is over capacity, remove LRU
        if self.capacity < len(self.cache):

            # Grab lru
            lruNode = self.dummyTail.prev

            # Remove lru
            self._remove_node(lruNode)

            # Remove from cache
            del self.cache[lruNode.key]

        # overall: tc O(1)
        # overall: sc O(n)

1865. Finding Pairs With a Certain Sum ::3:: - Medium

Topics: Array, Hash Table, Design

Intro

You are given two integer arrays nums1 and nums2. Implement a data structure that supports two queries:

  1. add(index, val): apply nums2[index] += val
  2. count(tot): return the number of pairs (i, j) such that nums1[i] + nums2[j] == tot
Example InputOutput
["FindSumPairs","count","add","count","count","add","add","count"] [[[1,1,2,2,2,3],[1,4,5,2,5,4]],[7],[3,2],[8],[4],[0,1],[1,1],[7]][null,8,null,2,1,null,null,11]

Constraints:

1 ≤ nums1.length ≤ 1000

1 ≤ nums2.length ≤ 10^5

1 ≤ nums1[i] ≤ 10^9

1 ≤ nums2[i] ≤ 10^5

0 ≤ index < nums2.length

1 ≤ val ≤ 10^5

1 ≤ tot ≤ 10^9

At most 1000 calls are made to add and count each

Abstraction

Support point updates on one array and count cross-array pairs that sum to a target, by iterating the small array and looking up complements in the large one.

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: [Brute Force] Brute Force Pair Check - Design/Brute Force

class FindSumPairs:

    def __init__(self, nums1: List[int], nums2: List[int]):

        # Store both arrays as given
        # sc: O(n1 + n2)
        self.nums1 = nums1
        self.nums2 = nums2

    def add(self, index: int, val: int) -> None:

        # Update nums2 in place
        # tc: O(1)
        self.nums2[index] += val

    def count(self, tot: int) -> int:

        # Brute Force:
        #   - Check every (i, j) pair
        #   - Too slow here: 1000 * 10^5 = 10^8 checks per call,
        #     times up to 1000 calls -> TLE
        pairs = 0

        # tc: O(n1)
        for a in self.nums1:

            # tc: O(n2)
            for b in self.nums2:

                # Pair sums to target
                if a + b == tot:
                    pairs += 1

        # overall: tc O(1) per add / O(n1 * n2) per count
        # overall: sc O(n1 + n2)
        return pairs

Solution 2: [Hash Map] Frequency Map of nums2 - Design/Hash Map Complement Lookup

class FindSumPairs:

    def __init__(self, nums1: List[int], nums2: List[int]):

        # Small, fixed array
        #   - At most 1000 elements, never changes
        #   - We iterate this one in count
        # sc: O(n1)
        self.nums1 = nums1

        # Large, changing array
        #   - Up to 10^5 elements
        #   - Still need it to know a value's OLD value during add
        # sc: O(n2)
        self.nums2 = nums2

        # Frequency Map of nums2:
        #   - value -> how many indices in nums2 hold that value
        #   - Lets count find all matching j's in one O(1) lookup
        #   - ex: nums2 = [1, 4, 5, 2, 5, 4] -> {1: 1, 4: 2, 5: 2, 2: 1}
        # tc: O(n2)
        # sc: O(n2)
        self.freq2 = Counter(nums2)

    def add(self, index: int, val: int) -> None:

        # Keep freq2 in sync with nums2:
        #   - One index changes value, so one count moves between keys

        # Old value at this index
        #   - ex: nums2[3] = 2
        old = self.nums2[index]

        # Remove old value from the frequency map
        #   - ex: freq2[2]: 1 -> 0
        self.freq2[old] -= 1

        # Apply the update
        #   - ex: 2 + 2 = 4
        self.nums2[index] += val

        # New value at this index
        new = self.nums2[index]

        # Add new value to the frequency map
        #   - ex: freq2[4]: 2 -> 3
        self.freq2[new] += 1

        # tc: O(1)

    def count(self, tot: int) -> int:

        # Complement Lookup:
        #   - For each a in nums1, we need b = tot - a in nums2
        #   - freq2[b] tells us how many j's hold b, all at once
        #   - Iterate nums1 (small), not nums2 (large)
        pairs = 0

        # tc: O(n1)
        for a in self.nums1:

            # Value needed from nums2 to reach tot
            #   - ex: tot = 7, a = 2 -> need 5
            need = tot - a

            # Every index in nums2 holding need forms a pair with a
            #   - Counter returns 0 for missing keys, no KeyError
            #   - ex: freq2[5] = 2 -> 2 pairs
            # tc: O(1)
            pairs += self.freq2[need]

        # overall: tc O(n1 + n2) init / O(1) per add / O(n1) per count
        # overall: sc O(n1 + n2) for arrays and frequency map
        return pairs

Solution 3: [Hash Map] Frequency Maps of Both Arrays - Design/Hash Map Complement Lookup

class FindSumPairs:

    def __init__(self, nums1: List[int], nums2: List[int]):

        # Frequency Map of nums1:
        #   - value -> how many indices in nums1 hold that value
        #   - nums1 never changes, so this map never needs updating
        #   - count only loops over DISTINCT values of nums1
        #   - ex: nums1 = [1, 1, 2, 2, 2, 3] -> {1: 2, 2: 3, 3: 1}
        # tc: O(n1)
        # sc: O(u1), u1 = distinct values in nums1
        self.freq1 = Counter(nums1)

        # Large, changing array
        #   - Still need it to know a value's OLD value during add
        # sc: O(n2)
        self.nums2 = nums2

        # Frequency Map of nums2:
        #   - value -> how many indices in nums2 hold that value
        #   - ex: nums2 = [1, 4, 5, 2, 5, 4] -> {1: 1, 4: 2, 5: 2, 2: 1}
        # tc: O(n2)
        # sc: O(n2)
        self.freq2 = Counter(nums2)

    def add(self, index: int, val: int) -> None:

        # Old value at this index
        old = self.nums2[index]

        # Remove old value from the frequency map
        self.freq2[old] -= 1

        # Drop keys that hit 0
        #   - Keeps freq2 holding only values that actually exist in nums2
        #   - Every add creates a new value, so without this,
        #     freq2 would keep growing with dead keys
        if self.freq2[old] == 0:
            del self.freq2[old]

        # Apply the update
        self.nums2[index] += val

        # New value at this index
        new = self.nums2[index]

        # Add new value to the frequency map
        self.freq2[new] += 1

        # tc: O(1)

    def count(self, tot: int) -> int:

        # Grouped Complement Lookup:
        #   - Same idea as Sol 2, but each distinct value in nums1
        #     is handled once
        #   - f copies of a value in nums1, each pairing with
        #     freq2[need] indices in nums2 -> f * freq2[need] pairs
        pairs = 0

        # tc: O(u1)
        for value, f in self.freq1.items():

            # Value needed from nums2 to reach tot
            #   - ex: tot = 7, value = 2 -> need 5
            need = tot - value

            # Number of indices in nums2 holding need
            #   - .get avoids inserting missing keys into freq2
            #   - ex: freq2[5] = 2
            # tc: O(1)
            matches = self.freq2.get(need, 0)

            # Every copy of value pairs with every match
            #   - ex: value 2 appears 3 times, need 5 appears 2 times
            #     -> 3 * 2 = 6 pairs
            pairs += f * matches

        # overall: tc O(n1 + n2) init / O(1) per add / O(u1) per count
        #          u1 = distinct values in nums1, u1 <= n1
        # overall: sc O(n1 + n2) for frequency maps and nums2
        return pairs

384. Shuffle an Array ::1:: - Medium

Topics: Array, Math, Design, Randomized

Intro

Given an integer array nums, design an algorithm to randomly shuffle the array. All permutations of the array should be equally likely as a result of the shuffling. Implement the Solution class: Solution(int[] nums) Initializes the object with the integer array nums. int[] reset() Resets the array to its original configuration and returns it. int[] shuffle() Returns a random shuffling of the array.

Example InputOutput
["Solution", "shuffle", "reset", "shuffle"] [[[1, 2, 3]], [], [], []][null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

Constraints:

1 ≤ nums.length ≤ 50

-10^6 ≤ nums[i] ≤ 10^6

All the elements of nums are unique.

At most 104 calls in total will be made to reset and shuffle.

Abstraction

Cha cha real smooth!

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Fisher Yates Shuffle On A Working Copy [TC Opt] - Array/Design

import random

class Solution:

    # Note:
    # - keep the original array untouched so reset() can return it
    # - keep a separate working copy that shuffle() rearranges in place
    # - Fisher Yates: for each index i from left to right,
    #   swap nums[i] with a random index j in [i, n - 1]
    # - each position is fixed once it is swapped, and every remaining element
    #   is equally likely to land there, so all n! permutations are equally likely
    # - the random range must be [i, n - 1], not [0, n - 1]
    #   picking from the full range biases the result toward some permutations
    # - shuffle rearranges the working copy from its current state, not the original
    #   this is still uniform, since Fisher Yates produces a uniform permutation
    #   from any starting order
    # - use secrets.randbelow instead of random for security sensitive shuffles
    #   (random is not cryptographically secure)

    # Track original and modified copy,
    # so we can return the original deck or reset our shuffle deck when requested
    # overall: sc O(n)
    def __init__(self, nums: list[int]):

        self.original = nums
        self.array = nums[:]

    # Restore the working copy so later shuffles start from the original order
    # overall: tc O(n)
    # overall: sc O(n)
    def reset(self) -> list[int]:
        self.array = self.original[:]
        return self.array

    # Shuffle In Place With Fisher Yates
    # overall: tc O(n)
    # overall: sc O(1)
    def shuffle(self) -> list[int]:

        n = len(self.array)

        # We will grab elements from non fixed section,
        # and begin to build a fix section on the left
        # tc: O(n)
        for i in range(n):

            # Grab new element from non fixed section
            notUsed = random.randint(i, n - 1) 

            # Set new element on fixed section
            self.array[i], self.array[notUsed] = self.array[notUsed], self.array[i]

        return self.array

535. Encode and Decode TinyURL ::2:: - Medium

Topics: Hash Table, String, Design, Hash Function, Encoding

Intro

Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design a class to encode a URL and decode a tiny URL. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. Implement the Solution class: Solution() Initializes the object of the system. String encode(String longUrl) Returns a tiny URL for the given longUrl. String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.

Example InputOutput
url = "https://leetcode.com/problems/design-tinyurl""https://leetcode.com/problems/design-tinyurl"

Constraints:

1 ≤ url.length ≤ 10^4

url is guaranteed to be a valid URL.

Abstraction

URL shortener

Pseudocode

Sol 1: Counter Base62 Bidirectional Hashmap
1. (code_to_url = {})
2. (url_to_code = {}) 
3. (counter = 1)
4. (BASE = "http://tinyurl.com/")
5. (ALPHABET = "0123456789abcedfghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
6. def _to_base62(self, n: int) -> str:
    a. chars = []
    b. while n:
         n, r = divmod(n, 62)
         chars.append(self.ALPHABET[r])
    c. return "".join(reversed(chars))
7. encode(longUrl):
    a. if longUrl in url_to_code:
         return BASE + url_to_code[longUrl]
    b. code = _to_base62(counter)
    c. code_to_url[code] = longUrl
    d. url_to_code[longUrl] = code
    e. counter += 1
    f. return BASE + code
8. decode(shortUrl):
    a. code = shortUrl without BASE
    b. return code_to_url[code]

Sol 2: Random Code With Collision Retry
1. (code_to_url = {})
2. (url_to_code = {})
3. def _to_base62(self, n: int) -> str:
    a. chars = []
    b. while n:
         n, r = divmod(n, 62)
         chars.append(self.ALPHABET[r])
    c. return "".join(reversed(chars))
4. encode(longUrl):
    a. if longUrl in url_to_code:
         return BASE + url_to_code[longUrl]
    b. code = random 6 char base62 string
    c. while code in code_to_url:
         code = random 6 char base62 string
    d. code_to_url[code] = longUrl
    e. url_to_code[longUrl] = code
    f. return BASE + code
5. decode(shortUrl):
    a. code = shortUrl without BASE
    b. return code_to_url[code]

Solution 1: Counter Base62 Bidirectional Hashmap [TC Opt] - Hashmap/Design

class Codec:

    # Note:
    
    # 6 character code space

    # Base10:   10^6
    #         = 1,000,000

    # Base62:
    #           62^6
    #         = 56,800,235,584
    #         ≈ 56.8 billion

    # - extends Solution 1 with a reverse map: url -> code
    # - same url always maps to the same short url,
    #   which allows us to check we have a mapped a url previously
    #   allowing us to avoid generating duplicate short urls for the same long url
    # - code_to_url supports decode: code -> url
    # - url_to_code supports duplicate detection: url -> code
    # - tradeoff: uses a second hashmap and therefore more memory
    # - for a duplicate url, we can immediately return the existing code

    # Base62:
    # - largest alphabet that is still purely alphanumeric (0-9, a-z, A-Z)
    # - url safe, no percent encoding needed (unlike base64's + and /)
    # - 6 chars ~ 56.8 billion combinations, 7 chars ~ 3.5 trillion
    # - tradeoff: case sensitive, and 0/O, l/1/I look alike
    #   base58 removes look alike chars if human readability matters

    BASE = "http://tinyurl.com/"
    ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    # overall: sc O(n * L)
    def __init__(self):

        # n short codes to n long urls of length L 
        # sc: O(n * L)
        self.code_to_url = {}

        # duplicate verifier
        # n long urls of length L to n short codes
        self.url_to_code = {}

        # Counter starts at 1 and is incremented after encoding, so n >= 1, 
        # as n == 0 would return an empty string after encoding to base62
        self.counter = 1

    # overall: tc O(log62(n)) ~ O(1)
    # overall: sc O(log62(n)) ~ O(1)
    def _to_base62(self, n: int) -> str:

        # Note:
        # - same as converting to binary or hex, but dividing by 62
        # - quotient is what is left to convert
        # - remainder is the current base-62 digit
        # - digits come out least significant first, so reverse at the end

        chars = []

        # tc: O(log62(n)) iterations
        while n:

            # divmod(n, 62) is equivalent to:
            # quotient = n // 62
            # remainder = n % 62
            quotient = n // 62
            remainder = n % 62

            # The quotient becomes the number we continue converting
            n = quotient

            # The remainder is the current base-62 digit (0-61)
            r = remainder

            # Map digit 0-61 to its corresponding character
            chars.append(self.ALPHABET[r])

        # Digits were extracted least significant first,
        # so reverse them to get standard most significant first order.
        #
        # Example:
        #   n = 3844
        #   3844 % 62 = 0
        #   62   % 62 = 0
        #   1    % 62 = 1
        #
        #   extracted: [0, 0, 1]
        #   reversed:  [1, 0, 0]
        #
        # This gives the normal base-62 representation.
        return "".join(reversed(chars))

    # overall: tc O(L)
    # overall: sc O(L) per new url
    def encode(self, longUrl: str) -> str:

        # Duplicate url,
        # grab prefix + already created url code
        # tc: O(L) to hash the url
        if longUrl in self.url_to_code:
            return self.BASE + self.url_to_code[longUrl]

        code = self._to_base62(self.counter)

        # tc: O(L) to hash the url
        self.code_to_url[code] = longUrl
        self.url_to_code[longUrl] = code

        # Increase global counter to guarantee uniqueness
        self.counter += 1

        # fully encoded short url with prefix BASE = "http://tinyurl.com/"
        return self.BASE + code

    # overall: tc O(1)
    # overall: sc O(1)
    def decode(self, shortUrl: str) -> str:

        # Remove the prefix BASE = "http://tinyurl.com/"
        # tc: O(1)
        code = shortUrl[len(self.BASE):]

        # Simple lookup on actual code
        # tc: O(1)
        longUrl = self.code_to_url[code]

        return longUrl

Solution 2: Cryptographically Secure Random Codes - Hashmap/Design

import secrets

class Codec:

    # Note:
    # - replaces the predictable counter with cryptographically secure random codes
    # - same url still maps to the same short url using url_to_code
    # - codes are unpredictable, so users cannot easily enumerate urls
    # - use secrets, not random, for cryptographically secure randomness
    # - fixed-length 6-character Base62 code gives 62^6 ~ 56.8 billion
    #   possible codes
    # - collisions are possible because codes are random, so retry until
    #   an unused code is found
    # - tradeoff: collision retries add expected work and random generation
    #   is more expensive than a simple counter

    BASE = "http://tinyurl.com/"
    ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    CODE_LEN = 6

    # overall: sc O(n * L) for n urls of length L
    def __init__(self):

        # n short codes to n long urls of length L 
        # sc: O(n * L)
        self.code_to_url = {}

        # duplicate verifier
        # n long urls of length L to n short codes
        # sc: O(n * L)
        self.url_to_code = {}


    # overall: tc O(k) ~ O(1) for k = CODE_LEN
    # overall: sc O(k) ~ O(1)
    def _random_code(self) -> str:

        return "".join(secrets.choice(self.ALPHABET) for _ in range(self.CODE_LEN))

    # overall: tc O(L) expected
    # overall: sc O(L) per new url
    def encode(self, longUrl: str) -> str:

        # Duplicate url, reuse existing code
        # tc: O(L) to hash the url
        if longUrl in self.url_to_code:
            return self.BASE + self.url_to_code[longUrl]

        # Retry on collision
        # tc: O(1) expected retries while map is far from full
        code = self._random_code()
        while code in self.code_to_url:
            code = self._random_code()

        # tc: O(L) to hash the url
        self.code_to_url[code] = longUrl
        self.url_to_code[longUrl] = code

        return self.BASE + code

    # overall: tc O(1)
    # overall: sc O(1)
    def decode(self, shortUrl: str) -> str:

        # tc: O(1)
        code = shortUrl[len(self.BASE):]

        return self.code_to_url[code]

Solution 4: Distributed Extension

    # Note: 
    
    # In-memory hashmaps cannot be extended to a distributed service as-is

    # Single counter:
    # - a single incrementing counter becomes a bottleneck and single point of failure
    # - all servers would need to coordinate on every encode

    # Range allocation:
    # - a coordinator hands each server a block of ids (e.g., 1M at a time)
    # - each server increments locally, coordinating only when its block runs out
    # - no collisions, minimal coordination

    # Alternatives:
    # - Snowflake-style ids (timestamp + machine id + sequence)
    # - random codes with a uniqueness check against a shared key-value store

    # Storage:
    # - replace in-memory hashmaps with a key-value store (code -> url)
    # - cache hot links (e.g., LRU cache / Redis) since reads far outnumber writes
    # - optional expiration (TTL) to reclaim old codes

    # Security:
    # - sequential codes are guessable and enumerable
    # - use random codes, or pass the counter through a keyed permutand blocklist maliciousation / encryption
    # - validate destination urls, rate limit encode requests,  domains

355. Design Twitter ::2:: - Medium

Topics: Hash Table, Linked List, Design, Heap (Priority Queue)

Intro

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the 10 most recent tweets in the user's news feed. Implement the Twitter class: Twitter() Initializes your twitter object. void postTweet(int userId, int tweetId) Composes a new tweet with ID tweetId by the user userId. Each call to this function will be made with a unique tweetId. List[Integer] getNewsFeed(int userId) Retrieves the 10 most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be ordered from most recent to least recent. void follow(int followerId, int followeeId) The user with ID followerId started following the user with ID followeeId. void unfollow(int followerId, int followeeId) The user with ID followerId started unfollowing the user with ID followeeId.

Example InputOutput
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"] [[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]][null, null, [5], null, null, [6, 5], null, [5]]

Constraints:

1 ≤ userId, follwerId, followeeId ≤ 500

0 ≤ tweetId ≤ 104

All the tweets have unique IDs.

At most 3 * 104 calls will be made to postTweet, getNewsFeed, follow, and unfollow

A user cannot follow themselves.

Abstraction

Design a miniTwitter that allows for efficient news feed and postTweet. Boils down to desicions on efficiently storing tweets and retrieving the top 10 recent ones. Also boils down to a merge k sorted lists question.

Pseudocode

Sol 1: Per-User Deque + Max Heap Merge
1. (followees = defaultdict(set))
2. (tweets = defaultdict(deque))
3. (time = 0)
4. (FEED_SIZE = 10)
5. (MAX_STORED = 100)
6. postTweet(userId, tweetId):
    a. time += 1
    b. tweets[userId].append((time, tweetId))
    c. if len(tweets[userId]) > MAX_STORED:
         tweets[userId].popleft()
7. follow(followerId, followeeId):
    a. if followerId != followeeId:
         followees[followerId].add(followeeId)
8. unfollow(followerId, followeeId):
    a. followees[followerId].discard(followeeId)
9. getNewsFeed(userId):
    a. (heap = [])
    b. users = followees[userId] | {userId}
    c. for u in users:
         if tweets[u]:
           idx = len(tweets[u]) - 1
           (t, tweetId) = tweets[u][idx]
           push (-t, tweetId, u, idx) onto heap
    d. (result = [])
    e. while heap and len(result) < FEED_SIZE:
         (neg_t, tweetId, u, idx) = pop heap
         result.append(tweetId)
         if idx > 0:
           idx -= 1
           (t, tweetId) = tweets[u][idx]
           push (-t, tweetId, u, idx) onto heap
    f. return result

Sol 2: Linked List Per User + Max Heap Merge
1. class TweetNode: tweetId, time, next
2. (tweets = {})  # userId -> head (newest) node
3. (followees = defaultdict(set))
4. (time = 0)
5. (FEED_SIZE = 10)
6. postTweet(userId, tweetId):
    a. time += 1
    b. node = TweetNode(tweetId, time)
    c. node.next = tweets.get(userId)
    d. tweets[userId] = node
7. follow(followerId, followeeId):
    a. if followerId != followeeId:
         followees[followerId].add(followeeId)
8. unfollow(followerId, followeeId):
    a. followees[followerId].discard(followeeId)
9. getNewsFeed(userId):
    a. (heap = [])
    b. users = followees[userId] | {userId}
    c. for u in users:
         if u in tweets:
           push (-tweets[u].time, tweets[u]) onto heap
    d. (result = [])
    e. while heap and len(result) < FEED_SIZE:
         (neg_t, node) = pop heap
         result.append(node.tweetId)
         if node.next:
           push (-node.next.time, node.next) onto heap
    f. return result

Sol 3: Bounded Per-User Deque + nlargest
1. (followees = defaultdict(set))
2. (tweets = defaultdict(lambda: deque(maxlen=FEED_SIZE)))
3. (time = 0)
4. (FEED_SIZE = 10)
5. postTweet(userId, tweetId):
    a. time += 1
    b. tweets[userId].append((time, tweetId))   # maxlen drops oldest
6. follow(followerId, followeeId):
    a. if followerId != followeeId:
         followees[followerId].add(followeeId)
7. unfollow(followerId, followeeId):
    a. followees[followerId].discard(followeeId)
8. getNewsFeed(userId):
    a. users = followees[userId] | {userId}
    b. (candidates = [])
    c. for u in users:
         candidates.extend(tweets.get(u, ()))
    d. top = nlargest(FEED_SIZE, candidates)   # largest time first
    e. return [tweetId for (t, tweetId) in top]

Solution 1: Per-User Deque + Max Heap Merge - Heap/Heap

import heapq
from collections import defaultdict, deque

class Twitter:

    # IRL Use Case:
    # Balanced usage, users follow a moderate number of accounts and
    # tweet counts are not huge.

    # Note:
    # - Tweets: each user has a deque of (time, tweetId), oldest on the left,
    #   newest on the right
    # - News Feed: k sorted lists merge, where k = followees + self
    #   each user's deque is already sorted by time, so a max heap always
    #   surfaces the most recent tweet across all k lists
    # - Heap stores (-time, tweetId, userId, index) since heapq is a min heap,
    #   negating time makes the newest tweet pop first
    # - time is a global counter so ordering is unambiguous, tweets are
    #   guaranteed unique so no tuple tie ever reaches userId/index
    # - Only FEED_SIZE (10) tweets per user can ever appear in a feed, so any
    #   MAX_STORED >= FEED_SIZE keeps results correct
    #   the cap only bounds memory
    # - Pros: simple, efficient for moderate tweet counts
    # - Cons: heap merge has overhead, memory grows with tweets per user
    #   (bounded here by MAX_STORED)

    FEED_SIZE = 10
    MAX_STORED = 100

    # overall: sc O(U * M + E) for U users, M = MAX_STORED, E follow edges
    def __init__(self):

        # userId -> deque of (time, tweetId)
        # sc: O(U * M)
        self.tweets = defaultdict(deque)

        # followerId -> set of followeeIds
        # sc: O(E)
        self.followees = defaultdict(set)

        # Global counter for ordering tweets
        self.time = 0

    # overall: tc O(1)
    # overall: sc O(1) amortized, old tweets are evicted past MAX_STORED
    def postTweet(self, userId: int, tweetId: int) -> None:

        self.time += 1

        # tc: O(1) append to the right, newest last
        self.tweets[userId].append((self.time, tweetId))

        # Evict oldest tweet once over the cap
        # tc: O(1) popleft
        if len(self.tweets[userId]) > self.MAX_STORED:
            self.tweets[userId].popleft()

    # overall: tc O(1)
    # overall: sc O(1)
    def follow(self, followerId: int, followeeId: int) -> None:

        # A user cannot follow themselves, and they are already
        # included in their own feed
        # tc: O(1) set add
        if followerId != followeeId:
            self.followees[followerId].add(followeeId)

    # overall: tc O(1)
    # overall: sc O(1)
    def unfollow(self, followerId: int, followeeId: int) -> None:

        # discard does not raise if followeeId was never followed
        # tc: O(1) set discard
        self.followees[followerId].discard(followeeId)

    # overall: tc O(k log k + F log k) for k = followees + 1, F = FEED_SIZE
    #          ~ O(k log k) since F is constant
    # overall: sc O(k + F) ~ O(k)
    def getNewsFeed(self, userId: int) -> list[int]:

        # heap entries: (-time, tweetId, userId, index_in_user_deque)
        # sc: O(k), at most one entry per user at any time
        heap = []

        # Users to pull tweets from: self + followees
        # tc: O(k) to build the union
        users = self.followees[userId] | {userId}

        # Seed the heap with each user's newest tweet
        # tc: O(k log k), k pushes at O(log k) each
        for u in users:

            if self.tweets[u]:

                # Index of last tweet in deque (newest)
                idx = len(self.tweets[u]) - 1
                time, tweetId = self.tweets[u][idx]
                heapq.heappush(heap, (-time, tweetId, u, idx))

        result = []

        # tc: O(F log k), at most F iterations each doing one pop and one push
        while heap and len(result) < self.FEED_SIZE:

            neg_time, tweetId, u, idx = heapq.heappop(heap)
            result.append(tweetId)

            # Advance this user's pointer to their next newest tweet
            if idx > 0:
                idx -= 1
                time, tweetId = self.tweets[u][idx]
                heapq.heappush(heap, (-time, tweetId, u, idx))

        return result

Solution 2: Linked List Per User + Max Heap Merge - Heap/Heap

import heapq
from collections import defaultdict

class TweetNode:

    # Note:
    # - One node per tweet, newest tweet is the head of the user's list
    # - next points to the next older tweet by the same user
    # - Posting prepends, so each list is already sorted newest -> oldest

    def __init__(self, tweetId: int, time: int):
        self.tweetId = tweetId
        self.time = time
        self.next = None

class Twitter:

    # IRL Use Case:
    # 'Celebrity' users with very large tweet histories, prepend is O(1)
    # and we only ever walk the first few nodes, no index bookkeeping.

    # Note:
    # - Tweets: linked list per user, head = newest
    # - News Feed: k sorted lists merge, where k = followees + self
    #   max heap holds the current head of each list, popping the newest
    #   and pushing its next node produces the feed newest -> oldest
    # - Heap stores (-time, node), time is globally unique so the tuple
    #   comparison never falls through to comparing TweetNode objects
    # - Pros: O(1) post with no eviction logic, handles huge histories
    # - Cons: pointer overhead per tweet, unbounded memory growth since
    #   nothing is evicted, more code than the deque version

    FEED_SIZE = 10

    # overall: sc O(N + E) for N total tweets, E follow edges
    def __init__(self):

        # userId -> head (newest) TweetNode
        # sc: O(N) across all nodes
        self.tweets = {}

        # followerId -> set of followeeIds
        # sc: O(E)
        self.followees = defaultdict(set)

        # Global counter for ordering tweets
        self.time = 0

    # overall: tc O(1)
    # overall: sc O(1) per tweet, one new node
    def postTweet(self, userId: int, tweetId: int) -> None:

        self.time += 1
        node = TweetNode(tweetId, self.time)

        # Prepend: new node points at the old head, then becomes the head
        # tc: O(1)
        node.next = self.tweets.get(userId)
        self.tweets[userId] = node

    # overall: tc O(1)
    # overall: sc O(1)
    def follow(self, followerId: int, followeeId: int) -> None:

        # tc: O(1) set add
        if followerId != followeeId:
            self.followees[followerId].add(followeeId)

    # overall: tc O(1)
    # overall: sc O(1)
    def unfollow(self, followerId: int, followeeId: int) -> None:

        # tc: O(1) set discard
        self.followees[followerId].discard(followeeId)

    # overall: tc O(k log k + F log k) for k = followees + 1, F = FEED_SIZE
    #          ~ O(k log k) since F is constant
    # overall: sc O(k + F) ~ O(k)
    def getNewsFeed(self, userId: int) -> list[int]:

        # Users to pull tweets from: self + followees
        # tc: O(k) to build the union
        users = self.followees[userId] | {userId}

        # heap entries: (-time, TweetNode)
        # sc: O(k), at most one node per user at any time
        heap = []

        # Seed the heap with the head (newest tweet) of each user's list
        # tc: O(k log k)
        for u in users:

            if u in self.tweets:
                head = self.tweets[u]
                heapq.heappush(heap, (-head.time, head))

        result = []

        # tc: O(F log k), at most F iterations each doing one pop and one push
        while heap and len(result) < self.FEED_SIZE:

            neg_time, node = heapq.heappop(heap)
            result.append(node.tweetId)

            # Advance this user's pointer to their next older tweet
            if node.next:
                heapq.heappush(heap, (-node.next.time, node.next))

        return result

Solution 3: Bounded Per User Deque + nlargest [TC Opt] - Heap/Heap

import heapq
from collections import defaultdict, deque

class Twitter:

    # IRL Use Case:
    # Most practical for real apps, a feed only ever shows FEED_SIZE tweets,
    # so there is no reason to store or scan more than FEED_SIZE per user.

    # Note:
    # - Tweets: deque(maxlen=FEED_SIZE) per user, the deque evicts the oldest
    #   tweet automatically on append
    # - News Feed: every user contributes at most FEED_SIZE candidates,
    #   gather all candidates and take the FEED_SIZE largest by time
    # - Why this is correct: the top 10 overall can contain at most 10 tweets
    #   from any single user, so each user's 10 newest tweets are a
    #   sufficient candidate set
    # - Tuples are (time, tweetId), time is unique so ordering is by time only
    # - Why TC Opt: F is a constant, so this is O(k) versus O(k log k) for the
    #   heap merge in Solutions 1 and 2, no per-user pointer/heap bookkeeping
    # - Pros: simplest code, bounded memory, no manual eviction
    # - Cons: scans up to k * F candidates even when the feed would be
    #   satisfied by a few users, heap merge can stop after F pops

    FEED_SIZE = 10

    # overall: sc O(U * F + E) for U users, F = FEED_SIZE, E follow edges
    def __init__(self):

        # userId -> deque of (time, tweetId) capped at FEED_SIZE
        # sc: O(U * F)
        self.tweets = defaultdict(lambda: deque(maxlen=self.FEED_SIZE))

        # followerId -> set of followeeIds
        # sc: O(E)
        self.followees = defaultdict(set)

        # Global counter for ordering tweets
        self.time = 0

    # overall: tc O(1)
    # overall: sc O(1), bounded by maxlen
    def postTweet(self, userId: int, tweetId: int) -> None:

        self.time += 1

        # maxlen drops the oldest tweet automatically when full
        # tc: O(1)
        self.tweets[userId].append((self.time, tweetId))

    # overall: tc O(1)
    # overall: sc O(1)
    def follow(self, followerId: int, followeeId: int) -> None:

        # tc: O(1) set add
        if followerId != followeeId:
            self.followees[followerId].add(followeeId)

    # overall: tc O(1)
    # overall: sc O(1)
    def unfollow(self, followerId: int, followeeId: int) -> None:

        # tc: O(1) set discard
        self.followees[followerId].discard(followeeId)

    # overall: tc O(k * F log F) for k = followees + 1, F = FEED_SIZE
    #          ~ O(k) since F is constant
    # overall: sc O(k * F) ~ O(k)
    def getNewsFeed(self, userId: int) -> list[int]:

        # Users to pull tweets from: self + followees
        # tc: O(k) to build the union
        users = self.followees[userId] | {userId}

        # Gather up to F newest tweets from every user
        # .get avoids creating empty deques for users who never tweeted
        # tc: O(k * F)
        # sc: O(k * F)
        candidates = []
        for u in users:
            candidates.extend(self.tweets.get(u, ()))

        # Keeps a size F heap while scanning, largest time first
        # tc: O(k * F log F)
        top = heapq.nlargest(self.FEED_SIZE, candidates)

        return [tweetId for _, tweetId in top]

225. Implement Stack using Queues ::1:: - Easy

Topics: Stack, Design, Queue

Intro

Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push, top, pop, and empty). Implement the MyStack class: void push(int x) Pushes element x to the top of the stack. int pop() Removes the element on the top of the stack and returns it. int top() Returns the element on the top of the stack. boolean empty() Returns true if the stack is empty, false otherwise. Notes: You must use only standard operations of a queue, which means that only push to back, peek/pop from front, size and is empty operations are valid. Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. Follow-up: Can you implement the stack using only one queue?

InputOutput
["MyStack", "push", "push", "top", "pop", "empty"] [[], [1], [2], [], [], []][null, null, null, 2, 2, false]

Constraints:

1 ≤ x ≤ 9

At most 100 calls will be made to push, pop, top, and empty.

All the calls to pop and top are valid.

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: [Stack] Lazy Transfer From In LIFO Stack To Out FIFO Stack [TC Opt] - Stack/Design Queue Using Stack

from collections import deque

class MyStack:

    # Note:
    # - use a single queue, the front of the queue is always the top of the stack
    # - on push, add the new element to the back, then rotate every older element
    #   behind it, so the new element ends up at the front
    # - this makes pop, top, and empty trivial since the top is always at the front
    # - only standard queue operations used: push to back, pop/peek front, size, is empty
    # - tradeoff: push is O(n), pop and top are O(1)

    # overall: sc O(n) for n elements
    def __init__(self):

        self.q = deque()

    # overall: tc O(n)
    # overall: sc O(1)
    def push(self, x: int) -> None:

        # tc: O(1)
        self.q.append(x)

        # Rotate all older elements behind the new one
        # so the newest element is now at the front
        # tc: O(n)
        for _ in range(len(self.q) - 1):
            self.q.append(self.q.popleft())

    # overall: tc O(1)
    # overall: sc O(1)
    def pop(self) -> int:

        # Front of the queue is the top of the stack
        return self.q.popleft()

    # overall: tc O(1)
    # overall: sc O(1)
    def top(self) -> int:

        return self.q[0]

    # overall: tc O(1)
    # overall: sc O(1)
    def empty(self) -> bool:

        return len(self.q) == 0

232. Implement Queue using Stacks ::1:: - Easy

Topics: Stack, Design, Queue

Intro

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty). Implement the MyQueue class: void push(int x) Pushes element x to the back of the queue. int pop() Removes the element from the front of the queue and returns it. int peek() Returns the element at the front of the queue. boolean empty() Returns true if the queue is empty, false otherwise. Notes: You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid. Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. Follow-up: Can you implement the queue such that each operation is amortized O(1) time complexity? In other words, performing n operations will take overall O(n) time even if one of those operations may take longer.

InputOutput
["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []][null, null, null, 1, 1, false]

Constraints:

1 ≤ x ≤ 9

At most 100 calls will be made to push, pop, peek, and empty.

All the calls to pop and peek are valid.

Abstract

something!

Pseudocode

Sol 1: Lazy Transfer In Stack Out Stack
1. def __init__(self):
    a. (self.inStack = [])
    b. (self.outStack = [])

2. _transfer():
    a. if not self.outStack:
         while self.inStack:
             self.outStack.append(self.inStack.pop())

3. push(x):
    a. self.inStack.append(x)

4. pop():
    a. self._transfer()
    b. return self.outStack.pop()

5. peek():
    a. self._transfer()
    b. return self.outStack[-1]

6. empty():
    a. return not self.inStack and not self.outStack

Solution 1: [Stack] Lazy Transfer From In LIFO Stack To Out FIFO Stack [TC Opt] - Stack/Design Queue Using Stack

class MyQueue:

    def __init__(self):

        # Two Stacks (In LIFO / Out FIFO):
        # - In stack holds elements in LIFO order, stored here until transferred
        # - Out stack holds elements in FIFO order, which are passed by switching from LIFO to FIFO

        # Lazy Transfer:
        # - Only transfer when out FIFO stack is empty and we need some element
        # - Transfer all elements current in LIFO In Stack to FIFO Out Stack
        # - All elem moved In to Out at most once, transfer is O(1) amortized across calls

        # In stack: 
        # - LIFO which wait to be transferred
        # sc: O(n)
        self.inStack = []

        # Out stack:
        # - FIFO order via reversing via grabbing from the top of the LIFO stack
        # sc: O(n)
        self.outStack = []


    # Transfer:
    # tc: O(n)
    def _transfer(self) -> None:

        # Ran out of FIFO elements
        if not self.outStack:

            # Transfer entire LIFO element to FIFO stack
            while self.inStack:

                # Grab and push
                elem = self.inStack.pop()
                self.outStack.append(elem)

    # Push:
    # tc: O(1)
    def push(self, x: int) -> None:

        # Push to LIFO stack, will eventually be transferred
        self.inStack.append(x)

    # Pop:
    # tc: O(1) amortized, 
    # tc: occasional O(n) transfer across many future O(1) calls
    def pop(self) -> int:

        # Check if LIFO is empty, and transfer if necessary
        self._transfer()

        # LIFO guaranteed to have at least 1 element
        return self.outStack.pop()

    # Peek:
    # tc: O(1) amortized
    # tc: occasional O(n) transfer across many future O(1) calls
    def peek(self) -> int:

        # Check if LIFO is empty, and transfer if necessary
        self._transfer()

        # LIFO guaranteed to have at least 1 element
        return self.outStack[-1]

    # Empty:
    # tc: O(1)
    def empty(self) -> bool:

        # Both LIFO and FIFO are empty
        return not self.inStack and not self.outStack


    # overall: tc O(1) amortized, O(n)
    # overall: sc O(n)

622. Design Circular Queue ::1:: - Easy

Topics: Array, Linked List, Design, Queue

Intro

Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. Implement the MyCircularQueue class: MyCircularQueue(k) Initializes the object with the size of the queue to be k. int Front() Gets the front item from the queue. If the queue is empty, return -1. int Rear() Gets the last item from the queue. If the queue is empty, return -1. boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful. boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful. boolean isEmpty() Checks whether the circular queue is empty or not. boolean isFull() Checks whether the circular queue is full or not. You must solve the problem without using the built-in queue data structure in your programming language.

InputOutput
["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"] [[3], [1], [2], [3], [4], [], [], [], [4], []][null, true, true, true, false, 3, true, true, true, 4]

Constraints:

1 ≤ k ≤ 1000

0 ≤ value ≤ 1000

At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.

Abstract

something!

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: [Stack] Lazy Transfer From In LIFO Stack To Out FIFO Stack [TC Opt] - Stack/Design Queue Using Stack

class MyCircularQueue:

    # Note:
    # - fixed size array of capacity k, reused as a ring
    # - head: index of the front element
    # - size: number of elements currently stored
    # - rear index is derived, not stored: (head + size - 1) % k
    # - enqueue writes at (head + size) % k, the first free slot after the rear
    # - dequeue advances head by one, wrapping with % k
    # - tracking size (instead of a tail pointer) removes the empty vs full ambiguity,
    #   since head == tail alone cannot tell the two states apart
    # - no built-in queue used, only a list as fixed storage

    # overall: sc O(k) for capacity k
    def __init__(self, k: int):

        self.capacity = k
        self.data = [0] * k
        self.head = 0
        self.size = 0

    # overall: tc O(1)
    # overall: sc O(1)
    def enQueue(self, value: int) -> bool:

        # No free slot
        if self.isFull():
            return False

        # Write into the first free slot after the rear, wrapping around
        # tc: O(1)
        self.data[(self.head + self.size) % self.capacity] = value
        self.size += 1

        return True

    # overall: tc O(1)
    # overall: sc O(1)
    def deQueue(self) -> bool:

        # Nothing to remove
        if self.isEmpty():
            return False

        # Advance head, the old front slot is now free to overwrite
        # tc: O(1)
        self.head = (self.head + 1) % self.capacity
        self.size -= 1

        return True

    # overall: tc O(1)
    # overall: sc O(1)
    def Front(self) -> int:

        if self.isEmpty():
            return -1

        return self.data[self.head]

    # overall: tc O(1)
    # overall: sc O(1)
    def Rear(self) -> int:

        if self.isEmpty():
            return -1

        # Rear is the last stored element, wrapping around
        return self.data[(self.head + self.size - 1) % self.capacity]

    # overall: tc O(1)
    # overall: sc O(1)
    def isEmpty(self) -> bool:

        return self.size == 0

    # overall: tc O(1)
    # overall: sc O(1)
    def isFull(self) -> bool:

        return self.size == self.capacity

155. Min Stack ::2:: - Medium

Topics: Stack, Design

Intro

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class: MinStack() initializes the stack object. void push(int val) pushes the element val onto the stack. void pop() removes the element on the top of the stack. int top() gets the top element of the stack. int getMin() retrieves the minimum element in the stack. You must implement a solution with O(1) time complexity for each function.

InputOutput
["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]][null,null,null,null,-3,null,0,-2]

Constraints:

-231 ≤ val ≤ 231 - 1

Methods pop, top and getMin operations will always be called on non-empty stacks.

At most 3 * 104 calls will be made to push, pop, top, and getMin.

Abstract

We need to design a stack that runs in O(1) time complexity for each main function.

Pseudocode

Sol 1: Tuple Stack Manual Size Pointer To Avoid Inbuilt Pop()

1. self.stack = [], self.size = 0

_overwriteCheck():
1. return self.size < len(self.stack)

push(val):
1. if self.size > 0:
    currMin = min(val, self.stack[self.size-1][1])
2. else:
    currMin = val
3. if self._overwriteCheck():
    self.stack[self.size] = (val, currMin)
4. else:
    self.stack.append((val, currMin))
5. self.size += 1

pop():
1. self.size -= 1

top():
1. return self.stack[self.size-1][0]

getMin():
1. return self.stack[self.size-1][1]


Sol 2: Stack Using Inbuilt Pop() and Push()

1. self.stack = []

push(val):
1. if self.stack:
    a. currMin = min(self.stack[-1][1], val)
2. else:
    a. currMin = val
3. self.stack.append((val, currMin))

pop():
1. self.stack.pop()

top():
1. return self.stack[-1][0]

getMin():
1. return self.stack[-1][1]

Solution 1: [Stack] Tuple Stack Manual Size Pointer To Avoid Inbuilt Pop() - Stack/Dynamic Programming State Compression

class MinStack:

    # MinStack:
    # Track 2 things
    #   - Top Of Stack
    #   - Min val

    # Push(), Pop(), Top(), GetMin():
    # - all in O(1)
    # - may need to update the above 2 details:

    # Stack:
    # Tuple Representing (Top Of Stack, Min At Level):
    
    #          (7, 1)       5
    #          (4, 1)       4
    #          (1, 1)       3
    #          (7, 5)       2
    #          (5, 5)       1
    #           Stack     Level

    def __init__(self):

        # Tuple Stack: (top of stack, min up to this level):
        # sc: O(n)
        self.stack = []
        self.size = 0
 
    # Helper:
    # If size pointer is behind actual length of stack, we overwrite a value when we push
    # If size pointer is accurate to length of stack, we simply append to the end of the stack 
    def _overwriteCheck(self):
        return self.size < len(self.stack)

    # Push():
    def push(self, val: int):

        # If some min exists, compare
        # else new value automatically update to new value
        if self.size > 0:
            currMin = min(val, self.stack[self.size-1][1])
        else:
            currMin = val
        
        # Overwrite, pointer is not at actual top of stack
        if self._overwriteCheck():
            self.stack[self.size] = (val, currMin)

        # No overwrite, append to end of stack
        else:
            self.stack.append((val, currMin))

        # Adjust pointer to new top of stack
        self.size += 1

    # Pop():
    def pop(self):

        # Adjust pointer to new top of stack,
        # allows us to pop without using the inbuilt pop(),
        # however, this now requires us to use an overwrite in push()
        # since actual stack memory size may differ from the pointer length
        self.size -= 1

    # Top():
    def top(self):

        # Grab val at top of stack
        return self.stack[self.size - 1][0]

    # GetMin():
    def getMin(self):

        # Grab min at current level
        return self.stack[self.size - 1][1]

    # overall: tc O(1)
    # overall: sc O(n)

Solution 2: [Stack] Stack Using Inbuilt Pop() and Push() - Stack/Dynamic Programming State Compression

class MinStack:

    # MinStack:
    # Track 2 things
    #   - Top Of Stack
    #   - Min val

    # Push(), Pop(), Top(), GetMin():
    # - all in O(1)
    # - may need to update the above 2 details:

    # Stack:
    # Tuple Representing (Top Of Stack, Min At Level):
    
    #          (7, 1)       5
    #          (4, 1)       4
    #          (1, 1)       3
    #          (7, 5)       2
    #          (5, 5)       1
    #           Stack     Level

    def __init__(self):
        
        # Tuple Stack: (top of stack, min up to this level):
        # sc: O(n)
        self.stack = []

    # Push():
    def push(self, val: int):

        # Compare new val to curr stack min
        if self.stack:
            currMin = min(self.stack[-1][1], val)
        else:
            currMin = val

        self.stack.append((val, currMin))

    # Pop():
    def pop(self):
        
        # Remove item at top of stack, 
        # new min automatically updates to new top
        self.stack.pop()

    # Top():
    def top(self):

        # View top of stack val
        return self.stack[-1][0]

    # GetMin():
    def getMin(self):

        # View top of stack min
        return self.stack[-1][1]

895. Maximum Frequency Stack ::1:: - Hard

Topics: Hash Table, Stack, Design, Ordered Set

Intro

Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the FreqStack class: FreqStack() constructs an empty frequency stack. void push(int val) pushes an integer val onto the top of the stack. int pop() removes and returns the most frequent element in the stack. If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.

InputOutput
["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"] [[], [5], [7], [5], [7], [4], [5], [], [], [], []][null, null, null, null, null, null, null, 5, 7, 5, 4]

Constraints:

0 ≤ val ≤ 10^9

At most 2 * 10^4 calls will be made to push and pop.

It is guaranteed that there will be at least one element in the stack before calling pop.

Abstract

Design a max stack??

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Frequency Map + Stack Per Frequency Group [TC Opt] - Hashmap/Design

from collections import defaultdict

class FreqStack:

    # Note:
    # - freq: val -> how many times val is currently in the stack
    # - group: frequency -> stack of values that reached that frequency, in push order
    #   a value pushed for the 3rd time is appended to group[3]
    #   it also stays in group[1] and group[2] from its earlier pushes
    # - max_freq: highest frequency currently in the stack
    # - pop takes the top of group[max_freq]
    #   ties on frequency are broken by recency for free, since each group
    #   is a stack and the most recently pushed value sits on top
    # - after a pop, decrement the value's frequency
    #   the value is still present in lower groups from its earlier pushes
    # - if group[max_freq] empties, max_freq drops by one
    #   no scan needed, frequencies increase one at a time so the next
    #   highest non-empty group is always max_freq - 1

    # overall: sc O(n) for n pushed elements
    def __init__(self):

        self.freq = defaultdict(int)
        self.group = defaultdict(list)
        self.max_freq = 0

    # overall: tc O(1)
    # overall: sc O(1)
    def push(self, val: int) -> None:

        # Value now appears one more time
        # tc: O(1)
        self.freq[val] += 1
        f = self.freq[val]

        # Track the highest frequency seen
        if f > self.max_freq:
            self.max_freq = f

        # Record the push in the group for its new frequency
        # tc: O(1)
        self.group[f].append(val)

    # overall: tc O(1)
    # overall: sc O(1)
    def pop(self) -> int:

        # Most recent value among those with the highest frequency
        # tc: O(1)
        val = self.group[self.max_freq].pop()

        # Value now appears one fewer time
        self.freq[val] -= 1

        # Top group emptied, next highest frequency is one lower
        if not self.group[self.max_freq]:
            self.max_freq -= 1

        return val

705. Design HashSet ::1:: - Easy

Topics: Array, Hash Table, Linked List, Design, Hash Function

Intro

Design a HashSet without using any built-in hash table libraries. Implement MyHashSet class: void add(key) Inserts the value key into the HashSet. bool contains(key) Returns whether the value key exists in the HashSet or not. void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing.

InputOutput
["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"] [[], [1], [2], [1], [3], [2], [2], [2], [2]][null, null, null, true, false, null, true, null, false]

Constraints:

0 ≤ key ≤ 10^6

At most 10^4 calls will be made to add, remove, and contains.

Abstract

We need to make a hashset

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Separate Chaining Buckets [TC Opt] - Hashmap/Design

class MyHashSet:

    # Note:
    # - fixed number of buckets, each bucket is a list (chain) of keys
    # - hash function maps a key to a bucket index: key % size
    # - keys that collide land in the same bucket and are stored in its chain
    # - use a prime bucket count (769) to spread keys evenly and reduce collisions
    # - no built-in hash table used, only lists

    # overall: sc O(k + n) for k buckets and n keys
    def __init__(self):

        self.size = 769
        self.buckets = [[] for _ in range(self.size)]

    # overall: tc O(1)
    # overall: sc O(1)
    def _hash(self, key: int) -> int:

        return key % self.size

    # overall: tc O(n / k) avg ~ O(1), O(n) worst if all keys collide
    # overall: sc O(1)
    def add(self, key: int) -> None:

        bucket = self.buckets[self._hash(key)]

        # Only insert if not already present, sets have no duplicates
        # tc: O(n / k) avg to scan the chain
        if key not in bucket:
            bucket.append(key)

    # overall: tc O(n / k) avg ~ O(1), O(n) worst if all keys collide
    # overall: sc O(1)
    def remove(self, key: int) -> None:

        bucket = self.buckets[self._hash(key)]

        # Key does not exist, do nothing
        # tc: O(n / k) avg to scan the chain
        if key in bucket:
            bucket.remove(key)

    # overall: tc O(n / k) avg ~ O(1), O(n) worst if all keys collide
    # overall: sc O(1)
    def contains(self, key: int) -> bool:

        bucket = self.buckets[self._hash(key)]

        # tc: O(n / k) avg to scan the chain
        return key in bucket

706. Design HashMap ::1:: - Easy

Topics: Array, Hash Table, Linked List, Design, Hash Function

Intro

Design a HashMap without using any built in hash table libraries. Implement the MyHashMap class: MyHashMap() initializes the object with an empty map. void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value. int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key. void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.

InputOutput
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]][null, null, null, 1, -1, null, 1, null, -1]

Constraints:

0 ≤ key, value ≤ 10^6

At most 10^4 calls will be made to put, get, and remove.

Abstract

We need to make a hashmap

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Separate Chaining Buckets [TC Opt] - Hashmap/Design

class MyHashMap:

    # Note:
    # - fixed number of buckets, each bucket is a list (chain) of [key, value] pairs
    # - hash function maps a key to a bucket index: key % size
    # - keys that collide land in the same bucket and are stored in its chain
    # - use a prime bucket count (769) to spread keys evenly and reduce collisions
    # - no built-in hash table used, only lists

    # overall: sc O(k + n) for k buckets and n pairs
    def __init__(self):

        self.size = 769
        self.buckets = [[] for _ in range(self.size)]

    # overall: tc O(1)
    # overall: sc O(1)
    def _hash(self, key: int) -> int:

        return key % self.size

    # overall: tc O(n / k) avg ~ O(1), O(n) worst if all keys collide
    # overall: sc O(1)
    def put(self, key: int, value: int) -> None:

        bucket = self.buckets[self._hash(key)]

        # Key already exists, update its value
        # tc: O(n / k) avg to scan the chain
        for pair in bucket:
            if pair[0] == key:
                pair[1] = value
                return

        # Key not found, add new pair
        bucket.append([key, value])

    # overall: tc O(n / k) avg ~ O(1), O(n) worst if all keys collide
    # overall: sc O(1)
    def get(self, key: int) -> int:

        bucket = self.buckets[self._hash(key)]

        # tc: O(n / k) avg to scan the chain
        for k, v in bucket:
            if k == key:
                return v

        # Key does not exist
        return -1

    # overall: tc O(n / k) avg ~ O(1), O(n) worst if all keys collide
    # overall: sc O(1)
    def remove(self, key: int) -> None:

        bucket = self.buckets[self._hash(key)]

        # tc: O(n / k) avg to scan the chain
        for i, pair in enumerate(bucket):
            if pair[0] == key:

                # Safe to delete mid-iteration since we return immediately
                del bucket[i]
                return

676. Implement Magic Dictionary ::1:: - Medium

Topics: Hash Table, String, Depth First Search, Design, Trie

Intro

Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure. Implement the MagicDictionary class: MagicDictionary() Initializes the object. void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary. bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.

InputOutput
["MagicDictionary", "buildDict", "search", "search", "search", "search"] [[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]][null, null, false, true, false, false]

Constraints:

1 ≤ dictionary.length ≤ 100

1 ≤ dictionary[i].length ≤ 100

dictionary[i] consists of only lower-case English letters.

All the strings in dictionary are distinct.

1 ≤ searchWord.length ≤ 100

searchWord consists of only lower-case English letters.

buildDict will be called only once before search.

At most 100 calls will be made to search.

Abstract

We need to make a hashmap

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Group By Length + Character Diff Count [SC Opt] - Hashmap/Design

from collections import defaultdict

class MagicDictionary:

    # Note:
    # - group dictionary words by length, words of different lengths can never
    #   differ by exactly one character
    # - on search, compare the searchWord against every word of the same length
    # - count mismatched characters, exit early once the count passes one
    # - exactly one change is required, so zero mismatches (identical word) is not a match
    # - tradeoff: cheap to build and store, but every search scans a length group
    #   wildcard pattern hashmap makes search O(L^2) at the cost of O(N * L^2) space

    # overall: sc O(N) for N words, words stored by reference
    def __init__(self):

        self.len_to_words = defaultdict(list)

    # overall: tc O(N)
    # overall: sc O(N)
    def buildDict(self, dictionary: list[str]) -> None:

        # tc: O(1) per word
        for word in dictionary:
            self.len_to_words[len(word)].append(word)

    # overall: tc O(k * L) for k words of the same length, O(N * L) worst case
    # overall: sc O(1)
    def search(self, searchWord: str) -> bool:

        # get does not insert empty groups into the defaultdict
        # tc: O(1)
        for word in self.len_to_words.get(len(searchWord), []):
            if self._one_diff(searchWord, word):
                return True

        return False

    # overall: tc O(L)
    # overall: sc O(1)
    def _one_diff(self, a: str, b: str) -> bool:

        diffs = 0

        # tc: O(L)
        for x, y in zip(a, b):
            if x != y:
                diffs += 1

                # More than one mismatch, cannot match
                if diffs > 1:
                    return False

        return diffs == 1

Solution 2: Wildcard Pattern Counts Hashmap [TC Opt] - Hashmap/Design

from collections import defaultdict

class MagicDictionary:

    # Note:
    # - for each word, replace one character at a time with a wildcard "*"
    #   "hello" -> "*ello", "h*llo", "he*lo", "hel*o", "hell*"
    # - two words differ by exactly one character iff they share a wildcard pattern
    #   and are not the same word
    # - patterns embed word length, so words of different lengths never match
    # - store pattern -> count of dictionary words that generate it
    # - store the dictionary words in a set to detect the searchWord itself
    # - the searchWord generates the same patterns as itself, so if it is in the dictionary
    #   it contributes 1 to every one of its own pattern counts
    #   subtract that 1, a match needs at least one OTHER word with the same pattern
    # - exactly one change is required, so an identical word does not count as a match
    # - tradeoff: pays O(L) extra memory per word per position to make search O(L^2)
    #   instead of scanning every dictionary word

    # overall: sc O(N * L^2) for N words of length L
    def __init__(self):

        self.words = set()
        self.patterns = defaultdict(int)

    # overall: tc O(N * L^2) each of L patterns costs O(L) to build and hash
    # overall: sc O(N * L^2)
    def buildDict(self, dictionary: list[str]) -> None:

        for word in dictionary:
            self.words.add(word)

            # Generate every one-wildcard pattern for this word
            # tc: O(L) patterns, O(L) each to slice and hash
            for i in range(len(word)):
                pattern = word[:i] + "*" + word[i + 1:]
                self.patterns[pattern] += 1

    # overall: tc O(L^2) L patterns, O(L) each to build and hash
    # overall: sc O(L) for the pattern string
    def search(self, searchWord: str) -> bool:

        # The searchWord counts toward its own patterns if it is in the dictionary
        # tc: O(L) to hash the word
        self_count = 1 if searchWord in self.words else 0

        # Try replacing each position with a wildcard
        # tc: O(L) patterns, O(L) each to slice and hash
        for i in range(len(searchWord)):
            pattern = searchWord[:i] + "*" + searchWord[i + 1:]

            # Some other word shares this pattern, exactly one character differs
            if self.patterns.get(pattern, 0) > self_count:
                return True

        return False

707. Design Linked List ::1:: - Medium

Topics: Linked List, Design

Intro

Design your implementation of the linked list. You can choose to use a singly or doubly linked list. A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. Implement the MyLinkedList class: MyLinkedList() Initializes the MyLinkedList object. int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1. void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. void addAtTail(int val) Append a node of value val as the last element of the linked list. void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted. void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.

InputOutput
["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] [[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]][null, null, null, 1, -1, null, 1, null, -1]

Constraints:

0 ≤ key, value ≤ 10^6

At most 10^4 calls will be made to put, get, and remove.

Abstract

We need to make a hashmap

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Separate Chaining Buckets [TC Opt] - Hashmap/Design

class Node:

    def __init__(self, val: int = 0):

        self.val = val
        self.prev = None
        self.next = None


class MyLinkedList:

    # Note:
    # - doubly linked list with dummy head and dummy tail sentinels
    # - sentinels remove edge cases, every real node always has a prev and next
    # - track size so index validity is an O(1) check
    # - traverse from whichever end is closer to the index, halving the worst case
    # - addAtHead / addAtTail are O(1) since sentinels give direct access to both ends

    # overall: sc O(n) for n nodes
    def __init__(self):

        self.head = Node()
        self.tail = Node()
        self.head.next = self.tail
        self.tail.prev = self.head
        self.size = 0

    # overall: tc O(min(i, n - i)) ~ O(n)
    # overall: sc O(1)
    def _get_node(self, index: int) -> Node:

        # Index in first half, walk forward from head
        # tc: O(i)
        if index < self.size // 2:
            curr = self.head.next
            for _ in range(index):
                curr = curr.next

        # Index in second half, walk backward from tail
        # tc: O(n - i)
        else:
            curr = self.tail.prev
            for _ in range(self.size - 1 - index):
                curr = curr.prev

        return curr

    # overall: tc O(1)
    # overall: sc O(1)
    def _insert_before(self, node: Node, val: int) -> None:

        new = Node(val)
        prev = node.prev

        # Wire new node between prev and node
        new.prev = prev
        new.next = node
        prev.next = new
        node.prev = new

        self.size += 1

    # overall: tc O(min(i, n - i)) ~ O(n)
    # overall: sc O(1)
    def get(self, index: int) -> int:

        # Invalid index
        if index < 0 or index >= self.size:
            return -1

        return self._get_node(index).val

    # overall: tc O(1)
    # overall: sc O(1)
    def addAtHead(self, val: int) -> None:

        # Insert before the first real node
        self._insert_before(self.head.next, val)

    # overall: tc O(1)
    # overall: sc O(1)
    def addAtTail(self, val: int) -> None:

        # Insert before the tail sentinel
        self._insert_before(self.tail, val)

    # overall: tc O(min(i, n - i)) ~ O(n)
    # overall: sc O(1)
    def addAtIndex(self, index: int, val: int) -> None:

        # Invalid index, do nothing
        if index < 0 or index > self.size:
            return

        # Index equals length, append at tail
        # tc: O(1)
        if index == self.size:
            self._insert_before(self.tail, val)
            return

        # Insert before the current node at index
        # tc: O(min(i, n - i))
        self._insert_before(self._get_node(index), val)

    # overall: tc O(min(i, n - i)) ~ O(n)
    # overall: sc O(1)
    def deleteAtIndex(self, index: int) -> None:

        # Invalid index, do nothing
        if index < 0 or index >= self.size:
            return

        # tc: O(min(i, n - i))
        node = self._get_node(index)

        # Bypass the node, its neighbors now point to each other
        node.prev.next = node.next
        node.next.prev = node.prev

        self.size -= 1

1845. Seat Reservation Manager ::1:: - Medium

Topics: Linked List, Design

Intro

Design a system that manages the reservation state of n seats that are numbered from 1 to n. Implement the SeatManager class: SeatManager(int n) Initializes a SeatManager object that will manage n seats numbered from 1 to n. All seats are initially available. int reserve() Fetches the smallest-numbered unreserved seat, reserves it, and returns its number. void unreserve(int seatNumber) Unreserves the seat with the given seatNumber.

InputOutput
["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"] [[5], [], [], [2], [], [], [], [], [5]][null, 1, 2, null, 2, 3, 4, 5, null]

Constraints:

1 ≤ n ≤ 10^5

1 ≤ seatNumber ≤ n

For each call to reserve, it is guaranteed that there will be at least one unreserved seat.

For each call to unreserve, it is guaranteed that seatNumber will be reserved.

At most 10^5 calls in total will be made to reserve and unreserve.

Abstract

We need to make a reservation system

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Separate Chaining Buckets [TC Opt] - Hashmap/Design

class Node:

    def __init__(self, val: int = 0):

        self.val = val
        self.prev = None
        self.next = None


class MyLinkedList:

    # Note:
    # - doubly linked list with dummy head and dummy tail sentinels
    # - sentinels remove edge cases, every real node always has a prev and next
    # - track size so index validity is an O(1) check
    # - traverse from whichever end is closer to the index, halving the worst case
    # - addAtHead / addAtTail are O(1) since sentinels give direct access to both ends

    # overall: sc O(n) for n nodes
    def __init__(self):

        self.head = Node()
        self.tail = Node()
        self.head.next = self.tail
        self.tail.prev = self.head
        self.size = 0

    # overall: tc O(min(i, n - i)) ~ O(n)
    # overall: sc O(1)
    def _get_node(self, index: int) -> Node:

        # Index in first half, walk forward from head
        # tc: O(i)
        if index < self.size // 2:
            curr = self.head.next
            for _ in range(index):
                curr = curr.next

        # Index in second half, walk backward from tail
        # tc: O(n - i)
        else:
            curr = self.tail.prev
            for _ in range(self.size - 1 - index):
                curr = curr.prev

        return curr

    # overall: tc O(1)
    # overall: sc O(1)
    def _insert_before(self, node: Node, val: int) -> None:

        new = Node(val)
        prev = node.prev

        # Wire new node between prev and node
        new.prev = prev
        new.next = node
        prev.next = new
        node.prev = new

        self.size += 1

    # overall: tc O(min(i, n - i)) ~ O(n)
    # overall: sc O(1)
    def get(self, index: int) -> int:

        # Invalid index
        if index < 0 or index >= self.size:
            return -1

        return self._get_node(index).val

    # overall: tc O(1)
    # overall: sc O(1)
    def addAtHead(self, val: int) -> None:

        # Insert before the first real node
        self._insert_before(self.head.next, val)

    # overall: tc O(1)
    # overall: sc O(1)
    def addAtTail(self, val: int) -> None:

        # Insert before the tail sentinel
        self._insert_before(self.tail, val)

    # overall: tc O(min(i, n - i)) ~ O(n)
    # overall: sc O(1)
    def addAtIndex(self, index: int, val: int) -> None:

        # Invalid index, do nothing
        if index < 0 or index > self.size:
            return

        # Index equals length, append at tail
        # tc: O(1)
        if index == self.size:
            self._insert_before(self.tail, val)
            return

        # Insert before the current node at index
        # tc: O(min(i, n - i))
        self._insert_before(self._get_node(index), val)

    # overall: tc O(min(i, n - i)) ~ O(n)
    # overall: sc O(1)
    def deleteAtIndex(self, index: int) -> None:

        # Invalid index, do nothing
        if index < 0 or index >= self.size:
            return

        # tc: O(min(i, n - i))
        node = self._get_node(index)

        # Bypass the node, its neighbors now point to each other
        node.prev.next = node.next
        node.next.prev = node.prev

        self.size -= 1

460. LFU Cache ::1:: - Hard

Topics: Hash Table, Linked List, Design, Doubly Linked List

Intro

Design and implement a data structure for a Least Frequently Used (LFU) cache. Implement the LFUCache class: LFUCache(int capacity) Initializes the object with the capacity of the data structure. int get(int key) Gets the value of the key if the key exists in the cache. Otherwise, returns -1. void put(int key, int value) Update the value of the key if present, or inserts the key if not already present. When the cache reaches its capacity, it should invalidate and remove the least frequently used key before inserting a new item. For this problem, when there is a tie (i.e., two or more keys with the same frequency), the least recently used key would be invalidated. To determine the least frequently used key, a use counter is maintained for each key in the cache. The key with the smallest use counter is the least frequently used key. When a key is first inserted into the cache, its use counter is set to 1 (due to the put operation). The use counter for a key in the cache is incremented either a get or put operation is called on it. The functions get and put must each run in O(1) average time complexity.

InputOutput
["SeatManager", "reserve", "reserve", "unreserve", "reserve", "reserve", "reserve", "reserve", "unreserve"] [[5], [], [], [2], [], [], [], [], [5]][null, 1, 2, null, 2, 3, 4, 5, null]

Constraints:

1 ≤ capacity ≤ 10^4

0 ≤ key ≤ 10^5

0 ≤ value ≤ 10^9

At most 2 * 105 calls will be made to get and put.

Abstract

We need to make a LFU

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Frequency Buckets Of Ordered Keys + Min Frequency [TC Opt] - Hashmap/Design

from collections import defaultdict, OrderedDict

class LFUCache:

    # Note:
    # - key_to_val: key -> value for O(1) lookup
    # - key_to_freq: key -> use counter for O(1) frequency lookup
    # - freq_to_keys: frequency -> OrderedDict of keys, ordered oldest to newest use
    #   the OrderedDict acts as an LRU list per frequency, breaking ties by recency
    # - min_freq: smallest frequency currently in the cache
    #   the eviction candidate is the oldest key in freq_to_keys[min_freq]
    # - on every get / put of an existing key, move it from bucket f to bucket f + 1
    # - if bucket f empties and f was min_freq, min_freq becomes f + 1
    # - on insert of a new key, min_freq resets to 1 since a new key always has frequency 1
    # - no need to scan for min_freq, it only changes in these two cases

    # overall: sc O(capacity)
    def __init__(self, capacity: int):

        self.capacity = capacity
        self.min_freq = 0

        self.key_to_val = {}
        self.key_to_freq = {}
        self.freq_to_keys = defaultdict(OrderedDict)

    # overall: tc O(1)
    # overall: sc O(1)
    def _touch(self, key: int) -> None:

        freq = self.key_to_freq[key]

        # Remove key from its current frequency bucket
        # tc: O(1)
        del self.freq_to_keys[freq][key]

        # Bucket emptied, drop it and advance min_freq if it was the minimum
        if not self.freq_to_keys[freq]:
            del self.freq_to_keys[freq]

            if self.min_freq == freq:
                self.min_freq += 1

        # Add key to the next frequency bucket as the most recently used
        # tc: O(1)
        self.key_to_freq[key] = freq + 1
        self.freq_to_keys[freq + 1][key] = None

    # overall: tc O(1)
    # overall: sc O(1)
    def get(self, key: int) -> int:

        # Key does not exist
        if key not in self.key_to_val:
            return -1

        # Using a key increments its frequency
        self._touch(key)

        return self.key_to_val[key]

    # overall: tc O(1)
    # overall: sc O(1)
    def put(self, key: int, value: int) -> None:

        # Zero capacity cache can never store anything
        if self.capacity == 0:
            return

        # Key exists, update value and count it as a use
        if key in self.key_to_val:
            self.key_to_val[key] = value
            self._touch(key)
            return

        # Cache full, evict the least recently used key in the lowest frequency bucket
        if len(self.key_to_val) == self.capacity:

            # popitem(last=False) removes the oldest key in O(1)
            # tc: O(1)
            evict_key, _ = self.freq_to_keys[self.min_freq].popitem(last=False)

            if not self.freq_to_keys[self.min_freq]:
                del self.freq_to_keys[self.min_freq]

            del self.key_to_val[evict_key]
            del self.key_to_freq[evict_key]

        # Insert new key with frequency 1, which is now the minimum
        # tc: O(1)
        self.key_to_val[key] = value
        self.key_to_freq[key] = 1
        self.freq_to_keys[1][key] = None
        self.min_freq = 1

432. All Ol In One Data Structure ::1:: - Hard

Topics: Hash Table, Linked List, Design, Doubly Linked List

Intro

Design a data structure to store the strings count with the ability to return the strings with minimum and maximum counts. Implement the AllOne class: AllOne() Initializes the object of the data structure. inc(String key) Increments the count of the string key by 1. If key does not exist in the data structure, insert it with count 1. dec(String key) Decrements the count of the string key by 1. If the count of key is 0 after the decrement, remove it from the data structure. It is guaranteed that key exists in the data structure before the decrement. getMaxKey() Returns one of the keys with the maximal count. If no element exists, return an empty string "". getMinKey() Returns one of the keys with the minimum count. If no element exists, return an empty string "". Note that each function must run in O(1) average time complexity.

InputOutput
["AllOne", "inc", "inc", "getMaxKey", "getMinKey", "inc", "getMaxKey", "getMinKey"] [[], ["hello"], ["hello"], [], [], ["leet"], [], []][null, null, null, "hello", "hello", null, "hello", "leet"]

Constraints:

1 ≤ key.length ≤ 10

key consists of lowercase English letters.

It is guaranteed that for each call to dec, key is existing in the data structure.

At most 5 * 10^4 calls will be made to inc, dec, getMaxKey, and getMinKey.

Abstract

We need to make a LFU

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Doubly Linked List Of Count Buckets + Key To Bucket Hashmap [TC Opt] - Hashmap/Design

class Bucket:

    def __init__(self, count: int = 0):

        self.count = count
        self.keys = set()
        self.prev = None
        self.next = None


class AllOne:

    # Note:
    # - doubly linked list of buckets, sorted ascending by count
    #   each bucket holds the set of all keys that currently have that count
    # - head and tail sentinels (count 0) remove edge cases
    #   head.next is always the min bucket, tail.prev is always the max bucket
    # - key_to_bucket: key -> the bucket it currently lives in, for O(1) lookup
    # - inc / dec only ever move a key to the adjacent bucket (count + 1 or count - 1)
    #   so at most one new bucket is created, spliced in next to the current one
    # - empty buckets are removed immediately, so min / max are always at the ends
    # - sentinel count 0 never equals a real count (>= 1), 
    #   so one count check also covers the sentinel case

    # overall: sc O(n) for n distinct keys
    def __init__(self):

        self.head = Bucket()
        self.tail = Bucket()
        self.head.next = self.tail
        self.tail.prev = self.head

        self.key_to_bucket = {}

    # overall: tc O(1)
    # overall: sc O(1)
    def _insert_after(self, node: Bucket, count: int) -> Bucket:

        new = Bucket(count)
        nxt = node.next

        # Wire new bucket between node and nxt
        new.prev = node
        new.next = nxt
        node.next = new
        nxt.prev = new

        return new

    # overall: tc O(1)
    # overall: sc O(1)
    def _remove(self, node: Bucket) -> None:

        # Bypass the bucket, its neighbors now point to each other
        node.prev.next = node.next
        node.next.prev = node.prev

    # overall: tc O(1)
    # overall: sc O(1)
    def inc(self, key: int) -> None:

        # New key, belongs in the count 1 bucket right after head
        # tc: O(1)
        if key not in self.key_to_bucket:

            if self.head.next.count != 1:
                self._insert_after(self.head, 1)

            self.head.next.keys.add(key)
            self.key_to_bucket[key] = self.head.next
            return

        curr = self.key_to_bucket[key]

        # Next bucket is not count + 1, create it right after curr
        # tc: O(1)
        if curr.next.count != curr.count + 1:
            self._insert_after(curr, curr.count + 1)

        # Move key from curr to the count + 1 bucket
        nxt = curr.next
        nxt.keys.add(key)
        self.key_to_bucket[key] = nxt
        curr.keys.remove(key)

        # Drop bucket if it emptied
        if not curr.keys:
            self._remove(curr)

    # overall: tc O(1)
    # overall: sc O(1)
    def dec(self, key: int) -> None:

        curr = self.key_to_bucket[key]
        curr.keys.remove(key)

        # Count hits 0, key leaves the data structure entirely
        # tc: O(1)
        if curr.count == 1:
            del self.key_to_bucket[key]

        else:

            # Previous bucket is not count - 1, create it right before curr
            # tc: O(1)
            if curr.prev.count != curr.count - 1:
                self._insert_after(curr.prev, curr.count - 1)

            # Move key from curr to the count - 1 bucket
            prev = curr.prev
            prev.keys.add(key)
            self.key_to_bucket[key] = prev

        # Drop bucket if it emptied
        if not curr.keys:
            self._remove(curr)

    # overall: tc O(1)
    # overall: sc O(1)
    def getMaxKey(self) -> str:

        # Empty, only sentinels remain
        if self.tail.prev is self.head:
            return ""

        # Any key from the max bucket works
        return next(iter(self.tail.prev.keys))

    # overall: tc O(1)
    # overall: sc O(1)
    def getMinKey(self) -> str:

        # Empty, only sentinels remain
        if self.head.next is self.tail:
            return ""

        # Any key from the min bucket works
        return next(iter(self.head.next.keys))

348. Design Tic Tac Toe ::1:: - Medium

Topics: Hash Table, String, Design, Hash Function, Premium

Intro

This problem asks you to implement a Tic Tac Toe game for an n x n board that can determine the winner after each move. You need to create a TicTacToe class with two methods: TicTacToe(int n): Initializes a game board of size n x n int move(int row, int col, int player): Places a mark for the given player (1 or 2) at position (row, col) and returns: 0 if there's no winner yet 1 if player 1 wins 2 if player 2 wins A player wins when they successfully place n of their marks in: Any complete row Any complete column The main diagonal (from top-left to bottom-right) The anti-diagonal (from top-right to bottom-left) The solution uses a counting approach where it tracks how many marks each player has placed in each row, column, and diagonal. The key insight is to use a dictionary to count marks: Rows are indexed as 0 to n-1 Columns are indexed as n to 2n-1 Main diagonal is indexed as n lt lt 1 (which is 2n) Anti-diagonal is indexed as n lt lt 1 | 1 (which is 2n + 1) For each move, the solution increments the appropriate counters for that player's row, column, and potentially diagonals (if the move is on a diagonal). If any counter reaches n, that player has won. The main diagonal contains cells where row == col, and the anti-diagonal contains cells where row + col == n - 1. This clever indexing scheme allows checking for a win in O(1) time after each move.

Example InputOutput
findwhat

Constraints:

this is

Abstraction

Tic tick tack

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Signed Row Column Diagonal Counters [TC Opt] - Array/Design

class TicTacToe:

    # Note:
    # - a win needs n marks from one player in a full row, column, or diagonal
    # - no need to store the board, only track a counter per line
    # - use one signed counter per line instead of one per player:
    #   player 1 adds +1, player 2 adds -1
    # - a line is won when its counter reaches +n (player 1) or -n (player 2)
    #   |counter| == n only happens if every mark in the line is from one player
    # - rows and columns get an array of n counters each
    # - the main diagonal (row == col) and anti-diagonal (row + col == n - 1)
    #   each need just one counter
    # - the center cell of an odd sized board sits on both diagonals, so it updates both
    # - problem guarantees no moves are made after a win, so a counter
    #   reaching +n / -n can only come from the current move

    # overall: sc O(n) for n row counters and n column counters
    def __init__(self, n: int):

        self.n = n
        self.rows = [0] * n
        self.cols = [0] * n
        self.diag = 0
        self.anti_diag = 0

    # overall: tc O(1)
    # overall: sc O(1)
    def move(self, row: int, col: int, player: int) -> int:

        # Player 1 counts up, player 2 counts down
        delta = 1 if player == 1 else -1

        # Update the row and column this move belongs to
        # tc: O(1)
        self.rows[row] += delta
        self.cols[col] += delta

        # Update the main diagonal if the move is on it
        if row == col:
            self.diag += delta

        # Update the anti-diagonal if the move is on it
        if row + col == self.n - 1:
            self.anti_diag += delta

        # A counter at +n or -n means one player owns the whole line
        # tc: O(1) only four counters to check
        target = self.n * delta
        if (
            self.rows[row] == target
            or self.cols[col] == target
            or self.diag == target
            or self.anti_diag == target
        ):
            return player

        # No winner yet
        return 0

353. Design Snake Game ::1:: - Medium

Topics: Hash Table, String, Design, Doubly Linked List, Hash Function, Premium

Intro

Implement a Snake game with the following rules and requirements: Game Setup: The game is played on a screen with dimensions height x width The snake starts at position (0, 0) (top-left corner) with length 1 Food items are provided as an array where food[i] = (ri, ci) represents the row and column position of the i-th food piece Game Mechanics: When the snake eats food, both its length and the game score increase by 1 Food appears one at a time - the next food item only appears after the current one is eaten Food is guaranteed to never appear on a position occupied by the snake Game Over Conditions: The snake moves out of bounds (hits a wall) The snake's head collides with its own body after moving Implementation Requirements: You need to implement a SnakeGame class with two methods: SnakeGame(int width, int height, int[][] food): Constructor that initializes the game with the screen dimensions and food positions int move(String direction): Processes one move in the given direction ("U" for up, "D" for down, "L" for left, "R" for right) and returns: The current score if the move is valid -1 if the game is over (snake hits wall or itself)

Example InputOutput
findwhat

Constraints:

this is

Abstraction

The key challenge is tracking the snake's body positions efficiently while handling the growth when eating food and checking for self-collision. The snake moves by adding a new head position in the direction of movement and removing the tail (unless food is eaten, in which case the tail remains to increase length).

Pseudocode

  oh! pseudocode hasn't been written yet, try another card! :)

Solution 1: Deque Snake Body + Hashset Of Occupied Cells [TC Opt] - Deque/Design

from collections import deque

class SnakeGame:

    # Note:
    # - snake body is a deque of (row, col) cells, head at the right, tail at the left
    # - hashset mirrors the deque for O(1) self collision checks
    # - moving without eating: append new head, pop old tail (length unchanged)
    # - moving while eating: append new head, keep the tail (length + 1)
    # - the tail moves out of its cell in the same step the head moves in,
    #   so the head is allowed to move into the cell the tail just left
    #   remove the tail from the set BEFORE the collision check when not eating
    # - when eating, the tail stays put, so moving into the tail cell is a real collision
    # - food appears one at a time, so only the next food index needs to be tracked
    # - game over (wall or self collision) returns -1

    DIRECTIONS = {
        "U": (-1, 0),
        "D": (1, 0),
        "L": (0, -1),
        "R": (0, 1),
    }

    # overall: sc O(n) for a snake of length n
    def __init__(self, width: int, height: int, food: list[list[int]]):

        self.width = width
        self.height = height
        self.food = food
        self.food_idx = 0
        self.score = 0

        # Snake starts at (0, 0) with length 1
        self.body = deque([(0, 0)])
        self.occupied = {(0, 0)}

    # overall: tc O(1)
    # overall: sc O(1)
    def move(self, direction: str) -> int:

        # Compute the new head position from the current head
        # tc: O(1)
        dr, dc = self.DIRECTIONS[direction]
        head_r, head_c = self.body[-1]
        new_r, new_c = head_r + dr, head_c + dc

        # Hit a wall, game over
        if not (0 <= new_r < self.height and 0 <= new_c < self.width):
            return -1

        # Next food is at the new head, snake eats and grows
        # tc: O(1)
        if (
            self.food_idx < len(self.food)
            and self.food[self.food_idx][0] == new_r
            and self.food[self.food_idx][1] == new_c
        ):
            self.food_idx += 1
            self.score += 1

        # No food, tail moves forward, free its cell before the collision check
        # tc: O(1)
        else:
            tail = self.body.popleft()
            self.occupied.remove(tail)

        # Head runs into the body, game over
        # tc: O(1)
        if (new_r, new_c) in self.occupied:
            return -1

        # Advance the head
        # tc: O(1)
        self.body.append((new_r, new_c))
        self.occupied.add((new_r, new_c))

        return self.score