Blog
One algorithm per article, taken apart properly: the intuition, the animation you can step through, the complexity argument, the edge cases that fail an interview, and the sentence to say out loud.
RSS feed — new articles as they publish, no email required.
9 min read
Approximate Nearest Neighbor Search: How HNSW Graphs Work
Approximate nearest neighbor search with a graph index: a greedy walk over linked vectors, why it misses, how search breadth buys recall, and what layers add.
ai mlalgorithmsgraphssystem designinterview
8 min read
BPE vs WordPiece Tokenization: How Each Picks Its Merges
BPE vs WordPiece tokenization: raw pair counts against a score relative to the parts, greedy longest-match encoding with ##, and why a whole word turns [UNK].
ai mlllmtokenizationpythoninterview
8 min read
The Call Stack, Visualized: Frames, Tracebacks and Depth
The call stack visualized in Python: what one frame holds, how to read a traceback as the stack, why depth and not call count sets memory, and RecursionError.
recursionalgorithmspythoninterview
9 min read
Design an Ad Click Aggregator: Dedup, Windows and Watermarks
Design an ad click aggregator: an append-only log, dedup by event id, per-campaign minute windows, and a watermark that trades lost late clicks against delay.
system designsystem design interviewdistributed systemsstreaming
9 min read
Don't Block the Event Loop: Find and Fix Blocking Calls
Don't block the event loop: why one slow call delays every task, how debug mode names the culprit, and fixes: await, yield in slices, or move it off the loop.
concurrencypythonasyncinterview
8 min read
Encapsulation and Invariants: Keep Objects in a Valid State
Encapsulation and invariants explained in Python: one validating door per change, all-or-nothing updates, no leaked lists, and a seeded test of every refusal.
lldooppythoninterview
7 min read
Grid Traversal: 4 and 8 Neighbours in a 2D Matrix
Grid traversal in Python: row-first indexing, the 4 and 8 neighbour offsets, the bounds guard, why grid[-1] silently wraps, and how many neighbours a cell has.
matrixgridspythoninterview
7 min read
Linked List Traversal and Search in Python
Linked list traversal and search in Python: the while-node loop, a look-ahead for the predecessor, why a hit costs (n + 1) / 2 checks and binary search fails.
linked listdata structurespythoninterview
9 min read
LLM as a Judge: Position Bias, Length Bias and Agreement
LLM as a judge explained: pairwise grading, why the verdict flips when you swap the order, how longer answers win, swap-and-tie, and kappa against human labels.
ai mlllmevaluationinterview
8 min read
Naive String Matching: Brute-Force Pattern Search
Naive string matching: try every alignment, count the comparisons, build the O(n·m) worst case, see why random text is near-linear and what a mismatch reveals.
stringspattern matchingalgorithmspythoninterview
8 min read
O(1) vs O(n): Constant Time vs Linear Time, Explained
O(1) vs O(n) explained by counting reads: one step or every step, why two passes are still O(n), which Python operations are which, and O(1) versus O(n) space.
big ocomplexitypythoninterview
8 min read
Recursion: Return Values Up or Pass State Down
Two ways recursion moves information: return values up, or pass state down as arguments. How to pick, when to use both, and the shared-list and global traps.
recursiontreesalgorithmspythoninterview
7 min read
Reverse an Array In Place: Swap the Ends, Step Inward
Reverse an array in place with two indexes and n / 2 swaps: why the loop stops at the middle, reversing a range, and which Python spellings secretly copy.
arraystwo pointersin placepythoninterview
8 min read
The Tool-Use Loop: How Function Calling Works
How function calling works as a loop: the model proposes a call, your code validates and runs it, errors return as observations and a step budget ends the run.
ai mlllmagentspythoninterview
8 min read
Top K Frequent Elements in a Stream: Heap and Space-Saving
Top k frequent elements in a stream: exact counts with a k-sized heap per query, why exact needs memory for every label, and the bounded Space-Saving answer.
heapstop kstreamingpythoninterview
8 min read
Union-Find / Disjoint Set Basics: Parent Array, Find, Union
Union-find basics: one parent array, find walks up to the root that names a group, union points one root at another, and why that answers same-group questions.
union finddata structuresgraphspythoninterview
8 min read
Arrays Explained: O(1) Indexing, O(n) Inserts, Dynamic Arrays
Arrays explained: why reading index i is one address calculation, why inserting at the front shifts everything, and how a dynamic array makes append O(1).
arraysdata structuresbig ointerview
8 min read
Atomic Operations Explained: Why counter += 1 Is Not Atomic
What an atomic operation is, why counter += 1 is three steps that can tear, which Python operations are atomic, and why two atomic steps still race, with code.
concurrencymultithreadingpythoninterview
8 min read
Backtracking Explained: Choose, Explore, Un-choose, Prune
Backtracking explained: build an answer one choice at a time, undo each choice on the way back and prune dead branches early. The template, two bugs, real code.
backtrackingrecursionalgorithmsinterview
8 min read
Binary Search Tree Basics: The Ordering Rule Explained
Binary search tree basics: the rule covers whole subtrees, why inorder is sorted, min and max, successor, range counts, and a balanced BST from sorted data.
treesbinary search treedata structuresinterview
9 min read
Cache Invalidation and Eviction: TTLs, Deletes and LRU
Cache invalidation vs eviction: what TTLs really guarantee, the race that defeats delete-on-write, stampedes and jitter, and why Redis LRU samples keys.
system designcachingredisinterview
7 min read
How to Check if Two Intervals Overlap, and Why Sort by Start
Two intervals overlap when each starts before the other ends. The one-line test, open vs closed ends, the intersection, and why sorting makes one scan enough.
intervalssortingpythoninterview
8 min read
Deadlock Detection: Wait-for Graphs, Cycles and Victims
Deadlock detection explained: build a wait-for graph from the lock table, find the cycle, tell members from bystanders, and abort one victim to break the ring.
concurrencydeadlockgraphsinterview
9 min read
Design a Chess Game: Low-Level Design of Pieces and Board
Design a chess game in a low-level design interview: pieces own move shape, the board owns occupancy, the game owns turns and check, and where castling belongs.
lldobject oriented designdesign patternsinterview
10 min read
Design a Collaborative Editor: OT vs CRDT Explained
Design a collaborative editor: local-first edits, why position-based ops must be transformed (OT), how character ids merge (CRDT), and what each one costs.
system designsystem design interviewdistributed systemsconcurrency
9 min read
Design a Distributed Job Scheduler: Leases, Retries, Dead Letters
Design a distributed job scheduler: run-at times, leases with heartbeats, fencing tokens, idempotent handlers, backoff, dead letters and the top-of-hour spike.
system designsystem design interviewdistributed systemsqueues
9 min read
Design a File Storage Service: Chunking, Dedup and Sync
Design a file sync and storage service for a system design interview: chunk and hash files, upload only new chunks, metadata vs blobs, conflicts, and dedup.
system designsystem design interviewhashingfile sync
9 min read
Design a Hotel Booking System: No Double Bookings, No Partial Stays
Design a hotel booking system: per-night inventory, one transaction per stay, conditional updates against races, a unique key as last defence, and holds.
system designsystem design interviewconcurrencydatabases
9 min read
Design a Payment System: Double-Entry Ledger and Idempotency
Design a payment ledger for a system design interview: double-entry rows that sum to zero, append-only reversals, idempotency keys and balance snapshots.
system designsystem design interviewpaymentsdatabases
8 min read
Design a Ride-Hailing Service: Matching Riders to Drivers
Design ride-hailing matching for a system design interview: 12,500 location writes a second in memory, grid cells and neighbours, ETA ranking, offer holds.
system designsystem design interviewgeospatialreal time
9 min read
Design an Inventory System: Prevent Overselling
Design an e-commerce inventory system: a conditional decrement so the last unit sells once, expiring holds, late payments, and hot items split over stock rows.
system designsystem design interviewconcurrencydatabases
8 min read
Design Search Autocomplete: System Design Interview Guide
Design search autocomplete for a system design interview: debounce keystrokes, cache prefixes at the edge, precompute top-k offline, and the cost of staleness.
system designsystem design interviewautocompletecaching
9 min read
Distributed Tracing Explained: Trace IDs, Spans and Sampling
Distributed tracing explained: how a trace id and parent span id ride in headers, how a collector rebuilds the span tree, what a lost header does, and sampling.
system designobservabilitydistributed systemsmicroservices
8 min read
Fine-Tuning vs Prompting vs RAG: Which One to Use
Fine-tuning vs prompting vs RAG: what each changes, what each costs, a break-even calculation for tuning, and the order to try them in, with runnable code.
machine learningllmfine tuningraginterview
9 min read
How a CDN Works: Edge Caching, Latency and Purging
How a CDN works: why distance is latency you cannot tune away, what an edge hit and miss cost, origin shields, private pages, and purging vs versioned files.
system designcdncachinglatency
8 min read
How to Evaluate an LLM: Test Sets, Scorers and Model Judges
How to evaluate an LLM: frozen test cases, normalised and deterministic scorers first, rubrics and model judges after, and enough cases to trust a difference.
llmai mlevaluationinterview
9 min read
How to Read a Query Plan: EXPLAIN in SQL, Line by Line
How to read EXPLAIN output: plan lines as nested loops, the outer vs inner table, join order flips, temp B-trees, and why a plan is only an estimate, in SQLite.
sqldatabasesindexesperformanceinterview
8 min read
Linear Search Explained: When O(n) Is the Right Call
Linear search explained: count the checks, (n + 1) / 2 on average, why one lookup never pays for a sort, searching by condition, and move-to-front in Python.
algorithmssearchingbig opythoninterview
9 min read
LLM Guardrails Explained: Input Checks, Scopes, Output Scans
LLM guardrails explained: why the model is not the boundary, soft input filters vs hard tool scopes, output scans for secrets, and what false positives cost.
ai mlllmsecurityagentsinterview
8 min read
Memoization Explained: Cache Recursive Calls in Python
Memoization explained: store each answer the first time, reuse it after. Call counts before and after, lru_cache, the shared-default trap and what to key on.
recursionmemoizationpythondynamic programming
8 min read
Mutex vs Lock: Reentrant Locks, Ownership and Granularity
Mutex vs lock explained: why they are usually the same thing, reentrant vs plain locks, who may release a lock, and how lock granularity decides throughput.
concurrencylocksthreadsinterview
8 min read
O(n²) Explained: Nested Loops and Hidden Quadratic Code
O(n²) explained: why a loop inside a loop counts every pair, why doubling n quadruples the work, and how a list lookup inside a loop hides a quadratic.
big otime complexitynested loopspython
8 min read
Observability Explained: Logs, Metrics and Traces
Observability basics: what logs, metrics and traces each answer, why you alert on percentiles, label cardinality, span self time and trace sampling, in code.
system designobservabilitymonitoringdistributed systems
8 min read
Radix Sort Explained: LSD, MSD, Bases and Negative Numbers
Radix sort explained pass by pass: why LSD starts at the last digit, choosing a base, sorting signed 32-bit integers, and MSD radix sort for strings, in Python.
sortingalgorithmsradix sortinterview
9 min read
RAG Chunking and Reranking: Overlap, Recall and Rerankers
RAG chunking and reranking explained: how a bad cut makes a fact unanswerable, what overlap guarantees, and why no reranker can recover a missed passage.
ai mlllmembeddingssearchinterview
8 min read
Redundant Connection and Graph Valid Tree with Union-Find
Union-find counts components and finds cycle edges in one pass: start at n, drop on each real merge, and the edge whose ends share a root is the redundant one.
union findgraphscycle detectioninterview
8 min read
Singly Linked List in Python: Nodes, Traversal and Big-O
A singly linked list in Python from scratch: nodes and links, why reaching item k costs k hops, a tail pointer for O(1) append, and when a list beats it.
linked listdata structurespythoninterview
8 min read
Sorting Basics: Stability, In-Place, Comparison Sorts
Sorting basics explained: what stable and in-place mean, why comparison sorts cannot beat n log n, layered sorts with tuple keys, and a stability fix in Python.
algorithmssortingbig opythoninterview
8 min read
SQL SELECT Basics: Columns, Aliases, DISTINCT and SELECT *
SQL SELECT basics: pick columns, compute expressions, name them with AS, drop duplicates with DISTINCT, and why SELECT * breaks code when a column is added.
sqldatabasessqliteinterview
8 min read
Strings in Python: Immutability, += vs join, and Hidden Copies
Strings in Python are immutable: every edit builds a new one. Why += in a loop can be quadratic, why join is linear, what slicing costs, and a Unicode trap.
stringspythonbig ointerview
8 min read
Training vs Inference in Machine Learning: Cost, Latency, Drift
Training vs inference: one slow loop that changes the parameters, then a fast pass that only reads them. Costs, batching, train/serve skew, with runnable code.
machine learningai mlinferenceinterview
9 min read
Transformer Architecture Explained: One Block, Stacked
The transformer architecture explained: token vectors, positions, a block of attention plus a per-position network with residuals, stacked, then vocab scores.
ai mltransformersllmattention
7 min read
Tree Data Structure Basics: Root, Leaf, Depth and Height
Tree data structure basics: root, parent, child, leaf, depth vs height, why a tree has n - 1 edges, and how to check a parent array is a tree, with Python code.
treesdata structurespythoninterview
8 min read
What Is an LLM? Large Language Models Explained Simply
What an LLM is: a model trained to score every possible next token, run in a loop to write text. Training, generation, why it sounds sure when wrong, with code.
machine learningllmlanguage modelsinterview
8 min read
What Is Low-Level Design? The LLD Interview Explained
What low-level design is: classes, responsibilities and the calls between them, how it differs from system design, and a step-by-step LLD interview method.
low level designobject oriented designinterviewpython
8 min read
What Is Machine Learning? Rules Learned From Examples
What machine learning is: instead of writing a rule, you fit one from labelled examples. Training, held-out data, overfitting and drift, with runnable code.
machine learningai mlfundamentalsinterview
8 min read
ACID Transactions Explained: Commit, Rollback and Constraints
ACID transactions explained with runnable SQL: atomic rollback, constraints that keep data valid, isolation from other connections, and what durability means.
sqldatabasestransactionsinterview
7 min read
Adjacency List vs Adjacency Matrix: Choosing a Graph Representation
Adjacency list vs adjacency matrix: what each stores, which operations each makes fast, why sparse graphs pick the list, and runnable Python for both forms.
graphsdata structuresbig ointerview
8 min read
Async/Await and the Event Loop Explained: One Thread, Taking Turns
Async/await and the event loop explained: one thread, cooperative turns at every await, why one blocking call freezes everything, and when threads fit better.
concurrencypythonthreadsinterview
8 min read
Autocomplete With a Trie: Prefix Search and Top-K Suggestions
How autocomplete works with a trie: walk the prefix in O(P), collect the subtree, return the first k alphabetically, and cache the top k per node for speed.
triesstringsautocompleteinterview
8 min read
AWS Cost Optimization: Spot vs Savings Plans vs Reserved
AWS cost optimization in order: right-size, scale, commit the floor with Savings Plans or Reserved Instances, restartable work on Spot, and watch NAT traffic.
awscost optimizationec2system designinterview
6 min read
Balanced Binary Tree and Maximum Depth: The O(n) Check
Maximum depth and the balanced binary tree check: height by recursion, why the top-down test repeats work, the one-pass -1 trick, and a brute-force check.
treesrecursiondfsinterview
8 min read
Best Time to Buy and Sell Stock: DP as a State Machine
Solve the stock problems with two states, hold and free: one trade, unlimited trades, a transaction fee and a cooldown, all O(n) and checked by brute force.
dynamic programmingarraysstate machineinterview
7 min read
Binary Search Tree Insert and Search: One Comparison per Level
Binary search tree insert and search, explained: one comparison per level, why both walk the same path, why height is the real cost, and floor and ceiling.
treesbinary search treedata structuresinterview
7 min read
Binary Tree Traversal: Preorder, Inorder and Postorder
Binary tree traversal explained: preorder, inorder and postorder as one recursion with one line moved, the iterative stack versions, and when to use which.
treesdfsrecursioninterview
8 min read
Bitmask as a Set: Enumerate Subsets and Write Bitmask DP
Bitmasks explained: one integer as a set, set operations in one instruction, every subset from a counting loop, submasks, and bitmask DP for the shortest tour.
bit manipulationsubsetsdynamic programminginterview
8 min read
Bitwise Operators Explained: AND, OR, XOR, NOT and Shifts
Bitwise operators explained lane by lane: AND, OR, XOR, NOT and shifts, two's complement and Python's negative numbers, permission masks, an adder from gates.
bit manipulationbinarypythoninterview
8 min read
Caching Explained: Cache-Aside, Hit Ratio, TTL and Stale Data
Caching explained for system design interviews: the cache-aside read path, why the hit ratio decides everything, how TTLs and invalidation limit stale data.
system designcachingperformanceinterview
8 min read
CAP Theorem Explained: CP vs AP When the Network Splits
The CAP theorem without the myths: why partitions force the choice, what CP and AP nodes do during a split, quorums, and a toy cluster model you can run.
system designdistributed systemsconsistencyinterview
9 min read
CloudWatch Metrics, Alarms, Logs and X-Ray Explained
CloudWatch alarms, Logs and X-Ray in one incident: M out of N alarm evaluation, log groups and metric filters, trace segments, sampling, and the SDK status.
awsobservabilitymonitoringsystem designinterview
7 min read
Coin Change II: Counting Combinations, Not Permutations
Coin change II counts ways to make an amount: why the coin loop sits outside, why ways[0] is 1, how swapped loops count orders, and a brute-force check.
dynamic programmingknapsackcombinatoricsinterview
8 min read
Compare-and-Swap Explained: Lock-Free Retry Loops and ABA
Compare-and-swap explained: how one atomic instruction prevents lost updates without a lock, the read-compute-retry loop, and the ABA trap and its version fix.
concurrencylock freeatomicsinterview
8 min read
Composite and Covering Indexes: Why Column Order Matters
Composite and covering indexes explained with real query plans: the leftmost prefix rule, equality before range, index-only reads, and what each index costs.
sqldatabasesindexesinterview
8 min read
Composition vs Inheritance: Why Has-A Usually Beats Is-A
Composition vs inheritance with runnable Python: the subclass explosion, the fragile base class, swapping parts at runtime, and when inheritance is right.
lldoopdesign patternsinterview
8 min read
Construct Binary Tree From Preorder and Inorder Traversal
Rebuild a binary tree from preorder and inorder: preorder names the root, inorder says where to cut, an O(n) index map, and why preorder plus postorder fails.
treesrecursionhash tablesinterview
7 min read
Container With Most Water: Why You Move the Shorter Wall
Container with most water in O(n): two pointers, why moving the shorter wall never skips the best pair, the proof in one line, and a brute-force cross-check.
arraystwo pointersgreedyinterview
8 min read
Containers vs Virtual Machines: Kernels, Namespaces, cgroups
Containers vs virtual machines: one shared kernel or a guest kernel each, namespaces for what a process sees, cgroups for what it uses, and opt-in limits.
kubernetesdockercontainersinterview
8 min read
Convert Recursion to Iteration With an Explicit Stack
How to convert recursion to iteration: an explicit stack of pending frames, a phase flag for work after the calls, a pausable iterator, and no recursion limit.
recursionstacktreesinterview
7 min read
Counting Set Bits: Brian Kernighan's Trick and Counting Bits
Count set bits with x & (x - 1): why it clears the lowest 1, why it loops once per set bit, negatives, the counting bits DP table, and a brute-force check.
bit manipulationpopcountdynamic programminginterview
8 min read
Database Replication Explained: Replicas, Lag and Failover
Database replication explained for system design interviews: primary and read replicas, replication lag, read-your-writes, sync vs async, and failover loss.
system designdatabasesreplicationinterview
7 min read
Database Sharding Explained: Shard Keys, Hot Shards, Resharding
Database sharding explained: choosing a shard key, why queries without it hit every shard, how hot shards form, and what resharding costs, with a toy model.
system designdatabasesshardingscalabilityinterview
9 min read
Design a Chat App: Messaging System Design Interview Guide
Design a chat app for system design interviews: stateful gateways, a session registry, store before ack, per-conversation sequence numbers, and offline sync.
system designmessagingdistributed systemsinterview
9 min read
Design a File System (LLD): The Composite Pattern
Design an in-memory file system for a low-level design interview: the composite pattern, path resolution, cached folder sizes, symlinks and flat tables.
llddesign patternsoopinterview
9 min read
Design a Key-Value Store: Quorums, Versions and Repair
Design a distributed key-value store for a system design interview: N, W and R quorums, why a failed write can still appear, vector clocks and read repair.
system designdistributed systemsreplicationinterview
9 min read
Design a Leaderboard: Sorted Sets, Top-K and Player Rank
Design a real-time leaderboard for a system design interview: a sorted set kept in order on write, top-K as a range read, exact rank, and approximate rank.
system designleaderboarddata structuresinterview
9 min read
Design a News Feed: Fan-Out on Write vs Fan-Out on Read
Design a news feed for system design interviews: fan-out on write vs read, the celebrity problem, the hybrid that fixes it, and how a feed page is ranked.
system designnews feedcachinginterview
8 min read
Design a Parking Lot: The Low-Level Design Interview Answer
Design a parking lot in a low-level design interview: requirements first, then Lot, Spot and Ticket, pluggable allocation and pricing, in runnable Python code.
low level designobject oriented designsystem designinterview
9 min read
Design a Proximity Service: Geohash vs Quadtree
Design a nearby-places search for a system design interview: geohash prefixes on a plain index, the eight neighbour cells, quadtrees for uneven density.
system designgeohashquadtreeinterview
8 min read
Design a Vending Machine: The State Pattern in Python
Design a vending machine for a low-level design interview: one class per state, transitions owned by states, a sold-out state, checked against a flag version.
llddesign patternsstate machineinterview
9 min read
Design a Web Crawler: Frontier, Politeness and Deduplication
Design a web crawler for a system design interview: a frontier partitioned by host, robots rules and crawl delays, URL and content dedupe, and scaling out.
system designweb crawlerbfsinterview
8 min read
Design an Elevator System: Low-Level Design Interview Walkthrough
Elevator system design for LLD interviews: the car as a state machine, pending floors in a set, the directional sweep, and why first-come order loses.
low level designobject oriented designstate machineinterview
7 min read
Design a Circular Queue: The Ring Buffer, Head, Size and Modulo
Design a circular queue, explained: a ring buffer that moves two integers instead of data, how modulo wraps the ends, and the classic full-versus-empty trap.
queuesdata structuresstacks queuesinterview
9 min read
Design Video Streaming: Transcoding, Segments and CDN Edges
Design a video streaming service for a system design interview: transcoding into a bitrate ladder, segments and manifests, CDN edges, and adaptive bitrate.
system designsystem design interviewcdnvideo streaming
8 min read
Diameter of a Binary Tree: One DFS That Returns Depth
The diameter of a binary tree in one post-order DFS: return each node's depth, record left plus right as the path that bends there, and skip the O(n^2) version.
treesdfsrecursioninterview
8 min read
Docker Compose Explained: depends_on, Healthchecks and Networks
Docker Compose explained: service names on the default network, container vs host ports, depends_on vs service_healthy, and what docker compose down keeps.
dockerdocker composecontainersinterview
8 min read
Docker Networking Explained: Bridge Networks, Ports, Volumes
Docker networking explained: why names resolve only on user-defined networks, what -p 8080:80 really exposes, and why data belongs in volumes, with a toy model.
dockercontainersnetworkinginterview
8 min read
Doubly Linked List Explained: O(1) Delete With Sentinel Nodes
A doubly linked list explained: why a prev pointer makes deleting a known node O(1), how sentinel nodes remove edge cases, and why LRU caches depend on it.
linked listsdata structureslru cacheinterview
9 min read
EC2 Auto Scaling Explained: Target Tracking, Health Checks, ALB
How an EC2 Auto Scaling group holds min, max and desired capacity, how target tracking picks a size, when health checks replace instances, and ALB versus NLB.
awsscalingload balancingsystem designinterview
9 min read
ECS vs EKS vs Fargate: How to Choose Containers on AWS
ECS vs EKS vs Fargate as two decisions: the orchestrator that runs your containers and the compute under it, and Fargate's limits on GPUs, daemons and networks.
awscontainerskubernetessystem designinterview
7 min read
Euclidean Algorithm Explained: GCD, LCM and Extended Euclid
The Euclidean algorithm explained: why gcd(a, b) equals gcd(b, a mod b), why it takes O(log n) steps, LCM without overflow, and extended Euclid for inverses.
mathnumber theoryrecursioninterview
7 min read
Factory Pattern Explained: One Place Decides What to Build
The factory design pattern explained with Python: a registry mapping keys to classes, self-registering products, alternative constructors, and when to skip it.
llddesign patternsoopinterview
6 min read
Fast Exponentiation: Binary Exponentiation in O(log n)
Fast exponentiation by squaring: read the exponent in binary, keep the rungs whose bit is on, reduce by the modulus as you go, and check it against pow().
mathbit manipulationmodular arithmeticinterview
8 min read
Find Median from Data Stream: The Two Heaps Pattern Explained
Find the median of a data stream with two heaps: a max-heap for the low half, a min-heap for the high half, O(log n) inserts, O(1) reads, and why sorting fails.
heapstwo heapsdata structuresinterview
7 min read
Find Peak Element: Binary Search on an Unsorted Array
Find peak element in O(log n): why comparing mid with its right neighbour lets binary search work on unsorted data, why hi = mid, and a brute-force check.
binary searcharrayssearchinginterview
7 min read
First and Last Position in a Sorted Array: Boundary Binary Search
Find the first and last position of a target in a sorted array with two boundary binary searches: record the hit, keep shrinking, and check it against a scan.
binary searchsearchingarraysinterview
7 min read
Flood Fill Algorithm Explained: DFS, BFS and the Same-Colour Trap
Flood fill explained: the paint bucket as a graph search, stack DFS against queue BFS, why a same-colour fill never stops, and why deep recursion crashes.
matrixdfsbfsgraphsinterview
8 min read
Graph Data Structure Explained: Nodes, Edges and Degree
The graph data structure explained: nodes and edges, directed vs undirected, degree and the handshake lemma, sparse vs dense, and when a graph is a tree.
graphsdata structurespythoninterview
8 min read
Hash Collisions Explained: When a Hash Table Degrades to O(n)
Hash collisions explained: chaining vs open addressing, why O(1) lookup is only an average, how a bad hash turns a table into a list scan, and mutable keys.
hash tableshashingbig ointerview
7 min read
Heapify Explained: Why Building a Heap Is O(n)
How heapify turns an array into a heap: sift down from the last parent backwards, why the total is O(n) and not O(n log n), and a brute-force check in Python.
heapspriority queuebig ointerview
8 min read
House Robber Explained: Dynamic Programming with Take or Skip
House robber with dynamic programming: take-or-skip recurrence, two rolling totals for O(1) space, recovering which houses to pick, and the circular variant.
dynamic programmingarraysinterview
8 min read
House Robber III: DP on Trees With a Take and Skip Pair
House Robber III explained: why each tree node returns a take and a skip value, why one post-order pass beats naive recursion, and how to dodge the stack limit.
dynamic programmingtreesrecursioninterview
7 min read
Implement a Queue Using Two Stacks: Amortized O(1) Explained
Build a FIFO queue from two LIFO stacks: why you pour only when the outbox is empty, why dequeue is amortized O(1) but can cost O(n), and a random check.
stacksqueuesamortized analysisinterview
7 min read
Insert Interval: Copy, Absorb, Copy in One Linear Pass
Insert interval in O(n) with no sort: copy what ends before, absorb what touches, copy the rest, plus the closed vs half-open boundary and a brute-force check.
intervalsarrayssortinginterview
7 min read
Insertion Sort Explained: Shifts, Inversions, Nearly Sorted Data
Insertion sort explained: why each shift fixes one inversion, why nearly sorted input runs in O(n), why it is stable, and a Python check against sorted().
sortingbig oarraysinterview
7 min read
Jump Game Explained: Greedy Farthest Reach in One Pass
Jump game in O(n) with one variable, the farthest reachable index. Why the greedy is correct, the minimum-jumps version, and a check against a full search.
greedyarraysdynamic programminginterview
7 min read
Kth Smallest Element in a Sorted Matrix: Binary Search on Values
Kth smallest element in a sorted matrix: binary search the value range, count with a staircase walk, why the answer is in the matrix, and the heap option.
binary searchmatrixheapsinterview
8 min read
Kubernetes ConfigMap vs Secret: Env Vars, Volumes and Base64
ConfigMap vs Secret in Kubernetes: env vars vs mounted files, why env goes stale until a restart, why base64 is not encryption, and how to lock Secrets down.
kubernetesconfigurationsecuritydevopsinterview
8 min read
Pod vs ReplicaSet vs Deployment in Kubernetes, Explained
Pod vs ReplicaSet vs Deployment: what each object owns, why a lost Pod is replaced, never moved, how labels decide ownership, and how rollbacks reuse history.
kubernetescontainersdevopsinterview
9 min read
Kubernetes Requests vs Limits and the HPA Formula Explained
What Kubernetes requests and limits do, why CPU is throttled but memory is OOM-killed, how the HPA computes replicas from the request, and key defaults.
kubernetesscalingdevopssystem designinterview
9 min read
Kubernetes StatefulSet vs Deployment: PVs, PVCs and Stable Storage
StatefulSet vs Deployment in Kubernetes: stable Pod names, one PVC per replica, ordered rollout, why scale-down keeps data, and how reclaim policies delete it.
kubernetesstoragedevopssystem designinterview
8 min read
KV Cache Explained: Why LLM Inference Keeps Keys and Values
The KV cache explained: why generation recomputes nothing for earlier tokens, what it saves, how much memory it costs per token, and why it caps the batch size.
ai mlllminferenceinterview
8 min read
Linked List Insertion and Deletion: Head, Middle and Tail
Linked list insertion and deletion explained: the two-pointer splice, why write order matters, the dummy head, remove the nth node from the end, and costs.
linked listdata structurespythoninterview
8 min read
LLM Agents Explained: Tool Calling in a Loop
What an LLM agent really is: a model in a loop that proposes structured tool calls your code runs, plus the iteration cap, permission checks and untrusted data.
ai mlllmagentsinterview
8 min read
LLM Context Window Explained: Token Budget and Truncation
What an LLM context window is: one token budget shared by instructions, history and the reply, why old turns fall off, and how to trim, pin and summarise.
ai mlllmcontext windowinterview
8 min read
LLM Quantization Explained: 8-Bit, 4-Bit, Scales and Outliers
LLM quantization explained: how a scale maps weights to 8-bit or 4-bit integers, why fewer bytes speed up decoding, and why outlier weights force small groups.
ai mlllmquantizationinference
8 min read
LLM Temperature, Top-k and Top-p Sampling Explained
LLM temperature, top-k and top-p explained with real numbers: how dividing the logits sharpens or flattens softmax, and how each filter trims the unlikely tail.
ai mlllmsamplinginterview
8 min read
Load Balancing Algorithms: Round Robin vs Least Connections
Load balancing algorithms compared: round robin, least connections and hashing, how health checks drop a dead server, why sticky sessions hurt, and a toy model.
system designload balancingscalabilityinterview
8 min read
LoRA Explained: Low-Rank Adapters for Cheap Fine-Tuning
LoRA explained: freeze the weights, train two thin matrices B and A, why their product has the layer's shape, what rank buys, and what merging does to serving.
ai mlllmfine tuninginterview
7 min read
Majority Element: Boyer-Moore Voting in O(1) Space
Majority element with Boyer-Moore voting: why cancelling pairs leaves the majority, why a second pass is needed, the n/3 variant, and a brute-force check.
arraysboyer moorecountinginterview
8 min read
Matrix Chain Multiplication: Interval DP Explained
Matrix chain multiplication explained as interval DP: why the order changes the cost, how the table fills by stretch length, and how to rebuild the best order.
dynamic programminginterval dpalgorithmsinterview
7 min read
Memoization vs Tabulation: Top-Down vs Bottom-Up DP
Memoization vs tabulation in dynamic programming: one recurrence solved top-down with a cache or bottom-up with a table, the trade-offs, and when each one wins.
dynamic programmingmemoizationrecursioninterview
6 min read
Merge Sorted Array In Place: Fill From the Back
Merge two sorted arrays into the first in place: why filling from the back never overwrites unread data, the early stop, and a Python check against sorted().
arraystwo pointerssortinginterview
7 min read
Merge Two Sorted Lists: The Dummy Head and the One-Write Tail
Merge two sorted linked lists in O(n + m) with no new nodes: the dummy head, why the leftover chain takes one write, the recursive version, and a random check.
linked liststwo pointersrecursioninterview
8 min read
Message Queues Explained: At-Least-Once, Idempotency, Dead Letters
Message queues explained: why producers stop waiting, how acks and redelivery give at-least-once delivery, why consumers must be idempotent, and what a DLQ is.
system designmessage queuesdistributed systemsinterview
7 min read
Middle of the Linked List: Fast and Slow Pointers
Find the middle of a linked list in one pass with fast and slow pointers: first vs second middle, the loop guard, palindromes, and deleting the middle node.
linked listtwo pointersfast slow pointersinterview
8 min read
Minimum Path Sum and Unique Paths: Dynamic Programming on Grids
Minimum path sum and unique paths with grid DP: why each cell needs only its top and left neighbours, reading the route back, one-row space and a brute force.
dynamic programmingmatrixgridinterview
8 min read
Modular Arithmetic Explained: Why Answers Use Mod 10^9 + 7
Modular arithmetic for coding interviews: which operations survive reducing early, why division needs a modular inverse, negative remainders, and why 10^9 + 7.
mathnumber theorymodular arithmeticinterview
7 min read
Move Zeroes: Two Pointers, One Pass, Order Preserved
Move zeroes to the end of an array in place, explained: a read pointer, a write pointer, why order survives, and the swap version that minimises writes.
arraystwo pointersin placeinterview
8 min read
Multi-Source BFS Explained: Rotting Oranges and Nearest Exits
Multi-source BFS seeds the queue with every source at distance 0, so one sweep finds each cell's nearest source. Rotting oranges, walls and the O(V + E) proof.
graphsbfsmatrixinterview
7 min read
The N+1 Query Problem: How to Spot It and Fix It
The N+1 query problem: why one query per row is slow even when each query is fast, how to count round trips, and the JOIN and IN fixes, checked in SQLite.
sqldatabasesperformanceinterview
7 min read
Number of Connected Components: DFS vs Union-Find
Count connected components in an undirected graph: a fresh DFS or BFS from each unvisited node, union-find instead, isolated nodes, and a brute-force check.
graphsdfsunion findinterview
7 min read
O(log n) Explained: Why Halving Makes Algorithms Fast
What O(log n) really means: why halving a million items takes about 20 steps, why the log base never matters, and how to spot logarithmic loops in code.
big ocomplexitybinary searchinterview
7 min read
Observer Pattern Explained: Subscribe, Notify and Unsubscribe
The observer pattern explained: a subject that knows only a list of callables, fire-and-forget notify, safe unsubscribe, failing observers and memory leaks.
low level designdesign patternsoopinterview
8 min read
Path Sum in a Binary Tree: Remainders and Prefix Sums
Path sum in a binary tree, three ways: carry the remainder to a leaf, collect every path with backtracking, and count any downward path with prefix sums.
treesdfsprefix suminterview
7 min read
Permutations vs Combinations: nPr, nCr and Pascal's Triangle
Permutations vs combinations explained: when order matters, why you divide by k!, Pascal's triangle, repeated items, and nCr mod 10^9 + 7 for coding interviews.
mathcombinatoricscountinginterview
8 min read
Polymorphism Explained: Interfaces and Abstract Base Classes
Polymorphism explained with Python: one method name, many types, interfaces as abstract base classes, duck typing vs protocols, and how method dispatch works.
lldooppythoninterview
8 min read
Priority Queue Explained: heapq, Tuples and Tie-Breaking
A priority queue explained: why a heap gives O(log n) push and pop, why heapq entries are tuples with a counter, how to change a priority, and max-heap tricks.
heapspriority queuepythoninterview
8 min read
Product of Array Except Self: Prefix and Suffix Products in O(n)
Product of array except self without division: a left sweep of prefix products, a right sweep of suffix products, O(1) space, and why zeros break division.
arraysprefix suminterview
7 min read
Queue Data Structure in Python: deque vs list.pop(0)
The queue data structure explained: FIFO order, why list.pop(0) is O(n) and deque.popleft() is O(1), a linked-list queue from scratch, and queue.Queue.
queuedata structurespythoninterview
8 min read
Recursion Explained: Base Case, Recursive Case, Unwinding
Recursion explained from countdown(3) up: the base case, the smaller step, how calls unwind in reverse, a three-question recipe, and why Python stops at 1000.
recursionalgorithmspythoninterview
7 min read
Reorganize String: Greedy Max-Heap With a Held-Back Letter
Reorganize string so no two neighbours match: a max-heap greedy that holds the last letter back one round, the half-length test, and an O(n) even-slot fill.
heapsgreedystringsinterview
8 min read
REST API Design: Resources, Methods, Status Codes, Idempotency
REST API design for interviews: nouns in paths, verbs as methods, 201 with Location, safe and idempotent methods, retries with idempotency keys, and a toy API.
system designapi designrestinterview
6 min read
Reverse Words in a String: Split and Join, or Fully In Place
Reverse words in a string, explained: split and join with two pointers, why split(' ') keeps empty words, and the in-place trick of reversing twice in O(1).
stringstwo pointersin placeinterview
7 min read
Rotate Array In Place: The Three-Reversal Trick
Rotate an array right by k in O(1) extra space: reverse all, then each block, why k % n comes first, the cyclic-replacement version, and a brute-force check.
arraystwo pointersin placeinterview
7 min read
Selection Sort Explained: n² Comparisons, at Most n − 1 Swaps
Selection sort explained: why it always makes n(n-1)/2 comparisons, why it needs at most n - 1 swaps, why it is not stable, and when fewer writes matter.
sortingbig ostabilityinterview
8 min read
Semaphore vs Mutex: Counting Permits Explained
Semaphore vs mutex: permits instead of owners, what acquire and release really do, why a semaphore of one is not quite a mutex, and threaded Python checks.
concurrencythreadssynchronizationinterview
8 min read
Sieve of Eratosthenes: Start at p Squared, Stop at the Square Root
The sieve of Eratosthenes: why crossing out starts at p squared, why the loop stops at the square root of n, the n log log n cost, and a smallest-factor sieve.
mathnumber theoryprimesarraysinterview
8 min read
SOLID Principles Explained With One Refactor, Letter by Letter
SOLID principles explained through one report exporter: split the reasons to change, add formats without edits, keep subtypes honest, and know when to stop.
low level designoopdesign principlesinterview
8 min read
Speculative Decoding Explained: Draft, Verify, Accept
Speculative decoding explained: a small model drafts tokens, the large one checks them all in one pass, and the acceptance rule that keeps the output unchanged.
ai mlllminferencespeculative decoding
7 min read
SQL NULL in WHERE: Why = NULL Matches Nothing
Why WHERE col = NULL returns no rows: SQL's three-valued logic, IS NULL, how NULL slips through AND, OR and NOT, and why COUNT and AVG skip it, run in SQLite.
sqlnulldatabasesinterview
8 min read
SQL ORDER BY and LIMIT: Top-N, OFFSET and Keyset Pagination
SQL ORDER BY and LIMIT explained: why LIMIT without ORDER BY is random, how ties break pages, why OFFSET gets slower, and how keyset pagination fixes it.
sqldatabasespaginationinterview
8 min read
SQL Order of Execution: Why WHERE Can't See Your Alias
SQL runs FROM, WHERE, GROUP BY, HAVING, SELECT, then ORDER BY. Why WHERE can't use an alias or an aggregate, where window functions fit, and SQLite's quirk.
sqldatabasesinterview
19 min read
40 SQL Interview Questions, Answered and Run in SQLite
40 SQL interview questions on NULLs, joins, GROUP BY, window functions, indexes and transactions, with short model answers and the tricky queries run for real.
sqldatabasesinterview
8 min read
SQL Recursive CTE Explained: Anchor, Recursive Step and Cycles
SQL recursive CTEs explained with runnable SQLite: the anchor, the recursive step, when the passes stop, and how UNION or a depth cap stops cycles in graphs.
sqldatabasesrecursiongraphsinterview
7 min read
SQL Subqueries Explained: Scalar, IN, EXISTS and Correlated
SQL subqueries explained with runnable SQLite: scalar and IN subqueries, correlated subqueries that re-run per row, and why one NULL empties a NOT IN result.
sqldatabasesinterview
8 min read
SQL vs NoSQL: How to Choose in a System Design Interview
SQL vs NoSQL explained with a runnable toy model: normalised tables and joins against whole documents, who pays on reads and on writes, and how to choose.
system designdatabasessqlinterview
8 min read
Stack Data Structure Explained: Push, Pop and Peek
The stack data structure explained: last in, first out, why push and pop are O(1), which end of a Python list is the top, and evaluating postfix with a stack.
stackdata structurespythoninterview
7 min read
Strategy Pattern Explained: Replace an If/Elif Chain With Objects
The strategy pattern explained: lift the step that varies into swappable objects, delete the if/elif chain, and know when a plain function is the better fit.
low level designdesign patternsoopinterview
7 min read
String Compression In Place: Run-Length Encoding With Two Cursors
String compression explained: run-length encoding in place with a read and a write cursor, why they never collide, multi-digit counts, and the decoding trap.
stringstwo pointersin placeinterview
9 min read
Strong vs Eventual Consistency: Consistency Models Explained
Strong vs eventual consistency, and the models between them: read-your-writes, monotonic reads and causal order, what each prevents, and what each one costs.
system designdistributed systemsconsistencyinterview
8 min read
Strongly Connected Components: Kosaraju's Two-Pass Algorithm
Strongly connected components with Kosaraju's algorithm: a DFS for finishing order, a DFS on reversed edges, why it works, Tarjan's one pass, checked in Python.
graphsdfsdirected graphsinterview
7 min read
Subarray Sum Equals K: Prefix Sums and a Hash Map in One Pass
Count subarrays that sum to k in O(n): running totals, a hash map of prefix counts, why it starts at 0: 1, and why a sliding window fails on negative numbers.
hash tablesprefix sumsarraysinterview
20 min read
40 System Design Interview Questions, Answered with Trade-offs
40 system design interview questions on scaling, caching, databases, queues, consistency and classic cases, each with a short model answer and what it costs.
system designinterviewdistributed systems
7 min read
Tail Recursion Explained: Why Python Still Hits the Recursion Limit
Tail recursion explained: what makes a call a tail call, why Python keeps every frame anyway, and how an accumulator, a loop or a trampoline removes the stack.
recursionpythoncall stackinterview
8 min read
Task Scheduler With Cooldown: Max-Heap Simulation vs the Formula
Task scheduler with a cooldown: why running the most frequent task first is optimal, the max-heap simulation, the one-line idle formula, and a brute-force test.
heapsgreedyschedulinginterview
8 min read
Thread Pools Explained: Reuse Workers and Cap Concurrency
Thread pools explained: a fixed crew of workers fed from a queue, why map returns input order, how pool size caps concurrency, and the starvation deadlock trap.
concurrencythreadsthread poolinterview
8 min read
How Many Threads? Sizing a Thread Pool for CPU and IO Work
How to size a thread pool: cores for CPU-bound work, the wait-to-compute rule for IO-bound work, Little's law, and why the longest task is a floor on the time.
concurrencythread poolperformanceinterview
9 min read
Thread Safety Explained: Confine, Freeze, or Lock
What thread-safe code means and how to design it: confine state to one thread, make shared data immutable, then guard the rest with one documented lock.
concurrencythreadspythoninterview
7 min read
Threads vs Processes: Shared Memory, Isolation and the GIL
Threads vs processes explained: shared memory against isolation, what a crash takes down, why data must be copied between processes, and when the GIL decides.
concurrencyoperating systemspythoninterview
6 min read
Top K Frequent Elements: Bucket Sort in O(n)
Top k frequent elements in O(n): count with a hash map, drop each value into the bucket named by its count, walk down, and check it against a heap in Python.
hash tablesbucket sorttop kinterview
8 min read
Types of Binary Trees: Full, Complete, Perfect and Balanced
Binary tree types explained: full vs complete vs perfect vs balanced vs degenerate, how to test each one, the height bounds, and why heaps are complete.
treesbinary treedata structuresinterview
7 min read
Unbounded Knapsack Explained: One Forward Loop, Unlimited Copies
Unbounded knapsack explained: why looping capacity forwards lets an item be reused, the one loop that splits it from 0/1, and how coin change fits in.
dynamic programmingknapsackarraysinterview
7 min read
Valid Palindrome: Two Pointers From Both Ends
Valid palindrome with two pointers: skip punctuation, compare case-blind, stop at the first mismatch, then the one-deletion follow-up and a brute-force check.
stringstwo pointerspalindromeinterview
8 min read
Vector Databases Explained: Exact vs Approximate Nearest Neighbours
Vector databases explained with a toy index: exact search against approximate nearest neighbours, what recall costs, and why filters and dimensions matter.
ai mldatabasessystem designinterview
8 min read
Vertical vs Horizontal Scaling: Scale Up or Scale Out?
Vertical vs horizontal scaling explained: the ceiling of one big machine, why scaling out needs stateless servers, the availability math, and when to switch.
system designscalabilitydistributed systemsinterview
8 min read
WebSockets vs Polling vs Server-Sent Events Explained
WebSockets vs polling vs server-sent events: the HTTP upgrade handshake, frames and masking, the latency and request cost of each, and scaling open sockets.
system designwebsocketsrealtimeinterview
8 min read
What Are Embeddings? Meaning as a List of Numbers
Embeddings explained from scratch: how text becomes a vector, why similar meanings land close, mean pooling and its trap, and why two models never mix.
ai mlembeddingsvector searchinterview
8 min read
What Is Big-O Notation? The Definition and the Rules
Big-O notation explained from its definition: what f(n) = O(g(n)) means, why constants and lower terms drop, and Big-O vs Big-Theta vs Big-Omega vs cases.
big ocomplexityalgorithmsinterview
8 min read
What Is Dynamic Programming? Overlapping Subproblems Explained
What dynamic programming is and how to spot it: overlapping subproblems, optimal substructure, why merge sort is not DP, and a four-step recipe with code.
dynamic programmingrecursionmemoizationinterview
8 min read
Which Sorting Algorithm to Use: Four Questions That Decide
How to choose a sorting algorithm: input size, nearly sorted data, small integer ranges and stability decide between insertion, counting, merge and quick sort.
sortingalgorithmsbig ointerview
7 min read
Word Ladder: BFS on a Graph You Never Build
Word ladder and other implicit graphs: generate neighbours on demand, keep a seen set, rebuild the path from parents, and check it against an explicit graph.
graphsbfsshortest pathinterview
8 min read
Word Search in a Grid: Backtracking With Pruning, Step by Step
Word search on a letter grid with backtracking: mark and restore visited cells, prune on the first wrong letter, the complexity bound, and a brute-force check.
backtrackingmatrixdfsinterview
7 min read
Word Search II: Trie + Backtracking on a Grid
Word search II explained: put the words in a trie, walk the grid once, prune as soon as a path stops being a prefix, and check it against one-word search.
triesbacktrackingmatrixinterview
8 min read
Z Algorithm Explained: Linear-Time Pattern Matching With a Z-Box
The Z algorithm explained: what z[i] measures, how the z-box reuses earlier matches, why the scan is O(n), and how to find every pattern occurrence in one pass.
stringspattern matchingtwo pointersinterview
8 min read
AWS IAM Policy Evaluation: Why an Explicit Deny Beats Any Allow
How AWS decides whether a request is allowed: default deny, explicit allow, explicit deny wins, and the guardrail policies that can only take access away.
awsiamsecuritycloudinterview
9 min read
AWS Lambda Cold Starts Explained: Init, Concurrency, Provisioning
What a Lambda cold start is, what runs in the init phase, how concurrency is counted, and when reserved or provisioned concurrency actually helps with latency.
awsserverlesslambdasystem designinterview
9 min read
AWS VPC: Public vs Private Subnets, Security Groups vs NACLs
What makes an AWS subnet public, how private subnets reach out through NAT, and how stateful security groups differ from stateless NACLs, with a toy model.
awsnetworkingsecuritysystem designinterview
7 min read
Climbing Stairs: From Exponential Recursion to O(1) Space DP
Why ways(n) = ways(n-1) + ways(n-2), why plain recursion makes 242,785 calls for 25 stairs, and how two variables replace the whole DP table in O(1) space.
dynamic programmingrecursionfibonacciinterview
9 min read
CloudFront Caching Explained: Cache Keys, TTLs and Invalidation
How CloudFront caches at edge locations and regional edge caches, how the cache key and TTLs decide hits, and why versioned file names beat invalidations.
awscachingcdnsystem designinterview
8 min read
Copy List With Random Pointer: Hash Map vs Interleaving
Deep-copy a linked list whose nodes also point at random nodes: the two-pass hash map, the O(1) extra space interleaving trick, and a randomised check of both.
linked listshash mappointersinterview
7 min read
Counting Sort vs Radix Sort: Sorting Without Comparisons
How counting sort beats O(n log n) on small integer ranges, why radix sort needs every pass to be stable, and when each is the right choice over a normal sort.
sortingbig oalgorithmsinterview
8 min read
Deadlock Explained: The Four Conditions and How to Break Them
A deadlock needs four conditions at once: mutual exclusion, hold and wait, no preemption and circular wait. Break any one and it cannot happen. Code included.
concurrencylocksdeadlockinterview
9 min read
Design a Notification System: Queues, Preferences, Idempotency
A system design walkthrough for push, email and SMS notifications: why a queue sits in the middle, how preferences apply, and how idempotency keys stop dupes.
system designqueuesdistributed systemsinterview
8 min read
Docker Image Layers and Build Cache: Why Dockerfile Order Matters
How Docker image layers and the build cache work, why one edited file can reinstall every dependency, and how multi-stage builds ship only the build output.
dockerkubernetescachingdevopsinterview
14 min read
40 Docker and Kubernetes Interview Questions, Answered
40 Docker and Kubernetes interview questions on images, networking, Pods, rollouts, Services, probes, autoscaling and storage, checked against official docs.
dockerkubernetesinterviewsystem design
9 min read
DynamoDB Hot Partitions: Why Writes Throttle and How to Shard
Why one busy partition key throttles a DynamoDB table with spare capacity, how per-partition limits work, and how random or calculated suffixes spread the load.
awsdatabasessystem designinterview
7 min read
Encode and Decode Strings: Why Length Prefixes Beat Delimiters
Turn a list of strings into one string and back: why any delimiter breaks, how length-prefix framing survives every character, escaping, and binary framing.
stringsserializationdesigninterview
7 min read
Group Anagrams: Sorted Key vs Letter-Count Key, Explained
Group anagrams in one pass by giving every word a canonical key. Sorted letters vs a 26-count tuple, their costs, and why a sum of character codes is a trap.
hash tablesstringssortinginterview
8 min read
Huffman Coding Explained: Why Merging the Two Rarest Symbols Works
Huffman coding builds an optimal prefix code by merging the two rarest symbols with a min-heap. The greedy proof idea, code, decoding, and the edge cases.
greedyheapstreescompressioninterview
7 min read
Implement a Trie: Insert, Search and startsWith Explained
How a trie (prefix tree) stores words one character per edge, why every node needs an end-of-word flag, and insert, search and startsWith in O(L) time each.
triestreesstringsdata structuresinterview
9 min read
Kubernetes Liveness vs Readiness vs Startup Probes Explained
What each Kubernetes probe does when it fails, the default thresholds, how startup probes protect slow boots, and how a bad liveness probe causes cascades.
kubernetesreliabilitydevopssystem designinterview
8 min read
Kubernetes Rolling Updates Explained: maxSurge and maxUnavailable
How a Deployment replaces v1 Pods with v2 without downtime, what maxSurge and maxUnavailable bound, how they round, and why a bad release stalls safely.
kubernetesdeploymentsdevopsinterview
9 min read
Kubernetes Services vs Ingress: ClusterIP, NodePort, LoadBalancer
How Kubernetes Services give changing Pods one stable name, what ClusterIP, NodePort and LoadBalancer do, and how Ingress routes HTTP by host and path to them.
kubernetesnetworkingdevopssystem designinterview
8 min read
Largest Rectangle in Histogram: The Monotonic Stack in O(n)
The largest rectangle in a histogram in O(n): how a monotonic stack finds each bar's two walls, why a trailing zero flushes it, and the binary-matrix follow-up.
monotonic stackstacksarraysinterview
8 min read
Meeting Rooms II: Minimum Rooms With a Min-Heap or a Sweep
Find the minimum number of meeting rooms with a min-heap of end times or two sorted lists. Why both count peak overlap, and the tie at equal times explained.
intervalsheapssortinggreedyinterview
7 min read
Min Stack: Get the Minimum in O(1) With a Second Stack
Design a stack whose push, pop, top and getMin all run in O(1). The shadow stack of running minimums, a leaner variant, and the duplicate bug that breaks it.
stacksdata structuresdesigninterview
8 min read
Partition Equal Subset Sum: The 0/1 Knapsack in Disguise
Can an array split into two equal-sum halves? A reachable-sums DP in O(n * sum), why its loop runs backwards, a bitset version, and how to recover the subset.
dynamic programmingknapsacksubset suminterview
8 min read
Producer-Consumer With a Bounded Buffer: Conditions and Sentinels
Why the queue between producers and consumers must be bounded, how to build one from a lock and two condition variables, and how to shut consumers down.
concurrencythreadsqueuesinterview
8 min read
Rabin-Karp Rolling Hash Explained: O(1) Window Updates
How a rolling hash turns each text window into one number updated in O(1), why hash matches still need a character check, and how collisions set the worst case.
stringshashingsliding windowinterview
7 min read
Race Conditions and Mutexes Explained: The Lost Update
Why count += 1 loses updates when two threads share it, every interleaving that causes it, and how a mutex removes those schedules instead of speeding code up.
concurrencythreadslocksinterview
9 min read
RAG Explained: Retrieval-Augmented Generation Step by Step
How retrieval-augmented generation works: chunk, embed, retrieve, then prompt. A runnable toy pipeline, where it fails, and how to explain RAG in an interview.
ai mlembeddingsllmsystem designinterview
7 min read
Search a 2D Matrix: Staircase Walk vs Binary Search
Two sorted-matrix problems that look alike: the top-right staircase walk in O(m + n), a flattened binary search in O(log mn), and how to tell which you have.
searchingmatrixbinary searchinterview
8 min read
Serialize and Deserialize a Binary Tree With Preorder and Null Markers
Turn a binary tree into a string and back with a preorder walk and a marker for every missing child. Why the markers matter, the BFS format, and the costs.
treesrecursionstringsinterview
8 min read
Shortest Path in an Unweighted Graph: BFS With Parent Pointers
Why breadth-first search finds the fewest-edge path on an unweighted graph, how parent pointers rebuild the route, and the grid version with a checked BFS.
graphsbfsshortest pathinterview
8 min read
SQL GROUP BY and HAVING Explained: WHERE vs HAVING
How GROUP BY folds rows into one row per group, why aggregates belong in HAVING and not WHERE, and what COUNT, SUM and NULL really do. Each query run in SQLite.
sqldatabasesaggregationinterview
8 min read
SQL Indexes Explained: Full Scan vs Index Search, With Query Plans
What an index is, how to read SCAN vs SEARCH in a query plan, why a composite index only helps its leftmost columns, and what indexes cost on every write.
sqldatabasesindexesinterview
9 min read
SQL Isolation Levels Explained: Dirty, Non-Repeatable, Phantom
Read uncommitted, read committed, repeatable read and serializable, and the anomaly each one rules out, with runnable SQLite transactions and the lost update.
sqldatabasestransactionsconcurrencyinterview
8 min read
SQL Window Functions Explained: OVER, PARTITION BY, RANK
What OVER and PARTITION BY do, how RANK, DENSE_RANK and ROW_NUMBER differ on ties, and the default frame that makes running totals jump. Every query run.
sqldatabaseswindow functionsinterview
8 min read
SQS vs SNS vs EventBridge: Queue, Topic or Event Bus?
When to use SQS, SNS or EventBridge: pull from a queue, push a copy to every subscriber, or route by content. Plus fan-out, dead-letter queues and idempotency.
awssystem designmessaginginterview
8 min read
Tokenization Explained: How LLMs Split Text Into Subword Tokens
Why language models read subword tokens, not words or letters: how byte-pair encoding learns merges, greedy matching, and why token counts set cost and context.
ai mlllmtokenizationstrings
7 min read
Valid Anagram and Frequency Counting With a Hash Map
Count once, answer many questions: valid anagram, first unique character and most common item in O(n) with a hash map, plus the sorting version it replaces.
hash tablesstringscountinginterview
7 min read
Vertical Order Traversal of a Binary Tree: BFS With Columns
Read a binary tree column by column: give each node a column number, fill the columns in BFS order, avoid the final sort, and handle the sorted-ties variant.
treesbfshash mapinterview
8 min read
0/1 Knapsack Problem: Dynamic Programming Step by Step
How 0/1 knapsack is solved with a table of capacities, why the one-row version must loop backwards, and why sorting by value per kilo gives the wrong answer.
dynamic programmingknapsackoptimizationinterview
10 min read
50 AWS Interview Questions, Answered Visually (Part 2: Architecture & Scenarios)
25 AWS interview questions on messaging, CloudFront, containers, CloudWatch, cost, disaster recovery and a full design walkthrough, checked against AWS docs.
awsinterviewcloudsystem design
10 min read
50 AWS Interview Questions, Answered Visually (Part 1: Core Services)
25 AWS interview questions on IAM, S3, EC2, Auto Scaling, Lambda, VPC, RDS and DynamoDB, with short model answers checked against the AWS documentation.
awsinterviewcloudsystem design
7 min read
Binary Tree Level Order Traversal: BFS, Queues and DFS Orders
Level order with a queue, the len(queue) trick that splits the rows, how it differs from pre-, in- and postorder, and when the queue costs more than recursion.
treesbfsqueuetraversalinterview
8 min read
Is a Graph Bipartite? BFS Two-Colouring and Odd Cycles
How BFS two-colouring decides whether a graph splits into two sides, why an odd cycle is the only thing that can stop it, and the disconnected-graph bug.
graphsbfsbipartiteinterview
7 min read
Bit Masks Explained: Set, Clear, Toggle and the Power-of-Two Test
How one shifted 1 reads, sets, clears and flips any bit, why n & (n - 1) removes the lowest set bit, and the precedence trap that breaks it in C and Java.
bit manipulationmasksinterview
8 min read
Cyclic Sort and First Missing Positive: O(n) Time, O(1) Space
When values run from 1 to n, each value knows its own index. How cyclic sort uses that to find missing numbers, duplicates and the first missing positive.
arrayssortingin placeinterview
8 min read
Detect a Cycle in a Graph: Directed vs Undirected
Why one visited set cannot find cycles in a directed graph, how white-grey-black colouring fixes it, and the parent check or union-find for undirected graphs.
graphsdfscycle detectioninterview
8 min read
Dutch National Flag Algorithm: Sort Colors in One Pass
Sort an array of 0s, 1s and 2s in one pass and O(1) space with three pointers. Why the cursor stays put after one swap, and how the idea powers 3-way quicksort.
arraystwo pointerssortinginterview
7 min read
Gas Station Problem: Why the One-Pass Greedy Works
The gas station problem in O(n): one sweep, two running totals. Why a failed stretch rules out every start inside it, with the proof and a brute-force check.
greedyarraysprefix sumsinterview
8 min read
K Closest Points to Origin: Max-Heap vs Sort vs Quickselect
Why a heap of size k keeps the farthest point on top, when sorting or quickselect wins instead, and why squared distance is enough. Every version tested.
heapspriority queuetop kinterview
8 min read
Kruskal vs Prim: Minimum Spanning Tree Algorithms Compared
Kruskal sorts edges and joins islands with union-find; Prim grows one tree from a heap. How each works, why both are correct, and when to pick which, in Python.
graphsminimum spanning treeunion findgreedyinterview
7 min read
Longest Common Subsequence: The DP Grid Explained
How the longest common subsequence is found with a grid of prefix answers, how to read the sequence back out, and the two-row version that saves memory.
dynamic programmingstringslcsinterview
7 min read
Longest Palindromic Substring: Expand Around Center in O(n²)
Find the longest palindromic substring by growing from all 2n − 1 centres: odd and even cases, O(n²) time with O(1) memory, and a brute-force check in Python.
stringspalindromestwo pointersinterview
7 min read
Lowest Common Ancestor: BST Walk vs Binary Tree Recursion
Two ways to find the lowest common ancestor: an O(h) walk that uses BST ordering, and an O(n) recursion for any binary tree. Why the first fails off a BST.
treesbinary search treerecursioninterview
7 min read
N-Queens Explained: Backtracking With Pruning
How the N-Queens problem is solved one row at a time, how three sets check column and diagonal attacks in O(1), and how much of the board pruning never visits.
backtrackingrecursionpruninginterview
7 min read
Reverse a Linked List: Iterative and Recursive, Step by Step
Reverse a singly linked list with three pointers in O(n) time and O(1) space, then recursively, and see why the recursive version fails on long lists in Python.
linked listpointersrecursioninterview
8 min read
Search in Rotated Sorted Array: Binary Search That Still Works
A sorted array rotated at an unknown point can still be searched in O(log n). How to find the sorted half, locate the rotation, and handle duplicate values.
binary searcharrayssearchinginterview
8 min read
SQL Joins Explained Visually: INNER, LEFT and FULL OUTER
What INNER, LEFT and FULL OUTER joins keep when a row has no match, why duplicates multiply rows, and the WHERE clause that turns a LEFT JOIN into an INNER one.
sqldatabasesjoinsinterview
7 min read
Word Break Problem: Dynamic Programming Over Cut Points
Solve word break with a boolean table over prefixes: why greedy fails, why plain recursion explodes, how to recover the words, and a brute-force check.
dynamic programmingstringsword breakinterview
8 min read
Design a URL Shortener: A System Design Interview Walkthrough
A URL shortener design end to end: the estimates, the API, base62 counter keys versus random keys, a cache on the read path, and why the redirect is a 302.
system designhashingcachinginterview
7 min read
Interval Scheduling: Why Earliest Finish Time Is the Right Greedy
Earliest start, shortest first, fewest conflicts: all plausible, all wrong. The counterexamples, the exchange argument for earliest finish, and a brute force.
greedyintervalssortinginterview
8 min read
KMP Algorithm Explained: Building the Failure Table Step by Step
What the KMP failure table (LPS array) stores, why a mismatch falls back to the border of a border, and why the search never re-reads a character of the text.
stringskmppattern matchinginterview
8 min read
LFU vs LRU Cache: Which Eviction Policy Wins, and When
LFU and LRU side by side: an O(1) LFU built from frequency buckets and a floor, two workloads where each policy wins, and a brute-force eviction check.
cachinghash tableslfulruinterview
7 min read
Rotate a Matrix 90 Degrees In Place: Transpose, Then Reverse
Rotate an n × n matrix 90° clockwise in place: transpose then reverse rows, the four-way ring swap, the counter-clockwise twin, and a brute-force check.
matrixarraysin placeinterview
7 min read
Sliding Window Median: Two Heaps and Lazy Deletion
Find the median of every window with two heaps. The hard part is removal: a leaving value is marked dead, not searched for, and popped when it reaches a root.
heapssliding windowtwo heapsinterview
7 min read
Sliding Window vs Two Pointers: How to Tell Which One Fits
Both use two indices, but they solve different questions. Three checks that pick the right one — and the negative-numbers case where neither works, tested.
sliding windowtwo pointersarrayspatternsinterview
7 min read
Spiral Matrix Traversal: The Four-Boundary Method
How to read a matrix in spiral order with four shrinking walls, why two small checks stop single rows being read twice, and how to test it against a plain walk.
matrixarrayssimulationinterview
7 min read
Subsets and Permutations: One Backtracking Template
Subsets and permutations are the same backtracking loop with a different branch rule. Choose, explore, un-choose — plus the clean fix for duplicate values.
backtrackingrecursioncombinatoricsinterview
7 min read
Top K Elements With a Heap: Why Not Just Sort?
Sorting everything to keep ten items does far more work than needed. How a size-k min-heap gets top K in O(n log k), measured, plus when sorting is fine.
heapspriority queuetop kbig ointerview
7 min read
How to Validate a Binary Search Tree: The Range Method
Why checking each node against its parent does not validate a BST, how passing a min/max range down fixes it in O(n), and the in-order check that agrees.
treesbinary search treerecursioninterview
7 min read
XOR Tricks Explained: Single Number, Missing Number, Two Singles
Why x ^ x = 0 finds the single number in one pass and O(1) memory, how the same idea finds a missing number and two singles, and where XOR swap silently fails.
bit manipulationxorarraysinterview
7 min read
Attention, Intuitively: What Does the Word 'Bank' Listen To?
Attention is a weighted average whose weights are recomputed for every input. Queries, keys, values and the square-root scaling, built from scratch in Python.
ai mlattentiontransformersinterview
8 min read
Edit Distance Explained: The DP Table, Cell by Cell
How Levenshtein edit distance fills its table: what each cell means, why a match copies the diagonal, how to read back the edits, and a check against a BFS.
dynamic programmingstringsedit distanceinterview
8 min read
Heap Sort vs Quick Sort: What the Heap Actually Buys You
Heap sort guarantees n log n in place, yet quick sort usually wins. Measured: comparisons, simulated cache misses, the sorted-input trap, and the hybrid.
sortingheap sortquick sortbig ointerview
7 min read
Merge K Sorted Lists: Min-Heap vs Divide and Conquer
Merge k sorted lists in O(n log k): the k-heads min-heap, the pairwise divide-and-conquer merge, why merging one by one is O(n k), and the heap tie-break trap.
heapsk way mergelinked listsinterview
7 min read
Number of Islands: BFS vs DFS Flood Fill, and the Recursion Trap
Count connected land cells in a grid: the sweep-and-flood idea, BFS and DFS side by side, why recursive DFS crashes on a 60 × 60 grid, and a brute-force check.
matrixgraphsflood fillbfsdfs
7 min read
Union-Find Explained: Path Compression and Union by Size
Union-Find answers 'are these connected?' in near-constant time. How path compression and union by size keep its trees flat, and why each is a few lines.
union findgraphsdata structuresbig ointerview
8 min read
Consistent Hashing Explained: Why Keys Barely Move
Adding a fifth cache server with key modulo n remaps 80% of keys; on a hash ring it moves about 20%. The ring, virtual nodes and the failure case, measured.
system designconsistent hashingcachingdistributed systemsinterview
7 min read
Floyd's Cycle Detection: Why Fast and Slow Pointers Must Meet
Two pointers, one list, O(1) memory. Why fast cannot skip past slow, the short proof that finds where the loop begins, and the same trick on a duplicate array.
linked liststwo pointerscycle detectioninterview
7 min read
Longest Increasing Subsequence in O(n log n), Explained
From the O(n²) DP to the tails array and binary search: why tails stays sorted, why it isn't the answer itself, and how to rebuild the real subsequence.
dynamic programmingbinary searchsubsequencesinterview
7 min read
Merge Intervals: The Sort-Then-Sweep Pattern Explained
Why merging intervals is sort by start, then one sweep with a single open block. The proof, the touching-edges question, and the sort-key bug to avoid.
intervalssortingsweep linebig ointerview
8 min read
Rate Limiting Algorithms Compared: Token Bucket vs Sliding Window
Fixed window, sliding log, sliding counter and token bucket on the same traffic: who lets a boundary burst through, what each costs, and which to pick.
system designrate limitingapi designinterview
8 min read
Backtracking vs Dynamic Programming: When to Prune or Memoize
Both start from the same recursion tree. The one question that decides between them — does the future depend on the whole path? — with call counts measured.
backtrackingdynamic programmingrecursioninterview
7 min read
Coin Change: Why Greedy Fails and Dynamic Programming Doesn't
Largest-coin-first works for everyday change and breaks on coins 1, 3, 4. The DP table that always works, how to rebuild the coins, and a greedy-safety check.
dynamic programminggreedycoin changeinterview
7 min read
Dijkstra's Algorithm Step by Step: The Heap, the Relax, the Proof
A full Dijkstra trace on a four-node graph: every heap pop, every relaxation, the stale entries, path rebuilding, and a brute-force check on 2,000 graphs.
graphsshortest pathdijkstraheapsinterview
8 min read
LRU Cache From Scratch: Hash Map + Doubly Linked List
Build an O(1) LRU cache without OrderedDict: why it takes a hash map and a doubly linked list, what sentinel nodes save you, and the bugs interviewers look for.
lldlinked listshash tablescachinginterview
7 min read
Trie vs Hash Set: Which One for Prefix Search?
A hash set wins exact lookups; a trie wins anything involving a prefix. Measured on 38,000 words: what each query costs, what the trie's memory buys, and when.
trieshash tablesstringsinterview
7 min read
Binary Search on the Answer: How to Spot the Pattern
No sorted array in sight, yet the fast solution is a binary search. The three signals that give it away, a reusable template, and a brute-force check.
binary searchsearchingpatternsinterview
7 min read
Topological Sort Explained: Course Scheduling With Kahn's Algorithm
How Kahn's algorithm orders tasks with prerequisites, why a leftover node proves a cycle, and the layer-by-layer variant that counts the minimum semesters.
graphstopological sortbfsinterview
7 min read
Two Sum: Why the Hash Map Beats Sorting (and When It Doesn't)
Two Sum has two good answers: a one-pass hash map and sort-plus-two-pointers. What each costs, the self-pairing bug, and the cases where sorting wins.
hash tablestwo sumtwo pointersbig ointerview
7 min read
Dijkstra vs Bellman-Ford: When the Greedy Shortcut Fails
Both find shortest weighted paths, but only one survives negative edges. The exact moment Dijkstra's greedy promise breaks and how Bellman-Ford avoids it.
graphsshortest pathdijkstrabellman fordinterview
7 min read
Sliding Window Maximum With a Deque, Step by Step
The O(n) sliding window maximum, traced step by step: why smaller older values can be thrown away, what each end of the deque does, and the bugs to avoid.
stacks queuesdequesliding windowbig ointerview
7 min read
Cosine Similarity Explained: Why Search Ignores Length
The measure behind vector search, taken apart: what the angle means, why a dot product alone favours long documents, and when to normalise once instead.
ai mlembeddingsvector searchinterview
7 min read
BFS Explained Visually: Why It Finds the Shortest Path
Breadth-first search, proved rather than asserted: what the queue guarantees, how to rebuild the path from parents, and why DFS cannot do the same job.
graphsbfsshortest pathinterview
7 min read
Kadane's Algorithm Explained: Maximum Subarray in O(n)
The one-line decision behind maximum subarray, why a negative carry-in is always worth dropping, and how to return the slice instead of just the number.
arrayskadanes algorithmdynamic programmingbig o
6 min read
Valid Parentheses: Why a Stack Is the Whole Answer
The bracket-matching question, solved properly: why counting fails, what the stack actually stores, and the empty-stack cases that decide the verdict.
stacks queuesstringsinterview
7 min read
DFS vs BFS: When to Use Which, and How to Decide Fast
Same traversal, one container apart. What a stack buys you, what a queue guarantees, and the four questions that pick the right one in a single sentence.
graphsdfsbfstraversalinterview
6 min read
Sliding Window Explained Visually: From O(n·k) to O(n)
How reusing the previous window turns a repeated subarray scan into one linear pass, plus the variable-size form behind most substring interview questions.
arrayssliding windowstringsbig o
6 min read
Prefix Sums Explained Visually: O(1) Range Queries
One pass of running totals turns every range-sum question into a subtraction, and the same idea counts subarrays in linear time. Why the leading zero matters.
arraysprefix sumshash tablesbig ointerview
6 min read
Two Pointers Explained Visually: One Pass Instead of Two Loops
Why two indices walking a sorted array turn an O(n²) pair search into O(n), the elimination argument behind it, and the three shapes the pattern takes.
arraystwo pointersbig ointerview
7 min read
Monotonic Stack Explained: The O(n) Next-Greater Trick
A stack kept in order turns a quadratic scan into one linear pass. What it stores, why each index moves twice at most, and how to spot the pattern fast.
stacks queuesmonotonic stackarraysbig ointerview
7 min read
How Hash Tables Work: Where O(1) Lookup Comes From
Build a hash table in twenty lines and see what really makes a lookup constant time, what a collision costs, and why its worst case is still linear time.
hash tablesdata structuresbig ointerview
7 min read
Merge Sort vs Quick Sort: How to Choose, and Why
Both sort in n log n on a good day, but they fail differently. The split that decides it: guaranteed time and stability, or in-place memory and speed.
sortingmerge sortquick sortbig ointerview
7 min read
Big-O Complexity Classes, From O(1) to O(2ⁿ)
The six growth curves that interviews actually use, what separates them, and how to name the complexity of your own code in one pass over all its loops.
big ocomplexityinterview
7 min read
Binary Search Explained Visually (and Its Off-By-One Traps)
How halving a sorted array finds any value in about log n probes, the loop invariant that makes it correct, and the boundary bugs that quietly break it.
searchingbinary searchbig ointerview
6 min read
Bubble Sort Explained Visually: Why It's O(n²)
Bubble sort taken apart pass by pass: how the largest value floats right, where the quadratic cost comes from, and the flag that saves the sorted case.
sortingbig ointerview