Skip to main content
Code Bank
925 questions · Python · DSA · Algorithms
Python
Data Structures
Algorithms
Patterns
System Design Coding
Showing 925 of 925
#1

Reverse a String

Easyamazongooglenew-grad

Given a string s, return the string reversed. Implement it without using any built-in reverse function.

Examples

Input: s = "hello"
Output: "olleh"
Input: s = "Python"
Output: "nohtyP"
Input: s = "a"
Output: "a"

Constraints

  • 0 <= len(s) <= 10^5
  • s consists of printable ASCII characters
Hints (2)
  1. Try two pointers from both ends
  2. Python slicing s[::-1] is the idiomatic one-liner

Solutions

Time: O(n)Space: O(n)

Convert to a list, swap characters from both ends moving inward until the pointers meet.

Loading editor...

Python and DSA Coding Question Bank - 200+ Interview Questions

Free coding interview prep with runnable Python solutions. Practice two sum, linked lists, binary trees, dynamic programming, graph algorithms, sliding window, and more. Filter by topic, company (Amazon, Google, Meta, Microsoft), and level (SWE1, SWE2, SWE3). Every question includes multiple solutions with time and space complexity analysis and an interactive Python editor powered by Pyodide.

Reverse a String - Python Solution | Engineers of AI

Reverse a string in Python using two-pointer O(n) and slice approaches. Common Amazon and Google new grad interview question.

Topics: strings

Companies: amazon, google

Level: new-grad

Two Pointers: Convert to a list, swap characters from both ends moving inward until the pointers meet.

Slice: Use Python slice notation s[::-1] to create a reversed copy in one expression.

Count Vowels in a String - Python Solution | Engineers of AI

Count vowels in a string using Python set lookup and generator expressions. Easy Amazon interview question for new grads.

Topics: strings

Companies: amazon

Level: new-grad

Set Lookup: Iterate over each character and check membership in a vowel set for O(1) per lookup.

Check Palindrome - Python Solution | Engineers of AI

Check if a string is a palindrome in Python using two-pointer and slice approaches. Common Amazon and Microsoft interview question.

Topics: strings, two-pointers

Companies: amazon, microsoft

Level: new-grad

Two Pointers: Clean the string to only alphanumeric lowercase chars, then use two pointers from both ends.

Slice Compare: Clean the string then compare it against its reverse using slice notation.

FizzBuzz - Python Solution | Engineers of AI

Solve FizzBuzz in Python with a clean string concatenation approach. Classic interview question at Amazon, Google, and Meta.

Topics: strings, lists

Companies: amazon, google, meta

Level: new-grad

String Concatenation: Build the token by concatenating "Fizz" and "Buzz" conditionally, falling back to str(i).

Find Duplicates in a List - Python Solution | Engineers of AI

Find duplicates in a list using hash map counting and two-set O(n) approaches. Common Amazon and Google interview question.

Topics: lists, hash-map

Companies: amazon, google

Level: new-grad, swe2

Hash Map Count: Count occurrences with a dict, then return keys whose count exceeds 1.

Two Sets: Track a "seen" set and a "duplicates" set — add to duplicates when a number is already seen.

Flatten a Nested List - Python Solution | Engineers of AI

Flatten an arbitrarily nested list in Python using recursion and iterative stack. Common Google and Meta interview question.

Topics: lists, recursion

Companies: google, meta

Level: swe2

Recursive: Recursively extend result for sub-lists, append directly for integers. Stack depth = nesting depth d.

Iterative Stack: Use an explicit stack (reversed items) to process elements without recursion limits.

List Comprehension Filter and Transform - Python | Engineers of AI

Filter and transform a list using Python list comprehensions. Easy Amazon new grad interview question.

Topics: lists, comprehensions

Companies: amazon

Level: new-grad

List Comprehension: A single list comprehension with an if clause selects evens and squares them in one expression.

Word Frequency Counter - Python Solution | Engineers of AI

Build a word frequency counter in Python using Counter and dict. Common Amazon, Google, Microsoft interview question.

Topics: dicts, strings

Companies: amazon, google, microsoft

Level: new-grad

collections.Counter: Normalize to lowercase, split on whitespace, and count with collections.Counter.

Implement a Stack Using a List - Python Solution | Engineers of AI

Implement a Stack class in Python using a list with O(1) push, pop, and peek. Common Amazon and Bloomberg OOP interview question.

Topics: stack, oop

Companies: amazon, bloomberg

Level: new-grad, swe2

List-Backed Stack: Use a Python list with append() for push and pop() from the end — both O(1) amortized.

Implement a Queue Using Deque - Python Solution | Engineers of AI

Implement a Queue in Python using collections.deque for O(1) enqueue and dequeue. Common Amazon and Google interview question.

Topics: queue, deque

Companies: amazon, google

Level: new-grad

Deque-Backed Queue: Use collections.deque with append() to enqueue at right and popleft() to dequeue from left.

BankAccount Class - Python OOP Solution | Engineers of AI

Design a BankAccount class in Python with deposit, withdraw, and balance. Common Amazon and Microsoft OOP interview question.

Topics: oop

Companies: amazon, microsoft

Level: new-grad

Basic OOP: Store balance as a private attribute, validate withdrawals, raise ValueError for overdrafts.

Decorator: Timing Function - Python Solution | Engineers of AI

Implement a @timer decorator in Python using functools.wraps and perf_counter. Common Google and Meta SWE2 interview question.

Topics: decorators

Companies: google, meta

Level: swe2

functools.wraps Decorator: Wrap the call with perf_counter before and after, print the delta, return the original result. functools.wraps preserves __name__ and __doc__.

Fibonacci Generator - Python Solution | Engineers of AI

Implement an infinite Fibonacci generator in Python using yield. Common Amazon and Google interview question on generators.

Topics: generators

Companies: amazon, google

Level: new-grad, swe2

Generator Function: Use yield to produce one value at a time while maintaining two running variables.

Context Manager for File Handling - Python Solution | Engineers of AI

Implement a custom context manager in Python with __enter__ and __exit__ for safe file handling. Common Google SWE2 interview question.

Topics: oop, exceptions

Companies: google

Level: swe2

Context Manager Class: __enter__ opens and returns the file; __exit__ closes it and optionally suppresses FileNotFoundError.

Filter Evens with Lambda and Filter - Python Solution | Engineers of AI

Filter even numbers using lambda+filter and list comprehension in Python. Easy Amazon new grad interview question.

Topics: comprehensions, lists

Companies: amazon

Level: new-grad

List Comprehension: A list comprehension with modulo filter — readable and Pythonic.

Lambda + filter(): Pass a lambda to built-in filter() and convert to list — functional programming style.

Email Validator with Regex - Python Solution | Engineers of AI

Validate email addresses in Python using regular expressions and re.fullmatch. Common Amazon and Google SWE2 interview question.

Topics: regex, strings

Companies: amazon, google

Level: swe2

Regex Fullmatch: Use re.fullmatch with a pattern covering local part, @, domain segments, and TLD with minimum 2 chars.

String Formatting: Format a Receipt - Python Solution | Engineers of AI

Format a receipt with aligned columns using Python f-strings. Easy Amazon new grad interview question on string formatting.

Topics: strings

Companies: amazon

Level: new-grad

f-String Formatting: Use f-strings with alignment specifiers to build aligned columns, then append subtotal, tax, and total.

Read and Count Lines from a File - Python Solution | Engineers of AI

Read a file and count lines with exception handling in Python. Common Amazon and Microsoft new grad interview question.

Topics: exceptions

Companies: amazon, microsoft

Level: new-grad

try/except File Read: try/except wrapping a with-statement. Generator expression counts lines without loading the whole file.

Custom Exception Classes - Python Solution | Engineers of AI

Design custom exception hierarchies in Python for payment processing. Common Google and Meta SWE2 OOP interview question.

Topics: exceptions, oop

Companies: google, meta

Level: swe2

Exception Hierarchy: Subclass PaymentError for each specific error type, storing context as attributes and building descriptive messages in __init__.

Type-Hinted Stack Implementation - Python Solution | Engineers of AI

Implement a generic type-hinted Stack using TypeVar and Generic in Python. Common Google and Microsoft SWE2 interview question.

Topics: typing, stack, oop

Companies: google, microsoft

Level: swe2

Generic Stack: Use TypeVar and Generic to parameterize the Stack class, providing type-safe operations with full annotations.

Zip and Enumerate Together - Python Solution | Engineers of AI

Use zip and enumerate together in Python to iterate multiple lists with index. Common Amazon new grad interview question.

Topics: lists

Companies: amazon

Level: new-grad

enumerate + zip: Combine enumerate and zip to iterate with index, name, and score in a single loop.

Default Mutable Argument Bug - Python Solution | Engineers of AI

Understand and fix the Python mutable default argument bug. Common Google and Meta SWE2 interview question on Python gotchas.

Topics: lists

Companies: google, meta

Level: swe2

None Default Pattern: Use None as default and assign a new list inside the body — creates a fresh list per call instead of sharing one object.

*args and **kwargs Variadic Functions - Python Solution | Engineers of AI

Master *args and **kwargs in Python. Common Amazon and Google new grad interview question on variadic functions.

Topics: oop

Companies: amazon, google

Level: new-grad

*args and **kwargs: *args captures positional args as a tuple; **kwargs as a dict. Use functools.reduce for the product.

Closure Counter - Python Solution | Engineers of AI

Implement a closure-based counter factory in Python using nonlocal. Common Google and Meta SWE2 interview question on closures.

Topics: oop

Companies: google, meta

Level: swe2

Closure with nonlocal: Use nonlocal to allow the inner function to mutate the enclosing scope count variable.

Inheritance: Shape Hierarchy - Python Solution | Engineers of AI

Implement a shape hierarchy with inheritance and method overriding in Python. Common Amazon and Microsoft SWE2 interview question.

Topics: oop

Companies: amazon, microsoft

Level: swe2

Inheritance with Override: Base class raises NotImplementedError; each subclass overrides area() with its own formula.

Abstract Base Class: Animal - Python Solution | Engineers of AI

Use Python abc to define abstract classes and enforce interfaces. Common Google SWE2 OOP interview question.

Topics: oop

Companies: google

Level: swe2

ABC with abstractmethod: abc.ABC + @abstractmethod enforces the interface. Python raises TypeError at instantiation if any abstract method is missing.

Custom Iterator: Countdown - Python Solution | Engineers of AI

Implement a custom iterator in Python using __iter__ and __next__. Common Google and Meta SWE2 interview question.

Topics: oop, generators

Companies: google, meta

Level: swe2

Iterator Protocol: __iter__ resets and returns self; __next__ yields and decrements, raising StopIteration when done.

Property Decorator: Temperature Converter - Python Solution | Engineers of AI

Use @property and @setter in Python for a Temperature class with validation. Common Amazon and Google SWE2 interview question.

Topics: oop, decorators

Companies: amazon, google

Level: swe2

@property with Validation: Store Celsius internally; expose both as properties converting on the fly. Celsius setter validates against absolute zero.

Named Tuples: Point and Distance - Python Solution | Engineers of AI

Use collections.namedtuple for a Point and compute Euclidean distance. Easy Amazon new grad Python interview question.

Topics: oop, typing

Companies: amazon

Level: new-grad

namedtuple + math.sqrt: Named tuple gives readable .x .y access; standard Euclidean formula computes distance.

Dataclass: Student Registry - Python Solution | Engineers of AI

Use Python dataclasses to build a Student Registry with filtering and sorting. Common Google and Microsoft SWE2 interview question.

Topics: oop, typing

Companies: google, microsoft

Level: swe2

dataclass + Registry: @dataclass generates boilerplate; __post_init__ validates; Registry methods filter and sort.

Two Sum - Python Hash Map Solution | Engineers of AI

Solve Two Sum in O(n) with a hash map and O(n^2) brute force. Classic Amazon, Google, Meta, Microsoft interview question.

Topics: array, hash-map

Companies: amazon, google, meta, microsoft

Level: new-grad, swe2

Optimal - Hash Map: One pass: for each element x, check if complement (target-x) is in the map. If yes return indices, else store x->index.

Brute Force: Check every pair (i,j) where i<j and return the pair that sums to target.

Best Time to Buy and Sell Stock - Greedy Python Solution | Engineers of AI

Maximize stock profit in O(n) with a greedy scan. Classic Amazon, Google, Meta interview question with full Python solution.

Topics: array, greedy

Companies: amazon, google, meta

Level: new-grad, swe2

Greedy: Track min_price and max_profit in one pass. At each price, update min or compute profit.

Contains Duplicate - Python Set Solution | Engineers of AI

Detect duplicates in an array in O(n) using a Python set. Easy Amazon and Google interview question.

Topics: array, hash-map

Companies: amazon, google

Level: new-grad

Set Length: If len(nums) != len(set(nums)), a duplicate exists.

Early-Exit Set: Iterate and return True as soon as a repeated element is found.

Product of Array Except Self - Python Solution | Engineers of AI

Compute product except self in O(n) without division using prefix and suffix passes. Top Amazon, Google, Meta interview question.

Topics: array, prefix-sum

Companies: amazon, google, meta, microsoft

Level: swe2

Prefix & Suffix Pass: First pass builds prefix products into result. Second pass multiplies by running suffix product from right.

Maximum Subarray - Kadane's Algorithm Python | Engineers of AI

Solve Maximum Subarray in O(n) with Kadane's algorithm. Classic Amazon, Google, Microsoft, Bloomberg interview question.

Topics: array, dynamic-programming

Companies: amazon, google, microsoft, bloomberg

Level: new-grad, swe2

Kadane's Algorithm: Maintain running sum; reset to current element if running sum goes negative. Track global max.

Maximum Product Subarray - Python Solution | Engineers of AI

Find maximum product subarray tracking both max and min products in O(n). Amazon and Google SWE2/SWE3 interview question.

Topics: array, dynamic-programming

Companies: amazon, google

Level: swe2, swe3

Track Max and Min: Track both max and min products ending at each position because a negative product can become the largest when multiplied by another negative.

Find Minimum in Rotated Sorted Array - Python Solution | Engineers of AI

Find minimum in a rotated sorted array in O(log n) with binary search. Common Amazon, Google, Microsoft interview question.

Topics: array, binary-search

Companies: amazon, google, microsoft

Level: swe2

Binary Search: Compare mid with right: if mid > right, minimum is in the right half; otherwise minimum is in the left half (including mid).

Search in Rotated Sorted Array - Python Solution | Engineers of AI

Search a rotated sorted array in O(log n) with modified binary search. Common Amazon, Google, Meta SWE2/SWE3 question.

Topics: array, binary-search

Companies: amazon, google, meta

Level: swe2, swe3

Modified Binary Search: At each step, one half is always sorted. Check if target lies in the sorted half; if so search there, otherwise search the other half.

Three Sum - Python Two Pointers Solution | Engineers of AI

Find all unique triplets summing to zero in O(n^2) with sort + two pointers. Classic Amazon, Google, Meta, Bloomberg interview question.

Topics: array, two-pointers, sorting

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2, swe3

Sort + Two Pointers: Sort the array. Fix element i, then use two pointers l=i+1 and r=n-1 to find pairs that sum to -nums[i]. Skip duplicates.

Container With Most Water - Python Two Pointers | Engineers of AI

Maximize water container area in O(n) using two pointers. Common Amazon, Google, Meta medium interview question.

Topics: array, two-pointers, greedy

Companies: amazon, google, meta

Level: swe2

Two Pointers: Start with left=0 and right=n-1. Area = min(h[l],h[r]) * (r-l). Move the shorter pointer inward; this is the only way to possibly increase area.

Valid Anagram - Python Solution | Engineers of AI

Check if two strings are anagrams using Counter or sorting. Easy Amazon, Google, Microsoft interview question.

Topics: strings, hash-map, sorting

Companies: amazon, google, microsoft

Level: new-grad, swe2

Counter Comparison: Count character frequencies with Counter and compare — O(1) space since alphabet is fixed size.

Sort: Sort both strings and compare — simple and correct, but slower.

Group Anagrams - Python Solution | Engineers of AI

Group anagrams using sorted key hash map in O(n*k log k). Common Amazon, Google, Meta, Microsoft interview question.

Topics: strings, hash-map, sorting

Companies: amazon, google, meta, microsoft

Level: swe2

Sorted Key HashMap: Sort each string to get a canonical key; group strings with the same key using defaultdict.

Longest Common Prefix - Python Solution | Engineers of AI

Find the longest common prefix in a string array in O(S). Easy Amazon, Google, Microsoft interview question.

Topics: strings

Companies: amazon, google, microsoft

Level: new-grad

Horizontal Scan: Take first string as prefix. Shrink it until every other string starts with it.

Valid Parentheses - Python Stack Solution | Engineers of AI

Validate bracket strings with a stack in O(n). Classic Amazon, Google, Meta, Microsoft, Bloomberg interview question.

Topics: strings, stack

Companies: amazon, google, meta, microsoft, bloomberg

Level: new-grad, swe2

Stack: Push opening brackets. For each closing bracket, pop from stack and check if it matches. Return True iff stack is empty at end.

Reverse Words in a String - Python Solution | Engineers of AI

Reverse word order in a string using split, reverse, join in O(n). Common Amazon and Microsoft SWE2 interview question.

Topics: strings, two-pointers

Companies: amazon, microsoft

Level: swe2

Split, Reverse, Join: split() tokenizes (handles extra spaces), reversed() reverses, join() reassembles with single space.

String Compression - Python Solution | Engineers of AI

Run-length encode a string in O(n) with two pointers. Common Amazon, Microsoft, Bloomberg SWE2 interview question.

Topics: strings, two-pointers

Companies: amazon, microsoft, bloomberg

Level: swe2

Two Pointer RLE: Walk the string counting consecutive identical characters; append char and count to result; return shorter of compressed vs original.

Rotate Array - Python Three Reverses Solution | Engineers of AI

Rotate an array in-place in O(n) O(1) space using three reverses. Common Amazon, Google, Microsoft interview question.

Topics: array, two-pointers

Companies: amazon, google, microsoft

Level: swe2

Three Reverses: Reverse whole array, reverse first k elements, reverse remaining n-k elements.

Missing Number - Python Math and XOR Solutions | Engineers of AI

Find the missing number in O(n) O(1) using Gauss sum or XOR trick. Common Amazon, Google, Microsoft new grad interview question.

Topics: array, bit-manipulation

Companies: amazon, google, microsoft

Level: new-grad

Math / Gauss Sum: Expected sum of 0..n is n*(n+1)//2. Missing = expected - actual sum.

XOR: XOR every index (0..n) with every value. Paired values cancel; only the missing number remains.

Single Number XOR Trick - Python Solution | Engineers of AI

Find the single non-duplicate element in O(n) O(1) using the XOR trick. Common Amazon, Google, Meta easy interview question.

Topics: array, bit-manipulation

Companies: amazon, google, meta

Level: new-grad

XOR: XOR all elements together. Duplicate pairs cancel (a ^ a = 0). What remains is the single number.

Move Zeroes - Python Two Pointers Solution | Engineers of AI

Move zeros to the end in-place in O(n) O(1) with two pointers. Easy Amazon and Google interview question.

Topics: array, two-pointers

Companies: amazon, google

Level: new-grad

Two Pointers: Use an insert_pos pointer. Copy non-zero elements to insert_pos. Fill the rest with zeros.

Merge Intervals - Python Sort Solution | Engineers of AI

Merge overlapping intervals in O(n log n) by sorting and scanning. Classic Amazon, Google, Meta, Bloomberg interview question.

Topics: array, sorting

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2, swe3

Sort + Scan: Sort by start. Extend last merged interval if current overlaps, else append new interval.

Insert Interval - Python Solution | Engineers of AI

Insert and merge a new interval in O(n) with three-phase approach. Common Google and LinkedIn SWE2 interview question.

Topics: array

Companies: google, linkedin

Level: swe2

Three-Phase Merge: Collect all intervals ending before new starts, then merge overlapping ones, then append the rest.

Spiral Matrix - Python Boundary Simulation | Engineers of AI

Traverse a matrix in spiral order using boundary simulation. Common Amazon, Google, Microsoft, Bloomberg interview question.

Topics: matrix

Companies: amazon, google, microsoft, bloomberg

Level: swe2

Boundary Simulation: Maintain top/bottom/left/right boundaries. Traverse right, down, left, up in turn, shrinking bounds each time.

Set Matrix Zeroes - Python O(1) Space Solution | Engineers of AI

Set matrix rows and columns to zero in O(m*n) O(1) space using first row/col as markers. Amazon, Google, Microsoft interview question.

Topics: matrix

Companies: amazon, google, microsoft

Level: swe2

O(1) Space Using First Row/Col: Use the first row and first column as markers for which rows/cols need zeroing. Handle the first row/col separately.

Longest Substring Without Repeating Characters - Python | Engineers of AI

Find longest substring without repeating chars in O(n) with sliding window. Top Amazon, Google, Meta, Bloomberg interview question.

Topics: strings, sliding-window, hash-map

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2

Sliding Window + Set: Expand right pointer. When duplicate found, shrink from left until removed. Track max window size.

Optimized Hash Map: Store char->last index. On duplicate, jump left pointer directly to last_index+1 instead of stepping one at a time.

Minimum Window Substring - Python Sliding Window | Engineers of AI

Find minimum window substring in O(|s|+|t|) with sliding window and frequency maps. Hard Amazon, Google, Meta SWE3 question.

Topics: strings, sliding-window, hash-map

Companies: amazon, google, meta

Level: swe3, senior

Sliding Window with Counts: Use two hash maps: required counts from t and current window counts. Track "have" vs "need" to know when window is valid. Expand right, shrink left when valid.

Find All Anagrams in a String - Python Sliding Window | Engineers of AI

Find all anagram positions in a string using fixed sliding window in O(n). Common Amazon and Google SWE2 interview question.

Topics: strings, sliding-window, hash-map

Companies: amazon, google

Level: swe2

Fixed Sliding Window: Use a fixed-size window of len(p). Maintain frequency counts and a "matches" counter to check validity in O(1).

Subarray Sum Equals K - Python Prefix Sum Solution | Engineers of AI

Count subarrays summing to k in O(n) with prefix sum and hash map. Common Amazon, Google, Meta SWE2/SWE3 question.

Topics: array, prefix-sum, hash-map

Companies: amazon, google, meta

Level: swe2, swe3

Prefix Sum + HashMap: At each position, compute prefix sum. If prefix_sum - k exists in the map, those subarrays sum to k. Store prefix sums with their counts.

Trapping Rain Water - Python Two Pointers Solution | Engineers of AI

Compute trapped rainwater in O(n) O(1) with two pointers. Hard Amazon, Google, Meta, Bloomberg senior interview question.

Topics: array, two-pointers, stack

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe3, senior

Two Pointers: Two pointers from both ends. Water at any position = min(left_max, right_max) - height. Process the side with smaller max; that side determines the water level.

Jump Game - Python Greedy Solution | Engineers of AI

Solve Jump Game in O(n) with greedy tracking of farthest reachable index. Common Amazon, Google, Meta, Microsoft interview question.

Topics: array, greedy, dynamic-programming

Companies: amazon, google, meta, microsoft

Level: swe2

Greedy: Track farthest reachable index. If current position exceeds it, we are stuck. Otherwise update farthest.

Reverse Linked List - Python Iterative and Recursive | Engineers of AI

Reverse a singly linked list in O(n) iteratively (O(1) space) and recursively. Classic Amazon, Google, Meta, Microsoft interview question.

Topics: linked-list, recursion

Companies: amazon, google, meta, microsoft

Level: new-grad, swe2

Iterative: Walk with three pointers; redirect each node's next to prev. O(1) extra space.

Recursive: Recurse to the tail; on the way back reverse each link.

Detect Cycle in Linked List - Python Floyd's Algorithm | Engineers of AI

Detect a cycle in a linked list in O(n) O(1) using Floyd's tortoise and hare. Classic Amazon, Google, Meta, Microsoft interview question.

Topics: linked-list, two-pointers

Companies: amazon, google, meta, microsoft

Level: new-grad, swe2

Floyd's Tortoise and Hare: Slow pointer moves 1 step, fast moves 2. If they ever point to the same node, a cycle exists.

Find Middle of Linked List - Python Slow/Fast Pointers | Engineers of AI

Find the middle of a linked list in O(n) O(1) with slow/fast pointers. Common Amazon and Microsoft new grad interview question.

Topics: linked-list, two-pointers

Companies: amazon, microsoft

Level: new-grad

Slow/Fast Pointers: Move slow by 1 and fast by 2. When fast reaches end, slow is at middle.

Merge Two Sorted Lists - Python Solution | Engineers of AI

Merge two sorted linked lists in O(m+n) iteratively and recursively. Classic Amazon, Google, Meta, Microsoft, Bloomberg interview question.

Topics: linked-list, recursion

Companies: amazon, google, meta, microsoft, bloomberg

Level: new-grad, swe2

Iterative with Dummy: Use a dummy head. At each step append the smaller of list1/list2 heads. Append remaining.

Remove Nth Node from End of List - Python Solution | Engineers of AI

Remove nth node from end in one pass using two pointers. Common Amazon, Google, Microsoft SWE2 interview question.

Topics: linked-list, two-pointers

Companies: amazon, google, microsoft

Level: swe2

Two Pointers One Pass: Advance fast pointer n+1 steps ahead. Then move both until fast is None. Slow is just before the node to delete.

Palindrome Linked List - Python Solution | Engineers of AI

Check if a linked list is palindrome in O(n) O(1) by reversing the second half. Common Amazon, Google, Meta interview question.

Topics: linked-list, two-pointers, stack

Companies: amazon, google, meta

Level: new-grad, swe2

Reverse Half: Find middle with slow/fast, reverse second half, compare both halves, then restore.

Intersection of Two Linked Lists - Python Solution | Engineers of AI

Find linked list intersection in O(m+n) O(1) with two-pointer switch trick. Common Amazon and Microsoft interview question.

Topics: linked-list, two-pointers, hash-map

Companies: amazon, microsoft

Level: new-grad

Two Pointer Switch: Each pointer traverses both lists. After m+n steps they either meet at intersection or both reach None together.

Remove Duplicates from Sorted List - Python Solution | Engineers of AI

Remove duplicates from a sorted linked list in O(n) O(1). Easy Amazon and Google new grad interview question.

Topics: linked-list

Companies: amazon, google

Level: new-grad

Single Pass: Walk the list; skip nodes whose value equals the current node's value.

Insert into Circular Linked List - Python Solution | Engineers of AI

Insert a node into a sorted circular linked list handling all edge cases. Common Google and Amazon SWE2 interview question.

Topics: linked-list, circular-linked-list

Companies: google, amazon

Level: swe2

Three-Case Insert: Traverse and handle: (1) insert between curr and curr.next when curr <= val <= next, (2) at boundary when curr is max and val is outside range, (3) full loop means all equal.

Delete Node in Linked List - Python Solution | Engineers of AI

Delete a node without head reference in O(1) by copying next value. Easy Amazon, Microsoft, Bloomberg interview question.

Topics: linked-list

Companies: amazon, microsoft, bloomberg

Level: new-grad

Copy and Skip: Copy next node's value into the current node, then bypass the next node.

Add Two Numbers Linked List - Python Solution | Engineers of AI

Add two numbers represented as reversed linked lists in O(max(m,n)). Classic Amazon, Google, Meta, Bloomberg interview question.

Topics: linked-list, math

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2

Digit-by-Digit Simulation: Walk both lists simultaneously, add digits with carry. Continue while either list or carry is non-zero.

Reverse Nodes in k-Group - Python Solution | Engineers of AI

Reverse linked list nodes in k-groups recursively. Hard Amazon, Google, Microsoft SWE3/Senior interview question.

Topics: linked-list, recursion

Companies: amazon, google, microsoft

Level: swe3, senior

Recursive: Check k nodes exist. If yes, reverse them and recurse on the rest. If not, return as-is.

Copy List with Random Pointer - Python Solution | Engineers of AI

Deep copy a linked list with random pointers using hash map in O(n). Common Amazon, Google, Microsoft SWE2/SWE3 interview question.

Topics: linked-list, hash-map

Companies: amazon, google, microsoft

Level: swe2, swe3

Hash Map Two Pass: First pass: create a copy of each node and store in a map. Second pass: set next and random pointers using the map.

LRU Cache - Python Doubly Linked List Solution | Engineers of AI

Implement LRU Cache in O(1) with doubly linked list and hash map. Classic Amazon, Google, Meta, Bloomberg SWE2/SWE3 interview question.

Topics: linked-list, doubly-linked-list, hash-map

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2, swe3

Doubly Linked List + Hash Map: Use a doubly linked list (most recent at head, LRU at tail) and a hash map. On access/update, move node to head. On capacity overflow, evict tail.

Sort List (Merge Sort on Linked List) - Python Solution | Engineers of AI

Sort a linked list in O(n log n) using merge sort. Common Amazon and Google SWE2/SWE3 interview question.

Topics: linked-list, sorting, divide-and-conquer

Companies: amazon, google

Level: swe2, swe3

Top-Down Merge Sort: Find middle with slow/fast, split, recursively sort both halves, merge. O(log n) recursion stack.

Reorder List - Python Solution | Engineers of AI

Reorder a linked list in O(n) O(1) by finding middle, reversing, and merging. Common Amazon and Google SWE2 interview question.

Topics: linked-list, two-pointers

Companies: amazon, google

Level: swe2

Find Middle + Reverse + Merge: Find middle with slow/fast, reverse second half, then interleave first and reversed second halves.

Swap Nodes in Pairs - Python Solution | Engineers of AI

Swap adjacent linked list nodes in O(n) O(1) iteratively. Common Amazon, Google, Microsoft SWE2 interview question.

Topics: linked-list, recursion

Companies: amazon, google, microsoft

Level: swe2

Iterative: Use a dummy head. At each iteration, swap the two nodes after prev pointer, then advance prev by 2.

Partition List - Python Solution | Engineers of AI

Partition a linked list around value x in O(n) O(1) using two sub-lists. Common Amazon and Bloomberg SWE2 interview question.

Topics: linked-list, two-pointers

Companies: amazon, bloomberg

Level: swe2

Two-Partition Lists: Build two sub-lists: one for nodes < x, one for nodes >= x. Merge them at the end.

Flatten Multilevel Doubly Linked List - Python Solution | Engineers of AI

Flatten a multilevel doubly linked list in O(n) by splicing child lists. Common Amazon and Google SWE2 interview question.

Topics: linked-list, doubly-linked-list, dfs

Companies: amazon, google

Level: swe2

Iterative DFS: Walk the list. When a node has a child, find the tail of the child list, splice it between current and current.next, then set child to None.

Rotate List - Python Solution | Engineers of AI

Rotate a linked list right by k places in O(n) O(1). Common Amazon, Google, Microsoft SWE2 interview question.

Topics: linked-list, two-pointers

Companies: amazon, google, microsoft

Level: swe2

Find Length + Rotate: Find length and tail, make circular, then find new tail at length-k%length-1 and break the circle.

Binary Tree Inorder Traversal - Python Recursive and Iterative | Engineers of AI

Inorder traversal of a binary tree recursively and iteratively with a stack. Common Amazon, Google, Microsoft interview question.

Topics: binary-tree, dfs, stack, recursion

Companies: amazon, google, microsoft

Level: new-grad, swe2

Recursive: Recursively visit left subtree, then root, then right subtree.

Iterative Stack: Use an explicit stack: push left nodes until null, then pop and record, then process right subtree.

Binary Tree Level Order Traversal - Python BFS | Engineers of AI

Level order traversal of a binary tree using BFS in O(n). Classic Amazon, Google, Meta, Bloomberg interview question.

Topics: binary-tree, bfs

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2

BFS with Queue: Use a deque for BFS. At start of each iteration, snapshot the queue length to process exactly one level.

Maximum Depth of Binary Tree - Python Solution | Engineers of AI

Find the maximum depth of a binary tree with recursive DFS in O(n). Easy Amazon, Google, Meta, Microsoft interview question.

Topics: binary-tree, dfs, bfs, recursion

Companies: amazon, google, meta, microsoft

Level: new-grad

Recursive DFS: Depth is 0 for null; 1 + max of left and right depths otherwise.

Symmetric Tree - Python Recursive Solution | Engineers of AI

Check if a binary tree is symmetric with recursive mirror comparison. Easy Amazon, Google, Microsoft interview question.

Topics: binary-tree, dfs, bfs, recursion

Companies: amazon, google, microsoft

Level: new-grad, swe2

Recursive Mirror Check: A tree is symmetric if its left and right subtrees are mirrors. Mirror check: left.val == right.val AND mirrors(left.left, right.right) AND mirrors(left.right, right.left).

Invert Binary Tree - Python Solution | Engineers of AI

Invert a binary tree recursively in O(n). Easy Amazon, Google, Meta interview question.

Topics: binary-tree, dfs, bfs, recursion

Companies: amazon, google, meta

Level: new-grad

Recursive: Swap left and right at current node, then recursively invert each subtree.

Diameter of Binary Tree - Python DFS Solution | Engineers of AI

Find the diameter of a binary tree in O(n) with post-order DFS. Easy Amazon, Google, Meta interview question.

Topics: binary-tree, dfs

Companies: amazon, google, meta

Level: new-grad, swe2

DFS with Global Max: Post-order DFS: at each node, diameter candidate = left_height + right_height. Return height to parent. Track global max.

Path Sum - Python DFS Solution | Engineers of AI

Check if a root-to-leaf path sums to target in O(n) with recursive DFS. Easy Amazon and Microsoft new grad interview question.

Topics: binary-tree, dfs, recursion

Companies: amazon, microsoft

Level: new-grad

Recursive DFS: At each node subtract its value from target. At a leaf, return True if remaining == 0.

Lowest Common Ancestor of BST - Python Solution | Engineers of AI

Find LCA in a BST in O(h) using BST ordering property. Classic Amazon, Google, Meta, Bloomberg SWE2 interview question.

Topics: binary-tree, bst, dfs

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2

BST Property: Use BST ordering: if both p,q < root go left; if both > root go right; else current root is LCA.

Validate Binary Search Tree - Python DFS with Bounds | Engineers of AI

Validate a BST in O(n) by passing min/max bounds through DFS. Classic Amazon, Google, Meta, Bloomberg interview question.

Topics: binary-tree, bst, dfs

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2

DFS with Bounds: Pass min and max bounds to each recursive call. A node must satisfy min < node.val < max.

Kth Smallest Element in BST - Python Inorder Solution | Engineers of AI

Find kth smallest in BST in O(H+k) with iterative inorder traversal. Common Amazon, Google, Bloomberg SWE2 interview question.

Topics: binary-tree, bst, dfs

Companies: amazon, google, bloomberg

Level: swe2

Iterative Inorder: Use iterative inorder traversal. Decrement k each time we process a node; return when k hits 0.

Convert Sorted Array to BST - Python Solution | Engineers of AI

Convert sorted array to height-balanced BST in O(n) with divide and conquer. Common Amazon and Google SWE2 interview question.

Topics: binary-tree, bst, divide-and-conquer

Companies: amazon, google

Level: swe2

Divide & Conquer: Always pick the middle element as root. Recursively build left subtree from left half and right from right half.

Binary Tree Maximum Path Sum - Python DFS Solution | Engineers of AI

Find maximum path sum in a binary tree in O(n) with post-order DFS. Hard Amazon, Google, Meta, Microsoft SWE3/Senior interview question.

Topics: binary-tree, dfs

Companies: amazon, google, meta, microsoft

Level: swe3, senior

Post-Order DFS: At each node compute: local_max = node.val + max(0,left) + max(0,right). Update global max. Return node.val + max(0, best_one_side) to parent.

Serialize and Deserialize Binary Tree - Python Solution | Engineers of AI

Serialize and deserialize a binary tree with BFS in O(n). Hard Amazon, Google, Meta, LinkedIn SWE3/Senior interview question.

Topics: binary-tree, bfs, dfs

Companies: amazon, google, meta, microsoft, linkedin

Level: swe3, senior

BFS Level-Order: Serialize with BFS, storing null for missing children. Deserialize by replaying BFS order from the tokens.

Binary Tree Right Side View - Python BFS Solution | Engineers of AI

Get the right side view of a binary tree using BFS in O(n). Common Amazon, Google, Meta SWE2 interview question.

Topics: binary-tree, bfs, dfs

Companies: amazon, google, meta

Level: swe2

BFS Last Node Per Level: BFS level-order; append the last node's value from each level to the result.

Sum Root to Leaf Numbers - Python DFS Solution | Engineers of AI

Sum all root-to-leaf path numbers in O(n) with DFS. Common Amazon and Google SWE2 interview question.

Topics: binary-tree, dfs

Companies: amazon, google

Level: swe2

DFS with Accumulated Sum: Pass current accumulated number (curr * 10 + node.val) down the DFS. At a leaf, return the accumulated value.

Subtree of Another Tree - Python DFS Solution | Engineers of AI

Check if a tree is a subtree of another in O(m*n) with DFS and same-tree comparison. Common Amazon and Google SWE2 question.

Topics: binary-tree, dfs

Companies: amazon, google

Level: swe2

DFS with Same-Tree Check: At each node in root, check if it matches subRoot with an is_same helper. Return True if any match found.

Balanced Binary Tree - Python Post-Order DFS | Engineers of AI

Check if a binary tree is height-balanced in O(n) with post-order DFS and -1 sentinel. Common Amazon, Google, Microsoft interview question.

Topics: binary-tree, dfs

Companies: amazon, google, microsoft

Level: new-grad, swe2

Post-Order DFS: Compute height in post-order. Return -1 as a sentinel for "unbalanced" so we can short-circuit early.

Implement Trie (Prefix Tree) - Python Solution | Engineers of AI

Implement a Trie with insert, search, and startsWith in O(m) per operation. Common Amazon, Google, Meta, Microsoft SWE2/SWE3 question.

Topics: trie, oop

Companies: amazon, google, meta, microsoft

Level: swe2, swe3

Dict-Based Trie: Each node stores a dict of children and a is_end flag. Insert/search/startsWith traverse character by character.

Flatten Binary Tree to Linked List - Python Solution | Engineers of AI

Flatten a binary tree to linked list in-place in O(n) O(1). Common Amazon, Google, Microsoft SWE2 interview question.

Topics: binary-tree, dfs, linked-list

Companies: amazon, google, microsoft

Level: swe2

Morris-like In-Place: For each node with a left child, find the rightmost node of the left subtree, connect it to right child, move left subtree to right, set left to null.

Construct Binary Tree from Preorder and Inorder - Python | Engineers of AI

Construct a binary tree from preorder and inorder traversals in O(n) with hash map. Common Amazon, Google, Bloomberg SWE2/SWE3 question.

Topics: binary-tree, dfs, hash-map

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Recursive with HashMap: preorder[0] is root. Use a hash map to find its position in inorder in O(1). Left subtree has inorder[:pos] elements, right has inorder[pos+1:].

Number of Islands - Python DFS BFS Solution | Engineers of AI

Count islands in a 2D grid using DFS or BFS in O(m*n). Top Amazon, Google, Microsoft interview question with complete Python solution.

Topics: graph, bfs, dfs, matrix

Companies: amazon, google, microsoft, bloomberg, meta

Level: swe2, swe3

DFS: For each unvisited land cell, run DFS marking the island visited by setting "1" to "0". Count DFS initiations.

BFS: For each unvisited land cell, BFS to mark the whole island. Count BFS initiations.

Clone Graph DFS BFS - Python | Engineers of AI

Deep copy a graph using DFS or BFS with hash map in O(V+E). Common Amazon, Google, Meta interview question with Python solution.

Topics: graph, dfs, bfs, hash-table

Companies: amazon, google, meta, microsoft

Level: swe2, swe3

DFS with Hash Map: Dictionary maps originals to clones. Recursively clone each neighbor, using the map to avoid duplicates.

BFS with Hash Map: BFS from start. Clone each node once into a hash map. Link cloned neighbors during traversal.

Course Schedule Topological Sort - Python | Engineers of AI

Detect cycle in directed graph with DFS or Kahn's BFS topological sort in O(V+E). Amazon, Google, Bloomberg interview question.

Topics: graph, topological-sort, dfs, bfs

Companies: amazon, google, microsoft, bloomberg, uber

Level: swe2, swe3

DFS Cycle Detection: 3-state DFS: 0=unvisited, 1=visiting, 2=done. If we re-visit a visiting node, there is a cycle.

Kahn's BFS Topological Sort: Count in-degrees. Enqueue zero-in-degree nodes. Process BFS decrementing neighbor in-degrees. If all processed, no cycle.

Pacific Atlantic Water Flow BFS - Python | Engineers of AI

Find cells where water flows to both oceans using multi-source BFS in O(m*n). Google, Amazon interview question with Python solution.

Topics: graph, bfs, dfs, matrix

Companies: amazon, google, bloomberg

Level: swe3, senior

Multi-Source BFS: BFS from all Pacific border cells and all Atlantic border cells separately. Result is the intersection of both reachable sets.

Word Ladder BFS Shortest Path - Python | Engineers of AI

Solve Word Ladder with BFS or bidirectional BFS. Amazon, Google, Bloomberg hard interview question with Python solution.

Topics: graph, bfs, hash-table

Companies: amazon, google, microsoft, bloomberg, linkedin

Level: swe3, senior

BFS: BFS level by level. Replace each character with a-z. If result is in word set and unvisited, enqueue.

Bidirectional BFS: BFS from both ends simultaneously. Expand the smaller frontier each step. Stop when frontiers meet.

Graph Valid Tree Union Find DFS - Python | Engineers of AI

Determine if edges form a valid tree using Union-Find or DFS. Google, LinkedIn interview question with Python solution.

Topics: graph, dfs, union-find

Companies: google, linkedin, amazon, microsoft

Level: swe2, swe3

Union-Find: Check n-1 edges first. Union-Find: adding an edge between nodes in the same component creates a cycle.

DFS: DFS from node 0 tracking parent to avoid false cycles. Tree is valid if all n nodes are visited.

Number of Connected Components - Python Union Find | Engineers of AI

Count connected components in undirected graph using Union-Find or DFS. Google, LinkedIn interview question with Python solution.

Topics: graph, dfs, union-find

Companies: google, linkedin, amazon, microsoft

Level: swe2, swe3

Union-Find: Initialize n components. For each edge, union two nodes. Each successful union decrements component count.

DFS: Build adjacency list. DFS from each unvisited node marking all reachable nodes. Count DFS initiations.

Alien Dictionary Topological Sort - Python | Engineers of AI

Derive alien language order using DFS topological sort with cycle detection. Amazon, Google, Airbnb hard interview question.

Topics: graph, topological-sort, dfs

Companies: amazon, google, meta, microsoft, airbnb

Level: swe3, senior

DFS Topological Sort: Build directed graph from adjacent word comparisons. DFS topological sort with 3-state cycle detection.

Shortest Path in Binary Matrix BFS - Python | Engineers of AI

Find shortest 8-directional clear path in binary matrix using BFS in O(n^2). Amazon, Google interview question with Python solution.

Topics: graph, bfs, matrix

Companies: amazon, google, bloomberg, microsoft

Level: swe2, swe3

BFS: BFS from (0,0) in 8 directions. Mark visited by setting cells to 1. First arrival at (n-1,n-1) is shortest path.

Surrounded Regions DFS - Python | Engineers of AI

Capture surrounded regions in a board using DFS from borders in O(m*n). Amazon, Google, Bloomberg interview question.

Topics: graph, dfs, bfs, matrix

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

DFS from Border: Mark all border-connected "O"s as "S" (safe). Flip remaining "O" to "X", then "S" back to "O".

Rotting Oranges Multi-Source BFS - Python | Engineers of AI

Solve Rotting Oranges with multi-source BFS in O(m*n). Amazon, Google, Bloomberg medium interview question with Python solution.

Topics: graph, bfs, matrix

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Multi-Source BFS: Enqueue all initially rotten oranges with time=0. BFS outward decrementing fresh count. Return max time if fresh==0.

Find if Path Exists in Graph - Python | Engineers of AI

Check if path exists between two nodes using BFS or Union-Find. Easy graph question for new grads with Python solution.

Topics: graph, dfs, bfs, union-find

Companies: amazon, google, microsoft

Level: new-grad, swe2

BFS: BFS from source. Return True if destination is reached.

Union-Find: Union all edges. Check if source and destination share the same root.

Max Area of Island DFS - Python | Engineers of AI

Find maximum island area using DFS in O(m*n). Amazon, Google, Bloomberg medium interview question with Python solution.

Topics: graph, dfs, bfs, matrix

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

DFS: For each unvisited 1, DFS counting cells by marking them 0. Return max count seen.

Network Delay Time Dijkstra - Python | Engineers of AI

Find minimum signal delay using Dijkstra's algorithm. Amazon, Google, Uber interview question with Python solution.

Topics: graph, dijkstra, heap

Companies: amazon, google, microsoft, uber

Level: swe3, senior

Dijkstra's Algorithm: Min-heap Dijkstra from k. Relax edges greedily. Answer is max shortest distance; -1 if any node unreachable.

Find the Town Judge - Python | Engineers of AI

Find the town judge using net degree scoring in O(E). Easy graph question for new grads with complete Python solution.

Topics: graph, array, hash-table

Companies: amazon, google, microsoft

Level: new-grad, swe2

Net Score: Net score: +1 for being trusted, -1 for trusting. Judge has score exactly n-1.

Is Graph Bipartite BFS 2-Coloring - Python | Engineers of AI

Check graph bipartiteness using BFS 2-coloring in O(V+E). Amazon, Google, Bloomberg interview question with Python solution.

Topics: graph, bfs, dfs

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

BFS 2-Coloring: Assign colors 0/1 via BFS. If any neighbor shares the same color, not bipartite.

Kruskal's Minimum Spanning Tree - Python | Engineers of AI

Implement Kruskal's MST with Union-Find in O(E log E). Amazon, Google, Microsoft hard interview question with Python solution.

Topics: graph, union-find, sorting, greedy

Companies: amazon, google, microsoft, bloomberg

Level: swe3, senior

Kruskal's with Union-Find: Sort edges by weight. Greedily add edges using Union-Find, skipping cycle-creating edges. Sum weights of n-1 chosen edges.

Accounts Merge Union Find - Python | Engineers of AI

Merge accounts with shared emails using Union-Find. Amazon, Google, Meta interview question with Python solution.

Topics: graph, union-find, dfs, sorting

Companies: amazon, google, meta, bloomberg

Level: swe3, senior

Union-Find: Map each email to a parent. Union all emails in the same account. Group by root then reconstruct.

Redundant Connection Union Find - Python | Engineers of AI

Find the redundant edge creating a cycle using Union-Find. Amazon, Google interview question with Python solution.

Topics: graph, union-find, dfs

Companies: amazon, google, microsoft

Level: swe2, swe3

Union-Find: Process edges in order. When union fails (both endpoints in same component), that edge is redundant.

Walls and Gates Multi-Source BFS - Python | Engineers of AI

Fill rooms with distances to nearest gate using multi-source BFS in O(m*n). Meta, Google, Amazon interview question.

Topics: graph, bfs, matrix

Companies: meta, google, amazon, bloomberg

Level: swe2, swe3

Multi-Source BFS: Enqueue all gate positions. BFS outward; update each INF room with current distance.

Climbing Stairs DP - Python | Engineers of AI

Count distinct ways to climb n stairs using DP (Fibonacci) in O(n) O(1). Classic Amazon, Google, Apple interview question.

Topics: dynamic-programming, math

Companies: amazon, google, microsoft, bloomberg, apple

Level: new-grad, swe2

DP (Bottom-Up): dp[i] = dp[i-1] + dp[i-2]. Use two variables instead of full array.

Recursive with Memoization: Top-down recursion with memo cache. Base cases: n=1 -> 1, n=2 -> 2.

House Robber DP - Python | Engineers of AI

Maximize robbery without adjacent houses using DP in O(n) O(1). Amazon, Google, Bloomberg medium interview question.

Topics: dynamic-programming, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

DP O(1) Space: At each house, max is either skip it (prev1) or rob it (prev2 + current). Track just two variables.

DP Array: Build dp array where dp[i] = max money robbing up to house i.

House Robber II Circular DP - Python | Engineers of AI

Circular house robber using two-pass linear DP in O(n). Amazon, Google medium interview question with Python solution.

Topics: dynamic-programming, array

Companies: amazon, google, microsoft

Level: swe2, swe3

Two-Pass DP: Since first and last are adjacent, solve two linear subproblems: rob houses 0..n-2 and rob houses 1..n-1. Return the max.

Longest Increasing Subsequence DP Binary Search - Python | Engineers of AI

Find LIS length using DP O(n^2) or binary search O(n log n). Amazon, Google, LinkedIn medium interview question.

Topics: dynamic-programming, binary-search, array

Companies: amazon, google, microsoft, bloomberg, linkedin

Level: swe2, swe3

DP O(n^2): dp[i] = length of LIS ending at index i. For each i, check all j < i where nums[j] < nums[i].

Binary Search (Patience Sorting) O(n log n): Maintain a tails array where tails[i] = smallest tail of increasing subsequence of length i+1. Binary search to place each element.

Coin Change DP - Python | Engineers of AI

Find minimum coins to make amount using bottom-up DP in O(amount*coins). Amazon, Google, Goldman Sachs interview question.

Topics: dynamic-programming, array, breadth-first-search

Companies: amazon, google, microsoft, goldman-sachs, bloomberg

Level: swe2, swe3

Bottom-Up DP: dp[i] = min coins to make amount i. Initialize to infinity. For each amount, try every coin.

BFS: BFS treats amount as a graph. Each node is an amount; edges are coin subtractions. BFS finds shortest path to 0.

Word Break DP - Python | Engineers of AI

Check if string can be segmented into dictionary words using DP in O(n^2). Amazon, Google, Meta, Bloomberg interview question.

Topics: dynamic-programming, trie, hash-table

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2, swe3

Bottom-Up DP: dp[i] = True if s[:i] can be formed. For each i, check all j < i where dp[j] is True and s[j:i] is in the word set.

Unique Paths DP - Python | Engineers of AI

Count unique paths in m x n grid using DP in O(m*n). Amazon, Google, Bloomberg medium interview question with Python solution.

Topics: dynamic-programming, math, combinatorics

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

DP O(m*n): dp[i][j] = paths to reach cell (i,j) = paths from top + paths from left.

DP O(n) Space: Use a single row dp. Update in-place: dp[j] += dp[j-1].

Jump Game Greedy DP - Python | Engineers of AI

Determine if you can reach the last index using greedy O(n) or DP. Amazon, Google, Bloomberg medium interview question.

Topics: dynamic-programming, greedy, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Greedy: Track max reachable index. If current index ever exceeds max_reach, return False.

DP: dp[i] = True if index i is reachable. For each reachable i, mark all positions i+1 to i+nums[i] as reachable.

Jump Game II Minimum Jumps - Python | Engineers of AI

Find minimum jumps to reach last index using greedy in O(n). Amazon, Google, Bloomberg medium interview question.

Topics: dynamic-programming, greedy, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Greedy: Track current jump end and farthest reachable. When i reaches current_end, increment jumps and set current_end = farthest.

Longest Common Subsequence DP - Python | Engineers of AI

Find LCS length using 2D DP in O(m*n). Amazon, Google, Microsoft, Bloomberg medium interview question with Python solution.

Topics: dynamic-programming, string

Companies: amazon, google, microsoft, bloomberg, oracle

Level: swe2, swe3

Bottom-Up DP: 2D DP table. If text1[i-1] == text2[j-1]: dp[i][j] = dp[i-1][j-1] + 1, else dp[i][j] = max(dp[i-1][j], dp[i][j-1]).

Space-Optimized DP: Use two rows instead of the full 2D table.

Edit Distance DP - Python | Engineers of AI

Find minimum edit distance between two strings using 2D DP in O(m*n). Amazon, Google, Bloomberg hard interview question.

Topics: dynamic-programming, string

Companies: amazon, google, microsoft, bloomberg, linkedin

Level: swe3, senior

Bottom-Up DP: dp[i][j] = min operations to convert word1[:i] to word2[:j]. If chars match, take diagonal. Else 1 + min of insert/delete/replace.

Partition Equal Subset Sum DP - Python | Engineers of AI

Partition array into equal subsets using 0/1 knapsack DP in O(n*sum). Amazon, Google, Bloomberg medium interview question.

Topics: dynamic-programming, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

DP with Bitset: Use a set of reachable sums. For each number, add it to all existing reachable sums. Check if target (sum/2) is reachable.

DP Array: Boolean array dp where dp[s] = can reach sum s. Traverse in reverse to avoid reuse.

Target Sum DP DFS - Python | Engineers of AI

Count ways to assign +/- to reach target sum using DFS memoization or DP. Amazon, Google, Meta interview question.

Topics: dynamic-programming, dfs, array

Companies: amazon, google, meta, bloomberg

Level: swe2, swe3

DFS with Memoization: Recursive DFS: at each index choose + or -. Memoize on (index, current_sum).

DP with Hash Map: Use a counter dict mapping sum -> count. For each number update all sums by adding or subtracting the number.

Decode Ways DP - Python | Engineers of AI

Count string decoding ways using DP in O(n). Amazon, Google, Meta, Bloomberg medium interview question with Python solution.

Topics: dynamic-programming, string

Companies: amazon, google, meta, bloomberg, microsoft

Level: swe2, swe3

Bottom-Up DP: dp[i] = ways to decode s[:i]. Add dp[i-1] if s[i-1] is 1-9, add dp[i-2] if s[i-2:i] is 10-26.

Space-Optimized DP: Only need prev2 and prev1 instead of full dp array.

Best Time to Buy and Sell Stock III - Python | Engineers of AI

Maximize profit with at most 2 stock transactions using state machine DP in O(n). Amazon, Google, Goldman Sachs hard interview question.

Topics: dynamic-programming, array

Companies: amazon, google, goldman-sachs, bloomberg

Level: swe3, senior

State Machine DP: Track 4 states: cost of first buy, profit after first sell, cost of second buy, profit after second sell. Update greedily.

Palindrome Partitioning II Minimum Cuts - Python | Engineers of AI

Find minimum palindrome partition cuts using 2D DP in O(n^2). Amazon, Google, Bloomberg hard interview question.

Topics: dynamic-programming, string

Companies: amazon, google, bloomberg

Level: swe3, senior

DP with Palindrome Precomputation: Precompute is_pal[i][j]. Then dp[i] = min of (dp[j-1] + 1) for all j <= i where s[j:i+1] is palindrome.

Wildcard Matching DP - Python | Engineers of AI

Wildcard pattern matching with ? and * using 2D DP in O(m*n). Amazon, Google, Bloomberg hard interview question.

Topics: dynamic-programming, string, greedy

Companies: amazon, google, microsoft, bloomberg

Level: swe3, senior

Bottom-Up DP: dp[i][j] = True if s[:i] matches p[:j]. Handle "*" as match-zero (dp[i][j-1]) or match-one-more (dp[i-1][j]).

Regular Expression Matching DP - Python | Engineers of AI

Regex pattern matching with . and * using 2D DP in O(m*n). Amazon, Google, Microsoft hard interview question.

Topics: dynamic-programming, string, recursion

Companies: amazon, google, microsoft, bloomberg

Level: swe3, senior

Bottom-Up DP: dp[i][j] = s[:i] matches p[:j]. For "*": zero occurrences (dp[i][j-2]) or match one more (dp[i-1][j] if chars match).

Maximum Product Subarray DP - Python | Engineers of AI

Find maximum product subarray by tracking min and max in O(n). Amazon, Google, Bloomberg medium interview question.

Topics: dynamic-programming, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

DP Track Min and Max: Track current max and min products. A negative number flips max and min. Update global max.

Triangle Minimum Path Sum DP - Python | Engineers of AI

Find minimum path sum in triangle using bottom-up DP in O(n^2). Amazon, Google, Bloomberg medium interview question.

Topics: dynamic-programming, array

Companies: amazon, google, bloomberg, microsoft

Level: swe2, swe3

Bottom-Up DP In-Place: Start from second-to-last row, add minimum of the two children below. Result is triangle[0][0].

Minimum Path Sum Grid DP - Python | Engineers of AI

Find minimum path sum in m x n grid using DP in O(m*n). Amazon, Google, Bloomberg medium interview question.

Topics: dynamic-programming, matrix

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

DP In-Place: Modify grid in-place. dp[i][j] = grid[i][j] + min of left and top neighbors.

Burst Balloons Interval DP - Python | Engineers of AI

Maximize coins by bursting balloons using interval DP in O(n^3). Amazon, Google hard interview question with Python solution.

Topics: dynamic-programming, divide-and-conquer

Companies: amazon, google, bloomberg

Level: senior, staff

Interval DP: Add boundary 1s. dp[l][r] = max coins bursting all balloons between l and r exclusive. Try each k as the last balloon burst.

0/1 Knapsack DP - Python | Engineers of AI

Solve 0/1 knapsack problem using 2D DP or space-optimized 1D DP in O(n*W). Amazon, Google, Goldman Sachs interview question.

Topics: dynamic-programming, array

Companies: amazon, google, microsoft, goldman-sachs

Level: swe2, swe3

2D DP: dp[i][w] = max value using first i items with capacity w. Either skip item i or take it.

1D DP (Space-Optimized): Use 1D dp array, traverse weights in reverse to avoid using same item twice.

Rod Cutting DP - Python | Engineers of AI

Solve rod cutting problem using bottom-up DP in O(n^2). Amazon, Google, Microsoft interview question with Python solution.

Topics: dynamic-programming, array

Companies: amazon, google, microsoft

Level: swe2, swe3

Bottom-Up DP: dp[i] = max revenue for rod of length i. Try all cuts j from 1 to i.

Egg Drop Problem DP - Python | Engineers of AI

Solve egg drop problem with minimum trials using DP in O(k log n). Amazon, Google, Goldman Sachs hard interview question.

Topics: dynamic-programming, binary-search, math

Companies: amazon, google, goldman-sachs, bloomberg

Level: senior, staff

DP on Trials: dp[m][k] = max floors checkable with m moves and k eggs. dp[m][k] = dp[m-1][k-1] + dp[m-1][k] + 1. Find min m where dp[m][k] >= n.

Merge Sort Implementation - Python | Engineers of AI

Implement merge sort from scratch in O(n log n). Amazon, Google, Microsoft interview question with complete Python solution.

Topics: sorting, divide-and-conquer, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Recursive Merge Sort: Recursively split array in half. Merge two sorted halves by comparing elements and building result.

In-Place Merge Sort: Sort in-place using index boundaries instead of slicing, reducing memory allocation.

Quick Sort Implementation - Python | Engineers of AI

Implement quicksort with Lomuto partition or randomized pivot in O(n log n). Amazon, Google interview question.

Topics: sorting, divide-and-conquer, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Lomuto Partition Scheme: Pick last element as pivot. Partition: elements <= pivot go left. Recursively sort both halves.

Randomized Pivot: Randomly swap pivot before partitioning to avoid worst-case O(n^2) on sorted input.

Heap Sort Implementation - Python | Engineers of AI

Implement heap sort in-place using max-heap in O(n log n) O(1) space. Amazon, Google, Microsoft interview question.

Topics: sorting, heap, array

Companies: amazon, google, microsoft

Level: swe2, swe3

Heap Sort In-Place: Build max-heap in O(n). Then repeatedly swap root with last, reduce heap size, and heapify down.

Find K-th Largest Element - Python Heap Quickselect | Engineers of AI

Find k-th largest using min-heap O(n log k) or quickselect O(n). Amazon, Google, Meta, Bloomberg interview question.

Topics: sorting, heap, divide-and-conquer, array

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2, swe3

Min-Heap of Size k: Maintain a min-heap of size k. For each element, push to heap; if size > k, pop the min. The top of heap is the k-th largest.

Quickselect: Use quickselect (partial quicksort). Partition around pivot; recurse only into the partition containing position n-k.

Sort Colors Dutch National Flag - Python | Engineers of AI

Sort 0s, 1s, 2s in-place using Dutch National Flag 3-pointer technique in O(n). Amazon, Google interview question.

Topics: sorting, two-pointers, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Dutch National Flag (3 Pointers): Three pointers: low (next 0 spot), mid (current), high (next 2 spot). Advance mid: swap 0 to low, skip 1, swap 2 to high.

Merge Intervals - Python | Engineers of AI

Merge overlapping intervals after sorting in O(n log n). Amazon, Google, Meta, Bloomberg medium interview question.

Topics: sorting, array, intervals

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2, swe3

Sort and Merge: Sort by start. Iterate; if current start <= last end, merge by extending end. Otherwise append new interval.

Insert Interval - Python | Engineers of AI

Insert and merge a new interval into sorted non-overlapping intervals in O(n). Amazon, Google, Meta interview question.

Topics: sorting, array, intervals

Companies: amazon, google, meta, bloomberg

Level: swe2, swe3

Three-Phase Linear Scan: Phase 1: add all non-overlapping intervals before new. Phase 2: merge all overlapping. Phase 3: add remaining.

Search in Rotated Sorted Array - Python | Engineers of AI

Binary search in rotated sorted array in O(log n). Amazon, Google, Meta, Bloomberg medium interview question with Python solution.

Topics: binary-search, array

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2, swe3

Modified Binary Search: At each step, determine which half is sorted. If target is in sorted half, search there; otherwise search the other half.

Find Peak Element Binary Search - Python | Engineers of AI

Find peak element using binary search in O(log n). Amazon, Google, Bloomberg medium interview question with Python solution.

Topics: binary-search, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Binary Search: If nums[mid] < nums[mid+1], the peak is to the right. Otherwise it is to the left (inclusive of mid).

Search a 2D Matrix Binary Search - Python | Engineers of AI

Search sorted 2D matrix using binary search in O(log(m*n)). Amazon, Google, Bloomberg medium interview question.

Topics: binary-search, matrix, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Binary Search on Virtual 1D Array: Treat the matrix as a sorted 1D array of length m*n. Binary search using virtual index mapping.

Median of Two Sorted Arrays - Python | Engineers of AI

Find median of two sorted arrays using binary search in O(log(min(m,n))). Amazon, Google, Goldman Sachs hard interview question.

Topics: binary-search, array, divide-and-conquer

Companies: amazon, google, microsoft, bloomberg, goldman-sachs

Level: swe3, senior

Binary Search on Partition: Binary search partition in shorter array. Ensure left partition has (m+n+1)//2 elements total. Check cross-border conditions.

Find Minimum in Rotated Sorted Array - Python | Engineers of AI

Find minimum in rotated sorted array using binary search in O(log n). Amazon, Google, Bloomberg interview question.

Topics: binary-search, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Binary Search: If nums[mid] > nums[hi], the min is in the right half. Otherwise min is in left half including mid.

H-Index - Python | Engineers of AI

Compute h-index by sorting citations in O(n log n). Google, Amazon, Bloomberg interview question with Python solution.

Topics: sorting, array, binary-search

Companies: google, amazon, bloomberg

Level: swe2, swe3

Sort and Scan: Sort descending. Walk through: if citations[i] >= i+1, h = i+1. Return the last valid h.

Meeting Rooms II Min Heap - Python | Engineers of AI

Find minimum conference rooms using min-heap or two sorted arrays in O(n log n). Amazon, Google, Meta interview question.

Topics: sorting, heap, intervals

Companies: amazon, google, meta, bloomberg, microsoft

Level: swe2, swe3

Min-Heap of End Times: Sort by start. Use min-heap of end times. If next meeting starts after earliest ending, reuse that room.

Two Sorted Arrays: Sort start and end times separately. Use two pointers; if next start < current end, need another room.

Largest Number Custom Sort - Python | Engineers of AI

Arrange numbers to form largest value using custom comparator sort in O(n log n). Amazon, Google, Bloomberg interview question.

Topics: sorting, string, greedy

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Custom Sort: Custom comparator: for two numbers a and b, prefer a first if str(a)+str(b) > str(b)+str(a). Edge case: all zeros.

3Sum Two Pointers - Python | Engineers of AI

Find all unique triplets summing to zero using sort and two pointers in O(n^2). Amazon, Google, Meta, Bloomberg interview question.

Topics: two-pointers, sorting, array

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2, swe3

Sort + Two Pointers: Sort array. For each index i, use two pointers lo=i+1 and hi=n-1. Move pointers based on sum. Skip duplicates.

4Sum Two Pointers - Python | Engineers of AI

Find all unique quadruplets summing to target using sort and two pointers in O(n^3). Amazon, Google interview question.

Topics: two-pointers, sorting, array

Companies: amazon, google, microsoft

Level: swe2, swe3

Sort + Two Nested Loops + Two Pointers: Sort. Two outer loops fix first two elements. Inner two pointers find the remaining pair. Skip duplicates.

Container With Most Water Two Pointers - Python | Engineers of AI

Find max water container using two pointers in O(n). Amazon, Google, Meta, Bloomberg medium interview question.

Topics: two-pointers, array, greedy

Companies: amazon, google, meta, bloomberg, microsoft

Level: swe2, swe3

Two Pointers: Start pointers at both ends. Area = min(h[lo], h[hi]) * (hi-lo). Move shorter pointer inward.

Trapping Rain Water Two Pointers DP - Python | Engineers of AI

Compute trapped rain water using two pointers O(n) O(1) or DP. Amazon, Google, Meta, Bloomberg hard interview question.

Topics: two-pointers, dynamic-programming, stack, array

Companies: amazon, google, meta, bloomberg, microsoft

Level: swe3, senior

Two Pointers: Two pointers lo/hi. Track max_left and max_right. Process side with smaller max; water at that side = max - height.

DP Precompute Max: Precompute max_left[i] and max_right[i] arrays. Water at i = min(max_left[i], max_right[i]) - height[i].

Minimum Window Substring Sliding Window - Python | Engineers of AI

Find minimum window substring using sliding window in O(|s|+|t|). Amazon, Google, Meta hard interview question.

Topics: sliding-window, hash-table, string, two-pointers

Companies: amazon, google, meta, bloomberg, microsoft

Level: swe3, senior

Sliding Window: Track needed char counts. Expand right pointer adding chars. When window is valid, contract left minimizing window.

Longest Substring Without Repeating - Python | Engineers of AI

Find longest substring without repeating characters using sliding window in O(n). Amazon, Google, Meta, Bloomberg interview question.

Topics: sliding-window, hash-table, string, two-pointers

Companies: amazon, google, meta, bloomberg, microsoft

Level: swe2, swe3

Sliding Window with Dict: Track last index of each char. When duplicate found, jump left to max(left, last_index+1). Track max window length.

Permutation in String Sliding Window - Python | Engineers of AI

Check if s2 contains permutation of s1 using fixed sliding window in O(n). Amazon, Google, Meta interview question.

Topics: sliding-window, hash-table, string, two-pointers

Companies: amazon, google, meta, bloomberg

Level: swe2, swe3

Fixed Sliding Window: Count chars in s1. Slide window of length len(s1) over s2, updating counts. Match when all counts are 0.

Find All Anagrams in a String - Python | Engineers of AI

Find all anagram start indices using fixed sliding window in O(n). Amazon, Google, Meta, Bloomberg interview question.

Topics: sliding-window, hash-table, string

Companies: amazon, google, meta, bloomberg

Level: swe2, swe3

Fixed Sliding Window: Slide window of size len(p). Use have/need counters to track when window is a valid anagram.

Longest Repeating Character Replacement - Python | Engineers of AI

Find longest substring with at most k replacements using sliding window in O(n). Amazon, Google, Bloomberg interview question.

Topics: sliding-window, hash-table, string

Companies: amazon, google, bloomberg, microsoft

Level: swe2, swe3

Sliding Window: Expand window right. Track frequency of most common char. If window_size - max_freq > k, slide left by 1.

Max Consecutive Ones III Sliding Window - Python | Engineers of AI

Find max consecutive 1s with k flips using sliding window in O(n). Amazon, Google, Bloomberg interview question.

Topics: sliding-window, array, two-pointers

Companies: amazon, google, bloomberg

Level: swe2, swe3

Sliding Window: Expand window right. When zero count exceeds k, move left. Track max window size.

Fruit Into Baskets Sliding Window - Python | Engineers of AI

Find max fruits with 2 baskets using sliding window in O(n). Amazon, Google, Bloomberg interview question.

Topics: sliding-window, hash-table, array

Companies: amazon, google, bloomberg

Level: swe2, swe3

Sliding Window with At Most 2 Distinct: Sliding window tracking count of each fruit type. When more than 2 types, shrink window from left.

Subarrays with K Different Integers - Python | Engineers of AI

Count subarrays with exactly k distinct integers using at-most-K trick in O(n). Amazon, Google, Bloomberg hard question.

Topics: sliding-window, hash-table, array

Companies: amazon, google, bloomberg

Level: swe3, senior

At Most K Trick: exactly(k) = at_most(k) - at_most(k-1). Helper counts subarrays with at most k distinct using sliding window.

Minimum Size Subarray Sum Sliding Window - Python | Engineers of AI

Find minimum subarray with sum >= target using sliding window in O(n). Amazon, Google, Bloomberg medium interview question.

Topics: sliding-window, two-pointers, array, binary-search

Companies: amazon, google, bloomberg, microsoft

Level: swe2, swe3

Sliding Window: Expand right pointer adding elements. When sum >= target, record length and shrink left pointer.

Longest Subarray of 1s After Deleting One Element - Python | Engineers of AI

Find longest subarray of 1s after deleting one element using sliding window. Amazon, Google interview question.

Topics: sliding-window, array, dynamic-programming

Companies: amazon, google, bloomberg

Level: swe2, swe3

Sliding Window (at most one zero): Sliding window allowing at most one 0 in window. Answer is max(window_size - 1) since we must delete one element.

Count Nice Subarrays - Python | Engineers of AI

Count subarrays with exactly k odd numbers using prefix sum in O(n). Amazon, Google, Bloomberg interview question.

Topics: sliding-window, hash-table, array, math

Companies: amazon, google, bloomberg

Level: swe2, swe3

Prefix Sum + Hash Map: Count prefix sums of (num % 2). For each prefix, look up (prefix - k) in map.

Valid Parentheses Stack - Python | Engineers of AI

Validate bracket string using a stack in O(n). Classic Amazon, Google, Meta easy interview question with Python solution.

Topics: stack, string

Companies: amazon, google, meta, bloomberg, microsoft

Level: new-grad, swe2

Stack: Push opening brackets onto stack. For closing brackets, check if stack top is the matching opener.

Min Stack Design - Python | Engineers of AI

Design a min stack with O(1) getMin using dual stacks. Amazon, Google, Meta, Bloomberg medium interview question.

Topics: stack, design

Companies: amazon, google, meta, bloomberg, microsoft

Level: swe2, swe3

Dual Stack: Maintain main stack and min_stack. Min stack stores the current minimum at each point. Push min to min_stack on each push.

Evaluate Reverse Polish Notation Stack - Python | Engineers of AI

Evaluate RPN expression using a stack in O(n). Amazon, Google, Bloomberg, LinkedIn medium interview question.

Topics: stack, array, math

Companies: amazon, google, bloomberg, linkedin

Level: swe2, swe3

Stack: Push numbers. On operator, pop two values, apply operation, push result. Final stack top is the answer.

Daily Temperatures Monotonic Stack - Python | Engineers of AI

Find days until warmer temperature using monotonic stack in O(n). Amazon, Google, Bloomberg medium interview question.

Topics: stack, array, monotonic-stack

Companies: amazon, google, bloomberg, microsoft

Level: swe2, swe3

Monotonic Stack: Stack of indices in decreasing temperature order. When current temp > stack top, pop and record gap.

Largest Rectangle in Histogram Stack - Python | Engineers of AI

Find largest rectangle in histogram using monotonic stack in O(n). Amazon, Google, Bloomberg hard interview question.

Topics: stack, array, monotonic-stack

Companies: amazon, google, bloomberg, microsoft

Level: swe3, senior

Monotonic Stack: Maintain increasing stack of indices. When current bar is shorter, pop and compute area. Use sentinel 0 at start and end.

Implement Queue Using Stacks - Python | Engineers of AI

Implement queue using two stacks with amortized O(1) operations. Amazon, Google easy design interview question.

Topics: stack, queue, design

Companies: amazon, google, microsoft, bloomberg

Level: new-grad, swe2

Two Stacks (Amortized O(1)): Input stack for push. Output stack for pop/peek. Transfer all from input to output when output is empty.

Implement Stack Using Queues - Python | Engineers of AI

Implement stack using queues with O(n) push. Amazon, Google easy design interview question with Python solution.

Topics: stack, queue, design

Companies: amazon, google, microsoft

Level: new-grad, swe2

Single Queue (rotate on push): After pushing new element, rotate queue (n-1 times) so new element is at the front.

Sliding Window Maximum Monotonic Deque - Python | Engineers of AI

Find sliding window maximum using monotonic deque in O(n). Amazon, Google, Bloomberg hard interview question.

Topics: stack, queue, sliding-window, array, monotonic-stack

Companies: amazon, google, bloomberg, microsoft

Level: swe3, senior

Monotonic Deque: Maintain deque of indices in decreasing value order. Front is always the window max. Remove indices out of window.

Next Greater Element Monotonic Stack - Python | Engineers of AI

Find next greater element using monotonic stack in O(m+n). Amazon, Google, Bloomberg easy interview question.

Topics: stack, array, hash-table, monotonic-stack

Companies: amazon, google, bloomberg

Level: new-grad, swe2

Monotonic Stack + Hash Map: Process nums2 with monotonic stack. Build a map from value to its next greater. Look up each nums1 element.

Basic Calculator II Stack - Python | Engineers of AI

Evaluate arithmetic expression with stack in O(n). Amazon, Google, Bloomberg medium interview question with Python solution.

Topics: stack, string, math

Companies: amazon, google, bloomberg, microsoft

Level: swe2, swe3

Stack: Parse left to right. On + push num, on - push -num, on * or / pop stack top and push result. Sum stack at end.

Single Number XOR Bit Manipulation - Python | Engineers of AI

Find the single non-duplicate number using XOR in O(n) O(1). Classic Amazon, Google, Meta easy bit manipulation question.

Topics: bit-manipulation, array

Companies: amazon, google, meta, bloomberg

Level: new-grad, swe2

XOR: XOR all elements. a XOR a = 0, a XOR 0 = a. All pairs cancel leaving the single element.

Number of 1 Bits Hamming Weight - Python | Engineers of AI

Count 1 bits using Brian Kernighan's algorithm in O(k). Amazon, Google easy bit manipulation interview question.

Topics: bit-manipulation

Companies: amazon, google, bloomberg

Level: new-grad, swe2

Brian Kernighan: n & (n-1) clears the lowest set bit. Count iterations until n becomes 0.

Built-in / Shift: Count set bits by shifting right and checking LSB, or use bin(n).count("1").

Reverse Bits - Python | Engineers of AI

Reverse 32 bits of an integer using bit shifting in O(32). Amazon, Google easy bit manipulation interview question.

Topics: bit-manipulation

Companies: amazon, google, bloomberg

Level: new-grad, swe2

Bit by Bit: For each of 32 bits, shift result left by 1, add LSB of n, then shift n right by 1.

Missing Number Math XOR - Python | Engineers of AI

Find missing number using math sum or XOR in O(n) O(1). Amazon, Google, Bloomberg easy interview question.

Topics: bit-manipulation, math, array

Companies: amazon, google, bloomberg, microsoft

Level: new-grad, swe2

Math (Sum): Expected sum = n*(n+1)/2. Actual sum = sum(nums). Missing = expected - actual.

XOR: XOR all indices 0..n with all values. Pairs cancel, missing index remains.

Power of Two Bit Manipulation - Python | Engineers of AI

Check if number is power of two using bit trick n & (n-1) in O(1). Amazon, Google easy bit manipulation question.

Topics: bit-manipulation, math

Companies: amazon, google, bloomberg

Level: new-grad, swe2

Bit Trick: n > 0 and (n & (n-1)) == 0. Powers of 2 have exactly one set bit; n-1 has all lower bits set; AND is 0.

Counting Bits DP Bit Manipulation - Python | Engineers of AI

Count set bits for 0..n using DP bit trick in O(n). Amazon, Google easy bit manipulation and DP question.

Topics: bit-manipulation, dynamic-programming

Companies: amazon, google, bloomberg

Level: new-grad, swe2

DP with Bit Trick: dp[i] = dp[i >> 1] + (i & 1). The count for i equals count for i/2 plus the last bit of i.

Sum of Two Integers Bit Manipulation - Python | Engineers of AI

Add two integers without + using XOR and AND carry in O(1). Amazon, Google, Bloomberg medium bit manipulation question.

Topics: bit-manipulation, math

Companies: amazon, google, bloomberg

Level: swe2, swe3

Bit Manipulation: XOR gives bits where exactly one is set (sum without carry). AND<<1 gives carry. Repeat until carry=0.

Reverse Integer - Python | Engineers of AI

Reverse integer digits with overflow check in O(log n). Amazon, Google, Bloomberg medium interview question.

Topics: math

Companies: amazon, google, bloomberg, microsoft

Level: swe2, swe3

Math: Extract digits with mod 10. Build reversed number. Check 32-bit bounds before returning.

Palindrome Number - Python | Engineers of AI

Check if integer is a palindrome without string conversion. Amazon, Google easy math interview question.

Topics: math

Companies: amazon, google, bloomberg, microsoft

Level: new-grad, swe2

Reverse Half: Negative or trailing-zero numbers are not palindromes. Reverse second half of digits and compare with first half.

String Conversion: Convert to string and compare with its reverse.

Integer to Roman Numeral - Python | Engineers of AI

Convert integer to Roman numeral using greedy approach in O(1). Amazon, Google, Bloomberg medium interview question.

Topics: math, string, hash-table

Companies: amazon, google, bloomberg, microsoft

Level: swe2, swe3

Greedy with Value Table: Table of values from 1000 to 1 including subtractive cases. Greedily subtract largest value, append symbol.

Roman to Integer - Python | Engineers of AI

Convert Roman numeral to integer using right-to-left scan in O(n). Amazon, Google easy math interview question.

Topics: math, string, hash-table

Companies: amazon, google, bloomberg, microsoft

Level: new-grad, swe2

Right to Left Scan: Scan right to left. If current value < previous value, subtract; otherwise add.

Excel Sheet Column Number - Python | Engineers of AI

Convert Excel column title to number using base-26 in O(n). Amazon, Google easy math interview question.

Topics: math, string

Companies: amazon, google, bloomberg, microsoft

Level: new-grad, swe2

Base-26 Conversion: Treat each char as a base-26 digit. A=1..Z=26. Accumulate result = result*26 + (ord(c)-64).

Happy Number Cycle Detection - Python | Engineers of AI

Determine if a number is happy using hash set or Floyd's cycle detection in O(log n). Amazon, Google easy math question.

Topics: math, hash-table, two-pointers

Companies: amazon, google, bloomberg

Level: new-grad, swe2

Hash Set for Cycle Detection: Compute sum of digit squares. If seen before, not happy. If reaches 1, happy.

Floyd's Cycle Detection: Fast pointer moves two steps, slow moves one. If they meet at 1, happy. If they meet elsewhere, unhappy.

Sqrt(x) Binary Search - Python | Engineers of AI

Compute integer square root using binary search in O(log x). Amazon, Google easy interview question with Python solution.

Topics: math, binary-search

Companies: amazon, google, bloomberg, microsoft

Level: new-grad, swe2

Binary Search: Binary search: find largest k where k*k <= x. Narrow range [0, x].

Greatest Common Divisor of Strings - Python | Engineers of AI

Find GCD of strings using math GCD of lengths in O(m+n). Amazon, Google easy math and string interview question.

Topics: math, string

Companies: amazon, google, bloomberg

Level: new-grad, swe2

Math GCD: If str1+str2 == str2+str1, a GCD string exists. Its length is gcd(len(str1), len(str2)).

Single Number - XOR Bit Manipulation Python | Engineers of AI

Find the element appearing once in O(n) time O(1) space using XOR bit manipulation. Classic Amazon Google interview question.

Topics: bit-manipulation, array, math

Companies: amazon, google, microsoft, meta, bloomberg

Level: new-grad, swe2

XOR Bit Manipulation: XOR all numbers together. Pairs cancel out (a^a=0) and 0^x=x leaves the single number.

Math (2*sum(set) - sum): 2 * sum(set(nums)) - sum(nums) equals the single number because each duplicate is counted once in the set.

Single Number II - Bit Manipulation Every Element 3 Times | Engineers of AI

Find the element appearing once when all others appear 3 times. Bit counting and state machine approaches in Python.

Topics: bit-manipulation, array, math

Companies: google, amazon, microsoft, bloomberg

Level: swe2, swe3

Bit Count Modulo 3: For each of the 32 bit positions, count how many numbers have that bit set. If count % 3 != 0, the single number has that bit set.

State Machine (ones, twos): Use two bitmasks: ones tracks bits seen once, twos tracks bits seen twice. When a bit is seen 3 times it resets to 0 in both.

Single Number III - Two Unique Numbers XOR Python | Engineers of AI

Find two numbers appearing once using XOR partitioning in O(n) time O(1) space. Google Amazon interview question.

Topics: bit-manipulation, array, math

Companies: google, amazon, microsoft

Level: swe2, swe3

XOR Partitioning: XOR all to get a^b. Find a set bit in a^b and use it to split numbers into two groups, each containing one unique number. XOR each group.

HashSet: Use a set: add elements not seen, remove if already present. What remains are the two unique numbers.

Hamming Weight Number of 1 Bits Python | Engineers of AI

Count set bits in an integer using Brian Kernighan algorithm and bit shifting. Classic bit manipulation interview question.

Topics: bit-manipulation, math

Companies: apple, microsoft, amazon, google

Level: new-grad, swe2

Brian Kernighan Algorithm: n & (n-1) clears the lowest set bit. Count how many times until n becomes 0.

Bit Check Each Position: Check each of the 32 bit positions by ANDing with 1 and right-shifting.

Reverse Bits 32-bit Integer Python | Engineers of AI

Reverse bits of a 32-bit unsigned integer using bit manipulation. Apple Amazon interview question with complete Python solution.

Topics: bit-manipulation, math

Companies: apple, amazon, microsoft

Level: new-grad, swe2

Bit by Bit Reversal: For each of 32 positions, take the LSB of n, add to result, shift n right and result left.

Python String Reversal: Format as 32-bit binary string, reverse it, convert back to int.

Missing Number XOR Gauss Formula Python | Engineers of AI

Find the missing number in range [0,n] using Gauss formula or XOR in O(n) time O(1) space. Amazon Microsoft interview question.

Topics: bit-manipulation, math, array

Companies: amazon, microsoft, google, bloomberg

Level: new-grad, swe2

Gauss Sum Formula: Expected sum is n*(n+1)/2. Subtract actual sum to find missing number.

XOR Approach: XOR all indices 0..n and all values. Each present number cancels its index; missing index remains.

Power of Two Bit Manipulation Python | Engineers of AI

Check if a number is power of two in O(1) using bit trick n&(n-1)==0. Classic bit manipulation interview question.

Topics: bit-manipulation, math, recursion

Companies: amazon, google, microsoft

Level: new-grad, swe2

Bit Trick: A power of two has exactly one bit set. n & (n-1) clears the lowest set bit; if result is 0, n was a power of two.

Repeated Division: Repeatedly divide by 2. If we reach 1, it is a power of two.

Counting Bits DP Python Solution | Engineers of AI

Count 1 bits for every number 0 to n in O(n) using DP relationship dp[i]=dp[i>>1]+(i&1).

Topics: bit-manipulation, dynamic-programming, math

Companies: amazon, google, microsoft, bloomberg

Level: new-grad, swe2

DP with Right Shift: dp[i] = dp[i // 2] + (i % 2). Dividing by 2 right-shifts, LSB contributes 1 if odd.

Brian Kernighan per element: For each number, repeatedly clear lowest bit to count set bits.

Sum of Two Integers Without Plus Operator Python | Engineers of AI

Add two integers without + operator using XOR and carry bit manipulation. Amazon Google interview question.

Topics: bit-manipulation, math

Companies: amazon, google, microsoft, meta

Level: swe2, swe3

Bit Manipulation with Carry: XOR gives bits that differ (sum without carry). AND<<1 gives carry. Repeat until carry is zero. Use mask for Python 32-bit handling.

Recursive: Recursively compute sum and carry until no carry remains.

Reverse Integer Python with Overflow Check | Engineers of AI

Reverse digits of a 32-bit integer with overflow handling. Amazon Bloomberg interview question with two Python solutions.

Topics: math

Companies: amazon, bloomberg, apple, microsoft

Level: new-grad, swe2

Pop and Push Digits: Extract digits from x using modulo, build reversed number, check 32-bit overflow.

String Reversal: Convert to string, reverse, handle sign and leading zeros, check overflow.

Palindrome Number Python Without String | Engineers of AI

Check if integer is palindrome by reversing half the number. Amazon Microsoft Bloomberg interview question.

Topics: math

Companies: amazon, microsoft, bloomberg, apple

Level: new-grad, swe2

Reverse Half the Number: Reverse the second half of x and compare with first half. Negative numbers and multiples of 10 (except 0) are not palindromes.

String Conversion: Convert to string and check if it equals its reverse.

Integer to Roman Numeral Python | Engineers of AI

Convert integer to Roman numeral using greedy approach. Amazon Bloomberg Microsoft interview question with complete Python solution.

Topics: math, string-matching

Companies: amazon, bloomberg, microsoft, uber

Level: swe2, swe3

Greedy with Value-Symbol Table: Define value-symbol pairs including subtractive forms in descending order. Greedily subtract largest possible value.

Digit by Digit Table: Pre-define Roman representations for each digit position (thousands, hundreds, tens, ones).

Roman to Integer Python Solution | Engineers of AI

Convert Roman numeral to integer using right-to-left scan. Amazon Google Bloomberg easy interview question.

Topics: math, string-matching

Companies: amazon, bloomberg, microsoft, apple, google

Level: new-grad, swe2

Right to Left Scan: Scan right to left. If current symbol value is less than the maximum seen so far, subtract it; otherwise add it.

Left to Right Peek Next: Scan left to right. If current value < next value, subtract current; otherwise add it.

Excel Sheet Column Number Python Base-26 | Engineers of AI

Convert Excel column title to number using base-26 arithmetic. Microsoft Amazon interview question.

Topics: math

Companies: microsoft, amazon, bloomberg

Level: new-grad, swe2

Base-26 Conversion: Treat as base-26 number where A=1, B=2, ..., Z=26. Process each character left to right.

functools.reduce: Use reduce to fold the base-26 accumulation over the string.

Happy Number Cycle Detection Python | Engineers of AI

Determine happy number using Floyd cycle detection or hashset. Amazon Microsoft Google interview question.

Topics: math, fast-slow-pointers, hash-map

Companies: amazon, microsoft, google, bloomberg

Level: new-grad, swe2

Fast-Slow Pointers (Floyd): Treat the sequence as a linked list. Use slow/fast pointers to detect cycle. If fast reaches 1, happy.

HashSet Cycle Detection: Track seen values in a set. If n becomes 1 return True; if n repeats return False.

Sqrt(x) Binary Search Newton Method Python | Engineers of AI

Compute integer square root using binary search or Newton method. Amazon Google Bloomberg interview question.

Topics: math, binary-search

Companies: amazon, google, bloomberg, microsoft

Level: new-grad, swe2

Binary Search: Binary search in [0, x]. Find largest m where m*m <= x.

Newton's Method: Newton's iteration: r = (r + x/r) / 2 converges to sqrt(x) quadratically.

GCD LCM Euclidean Algorithm Python | Engineers of AI

Implement GCD and LCM using Euclidean algorithm recursively and iteratively. Google Amazon math interview question.

Topics: math, number-theory, recursion

Companies: google, amazon, microsoft, bloomberg

Level: new-grad, swe2

Euclidean Algorithm: gcd: repeatedly replace (a,b) with (b, a%b) until b=0. lcm: a*b//gcd(a,b).

Recursive GCD: Recursive Euclidean: gcd(a,b) = a if b==0 else gcd(b, a%b).

Sieve of Eratosthenes Count Primes Python | Engineers of AI

Count primes less than n using Sieve of Eratosthenes in O(n log log n). Classic math interview question.

Topics: math, number-theory

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Sieve of Eratosthenes: Create boolean array, mark all multiples of each prime p starting from p^2 as composite.

Segmented Sieve (memory efficient): Use a standard sieve for small primes up to sqrt(n), then sieve segments of size sqrt(n).

Fast Power Exponentiation Python O(log n) | Engineers of AI

Implement pow(x,n) in O(log n) using recursive halving and iterative bit manipulation. Google Amazon interview question.

Topics: math, recursion, divide-and-conquer, bit-manipulation

Companies: google, amazon, microsoft, bloomberg, facebook

Level: swe2, swe3

Recursive Fast Exponentiation: Halve n each step: if n even x^n=(x^2)^(n/2), if n odd multiply by x. Handle negative n.

Iterative Bit Manipulation: Use bits of n to decide which powers of x to multiply. Square x each step, multiply result when bit is set.

Multiply Strings Python Grade School Algorithm | Engineers of AI

Multiply two large numbers represented as strings without converting to int. Amazon Google interview question.

Topics: math, string-matching, array

Companies: amazon, google, microsoft, bloomberg, facebook

Level: swe2, swe3

Grade School Multiplication: Each pair of digits (i,j) contributes to positions (i+j, i+j+1) in the result array. Build array, handle carries, convert to string.

Built-in Conversion (reference): Convert strings to int using ord arithmetic only, multiply, convert back without int().

Add Binary Strings Python | Engineers of AI

Add two binary strings and return the sum as binary string. Amazon Google easy interview question.

Topics: math, bit-manipulation, string-matching

Companies: amazon, google, microsoft, bloomberg, apple

Level: new-grad, swe2

Two Pointer from Right: Use pointers starting from end of each string. Add digits + carry, build result in reverse.

Python int Conversion: Convert both binary strings to int using base 2, add, convert result back to binary string.

Add Two Numbers Strings Python Without int() | Engineers of AI

Add two large numbers represented as strings using grade school algorithm. Amazon Google interview question.

Topics: math, string-matching

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Grade School Addition: Add digit by digit from right with carry, using ord to convert chars to ints.

zip_longest approach: Use itertools.zip_longest to pair up reversed strings, add digits + carry.

Count Digit 1 in Range 0 to N Python | Engineers of AI

Count occurrences of digit 1 in all numbers from 0 to n using mathematical position analysis. Hard Google Amazon interview.

Topics: math, number-theory, dynamic-programming

Companies: google, amazon, bloomberg, microsoft

Level: swe3, senior

Mathematical Position Analysis: For each digit position p (1,10,100...), calculate how many 1s appear in that position across all numbers 0..n.

Digit DP: Use digit DP counting 1s digit by digit with tight constraints.

Nth Ugly Number DP Three Pointers Python | Engineers of AI

Find nth ugly number (factors 2,3,5) using three pointer DP in O(n). Google Amazon interview question.

Topics: math, dynamic-programming, heap, two-pointers

Companies: google, amazon, bloomberg, microsoft

Level: swe2, swe3

Three Pointers DP: Maintain three pointers p2, p3, p5 into the ugly array. Each step take the minimum of dp[p2]*2, dp[p3]*3, dp[p5]*5.

Min Heap: Use a min-heap. Pop the minimum, push *2, *3, *5 of popped value. Skip duplicates with a seen set.

Perfect Squares Minimum Count DP BFS Python | Engineers of AI

Find minimum perfect squares summing to n using DP and BFS. Google Amazon interview question with two Python solutions.

Topics: dynamic-programming, bfs, math, number-theory

Companies: google, amazon, microsoft, bloomberg

Level: swe2, swe3

Dynamic Programming: dp[i] = minimum squares summing to i. For each i, try all perfect squares <= i.

BFS Level by Level: Treat as shortest path: BFS level = number of squares used. Return level when n is reached.

Merge Sort Python Implementation | Engineers of AI

Implement merge sort from scratch in Python. Covers recursive divide-and-conquer approach with O(n log n) time complexity.

Topics: sorting, divide-and-conquer, recursion

Companies: google, amazon, microsoft, meta, bloomberg

Level: new-grad, swe2

Recursive Merge Sort: Divide the array in half, recursively sort each half, then merge the two sorted halves by comparing elements one at a time.

In-place Merge Sort: Sort in place by modifying the input array directly during merge, using O(log n) stack space for recursion.

Quick Sort Randomized Pivot Python | Engineers of AI

Implement quicksort with randomized pivot in Python. Covers Lomuto and three-way partition approaches with complexity analysis.

Topics: sorting, divide-and-conquer, recursion

Companies: google, amazon, meta, microsoft, apple

Level: new-grad, swe2, swe3

Randomized QuickSort (Lomuto partition): Pick a random pivot, swap it to the end, then partition the array so all elements less than pivot are on the left. Recurse on both sides.

Three-Way Partition (Dutch Flag): Use Dutch National Flag three-way partition to handle duplicates efficiently. Partition into <pivot, ==pivot, >pivot.

Heap Sort Python Implementation | Engineers of AI

Implement heap sort in Python using a max-heap. In-place O(n log n) sorting with detailed heapify explanation.

Topics: sorting, heap

Companies: microsoft, amazon, google, bloomberg

Level: new-grad, swe2

Heap Sort (in-place max-heap): Build a max-heap in-place with O(n) heapify. Then repeatedly swap root (max) with last element, reduce heap size, and sift down.

Find Kth Largest Element Python - Heap and Quickselect | Engineers of AI

Find the kth largest element using min-heap O(n log k) and quickselect O(n). Top Amazon, Google, Meta interview question.

Topics: heap, sorting, divide-and-conquer

Companies: amazon, google, meta, microsoft, apple, uber, linkedin

Level: swe2, swe3

Min-Heap of size k: Maintain a min-heap of size k. For each element, push it. If heap exceeds k, pop the minimum. The root is always the kth largest.

Quickselect: Use quickselect: partition around a random pivot. If the pivot lands at position k-1 from the end, it is the answer. Recurse only on the relevant partition.

Sort Colors Dutch National Flag Python | Engineers of AI

Sort colors (0,1,2) in one pass using Dutch National Flag algorithm with three pointers. Classic Amazon and Microsoft interview question.

Topics: array, sorting, two-pointers, dutch-flag

Companies: amazon, microsoft, google, meta, bloomberg, uber

Level: new-grad, swe2

Dutch National Flag (one pass): Use three pointers: low (boundary of 0s), mid (current), high (boundary of 2s). Swap 0s left and 2s right while advancing mid.

Two-pass count sort: Count occurrences of 0, 1, 2, then overwrite the array. Simple but two passes.

Merge Intervals Python Solution | Engineers of AI

Merge overlapping intervals in Python with sort and scan approach. O(n log n) solution for Google, Amazon, Meta interviews.

Topics: array, sorting, interval

Companies: google, amazon, microsoft, meta, bloomberg, uber, linkedin, apple

Level: swe2, swe3

Sort and Merge: Sort intervals by start time. Iterate through and merge the current interval with the last interval in result if they overlap (start <= last end).

Insert Interval Python Solution | Engineers of AI

Insert and merge a new interval into a sorted non-overlapping interval list. O(n) linear scan solution for Google and Amazon interviews.

Topics: array, interval, binary-search

Companies: google, amazon, microsoft, linkedin, bloomberg

Level: swe2, swe3

Linear Scan Three Phases: Add all intervals ending before new interval starts. Merge all overlapping intervals. Add all remaining intervals.

Search in Rotated Sorted Array Python | Engineers of AI

Binary search in a rotated sorted array in O(log n). Essential Amazon, Google, Apple interview question with clear Python solution.

Topics: binary-search, array

Companies: amazon, google, microsoft, meta, apple, bloomberg, uber

Level: swe2, swe3

Binary Search on Rotated Array: At each step, determine which half is sorted. If the target lies in the sorted half, search there. Otherwise search the other half.

Find Peak Element Binary Search Python | Engineers of AI

Find a peak element in O(log n) using binary search. Google interview question with detailed explanation.

Topics: binary-search, array

Companies: google, microsoft, amazon, meta

Level: swe2, swe3

Binary Search: If nums[mid] < nums[mid+1], slope is going up so peak is to the right. Otherwise slope is going down (or mid is peak) so peak is to the left or at mid.

Search 2D Matrix Binary Search Python | Engineers of AI

Search a sorted 2D matrix in O(log(mn)) by treating it as a 1D array. Amazon and Microsoft interview question.

Topics: binary-search, matrix, array

Companies: amazon, microsoft, google, bloomberg, apple

Level: swe2, swe3

Binary Search (treat as 1D): Treat the m*n matrix as a sorted 1D array. Binary search on indices 0 to m*n-1. Convert mid index to row=mid//n, col=mid%n.

Median of Two Sorted Arrays Python O(log n) | Engineers of AI

Find median of two sorted arrays in O(log(min(m,n))) using binary search partition. Hard Google and Amazon interview problem.

Topics: binary-search, divide-and-conquer, array

Companies: google, amazon, microsoft, meta, apple, uber, bloomberg

Level: swe3, senior, staff

Binary Search on partition: Binary search on the smaller array to find partition point. Left side of both arrays combined = half of total elements. Median comes from max of left parts and min of right parts.

Merge then find median (O(m+n)): Merge both sorted arrays fully, then return the middle element(s). Simpler but does not meet the O(log(m+n)) constraint.

Find Minimum Rotated Sorted Array Python | Engineers of AI

Find minimum element in rotated sorted array in O(log n) with binary search. Amazon, Google interview question.

Topics: binary-search, array

Companies: amazon, microsoft, google, apple, bloomberg

Level: swe2, swe3

Binary Search: Binary search: if nums[mid] > nums[right], minimum is in right half. Otherwise minimum is in left half (including mid).

H-Index Python Solution | Engineers of AI

Calculate researcher h-index in Python using sort or counting sort. Google and LinkedIn interview question with O(n) solution.

Topics: array, sorting, binary-search

Companies: google, amazon, bloomberg, linkedin

Level: swe2, swe3

Sort descending: Sort descending. h is the largest index+1 where citations[i] >= i+1. After sort, citations[i] >= i+1 means at least i+1 papers with >= i+1 citations.

Counting Sort O(n): Use bucket counting: bucket[i] = papers with exactly i citations (cap at n). Scan from right; accumulate count; first position where count >= i is h-index.

Meeting Rooms II Python Min Heap | Engineers of AI

Find minimum conference rooms needed with min-heap approach. O(n log n) solution for Amazon, Google, Meta interviews.

Topics: heap, sorting, interval, greedy

Companies: amazon, google, microsoft, meta, bloomberg, uber, linkedin

Level: swe2, swe3, senior

Min-Heap of end times: Sort by start. Maintain a min-heap of end times (rooms in use). For each meeting, if the earliest-ending room ends before this starts, reuse it. Otherwise allocate a new room.

Two sorted arrays (events): Create separate sorted arrays of start times and end times. Use two pointers: when a new meeting starts, if earliest end has passed, decrement rooms needed.

Largest Number Custom Sort Python | Engineers of AI

Arrange numbers to form largest number using custom comparator sort. Amazon and Google interview question.

Topics: sorting, greedy, strings

Companies: amazon, microsoft, google, bloomberg, uber

Level: swe2, swe3

Custom Comparator Sort: Convert numbers to strings. Custom sort: a comes before b if str(a)+str(b) > str(b)+str(a). Join sorted strings and handle leading zeros.

Count Smaller Numbers After Self Python Merge Sort | Engineers of AI

Count smaller elements to the right using merge sort in O(n log n). Hard Google and Amazon interview problem.

Topics: sorting, divide-and-conquer, binary-search

Companies: google, amazon, meta, microsoft

Level: swe3, senior

Merge Sort with index tracking: Merge sort on (value, original_index) pairs. During merge, whenever a right-half element is placed before a left-half element, all remaining left-half elements get +1 count.

Sort Linked List Merge Sort Python | Engineers of AI

Sort a linked list in O(n log n) using merge sort with slow/fast pointer split. Amazon and Google interview question.

Topics: linked-list, sorting, divide-and-conquer, two-pointers

Companies: amazon, microsoft, google, meta, bloomberg

Level: swe2, swe3

Merge Sort (top-down recursive): Find midpoint with slow/fast pointers, split into two halves, sort each half recursively, then merge the two sorted lists.

Top K Frequent Elements Python Heap Bucket Sort | Engineers of AI

Find top k frequent elements using heap O(n log k) or bucket sort O(n). Amazon, Google, Meta interview question.

Topics: heap, hash-map, sorting, bucket-sort

Companies: amazon, google, meta, microsoft, bloomberg, uber, apple

Level: swe2, swe3

Min-Heap: Count frequency of each element. Maintain min-heap of size k keyed by frequency. Final heap contains the k most frequent elements.

Bucket Sort O(n): Count frequencies. Create frequency buckets where bucket[i] holds all elements with frequency i. Read from highest bucket downward until k elements collected.

Top K Frequent Words Python Heap | Engineers of AI

Find top k frequent words sorted by frequency then lexicographically using a min-heap. Amazon and Google interview question.

Topics: heap, hash-map, sorting, strings

Companies: amazon, google, microsoft, bloomberg, apple

Level: swe2, swe3

Min-Heap with negated frequency: Count frequencies. Use a min-heap of (-frequency, word) tuples. Python heaps are min-heaps; negating frequency makes highest frequency float up. Pop when size > k.

Find K Closest Elements Binary Search Python | Engineers of AI

Find k closest elements to x in sorted array using binary search on window boundary. Google and Amazon interview question.

Topics: binary-search, array, two-pointers, sliding-window

Companies: google, amazon, microsoft, linkedin

Level: swe2, swe3

Binary Search on window left boundary: Binary search for the left start of the k-element window. At each mid, compare distance of arr[mid] vs arr[mid+k] to x to decide which side the window should be on.

Kth Smallest in Sorted Matrix Python Heap Binary Search | Engineers of AI

Find kth smallest in sorted matrix using binary search or min-heap. Google and Goldman Sachs interview question.

Topics: binary-search, heap, matrix

Companies: google, amazon, microsoft, goldman-sachs, bloomberg

Level: swe3, senior

Binary Search on value: Binary search on answer in range [matrix[0][0], matrix[n-1][n-1]]. Count elements <= mid using sorted row property. Find smallest value with count >= k.

Min-Heap k-way merge: Push first element of each row into min-heap. Pop k times; each pop, push the next element in same row.

Find K Pairs Smallest Sums Python Min Heap | Engineers of AI

Find k pairs with smallest sums from two sorted arrays using min-heap. Google interview question with O(k log k) solution.

Topics: heap, array, k-way-merge

Companies: google, amazon, microsoft, bloomberg

Level: swe3, senior

Min-Heap: Initialize heap with (sum, i=0..min(k,len(nums1)), j=0). Pop smallest, record pair, push next j for same i.

Sort Characters By Frequency Python | Engineers of AI

Sort string characters by frequency using Counter and heap. Amazon and Google interview question with clean O(n log n) solution.

Topics: hash-map, heap, sorting, strings

Companies: amazon, google, microsoft, bloomberg

Level: new-grad, swe2

Counter + Sort: Count character frequencies. Sort unique characters by frequency descending. Build result by repeating each character by its frequency count.

Wiggle Sort II Python | Engineers of AI

Reorder array into wiggle pattern using sort and interleave. Google and Amazon interview question.

Topics: array, sorting, dutch-flag

Companies: google, amazon, microsoft

Level: swe3, senior

Sort + interleave: Sort array. Place upper half (larger values) at odd indices and lower half (smaller) at even indices, both from back to front to handle duplicate medians.

Relative Ranks Python | Engineers of AI

Assign relative ranks and medals to athletes by score. Easy sorting problem for Amazon and Microsoft interviews.

Topics: array, sorting, heap

Companies: amazon, microsoft, bloomberg

Level: new-grad, swe2

Sort by index: Create list of (score, index) pairs, sort by score descending. Assign medal or rank string to each index in that order.

3Sum Two Pointers Python | Engineers of AI

Find all unique triplets summing to zero using sort and two pointers in O(n^2). Amazon, Google, Meta interview question.

Topics: array, two-pointers, sorting

Companies: amazon, google, meta, microsoft, apple, bloomberg, uber, adobe

Level: swe2, swe3

Sort + Two Pointers: Sort the array. For each index i, use two pointers left=i+1 and right=n-1. Move pointers based on sum. Skip duplicates by advancing past equal values.

4Sum Python Two Pointers | Engineers of AI

Find all unique quadruplets summing to target using nested loops and two pointers. Amazon and Google interview question.

Topics: array, two-pointers, sorting

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Sort + Two Nested Loops + Two Pointers: Sort array. Two outer loops fix first two elements, two pointers scan remaining. Skip duplicates at all four positions.

Container With Most Water Two Pointers Python | Engineers of AI

Find maximum water container area using two pointers in O(n). Amazon, Google, Meta, Apple interview question.

Topics: array, two-pointers, greedy

Companies: amazon, google, meta, microsoft, apple, bloomberg, uber, adobe

Level: swe2, swe3

Two Pointers: Start with left=0, right=n-1. Area = min(height[left], height[right]) * (right-left). Move the pointer with shorter height inward to potentially find larger area.

Trapping Rain Water Python Two Pointers | Engineers of AI

Compute trapped rain water in O(n) time O(1) space using two pointers. Hard Amazon, Google, Meta interview problem.

Topics: array, two-pointers, stack, dynamic-programming

Companies: amazon, google, microsoft, meta, apple, bloomberg, uber, goldman-sachs

Level: swe3, senior

Two Pointers O(1) space: Two pointers from each end. Track max_left and max_right. The side with smaller max determines the water at that position. Move that pointer inward.

Precompute left/right max arrays: Precompute max height to the left and right of each position. Water at each position is min(left_max, right_max) - height[i].

Minimum Window Substring Python Sliding Window | Engineers of AI

Find minimum window substring using sliding window and frequency maps in O(|s|+|t|). Hard Amazon, Google, Meta interview.

Topics: sliding-window, hash-map, two-pointers, strings

Companies: amazon, google, meta, microsoft, bloomberg, uber, linkedin

Level: swe3, senior

Sliding Window with Frequency Map: Expand window right pointer. Once all chars of t covered, try shrinking from left. Track "formed" count (chars meeting their required frequency). Update min window whenever formed == required.

Longest Substring Without Repeating Characters Python | Engineers of AI

Find longest substring without repeating characters using sliding window in O(n). Classic Amazon, Google, Meta interview question.

Topics: sliding-window, hash-map, strings, two-pointers

Companies: amazon, google, meta, microsoft, apple, bloomberg, uber, adobe

Level: new-grad, swe2

Sliding Window with Set: Expand right. If character already in window set, shrink left until it is removed. Track max window length.

Sliding Window with HashMap (O(n) jumps): Store last seen index of each character. When a repeat is found, jump left pointer directly to last_seen[char]+1 instead of shrinking one step at a time.

Permutation in String Sliding Window Python | Engineers of AI

Check if string contains permutation of s1 using fixed sliding window with frequency arrays. Amazon and Microsoft interview question.

Topics: sliding-window, hash-map, strings, two-pointers

Companies: amazon, microsoft, google, bloomberg, meta

Level: swe2, swe3

Fixed Sliding Window with frequency arrays: Maintain frequency count arrays of size 26 for s1 and current window. Slide window of length len(s1) across s2, updating counts. If arrays match, return True.

Find All Anagrams in String Python | Engineers of AI

Find all anagram start indices using sliding window in O(|s|). Amazon, Google, Meta interview question.

Topics: sliding-window, hash-map, strings

Companies: amazon, google, meta, microsoft, bloomberg

Level: swe2, swe3

Sliding Window with "matches" counter: Track count of characters with matching frequencies between window and p. When matches == 26, window is an anagram. Slide and update matches count.

Longest Repeating Character Replacement Python | Engineers of AI

Find longest substring after k replacements using sliding window in O(n). Amazon and Google interview question.

Topics: sliding-window, hash-map, strings, two-pointers

Companies: amazon, google, microsoft, bloomberg, uber

Level: swe2, swe3

Sliding Window: Expand window right. Valid if (window_size - max_char_count) <= k. When invalid, slide window right by moving left pointer. Track global max_count (never decrease it since smaller windows cannot give better answer).

Max Consecutive Ones III Sliding Window Python | Engineers of AI

Maximize consecutive ones with k zero flips using sliding window in O(n). Google and Amazon interview question.

Topics: sliding-window, array, two-pointers

Companies: google, amazon, microsoft, bloomberg

Level: swe2, swe3

Sliding Window: Expand right. Count zeros in window. When zeros > k, shrink left until zeros <= k. Track max window size.

Fruit Into Baskets Sliding Window Python | Engineers of AI

Find max fruits with 2 baskets using sliding window with at most 2 distinct types. Amazon and Google interview question.

Topics: sliding-window, hash-map, array

Companies: amazon, google, microsoft

Level: swe2, swe3

Sliding Window - at most 2 distinct: Sliding window maintaining at most 2 distinct fruit types in a frequency map. When map has 3 types, shrink left until one type is removed.

Subarrays with K Different Integers Python | Engineers of AI

Count subarrays with exactly k distinct integers using at-most trick with sliding window. Hard Google interview question.

Topics: sliding-window, hash-map, array

Companies: google, amazon, meta

Level: swe3, senior

Sliding Window: exact = atMost(k) - atMost(k-1): Subarrays with exactly k distinct = subarrays with at most k distinct - subarrays with at most k-1 distinct. The atMost function uses a sliding window.

Minimum Size Subarray Sum Python Sliding Window | Engineers of AI

Find minimum subarray with sum >= target using sliding window in O(n). Amazon and Google interview question.

Topics: sliding-window, array, binary-search, two-pointers

Companies: amazon, google, microsoft, bloomberg, linkedin

Level: swe2, swe3

Sliding Window: Expand right adding to current sum. Whenever sum >= target, try shrinking from left and update minimum length.

Longest Subarray of 1s After Deleting One Element Python | Engineers of AI

Find longest subarray of 1s after deleting one element using sliding window. Amazon and Google interview question.

Topics: sliding-window, array, dynamic-programming

Companies: amazon, google, microsoft

Level: swe2, swe3

Sliding Window with at most 1 zero: Sliding window allowing at most 1 zero. Result is max window length - 1 (one element must be deleted).

Count Nice Subarrays with K Odd Numbers Python | Engineers of AI

Count subarrays with exactly k odd numbers using prefix sum in O(n). Amazon and Google interview question.

Topics: sliding-window, prefix-sum, array

Companies: amazon, google, bloomberg

Level: swe2, swe3

Prefix Sum: Track cumulative odd count. For each position, if (odd_count - k) seen before, those starting positions give valid subarrays. Store prefix odd counts in a hash map.

Subarray Product Less Than K Sliding Window Python | Engineers of AI

Count subarrays with product less than k using sliding window in O(n). Amazon and Google interview question.

Topics: sliding-window, array, two-pointers

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Sliding Window: Expand right, multiply product. When product >= k, shrink left by dividing. Count of new valid subarrays ending at right = right - left + 1.

Minimum Operations Reduce X to Zero Python | Engineers of AI

Minimum edge removals to reduce x to zero using complement sliding window. Google and Amazon interview question.

Topics: sliding-window, array, prefix-sum, hash-map

Companies: google, amazon, microsoft

Level: swe2, swe3

Sliding Window on complement: Instead of removing from edges, find the longest subarray in the middle with sum = total - x. Answer is n minus that length.

Maximum Erasure Value Sliding Window Python | Engineers of AI

Find maximum sum subarray with unique elements using sliding window in O(n). Amazon and Google interview question.

Topics: sliding-window, hash-map, array

Companies: amazon, google, microsoft

Level: swe2, swe3

Sliding Window with Set: Maintain a set of current window elements and running sum. When a duplicate is found, remove elements from the left until the duplicate is gone.

Substrings Containing All Three Characters Python | Engineers of AI

Count substrings with all three characters a, b, c using last-seen index trick in O(n). Google interview question.

Topics: sliding-window, hash-map, strings

Companies: google, amazon, bloomberg

Level: swe2, swe3

Sliding Window: Track last seen index of each of a, b, c. For each right position, the number of valid subarrays ending at right equals min(last_a, last_b, last_c) + 1.

Replace Substring for Balanced String Python | Engineers of AI

Find minimum replacement window to balance QWER string using sliding window. Google interview question.

Topics: sliding-window, strings, two-pointers

Companies: google, amazon

Level: swe3, senior

Sliding Window: Count frequencies. Slide a window: outside window, all character counts must be <= n/4. Shrink left when possible. Track minimum valid window size.

Sliding Window Median Python Two Heaps | Engineers of AI

Compute sliding window median using two heaps with lazy deletion in O(n log k). Hard Google and Amazon interview problem.

Topics: sliding-window, heap, two-heaps

Companies: google, amazon, meta, bloomberg

Level: senior, staff

Two Heaps with Lazy Deletion: Maintain max-heap (lower half) and min-heap (upper half). Use lazy deletion: track counts of elements to remove. Balance heaps after each slide. Median comes from heap tops.

Maximum Points from Cards Sliding Window Python | Engineers of AI

Maximize card points from edges using complement sliding window. Amazon and Google interview question.

Topics: sliding-window, array, prefix-sum

Companies: amazon, google, microsoft

Level: swe2, swe3

Sliding Window on middle subarray: Total - minimum window sum of size (n-k). Slide a window of size n-k and find the minimum sum. Answer is total - that minimum.

Longest Subarray Absolute Diff at Most Limit Python | Engineers of AI

Find longest subarray with max-min <= limit using monotonic deques. Google and Amazon interview question.

Topics: sliding-window, deque, monotonic-stack

Companies: google, amazon, meta

Level: swe3, senior

Sliding Window with Two Deques: Maintain two deques: max_deque (decreasing) and min_deque (increasing). Max-min gives range of window. When range > limit, shrink left, removing from deques if they point to left index.

Grumpy Bookstore Owner Sliding Window Python | Engineers of AI

Maximize satisfied customers using sliding window on grumpy minutes. Amazon and Google interview question.

Topics: sliding-window, array

Companies: amazon, google, bloomberg

Level: swe2, swe3

Sliding Window: Base satisfied customers when not grumpy. Add sliding window of size minutes to find maximum extra customers gained (grumpy minutes converted). Result = base + max_extra.

Minimum K Consecutive Bit Flips Python | Engineers of AI

Find minimum k-bit flips to make all ones using greedy sliding window. Hard Google interview problem.

Topics: sliding-window, array, greedy, bit-manipulation

Companies: google, amazon, meta

Level: senior, staff

Sliding Window with flip tracker: Use a deque to track flip endpoints. For each position, current flip state = len(deque) % 2. If flip needed (nums[i] XOR flips == 0), flip and add end position. If window expired, pop from deque.

Valid Parentheses Stack Python | Engineers of AI

Validate matching parentheses using a stack in O(n). Classic Amazon, Google, Meta interview question.

Topics: stack, strings

Companies: amazon, google, meta, microsoft, bloomberg, apple, uber

Level: new-grad, swe2

Stack: Use a stack. Push open brackets. For each closing bracket, check if the top of the stack is the corresponding open bracket. If stack is empty or mismatch, return False.

Min Stack Design Python O(1) | Engineers of AI

Design a stack with O(1) push, pop, top, and getMin. Classic Amazon, Google, Apple interview question.

Topics: stack, design

Companies: amazon, google, microsoft, meta, bloomberg, apple

Level: new-grad, swe2

Auxiliary min stack: Maintain two stacks: main stack and min_stack. min_stack[i] = minimum of all elements up to position i. Push to both; pop from both; getMin returns min_stack top.

Single stack storing (val, min) pairs: Store tuples (value, current_min) in a single stack. Each push records the running minimum.

Evaluate Reverse Polish Notation Stack Python | Engineers of AI

Evaluate RPN arithmetic expression using a stack in O(n). Amazon, Microsoft, Bloomberg interview question.

Topics: stack, array, math

Companies: amazon, microsoft, bloomberg, google, linkedin

Level: swe2, swe3

Stack: Iterate tokens. Push numbers onto stack. For each operator, pop two operands, compute result, push back. Final stack element is the answer.

Daily Temperatures Monotonic Stack Python | Engineers of AI

Find days until warmer temperature using monotonic stack in O(n). Amazon, Google, Microsoft interview question.

Topics: stack, array, monotonic-stack

Companies: amazon, google, microsoft, bloomberg, uber, meta

Level: swe2, swe3

Monotonic Stack: Maintain a monotonic decreasing stack of indices. For each day, pop all indices where current temperature is warmer; record the wait. Push current index.

Largest Rectangle in Histogram Stack Python | Engineers of AI

Find largest rectangle in histogram using monotonic stack in O(n). Hard Amazon, Google, Goldman Sachs interview problem.

Topics: stack, array, monotonic-stack

Companies: amazon, google, microsoft, meta, bloomberg, goldman-sachs

Level: swe3, senior, staff

Monotonic Stack: Maintain a monotonic increasing stack of (index, height) pairs. When a shorter bar is encountered, pop taller bars and compute their maximum rectangles using the current index as the right boundary.

Implement Queue Using Stacks Python | Engineers of AI

Implement FIFO queue using two stacks with amortized O(1) operations. Amazon and Microsoft interview design question.

Topics: stack, queue, design

Companies: amazon, microsoft, google, bloomberg

Level: new-grad, swe2

Two Stacks with lazy transfer: Push always goes to in_stack. Pop/peek: if out_stack is empty, transfer all from in_stack to out_stack. Then operate on out_stack.

Implement Stack Using Queues Python | Engineers of AI

Implement LIFO stack using queues with rotation approach. Amazon and Google interview design question.

Topics: stack, queue, design

Companies: amazon, google, microsoft

Level: new-grad, swe2

One Queue with rotation: Push x to queue, then rotate all previous elements to the back (dequeue and enqueue n-1 times). Now x is at the front, simulating LIFO.

Sliding Window Maximum Monotonic Deque Python | Engineers of AI

Find sliding window maximum using monotonic deque in O(n). Hard Amazon, Google, Meta interview problem.

Topics: deque, sliding-window, monotonic-stack, array

Companies: amazon, google, meta, microsoft, bloomberg, uber

Level: swe3, senior

Monotonic Deque: Maintain a deque of indices with decreasing values. Front is always the max of current window. Remove front when it falls out of window. Remove from back when adding larger elements.

Next Greater Element I Monotonic Stack Python | Engineers of AI

Find next greater element for each number using monotonic stack and hash map in O(n). Amazon interview question.

Topics: stack, array, hash-map, monotonic-stack

Companies: amazon, microsoft, bloomberg

Level: new-grad, swe2

Monotonic Stack + Hash Map: Compute next greater element for each element in nums2 using a monotonic stack. Store results in a hash map. Answer for each element of nums1 is a lookup.

Next Greater Element II Circular Array Python | Engineers of AI

Find next greater element in circular array using monotonic stack with double pass. Amazon and Google interview question.

Topics: stack, array, monotonic-stack

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Monotonic Stack with 2x pass: Iterate 2n indices. Use i % n for circular indexing. Monotonic decreasing stack stores indices. When current > stack top element, pop and record next greater.

Basic Calculator Stack Python | Engineers of AI

Evaluate arithmetic expression with parentheses using a stack in O(n). Hard Google, Amazon interview problem.

Topics: stack, strings, math

Companies: google, amazon, microsoft, bloomberg, meta

Level: swe3, senior

Stack for parentheses: Track current result and sign. On "(", push current result and sign to stack, reset. On ")", pop saved result and sign and combine. Accumulate number before processing operator.

Basic Calculator II Stack Python | Engineers of AI

Evaluate expression with +, -, *, / using stack in O(n). Amazon, Google, Meta interview question.

Topics: stack, strings, math

Companies: amazon, google, microsoft, bloomberg, meta, uber

Level: swe2, swe3

Stack with operator handling: Iterate through string building current number. At each operator (or end), apply the previous operator to the current number: push for +/-, compute immediately for */. Sum the stack.

Remove Duplicate Letters Greedy Stack Python | Engineers of AI

Find lexicographically smallest string after removing duplicates using greedy monotonic stack. Google interview question.

Topics: stack, greedy, strings, monotonic-stack

Companies: google, amazon, meta

Level: swe3, senior

Greedy Monotonic Stack: Count last occurrences. Maintain stack (result). For each char: if already in stack, skip. Else pop stack top while top > current char AND top appears again later. Push current char.

Remove K Digits Smallest Number Python | Engineers of AI

Find smallest number after removing k digits using greedy monotonic stack. Google and Amazon interview question.

Topics: stack, greedy, strings, monotonic-stack

Companies: google, amazon, microsoft, bloomberg

Level: swe2, swe3

Greedy Monotonic Stack: Maintain monotonic increasing stack. For each digit, pop the stack top when it is larger than current digit and k > 0. Append current digit. After all digits, remove remaining k from end. Strip leading zeros.

132 Pattern Monotonic Stack Python | Engineers of AI

Detect 132 pattern in array using monotonic stack from right in O(n). Google and Amazon interview question.

Topics: stack, array, monotonic-stack

Companies: google, amazon, microsoft

Level: swe3, senior

Monotonic Stack from right: Scan right to left. Maintain a decreasing stack. Whenever we pop (current > stack top), that popped value is "k" (the middle). If we ever find a value smaller than k, we found nums[i] < k < nums[j].

Score of Parentheses Stack Python | Engineers of AI

Compute score of balanced parentheses string using a stack in O(n). Google and Bloomberg interview question.

Topics: stack, strings

Companies: google, amazon, bloomberg

Level: swe2, swe3

Stack: Push 0 onto stack for each "(". For each ")", if top is 0 it was "()" so replace with 1; else pop, double it, add to new top (cumulative at that level).

Asteroid Collision Stack Python | Engineers of AI

Simulate asteroid collisions using a stack in O(n). Amazon and Google interview question.

Topics: stack, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Stack: Push each asteroid. If current is negative and top is positive, they collide. Pop the stack if current wins. If equal, both explode. Current is destroyed if stack top wins.

Online Stock Span Monotonic Stack Python | Engineers of AI

Compute stock price span online using monotonic stack with O(1) amortized per call. Amazon and Google interview question.

Topics: stack, design, monotonic-stack

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Monotonic Stack: Stack of (price, span) pairs, monotonically decreasing by price. When new price >= top price, pop and add span. Push (price, total_span). Return total_span.

Sum of Subarray Minimums Monotonic Stack Python | Engineers of AI

Compute sum of subarray minimums using contribution technique with monotonic stack in O(n). Amazon and Google interview question.

Topics: stack, array, monotonic-stack, dynamic-programming

Companies: amazon, google, meta, microsoft

Level: swe3, senior

Monotonic Stack - contribution technique: For each element arr[i], find the number of subarrays where it is the minimum: left_count = distance to previous smaller, right_count = distance to next smaller or equal. Contribution = arr[i] * left_count * right_count.

Maximal Rectangle Matrix Stack Python | Engineers of AI

Find maximal rectangle in binary matrix using histogram and monotonic stack. Hard Amazon, Google interview problem.

Topics: stack, matrix, array, dynamic-programming, monotonic-stack

Companies: amazon, google, microsoft, meta, bloomberg

Level: swe3, senior, staff

Histogram + Monotonic Stack: Build cumulative height histogram row by row (height[j] = consecutive 1s above, reset to 0 on "0"). Apply largest rectangle in histogram algorithm on each row.

Car Fleet Stack Python | Engineers of AI

Count car fleets arriving at destination using sort and stack in O(n log n). Amazon and Google interview question.

Topics: stack, array, sorting, monotonic-stack

Companies: amazon, google, microsoft

Level: swe2, swe3

Sort + Stack: Sort cars by position descending. Compute time to target for each. Use a stack: if current car arrives faster than stack top (closer car), they merge (same fleet, current does not add). Else push.

Decode String Stack Python | Engineers of AI

Decode encoded string with k[encoded_string] format using two stacks. Amazon, Google, Bloomberg interview question.

Topics: stack, strings, recursion

Companies: amazon, google, microsoft, bloomberg, meta

Level: swe2, swe3

Two-stack approach: Maintain a count_stack and string_stack. On digit, accumulate count. On "[", push current string and count to stacks, reset. On "]", pop count and base, repeat current and concatenate.

Maximum Width Ramp Monotonic Stack Python | Engineers of AI

Find maximum width ramp using prefix minimum stack and right scan in O(n). Google interview question.

Topics: stack, array, two-pointers, monotonic-stack

Companies: google, amazon

Level: swe3, senior

Monotonic Stack + Right Scan: Build decreasing stack of indices (prefix minimums, left candidates). Then scan right to left: for each j, pop stack while nums[stack.top] <= nums[j] and record j - stack.top.

Number of Visible People in Queue Stack Python | Engineers of AI

Count visible people in queue using monotonic stack scan from right. Hard Google and Amazon interview problem.

Topics: stack, array, monotonic-stack

Companies: google, amazon, meta

Level: swe3, senior

Monotonic Stack from right: Scan right to left. Maintain a decreasing monotonic stack. For each person i, pop all shorter people from stack (they are visible to i). The first taller person in the stack (if any) is also visible. Count = pops + (1 if stack non-empty).

Minimum Add Make Parentheses Valid Python | Engineers of AI

Find minimum insertions to make parentheses string valid using counter in O(n). Amazon and Google interview question.

Topics: stack, strings, greedy

Companies: amazon, google, bloomberg

Level: swe2, swe3

Greedy Counter: Track open (unmatched opens) and close (unmatched closes). For "(" increment open. For ")" if open > 0 decrement open (matched), else increment close. Answer = open + close.

Kth Largest Element Heap Python | Engineers of AI

Find kth largest element using min-heap of size k. Amazon, Google, Meta interview question with heap focus.

Topics: heap, sorting

Companies: amazon, google, meta, microsoft, apple, bloomberg

Level: swe2, swe3

heapq.nlargest: Use heapq.nlargest which internally maintains a min-heap of size k, returning the kth largest element as heap[0].

Manual min-heap of size k: Build heap manually, pushing each element and popping when size exceeds k. The heap root is the kth largest.

Find Median from Data Stream Two Heaps Python | Engineers of AI

Find streaming median using two heaps (max + min) with O(log n) insert, O(1) median. Amazon, Google, Meta hard interview.

Topics: heap, two-heaps, design, sorting

Companies: amazon, google, microsoft, meta, bloomberg, apple

Level: swe3, senior

Two Heaps (max-heap + min-heap): lo is a max-heap (negated in Python) for the lower half. hi is a min-heap for the upper half. Always maintain len(lo) >= len(hi). On add: push to lo first, then balance.

Merge K Sorted Lists Heap Divide Conquer Python | Engineers of AI

Merge k sorted linked lists using min-heap O(n log k) or divide and conquer. Amazon, Google, Meta hard interview.

Topics: heap, linked-list, k-way-merge, divide-and-conquer

Companies: amazon, google, microsoft, meta, bloomberg, apple, uber

Level: swe3, senior

Min-Heap: Initialize heap with (val, index, node) for each list head. Pop min, attach to result, push next node from same list. Use index as tiebreaker.

Divide and Conquer: Recursively merge lists in pairs (like merge sort). Each level merges n total nodes across k/2 pairs, log k levels total.

Task Scheduler Greedy Heap Python | Engineers of AI

Minimize CPU intervals for task scheduling with cooldown using formula or heap simulation. Amazon, Google, Meta interview.

Topics: heap, greedy, hash-map, array

Companies: amazon, google, microsoft, meta, bloomberg, uber

Level: swe2, swe3

Math formula: Count task frequencies. The minimum time is max(len(tasks), (max_freq-1)*(n+1) + count_of_tasks_with_max_freq). The formula accounts for idles between most frequent tasks.

Max-Heap Simulation: Simulate scheduling: use a max-heap (negated freq). Each cycle of n+1, pick the most frequent tasks, reduce counts. Count total time including any idles.

Reorganize String No Adjacent Duplicates Python | Engineers of AI

Rearrange string so no two adjacent characters are equal using max-heap. Amazon and Google interview question.

Topics: heap, greedy, hash-map, strings

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Max-Heap: Count frequencies. If max_freq > (n+1)//2, impossible. Else use max-heap: pop two most frequent at a time, append both, push back if remaining count > 0.

K Closest Points to Origin Heap Python | Engineers of AI

Find k closest points to origin using max-heap O(n log k) or sort O(n log n). Amazon, Google, Meta interview question.

Topics: heap, array, sorting, divide-and-conquer

Companies: amazon, google, meta, microsoft, uber, linkedin, bloomberg

Level: swe2, swe3

Max-Heap of size k: Use a max-heap of size k (negate distance for Python min-heap). For each point, if heap is smaller than k push it. Otherwise if distance < heap max, replace. Return heap elements.

Sort by distance: Sort all points by their squared Euclidean distance (no need for sqrt). Return the first k.

Smallest Range Covering K Lists Python | Engineers of AI

Find smallest range covering elements from k sorted lists using min-heap. Hard Google and Amazon interview problem.

Topics: heap, array, sorting, k-way-merge, sliding-window

Companies: google, amazon, meta, bloomberg

Level: senior, staff

Min-Heap + global max tracking: Initialize heap with first element of each list. Track current_max. Pop min, update range [min, max] if better, push next from same list. Stop when any list exhausted.

Ugly Number II DP Three Pointers Python | Engineers of AI

Find nth ugly number using three pointers DP in O(n) or min-heap. Google and Amazon interview question.

Topics: heap, dynamic-programming, math

Companies: google, amazon, microsoft, bloomberg

Level: swe2, swe3

Dynamic Programming with three pointers: Maintain dp array and three pointers for factors 2, 3, 5. Each step, next ugly = min of the three candidates. Advance pointer(s) that produced the minimum.

Min-Heap: Use a min-heap initialized with 1. Pop the smallest, push its 2x, 3x, 5x multiples if not seen. Return after n pops.

Super Ugly Number DP Python | Engineers of AI

Find nth super ugly number with custom primes using k-pointer DP in O(nk). Google interview question.

Topics: heap, dynamic-programming, array

Companies: google, amazon

Level: swe3, senior

DP with k pointers: Generalize ugly number II: maintain one pointer per prime. At each step, next = min of dp[pointers[i]] * primes[i]. Advance all pointers that produced the min.

IPO Maximize Capital Two Heaps Python | Engineers of AI

Maximize capital for IPO using greedy two-heap approach. Hard Amazon and Google interview problem.

Topics: heap, greedy, sorting, two-heaps

Companies: amazon, google, microsoft

Level: swe3, senior

Two Heaps (min by capital + max by profit): Sort projects by capital into a min-heap. Maintain a max-heap of profits for affordable projects. For each of k rounds: push all affordable projects to max-heap, pop highest profit, add to w.

Furthest Building Reach Greedy Heap Python | Engineers of AI

Find furthest building using greedy ladder/bricks allocation with min-heap. Amazon and Google interview question.

Topics: heap, greedy, array

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Min-Heap for ladder climbs: Greedily allocate ladders to the largest climbs. Maintain a min-heap of size ladders tracking climbs assigned to ladders. When heap is full and new climb comes in, reassign the smallest ladder-climb to bricks if possible.

Single Threaded CPU Heap Simulation Python | Engineers of AI

Simulate single-threaded CPU task scheduling with min-heap in O(n log n). Amazon and Google interview question.

Topics: heap, sorting, array

Companies: amazon, google, microsoft, bloomberg

Level: swe3, senior

Min-Heap Simulation: Sort tasks by enqueue time. Simulate CPU: maintain current time and min-heap of (processing_time, index). At each step, push all tasks with enqueue_time <= current_time. Pop shortest, update current_time.

Skyline Problem Heap Python | Engineers of AI

Solve the skyline problem using event-based max-heap in O(n log n). Hard Google and Amazon interview problem.

Topics: heap, divide-and-conquer, sorting, binary-search

Companies: google, amazon, microsoft, bloomberg, apple

Level: senior, staff

Event-based Max-Heap: Create events: (x, -h) for start and (x, h) for end. Sort events (end before start at same x). Maintain a max-heap of active heights. When max height changes, add to result.

Employee Free Time Intervals Python | Engineers of AI

Find employee free time by merging intervals and detecting gaps. Hard Amazon, Google, Airbnb interview problem.

Topics: heap, interval, sorting, k-way-merge

Companies: amazon, google, bloomberg, airbnb

Level: swe3, senior

Flatten, Sort, Find Gaps: Collect all intervals from all employees, sort by start time. Merge overlapping intervals, then find gaps between consecutive merged intervals.

Minimum Cost Hire K Workers Python | Engineers of AI

Find minimum cost to hire k workers using ratio sort and max-heap. Hard Google interview problem.

Topics: heap, greedy, sorting, two-heaps

Companies: google, amazon, meta

Level: senior, staff

Sort by ratio + max-heap for quality sum: Sort workers by wage/quality ratio. For each worker as the "captain" (highest ratio), choose the k-1 workers with smallest quality from all those seen. Cost = ratio_captain * sum_of_k_qualities. Use max-heap to maintain k smallest qualities.

Seat Reservation Manager Min Heap Python | Engineers of AI

Design seat reservation system with min-heap for O(log n) reserve and unreserve. Amazon and Google interview design question.

Topics: heap, design

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Min-Heap: Initialize min-heap with all seat numbers. reserve() pops min. unreserve() pushes seat number back. Heap always gives smallest available seat.

Maximum Subsequence Score Greedy Heap Python | Engineers of AI

Maximize subsequence score (sum * min) using sort and min-heap in O(n log n). Amazon and Google interview question.

Topics: heap, greedy, sorting, array

Companies: amazon, google, meta

Level: swe3, senior

Sort by nums2 desc + min-heap: Sort pairs by nums2 descending. Maintain a min-heap of size k for nums1 values and their running sum. For each position (which fixes the min of nums2), compute score = sum * nums2[i].

Minimum Refueling Stops Greedy Heap Python | Engineers of AI

Find minimum refueling stops using greedy max-heap retroactive approach. Hard Amazon and Google interview problem.

Topics: heap, greedy, dynamic-programming, array

Companies: amazon, google, meta

Level: senior, staff

Greedy Max-Heap: Simulate driving. When stuck (fuel < 0 after reaching next position), retroactively refuel at the largest station seen so far (max-heap). Count refuels. If heap empty and still stuck, return -1.

Kth Smallest Prime Fraction Heap Python | Engineers of AI

Find kth smallest fraction from prime array using min-heap in O(k log n). Google and Amazon interview question.

Topics: heap, array, binary-search

Companies: google, amazon, meta

Level: swe3, senior

Min-Heap: Initialize min-heap with fractions arr[0]/arr[j] for each denominator j. Pop k times: each pop, if numerator index i+1 < j, push arr[i+1]/arr[j]. Return arr[i], arr[j] of the kth pop.

Minimize Deviation in Array Heap Python | Engineers of AI

Minimize array deviation using max-heap with multiply/divide operations. Hard Google interview problem.

Topics: heap, greedy, array

Companies: google, amazon, meta

Level: senior, staff

Max-Heap: Convert all odds to even (multiply by 2). Push to max-heap. Track min. Pop max: if even, divide by 2, push back; update min; compute max-min. Stop when max is odd (cannot divide further).

Maximum Performance of Team Heap Sort Python | Engineers of AI

Maximize team performance (speed sum * min efficiency) using sort and min-heap. Hard Google interview problem.

Topics: heap, greedy, sorting, array

Companies: google, amazon, meta, bloomberg

Level: senior, staff

Sort by efficiency + min-heap: Sort engineers by efficiency descending. For each as the minimum efficiency, pick k highest speeds from seen engineers (min-heap). Performance = speed_sum * efficiency.

Kth Largest in Stream Min Heap Python | Engineers of AI

Find kth largest element in data stream using min-heap of size k with O(log k) per insert. Amazon and Google interview.

Topics: heap, design, binary-search

Companies: amazon, google, microsoft, bloomberg

Level: new-grad, swe2

Min-Heap of size k: Maintain a min-heap of size k. The root is always the kth largest. On add, push val and pop if size > k. Return root.

Top K Frequent from Stream Design Python | Engineers of AI

Design streaming top-k frequent elements tracker using frequency map and heap. Amazon and Google interview design question.

Topics: heap, hash-map, design

Companies: amazon, google, twitter, bloomberg

Level: swe3, senior

HashMap + heapq.nlargest: Maintain a frequency counter. On each add, increment freq[num] and return heapq.nlargest(k) by frequency.

Process Tasks Using Servers Two Heaps Python | Engineers of AI

Assign tasks to servers greedily using two heaps (free and busy). Amazon and Google interview question.

Topics: heap, array, two-heaps

Companies: amazon, google, microsoft

Level: swe3, senior

Two Heaps (free + busy): Free heap: (weight, idx). Busy heap: (end_time, weight, idx). At time j (0-indexed task), move done servers to free. If no free server, advance time to next completion. Assign lightest free server.

Swim in Rising Water Dijkstra Binary Search Python | Engineers of AI

Find minimum time to swim across grid using Dijkstra min-heap or binary search BFS. Hard Google interview problem.

Topics: heap, graph, bfs, binary-search, union-find

Companies: google, amazon, meta, bloomberg

Level: senior, staff

Dijkstra / Min-Heap: Treat problem as finding path from (0,0) to (n-1,n-1) minimizing the maximum elevation encountered. Use Dijkstra with priority key = max(current_t, grid[r][c]).

Binary Search + BFS: Binary search on answer t (0..n^2-1). For each t, BFS/DFS checking if path exists from (0,0) to (n-1,n-1) using only cells with elevation <= t.

LRU Cache OrderedDict Python | Engineers of AI

Implement LRU cache with O(1) ops using OrderedDict and doubly linked list.

Topics: lru-cache, design-patterns, hash-map, collections

Companies: amazon, google, microsoft, meta, bloomberg

Level: swe2, swe3

OrderedDict: OrderedDict maintains order. move_to_end on access marks MRU. popitem(last=False) evicts LRU.

Doubly Linked List + HashMap: DLL for order, dict for O(1) access. head=LRU, tail=MRU. Remove and insert before tail on access.

LFU Cache O(1) Python Implementation | Engineers of AI

Implement Least Frequently Used cache with O(1) ops using two dicts and OrderedDict buckets.

Topics: lfu-cache, design-patterns, hash-map, collections

Companies: amazon, google, microsoft, meta

Level: swe3, senior

Two Dicts + Min Freq: key_val, key_freq dicts plus freq_keys (freq->OrderedDict). Track min_freq. On access increment freq, move to next bucket.

Thread-Safe Singleton Metaclass Python | Engineers of AI

Thread-safe Singleton using Python metaclass with locking. Advanced OOP interview question.

Topics: metaclasses, concurrency, design-patterns, oop

Companies: amazon, google, microsoft, meta

Level: swe3, senior

Metaclass with Lock: Override __call__ in metaclass. Lock prevents race condition. Class-keyed dict stores instances.

Observer Pattern Python OOP | Engineers of AI

Implement Observer pattern with abstract observers and stock price notification. Amazon Google OOP interview.

Topics: design-patterns, oop, object-design

Companies: amazon, google, microsoft, meta, bloomberg

Level: swe2, swe3

ABC Observer: Abstract Observer with update(). Subject provides subscribe/unsubscribe/notify. Concrete classes implement update().

Python Iterator Protocol __iter__ __next__ | Engineers of AI

Implement Python iterator protocol with custom Range, Flatten, and Chain iterators.

Topics: iterators, generators, oop, protocols

Companies: google, amazon, microsoft

Level: swe2, swe3

Iterator Protocol: __iter__ returns self. __next__ advances and raises StopIteration when done. Stack-based flatten.

Python Context Manager __enter__ __exit__ | Engineers of AI

Implement context managers with class protocol and @contextmanager decorator. Advanced Python interview.

Topics: context-managers, oop, exceptions, decorators

Companies: google, amazon, microsoft, meta

Level: swe2, swe3

Class and Decorator Context Managers: __enter__ sets up, __exit__ tears down. @contextmanager: yield splits setup/teardown.

Python Retry Decorator Exponential Backoff | Engineers of AI

Retry decorator with exponential backoff. Amazon Google Stripe interview question.

Topics: decorators, exceptions, closures, functools

Companies: amazon, google, microsoft, stripe, netflix

Level: swe2, swe3

Retry with Exponential Backoff: Loop up to max_attempts, catch specified exceptions, multiply delay. Re-raise on final failure.

Memoization Decorator LRU Python | Engineers of AI

Build memoize decorator with LRU eviction and cache statistics. Google Amazon Python interview.

Topics: decorators, memoization, closures, functools, dynamic-programming

Companies: google, amazon, microsoft, meta

Level: swe2, swe3

Memoize with LRU and Stats: OrderedDict cache keyed by (args, kwargs_tuple). move_to_end on hit, popitem on overflow. cache_info() reports stats.

Python flatten Generator Nested Lists | Engineers of AI

Flatten arbitrarily nested iterables with yield from recursive generator. Advanced Python interview.

Topics: generators, iterators, recursion, typing

Companies: google, amazon, microsoft

Level: swe2, swe3

Recursive Generator: yield from for sub-iterables. Exclude str/bytes to yield as atomic items.

Iterative Stack: Explicit iterator stack avoids recursion depth limits.

Python Lazy Property Descriptor | Engineers of AI

Implement lazy_property that caches on first access using non-data descriptor protocol.

Topics: descriptors, oop, decorators, caching

Companies: google, amazon, microsoft

Level: swe3, senior

Non-Data Descriptor: No __set__, so Python checks instance.__dict__ first. Store result there to bypass descriptor on next access.

Python Dataclass Validation __post_init__ | Engineers of AI

Typed dataclasses with runtime validation using __post_init__. Advanced Python interview.

Topics: dataclasses, typing, oop, descriptors

Companies: google, amazon, microsoft, stripe

Level: swe2, swe3

__post_init__ Validation: @dataclass with __post_init__ for validation. ClassVar for constraints. Custom validators per field.

Abstract Base Class Payment System Python | Engineers of AI

Payment processor ABC with CreditCard and PayPal implementations using template method.

Topics: abstract-classes, oop, design-patterns

Companies: stripe, paypal, amazon, google, visa

Level: swe2, swe3

ABC Payment Hierarchy: PaymentProcessor ABC with template method process(). Subclasses implement charge() and refund().

Python __getattr__ __setattr__ Tracking | Engineers of AI

Track attribute changes with __getattr__ and __setattr__. Advanced Python OOP interview.

Topics: descriptors, oop, metaclasses

Companies: google, amazon, microsoft

Level: swe3, senior

Attribute History Tracking: __setattr__ logs changes. object.__setattr__ for internal state avoids recursion. __getattr__ for missing attrs.

Python Protocol Comparable Structural Typing | Engineers of AI

Use typing.Protocol for Comparable interface with structural subtyping. Advanced Python interview.

Topics: protocols, typing, oop, abstract-classes

Companies: google, amazon, microsoft

Level: swe3, senior

Protocol with Generic Functions: Protocol defines interface via structural typing. Concrete classes need not inherit. Generic functions accept any Comparable.

Asyncio Producer Consumer Queue Python | Engineers of AI

Async producer-consumer with asyncio.Queue, backpressure, and graceful shutdown.

Topics: async-await, generators, concurrency

Companies: google, amazon, netflix, microsoft

Level: swe3, senior

asyncio Queue Pipeline: Producer puts items, sends None sentinel per consumer. Consumers loop until None. asyncio.gather runs all.

asyncio gather Semaphore Python | Engineers of AI

asyncio.gather with semaphore and timeout. Google Netflix async interview.

Topics: async-await, concurrency

Companies: google, amazon, netflix, stripe

Level: swe2, swe3

gather with Semaphore and Timeout: asyncio.gather runs concurrently. Semaphore limits parallelism. wait_for adds per-task timeout. return_exceptions avoids one failure killing all.

Token Bucket Rate Limiter Python | Engineers of AI

Thread-safe token bucket rate limiter with lazy refill. Amazon Google Stripe Cloudflare interview.

Topics: rate-limiting, design-patterns, system-design-coding, concurrency

Companies: amazon, google, stripe, cloudflare, netflix

Level: swe3, senior

Lazy Token Bucket: Lazily refill on consume based on elapsed time. Lock for thread safety. Optional blocking mode.

Python ThreadPoolExecutor concurrent.futures | Engineers of AI

Parallel task processing with ThreadPoolExecutor and progress tracking. Amazon Google interview.

Topics: concurrency, async-await, functools

Companies: amazon, google, microsoft, netflix

Level: swe2, swe3

ThreadPoolExecutor with Progress: Submit all tasks, use as_completed for progress, handle per-task exceptions, map for ordered results.

Custom defaultdict Python __missing__ | Engineers of AI

Implement defaultdict from scratch with __missing__. Classic Python OOP interview.

Topics: collections, oop, hash-map

Companies: google, amazon, microsoft

Level: new-grad, swe2

__missing__ Implementation: Inherit dict, override __missing__ to call default_factory and store result.

Trie Python Implementation with Autocomplete | Engineers of AI

Implement Trie with insert, search, autocomplete, delete. Amazon Google interview.

Topics: trie, oop, hash-map, string-matching

Companies: amazon, google, microsoft, meta, bloomberg

Level: swe2, swe3

Trie with Autocomplete: TrieNode with children dict and is_end. DFS for autocomplete. Recursive post-order delete.

Graph Class BFS DFS Topological Sort Python | Engineers of AI

Implement Graph with BFS, DFS, cycle detection, topological sort. Amazon Google interview.

Topics: graph, bfs, dfs, oop, topological-sort

Companies: amazon, google, microsoft, meta, bloomberg

Level: swe2, swe3

Graph with BFS DFS Topo Sort: BFS with deque. DFS recursive. Cycle detection via coloring. Topo sort via DFS post-order.

MinHeap from Scratch Python | Engineers of AI

Build MinHeap with insert, extract, build_heap. Amazon Google interview.

Topics: heap, array, oop

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Array-Based MinHeap: Append and sift up on insert. Swap root with last, pop, sift down on extract. Build by sifting down from n//2-1.

Circular Buffer Ring Buffer Python | Engineers of AI

Fixed-size circular buffer with head/tail pointers and overwrite mode.

Topics: array, design-patterns, queue, system-design-coding

Companies: amazon, google, microsoft, nvidia, bloomberg

Level: swe2, swe3

Head/Tail Pointer Buffer: Fixed array with head and tail. count tracks size. Modular arithmetic for wrap-around.

Bloom Filter Python Implementation | Engineers of AI

Bloom filter with optimal bit array and double hashing. Google Databricks Cloudflare interview.

Topics: hash-map, bit-manipulation, system-design-coding

Companies: google, amazon, databricks, cloudflare, netflix

Level: swe3, senior, staff

Double Hashing Bloom Filter: bytearray as bit array. Two base hashes (MD5, SHA1) derive k positions. Optimal m and k from n and p.

Consistent Hash Ring Python | Engineers of AI

Implement consistent hashing with virtual nodes. Amazon Google Netflix distributed systems interview.

Topics: hash-map, system-design-coding, design-patterns, sorting

Companies: amazon, google, databricks, netflix, cloudflare, uber

Level: swe3, senior, staff

Virtual Node Hash Ring: Hash each node v times onto ring (sorted list). Key lookup: hash key, bisect for successor node.

Design LRU Cache O(1) Python | Engineers of AI

LRU cache design with O(1) get/put using OrderedDict. Classic Amazon Google system design coding.

Topics: lru-cache, system-design-coding, hash-map, design-patterns

Companies: amazon, google, microsoft, meta, bloomberg

Level: swe2, swe3

OrderedDict O(1): OrderedDict preserves insertion order. move_to_end marks MRU. popitem(last=False) evicts LRU.

Design LFU Cache Python O(1) | Engineers of AI

LFU cache with O(1) ops using frequency buckets. Hard Amazon Google interview.

Topics: lfu-cache, system-design-coding, hash-map, design-patterns

Companies: amazon, google, microsoft, meta

Level: swe3, senior

Freq Bucket + Min Freq Tracking: Three dicts: key->val, key->freq, freq->OrderedDict(keys). min_freq for O(1) eviction.

Design Hit Counter Last 5 Minutes Python | Engineers of AI

Hit counter counting requests in last 300 seconds. Deque and circular array approaches. Amazon Google interview.

Topics: system-design-coding, queue, design-patterns, sliding-window

Companies: amazon, google, microsoft, bloomberg, dropbox

Level: swe2, swe3

Deque Sliding Window: Deque stores hit timestamps. getHits pops timestamps older than 5 minutes.

Circular Array O(1): Fixed array of 300 (seconds, count) pairs. Index by timestamp%300. Reset stale buckets.

Design Rate Limiter Sliding Window Python | Engineers of AI

Rate limiter with sliding window per user. Amazon Google Stripe Cloudflare interview.

Topics: rate-limiting, system-design-coding, sliding-window, design-patterns

Companies: amazon, google, stripe, cloudflare, netflix

Level: swe3, senior

Sliding Window Counter: Per-user deque of timestamps. Pop stale, check count, append if allowed.

Fixed Window Counter (simpler): Track (window_start, count) per user. Reset on new window.

Design Twitter Post Tweet News Feed Python | Engineers of AI

Twitter design with heap-based k-way merge for news feed. Amazon Meta Google system design coding.

Topics: system-design-coding, heap, hash-map, design-patterns

Companies: twitter, meta, amazon, google, linkedin

Level: swe2, swe3

Heap K-Way Merge: Each user has tweet list. getNewsFeed heap-merges followees tweets, returns top 10. Global timestamp orders tweets.

Design File System In-Memory Python | Engineers of AI

In-memory file system with mkdir, ls, addFile using trie. Amazon Google Dropbox interview.

Topics: trie, system-design-coding, hash-map, design-patterns

Companies: amazon, google, microsoft, dropbox

Level: swe2, swe3

Trie Node File System: Each node is a dir or file with children dict and content. Path segments traverse the trie.

Key-Value Store with TTL Python | Engineers of AI

In-memory KV store with TTL expiry and lazy deletion. Amazon Redis Google interview.

Topics: system-design-coding, hash-map, design-patterns, caching

Companies: amazon, google, microsoft, redis, stripe

Level: swe2, swe3

Lazy Expiration + Background Cleanup: Store (value, expiry). get checks expiry and deletes if stale. Optional background thread purges periodically.

Design In-Memory Database Python | Engineers of AI

In-memory DB with set/get/scan and transaction support. Amazon Snowflake Databricks interview.

Topics: system-design-coding, hash-map, sorting, design-patterns

Companies: amazon, google, microsoft, snowflake, databricks

Level: swe3, senior

In-Memory DB with Transactions: Nested defaultdict for storage. Sorted scan with prefix filter. Transaction stack stores undo log.

Design URL Shortener Python Base62 | Engineers of AI

URL shortener with base62 encoding, custom aliases, expiry, and click tracking.

Topics: system-design-coding, hash-map, design-patterns

Companies: amazon, google, microsoft, twitter, bitly

Level: swe2, swe3

Counter + Base62 Encoding: Increment counter, encode to base62 for short key. Two dicts: short->url and url->short for dedup. Track clicks and expiry.

Design Leaderboard Top K Python | Engineers of AI

Leaderboard with addScore, top K, reset using heap. Amazon Google interview.

Topics: system-design-coding, heap, sorting, hash-map

Companies: amazon, google, microsoft, gaming-companies

Level: swe2, swe3

HashMap + heapq.nlargest: Store scores in dict. top(K) uses heapq.nlargest O(n log K).

Design Parking Lot OOP Python | Engineers of AI

Parking lot OOP design with vehicles, spots, tickets and fee calculation. Amazon Google Uber interview.

Topics: system-design-coding, object-design, oop, design-patterns

Companies: amazon, google, microsoft, uber, bloomberg

Level: swe2, swe3

OOP Parking Lot System: Vehicle, Spot, Floor, ParkingLot, Ticket classes. park() finds first compatible spot. leave() calculates fee by time.

Vending Machine State Pattern Python | Engineers of AI

Vending machine using State design pattern. Amazon Google OOP system design interview.

Topics: system-design-coding, object-design, oop, design-patterns

Companies: amazon, google, microsoft

Level: swe2, swe3

State Pattern Vending Machine: VendingMachine holds state. Each State subclass implements transitions. Invalid ops raise in each state.

Design Elevator System SCAN Algorithm Python | Engineers of AI

Multi-elevator system with SCAN scheduling algorithm. Amazon Google senior engineer interview.

Topics: system-design-coding, object-design, oop, design-patterns, sorting

Companies: amazon, google, microsoft, bloomberg

Level: swe3, senior

SCAN Algorithm Multi-Elevator: Each Elevator has current floor, direction, and sorted queues for up/down. Assign request to nearest elevator. SCAN sweeps then reverses.

Library Management System OOP Python | Engineers of AI

Library management with checkout, return, reservations, and fines. Amazon Microsoft OOP interview.

Topics: system-design-coding, object-design, oop

Companies: amazon, microsoft, google, bloomberg

Level: swe2, swe3

Library OOP Design: Book, BookCopy, Member, Library classes. Checkout assigns available copy. Return calculates fine. Reservation queue notifies next member.

Restaurant Reservation System Python OOP | Engineers of AI

Restaurant table reservation with interval overlap detection. Amazon Airbnb Uber interview.

Topics: system-design-coding, object-design, oop, interval

Companies: amazon, google, uber, airbnb

Level: swe2, swe3

Interval Overlap Reservation: Per-table reservation list. Check overlap with each existing reservation. Find smallest capacity >= party_size.

Movie Ticket Booking System Python OOP | Engineers of AI

Thread-safe movie booking with seat locking and confirmation. Amazon Netflix interview.

Topics: system-design-coding, object-design, oop, concurrency

Companies: amazon, google, netflix, uber

Level: swe2, swe3

Thread-Safe Movie Booking: Seat has status, lock, expiry. bookSeat atomically checks and locks. Payment confirms. Cancel releases.

Design Chat System Python OOP | Engineers of AI

Chat system with 1:1 and group messaging OOP design. Meta Discord Amazon interview.

Topics: system-design-coding, object-design, oop, design-patterns

Companies: meta, amazon, google, discord, slack

Level: swe2, swe3

Chat System OOP: Conversation keyed by sorted user pair. Group has member set and message list. Unread counter per user-conversation.

Autocomplete System Trie Python | Engineers of AI

Autocomplete with trie and frequency tracking. Top 3 results by frequency. Amazon Google interview.

Topics: trie, system-design-coding, heap, string-matching

Companies: amazon, google, microsoft, meta, linkedin

Level: swe2, swe3

Trie with Frequency Tracking: Trie with freq dict at each end node. On input: walk trie to current node, DFS for all sentences, return top 3 by (-freq, text).

Log Aggregator K-Way Merge Python | Engineers of AI

Merge K sorted log streams with heap-based k-way merge. Amazon Datadog interview.

Topics: system-design-coding, heap, k-way-merge, sorting

Companies: amazon, google, datadog, splunk, cloudflare

Level: swe3, senior

K-Way Merge with Heap: Per-stream sorted list. Merge query: push first log of each stream, pop-min into result, push next from same stream.

Priority Task Scheduler Python | Engineers of AI

Task scheduler with priority heap and thread workers. Amazon Google Airflow interview.

Topics: system-design-coding, heap, design-patterns, concurrency

Companies: amazon, google, microsoft, celery, airflow

Level: swe2, swe3

Priority Heap Scheduler: Min-heap with (-priority, ready_time, id, func). Worker thread pops when ready_time <= now. ThreadPoolExecutor for concurrent execution.

Design Pub/Sub Message Queue Python | Engineers of AI

In-memory pub/sub with async delivery and worker threads. Amazon Kafka Google interview.

Topics: system-design-coding, design-patterns, concurrency, object-design

Companies: amazon, google, meta, kafka, stripe

Level: swe3, senior

Async Pub/Sub with Worker Threads: Per-subscriber Queue. Dedicated worker thread per subscriber drains queue. publish enqueues to all subscribers.

Event Sourcing System Python | Engineers of AI

Implement event sourcing with append-only log, snapshots, and state replay. Amazon Stripe Netflix interview.

Topics: system-design-coding, design-patterns, object-design, caching

Companies: amazon, google, stripe, netflix, databricks

Level: swe3, senior, staff

Event Store with Snapshots: Append-only event list. Reducer function applies each event to state. Snapshots checkpoint state. Replay from latest snapshot + subsequent events.

Circuit Breaker Pattern Python | Engineers of AI

Thread-safe circuit breaker with CLOSED/OPEN/HALF_OPEN states. Amazon Netflix Google interview.

Topics: system-design-coding, design-patterns, concurrency, rate-limiting

Companies: amazon, google, netflix, stripe, uber

Level: swe3, senior

Thread-Safe Circuit Breaker: State machine with CLOSED/OPEN/HALF_OPEN. Failure threshold opens circuit. Timeout allows HALF_OPEN test. Success closes circuit.

API Gateway Design Python Middleware | Engineers of AI

API gateway with middleware pipeline: auth, rate limiting, caching, routing. Amazon Netflix senior interview.

Topics: system-design-coding, design-patterns, rate-limiting, caching

Companies: amazon, google, netflix, cloudflare, stripe

Level: senior, staff

Middleware Pipeline API Gateway: Chain of middleware: auth -> rate limit -> cache -> route -> backend. Each middleware calls next() or returns early. Route registry maps path to handler.

Search Suggestions Trie Binary Search Python | Engineers of AI

Product search suggestions with sorted list and binary search. Amazon Google LinkedIn interview.

Topics: trie, system-design-coding, string-matching, sorting

Companies: amazon, google, microsoft, linkedin, meta

Level: swe2, swe3

Sorted List + Binary Search: Sort products. For each prefix, bisect to find start, take up to 3 matching products.

Rabin-Karp Rolling Hash Python | Engineers of AI

Implement Rabin-Karp string search with rolling hash. Polynomial hashing and collision handling. Google interview.

Topics: string, hash-table

Companies: google, facebook, microsoft

Level: senior, staff

Rolling Hash: Compute hash of pattern and rolling hash of each text window. On hash match, verify character by character.

Z-Algorithm Pattern Matching Python | Engineers of AI

Implement Z-algorithm for string matching and Z-array construction in O(n). Google Amazon senior interview.

Topics: string, two-pointers

Companies: google, amazon

Level: senior, staff

Z-Array Construction: Maintain a Z-box [L, R]. For each position, reuse previous results where possible.

Longest Palindromic Substring Manacher's Python | Engineers of AI

Find longest palindromic substring using Manacher's O(n) algorithm and expand-around-center. Amazon Google interview.

Topics: string, dynamic-programming

Companies: amazon, google, microsoft, apple

Level: senior, staff

Manacher's Algorithm O(n): Transform string with separators, then use Manacher's to find palindrome radii in linear time.

Expand Around Center O(n^2): For each center (including between characters), expand outward while palindrome holds.

Palindrome Partitioning Backtracking Python | Engineers of AI

Partition string into all palindrome substrings using backtracking and DP. Amazon Google interview.

Topics: backtracking, dynamic-programming, string

Companies: amazon, google, facebook

Level: swe2, senior

Backtracking with DP Palindrome Check: Use DP to precompute is_palindrome[i][j], then backtrack adding valid palindrome prefixes.

Merge Intervals - Python Solution | EngineersOfAI

Solve Merge Intervals in Python with sorting and greedy merge. O(n log n) time complexity with detailed explanation.

Topics: array, sorting, interval

Companies: google, amazon, microsoft, facebook, bloomberg

Level: new-grad, swe2, swe3

Sort and Merge: Sort intervals by start. Iterate and merge when current start <= last merged end.

Insert Interval - Python Solution | EngineersOfAI

Insert and merge an interval into a sorted non-overlapping interval list in O(n) time using linear scan.

Topics: array, interval

Companies: google, amazon, linkedin, microsoft

Level: new-grad, swe2, swe3

Linear Scan: Three-phase linear scan: add non-overlapping before, merge overlapping, add remaining.

Non-overlapping Intervals - Python Greedy | EngineersOfAI

Find minimum intervals to remove to make rest non-overlapping using greedy sort by end time in O(n log n).

Topics: array, sorting, interval, greedy

Companies: google, amazon, microsoft

Level: swe2, swe3

Greedy - Sort by End: Sort by end time. Greedily select intervals with earliest end. Count removed = total - kept.

Meeting Rooms I - Python Solution | EngineersOfAI

Determine if a person can attend all meetings with no overlaps using sorting in O(n log n) time.

Topics: array, sorting, interval

Companies: amazon, microsoft, bloomberg, facebook

Level: new-grad, swe2

Sort and Check: Sort by start. If any meeting starts before previous ends, return False.

Meeting Rooms II - Python Min-Heap Solution | EngineersOfAI

Find minimum conference rooms needed using min-heap or two sorted arrays approach in O(n log n) time.

Topics: array, sorting, interval, heap, two-pointers

Companies: amazon, google, microsoft, bloomberg, uber, facebook

Level: swe2, swe3, senior

Min-Heap: Sort by start. Min-heap tracks earliest ending room. Reuse room if it ends before new meeting starts.

Two Sorted Arrays: Separate start and end times sorted. Use two pointers to track concurrent meetings.

Employee Free Time - Python Solution | EngineersOfAI

Find common free time for all employees by flattening, sorting, merging intervals and finding gaps.

Topics: array, sorting, interval, heap

Companies: google, amazon, uber, airbnb

Level: swe3, senior, staff

Flatten Sort and Find Gaps: Flatten all intervals, sort by start, merge overlapping, then collect gaps between merged intervals.

Interval List Intersections - Python Two Pointers | EngineersOfAI

Find intersections of two sorted interval lists using two pointers in O(m+n) time.

Topics: array, two-pointers, interval

Companies: facebook, google, amazon, linkedin

Level: swe2, swe3

Two Pointers: Two pointers. Intersection = [max(starts), min(ends)]. Advance pointer with smaller end.

Remove Covered Intervals - Python Sorting | EngineersOfAI

Count remaining intervals after removing covered ones using sorting in O(n log n) time.

Topics: array, sorting, interval, greedy

Companies: amazon, google

Level: swe2, swe3

Sort and Track Max End: Sort by start asc, end desc. An interval is not covered if its end exceeds max end seen so far.

Video Stitching - Python Greedy Solution | EngineersOfAI

Find minimum video clips to cover event duration using greedy interval jumping in O(n log n) time.

Topics: array, interval, greedy, dynamic-programming

Companies: google, amazon

Level: swe3, senior

Greedy Jump: Greedy: sort clips. At each position extend as far as possible with available clips. Count jumps.

Minimum Arrows to Burst Balloons - Python Greedy | EngineersOfAI

Find minimum arrows to burst all balloons using greedy sort by end time in O(n log n) time.

Topics: array, sorting, interval, greedy

Companies: amazon, google, microsoft

Level: swe2, swe3

Greedy Sort by End: Sort by end. Shoot at current balloon end. New arrow only when next start > current arrow pos.

My Calendar I - Python Binary Search | EngineersOfAI

Implement a calendar booking system without double bookings using binary search in O(n) per operation.

Topics: array, binary-search, interval, design-patterns

Companies: google, amazon, microsoft

Level: swe2, swe3

Binary Search with SortedList: Maintain sorted list of events. Use bisect to find insertion point and check neighbors for overlap.

My Calendar II - Python Double Booking | EngineersOfAI

Implement calendar with at most double bookings using two interval lists to track overlaps.

Topics: array, binary-search, interval, design-patterns

Companies: google, amazon

Level: swe3, senior

Two Lists: Singles and Doubles: Maintain two lists: single bookings and double bookings. Reject if triple booking would occur.

My Calendar III - Python Difference Array | EngineersOfAI

Track maximum k-booking using difference array with sorted dict in O(n) per booking.

Topics: interval, segment-tree, design-patterns, binary-search

Companies: google, amazon

Level: senior, staff

Difference Array with Sorted Dict: Difference array approach: +1 at start, -1 at end. Prefix sum gives concurrent events at any point.

Data Stream as Disjoint Intervals - Python | EngineersOfAI

Summarize a data stream as disjoint intervals with efficient merge operations.

Topics: interval, binary-search, design-patterns, sorted-list

Companies: google, amazon, stripe

Level: senior, staff

Sorted List with Merge: Maintain sorted disjoint intervals. On addNum, find and merge all touching/overlapping intervals.

Range Module - Python Interval Design | EngineersOfAI

Implement a Range Module tracking number ranges with add, remove, and query operations on intervals.

Topics: interval, segment-tree, design-patterns, binary-search

Companies: google, amazon, stripe

Level: senior, staff

Sorted Intervals List: Maintain sorted disjoint intervals. Add merges overlapping, remove splits overlapping intervals.

Count of Range Sum - Python Merge Sort | EngineersOfAI

Count range sums within bounds using merge sort on prefix sums in O(n log^2 n) time.

Topics: array, prefix-sum, divide-and-conquer, binary-search, sorting

Companies: google, amazon, jane-street

Level: senior, staff

Merge Sort on Prefix Sums: Build prefix sums. Use merge sort to count pairs (i,j) where prefix[j]-prefix[i] in [lower,upper].

Falling Squares - Python Interval Heights | EngineersOfAI

Simulate falling squares and compute maximum height after each drop using interval overlap detection.

Topics: array, interval, segment-tree, sorting

Companies: google, amazon

Level: senior, staff

Brute Force with Interval Heights: For each square, find max height of overlapping previous squares. New height = base + size.

Rectangle Area II - Python Sweep Line | EngineersOfAI

Compute total area covered by overlapping rectangles using sweep line with coordinate compression.

Topics: array, interval, segment-tree, sorting, prefix-sum

Companies: google, amazon, jane-street

Level: senior, staff

Coordinate Compression + Sweep Line: Sweep line on x-axis with coordinate-compressed y-axis. Track active y segments to compute covered length.

Minimum Interval to Include Each Query - Python Heap | EngineersOfAI

Find smallest interval containing each query using sort and min-heap in O((n+q) log n) time.

Topics: array, sorting, interval, heap, binary-search

Companies: google, amazon, stripe

Level: senior, staff

Sort + Min-Heap: Sort intervals by start, queries by value. Sweep with min-heap of active intervals keyed by size.

Number of Flowers in Full Bloom - Python Binary Search | EngineersOfAI

Count flowers blooming at each arrival time using binary search on sorted start and end arrays.

Topics: array, sorting, binary-search, interval, prefix-sum

Companies: google, amazon, databricks

Level: swe3, senior

Binary Search on Sorted Start/End: Sort starts and ends separately. For each person: blooming = #started_by_t - #ended_before_t.

Find Right Interval - Python Binary Search | EngineersOfAI

Find the smallest starting interval >= each interval end using binary search in O(n log n) time.

Topics: array, binary-search, interval, sorting

Companies: amazon, google

Level: swe2, swe3

Binary Search on Sorted Starts: Sort (start, index) pairs. For each interval end, binary search in sorted starts for >= end.

Partition Labels - Python Greedy Solution | EngineersOfAI

Partition string into maximum parts where each letter appears in one part using greedy last-occurrence approach.

Topics: string, greedy, interval, two-pointers

Companies: amazon, google, facebook, microsoft

Level: swe2, swe3

Last Occurrence Greedy: Track last index of each char. Expand current partition until current index equals partition end.

Task Scheduler - Python Greedy & Math | EngineersOfAI

Find minimum CPU intervals for task scheduling with cooldown using math formula or max-heap simulation.

Topics: array, greedy, heap, interval, sorting

Companies: amazon, google, facebook, microsoft, bloomberg

Level: swe2, swe3, senior

Math Formula: Math: answer = max(total_tasks, (max_freq-1)*(n+1)+count_of_max_freq_tasks)

Greedy with Max-Heap: Max-heap simulation: each cycle of n+1 slots, execute most frequent tasks.

Car Fleet - Python Monotonic Stack Solution | EngineersOfAI

Count car fleets arriving at destination by sorting by position and using a monotonic stack approach.

Topics: array, sorting, monotonic-stack, interval

Companies: amazon, google, microsoft

Level: swe2, swe3

Sort by Position Descending + Stack: Sort by position desc. A car joins fleet ahead if its arrival time <= fleet in front. Use stack.

Jump Game VII - Python Prefix Sum | EngineersOfAI

Determine reachability in Jump Game VII using prefix sum of reachable positions in O(n) time.

Topics: string, bfs, prefix-sum, sliding-window, interval

Companies: amazon, google

Level: swe3, senior

Prefix Sum BFS: Prefix sum of reachable positions. Position j reachable if any position in [j-maxJump, j-minJump] is reachable.

Koko Eating Bananas - Python Binary Search | EngineersOfAI

Find minimum eating speed using binary search on the answer in O(n log m) time.

Topics: array, binary-search

Companies: amazon, google, facebook, uber

Level: swe2, swe3

Binary Search on Speed: Binary search on eating speed. Feasibility check: sum of ceil(pile/k) for all piles <= h.

Capacity to Ship Packages Within D Days - Python Binary Search | EngineersOfAI

Find minimum ship capacity to deliver all packages within D days using binary search on the answer.

Topics: array, binary-search

Companies: amazon, google, facebook

Level: swe2, swe3

Binary Search on Capacity: Binary search on capacity in range [max(w), sum(w)]. Greedy check if packages can be shipped in D days.

Minimum Days to Make m Bouquets - Python Binary Search | EngineersOfAI

Find minimum days to form m bouquets of k adjacent flowers using binary search in O(n log max_day).

Topics: array, binary-search

Companies: amazon, google, bloomberg

Level: swe2, swe3

Binary Search on Days: Binary search on the day. Feasibility: greedily count consecutive bloomed flowers forming bouquets.

Split Array Largest Sum - Python Binary Search | EngineersOfAI

Minimize the largest subarray sum when splitting into k parts using binary search on the answer.

Topics: array, binary-search, dynamic-programming, greedy

Companies: google, amazon, facebook, bloomberg

Level: swe3, senior

Binary Search on Answer: Binary search on the max subarray sum. Greedily count splits needed for a given max sum.

Magnetic Force Between Two Balls - Python Binary Search | EngineersOfAI

Maximize minimum distance between balls using binary search on the answer after sorting positions.

Topics: array, binary-search, sorting

Companies: amazon, google, airbnb

Level: swe3, senior

Binary Search on Minimum Distance: Sort positions. Binary search on min distance. Greedy feasibility: place balls maximizing spacing.

Find in Mountain Array - Python Binary Search | EngineersOfAI

Find target in mountain array using three binary searches: find peak, search ascending, search descending.

Topics: array, binary-search, divide-and-conquer

Companies: google, amazon, facebook

Level: swe3, senior

Three Binary Searches: Three binary searches: find peak, search ascending left half, search descending right half.

Search in Rotated Sorted Array II - Python | EngineersOfAI

Search for a target in rotated sorted array with duplicates using modified binary search.

Topics: array, binary-search

Companies: amazon, google, microsoft, facebook

Level: swe2, swe3

Binary Search with Duplicate Handling: Binary search. When lo==mid, advance lo. Otherwise determine sorted half and prune.

Find the Duplicate Number - Python Floyd Cycle | EngineersOfAI

Find the duplicate number in O(n) time O(1) space using Floyd's cycle detection algorithm.

Topics: array, two-pointers, binary-search, bit-manipulation

Companies: amazon, google, facebook, microsoft, bloomberg

Level: swe2, swe3

Floyd's Cycle Detection: Model array as linked list (index->value). Duplicate creates cycle. Floyd's algorithm finds cycle entry.

First Bad Version - Python Binary Search | EngineersOfAI

Find the first bad version using binary search to minimize API calls in O(log n) time.

Topics: binary-search

Companies: amazon, facebook, microsoft, linkedin

Level: new-grad, swe2

Binary Search: Standard binary search. Converge lo and hi to the leftmost bad version.

Find Smallest Letter Greater Than Target - Python | EngineersOfAI

Find next greatest letter in circular sorted array using binary search in O(log n) time.

Topics: array, binary-search

Companies: amazon, google

Level: new-grad, swe2

Binary Search: bisect_right finds first position after target. Modulo handles wraparound.

Count Negative Numbers in Sorted Matrix - Python | EngineersOfAI

Count negatives in row/column sorted matrix using staircase traversal in O(m+n) time.

Topics: array, binary-search, matrix

Companies: amazon, google, microsoft

Level: new-grad, swe2

Staircase from Top-Right: Start top-right. Negative -> count remaining rows, move left. Non-negative -> move down.

Kth Smallest Element in Sorted Matrix - Python Binary Search | EngineersOfAI

Find kth smallest element in sorted matrix using binary search on value with staircase count.

Topics: matrix, binary-search, heap, sorting

Companies: amazon, google, facebook, microsoft

Level: swe2, swe3

Binary Search on Value: Binary search on value range. Count elements <= mid using staircase. Converge to kth smallest.

Find Kth Smallest Pair Distance - Python Binary Search | EngineersOfAI

Find kth smallest pairwise distance using binary search on distance with sliding window count.

Topics: array, binary-search, sorting, two-pointers

Companies: google, amazon, stripe

Level: senior, staff

Binary Search + Sliding Window: Sort array. Binary search on distance value. Count pairs with distance <= mid using sliding window.

Kth Smallest in Multiplication Table - Python Binary Search | EngineersOfAI

Find kth smallest in m x n multiplication table using binary search with O(m log mn) complexity.

Topics: binary-search, math

Companies: google, amazon, jane-street

Level: senior, staff

Binary Search on Value: Binary search on value. Count(x) = sum(min(x//i, n) for i in 1..m). Find smallest value with count >= k.

Random Pick with Weight - Python Binary Search | EngineersOfAI

Implement weighted random selection using prefix sum and binary search in O(log n) per pick.

Topics: array, binary-search, prefix-sum, math

Companies: google, amazon, facebook, uber, airbnb

Level: swe2, swe3

Prefix Sum + Binary Search: Build prefix sums. Random int in [1, total]. Binary search prefix array to find weighted index.

Time Based Key-Value Store - Python Binary Search Design | EngineersOfAI

Design a time-based key-value store with O(log n) get using HashMap and binary search.

Topics: hash-map, binary-search, design-patterns

Companies: google, amazon, facebook, stripe, uber

Level: swe2, swe3

HashMap + Binary Search: HashMap of sorted (timestamp, value) lists. Binary search for largest timestamp <= query.

Online Election - Python Binary Search | EngineersOfAI

Precompute election leaders at each timestamp and answer queries with binary search in O(log n).

Topics: array, binary-search, hash-map

Companies: google, amazon

Level: swe3, senior

Precompute + Binary Search: Precompute leader at each timestamp. For query t, binary search for latest vote time <= t.

Peak Index in Mountain Array - Python Binary Search | EngineersOfAI

Find peak index in mountain array using binary search on slope direction in O(log n) time.

Topics: array, binary-search

Companies: amazon, google, microsoft

Level: new-grad, swe2

Binary Search: Binary search. If arr[mid] < arr[mid+1], rising slope so peak is right. Else peak is left.

Search a 2D Matrix II - Python Staircase | EngineersOfAI

Search sorted 2D matrix using staircase approach from top-right corner in O(m+n) time.

Topics: array, binary-search, matrix, divide-and-conquer

Companies: amazon, google, facebook, microsoft, bloomberg

Level: swe2, swe3

Staircase Search from Top-Right: Start top-right. Value > target: move left (eliminate column). Value < target: move down (eliminate row).

Sqrt(x) - Python Binary Search | EngineersOfAI

Compute integer square root using binary search without built-in sqrt in O(log x) time.

Topics: math, binary-search

Companies: amazon, google, microsoft, bloomberg

Level: new-grad, swe2

Binary Search: Binary search in [1, x//2]. When lo > hi, hi is floor(sqrt(x)).

H-Index II - Python Binary Search | EngineersOfAI

Find H-Index from sorted citations array using binary search in O(log n) time.

Topics: array, binary-search

Companies: facebook, google, amazon

Level: swe2, swe3

Binary Search: Binary search on h. Check if citations[n-h] >= h (at least h papers with >= h citations).

Minimum Speed to Arrive on Time - Python Binary Search | EngineersOfAI

Find minimum train speed to arrive on time using binary search on speed in O(n log max) time.

Topics: array, binary-search

Companies: amazon, google, uber

Level: swe2, swe3

Binary Search on Speed: Binary search on speed. Sum ceiling times for all but last train plus actual last train time.

Minimum Time to Complete Trips - Python Binary Search | EngineersOfAI

Find minimum time for buses to complete totalTrips using binary search on time value.

Topics: array, binary-search

Companies: amazon, google, leetcode

Level: swe2, swe3

Binary Search on Time: Binary search on total time. Feasibility: sum of t//time[i] for all buses >= totalTrips.

Maximum Candies Allocated to K Children - Python Binary Search | EngineersOfAI

Maximize candies per child by binary searching on candy count with pile splitting feasibility check.

Topics: array, binary-search

Companies: amazon, google

Level: swe2, swe3

Binary Search on Candy Count: Binary search on candy count m. Feasibility: sum(c//m for c in candies) >= k children.

Minimum Limit of Balls in a Bag - Python Binary Search | EngineersOfAI

Minimize maximum bag size after splitting with limited operations using binary search on the answer.

Topics: array, binary-search

Companies: amazon, google, facebook

Level: swe2, swe3

Binary Search on Max Size: Binary search on max bag size. Operations needed for bag n with limit m: ceil(n/m) - 1.

Binary Tree Maximum Path Sum - Python DFS | EngineersOfAI

Find maximum path sum in binary tree using DFS with global max tracking in O(n) time.

Topics: binary-tree, dfs, dynamic-programming, recursion

Companies: amazon, google, facebook, microsoft, bloomberg

Level: swe3, senior

DFS with Global Max: DFS returns max one-sided path sum. At each node compute full path sum and update global max.

Binary Tree Cameras - Python Greedy DFS | EngineersOfAI

Place minimum cameras in binary tree using greedy post-order DFS with three-state node classification.

Topics: binary-tree, dfs, greedy, dynamic-programming

Companies: google, amazon, facebook

Level: senior, staff

Greedy DFS: Post-order DFS. Place camera when child is uncovered. Greedy: place cameras as high as possible.

Distribute Coins in Binary Tree - Python DFS | EngineersOfAI

Find minimum coin moves in binary tree using DFS excess calculation in O(n) time.

Topics: binary-tree, dfs, recursion

Companies: amazon, google, facebook

Level: swe3, senior

DFS Excess Calculation: DFS returns excess coins. Each edge move = |excess|. Total moves = sum of excess over all subtrees.

Maximum Width of Binary Tree - Python BFS | EngineersOfAI

Find maximum width of binary tree using BFS with position indices and normalization in O(n).

Topics: binary-tree, bfs, dfs

Companies: amazon, google, facebook

Level: swe2, swe3

BFS with Index Normalization: BFS with node position indices. Left child = 2*i, right child = 2*i+1. Normalize to prevent overflow.

Count Complete Tree Nodes - Python O(log^2 n) | EngineersOfAI

Count nodes in complete binary tree in O(log^2 n) by comparing heights to detect perfect subtrees.

Topics: binary-tree, binary-search, dfs

Companies: amazon, google, microsoft

Level: swe2, swe3

Binary Search on Height: Compare left-spine and right-spine heights. If equal: perfect subtree. Else recurse both sides.

Sum Root to Leaf Numbers - Python DFS | EngineersOfAI

Sum all root-to-leaf numbers in binary tree using DFS with running number accumulation.

Topics: binary-tree, dfs, recursion

Companies: amazon, google, facebook, microsoft

Level: swe2, swe3

DFS with Running Number: DFS with running number. At each node: cur = cur*10 + val. Return cur at leaves, sum of children otherwise.

Path Sum III - Python Prefix Sum Hash Map | EngineersOfAI

Count paths with target sum using DFS with prefix sum hash map in O(n) time.

Topics: binary-tree, dfs, prefix-sum, hash-map

Companies: amazon, google, facebook, microsoft

Level: swe2, swe3

Prefix Sum Hash Map: DFS with prefix sum hash map. At each node, check if (cur_sum - target) exists in map. Backtrack on exit.

Flatten Binary Tree to Linked List - Python O(1) Space | EngineersOfAI

Flatten binary tree to linked list in-place using Morris traversal approach in O(n) O(1) space.

Topics: binary-tree, dfs, recursion, linked-list

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Iterative with Stack: Morris-style: for each node with left, find rightmost of left subtree, connect to right, move left to right.

Binary Tree Right Side View - Python BFS | EngineersOfAI

Get right side view of binary tree using BFS level order traversal taking last node per level.

Topics: binary-tree, bfs, dfs

Companies: amazon, facebook, google, microsoft, bloomberg

Level: swe2, swe3

BFS Level Order: BFS level by level. Take the last node value at each level as the right-side visible node.

Find Duplicate Subtrees - Python Serialization | EngineersOfAI

Find all duplicate subtrees by serializing each subtree and counting occurrences with a hash map.

Topics: binary-tree, dfs, hash-map, serialization

Companies: amazon, google, facebook

Level: swe2, swe3

Post-order Serialization: Post-order DFS serializes each subtree. Hash map counts occurrences; collect on second occurrence.

LRU Cache Python - O(1) OrderedDict & Doubly Linked List Solution

Implement LRU Cache in Python with O(1) get and put using OrderedDict or a doubly linked list + hash map. Includes full solutions with test cases.

Topics: design-patterns, hash-map, linked-list, caching

Companies: amazon, google, meta, microsoft, uber, bloomberg

Level: swe2, swe3, senior

OrderedDict (Pythonic): Use collections.OrderedDict. move_to_end() marks recently used; popitem(last=False) evicts LRU.

Doubly Linked List + HashMap: Manual DLL with sentinel head/tail. HashMap stores key -> node. O(1) insert/delete/lookup.

LFU Cache Python - O(1) Least Frequently Used Cache Implementation

Implement an LFU Cache in Python with O(1) get and put. Covers three-dict solution and doubly linked list per frequency bucket approach.

Topics: design-patterns, hash-map, linked-list, caching

Companies: amazon, google, meta, microsoft, databricks

Level: swe3, senior, staff

Three-dict O(1) solution: key_val: key->val, key_freq: key->freq, freq_keys: freq->OrderedDict(key). min_freq tracks eviction target.

Doubly Linked List per frequency: Each frequency bucket is a DLL of nodes. Moving a node to next bucket is O(1). Maintains true LRU order within each bucket.

Design Twitter Python - News Feed with Heap Merge Solution

Design a simplified Twitter with postTweet, follow, unfollow, and getNewsFeed in Python. Uses a max-heap to merge per-user tweet lists efficiently.

Topics: design-patterns, heap, hash-map, object-design

Companies: twitter, amazon, google, meta, uber

Level: swe2, swe3, senior

Heap merge of per-user tweet lists: Store tweets per user with timestamp. getNewsFeed uses a max-heap seeded with the latest tweet from each followed user, then pops up to 10.

Simple list merge (brute force): Collect all tweets from self + followees, sort by timestamp descending, return top 10. Simpler but slower.

Design Snake Game Python - Deque and Set Solution

Implement the Snake Game in Python using a deque and set for O(1) body collision detection. Full solution with food eating and wall boundary logic.

Topics: design-patterns, deque, hash-map, object-design

Companies: amazon, google, microsoft, apple, bloomberg

Level: swe2, swe3, senior

Deque + set for O(1) collision: Deque stores body cells (row, col). Set mirrors deque for O(1) membership. New head computed from direction, tail removed before self-collision check to handle tail-chasing correctly.

Deque only (O(n) collision check): Same deque approach but uses 'in' on deque for collision check. Simpler but O(n) per move for large snakes.

Design Hit Counter Python - Circular Buffer and Queue Solutions

Implement a Hit Counter in Python that counts hits in the past 5 minutes. Covers O(1) circular buffer and queue-based approaches with full test cases.

Topics: design-patterns, queue, array, object-design

Companies: amazon, google, microsoft, stripe, bloomberg

Level: swe2, swe3, senior

Circular buffer (O(1) always): Two arrays of size 300: times[i] stores the timestamp that last wrote slot i, counts[i] stores hits at that timestamp. Slot index = timestamp % 300.

Queue-based (intuitive): Store (timestamp, count) pairs in a deque. On getHits, pop entries older than 300 seconds from front.

Design Phone Directory Python - Set and Queue Solutions

Implement a Phone Directory in Python with O(1) get, check, and release operations using a set of available numbers or queue with boolean array.

Topics: design-patterns, sets, object-design, hash-map

Companies: google, amazon, microsoft, linkedin, bloomberg

Level: swe2, swe3

Set of available numbers: Keep a set of free numbers. get() pops any element O(1). check() is O(1) membership. release() adds back O(1).

Queue + boolean array: Queue of free numbers for O(1) get. Boolean array for O(1) check. Release adds back to queue only if not already free.

Design In-Memory File System Python - Trie Solution

Implement an in-memory file system in Python supporting ls, mkdir, addContentToFile, and readContentFromFile using a trie with dict children.

Topics: design-patterns, trie, object-design, dicts

Companies: google, amazon, microsoft, meta, airbnb, uber

Level: swe3, senior, staff

Trie with dict children: Each node stores children dict and file content string. Traversal splits path on '/'. ls checks if terminal node is file or dir.

Flat dict paths: Two flat dicts: dirs (set of dir paths) and files (file path -> content). ls iterates flat dict to find direct children.

Implement Trie Prefix Tree Python - Insert Search StartsWith

Implement a Trie (Prefix Tree) in Python with insert, search, and startsWith operations. Covers TrieNode dict approach and compact defaultdict solution.

Topics: trie, design-patterns, strings, dicts

Companies: google, amazon, meta, microsoft, apple, bloomberg, uber

Level: swe2, swe3, senior

TrieNode with dict children: Each node stores a dict of char->TrieNode and a boolean is_end. Dynamic children dict avoids fixed 26-slot arrays.

Nested defaultdict (compact): Use nested defaultdict to avoid explicit TrieNode class. Terminator key signals end of word.

Add and Search Word Python - Trie with Wildcard Dot Support

Design a WordDictionary in Python with addWord and wildcard search using a Trie and DFS. Full solution with dot wildcard matching and test cases.

Topics: trie, dfs, backtracking, strings

Companies: google, amazon, meta, microsoft, bloomberg, linkedin

Level: swe2, swe3, senior

Trie with DFS for wildcard: Standard trie insertion. Search uses recursive DFS; when '.' is encountered, recursively check all children nodes.

Dict of word lengths: Group words by length. search checks length match, then each stored word character by character allowing dots as wildcards. Simpler but higher memory overhead per lookup.

Word Search II Python - Trie + DFS Backtracking Solution

Solve Word Search II in Python using a Trie combined with DFS backtracking on the board. Includes trie pruning optimization and full test cases.

Topics: trie, backtracking, dfs, matrix

Companies: amazon, google, meta, microsoft, bloomberg, airbnb

Level: swe3, senior, staff

Trie + DFS with pruning: Build trie from words. DFS from every cell, following trie branches. Record found words and delete trie nodes to avoid revisiting.

Trie + DFS (class-based TrieNode): Same algorithm but with an explicit TrieNode class. Cleaner code, easier to extend.

Implement Stack Using Queues Python - One and Two Queue Solutions

Implement a LIFO stack using only queues in Python. Covers one-queue rotation trick and two-queue swap approach with full test cases.

Topics: stack, queue, design-patterns

Companies: amazon, google, microsoft, bloomberg, adobe

Level: new-grad, swe2

One queue, rotate on push: Use one deque. After appending new element, rotate (n-1) elements to front. Now front is always the top of stack.

Two queues: q1 holds stack elements (top at front). On push, enqueue to q2, drain q1 into q2, then swap references.

Implement Queue Using Stacks Python - Amortized O(1) Solution

Implement a FIFO queue using two stacks in Python with amortized O(1) pop. Covers two-stack inbox/outbox approach and recursive one-stack solution.

Topics: queue, stack, design-patterns

Companies: amazon, google, meta, microsoft, bloomberg

Level: new-grad, swe2

Two stacks - amortized O(1): inbox for pushes, outbox for pops/peeks. Transfer only when outbox empty. Each element moves at most twice total, giving amortized O(1).

One stack with recursion: Pop all elements recursively to reach the bottom (front), perform operation, re-push everything. Elegant but O(n) per operation.

Min Stack Python - O(1) getMin with Auxiliary Stack Solution

Implement a Min Stack in Python that retrieves the minimum element in O(1). Covers auxiliary min stack and tuple-pair approaches with test cases.

Topics: stack, design-patterns

Companies: amazon, google, meta, microsoft, bloomberg, uber, apple

Level: new-grad, swe2, swe3

Auxiliary min stack: Two stacks: main stack and min_stack. min_stack top always holds the minimum of the current stack state.

Store (val, min) pairs: Each stack element is a tuple (value, current_min). Avoids a second stack, same time/space asymptotically.

Max Stack Python - O(log n) Solution with Heap and Lazy Deletion

Implement a Max Stack in Python with O(log n) popMax using a max-heap and lazy deletion. Also covers the simpler two-stack O(n) approach.

Topics: stack, design-patterns, heap, linked-list

Companies: amazon, google, meta, bloomberg, stripe

Level: swe3, senior, staff

Heap + DLL with lazy deletion: DLL maintains stack order. Max-heap stores (-val, uid). popMax: pop heap lazily skipping deleted nodes, remove DLL node via uid lookup.

Two stacks (O(n) popMax): Two stacks: main and max_stack (tracks max at each level). popMax is O(n): pop to temp until max found, push back. Simpler code.

Sliding Window Maximum Python - Monotonic Deque O(n) Solution

Solve Sliding Window Maximum in Python using a monotonic decreasing deque for O(n) time. Includes full walkthrough and test cases.

Topics: deque, sliding-window, monotonic-stack, array

Companies: amazon, google, meta, microsoft, bloomberg, uber, bytedance

Level: swe3, senior, staff

Monotonic decreasing deque: Deque stores indices in decreasing order of nums value. Front = current max index. Pop back when new element is larger; pop front when out of window.

Brute force O(n*k): For each window position, take the max of k elements. Simple but too slow for large inputs.

Sliding Window Minimum Python - Monotonic Deque O(n) Solution

Solve Sliding Window Minimum in Python using a monotonic increasing deque for O(n) time. Includes sparse table RMQ alternative and test cases.

Topics: deque, sliding-window, monotonic-stack, array

Companies: amazon, google, microsoft, bloomberg, palantir

Level: swe2, swe3, senior

Monotonic increasing deque: Deque stores indices in increasing order of nums value (front = min). Pop back when new element is smaller; pop front when index falls outside window.

Segment tree approach: Build a segment tree for range minimum queries. Each window query is O(log n), total O(n log n). Overkill here but demonstrates the general pattern.

First Unique Character in Stream Python - OrderedDict and Deque Solutions

Find the first unique character in a character stream in Python using OrderedDict or a lazy-eviction deque. Full solutions with test cases.

Topics: design-patterns, queue, hash-map, strings, deque

Companies: amazon, google, meta, microsoft, twitter, bloomberg

Level: swe2, swe3, senior

OrderedDict + count: OrderedDict preserves insertion order. Count dict tracks frequency. showFirstUnique scans OrderedDict for first key with count 1.

Deque with lazy eviction: Deque stores all added chars. count dict tracks frequency. showFirstUnique pops from front while count > 1 (lazy), then returns front or # if empty.

Design HashMap Python - Separate Chaining and Direct Address Solutions

Implement a HashMap from scratch in Python using separate chaining with prime buckets or a direct address table. Full solutions with test cases.

Topics: hash-map, design-patterns, array, linked-list

Companies: amazon, google, meta, microsoft, bloomberg, oracle

Level: new-grad, swe2

Separate chaining with prime buckets: Array of 1009 buckets (prime reduces clustering). Each bucket is a list of (key, value) pairs. Operations scan the small chain list.

Direct address table (for small key range): Use a fixed-size array of size max_key+1. Direct index gives O(1) for all operations. Only feasible when key range is small.

Design HashSet Python - Chaining and Bitset Solutions

Implement a HashSet from scratch in Python using separate chaining or a bytearray bitset. Full solutions with add, remove, contains and test cases.

Topics: sets, design-patterns, hash-map, array

Companies: amazon, google, microsoft, bloomberg, oracle, adobe

Level: new-grad, swe2

Separate chaining with lists: Array of 1009 buckets, each a list of keys. add/remove/contains scan the small bucket list.

Bitset / boolean array: Boolean array of size max_key+1. add sets True, remove sets False, contains returns the boolean. O(1) all operations.

Iterator for Combination Python - Lazy Generator and Bitmask Solutions

Implement a CombinationIterator in Python using itertools, a lazy bitmask generator, or a backtracking generator. Full solutions with test cases.

Topics: design-patterns, backtracking, recursion, array

Companies: google, amazon, meta, microsoft, bloomberg, palantir

Level: swe2, swe3, senior

Pre-generated list (itertools): Generate all combinations at init using itertools.combinations. Store as list in reverse for O(1) pop-from-back in lexicographic order.

Lazy bitmask generator: Iterate all 2^n bitmasks in order; yield those with exactly k set bits. Builds combinations lazily without storing all upfront.

Backtracking generator: Use a Python generator with backtracking to yield combinations lazily one at a time. next() calls next() on the generator object.

N-ary Tree Level Order Traversal - Python BFS Solution

Solve N-ary Tree Level Order Traversal in Python using BFS queue and recursive DFS with depth tracking. Includes full code with test cases.

Topics: binary-tree, bfs, queue

Companies: google, amazon, microsoft

Level: new-grad, swe2

BFS with queue: Use a queue. Snapshot the queue size at each level, process exactly that many nodes, push all children. O(n) time and space.

Recursive DFS: DFS with depth tracking. Pass the current depth and append the node value to result[depth]. O(n) time, O(h) stack space where h is height.

Maximum Depth of N-ary Tree - Python DFS and BFS Solutions

Find the maximum depth of an N-ary tree in Python using recursive DFS and iterative BFS. Includes complexity analysis and test cases.

Topics: binary-tree, dfs, bfs

Companies: amazon, facebook, google

Level: new-grad

Recursive DFS: Recursively compute 1 + max depth of all children. If no children, return 1. If root is None, return 0.

Iterative BFS: BFS level by level, counting levels. Return the total level count.

Diameter of Binary Tree - Python DFS Solution with Examples

Solve Diameter of Binary Tree in Python with DFS height tracking. Includes iterative post-order solution, complexity analysis, and test cases.

Topics: binary-tree, dfs, recursion

Companies: amazon, google, facebook, microsoft, apple

Level: new-grad, swe2

DFS with global max: For each node compute height of left and right subtrees. The local diameter = left_h + right_h. Track global max. Return height = 1 + max(left_h, right_h).

Iterative post-order: Iterative post-order traversal using a stack. Store heights in a dict keyed by node. Update diameter at each node.

Lowest Common Ancestor of Deepest Leaves - Python DFS Solution

Find the LCA of deepest leaves in a binary tree using Python DFS. Two clean approaches with full code and complexity analysis.

Topics: binary-tree, dfs, recursion

Companies: google, amazon, facebook

Level: swe2, swe3

DFS returning (node, depth): Each recursive call returns (LCA candidate, max depth in subtree). If left depth == right depth, current node is LCA. Otherwise recurse into the deeper side.

Two-pass: find depth then LCA: First DFS to find max depth. Second DFS to find LCA of all nodes at max depth.

Check Completeness of a Binary Tree - Python BFS Solution

Check if a binary tree is complete using Python BFS with None sentinel and array index approaches. Full code and test cases included.

Topics: binary-tree, bfs

Companies: amazon, facebook, google, microsoft

Level: swe2, swe3

BFS with None sentinel: BFS. Once a None is dequeued, set a flag. If any subsequent non-None node is dequeued, return False.

Array index check: Number nodes with BFS index (root=1, left=2i, right=2i+1). The tree is complete iff count of nodes equals max index.

Cousins in Binary Tree II - Python BFS Solution

Replace each node with the sum of its cousins using Python BFS. Level-sum and sibling-sum trick explained with full code.

Topics: binary-tree, bfs, dfs, hash-map

Companies: google, amazon

Level: swe2, swe3

BFS two-pass: BFS. At each level compute total level sum. Then for each parent node, sibling sum = left.val + right.val. Assign each child: cousin_sum = level_sum - sibling_sum.

Even Odd Tree - Python BFS Level Validation Solution

Validate an Even-Odd tree using Python BFS with level-by-level parity and ordering checks. Full code with test cases.

Topics: binary-tree, bfs

Companies: amazon, google, microsoft

Level: swe2

BFS level validation: BFS. At each level, check: even level -> values must be odd and strictly increasing. Odd level -> values must be even and strictly decreasing.

Step-By-Step Directions From a Binary Tree Node to Another - Python

Find shortest directions between two binary tree nodes in Python using root-to-node paths and LCA prefix removal. Full code included.

Topics: binary-tree, dfs, strings

Companies: google, amazon, facebook

Level: swe2, swe3

Root-to-node paths + LCA trick: Find path from root to start and root to dest. Strip common prefix (which is path to LCA). Answer = "U"*len(remaining_start) + remaining_dest.

Pseudo-Palindromic Paths in a Binary Tree - Python Bitmask DFS

Count pseudo-palindromic root-to-leaf paths using Python DFS with XOR bitmask. Includes iterative solution and full test cases.

Topics: binary-tree, dfs, bit-manipulation

Companies: amazon, google, adobe

Level: swe2, swe3

DFS with bitmask: XOR bitmask tracks odd/even frequency of each digit. At a leaf, check if at most one bit is set using mask & (mask-1) == 0.

Iterative DFS with stack: Iterative DFS using explicit stack storing (node, mask) pairs. Same bitmask logic at leaves.

Sum of Nodes with Even-Valued Grandparent - Python DFS Solution

Sum all nodes whose grandparent has even value using Python DFS with parent tracking. BFS alternative also included.

Topics: binary-tree, dfs, bfs

Companies: amazon, google

Level: swe2

DFS with parent/grandparent tracking: Recursive DFS passing parent and grandparent values. Add current node value when grandparent is even.

BFS with grandchildren tracking: BFS. For each even-valued node, add the values of all its grandchildren (children of children).

Create Binary Tree From Descriptions - Python Hash Map Solution

Build a binary tree from parent-child descriptions using Python hash map. Find root by tracking child set. Full code with test cases.

Topics: binary-tree, hash-map, dfs

Companies: amazon, google, facebook

Level: swe2, swe3

Hash map + child set: Build all nodes in a dict. Track all child values in a set. Root is the node whose value never appears as a child.

Count Nodes Equal to Average of Subtree - Python DFS Solution

Count nodes where value equals floor average of subtree using Python post-order DFS. Full code with complexity analysis and test cases.

Topics: binary-tree, dfs, recursion

Companies: amazon, google, microsoft

Level: swe2

Post-order DFS: Each call returns (total_sum, count). At the node, total = left_sum + right_sum + node.val, cnt = left_cnt + right_cnt + 1. Check node.val == total // cnt.

Maximum Level Sum of Binary Tree - Python BFS Solution

Find the level with maximum sum in a binary tree using Python BFS. Simple level-order traversal with sum tracking.

Topics: binary-tree, bfs

Companies: amazon, google, facebook

Level: new-grad, swe2

BFS level sum: BFS. At each level compute sum. Track max sum and corresponding level. Return that level.

Reverse Odd Levels of Binary Tree - Python BFS and DFS Solutions

Reverse values at odd levels of a perfect binary tree using Python BFS and DFS mirror swap. Full code with test cases.

Topics: binary-tree, bfs, dfs

Companies: google, amazon, microsoft

Level: swe2, swe3

BFS with value reversal at odd levels: BFS. At odd levels collect all nodes, reverse their values (not the nodes themselves). Continue BFS normally.

DFS mirror swap: DFS with two symmetric nodes. At odd levels swap their values. Recurse with outer-outer and inner-inner child pairs.

Count Good Nodes in Binary Tree - Python DFS Solution

Count good nodes in a binary tree where no ancestor has a greater value. Python DFS with max tracking. Iterative and recursive solutions.

Topics: binary-tree, dfs

Companies: google, amazon, facebook, microsoft

Level: new-grad, swe2

DFS with max tracking: DFS from root, carrying max value along the path. Count the node if node.val >= max. Update max before recursing.

Iterative DFS with stack: Iterative DFS using explicit stack of (node, max_so_far). Count good nodes as we go.

Trapping Rain Water II - Python Min-Heap BFS Solution

Solve 3D Trapping Rain Water using Python min-heap BFS. Process border cells outward, accumulate trapped water. Full code with complexity analysis.

Topics: matrix, heap, bfs, greedy

Companies: google, amazon, facebook, microsoft, bloomberg

Level: swe3, senior, staff

Min-heap BFS (3D water fill): Push all border cells into a min-heap. BFS inward always processing the lowest boundary cell. Water at interior cell = max(0, boundary_height - cell_height). Update boundary to max(boundary_height, cell_height).

Maximal Square - Python DP Solution with O(n) Space Optimization

Find the largest square of 1s in a binary matrix using Python DP. Includes O(mn) and O(n) space solutions with full code.

Topics: dynamic-programming, matrix

Companies: amazon, google, facebook, microsoft, apple, bloomberg

Level: swe2, swe3, senior

DP 2D table: dp[i][j] = max side when bottom-right is (i,j). Transition: min of three neighbors + 1. Track global max side.

DP O(n) space: Use a 1D dp array and a prev variable to store dp[i-1][j-1]. Reduces space to O(n).

Maximal Rectangle - Python Monotonic Stack and DP Solutions

Find the maximal rectangle of 1s in a binary matrix using Python histogram with monotonic stack. DP left/right approach also included.

Topics: dynamic-programming, stack, matrix, monotonic-stack

Companies: amazon, google, facebook, microsoft, bloomberg, goldman-sachs

Level: swe3, senior

Histogram + monotonic stack: Convert each row into heights (running count of consecutive 1s above). Apply largest-rectangle-in-histogram with a monotonic stack for each row.

DP left/right/height arrays: For each cell track: height (consecutive 1s above), left boundary (leftmost contiguous 1 in current row), right boundary. Area = height*(right-left).

Longest Consecutive Sequence - Python O(n) Hash Set Solution

Find the longest consecutive sequence in O(n) using Python hash set. Union-Find alternative included. Full code with test cases.

Topics: array, hash-map, sets

Companies: amazon, google, facebook, microsoft, linkedin, uber

Level: swe2, swe3

Hash set O(n): Build a set. For each num where num-1 is not in the set (sequence start), count consecutive nums. Each element is visited at most twice.

Union-Find approach: Union each num with num+1 if both exist. Track component sizes. Max size is the answer.

First Missing Positive - Python Cyclic Sort O(n) O(1) Solution

Find the first missing positive integer in O(n) time O(1) space using cyclic sort and index marking in Python. Complete solutions with test cases.

Topics: array, sorting

Companies: amazon, google, facebook, microsoft, bloomberg, stripe

Level: swe3, senior

Cyclic sort: For each index, swap nums[i] into its correct position (index nums[i]-1) while 1 <= nums[i] <= n and nums[i] != nums[nums[i]-1]. Then find the first index where nums[i] != i+1.

Index marking (sign flip): First pass: replace non-positives and out-of-range with n+1. Second pass: for each value v in [1,n], negate nums[v-1]. Third pass: first non-negative index+1 is the answer.

Text Justification - Python Greedy String Simulation Solution

Solve Text Justification in Python using greedy line packing and space distribution. Full simulation with edge cases and test output.

Topics: strings, greedy

Companies: google, amazon, facebook, microsoft, bloomberg, uber

Level: swe3, senior

Greedy line packing: Group words greedily. For each non-last line compute total extra spaces, distribute left to right. Last line is left-justified with single spaces and trailing spaces.

Jump Game VI - Python Deque DP Sliding Window Solution

Solve Jump Game VI with max score using Python DP and monotonic deque for O(n) sliding window max. Full code with test cases.

Topics: dynamic-programming, deque, sliding-window

Companies: amazon, google, microsoft, linkedin

Level: swe2, swe3

DP + monotonic deque: dp[i] = nums[i] + max(dp[i-k..i-1]). Maintain a max-deque of dp values within the window. Deque front is always the max.

DP + segment tree (for clarity): Use a segment tree for range max queries. dp[i] = nums[i] + range_max(dp, i-k, i-1). O(n log n).

Minimum Cost to Cut a Stick - Python Interval DP Solution

Solve minimum cost stick cutting using Python interval DP. Both bottom-up table and top-down memoized recursion explained with full code.

Topics: dynamic-programming, interval

Companies: amazon, google, facebook, bloomberg

Level: swe3, senior

Interval DP: Sort cuts, add 0 and n as boundaries. dp[i][j] = min cost to cut the segment [cuts[i], cuts[j]]. For each sub-segment try every cut as the last one.

Memoized recursion: Top-down DP. rec(i, j) = min cost for all cuts strictly inside [cuts[i], cuts[j]]. Try each cut as the first cut in that segment.

Largest Color Value in a Directed Graph - Python Topological DP

Find the largest color value along any path in a directed graph using Python topological sort and DP. Cycle detection included.

Topics: graph, topological-sort, dynamic-programming, hash-map

Companies: google, amazon, facebook, coinbase

Level: senior, staff

Kahn's topological sort + DP: Build adjacency list and in-degree. Kahn's BFS topological sort. dp[u][c] = max color-c count on path ending at u. Propagate: dp[v][c] = max(dp[v][c], dp[u][c] + (colors[v]==c)). Answer = max over all nodes and colors. If not all nodes processed, cycle exists.

Parallel Courses III - Python Topological Sort Critical Path

Find minimum completion time for parallel courses using Python topological sort and critical path DP. Full code with test cases.

Topics: graph, topological-sort, dynamic-programming

Companies: google, amazon, facebook, linkedin, databricks

Level: senior, staff

Topological sort critical path: Kahn's BFS topological sort. dp[i] = earliest completion time. When processing course u, update each dependent v: dp[v] = max(dp[v], dp[u] + time[v-1]). Answer = max(dp).

Count Vowels Permutation - Python DP and Matrix Exponentiation

Count valid vowel strings of length n using Python DP state transitions and matrix exponentiation. Full code with modular arithmetic.

Topics: dynamic-programming, math, combinatorics

Companies: google, amazon, facebook

Level: swe3, senior

DP on vowel states: Track count of strings ending with each vowel. Update using the allowed transitions (reversed: which vowels can precede each vowel). Iterate n-1 times.

Matrix exponentiation: Model transitions as a 5x5 matrix. Use fast matrix exponentiation for very large n. O(26^3 * log n) but with only 5 vowels it is O(5^3 * log n).

Strange Printer - Python Interval DP Solution

Solve Strange Printer with minimum turns using Python interval DP. Merge matching characters to reduce turns. Full code with test cases.

Topics: dynamic-programming, interval, recursion

Companies: google, amazon, facebook, bloomberg

Level: senior, staff

Interval DP bottom-up: dp[i][j] = min turns for s[i..j]. Base: dp[i][i]=1. For each character s[k] in (i,j] where s[k]==s[i], dp[i][j] = min(dp[i][j], dp[i+1][k] + dp[k][j]) (s[i] merges with s[k]).

Memoized recursion: Top-down DP. Deduplicate consecutive chars first. rec(i,j) = min turns for s[i..j]. Try merging s[i] with each matching s[k].

Minimum Number of Days to Disconnect Island - Python DFS

Find minimum days to disconnect an island grid using Python DFS. Exploit the observation that the answer is always 0, 1, or 2.

Topics: graph, dfs, matrix

Companies: google, amazon, facebook

Level: senior, staff

Observation: answer <= 2 + brute force check: Count islands. If != 1 return 0. Try removing each land cell and re-count islands; if any gives != 1 return 1. Otherwise return 2.

Minimum Total Distance Traveled - Python DP Robot Factory Solution

Minimize total robot travel distance to factories using Python DP with expanded slots or memoized recursion. Full code with test cases.

Topics: dynamic-programming, sorting, greedy

Companies: google, amazon, facebook, palantir

Level: senior, staff

Sort + DP on expanded factories: Sort robots and factories. Expand each factory position by its limit into individual slots. dp[i][j] = min cost to assign first i robots to first j slots. dp[i][j] = min(dp[i-1][j-1]+|r[i]-slot[j]|, dp[i][j-1]).

Memoized recursion: Top-down DP with lru_cache on (robot_idx, factory_idx, capacity_used). Sort both arrays first.

Minimize the Maximum Difference of Pairs - Python Binary Search

Minimize the max pair difference using Python binary search and greedy pair counting on a sorted array. Full code with complexity analysis.

Topics: binary-search, greedy, sorting

Companies: amazon, google, microsoft, bloomberg

Level: swe2, swe3

Binary search + greedy pair count: Sort nums. Binary search on answer mid. Greedy: scan sorted nums, if nums[i+1]-nums[i] <= mid, take pair and skip i+1, else move forward. If pairs >= p, mid might be feasible.

Count Palindromic Substrings - Python Expand Center and Manacher

Count all palindromic substrings using Python expand-around-center O(n^2) and Manacher's O(n) algorithm. Full code with test cases.

Topics: strings, dynamic-programming, two-pointers

Companies: amazon, google, facebook, microsoft, linkedin

Level: swe2, swe3

Expand around center: For each of the 2n-1 centers, expand outward while characters match. Count palindromes found.

Manacher's algorithm O(n): Manacher's algorithm computes palindrome radii in O(n). Sum the ceiling of each radius+1 to count palindromes.

Shortest Palindrome - Python KMP O(n) Solution

Find the shortest palindrome by prepending characters using Python KMP failure function. O(n) solution with full explanation and test cases.

Topics: strings, string-matching, two-pointers

Companies: google, amazon, facebook, bloomberg

Level: senior, staff

KMP failure function: Construct t = s + "#" + reverse(s). Run KMP to find the longest prefix of t that is also a suffix, which gives the longest palindromic prefix of s.

Two-pointer + recursion: Find the longest palindrome starting from index 0 greedily. Reverse the rest and prepend. Recurse on remaining middle part.

Wildcard Matching - Python DP and Greedy Solutions

Implement wildcard pattern matching with ? and * in Python using 2D DP and greedy two-pointer. Full solutions with complexity analysis.

Topics: dynamic-programming, strings, greedy, recursion

Companies: amazon, google, facebook, microsoft, bloomberg

Level: swe3, senior

DP 2D table: dp[i][j] = does p[:j] match s[:i]. Handle "*" by either matching empty (dp[i][j-1]) or one character (dp[i-1][j]).

Greedy two-pointer: Track last "*" position in pattern and last match position in s. When mismatch, backtrack to last "*" and advance s.

Regular Expression Matching - Python DP and Recursion Solutions

Implement regular expression matching with . and * in Python using 2D DP and memoized recursion. Full code with all edge cases.

Topics: dynamic-programming, strings, recursion

Companies: google, amazon, facebook, microsoft, bloomberg, uber

Level: senior, staff

DP 2D table: dp[i][j] = match. "*" can mean zero (dp[i][j-2]) or extend if preceding element matches (dp[i-1][j]). "." matches any character.

Recursive with memoization: Top-down recursion. Base cases: empty pattern, empty string. Handle "*" by trying zero or one match. Cache results.

Edit Distance - Python DP Levenshtein Distance Solution

Compute the minimum edit distance (Levenshtein) between two strings using Python 2D DP and space-optimized O(n) version. Full code with test cases.

Topics: dynamic-programming, strings

Companies: amazon, google, facebook, microsoft, linkedin, uber, bloomberg

Level: swe2, swe3, senior

DP 2D table: Classic DP. dp[i][j] = Levenshtein distance for word1[:i] and word2[:j]. Three transitions: insert, delete, replace.

DP O(n) space: Use a single row dp array, updating in place. Track the diagonal value with a prev variable.

Word Break II - Python Backtracking with Memoization Solution

Find all sentence breakdowns of a string using a word dictionary in Python with memoized backtracking and DP pruning. Full code with test cases.

Topics: dynamic-programming, backtracking, memoization, trie, strings

Companies: amazon, google, facebook, microsoft, bloomberg, apple

Level: swe3, senior

Backtracking with memoization: Recursive backtrack from index i. Try all dict words that match at i. Memoize (index -> list of sentences from that index).

DP precompute + backtrack: First DP pass checks if s[i:] is breakable. Then backtrack only on reachable indices (pruning invalid branches).

Concatenated Words - Python DP and Trie DFS Solutions

Find all concatenated words formed from shorter words using Python DP Word Break and Trie DFS. Full code with test cases.

Topics: dynamic-programming, trie, dfs, strings

Companies: amazon, google, facebook, microsoft

Level: senior, staff

DP word break per word: Sort words by length. Maintain a set of shorter words. For each word, run Word Break DP: dp[i]=True if s[:i] can be formed from shorter words. A word is concatenated if dp[n] is True and it uses at least 2 pieces.

Trie + DFS: Build a Trie of all words. For each word, DFS through trie matching characters. On end-of-word node, recursively check remainder. Count segments; if >= 2, it is a concatenated word.

Distinct Subsequences - Python DP Solution with Space Optimization

Count distinct subsequences of s equal to t using Python 2D DP and O(n) space optimized version. Full code with test cases.

Topics: dynamic-programming, strings

Companies: amazon, google, facebook, bloomberg

Level: swe3, senior

DP 2D table: dp[i][j] = ways to form t[:j] using s[:i]. Match: use dp[i-1][j-1] (use s[i]) + dp[i-1][j] (skip s[i]). No match: dp[i-1][j] (skip s[i]).

DP O(n) space: Use a 1D dp array, update right to left to avoid overwriting values needed for current row.

Interleaving String - Python DP Solution with Space Optimization

Check if s3 is an interleaving of s1 and s2 using Python 2D DP and O(n) space optimization. Full code with test cases.

Topics: dynamic-programming, strings, recursion

Companies: amazon, google, facebook, microsoft, bloomberg

Level: swe2, swe3

DP 2D table: dp[i][j] = is s3[:i+j] an interleaving of s1[:i] and s2[:j]. Transition uses either s1[i-1] or s2[j-1] to extend s3[i+j-1].

DP O(n) space: Optimize to a 1D dp array by noting that dp[i][j] only depends on dp[i-1][j] and dp[i][j-1].

Word Ladder II - Python BFS Backtrack All Shortest Paths

Find all shortest word ladder transformation sequences using Python BFS with parent map and backtracking. Bidirectional BFS also included.

Topics: graph, bfs, backtracking, hash-map, strings

Companies: amazon, google, facebook, microsoft, bloomberg, uber

Level: senior, staff

BFS layer-by-layer + backtrack: BFS layer by layer. For each word at current layer, find all one-letter neighbors in wordList. Record parent->children. Stop after finding endWord level. Backtrack from endWord using parent map.

Bidirectional BFS + backtrack: Expand from both beginWord and endWord simultaneously, meeting in the middle. Significantly reduces the BFS frontier. Then backtrack through the merged parent map.

Extract Email Addresses with Named Regex Groups | Python Interview Q501

Python interview question: use named regex capture groups to extract and decompose email addresses from unstructured text.

Topics: regex, string, comprehensions

Companies: paypal, visa, datadog, splunk, oracle, discord

Level: new-grad, swe2, swe3

Named Groups with finditer: Single regex with named capture groups, finditer for lazy match streaming

Compiled pattern with list comprehension: Pre-compile regex once at module level, list comprehension over match objects

Parse Structured Log Lines with Regex | Python Interview Q502

Python interview: parse structured log lines using compiled regex with named capture groups for timestamp, level, service, and message.

Topics: regex, string, collections

Companies: datadog, splunk, snowflake, discord, slack, oracle

Level: new-grad, swe2, swe3

Compiled regex with named groups: Pre-compiled regex pattern with named groups, returns None on no match

Parse with split fallback for message: fullmatch anchors both ends; strip message trailing whitespace

Validate and Normalize Phone Numbers with Regex | Python Q503

Python interview: validate and normalize international phone numbers using regex, extracting country code and subscriber number.

Topics: regex, string

Companies: paypal, visa, coinbase, oracle, discord, bytedance

Level: new-grad, swe2, swe3

Strip then validate digit count: Strip non-digits, infer country code from digit count and leading +

Regex pattern with alternation: Two dedicated regexes: one for US/Canada, one for international with explicit country code

Nested List Comprehension Multi-Condition Filter | Python Q504

Python interview: filter a 2D grid with nested list comprehensions using multiple conditions on row index and value.

Topics: comprehensions, lists

Companies: nvidia, snowflake, bytedance, dropbox, oracle, discord

Level: new-grad, swe2

Nested comprehension with enumerate: Single nested comprehension with enumerate for indices, three-condition filter

Generator expression wrapped in list(): Inner generator with early continue on odd rows, yielding matching tuples

Dict Comprehension Invert and Aggregate Duplicates | Python Q505

Python interview: invert a dictionary with duplicate values, aggregating keys into sorted lists using dict comprehension and defaultdict.

Topics: comprehensions, dicts, collections

Companies: snowflake, redis, datadog, oracle, visa, dropbox

Level: new-grad, swe2, swe3

defaultdict then dict comprehension: Group with defaultdict, then dict comprehension with sorted() on each group

itertools.groupby approach: Sort by value, then groupby to collect keys, dict comprehension for output

Set Comprehension Symmetric Difference Analysis | Python Q506

Python interview: use set comprehensions and symmetric difference to detect feature flag drift between deployment environments.

Topics: comprehensions, sets

Companies: discord, slack, snowflake, datadog, nvidia, dropbox

Level: new-grad, swe2

Set operator symmetric_difference: Set comprehensions to deduplicate, then symmetric_difference for O(n+m) set operation

Set comprehension explicit form: Explicit set comprehensions for each side then union - shows the definition clearly

Infinite Fibonacci Generator with send() Reset | Python Q507

Python interview: implement an infinite Fibonacci generator that supports mid-iteration reset via generator.send(), demonstrating two-way generator communication.

Topics: generators, iterators

Companies: jane-street, nvidia, bytedance, coinbase, snowflake, oracle

Level: swe2, swe3

Generator with send() and reset logic: yield expression captures sent value; truthy value resets a, b to 0, 1

Class-based generator with __iter__/__next__: Iterator class with explicit send() method; reset rewinds state before yielding next

Lazy ETL Generator Pipeline Read Filter Transform Batch | Python Q508

Python interview: build a four-stage lazy ETL generator pipeline with reader, filter, transform, and batcher stages that process data without loading it all into memory.

Topics: generators, iterators, functools

Companies: snowflake, datadog, splunk, redis, oracle, bytedance

Level: swe2, swe3

Four-stage generator pipeline with islice batcher: Chain of generator functions; islice pulls exactly size items per batch without buffering upstream

Functional composition with a pipeline helper: compose_pipeline wires stages left-to-right; make_batcher factory parameterizes chunk size

Retry Decorator with Exponential Backoff | Python Interview Q509

Python interview: implement a retry decorator factory with exponential backoff, configurable exceptions, and functools.wraps signature preservation.

Topics: decorators, closures, exceptions

Companies: paypal, coinbase, discord, slack, datadog, visa

Level: swe2, swe3

Decorator factory with exponential backoff: Three-level nesting: factory -> decorator -> wrapper; delay doubles in loop before sleeping

Retry with jitter and selective exception types: Adds jitter (up to 10% of delay) to prevent thundering-herd; re-raises on final attempt

Rate Limiting Decorator with Token Bucket | Python Interview Q510

Python interview: implement a token bucket rate limiting decorator with thread-safe token state, configurable burst, and block or raise behavior.

Topics: decorators, closures, async-await

Companies: discord, slack, paypal, coinbase, bytedance, nvidia, redis

Level: swe2, swe3

Token bucket with threading.Lock: Floating-point token bucket; elapsed time since last check adds fractional tokens; Lock prevents race on shared state

Sliding window counter (simpler, less burst-friendly): Sliding window stores timestamps of recent calls; evicts old entries; no fractional tokens

Type-Annotated Generic Stack Using TypeVar and Generic | Python Q511

Python interview: implement a type-safe generic Stack[T] using TypeVar and Generic with push, pop, peek, __iter__, and from_iterable.

Topics: typing, oop, generics

Companies: nvidia, jane-street, snowflake, coinbase, oracle, dropbox

Level: swe2, swe3

Generic Stack with all methods: list-backed with Generic[T] type parameter; __iter__ uses reversed() for top-to-bottom order

Stack with __slots__ and size limit option: __slots__ reduces per-instance memory; optional maxsize enforced in push

Protocol for Comparable Objects and top_k | Python Interview Q512

Python interview: define a Comparable Protocol using structural subtyping and implement a generic top_k function using only protocol-defined methods.

Topics: protocols, typing, oop

Companies: jane-street, nvidia, snowflake, oracle, coinbase, dropbox

Level: swe2, swe3

Protocol with TypeVar bound and heapq: Min-heap of size k; push when under capacity, replace min when new item is larger; sort result descending

Manual selection sort using only protocol methods: Repeated linear scan using only < and ==; removes selected max each round - demonstrates protocol sufficiency

Retry Decorator with Exponential Backoff | Python Interview Q513

Python interview: implement a retry decorator with exponential backoff and configurable max attempts for resilient distributed systems.

Topics: decorators, closures, exceptions

Companies: google, stripe, amazon, netflix, bloomberg, shopify

Level: swe2, swe3, senior

Loop with exponential sleep: Loop over attempts, catch all exceptions, sleep with doubling delay, re-raise on exhaustion

Recursive with specific exception types: Accept tuple of exception types to catch; only retry on those, let others propagate immediately

Memoize Decorator with functools.wraps | Python Interview Q514

Python interview: implement a memoize decorator that caches results and preserves function metadata using functools.wraps.

Topics: decorators, functools, closures

Companies: google, meta, amazon, microsoft, linkedin, airbnb

Level: swe2, swe3, senior

Dict cache with wraps: Closure over dict, tuple+frozenset key for positional+keyword args, wraps for metadata

Class-based memoize with __call__: Callable class with __call__; functools.update_wrapper copies metadata onto class instance

Timer Decorator Measuring Execution Time | Python Interview Q515

Python interview: build a timer decorator using time.perf_counter and functools.wraps to measure and log function execution time.

Topics: decorators, closures, functools

Companies: amazon, microsoft, bloomberg, shopify, linkedin, airbnb

Level: swe2, swe3, senior

try/finally with perf_counter: try/finally guarantees timing even when function raises; perf_counter for sub-millisecond accuracy

Parametrized timer with logger callback: Optional-argument decorator pattern; accepts @timer or @timer(logger=...) without parentheses ambiguity

Rate Limiter Decorator N Calls Per Second | Python Interview Q516

Python interview: implement a sliding-window rate limiter decorator that enforces N calls per second using a deque of timestamps.

Topics: decorators, closures, python-internals

Companies: stripe, google, netflix, amazon, bloomberg, shopify

Level: swe2, swe3, senior

Sliding window with deque: Deque stores timestamps of recent calls; prune expired ones, raise if still at limit

Blocking rate limiter with sleep: Thread-safe with Lock; block=True sleeps until slot available instead of raising

Class Decorator Adding __repr__ and __eq__ | Python Interview Q517

Python interview: write a class decorator that reads type annotations and injects __init__, __repr__, and __eq__ like a mini dataclass.

Topics: decorators, oop, python-internals

Companies: google, meta, microsoft, airbnb, linkedin, shopify

Level: swe2, swe3, senior

Inject __init__, __repr__, __eq__ via setattr: Read __annotations__, define three dunder methods as closures over fields list, inject with setattr

With default values support: Inspect class dict for default values; merge with positional/keyword args in __init__

Infinite Fibonacci Generator with take(n) | Python Interview Q518

Python interview: implement an infinite Fibonacci generator using yield and a take utility with itertools.islice.

Topics: generators, itertools, python-internals

Companies: google, amazon, microsoft, meta, linkedin, airbnb

Level: swe2, swe3, senior

Pure generator with itertools.islice: Yield a then update a,b simultaneously; islice avoids materializing whole sequence

Generator with takewhile and index filter: Generator composes cleanly with takewhile and comprehensions for filtered subsequences

Generator Pipeline Read Filter Transform | Python Interview Q519

Python interview: chain generator functions into a lazy pipeline that filters, transforms, and parses streaming data without intermediate lists.

Topics: generators, itertools, comprehensions

Companies: google, amazon, netflix, airbnb, linkedin, bloomberg

Level: swe2, swe3, senior

Chained generator functions: Each generator pulls from the previous; no intermediate lists; single-pass O(n) processing

Composable pipeline builder: functools.reduce threads source through list of generator transformers; stages added without changing pipeline() call

Coroutine Data Pipeline Using send() | Python Interview Q520

Python interview: implement a push-based coroutine pipeline using generator send() for two-way communication between stages.

Topics: coroutines, generators, python-internals

Companies: google, netflix, amazon, meta, bloomberg, stripe

Level: swe3, senior

Generator coroutine pipeline with send(): @coroutine auto-primes; each stage receives via yield, forwards via target.send(); close() triggers GeneratorExit

Broadcast fan-out coroutine: broadcast sends each value to all downstream coroutines; grep filters before forwarding to its target

Async Generator for Paginated API Results | Python Interview Q521

Python interview: implement an async generator that transparently iterates paginated API results using async for and cursor-based pagination.

Topics: asyncio, generators, coroutines

Companies: stripe, shopify, google, meta, netflix, amazon

Level: swe3, senior

Async generator with cursor loop: Async generator loops fetching pages; inner for loop yields individual items; stops on null cursor or empty page

With rate limiting and retry: Adds configurable inter-page delay for rate limiting and retry with exponential backoff per page fetch

Context Manager for Database Transaction | Python Interview Q522

Python interview: implement a database transaction context manager with __enter__/__exit__ for commit on success and rollback on exception.

Topics: context-managers, oop, exceptions

Companies: amazon, stripe, google, bloomberg, microsoft, netflix

Level: swe2, swe3, senior

__enter__/__exit__ with commit/rollback: exc_type is None signals clean exit -> commit; any exception -> rollback; return False propagates exception

Savepoint-aware nested transaction: Nested transactions use savepoints; depth counter tracks nesting; only outermost calls COMMIT

Context Manager with contextlib.contextmanager | Python Interview Q523

Python interview: use @contextlib.contextmanager to build a temporary directory context manager with guaranteed cleanup in the finally block.

Topics: context-managers, generators, file-io

Companies: google, amazon, microsoft, airbnb, linkedin, shopify

Level: swe2, swe3, senior

contextmanager generator with finally cleanup: try/yield/finally idiom; finally ensures cleanup whether body raised or returned normally

Parametrized temp_dir with prefix and suffix: Optional keep=True skips rmtree for debugging; prefix/suffix customize the temp directory name

Reentrant Context Manager with Nesting Depth | Python Interview Q524

Python interview: implement a reentrant context manager that tracks nesting depth and releases resources only when the outermost with block exits.

Topics: context-managers, python-internals, oop

Companies: google, meta, amazon, bloomberg, netflix, microsoft

Level: swe3, senior

Depth counter reentrant context manager: Integer depth counter; acquire only at depth 0->1 transition; release only at 1->0 transition

Thread-safe reentrant lock with owner tracking: Track owner thread; same-thread reentry increments depth without re-acquiring the lock; different thread blocks

Descriptor for Validated Typed Attributes | Python Interview Q525

Python interview: implement a descriptor class with __get__, __set__, and __set_name__ for runtime type validation on class attributes.

Topics: descriptors, oop, python-internals

Companies: google, meta, amazon, microsoft, stripe, bloomberg

Level: swe3, senior

Full descriptor with type and range validation: __set_name__ captures attribute name; __get__/__set__ use private key in instance.__dict__ to avoid recursion

Descriptor with default value support: Uses mangled private name for storage; getattr with default avoids KeyError on unset attributes

Lazy Property Descriptor Python | Python Interview Q526

Python interview: implement a lazy property descriptor that computes a value on first access and caches it in the instance __dict__.

Topics: descriptors, python-internals, oop

Companies: google, amazon, meta, netflix, bloomberg, linkedin

Level: swe2, swe3, senior

Non-data descriptor caching in instance __dict__: Non-data descriptor: no __set__ means instance.__dict__ wins on lookup; first __get__ populates cache

Lazy property with invalidation support: Adds invalidate() method on descriptor to pop from instance.__dict__; allows cache busting when underlying data changes

Read-Only Descriptor Raising AttributeError | Python Interview Q527

Python interview: implement a read-only data descriptor that raises AttributeError on set, blocking instance __dict__ override.

Topics: descriptors, oop, python-internals

Companies: google, meta, amazon, stripe, bloomberg, microsoft

Level: swe2, swe3, senior

Data descriptor with per-instance WeakKeyDictionary: WeakKeyDictionary allows per-instance values without preventing GC; __set__ raises after first write; __delete__ also blocked

Strictly read-only with class-level value: Single value on descriptor object; data descriptor priority ensures instance.__dict__ can never shadow it

Metaclass Auto-Registering Subclasses | Python Interview Q528

Python interview: implement a metaclass that automatically registers every subclass in a shared registry dict at class creation time.

Topics: metaclasses, oop, python-internals

Companies: google, meta, amazon, netflix, bloomberg, stripe

Level: swe3, senior

Metaclass __init__ with registry on base: RegistryMeta.__init__ fires at class creation; checks bases to skip root; walks MRO to find shared registry

Simpler version using __init_subclass__ for comparison: __init_subclass__ is the modern alternative; metaclass version shown for completeness and to support multiple independent hierarchies

Metaclass Enforcing snake_case Method Names | Python Interview Q529

Python interview: write a metaclass that enforces snake_case method naming conventions at class definition time using regex.

Topics: metaclasses, python-internals, regex

Companies: google, meta, bloomberg, microsoft, stripe, amazon

Level: swe3, senior

Metaclass __new__ with regex name check: __new__ runs before class object is created; regex rejects camelCase; helper suggests the correct snake_case name

Metaclass with whitelist of allowed non-snake names: Collects all violations before raising so the error message lists all offending names at once

Singleton Pattern Using Metaclass | Python Interview Q530

Python interview: implement the Singleton pattern using a metaclass that overrides __call__ with thread-safe double-checked locking.

Topics: metaclasses, oop, python-internals

Companies: google, amazon, microsoft, bloomberg, netflix, meta

Level: swe2, swe3, senior

Metaclass __call__ with thread safety: Override __call__ on metaclass; double-checked locking prevents race conditions; first initialization wins

Singleton with reset support for testing: reset() class method allows unit tests to get fresh instances without monkey-patching; lock protects reset too

Abstract Base Class with __init_subclass__ | Python Interview Q531

Python interview: use __init_subclass__ to enforce interface contracts on subclasses at class definition time.

Topics: oop, python-internals, typing

Companies: google, amazon, meta, microsoft, netflix, bloomberg

Level: swe2, swe3, senior

__init_subclass__ interface enforcement: __init_subclass__ fires at class creation; abstract=True keyword arg skips check for intermediate abstract classes

ABC module comparison: Shows abc.ABC for comparison; key difference: abc raises at instantiation, __init_subclass__ raises at class definition

__slots__ vs Regular Class Memory Comparison | Python Interview Q532

Python interview: compare __slots__ and regular class memory usage, demonstrate the 40-60% reduction, and explain trade-offs.

Topics: python-internals, oop, descriptors

Companies: google, amazon, meta, bloomberg, netflix, microsoft

Level: swe2, swe3, senior

Memory benchmark with tracemalloc: sys.getsizeof shows shallow size difference; tracemalloc measures real heap usage at scale

Slots inheritance and trade-offs: Shows slots trade-offs: no weakref by default, inheritance pitfalls, __dict__ escape hatch; child without __slots__ re-acquires __dict__

Flexible Config Object with __getattr__ and __setattr__ | Python Interview Q533

Python interview: implement a dynamic config object with dot-access using __getattr__ and __setattr__, avoiding recursion with object.__setattr__.

Topics: python-internals, oop, descriptors

Companies: amazon, google, stripe, netflix, shopify, linkedin

Level: swe2, swe3, senior

Dot-access config with recursive nested support: object.__setattr__ bypasses our __setattr__ for _data initialization; dict values auto-converted to nested Config

Frozen config with change detection: frozen flag blocks __setattr__ after initialization; _changes list tracks all mutations for audit logging

__missing__ in Dict Subclass for Auto-Default | Python Interview Q534

Python interview: override __missing__ in a dict subclass to auto-compute and cache values based on the missing key.

Topics: python-internals, oop, closures

Companies: google, amazon, meta, bloomberg, microsoft, shopify

Level: swe2, swe3, senior

__missing__ auto-computing dict subclass: __missing__ called by dict.__getitem__ on miss; stores result in self[key] before returning, so next access is O(1)

Recursive defaultdict vs __missing__ comparison: Contrasts defaultdict (fixed factory) with __missing__ (key-aware factory); shows nested defaultdict for completeness

Custom Range with __iter__ and __next__ | Python Interview Q535

Python interview: implement the iterator protocol with __iter__ and __next__ to create a custom range class with configurable step.

Topics: python-internals, oop, generators

Companies: amazon, google, microsoft, meta, linkedin, airbnb

Level: swe2, swe3, senior

Stateful iterator class: __iter__ resets _current enabling reuse; __next__ checks boundary condition based on step sign before advancing

Separate iterator and iterable classes: Separate Iterable and Iterator; each __iter__ call creates a fresh iterator so the range can be re-iterated safely

Sorted Collection __len__ __getitem__ __contains__ | Python Interview Q536

Python interview: implement a sorted collection with O(log n) __contains__ using bisect, plus __len__ and __getitem__ for sequence protocol.

Topics: python-internals, oop, itertools

Companies: google, amazon, meta, bloomberg, microsoft, netflix

Level: swe2, swe3, senior

bisect-based sorted collection: bisect_left finds insertion point; check element at that index to confirm membership; insort maintains order on add

Sorted collection with range query support: irange uses both bisect_left and bisect_right with inclusive flags to implement range queries efficiently

Vector Class with __add__ and __mul__ | Python Interview Q537

Python interview: implement a Vector class with operator overloading for element-wise addition, scalar multiplication, and dot product.

Topics: oop, python-internals, typing

Companies: google, amazon, meta, microsoft, bloomberg, netflix

Level: swe2, swe3, senior

Vector with full arithmetic operator set: Return NotImplemented (not raise) to allow Python to try reflected operation; dispatch __mul__ on isinstance check

Vector with NumPy-style broadcasting: __radd__ and __rmul__ enable commutative scalar operations; normalize() uses __abs__ and __mul__

Sync and Async Context Manager for Resource | Python Interview Q538

Python interview: implement a class with both __enter__/__exit__ and __aenter__/__aexit__ for dual sync/async context manager usage.

Topics: context-managers, asyncio, oop

Companies: stripe, google, netflix, amazon, bloomberg, meta

Level: swe3, senior

Dual sync/async context manager: __aenter__ and __aexit__ are async coroutines awaiting IO; both protocols return self and set acquired flag

Connection pool with async/sync dual protocol: contextlib.contextmanager and asynccontextmanager produce sync and async context managers from generators without full class protocol

Dataclass with __post_init__ Validation and __hash__ | Python Interview Q539

Python interview: use Python dataclasses with __post_init__ for validation and explicit __hash__ for hashable value objects.

Topics: dataclasses, oop, python-internals

Companies: google, amazon, meta, stripe, bloomberg, shopify

Level: swe2, swe3, senior

Dataclass with validation and explicit __hash__: __post_init__ coerces to float and validates finiteness; __hash__ on (x, y) tuple ensures equal objects hash equally

Frozen dataclass for true immutability: frozen=True auto-generates __hash__ and blocks __setattr__; object.__setattr__ required for post-init normalization in frozen classes

Dataclass field() Defaults and Computed Fields | Python Interview Q540

Python interview: use dataclass field() with default_factory, init=False computed fields, and repr=False to build clean domain models.

Topics: dataclasses, oop, python-internals

Companies: google, amazon, meta, microsoft, stripe, netflix

Level: swe2, swe3, senior

field() with default_factory and computed fields: default_factory=list gives each instance its own list; init=False fields must be set in __post_init__; repr=False hides verbose/sensitive fields

Dataclass with field metadata and validators: field(metadata=...) stores validation rules; __post_init__ uses fields() to iterate and check each; eliminates per-field if/raise boilerplate

NamedTuple with Methods and Default Values | Python Interview Q541

Python interview: use typing.NamedTuple to create an immutable, hashable, typed tuple with methods and default field values.

Topics: typing, oop, python-internals

Companies: google, amazon, meta, microsoft, bloomberg, airbnb

Level: swe2, swe3, senior

NamedTuple with distance method and defaults: NamedTuple is a true tuple subclass; methods defined normally; defaults on trailing fields; _replace() for updated copies

NamedTuple vs dataclass comparison: Side-by-side comparison shows NamedTuple advantages: immutability, hashability, no __dict__; dataclass advantages: mutability, field() metadata

TypedDict for Structured Dicts with Optional Keys | Python Interview Q542

Python interview: use TypedDict with total=False and NotRequired to define structured dicts with required and optional keys for mypy type checking.

Topics: typing, python-internals, oop

Companies: google, stripe, amazon, meta, bloomberg, shopify

Level: swe2, swe3, senior

TypedDict with required and optional fields: Inheritance combines required base with optional extension; total=False on child makes all child fields optional; runtime is plain dict

TypedDict with NotRequired and runtime validation: NotRequired[T] marks optional keys; __required_keys__ attr (Python 3.9+) enables runtime required-key validation

Generic Class with Bounded TypeVar | Python Interview Q543

Python interview: implement a Generic class using TypeVar and Generic from typing, with a bounded TypeVar for type-safe comparable collections.

Topics: typing, oop, python-internals

Companies: google, amazon, meta, stripe, bloomberg, microsoft

Level: swe2, swe3, senior

Generic Stack and bounded SortedList: Generic[T] parameterizes the class; CT bound=Comparable ensures SortedList only accepts types with __lt__; Protocol for structural checking

Generic Result[T, E] type: Two-parameter generic Result[T, E] models success or failure explicitly; map() chains transformations without unwrapping

Protocol Class for Structural Subtyping | Python Interview Q544

Python interview: use typing.Protocol with @runtime_checkable for structural duck typing without explicit inheritance.

Topics: typing, oop, python-internals

Companies: google, amazon, meta, microsoft, stripe, bloomberg

Level: swe2, swe3, senior

Protocol with runtime_checkable for duck typing: @runtime_checkable enables isinstance; Protocol checks structural match (method presence); no inheritance required

Protocol for comparable and serializable: Serializable protocol defines to_dict/from_dict contract; unrelated User and Product satisfy it structurally; isinstance filters non-conforming objects

Implement functools.partial from Scratch | Python Interview Q545

Python interview: implement functools.partial from scratch, merging pre-filled positional and keyword arguments with call-site arguments.

Topics: functools, closures, python-internals

Companies: google, amazon, meta, microsoft, bloomberg, airbnb

Level: swe2, swe3, senior

Class-based partial implementation: __new__ flattens nested partials; call merges stored and call-site args/kwargs; call-site kwargs win on conflict

Closure-based functional partial: Closure captures partial args/kwargs; wrapper prepends stored positional args and merges kwargs; exposes .func .args .keywords attributes

Implement functools.reduce from Scratch | Python Interview Q546

Python interview: implement functools.reduce with optional initial value, handling empty iterables correctly.

Topics: functools, closures, python-internals

Companies: google, amazon, meta, microsoft, bloomberg, netflix

Level: swe2, swe3, senior

reduce with optional initializer: Sentinel _MISSING distinguishes "no initial" from None; iter() consumes lazily; first element seeds accumulator when no initial provided

reduce with scan (running accumulation) variant: scan() yields intermediate accumulators (prefix reductions); useful for running totals, prefix products, and cumulative operations

Implement itertools.groupby from Scratch | Python Interview Q547

Python interview: implement itertools.groupby grouping consecutive equal-key elements, understanding the lazy shared-iterator design.

Topics: itertools, generators, python-internals

Companies: google, amazon, meta, bloomberg, netflix, airbnb

Level: swe2, swe3, senior

groupby with materialized groups: Materializes each group as a list; yields iter(group) for protocol compatibility; simpler but uses O(group_size) memory

Lazy groupby sharing underlying iterator: True lazy implementation: _GroupIter shares _GroupByState; advancing outer iterator invalidates current group sub-iterator

Implement itertools.chain from Scratch | Python Interview Q548

Python interview: implement itertools.chain and chain.from_iterable as lazy generators that concatenate multiple iterables without intermediate lists.

Topics: itertools, generators, python-internals

Companies: google, amazon, meta, microsoft, bloomberg, shopify

Level: swe2, swe3, senior

Generator-based chain: __iter__ uses yield from for each iterable; from_iterable returns special instance with generator; both fully lazy

Functional chain implementations: yield from is the key primitive; chain_from_iterable enables flat-mapping; recursive flatten handles arbitrary nesting depth

Implement itertools.islice from Scratch | Python Interview Q549

Python interview: implement itertools.islice that lazily slices an iterator with start, stop, and step without materializing elements.

Topics: itertools, generators, python-internals

Companies: google, amazon, meta, microsoft, bloomberg, airbnb

Level: swe2, swe3, senior

islice with start/stop/step logic: Use slice() to parse args uniformly; skip start elements; yield with inner skip loop for step > 1

islice using enumerate for index tracking: Pre-compute target indices as range(start, stop, step); iterate with enumerate and yield when index matches next target

Implement itertools.product Cartesian Product | Python Interview Q550

Python interview: implement itertools.product for Cartesian product of iterables using odometer-style index arrays.

Topics: itertools, generators, python-internals

Companies: google, amazon, meta, microsoft, bloomberg, netflix

Level: swe2, swe3, senior

Odometer-style index increment: Odometer analogy: increment rightmost index, carry to left when pool exhausted; repeat multiplies pools list

Recursive generator approach: Recursive generator builds prefix tuple; each level appends one pool element; base case yields complete tuple

Closure Loop Variable Capture Gotcha | Python Interview Q551

Python interview: explain and fix the closure loop variable late binding gotcha using default args, functools.partial, and factory functions.

Topics: closures, python-internals, functools

Companies: google, amazon, meta, microsoft, bloomberg, airbnb

Level: swe2, swe3, senior

All three fixes with explanation: Default arg: evaluated at def time, stores current value in function object; partial: stores value in args tuple; factory: new frame binds new local i

Deep dive: cell objects and LEGB: Cell objects explain the mechanism; IIFE (lambda x: lambda: x)(i) creates immediate new scope; make_handler is the idiomatic production pattern

Event Emitter with on/emit/off in Python | Python Interview Q552

Python interview: implement an event emitter with on(), emit(), off(), and once() methods for the Observer pattern.

Topics: oop, closures, python-internals

Companies: amazon, netflix, shopify, stripe, bloomberg, airbnb

Level: swe2, swe3, senior

Event emitter with once() and error handling: defaultdict(list) stores handlers; copy list before emit to allow safe off() during dispatch; once() wraps handler to self-remove after first call

Event emitter with wildcard and priority: Heap stores (negated_priority, counter, handler) tuples; wildcard * catches all events; priority ordering ensures predictable dispatch

Weak References with weakref to Avoid Memory Leaks | Python Interview Q553

Python interview: use weakref.ref and WeakValueDictionary to build caches and event emitters that do not prevent garbage collection.

Topics: python-internals, oop, closures

Companies: google, amazon, meta, bloomberg, netflix, microsoft

Level: swe3, senior

weakref.ref and WeakValueDictionary cache: ref() returns None after GC; WeakValueDictionary automatically removes entries; finalize runs callback on collection

Weak reference in event emitter to avoid leaks: WeakMethod handles bound method references; dead refs pruned during emit; subscribers not kept alive by the emitter

copy and deepcopy with __copy__ and __deepcopy__ | Python Interview Q554

Python interview: implement __copy__ and __deepcopy__ for custom classes, handling reference cycles with memo and selective deep copying.

Topics: python-internals, oop, descriptors

Companies: google, amazon, meta, microsoft, bloomberg, shopify

Level: swe2, swe3, senior

__copy__ and __deepcopy__ with memo cycle prevention: __copy__ copies __dict__ shallowly; __deepcopy__ registers self in memo before recursing to handle reference cycles; deepcopy recurses into each field

Selective deep copy for mixed resource/data objects: Selectively skip deepcopy for shared resources (_pool); deepcopy only per-session mutable state; documents the intent explicitly

Pickle-Aware Class with __getstate__ and __setstate__ | Python Interview Q555

Python interview: implement __getstate__ and __setstate__ for custom pickling, excluding unpicklable attributes like locks and file handles.

Topics: python-internals, oop, file-io

Companies: google, amazon, meta, bloomberg, netflix, airbnb

Level: swe2, swe3, senior

__getstate__/__setstate__ for unpicklable attributes: __getstate__ converts unpicklable objects to picklable equivalents (StringIO -> str, lock excluded); __setstate__ recreates them after deserialization

Model checkpointing with reduce for protocol 2: Transient compiled state excluded from state; deserialized model requires re-compile; thread.local recreated fresh; pattern common in ML serving

Extract Emails from Text Using Regex Named Groups | Python Interview Q556

Python interview: extract and decompose email addresses from text using Python regex named capture groups and re.finditer.

Topics: regex, python-internals, comprehensions

Companies: google, amazon, meta, bloomberg, shopify, linkedin

Level: swe2, swe3, senior

Named groups with finditer: Named groups with character classes; finditer lazy-matches all non-overlapping emails; groupdict() returns structured dict per match

Extended extraction with validation and normalization: NamedTuple Email with normalized() method; pattern limits local/domain length per RFC; deduplication using set of normalized forms

Parse Log Lines with Named Regex Groups | Python Interview Q557

Python interview: parse structured log lines into dicts using Python regex named capture groups for timestamp, level, module, and message.

Topics: regex, python-internals, file-io

Companies: amazon, netflix, google, bloomberg, stripe, shopify

Level: swe2, swe3, senior

Named group log parser with level filtering: Named groups; match() anchors to line start; timestamp converted to datetime; level filtering by rank dict; generator for streaming large files

Multi-format log parser with fallback patterns: Try multiple compiled patterns in order; first match wins; _format field identifies which pattern matched; extensible by appending to PATTERNS list

Validate and Parse ISO 8601 Datetime Strings | Python Interview Q558

Python interview: validate and parse ISO 8601 datetime strings using Python regex named groups, handling optional time and timezone components.

Topics: regex, python-internals, typing

Companies: google, stripe, amazon, bloomberg, shopify, meta

Level: swe2, swe3, senior

Named group ISO 8601 parser: Non-capturing groups (?:...) for optional time section; named groups for all components; separate to_datetime converts dict to datetime with tz

Flexible parser with multiple format support: Multiple patterns tried in order; most specific first; _format field records which pattern matched; flexible T-or-space separator

Exception Chaining raise X from Y and __cause__ vs __context__ | Python Interview Q559

Python interview: understand and use exception chaining with raise X from Y, explaining __cause__, __context__, and raise from None.

Topics: exceptions, python-internals, oop

Companies: google, amazon, meta, bloomberg, stripe, netflix

Level: swe2, swe3, senior

Explicit vs implicit chaining demonstration: raise X from Y sets __cause__; implicit raise in except sets __context__; raise X from None sets __suppress_context__=True hiding the chain in traceback

Domain exception wrapper utility: Context manager centralizes exception translation; suppress_chain=True hides internal details; pass-through for already-domain exceptions

Custom Exception Hierarchy with Error Codes | Python Interview Q560

Python interview: design a custom exception hierarchy with structured error codes, HTTP status hints, and a code-based factory method.

Topics: exceptions, oop, python-internals

Companies: stripe, google, amazon, bloomberg, shopify, netflix

Level: swe2, swe3, senior

Full exception hierarchy with error registry: Hierarchy: AppError -> domain -> specific; DEFAULT_CODE/STATUS class attributes override per class; from_gateway_code classmethod translates external codes; to_dict() for API serialization

Error registry with code-based lookup and HTTP mapping: __init_subclass__ auto-registers every subclass with a CODE attribute; from_code() factory enables code-based error construction without import dependencies

Doubly Linked List with Sentinel Nodes | Python Interview Q561

Implement a doubly linked list with sentinel head and tail nodes for O(1) insert and delete anywhere.

Topics: doubly-linked-list, linked-list, hash-table

Companies: oracle, palantir, dropbox, adobe, airbnb, goldman-sachs

Level: swe2, swe3, senior

Sentinel Head/Tail Pattern: Create dummy head and tail nodes permanently connected. Every real insert and delete operates between existing nodes — no None checks needed anywhere.

Circular Doubly Linked List Rotate Insert Delete | Python Q562

Implement a circular doubly linked list with rotate, insert, delete while maintaining circular invariant.

Topics: circular-linked-list, doubly-linked-list, linked-list

Companies: oracle, adobe, coinbase, palantir, airbnb, twitter

Level: swe2, swe3, senior

Circular DLL with Head Pointer: Maintain only a head pointer. Since circular, head.prev is always the tail. Insert appends before head. Rotate advances head k steps.

Doubly Linked List as Deque O(1) All Operations | Python Q563

Build a deque using a doubly linked list with O(1) push_front, push_back, pop_front, pop_back.

Topics: doubly-linked-list, deque, linked-list, queue, stack

Companies: oracle, adobe, dropbox, twitter, kafka, cloudflare

Level: swe2, swe3

Sentinel DLL Deque: Use sentinel head and tail. push_front inserts after head; push_back inserts before tail. pop operations remove from those ends.

Flatten Multilevel Doubly Linked List | Python Interview Q564

Flatten a multilevel doubly linked list with child pointers in-place using a stack.

Topics: doubly-linked-list, linked-list, stack

Companies: oracle, adobe, palantir, airbnb, dropbox, coinbase

Level: swe2, swe3, senior

Iterative Stack: Walk the list. When node has child, push current next, set child as new next, clear child. When next is None and stack non-empty, pop and reattach.

Reverse Doubly Linked List in Groups of K | Python Q565

Reverse every k nodes of a doubly linked list in-place, maintaining correct prev and next pointers.

Topics: doubly-linked-list, linked-list, deque

Companies: oracle, palantir, goldman-sachs, adobe, airbnb, coinbase

Level: swe3, senior, staff

Iterative Group Reversal: Walk groups of k. For each group, swap every node's prev/next, then stitch reversed group back into the surrounding list via group_prev and group_next.

Segment Tree Range Sum Query Point Update | Python Q566

Implement a segment tree for O(log n) range sum queries and point updates over an array.

Topics: segment-tree, binary-tree, hash-table

Companies: palantir, jane-street, goldman-sachs, databricks, oracle, coinbase

Level: swe3, senior, staff

Recursive Segment Tree: Store tree in a 1-indexed array. Build bottom-up. query and update top-down with range checking. Node at index i has children at 2i and 2i+1.

Iterative Segment Tree: Use 2n-size array where leaves start at index n. Updates walk from leaf to root; queries combine segments walking from both ends inward.

Segment Tree Range Minimum Query | Python Interview Q567

Build a segment tree for O(log n) range minimum queries with point updates.

Topics: segment-tree, binary-tree

Companies: palantir, jane-street, databricks, goldman-sachs, oracle, airbnb

Level: swe3, senior, staff

Recursive RMQ Segment Tree: Same structure as sum segment tree but merge function is min. Identity element for out-of-range is positive infinity.

Lazy Propagation Segment Tree Range Add Sum | Python Q568

Implement segment tree with lazy propagation for O(log n) range add updates and range sum queries.

Topics: segment-tree, binary-tree

Companies: jane-street, palantir, goldman-sachs, databricks, oracle, coinbase

Level: senior, staff

Lazy Propagation with Push Down: Store sum and lazy at each node. Before accessing children, push pending lazy down. Range add multiplies delta by segment length for the sum update.

Fenwick Tree BIT Prefix Sums Count Inversions | Python Q569

Implement a Binary Indexed Tree for O(log n) prefix sums and use it to count inversions in O(n log n).

Topics: fenwick-tree, binary-tree, hash-table

Companies: jane-street, palantir, goldman-sachs, databricks, oracle, airbnb

Level: swe3, senior, staff

BIT + Inversion Count via Coordinate Compression: BIT stores prefix sums. For inversions: process right-to-left, for each element query how many elements already seen are smaller using prefix_sum, then add current element to BIT.

2D Fenwick Tree Rectangle Sum Queries | Python Interview Q570

Implement a 2D BIT for O(log m log n) point updates and rectangle sum queries.

Topics: fenwick-tree, hash-table, binary-tree

Companies: jane-street, palantir, goldman-sachs, databricks, coinbase, oracle

Level: senior, staff

2D Fenwick Tree: Nested lowbit loops for both dimensions. update propagates through row and column ancestors. rect_sum uses inclusion-exclusion over four corner prefix queries.

BST Floor and Ceiling Operations | Python Interview Q571

Implement floor and ceiling on a BST: largest key <= k and smallest key >= k in O(h).

Topics: bst, binary-tree

Companies: oracle, palantir, jane-street, adobe, airbnb, goldman-sachs

Level: swe2, swe3, senior

Iterative Floor and Ceiling: For floor: walk BST, track best candidate when node.val<=k, go right to find larger valid values. For ceiling: track best when node.val>=k, go left for smaller valid values.

BST Rank and Select with Augmented Subtree Sizes | Python Q572

Augment a BST with subtree sizes to support O(h) rank and select order statistics operations.

Topics: bst, binary-tree, sorted-list

Companies: jane-street, palantir, goldman-sachs, databricks, oracle, airbnb

Level: swe3, senior, staff

Augmented BST with Size Field: Each node stores subtree size. Insert updates sizes on the way back up. Rank and select use left subtree sizes to determine position without full traversal.

BST In-Order Successor Predecessor Parent Pointers | Python Q573

Find BST in-order successor and predecessor using parent pointers, O(h) without recursion.

Topics: bst, binary-tree, linked-list

Companies: oracle, palantir, adobe, twitter, airbnb, dropbox

Level: swe2, swe3, senior

Parent Pointer Navigation: Successor: go right then leftmost if right exists; else ascend until arriving from a left child. Predecessor mirrors for left child.

AVL Tree Balanced BST with Rotations | Python Interview Q574

Implement a self-balancing AVL tree with LL, RR, LR, RL rotations for O(log n) guaranteed operations.

Topics: bst, binary-tree

Companies: jane-street, palantir, goldman-sachs, oracle, databricks, coinbase

Level: senior, staff

Full AVL Tree with Four Rotations: Store height at each node. After insertion, recompute heights on the way up. Check balance factor and apply LL/RR/LR/RL rotations. Return new subtree root after each rotation.

BST Serialization and Deserialization | Python Interview Q575

Serialize a BST to compact pre-order string and reconstruct using BST bounds in O(n).

Topics: bst, binary-tree, queue

Companies: oracle, palantir, adobe, dropbox, airbnb, twitter

Level: swe2, swe3, senior

Pre-order Serialize, Bounded Deserialize: Serialize with pre-order DFS (no nulls). Deserialize using a deque of values with min/max bounds — each value is placed only if it falls within bounds, achieving O(n) reconstruction.

Trie Autocomplete with Frequency Ranking Top-K | Python Q577

Build a trie ranking autocomplete suggestions by insertion frequency, returning top-k results for any prefix.

Topics: trie, heap, hash-table, sorted-list

Companies: oracle, adobe, dropbox, airbnb, twitter, coinbase

Level: swe2, swe3, senior

Trie with Frequency and DFS Collection: Each node stores children and freq field. suggest navigates to prefix endpoint, DFS collects all (freq,word) pairs. Sort by (-freq,word), return top k.

Compressed Patricia Trie Implementation | Python Interview Q578

Implement a Patricia (compressed) trie collapsing single-child chains into edge labels for memory efficiency.

Topics: trie, hash-table

Companies: jane-street, palantir, cloudflare, oracle, coinbase, databricks

Level: senior, staff

Patricia Trie with Edge Splitting: Edges stored as [label, child_node] keyed by first character. On insert, compute LCP with existing edge; if partial match, split edge into two at divergence point.

Trie for IP Routing Longest Prefix Match | Python Q579

Build a binary trie for IP routing supporting add_route and longest prefix match lookup in O(32).

Topics: trie, hash-table, graph

Companies: cloudflare, oracle, coinbase, databricks, palantir, jane-street

Level: senior, staff

Binary Trie for 32-bit IP Routing: Each node has two children (bit 0, bit 1). add_route converts CIDR to 32 bits and inserts prefix_length bits. lookup traverses all 32 bits tracking the most recent next_hop seen.

Aho-Corasick Automaton Multi-Pattern String Matching | Python Q580

Build Aho-Corasick automaton with failure links for O(n) simultaneous multi-pattern string matching.

Topics: trie, queue, hash-table, graph

Companies: jane-street, palantir, cloudflare, databricks, oracle, coinbase

Level: senior, staff

Aho-Corasick with Failure and Output Links: Build trie, BFS to set failure links pointing to longest proper suffix in trie. Output links chain to all patterns that are proper suffixes of current node path. Text scan follows failure links on mismatch.

Deque Sliding Window Sum | Python Interview Q581

Compute the running sum for every window of size k using a deque buffer with O(n) time.

Topics: deque, queue, hash-table

Companies: oracle, adobe, dropbox, kafka, airbnb, twitter

Level: swe2, swe3

Deque Buffer with Running Sum: Use a deque to store the k elements of the current window. Maintain a running sum, add each new element, subtract element leaving from left.

Sliding Window Median Sorted List | Python Interview Q582

Find the median of every sliding window of size k using a sorted list in O(n log k) with SortedList.

Topics: sorted-list, two-heaps, heap, deque

Companies: jane-street, palantir, goldman-sachs, databricks, oracle, coinbase

Level: senior, staff

Sorted List via bisect: Maintain window as a sorted list using bisect.insort and bisect_left for O(log k) search. Median is middle element for odd k or average of two middles for even.

Monotonic Deque Jump Game Minimum Jumps | Python Q583

Find minimum jumps in O(n) using greedy sliding window — the monotonic deque DP optimization.

Topics: deque, queue, graph

Companies: palantir, jane-street, goldman-sachs, databricks, oracle, airbnb

Level: senior, staff

Greedy O(n): Track current range endpoint and farthest reachable. When exhausting current range, increment jump count and advance to farthest. Equivalent to BFS levels.

LRU Cache with TTL Expiration | Python Interview Q584

Implement an LRU cache with per-entry TTL expiration combining capacity eviction and time-based expiry.

Topics: lru-cache, doubly-linked-list, hash-table

Companies: oracle, dropbox, cloudflare, airbnb, coinbase, twitter

Level: swe3, senior, staff

OrderedDict LRU with TTL Check: Use OrderedDict for O(1) move-to-end LRU. Store (value,expiry) tuples. On get, check expiry and delete if expired. On put, evict LRU if at capacity.

Thread-Safe LRU Cache with threading.Lock | Python Q585

Build a thread-safe LRU cache using threading.Lock to protect concurrent get and put operations.

Topics: lru-cache, doubly-linked-list, hash-table

Companies: oracle, dropbox, airbnb, kafka, coinbase, cloudflare

Level: swe3, senior, staff

Mutex-Protected OrderedDict LRU: Wrap all operations in threading.Lock context manager. Track hits/misses under lock. Return hit_rate in stats().

LFU Cache O(1) All Operations | Python Interview Q586

Implement LFU cache with O(1) get and put using frequency buckets backed by OrderedDicts.

Topics: lfu-cache, doubly-linked-list, hash-table

Companies: jane-street, palantir, oracle, airbnb, coinbase, databricks

Level: senior, staff

Frequency Buckets with OrderedDicts: key_freq maps key to freq; freq_keys maps freq to OrderedDict. min_freq tracks lowest. On get/put: remove from current freq bucket, add to freq+1 bucket; update min_freq.

LFU Cache with Frequency Aging | Python Interview Q587

Extend LFU cache with periodic frequency aging to prevent stale hot-key dominance via frequency halving.

Topics: lfu-cache, doubly-linked-list, hash-table

Companies: jane-street, palantir, databricks, cloudflare, coinbase, oracle

Level: senior, staff

LFU with Periodic Frequency Halving: Standard LFU internals plus access_count. Every age_every accesses, call age() which snapshots all frequencies, halves them (min 1), clears freq_keys, rebuilds buckets.

SortedList Order Statistics Insert Delete Rank | Python Q588

Use a sorted list for O(log n) rank and kth-smallest order statistics queries using bisect.

Topics: sorted-list, heap, binary-tree, bst

Companies: jane-street, palantir, goldman-sachs, databricks, airbnb, coinbase

Level: swe3, senior

Bisect-Based Sorted List: Python list maintained in sorted order via bisect.insort (O(n) insert due to shift) and bisect_left (O(log n) search). rank is bisect_left; kth_smallest is O(1) indexing.

Skip List Probabilistic Data Structure | Python Interview Q589

Implement a skip list with random levels for O(log n) expected search, insert, delete — as used in Redis ZSET.

Topics: sorted-list, linked-list, hash-table

Companies: jane-street, palantir, databricks, oracle, coinbase, goldman-sachs

Level: senior, staff

Probabilistic Skip List with Forward Pointer Arrays: Nodes have forward pointer arrays per level. Insert: random_level(), maintain update[], splice at each level. Delete: use update[] to remove from all levels.

K-Way Merge Sorted Arrays Min-Heap | Python Q590

Merge k sorted arrays in O(n log k) using a min-heap — foundation of external sort and database merge-join.

Topics: k-way-merge, heap, sorted-list

Companies: palantir, jane-street, databricks, oracle, airbnb, goldman-sachs

Level: swe2, swe3, senior

Min-Heap K-Way Merge: Initialize heap with first element from each non-empty array as (value, array_idx, elem_idx). Extract min, append, push next from same source. Handle empty arrays by skipping.

External Sort Merge Phase K-Way Heap | Python Q591

Implement external sort merge phase using a k-way heap, merging sorted runs with O(k) memory.

Topics: k-way-merge, heap, sorted-list, queue

Companies: databricks, palantir, oracle, jane-street, airbnb, kafka

Level: senior, staff

Buffered K-Way External Merge Generator: Push first element from each run into heap. On extract, advance that iterator. Wrap in try/except StopIteration. external_sort creates sorted chunks then merges.

Median of Two Sorted Arrays O(log min m n) | Python Q592

Find the median of two sorted arrays in O(log(min(m,n))) using binary search on array partitions.

Topics: two-heaps, sorted-list, binary-tree

Companies: jane-street, palantir, goldman-sachs, databricks, oracle, airbnb

Level: senior, staff

O(m+n) Merge: Merge both arrays, compute median.

O(log min(m,n)) Binary Search: Binary search on partition index of smaller array. For each partition i in nums1, compute j so left halves together have (m+n+1)//2 elements. Check cross-boundary conditions.

Streaming Median with Two Heaps | Python Interview Q593

Implement streaming median with O(log n) addNum and O(1) findMedian using two balanced heaps.

Topics: two-heaps, heap, sorted-list

Companies: jane-street, palantir, databricks, oracle, airbnb, goldman-sachs

Level: swe3, senior

Two Heaps — Max-Heap Lower, Min-Heap Upper: Always push to lo (max-heap). If lo top exceeds hi top, move to hi. Size rebalancing: if lo has more than 1 extra, move excess to hi.

Sliding Window Median Two Heaps Lazy Deletion | Python Q594

Sliding window medians using two heaps with lazy deletion, O(n log k) total.

Topics: two-heaps, heap, deque

Companies: jane-street, palantir, goldman-sachs, databricks, oracle, coinbase

Level: senior, staff

Two Heaps with Lazy Deletion Counter: Maintain effective sizes lo_size/hi_size. On remove, mark in removed dict, decrement effective size, then rebalance. prune_top skips stale entries.

Union-Find Path Compression Union by Rank | Python Q595

Implement Union-Find with path compression and union by rank for O(alpha(n)) amortized operations.

Topics: union-find, graph, hash-table

Companies: palantir, oracle, databricks, airbnb, jane-street, coinbase

Level: swe2, swe3, senior

Path Halving + Union by Rank: find() uses path halving for compression. union() compares ranks; smaller attaches under larger. Equal ranks: increment new root rank. Track component count.

Union-Find Dynamic Connectivity Arbitrary Keys | Python Q596

Build dynamic connectivity for arbitrary hashable node identifiers using a dictionary-based Union-Find.

Topics: union-find, graph, hash-table

Companies: palantir, oracle, jane-street, airbnb, databricks, goldman-sachs

Level: swe3, senior

Dict-Based Union-Find: Use dict for parent and rank. _add() inserts node as its own root. find(), connect(), is_connected() proceed identically to array-based DSU.

Kruskal's MST with Union-Find | Python Interview Q597

Implement Kruskal's Minimum Spanning Tree algorithm using Union-Find for O(E log E) time.

Topics: union-find, graph, sorted-list

Companies: palantir, oracle, databricks, airbnb, jane-street, goldman-sachs

Level: swe3, senior

Kruskal's Algorithm with Union-Find: Sort edges by weight. For each edge attempt union; if successful (different components) add to MST. Stop when n-1 edges collected.

Persistent Union-Find with Rollback | Python Interview Q598

Implement rollbackable Union-Find using union-by-rank with a change stack — no path compression.

Topics: union-find, stack, graph

Companies: jane-street, palantir, goldman-sachs, databricks, oracle, coinbase

Level: staff

Union by Rank with Change History Stack: find() walks without compression. union() records state before modifying. checkpoint() returns stack length. rollback(v) reverses all changes since v.

Circular Queue Ring Buffer Implementation | Python Interview Q599

Implement a circular queue (ring buffer) with O(1) enqueue and dequeue using modular arithmetic.

Topics: queue, circular-linked-list, deque

Companies: oracle, kafka, adobe, dropbox, twitter, airbnb

Level: swe2, swe3

Array Ring Buffer with Size Counter: Fixed array with head, tail, size. enqueue writes at tail and advances tail mod capacity. dequeue reads from head and advances head mod capacity.

Queue from Two Stacks O(1) Amortized | Python Interview Q600

Implement a FIFO queue using two stacks with O(1) amortized dequeue using inbox/outbox pattern.

Topics: queue, stack, deque

Companies: oracle, adobe, dropbox, airbnb, twitter, palantir

Level: swe2, swe3

Inbox and Outbox Stacks: enqueue pushes to inbox. dequeue pops from outbox; if outbox empty, pour inbox into outbox first reversing order. Total moves per element: 2, giving O(1) amortized.

BFS Shortest Path in Unweighted Graph - Python Interview Question

Learn how to find the shortest path in an unweighted graph using BFS in Python. Includes two solutions with complexity analysis.

Topics: graph, bfs, hash-map

Companies: amazon, google, meta, microsoft, uber, linkedin

Level: swe2, swe3

BFS with distance tracking: Standard BFS - explore level by level, return distance when destination is found.

BFS with parent map for path reconstruction: Level-by-level BFS using queue length snapshot to count distance in whole steps.

Count Connected Components in Graph - Python DFS and Union-Find

Count connected components in an undirected graph using DFS and Union-Find in Python. Full solutions with complexity analysis.

Topics: graph, dfs, union-find

Companies: google, meta, amazon, linkedin, microsoft, stripe

Level: swe2, swe3

DFS with adjacency list: Build adjacency list, iterate nodes, DFS from each unvisited node, count launches.

Union-Find (Disjoint Set Union): Union-Find with path compression and union by rank. Start with n components, decrement on each successful union.

Topological Sort Kahn's Algorithm Python - BFS Approach

Implement topological sort using Kahn's BFS algorithm in Python. Includes cycle detection and full complexity analysis.

Topics: graph, bfs, topological-sort

Companies: amazon, google, microsoft, uber, meta, bloomberg

Level: swe2, swe3, senior

Kahn's BFS with in-degree array: Build in-degree map, BFS from zero-in-degree nodes, detect cycles via result length check.

Kahn's with explicit cycle detection message: Same BFS approach with explicit cycle detection logging before returning empty list.

Topological Sort DFS Postorder Python - Iterative and Recursive

Implement topological sort using DFS postorder in Python. Includes both recursive and iterative solutions with complexity analysis.

Topics: graph, dfs, topological-sort

Companies: google, amazon, meta, microsoft, airbnb, stripe

Level: swe2, swe3, senior

Recursive DFS postorder with stack: DFS postorder: recurse into all unvisited neighbors before appending current node. Reverse for topological order.

Iterative DFS postorder (avoids recursion limit): Iterative DFS with a "processed" flag to simulate postorder without hitting Python's recursion limit on large graphs.

Detect Cycle in Directed Graph Using DFS Colors - Python

Detect cycles in a directed graph using the three-color DFS white/gray/black technique in Python with full solutions.

Topics: graph, dfs

Companies: google, amazon, microsoft, meta, uber, oracle

Level: swe2, swe3, senior

Three-color DFS (recursive): Three-color DFS marks nodes white/gray/black. Gray neighbor during traversal signals a back edge (cycle).

Iterative DFS with explicit call stack simulation: Iterative simulation of recursive DFS using an explicit stack of (node, neighbor_iterator) pairs to avoid Python recursion limits.

Detect Cycle in Undirected Graph Using Union-Find - Python

Detect cycles in an undirected graph using Union-Find with path compression in Python. Includes DFS alternative.

Topics: graph, union-find

Companies: amazon, google, meta, bloomberg, microsoft, linkedin

Level: swe2, swe3

Union-Find with path compression and union by rank: Union-Find with path compression and union by rank. Cycle detected when two nodes already share a root.

DFS-based cycle detection for comparison: DFS tracking parent to distinguish back edges from the edge we came from. Included as alternative to Union-Find.

Dijkstra's Shortest Path Algorithm Python - Min-Heap Implementation

Implement Dijkstra's shortest path algorithm with a min-heap in Python. Two solutions with full complexity analysis.

Topics: graph, dijkstra, heap

Companies: google, uber, amazon, microsoft, meta, airbnb

Level: swe3, senior

Dijkstra with min-heap and lazy deletion: Min-heap with lazy deletion: push updated distances and skip stale entries when popped. Greedy relaxation of edges.

Dijkstra with visited set (early termination): Same heap approach but uses a finalized set for early node skip instead of distance comparison - slightly cleaner logic.

Bellman-Ford Algorithm Python - Negative Edges and Cycle Detection

Implement Bellman-Ford algorithm in Python to handle negative edge weights and detect negative cycles. Full solutions with analysis.

Topics: graph, dynamic-programming

Companies: google, amazon, meta, bloomberg, stripe, microsoft

Level: swe3, senior

Classic Bellman-Ford with negative cycle detection: Relax all edges V-1 times using dynamic programming. V-th pass detects negative cycles. Simple and correct for all cases.

Bellman-Ford with early termination optimization: Same algorithm with early exit if no edge was relaxed in a full iteration - avoids unnecessary passes on simple graphs.

Floyd-Warshall All-Pairs Shortest Path Python - Full DP Solution

Implement Floyd-Warshall algorithm in Python for all-pairs shortest paths. Includes negative cycle detection and complexity analysis.

Topics: graph, dynamic-programming, matrix

Companies: google, amazon, bloomberg, microsoft, oracle, meta

Level: swe3, senior

Classic Floyd-Warshall DP: Triple nested loop DP. For each intermediate node k, relax all (i,j) pairs considering k as a waypoint.

Floyd-Warshall with negative cycle detection: Same DP with post-processing check: if dist[i][i] < 0 after the algorithm, node i participates in a negative cycle.

Prim's MST Algorithm Python - Min-Heap Implementation

Implement Prim's Minimum Spanning Tree algorithm in Python using a min-heap. Two approaches: lazy and eager Prim's.

Topics: graph, heap, dijkstra

Companies: google, amazon, microsoft, airbnb, oracle, uber

Level: swe3, senior

Prim's with min-heap (lazy Prim's): Lazy Prim's: push all candidate edges to heap, skip already-visited nodes when popped. Simple and effective for sparse graphs.

Eager Prim's with key-decrease using distance array: Tracks minimum known edge cost per node. Only pushes to heap when a better edge is found - reduces heap size significantly.

Number of Islands Python - DFS and BFS Grid Solutions

Solve the Number of Islands problem in Python using DFS and BFS. Classic grid graph problem with full solutions and complexity analysis.

Topics: graph, dfs, bfs, matrix

Companies: amazon, google, meta, microsoft, bloomberg, airbnb

Level: swe2, swe3

DFS with in-place marking: DFS from each unvisited land cell, mark all reachable land as visited in-place. Count DFS launches.

BFS with queue: BFS from each unvisited land cell, mark visited immediately before enqueuing. Avoids deep recursion of DFS approach.

Word Ladder BFS Python - Minimum Transformations Solution

Solve the Word Ladder problem using BFS in Python. Includes unidirectional and bidirectional BFS with full complexity analysis.

Topics: graph, bfs, hash-map

Companies: amazon, google, meta, microsoft, linkedin, uber

Level: swe3, senior

BFS with character substitution: BFS from beginWord, try all single-character mutations at each position. Return path length when endWord is found.

Bidirectional BFS for large inputs: Bidirectional BFS simultaneously expands from both ends. Always expand the smaller frontier to minimize work. Drastically faster in practice.

Alien Dictionary Problem Python - Topological Sort Solution

Solve the Alien Dictionary problem using topological sort in Python. BFS and DFS approaches with cycle detection.

Topics: graph, topological-sort, bfs, dfs

Companies: google, meta, amazon, airbnb, bloomberg, stripe

Level: swe3, senior

BFS topological sort (Kahn's) on character graph: Extract edges from adjacent word comparisons, then Kahn's BFS topological sort on character graph. Detect cycles via length check.

DFS topological sort on character graph: Same graph construction, but uses three-color DFS postorder for topological sort and cycle detection.

Course Schedule II Python - Topological Sort Order Solution

Find valid course ordering using topological sort in Python. BFS and DFS solutions for Course Schedule II with cycle detection.

Topics: graph, topological-sort, bfs, dfs

Companies: amazon, google, meta, microsoft, uber, bloomberg

Level: swe2, swe3

Kahn's BFS topological sort: Build graph with edge from prereq to course. Kahn's BFS from zero-in-degree nodes gives valid ordering or detects cycle.

DFS postorder topological sort: DFS with three-color state tracking. Postorder collection reversed gives topological order. Cycle makes output empty.

Network Delay Time Python - Dijkstra's Algorithm Solution

Solve Network Delay Time in Python using Dijkstra's algorithm. Find maximum shortest path from source node with full analysis.

Topics: graph, dijkstra, heap

Companies: amazon, google, meta, uber, microsoft, oracle

Level: swe2, swe3, senior

Dijkstra's from source k: Dijkstra from k to all nodes. Answer is max shortest path; -1 if any node unreachable.

Bellman-Ford alternative (handles edge case validation): Bellman-Ford as an alternative. Simpler to implement for small n; useful when asked to handle negative edges in follow-up questions.

Cheapest Flights Within K Stops Python - Bellman-Ford and Dijkstra

Find cheapest flights within K stops in Python using Bellman-Ford and Dijkstra. Full solutions with complexity analysis.

Topics: graph, dynamic-programming, dijkstra, bfs

Companies: amazon, google, meta, airbnb, uber, bloomberg

Level: swe3, senior

Modified Bellman-Ford (K+1 relaxations): Modified Bellman-Ford: relax all edges exactly K+1 times. Use a snapshot of distances each round to prevent within-round propagation.

Dijkstra with stops constraint: Modified Dijkstra with stops as extra state. Prune states where stops exceed k or a better stop-count exists for same node.

Pacific Atlantic Water Flow Python - BFS from Edges Solution

Solve Pacific Atlantic Water Flow using reverse BFS and DFS in Python. Full grid graph solution with complexity analysis.

Topics: graph, bfs, dfs, matrix

Companies: google, amazon, meta, microsoft, airbnb, linkedin

Level: swe3, senior

BFS from both ocean edges: Reverse BFS from ocean borders, allow uphill flow. Intersection of Pacific-reachable and Atlantic-reachable cells is the answer.

DFS from both ocean edges: DFS from edge cells for each ocean. Uphill traversal (reversed flow) marks cells that can reach each ocean. Intersection is the answer.

Walls and Gates Multi-Source BFS Python - Grid Distance Problem

Solve Walls and Gates using multi-source BFS in Python. Fill rooms with minimum distance to nearest gate efficiently.

Topics: graph, bfs, matrix

Companies: google, meta, amazon, microsoft, bloomberg, linkedin

Level: swe2, swe3

Multi-source BFS from all gates: Multi-source BFS: enqueue all gates at level 0 simultaneously. BFS naturally assigns minimum distances without revisiting.

BFS with explicit distance tracking (cleaner for explanation): Same multi-source BFS with explicit distance in queue tuple - slightly more readable and easier to adapt for tracking paths.

Rotting Oranges BFS Python - Multi-Source Grid Propagation

Solve Rotting Oranges using multi-source BFS in Python. Find minimum minutes for rot to spread with full complexity analysis.

Topics: graph, bfs, matrix

Companies: amazon, google, meta, microsoft, uber, stripe

Level: swe2, swe3

Multi-source BFS with fresh orange counter: Multi-source BFS from all rotten oranges. Track fresh count and max time reached. Remaining fresh means impossible.

Level-by-level BFS (minute tracking): Level-by-level BFS using queue size snapshot each minute. Clean separation between time steps, easier to reason about minute counting.

Clone Graph Python - DFS and BFS with Hash Map Solutions

Clone a graph using DFS with hash map in Python. Handles cycles using memoization. Includes BFS alternative.

Topics: graph, dfs, bfs, hash-map

Companies: google, meta, amazon, microsoft, linkedin, uber

Level: swe2, swe3

DFS with hash map (recursive): DFS with memoization map. Create clone before recursing into neighbors to handle cycles. Return existing clone if already visited.

BFS with hash map (iterative): BFS with map: create clone immediately when first encountered. Process neighbors level by level, linking clones as we go. Avoids recursion limit.

Accounts Merge - Union-Find Graph Problem | Python Solution

Learn how to merge accounts with shared emails using Union-Find and DFS in Python. Detailed solutions with time and space complexity analysis.

Topics: union-find, graph, hash-map

Companies: google, amazon, meta, microsoft, linkedin, airbnb

Level: swe2, swe3, senior

Union-Find: Assign each email a unique ID. For each account, union all emails together. Then group emails by their root representative and reconstruct merged accounts.

DFS / BFS Graph: Build an adjacency list where emails in the same account are connected. Then run DFS from each unvisited email to collect all emails in the same connected component.

Redundant Connection - Cycle Detection with Union-Find | Python

Find the redundant edge in an undirected graph using Union-Find and DFS cycle detection. Python solutions with complexity analysis.

Topics: union-find, graph

Companies: amazon, google, bloomberg, microsoft, uber, meta

Level: swe2, swe3, senior

Union-Find with Path Compression: Use Union-Find. For each edge, if both nodes share the same root, they are already connected - this edge is redundant. Otherwise, union them.

DFS Cycle Detection: Build adjacency list incrementally. Before adding each edge, run DFS to check if a path already exists between the two endpoints. If yes, the current edge is redundant.

Longest Consecutive Sequence O(n) - Hash Set Solution | Python

Solve the longest consecutive sequence problem in O(n) time using a hash set. Two Python approaches with detailed complexity analysis.

Topics: array, hash-map

Companies: google, amazon, meta, microsoft, uber, linkedin

Level: swe2, swe3, senior

Hash Set O(n): Add all numbers to a set. For each number that is a sequence start (no num-1 in set), count consecutive numbers forward. Track the maximum.

Hash Map with Sequence Lengths: Use a dict to store the length of consecutive sequence each number belongs to. When inserting a number, check left and right neighbors and merge sequences.

Max Area of Island - DFS BFS Grid Problem | Python Solution

Find the maximum area island in a binary grid using DFS and BFS in Python. Complete solutions with time and space complexity.

Topics: graph, array

Companies: amazon, google, meta, airbnb, uber, bloomberg

Level: swe2, swe3, senior

DFS with In-place Marking: Iterate over every cell. When a land cell is found, run DFS to count the island area and mark visited cells as 0. Track the maximum area seen.

BFS Iterative: Use a queue to explore islands iteratively. For each land cell, add it to a queue and expand in four directions, counting cells until the queue is empty.

Swim in Rising Water - Min-Heap and Binary Search | Python

Solve the swim in rising water problem using Dijkstra min-heap and binary search with BFS. Python solutions with full complexity analysis.

Topics: graph, heap, greedy

Companies: google, amazon, meta, stripe, microsoft, uber

Level: swe3, senior

Min-Heap (Dijkstra): Use a min-heap where each entry is (max_elevation_seen, row, col). Greedily pick the path that minimizes the maximum elevation encountered. This is Dijkstra with a modified cost function.

Binary Search + BFS: Binary search on the answer t. For each t, run BFS to check if there is a valid path from (0,0) to (n-1,n-1) using only cells with elevation <= t.

Coin Change DP - Bottom-up and Memoization Solutions | Python

Solve coin change with minimum coins using bottom-up dynamic programming and top-down memoization in Python. Interview-ready solutions.

Topics: dynamic-programming, memoization

Companies: amazon, google, meta, microsoft, airbnb, stripe

Level: swe2, swe3, senior

Bottom-up DP: Build a dp array where dp[i] is the min coins for amount i. Initialize with infinity, set dp[0]=0, then fill from 1 to amount using all coin denominations.

Top-down Memoization: Recursively compute minimum coins for each amount, caching results to avoid recomputation. For each amount, try subtracting every coin and recurse.

Coin Change II - Count Combinations DP | Python Solution

Count the number of coin combinations that make up an amount using dynamic programming in Python. Two DP approaches explained.

Topics: dynamic-programming

Companies: amazon, google, bloomberg, meta, microsoft, oracle

Level: swe2, swe3, senior

1D DP - Combinations Count: Use a 1D dp array. Outer loop over coins, inner loop over amounts. This ordering ensures each coin is processed once per amount, counting combinations not permutations.

2D DP - Explicit States: Use a 2D dp table where dp[i][j] = number of ways to make amount j using first i coin types. This makes the state transitions more explicit and easier to reason about.

Climbing Stairs - Fibonacci DP Solution | Python

Solve the climbing stairs problem using Fibonacci dynamic programming in Python. Iterative and memoization approaches with O(1) space solution.

Topics: dynamic-programming, memoization

Companies: amazon, google, meta, microsoft, bloomberg, oracle

Level: swe2, swe3

Iterative Fibonacci O(1) Space: Track only the last two values. At each step, the new value is the sum of the previous two. This reduces space from O(n) to O(1).

Top-down Memoization: Recursively compute climbStairs(n) = climbStairs(n-1) + climbStairs(n-2) with memoization to avoid exponential recomputation.

House Robber - Linear DP No Adjacent Selection | Python

Maximize robbery amount without robbing adjacent houses using dynamic programming. O(1) space Python solution with detailed explanation.

Topics: dynamic-programming

Companies: amazon, google, meta, microsoft, airbnb, linkedin

Level: swe2, swe3

O(1) Space DP: Track only two variables: the best result excluding the previous house and the best result including it. Update in a single pass.

Bottom-up DP Array: Build a dp array where dp[i] is the max rob amount up to house i. Fill forward using the recurrence dp[i] = max(dp[i-1], dp[i-2] + nums[i]).

House Robber II - Circular DP Problem | Python Solution

Solve the circular house robber problem by splitting into two linear subproblems. Python DP solution with O(1) space.

Topics: dynamic-programming

Companies: amazon, google, meta, microsoft, bloomberg, uber

Level: swe2, swe3, senior

Two-pass Linear DP: Run the standard House Robber DP on two subarrays: nums[:-1] and nums[1:]. The answer is max of both results. Handle n=1 as an edge case.

Explicit DP with Two Arrays: Compute dp1 for range [0, n-2] and dp2 for range [1, n-1] using full DP arrays for clarity. The explicit arrays make the logic easier to trace and debug.

House Robber III - Binary Tree DP | Python Solution

Solve house robber on a binary tree using tree DP with pair return values. Efficient O(n) Python solution with detailed explanation.

Topics: dynamic-programming, graph

Companies: amazon, google, meta, microsoft, uber, stripe

Level: swe3, senior

Tree DP with Pair Return: Post-order DFS returning (rob_node, skip_node) for each subtree. Compute the max at each level using children results. No memoization needed.

Memoized DFS: Two separate recursive functions: one for robbing a node, one for skipping. Cache results with a dict to avoid recomputing the same subtree twice.

Unique Paths - Grid DP and Combinatorics | Python Solution

Count unique paths in a grid using dynamic programming and combinatorics in Python. Two solutions with O(1) and O(n) space.

Topics: dynamic-programming

Companies: amazon, google, microsoft, meta, bloomberg, oracle

Level: swe2, swe3

1D DP O(n) Space: Use a single row of length n. For each row, update each cell by adding the value from the left (same row). The top-row equivalent is already in the array.

Math Combinatorics: Total moves = m+n-2. Choose m-1 of them to be downward moves. Answer is C(m+n-2, m-1) using math.comb for clean O(1) space solution.

Minimum Path Sum - Grid DP Solution | Python

Find the minimum path sum in a grid using dynamic programming in Python. In-place and 1D DP solutions with complexity analysis.

Topics: dynamic-programming

Companies: amazon, google, meta, microsoft, airbnb, stripe

Level: swe2, swe3

In-place DP: Modify the grid in place. Fill first row and first column as cumulative sums. For remaining cells, add the minimum of the cell above and the cell to the left.

1D DP Array: Use a 1D dp array of size n. Process row by row, updating dp[j] to represent the minimum path sum to reach current cell (i, j).

Edit Distance (Levenshtein) - DP Solution | Python

Compute the minimum edit distance between two strings using dynamic programming in Python. 2D and space-optimized 1D DP solutions.

Topics: dynamic-programming

Companies: google, amazon, meta, microsoft, linkedin, airbnb

Level: swe3, senior

Bottom-up 2D DP: Build a (m+1) x (n+1) DP table. Row 0 and column 0 represent empty string conversions. Fill using the Levenshtein recurrence.

Space-optimized 1D DP: Use two 1D arrays (previous row and current row) instead of the full 2D table, reducing space from O(m*n) to O(n).

Longest Common Subsequence - DP Solution | Python

Find the longest common subsequence of two strings using dynamic programming in Python. 2D DP and space-optimized O(n) solutions.

Topics: dynamic-programming

Companies: google, amazon, meta, microsoft, linkedin, bloomberg

Level: swe2, swe3, senior

Bottom-up 2D DP: Build a (m+1) x (n+1) table. For matching characters extend the diagonal, otherwise take max of skipping one character from either string.

Space-optimized 1D DP: Use two rows only (prev and curr) to reduce space. Track the diagonal value separately before overwriting.

Longest Increasing Subsequence O(n log n) | Python Solution

Solve the longest increasing subsequence problem in O(n log n) with patience sorting and binary search in Python.

Topics: dynamic-programming, greedy

Companies: google, amazon, meta, microsoft, bloomberg, stripe

Level: swe2, swe3, senior

O(n log n) Patience Sorting: Maintain a tails array. For each number, binary search for the leftmost position in tails that is >= num. Replace that position or extend tails. The length of tails is the LIS length.

O(n^2) DP: For each index i, compute dp[i] = max of dp[j]+1 for all j < i where nums[j] < nums[i]. Track the global maximum.

Longest Palindromic Subsequence - Interval DP | Python

Find the longest palindromic subsequence using interval DP and LCS techniques in Python. Two O(n^2) solutions explained.

Topics: dynamic-programming

Companies: amazon, google, meta, microsoft, bloomberg, oracle

Level: swe2, swe3, senior

Interval DP: dp[i][j] is the LPS length in s[i..j]. If s[i]==s[j], extend from dp[i+1][j-1]+2. Otherwise take max of dp[i+1][j] and dp[i][j-1].

LCS with Reversed String: The longest palindromic subsequence of s equals the LCS of s and its reverse. Reuse the LCS algorithm directly.

Palindromic Substrings Count - Expand Around Center | Python

Count all palindromic substrings using expand-around-center and DP table in Python. O(n^2) solutions with O(1) space option.

Topics: dynamic-programming, array

Companies: amazon, google, meta, microsoft, airbnb, stripe

Level: swe2, swe3

Expand Around Center: For each character and each pair of adjacent characters, expand outward while characters match. Each valid expansion contributes one palindromic substring.

DP Table: Build a boolean dp[i][j] = True if s[i..j] is a palindrome. Fill diagonally by substring length. Count all True entries.

Word Break DP - Dictionary Segmentation | Python Solution

Solve the word break problem using bottom-up DP and memoized DFS in Python. Complete solutions with complexity analysis.

Topics: dynamic-programming, memoization, hash-map

Companies: amazon, google, meta, microsoft, bloomberg, linkedin

Level: swe2, swe3, senior

Bottom-up DP: Use a boolean dp array of size n+1. dp[i] indicates if s[:i] can be broken. For each i, iterate over all j < i and check dp[j] and s[j:i] in word set.

Top-down Memoization (DFS): Recursively check if s[start:] can be segmented. Memoize results for each start index. Try all dictionary words as prefixes at the current position.

Word Break II - Backtracking with Memoization | Python

Find all valid word break sentences using backtracking and memoization in Python. Two complete solutions for this hard DP problem.

Topics: dynamic-programming, memoization

Companies: google, amazon, meta, microsoft, uber, airbnb

Level: swe3, senior

Backtracking with Memoization: DFS from each index, trying all words as prefixes. Cache results (list of valid sentence suffixes) per start index. Combine current word with memoized suffixes.

Iterative DP + Reconstruction: First build dp[i] = list of words that end at position i and are valid. Then reconstruct all paths from the end back to the start using these dp lists.

Interleaving String - 2D DP Solution | Python

Solve the interleaving string problem using 2D dynamic programming. Learn the dp[i][j] transition and space-optimized 1D DP approach with Python examples.

Topics: dynamic-programming, string

Companies: google, amazon, meta, microsoft, bloomberg, adobe

Level: senior, staff

2D DP Table: Build a 2D DP table where dp[i][j] indicates whether s3[:i+j] is a valid interleaving of s1[:i] and s2[:j]. Fill row by row using transitions from the top and left cells.

Space-Optimized 1D DP: Compress the 2D DP table to a single row by iterating row by row and updating dp[j] in-place, reducing space from O(m*n) to O(n).

Decode Ways - Count Encodings DP | Python

Count the number of ways to decode a digit string using dynamic programming. Covers bottom-up DP and space-optimized two-variable approach in Python.

Topics: dynamic-programming, string

Companies: amazon, meta, microsoft, google, bloomberg, stripe

Level: swe3, senior

Bottom-Up DP: Use a DP array where dp[i] counts decodings for the first i characters. At each step consider single-digit and two-digit decodings, guarding against zeros.

Space-Optimized Two Variables: Since each dp[i] depends only on dp[i-1] and dp[i-2], maintain two rolling variables instead of the full array, achieving constant space.

Distinct Subsequences - DP Count | Python

Count distinct subsequences of s equal to t using 2D and space-optimized 1D dynamic programming. Detailed Python solutions with complexity analysis.

Topics: dynamic-programming, string

Companies: google, amazon, meta, apple, goldman-sachs, bloomberg

Level: senior, staff

2D DP: Build a 2D DP table. For each cell, the count is the number of ways skipping the current character in s plus, when characters match, the ways using it.

1D Space-Optimized DP: Compress the DP table to one row. Iterate j from right to left to prevent using updated values from the current row, mimicking the prev-row semantics.

Regular Expression Matching DP | Python

Implement regex matching with . and * using 2D DP and memoization. Google interview classic with full Python solutions and complexity analysis.

Topics: dynamic-programming, string

Companies: google, meta, amazon, microsoft, apple, stripe

Level: senior, staff

2D Bottom-Up DP: Build a 2D DP table handling three cases: literal match or dot, star with zero occurrences, and star with one-or-more occurrences. Initialize first row for star-patterns matching empty string.

Recursive Memoization: Use top-down recursion with memoization on indices (i, j). At each step, handle the star lookahead case first, then plain character or dot match.

Wildcard Matching DP and Greedy | Python

Solve wildcard pattern matching with ? and * using 2D DP or greedy two-pointer. Full Python solutions with time and space complexity breakdown.

Topics: dynamic-programming, string

Companies: amazon, google, meta, microsoft, bloomberg, adobe

Level: senior, staff

2D DP: A 2D DP where * transitions come from consuming one char in s (dp[i-1][j]) or matching nothing (dp[i][j-1]). Initialize first row for leading stars.

Two-Pointer Greedy: Greedy two-pointer: advance both pointers on match or question-mark. On *, save position and try matching zero characters first, backtracking to match one more each time matching fails.

Burst Balloons - Interval DP | Python

Maximize coins from bursting balloons using interval dynamic programming. Learn the "last burst" insight with bottom-up and top-down memoization in Python.

Topics: dynamic-programming, array

Companies: google, meta, amazon, apple, goldman-sachs, stripe

Level: staff

Interval DP (Bottom-Up): Enumerate all intervals by increasing length. For each interval [left, right], try every balloon k as the last to burst, accumulating coins from sub-intervals.

Top-Down Memoization: Recursive interval DP with memoization. For each open interval (left, right), enumerate the last balloon k to burst, caching results with lru_cache.

Stone Game I - DP and Math Proof | Python

Solve Stone Game I with the O(1) math insight and the general interval DP approach. Full Python solutions with explanations for coding interviews.

Topics: dynamic-programming, array

Companies: amazon, meta, google, bloomberg, microsoft, goldman-sachs

Level: swe3, senior

Math Observation O(1): With an even number of piles and odd total, Alice can always guarantee she picks the larger half (all odd or all even indexed piles). She always wins.

Interval DP General Solution: Build interval DP where dp[i][j] stores the score advantage for the current player. At each step, pick whichever end maximizes advantage minus the opponent's optimal play.

Partition Equal Subset Sum - 0/1 Knapsack | Python

Partition array into two equal-sum subsets using 0/1 knapsack DP and Python bitset trick. Full solutions with complexity analysis for coding interviews.

Topics: dynamic-programming, array

Companies: amazon, google, meta, microsoft, apple, netflix

Level: swe3, senior

0/1 Knapsack DP: Standard 0/1 knapsack: iterate each number, update dp array from right to left to avoid reusing the same number. Check dp[target] at the end.

Bitset (Python int as bitmask): Use a Python integer as a bitset where bit s is set if sum s is achievable. For each number, shift the bitset left by num and OR it in. Check if bit target is set.

Target Sum - DP and DFS Memoization | Python

Count ways to assign +/- to reach a target sum using subset sum DP reduction and DFS memoization. Python solutions with math derivation explained.

Topics: dynamic-programming, array

Companies: amazon, google, meta, bloomberg, stripe, microsoft

Level: swe3, senior

Subset Sum DP Reduction: Reduce to counting subsets summing to (total + target) // 2 using 0/1 knapsack counting DP. Each dp[s] holds the number of ways to achieve sum s.

DFS with Memoization: Recursive DFS tries both + and - at each index. Memoize on (index, remaining) to avoid recomputation. Straightforward but uses more memory than the DP reduction.

Last Stone Weight - Max-Heap Greedy | Python

Simulate stone smashing using a max-heap in Python. Learn negation trick for max-heap with heapq, with time and space complexity analysis.

Topics: heap, greedy, array

Companies: amazon, google, bloomberg, microsoft, meta, apple

Level: swe3

Max-Heap Simulation: Negate all values to use Python's min-heap as a max-heap. Repeatedly pop two largest values, push the difference back if non-zero, until one or zero stones remain.

Sorted List Simulation: Maintain a sorted list, popping the two largest and binary-searching to re-insert the difference. Simpler to understand but O(n^2) due to list insertions.

Task Scheduler - Greedy and Heap | Python

Find minimum CPU intervals for task scheduling with cooldown using the math formula and max-heap simulation. Python solutions with full complexity analysis.

Topics: greedy, heap, array

Companies: amazon, google, meta, microsoft, bloomberg, netflix

Level: swe3, senior

Math Formula O(1): The most frequent task creates frames of size n+1. Total frames = max_freq - 1, each with n+1 slots, plus the final group of max-freq tasks. Take max with len(tasks) for the dense case.

Greedy Max-Heap Simulation: Max-heap simulation: each unit of time, pop the highest-frequency task, decrement its count, and put it in a cooldown queue. When cooldown expires, push back to heap. Count idle time implicitly.

Jump Game I - Greedy Reachability | Python

Determine if you can reach the last index using greedy forward and backward scan. O(n) Python solutions with clear explanation for coding interviews.

Topics: greedy, array

Companies: amazon, google, meta, microsoft, bloomberg, apple

Level: swe3, senior

Greedy Forward Scan: Single pass greedy: maintain the farthest reachable index. If the current index exceeds it, the last index is unreachable. Otherwise update the reach and continue.

Greedy Backward Scan: Scan from right to left, updating the goal to the leftmost index that can reach the current goal. If goal reaches index 0, the start can reach the end.

Jump Game II - Minimum Jumps Greedy | Python

Find minimum jumps to reach the last index using greedy BFS-level approach and DP. O(n) Python solutions explained step by step for coding interviews.

Topics: greedy, array

Companies: amazon, google, meta, microsoft, bloomberg, stripe

Level: swe3, senior

Greedy BFS Level Approach: Scan left to right maintaining farthest reachable. When reaching the end of the current jump range, increment jump count and extend the range to farthest. Stop early once last index is reachable.

DP Approach (for reference): For each index, update the minimum jumps needed to reach all positions within its range. Less optimal than greedy but easier to reason about correctness initially.

Gas Station - Circular Greedy | Python

Find the valid starting gas station for a circular route using O(n) greedy and prefix sum approaches. Python solutions with detailed explanation.

Topics: greedy, array

Companies: amazon, google, meta, microsoft, bloomberg, goldman-sachs

Level: swe3, senior

Greedy O(n): Check feasibility with total gas vs cost. Then scan: accumulate net gas, and whenever tank drops negative reset start to next station. The remaining candidate is the answer.

Two-Pass Verification: Compute prefix sums of net gas. The optimal start is just after the position of the minimum prefix sum - this ensures the tank never goes negative when starting there.

Candy Distribution - Two-Pass Greedy | Python

Solve the candy distribution problem using two-pass greedy and one-pass slope tracking. O(n) Python solutions with explanation for coding interviews.

Topics: greedy, array

Companies: amazon, google, meta, apple, bloomberg, microsoft

Level: senior, staff

Two-Pass Greedy: Left pass ensures each child with higher rating than left neighbor gets more candy. Right pass ensures the same for right neighbors. Taking max satisfies both constraints simultaneously.

One-Pass with Slope Tracking: Track ascending and descending slopes. When descending, if the valley is longer than the peak, the peak child needs an extra candy. Complex but O(1) space.

Meeting Rooms I - Can Attend All | Python

Determine if one person can attend all meetings by checking for overlapping intervals after sorting. Easy Python solutions for coding interviews.

Topics: greedy, array

Companies: amazon, google, meta, microsoft, bloomberg, stripe

Level: swe3

Sort and Check: Sort by start time, then verify each meeting starts at or after the previous meeting ends. O(n log n) for sorting, O(n) for the linear scan.

Using all() with zip: Pythonic one-liner using zip to pair consecutive sorted intervals and all() to verify no overlap. Same complexity as the explicit loop but more concise.

Meeting Rooms II - Minimum Rooms Heap | Python

Find the minimum number of conference rooms using heap and sweep line approaches. O(n log n) Python solutions with step-by-step explanation.

Topics: greedy, heap, array

Companies: amazon, google, meta, microsoft, bloomberg, apple

Level: swe3, senior

Min-Heap of End Times: Sort by start time. Maintain a min-heap of end times. For each meeting, if the earliest-ending room is free (end <= start), reuse it; otherwise add a new room.

Sweep Line Two-Pointer: Sort starts and ends separately. Sweep through start events; if an end event precedes a start, a room is freed. Track peak concurrent rooms.

Non-overlapping Intervals - Remove Minimum | Python

Find minimum intervals to remove for non-overlapping set using greedy sort-by-end and DP approaches. O(n log n) Python solutions explained.

Topics: greedy, array

Companies: google, amazon, meta, microsoft, bloomberg, goldman-sachs

Level: swe3, senior

Greedy Sort by End Time: Sort by end time (activity selection). Greedily include intervals whose start >= last kept end. The number of removals = total - kept (maximum non-overlapping set).

DP Approach (LIS-style): Patience sorting variant: maintain a list of smallest end times for chains of length k. Binary search to extend the longest non-overlapping chain. Analogous to LIS with binary search.

Merge Intervals - Sort and Merge | Python

Merge overlapping intervals using sort and linear scan. Two clean Python solutions with O(n log n) complexity, ideal for coding interviews.

Topics: greedy, array

Companies: amazon, google, meta, microsoft, bloomberg, stripe

Level: swe3, senior

Sort and Linear Merge: Sort by start time. Walk through intervals: if the current interval starts before the last merged interval ends, merge by extending the end. Otherwise start a new merged interval.

In-place Merge (stack-style): Use a stack to track merged intervals. For each sorted interval, either extend the top of the stack (overlap) or push a new interval. Clean and interview-friendly framing.

Insert Interval - Binary Search and Merge | Python

Insert a new interval into a sorted non-overlapping list and merge as needed. Three-phase linear scan and binary search Python solutions with complexity analysis.

Topics: greedy, array

Companies: google, amazon, meta, microsoft, bloomberg, apple

Level: swe3, senior

Three-Phase Linear Scan: Three clean phases: skip non-overlapping before, merge all overlapping by expanding newInterval bounds, then append non-overlapping after. No sorting needed since input is pre-sorted.

Binary Search + Merge: Use binary search on the sorted ends and starts arrays to find the overlap range in O(log n). Merge the overlapping block into one interval. List slicing still costs O(n) overall.

Quicksort Partition In-Place | Python Sorting Interview Question

Learn to implement Lomuto and Hoare quicksort partition schemes in Python. Covers in-place partitioning, pivot selection, and recursion for coding interviews.

Topics: sorting, divide-and-conquer, array

Companies: google, amazon, microsoft, meta, bloomberg, adobe

Level: swe2, swe3

Lomuto Partition Scheme: Lomuto scheme picks last element as pivot, maintains a boundary index i for elements smaller than pivot, and scans left to right placing qualifying elements before the boundary.

Hoare Partition Scheme: Hoare scheme uses two converging pointers from both ends and swaps elements that are on the wrong side of the pivot. It performs roughly 3x fewer swaps than Lomuto on average.

Merge Sort Counting Inversions | Python Divide and Conquer Interview

Count array inversions in O(n log n) using merge sort in Python. Essential divide and conquer technique for coding interviews at Google, Amazon, and Goldman Sachs.

Topics: sorting, divide-and-conquer, array

Companies: google, amazon, microsoft, goldman-sachs, stripe, bloomberg

Level: swe3, senior

Merge Sort with Inversion Count: Augment merge sort to count inversions during the merge step. When an element from the right subarray is placed before remaining left elements, those left elements all form inversions with it.

In-place Merge Sort with Count: Index-based merge sort that operates on a shared temp array to avoid repeated list slicing, reducing constant factor overhead while maintaining the same inversion counting logic.

Counting Sort for Bounded Integers | Python Sorting Interview Question

Implement counting sort in Python for bounded integer arrays. Learn the frequency table approach and stable variant used in radix sort for coding interviews.

Topics: sorting, array, hash-map

Companies: amazon, microsoft, adobe, bloomberg, google, meta

Level: swe2, swe3

Standard Counting Sort: Build a frequency table indexed by value offset from minimum, then reconstruct the sorted output by iterating the count table and appending each value the corresponding number of times.

Stable Counting Sort (Cumulative Prefix): Stable variant uses a cumulative prefix sum on the count array to determine exact output positions, then fills the output array in reverse to preserve relative order of equal elements - critical when sorting compound objects by a key.

Radix Sort for Large Integers | Python Sorting Interview Question

Implement LSD radix sort in Python for large integers. Learn digit-by-digit stable sorting with counting sort subroutine for coding interviews.

Topics: sorting, array

Companies: google, amazon, microsoft, stripe, bloomberg, netflix

Level: swe2, swe3

LSD Radix Sort with Counting Sort Subroutine: For each digit position (ones, tens, hundreds, ...), apply a stable counting sort keyed on that digit. LSD processes least significant digit first, and stability ensures earlier-pass orderings are preserved in later passes.

Radix Sort with Base 256 for Speed: Use base 256 (byte-level) instead of base 10 to reduce the number of passes from ~10 to exactly 4 for 32-bit integers, significantly improving the constant factor through better cache utilization.

Bucket Sort for Uniform Distribution | Python Sorting Interview

Implement bucket sort in Python for uniformly distributed floats. Learn O(n) average case sorting for coding interviews at top tech companies.

Topics: sorting, array, hash-map

Companies: amazon, google, meta, microsoft, apple, stripe

Level: swe2, swe3

Standard Bucket Sort: Map each element to a bucket using the formula int(x * n), sort each bucket independently, then concatenate. The average O(1) elements per bucket with uniform input makes inner sorts negligible.

Generalized Bucket Sort for Arbitrary Range: Generalize by computing min and max to normalize any range into [0, num_buckets). The bucket index formula (num - min) / bucket_range scales elements into the bucket space, making this work for arbitrary floating-point ranges.

Kth Largest Element Quickselect | Python Interview Question

Find the kth largest element using quickselect O(n) and min-heap O(n log k) in Python. Classic coding interview question at Google, Amazon, and Meta.

Topics: sorting, divide-and-conquer, array, heap

Companies: google, amazon, meta, microsoft, apple, netflix

Level: swe2, swe3

Quickselect (Average O(n)): Quickselect uses Lomuto partition scheme with random pivot. After each partition, we know the exact sorted position of the pivot. If it equals our target index we are done; otherwise we recurse only into the relevant half.

Min-Heap of Size K (Guaranteed O(n log k)): Maintain a min-heap of size k. For each element, push it and pop the minimum if the heap exceeds size k. The heap root always holds the kth largest seen so far. Preferred when k is small relative to n or when the array is a stream.

Sort Colors Dutch National Flag | Python Two Pointers Interview

Solve Sort Colors using Dutch National Flag three-way partition in Python. Single-pass O(n) O(1) space solution for coding interviews.

Topics: sorting, two-pointers, array

Companies: amazon, google, meta, microsoft, bloomberg, apple

Level: swe2, swe3

Dutch National Flag - One Pass Three Pointers: Dutch National Flag algorithm maintains three regions: [0..low-1] contains all 0s, [low..mid-1] contains all 1s, [high+1..n-1] contains all 2s. The mid pointer scans through the unknown region [mid..high] making decisions based on the current value.

Two-Pass Counting Approach: Count occurrences of 0, 1, and 2, then overwrite the array in order. Simpler to implement but requires two passes over the array. The interviewer usually wants the single-pass DNF solution.

Wiggle Sort Alternating Array | Python Greedy Interview Question

Rearrange an array into wiggle order in O(n) using greedy swaps in Python. In-place alternating valley-peak pattern for coding interviews.

Topics: sorting, greedy, array, two-pointers

Companies: amazon, google, microsoft, meta, bloomberg, stripe

Level: swe2, swe3

Greedy One-Pass O(n): Single left-to-right pass: at even indices ensure current <= next (swap if not), at odd indices ensure current >= next (swap if not). The local correction never invalidates the previous position's invariant because the swap only affects adjacent elements.

Sort Then Interleave: Sort the array first, then swap every pair of adjacent elements at odd positions. After sorting, consecutive equal elements are adjacent, and the pairwise swaps create the alternating pattern without violating the wiggle property.

Find Median from Data Stream | Python Two Heaps Interview Question

Design a MedianFinder using two heaps in Python. O(log n) insertion and O(1) median query for streaming data. Classic hard interview question at FAANG.

Topics: heap, sorting, two-pointers

Companies: google, amazon, meta, microsoft, apple, netflix

Level: swe3, senior

Two Heaps - Max-Heap Lower + Min-Heap Upper: Maintain two heaps where lower (max-heap) holds the smaller half and upper (min-heap) holds the larger half. After each insertion, rebalance heap sizes to differ by at most 1, ensuring the median is always at the heap tops.

Two Heaps with Cleaner Rebalance Logic: Always route new elements through small first to small->large to guarantee the ordering invariant. The rebalance step then simply checks sizes and moves one element if needed. This two-step approach eliminates the need for an explicit comparison check.

Top K Frequent Elements Bucket Sort O(n) | Python Interview

Find top K frequent elements in O(n) using bucket sort in Python. Compare with heap approach O(n log k) for coding interview preparation.

Topics: sorting, hash-map, heap, array

Companies: amazon, google, meta, microsoft, bloomberg, stripe

Level: swe2, swe3

Bucket Sort O(n): Count frequencies with a hash map, then use bucket sort where bucket index equals frequency. Since frequencies range from 1 to n, bucket indices never exceed n. Scan buckets right-to-left (highest to lowest frequency) to collect the top k elements.

Min-Heap of Size K: Count frequencies with a hash map, then use heapq.nlargest to extract the k elements with the highest frequency. The heap internally maintains a size-k structure giving O(n log k) total time - worse than bucket sort but cleaner to write.

Sort Characters by Frequency | Python Hash Map Interview Question

Sort string characters by frequency in O(n) using bucket sort or Counter sort in Python. Classic interview question testing frequency counting and sorting.

Topics: sorting, hash-map, heap, array

Companies: amazon, google, meta, microsoft, adobe, bloomberg

Level: swe2, swe3

Counter + Sorted: Count frequencies with Counter, sort unique characters by descending frequency, then reconstruct the string by repeating each character its frequency count times. Since k <= 128 for ASCII, sorting k characters is effectively O(1).

Bucket Sort O(n): Use bucket sort where bucket[i] collects all characters with frequency i. Scan buckets from high to low frequency and append each character repeated by its bucket index. Avoids the log factor from sorting.

Largest Number from Array of Integers | Python Sorting Interview

Form the largest number from an array of integers using custom comparator sort in Python. Greedy string comparison technique for coding interviews.

Topics: sorting, greedy, array

Companies: amazon, google, meta, microsoft, bloomberg, stripe

Level: swe2, swe3

Custom Comparator Sort: Define a custom comparator that concatenates two strings both ways and picks the order that yields the larger concatenation. Apply this with cmp_to_key, sort descending, then join. This total order is consistent and transitive by the properties of string lexicographic ordering.

Using Bubble Sort with Custom Compare: Bubble sort using the same concatenation comparison. O(n^2) but illustrates the comparator clearly. Only use this for interview explanation - use the cmp_to_key approach in production.

Minimum Arrows to Burst Balloons | Python Greedy Interval Interview

Find minimum arrows to burst all balloons using greedy interval scheduling in Python. Sort by end coordinate for optimal arrow placement.

Topics: sorting, greedy, array

Companies: amazon, google, meta, microsoft, bloomberg, apple

Level: swe2, swe3

Greedy Sort by End: Sort by end coordinate, shoot the first arrow at the end of the first balloon. For each subsequent balloon, if the current arrow position falls within its range we skip it (already burst); otherwise we must fire a new arrow at the end of this balloon, maximizing the chance to catch future overlapping balloons.

Track Minimum End of Overlapping Group: Sort by start coordinate, track the minimum end seen in the current overlapping group. When a new balloon's start exceeds the tracked minimum end, the group is complete and we fire an arrow, starting a new group with the current balloon.

Queue Reconstruction by Height | Python Greedy Sort Interview

Reconstruct a queue by height using greedy sort and insert in Python. Classic O(n^2) greedy problem for coding interviews at Google and Amazon.

Topics: sorting, greedy, array

Companies: google, amazon, meta, microsoft, bloomberg, netflix

Level: swe2, swe3

Sort + Insert at Index K: Sort descending by height (ascending by k for ties). For each person in this sorted order, list.insert(k, person) places them correctly. Because all previously inserted people are taller or equal, the insertion index k directly counts exactly the right number of people ahead.

BIT/Segment Tree for O(n log n): Instead of list.insert (which shifts elements), maintain a result array and find the k-th empty slot for each person. With a Binary Indexed Tree tracking empty slots, this becomes O(n log n). The linear scan version shown here has the same O(n^2) complexity as insert but avoids repeated memory copies.

Hand of Straights Consecutive Groups | Python Greedy Interview

Determine if cards can be arranged into consecutive groups of size W in Python. Greedy frequency map approach for coding interviews.

Topics: sorting, greedy, hash-map, array

Companies: amazon, google, meta, microsoft, stripe, apple

Level: swe2, swe3

Greedy with Sorted Counter: Count card frequencies, sort unique cards, and greedily form groups starting from the smallest available card. The frequency of the smallest card tells us how many groups must start there. We reduce all W consecutive cards by that amount and check none go negative.

Heap-based Greedy: Use a min-heap to always access the smallest remaining card. For each group starting card, attempt to extend W-1 times. Pop cards from the heap only when their count reaches zero. Validate heap front matches expected card when popping.

Advantage Shuffle Greedy Pairing | Python Sorting Interview

Rearrange array A to maximize wins against array B using greedy pairing in Python. Two-pointer and bisect approaches for coding interviews.

Topics: sorting, greedy, two-pointers, array

Companies: google, amazon, microsoft, meta, bloomberg, stripe

Level: swe2, swe3

Greedy with Sorted A and Indexed B: Sort A and B's indices by B values. Use two pointers on B's sorted indices (lo=easiest, hi=hardest). For each A element (smallest first): if it beats the easiest B, assign it there; otherwise waste it on the hardest B. This is the "weakest horse strategy" from Chinese horse racing folklore.

Greedy with SortedList (Bisect): For each B value in descending order, use binary search to find the smallest A that beats it. If found, assign and remove it; otherwise assign the smallest remaining A. Conceptually cleaner but list.pop is O(n); use sortedcontainers.SortedList for O(log n) removal.

Maximum XOR of Two Numbers Trie | Python Bit Manipulation Interview

Find maximum XOR of two array elements using trie or bitwise greedy in Python. O(n) solution with bit-by-bit construction for coding interviews.

Topics: bit-manipulation, divide-and-conquer, hash-map, array

Companies: google, amazon, meta, microsoft, apple, stripe

Level: swe3, senior

Trie-based O(32n): Build a binary trie from MSB to LSB. For each number, traverse the trie greedily choosing the child whose bit is the complement of the current number's bit (maximizing XOR at each position). The XOR accumulates one bit at a time from the most to least significant.

Bitwise Greedy with Sets O(32n): Build the answer bit by bit from MSB. At each step, compute the set of all numbers' prefixes up to the current bit. Try to set the current bit in the result (candidate). Using XOR property a^b=c <=> a^c=b, check if any two prefixes XOR to the candidate. If so, the bit is achievable.

Bitwise AND of Numbers Range | Python Bit Manipulation Interview

Compute bitwise AND of all numbers in a range in O(log n) using common prefix trick in Python. Brian Kernighan bit strip for coding interviews.

Topics: bit-manipulation, array

Companies: amazon, google, microsoft, meta, bloomberg, goldman-sachs

Level: swe2, swe3

Right Shift Until Equal (Common Prefix): Shift both left and right right until they are equal. At this point they share the same bit prefix, and all lower bits get zeroed by the AND. Shift the common value back left by the number of shifts to restore magnitude. Maximum 32 iterations for 32-bit integers.

Brian Kernighan Bit Strip: Use the bit trick x & (x-1) which clears the lowest set bit of x. Repeatedly apply this to right until right <= left. At that point, right holds the common prefix of all numbers in [left, right] because all bits that would differ across the range have been stripped.

Number of 1 Bits Hamming Weight | Python Bit Manipulation Interview

Count set bits using Hamming weight in Python. Brian Kernighan trick, bit shift, and SWAR parallel counting for coding interviews at FAANG.

Topics: bit-manipulation, array

Companies: amazon, google, microsoft, meta, apple, bloomberg

Level: swe2, swe3

Brian Kernighan - Clear Lowest Set Bit: Brian Kernighan's trick: n & (n-1) always clears the lowest set bit (LSB). For example 12 (1100) & 11 (1011) = 8 (1000). Loop until n becomes 0, counting iterations. Runs in O(popcount) iterations - faster than 32 iterations when few bits are set.

Bit Shift + Mask: Three methods: (1) right-shift and check LSB each iteration - always 32 iterations; (2) Python built-in bin().count("1") - fine in interviews but know how it works; (3) SWAR (SIMD Within A Register) parallel counting that processes all 32 bits simultaneously using bitmask arithmetic - used in hardware popcount instructions.

Power of Two Bit Check | Python Bit Manipulation Interview Question

Check if a number is a power of two using O(1) bit trick in Python. n & (n-1) == 0 explained with power of four extension for coding interviews.

Topics: bit-manipulation, array

Companies: amazon, google, microsoft, meta, adobe, bloomberg

Level: swe2

Bit Trick O(1): n & (n-1) clears the lowest set bit. A power of two has exactly one set bit, so after clearing it the result is zero. Combined with n > 0 to exclude zero and negatives, this gives a one-line O(1) solution. The negative check is necessary in Python/Java because negative numbers in two's complement can satisfy n & (n-1) == 0.

Multiple Approaches + Power of 4 Extension: Three approaches: (1) repeated division by 2 until odd - checks if remainder is 1; (2) the elegant bit trick n > 0 and n & (n-1) == 0; (3) floating-point log2 check. Bonus: power of four check requires the single set bit to be at an even position, enforced by masking with 0x55555555 (alternating 1s at even positions).

Thread-Safe Bounded Queue | Python Concurrency Interview

Implement a producer-consumer bounded queue using threading.Condition in Python. Common in system design interviews at Google, Uber, Stripe.

Topics: concurrency, queue, design

Companies: google, amazon, uber, stripe, datadog, snowflake, linkedin

Level: senior, staff

threading.Condition Solution: Use a single Condition wrapping one lock. Producers wait while full; consumers wait while empty. notify_all wakes the other side after each operation.

Two-Condition Solution: Use separate not_full and not_empty Condition objects sharing one lock for clearer semantic signaling between producers and consumers.

Thread-Safe LRU Cache Python | Read-Write Lock Interview

Implement a concurrent LRU cache with a readers-writer lock in Python. Covers OrderedDict, threading, and cache eviction for senior engineering interviews.

Topics: concurrency, caching, hash-table, linked-list, design

Companies: facebook, google, netflix, airbnb, stripe, datadog, linkedin

Level: senior, staff

RWLock with OrderedDict: Implement a readers-writer lock using a counter and two locks. Readers increment a counter; only the first reader acquires the write lock. Writers acquire exclusively.

threading.RLock Simple Version: Use a single reentrant lock for simplicity. Suitable when the read/write ratio does not justify the complexity of a full RW lock.

asyncio Task Manager Python | Coroutine Cancellation Interview

Build an asyncio coroutine task manager with per-task timeouts and graceful cancellation in Python. Essential for senior backend and async systems interviews.

Topics: async-await, concurrency, design

Companies: stripe, datadog, cloudflare, netflix, uber, twitter, snowflake

Level: senior, staff

asyncio.gather with per-task timeout: Wrap each coroutine in asyncio.wait_for with its timeout. Use gather(return_exceptions=True) to collect results and exceptions without stopping on first failure.

asyncio.create_task with cancellation: Create named Task objects so they can be individually cancelled. Use asyncio.wait with FIRST_EXCEPTION or ALL_COMPLETED to control collection behavior.

async HTTP Request Batching Python | asyncio Interview Question

Implement async HTTP request batching with error handling and retries using asyncio in Python. Common in Stripe, Cloudflare, and Datadog engineering interviews.

Topics: async-await, concurrency, design, rate-limiting

Companies: stripe, cloudflare, datadog, netflix, twitter, uber, adobe

Level: senior, staff

Chunked asyncio.gather: Split URL list into chunks of batch_size. For each chunk, use asyncio.gather with return_exceptions=True. Flatten results in order.

Semaphore-controlled concurrency: Use asyncio.Semaphore to cap total concurrent requests rather than strict batches. All requests are submitted at once but semaphore throttles execution.

Async Connection Pool Python | asyncio Semaphore Interview

Build a semaphore-based async connection pool in Python with timeout support and context manager protocol. Common in Snowflake, Databricks, and Stripe interviews.

Topics: async-await, concurrency, design, queue

Companies: snowflake, databricks, stripe, datadog, palantir, airbnb, netflix

Level: senior, staff

asyncio.Queue pool: Pre-create connections and place them in an asyncio.Queue. Acquire pops from the queue (blocks if empty), release pushes back. asynccontextmanager ensures cleanup.

Semaphore + list pool: Use asyncio.Semaphore to gate the number of concurrent users; maintain a list of connections with a lock for thread-safe borrowing.

Token Bucket Rate Limiter Python | System Design Interview

Implement a thread-safe token bucket rate limiter in Python with per-key support. Used in Stripe, Cloudflare, and Twitter API gateway interviews.

Topics: rate-limiting, design, concurrency, object-design

Companies: stripe, cloudflare, twitter, uber, datadog, linkedin, apple

Level: swe3, senior, staff

Time-based refill with lock: Store last_time and current_tokens. On each consume, compute elapsed time, add rate*elapsed tokens (capped at capacity), then check if enough tokens exist.

Async token bucket: Same algorithm but using asyncio.Lock for use in async services. Suitable for FastAPI middleware or aiohttp rate limiting.

Sliding Window Rate Limiter Python | API Rate Limiting Interview

Implement a sliding window rate limiter with deque-based timestamp tracking in Python. Key algorithm for Cloudflare, Stripe, and Twitter API design interviews.

Topics: rate-limiting, design, queue, hash-table

Companies: cloudflare, stripe, twitter, uber, linkedin, datadog, snowflake

Level: swe3, senior, staff

Per-key deque of timestamps: Store request timestamps per key in a deque. On each request, remove timestamps older than window, then check if count < limit. Thread-safe with per-key locks.

Sliding window with sorted list: Use a sorted list and bisect to efficiently find the cutoff index for the window start.

Fixed Window Rate Limiter Python | Rate Limiting Interview

Implement a fixed window rate limiter with atomic counter reset in Python. Simple and widely deployed in internal APIs at LinkedIn, Adobe, and Twitter.

Topics: rate-limiting, design, hash-table, concurrency

Companies: linkedin, apple, adobe, splunk, twitter, uber, stripe

Level: swe3, senior

Window ID + counter dict: Compute window ID as int(time() // window). If the window ID changed since last request, reset counter. Increment and compare against limit.

Per-key RLock with window reset: Use per-key reentrant locks for finer granularity. Useful when many independent keys need concurrent access without contending on a single global lock.

Distributed Rate Limiter Redis Python | System Design Interview

Implement a Redis-backed distributed sliding window rate limiter in Python. Critical for Cloudflare, Stripe, and Datadog distributed systems interviews.

Topics: rate-limiting, design, system-design-coding, concurrency

Companies: cloudflare, stripe, datadog, snowflake, palantir, netflix, uber

Level: senior, staff

Sorted set simulation: FakeRedis implements ZADD, ZREMRANGEBYSCORE, ZCARD as atomic operations under a lock. DistributedRateLimiter uses pipeline: expire old, add new, count, conditionally remove.

Write-Through vs Write-Behind Cache Python | System Design

Implement write-through and write-behind cache strategies in Python. Covers consistency trade-offs critical for Netflix, Airbnb, and Databricks system design interviews.

Topics: caching, design, concurrency, object-design

Companies: netflix, airbnb, stripe, databricks, palantir, datadog, snowflake

Level: senior, staff

Strategy pattern with background flusher: Write-through calls db immediately in put(). Write-behind adds key to dirty set and a background thread periodically flushes dirty keys to db.

Cache Invalidation TTL LRU Event Python | System Design Interview

Implement TTL, LRU, and event-based cache invalidation in Python. Covers the hardest problem in distributed systems for Netflix, Cloudflare, and Stripe interviews.

Topics: caching, design, hash-table, object-design

Companies: netflix, cloudflare, airbnb, stripe, datadog, twitter, linkedin

Level: senior, staff

Combined TTL + LRU + event invalidation: Store (value, expiry) in OrderedDict. On get(), check TTL first. On put(), enforce LRU capacity. invalidate() removes immediately and triggers callbacks for event subscribers.

Read-Through Cache Stampede Protection Python | Interview

Implement a read-through cache with thundering herd protection using per-key locks in Python. Essential for Airbnb, Netflix, and Stripe senior engineering interviews.

Topics: caching, concurrency, design, hash-table

Companies: airbnb, netflix, stripe, datadog, uber, linkedin, snowflake

Level: senior, staff

Per-key locks with double-checked locking: Check cache first. On miss, acquire per-key lock and check again (double-check). Only if still missing, call loader. Other threads for same key wait and then read from cache.

Cache-Aside Pattern Python | Caching Interview Question

Implement the cache-aside pattern in Python with explicit get, set, and invalidate operations. Used at Uber, Twitter, and LinkedIn for scalable caching.

Topics: caching, design, hash-table, object-design

Companies: uber, twitter, linkedin, adobe, splunk, airbnb, datadog

Level: swe3, senior

CacheAsideClient with loader callback: get() checks cache, calls loader(key) on miss, stores result. set() writes directly to cache. invalidate() removes entry. Pattern keeps DB and cache logic decoupled.

Custom JSON Serializer Python | datetime Decimal Enum Interview

Build a JSON serializer for datetime, Decimal, Enum, and UUID in Python. Critical for Stripe, Palantir, and Datadog API serialization interview questions.

Topics: serialization, design, oop, object-design

Companies: stripe, datadog, palantir, adobe, splunk, airbnb, linkedin

Level: swe3, senior

JSONEncoder subclass with type dispatch: Override default() in JSONEncoder to dispatch on type. Use json.loads() with object_hook for deserialization with type hints embedded in the JSON.

Protocol Buffer Encoder Decoder Python | Binary Serialization Interview

Implement a Protocol Buffer encoder and decoder in Python using varint encoding. Covers binary serialization fundamentals for Google, Netflix, and Uber interviews.

Topics: serialization, design, object-design, system-design-coding

Companies: google, netflix, uber, datadog, palantir, stripe, cloudflare

Level: senior, staff

Varint + length-delimited encoding: Wire type 0 for int/bool (varint encoding: 7 bits per byte), wire type 2 for str (length + UTF-8 bytes). Tag = (field_num << 3) | wire_type.

Avro Schema Evolution Python | Schema Compatibility Interview

Simulate Avro schema evolution with backward and forward compatibility checks in Python. Essential for Databricks, Snowflake, and LinkedIn data engineering interviews.

Topics: serialization, design, system-design-coding, object-design

Companies: databricks, snowflake, palantir, linkedin, splunk, datadog, netflix

Level: senior, staff

Schema compatibility checker with projection: Parse field lists into dicts. Check backward: all old required fields exist in new. Check forward: all new required fields exist in old. Deserialize by projecting writer data onto reader schema with defaults.

Observer Pattern Async Python | Event System Design Interview

Implement an async observer pattern event bus in Python with concurrent dispatch and error isolation. Used at Stripe, Datadog, and Netflix for event-driven systems.

Topics: design-patterns, async-await, design, object-design

Companies: stripe, datadog, airbnb, netflix, twitter, uber, adobe

Level: swe3, senior, staff

Async EventBus with concurrent dispatch: Store callbacks in a dict of sets. emit() calls all subscribers concurrently via asyncio.gather. Sync callbacks are wrapped in run_in_executor. Errors are caught and logged per-subscriber.

Command Pattern Undo Redo Python | Design Pattern Interview

Implement the Command pattern for undo/redo in Python. Core design pattern for Adobe, Apple, and collaborative editor system design interviews.

Topics: design-patterns, design, object-design, oop

Companies: adobe, apple, netflix, twitter, linkedin, google, stripe

Level: swe3, senior

Stack-based command history: CommandHistory maintains undo_stack and redo_stack. execute() runs command, pushes to undo_stack, clears redo_stack. undo() pops from undo_stack, calls undo(), pushes to redo_stack.

Strategy Pattern Sort Algorithms Python | Design Pattern Interview

Implement the Strategy pattern with QuickSort, MergeSort, and HeapSort in Python. Classic OOP design pattern interview at Google, Apple, and LinkedIn.

Topics: design-patterns, sorting, oop, object-design

Companies: google, apple, linkedin, adobe, twitter, uber, stripe

Level: swe3, senior

Strategy pattern with multiple implementations: Define SortStrategy ABC. Implement QuickSort, MergeSort, HeapSort as concrete strategies. Sorter delegates to current strategy and allows runtime switching.

Chain of Responsibility Pattern Python | Middleware Pipeline Interview

Implement the Chain of Responsibility pattern for HTTP request processing in Python. Used in Netflix, Stripe, and Cloudflare middleware pipeline design interviews.

Topics: design-patterns, design, object-design, oop

Companies: netflix, stripe, uber, cloudflare, adobe, datadog, twitter

Level: swe3, senior

Linked handler chain: Each Handler holds a _next reference. set_next() enables fluent builder pattern. Concrete handlers check their condition; if passing, call _next.handle() or return True at end of chain.

Builder Pattern SQL Query Builder Python | Design Pattern Interview

Implement a fluent SQL query builder using the Builder pattern in Python. Core ORM design question at Databricks, Snowflake, and Palantir engineering interviews.

Topics: design-patterns, object-design, oop, design

Companies: databricks, snowflake, palantir, stripe, linkedin, google, airbnb

Level: swe3, senior

Fluent builder with clause accumulation: Each method appends to internal clause lists and returns self. build() validates required clauses then joins them in correct SQL order with collected parameters.

Flyweight Pattern Python | Memory Optimization Design Interview

Implement the Flyweight pattern for shared object state in Python. Covers memory optimization at Apple, Adobe, and Google for game engine and text rendering systems.

Topics: design-patterns, object-design, oop, hash-table

Companies: google, apple, adobe, netflix, twitter, linkedin, stripe

Level: swe3, senior

Factory with shared state pool: FlyweightFactory maintains a dict of Flyweight instances keyed by frozen shared state. get_flyweight() creates new only if not present. Clients call operation() with extrinsic state each time.

Proxy Pattern Lazy Loading Python | Design Pattern Interview

Implement virtual, caching, and protection proxies in Python. Common design pattern interview at Netflix, Airbnb, and Stripe for deferred loading and access control.

Topics: design-patterns, object-design, caching, oop

Companies: netflix, airbnb, stripe, palantir, uber, apple, adobe

Level: swe3, senior

Virtual + caching proxy: LazyImageProxy holds filename but not RealImage. On first display(), creates RealImage (expensive) and caches result. Subsequent calls return cached value. AuthProxy wraps another proxy for access control.

Composite Pattern File System Python | Design Pattern Interview

Implement the Composite pattern for a file system tree in Python. Classic design interview at Apple, Google, and Dropbox covering recursive tree operations.

Topics: design-patterns, graph, object-design, oop

Companies: apple, google, adobe, dropbox, linkedin, netflix, airbnb

Level: swe3, senior

Composite with recursive operations: File is a leaf with fixed size. Directory is composite holding children list. size() recursively sums children. search() does DFS. display() shows tree with indentation.

Visitor Pattern AST Traversal Python | Compiler Design Interview

Implement the Visitor pattern for AST traversal with type checker and code generator in Python. Advanced design pattern interview at Google, Palantir, and Databricks.

Topics: design-patterns, graph, object-design, oop

Companies: google, palantir, databricks, apple, stripe, cloudflare, adobe

Level: senior, staff

Double-dispatch visitor with type checker and code gen: Each ASTNode.accept() calls visitor.visit_ClassName(self). TypeChecker returns type strings. CodeGenerator returns Python bytecode-like string. New operations add new Visitor subclass only.

Job Scheduler Python | Priority Queue Dependency Graph Interview

Design a job scheduler with priorities, dependencies, and recurring jobs in Python. Core system design interview at Airbnb, Stripe, and LinkedIn.

Topics: system-design-coding, heap, graph, design, concurrency

Companies: airbnb, uber, stripe, linkedin, datadog, palantir, snowflake

Level: senior, staff

Heap + dependency graph scheduler: Maintain dependency graph and count of unresolved deps per job. When a job completes, decrement dep counts of dependents and enqueue newly ready jobs. Use heapq for priority ordering.

Pub/Sub Message Broker Dead Letter Queue Python | System Design

Implement a pub/sub message broker with retry logic and dead letter queue in Python. Core distributed systems interview at Google, Stripe, and Netflix.

Topics: system-design-coding, queue, design, concurrency

Companies: google, stripe, datadog, netflix, uber, cloudflare, linkedin

Level: senior, staff

Async broker with retry and DLQ: Each subscription has independent delivery state. publish() dispatches to all subs concurrently. Failed deliveries retry with backoff. After max_retries, message moved to DLQ.

Circuit Breaker Pattern Python | Resilience System Design Interview

Implement the circuit breaker pattern with closed, open, and half-open states in Python. Core resilience pattern interview at Netflix, Uber, and Stripe.

Topics: system-design-coding, design, design-patterns, concurrency

Companies: netflix, uber, stripe, cloudflare, datadog, airbnb, twitter

Level: senior, staff

State machine circuit breaker: Track failure count and last_failure_time. CLOSED->OPEN on threshold. OPEN rejects immediately. After timeout, OPEN->HALF_OPEN allows one probe. Probe success: CLOSED; probe failure: OPEN.

API Gateway Python | Auth Rate Limiting Routing System Design

Build an API gateway with authentication, rate limiting, and route-based proxying in Python. Advanced system design coding interview at Cloudflare, Stripe, and Netflix.

Topics: system-design-coding, design, rate-limiting, design-patterns

Companies: cloudflare, stripe, netflix, uber, datadog, airbnb, twitter

Level: senior, staff

Middleware pipeline gateway: Chain auth, rate limiter, and router as middleware. Each middleware returns Response on error or calls next(). Router matches path prefix to registered backend handlers.

Distributed Counter CRDT Python | Eventual Consistency Interview

Implement a G-Counter CRDT for distributed eventual consistency in Python. Core distributed systems interview at Twitter, LinkedIn, and Datadog.

Topics: system-design-coding, design, concurrency, hash-table

Companies: twitter, linkedin, facebook, datadog, snowflake, stripe, cloudflare

Level: senior, staff

G-Counter CRDT: Each node maintains its own count in a dict keyed by node_id. value() returns sum of all entries. merge() takes per-node maximum, making it commutative, associative, and idempotent.

Real-Time Leaderboard Python | Sorted Data Structure Interview

Implement a real-time leaderboard with O(log n) rank queries in Python using SortedList. Common system design interview at Twitter, LinkedIn, and Apple.

Topics: system-design-coding, heap, hash-table, design

Companies: twitter, linkedin, apple, google, adobe, netflix, uber

Level: senior, staff

SortedList leaderboard: Maintain sorted list of (-score, player_id) tuples for desc order. player_scores dict for O(1) score lookup. update removes old entry, inserts new. rank = bisect position + 1.

Notification Service Python | Multi-Channel Dedup Retry Interview

Build a multi-channel notification service with deduplication and retry in Python. Common system design coding interview at Stripe, Airbnb, and Uber.

Topics: system-design-coding, design, concurrency, async-await

Companies: stripe, airbnb, uber, linkedin, datadog, netflix, twitter

Level: senior, staff

Async multi-channel with dedup and retry: Hash-based dedup cache with TTL. Per-channel sender classes implementing common interface. asyncio.gather dispatches to all channels concurrently. Exponential backoff retry per channel.

Feature Flag System Python | Gradual Rollout A/B Testing Interview

Implement a feature flag system with percentage rollout and segment targeting in Python. Used at LinkedIn, Airbnb, and Stripe for safe feature releases.

Topics: system-design-coding, design, hash-table, object-design

Companies: linkedin, airbnb, twitter, stripe, datadog, netflix, uber

Level: senior, staff

Rule-based evaluator with hash bucketing: Sort rules by priority descending. Each rule type: whitelist checks membership, percentage uses stable hash bucket, segment checks user_attrs. First matching rule wins.

Config Management Service Python | Versioned CAS Watcher Interview

Build a versioned config management service with compare-and-swap and hot-reload watchers in Python. Used at Palantir, Stripe, and Datadog for dynamic configuration.

Topics: system-design-coding, design, hash-table, object-design

Companies: palantir, stripe, datadog, airbnb, snowflake, linkedin, uber

Level: senior, staff

Versioned store with watcher notification: Each key maps to a list of (version, value, timestamp) entries. set() checks expected_version for CAS, appends new entry, notifies watchers. get() returns specific version or latest.

Distributed Lock Python | Optimistic Pessimistic Locking Interview

Implement optimistic and pessimistic locking patterns in Python with TTL and CAS semantics. Core distributed systems interview at Stripe, Airbnb, and Snowflake.

Topics: concurrency, system-design-coding, design, hash-table

Companies: stripe, airbnb, uber, snowflake, palantir, databricks, netflix

Level: senior, staff

Combined pessimistic + optimistic lock managers: Pessimistic: per-resource threading.Lock with TTL stored alongside. Lock acquisition spins until available or timeout. Optimistic: version dict with CAS write that raises ConflictError on mismatch.

Workflow Engine DAG Python | Airflow Task Scheduling Interview

Build a DAG-based workflow engine with parallel execution and cycle detection in Python. Core system design interview at Airbnb, Databricks, and Stripe.

Topics: system-design-coding, graph, concurrency, design

Companies: airbnb, stripe, databricks, palantir, linkedin, uber, datadog

Level: senior, staff

Kahn topological + thread pool execution: Build adjacency list and in-degree map. Queue tasks with zero in-degree. Worker threads execute tasks and decrement in-degree of dependents, enqueuing newly ready tasks.

Metrics Collection System Python | Counter Gauge Histogram Interview

Build a metrics collection system with counter, gauge, histogram, and percentile computation in Python. Core APM design interview at Datadog, Splunk, and Netflix.

Topics: system-design-coding, design, heap, sorting

Companies: datadog, splunk, netflix, stripe, cloudflare, uber, linkedin

Level: senior, staff

Registry with reservoir sampling histogram: Counter: atomic increment. Gauge: latest value. Histogram: reservoir sampling (random replacement after reservoir full). Percentile: sort reservoir and index. Thread-safe throughout.

Audit Log System Python | Hash Chain Tamper-Evident Interview

Build an immutable audit log with cryptographic hash chaining in Python. Critical compliance system design at Stripe, Goldman Sachs, and Palantir.

Topics: system-design-coding, design, hash-table, object-design

Companies: stripe, palantir, goldman-sachs, snowflake, datadog, linkedin, airbnb

Level: senior, staff

Hash-chained append-only log: Each entry includes prev_hash computed from previous entry. Entries stored in list (append-only). Query filters applied in Python with pagination. verify() recomputes chain from start.

Thread Pool Implementation Python | Future Graceful Shutdown Interview

Implement a thread pool with Future and graceful shutdown in Python from scratch. Essential concurrency interview at Google, Uber, Netflix, and Stripe.

Topics: concurrency, design, queue, object-design

Companies: google, amazon, uber, stripe, netflix, datadog, linkedin

Level: senior, staff

Queue-based thread pool with Future: Worker threads loop on queue.get(). Submit wraps callable in (fn, args, future) tuple. Future uses threading.Event for blocking result(). Sentinel None signals each worker to exit.

Python Process Pool CPU-Bound | multiprocessing Interview

Master Python's multiprocessing Pool with map, starmap, and apply_async for CPU-bound parallelism. Key interview topic at Databricks, Snowflake, and Google.

Topics: concurrency, design, queue

Companies: databricks, snowflake, palantir, netflix, google, uber, stripe

Level: senior, staff

Multiprocessing Pool patterns: Demonstrate map, starmap, apply_async, imap. Use context manager for cleanup. Show error handling with error_callback. Compare with threading for CPU vs I/O bound tasks.

Async Priority Queue Python | asyncio PriorityQueue Interview

Build an async priority task queue with worker coroutines and graceful shutdown in Python. Used at Stripe, Cloudflare, and Netflix for priority-based task dispatch.

Topics: async-await, concurrency, queue, heap

Companies: stripe, datadog, cloudflare, netflix, uber, twitter, airbnb

Level: senior, staff

asyncio.PriorityQueue with worker coroutines: PriorityQueue stores (priority, seq, fn, args). Worker coroutines loop on get(). Shutdown enqueues sentinel per worker. Results tracked via asyncio.Event per task.

Banker's Algorithm Python | Deadlock Detection Interview

Implement the Banker's Algorithm for deadlock detection and prevention in Python. Core OS and concurrency interview at Google, Uber, and Databricks.

Topics: concurrency, graph, design, system-design-coding

Companies: google, uber, databricks, palantir, snowflake, stripe, netflix

Level: senior, staff

Safety check with need matrix: Compute need = max - allocation. Safety: find process whose need <= work (available). Simulate completion: add allocation to work. If all processes finish, safe. request_resources() tentatively allocates then checks safety.

Dining Philosophers Python | Deadlock Prevention Concurrency Interview

Solve the dining philosophers problem without deadlock using fork ordering in Python. Classic concurrency interview at Google, Uber, and Stripe.

Topics: concurrency, design, object-design

Companies: google, amazon, uber, stripe, netflix, apple, datadog

Level: senior, staff

Fork ordering solution: Each philosopher picks up forks in order min(left,right) first. This breaks the circular wait condition. Even-numbered philosophers pick left first, odd pick right first - equivalent.

Readers-Writers Problem Python | Fair RW Lock Interview

Implement the readers-writers problem with writer-preference fairness in Python. Classic synchronization interview at Google, Netflix, and Datadog.

Topics: concurrency, design, queue

Companies: google, netflix, datadog, stripe, uber, linkedin, apple

Level: senior, staff

Fair RW lock with writer preference: Track active_readers, active_writer, waiting_writers. New readers block if waiting_writers > 0 (writer preference). Writers block while active_readers > 0 or active_writer. Release notifies all blocked parties.

asyncio Producer Consumer Backpressure Python | Streaming Interview

Implement producer-consumer with asyncio bounded queue backpressure in Python. Critical streaming system pattern at Stripe, Netflix, and Cloudflare.

Topics: async-await, concurrency, queue, design

Companies: stripe, datadog, cloudflare, netflix, uber, twitter, linkedin

Level: senior, staff

Bounded queue async pipeline: Producer is async generator yielding items; feeder coroutine puts into bounded queue. Consumers loop on queue.get() with task_done(). queue.join() waits for all items processed before shutdown.

concurrent.futures Python | Futures Promises Interview Patterns

Master Python's concurrent.futures with parallel_map, race, callbacks, and chaining. Essential concurrency patterns for Google, Stripe, and Netflix interviews.

Topics: concurrency, async-await, design

Companies: google, stripe, netflix, datadog, uber, airbnb, linkedin

Level: senior, staff

concurrent.futures patterns: parallel_map uses ThreadPoolExecutor with as_completed for ordered results with per-task timeout. race() submits all, returns first completed. Callbacks for non-blocking notification.

Cache Eviction Policy Simulator Python | LRU LFU FIFO Interview

Simulate and compare LRU, LFU, FIFO, and random cache eviction policies in Python. Practical cache design interview at Netflix, Cloudflare, and Datadog.

Topics: caching, design, hash-table, sorting

Companies: netflix, cloudflare, datadog, airbnb, linkedin, stripe, uber

Level: senior, staff

Multi-policy cache simulator: Each policy implemented as standalone function. LRU=OrderedDict, LFU=heap+counter, FIFO=deque, Random=set. compare_policies() runs all and returns comparison dict.

Bloom Filter Python | Probabilistic Data Structure Interview

Implement a Bloom filter with optimal sizing and double hashing in Python. Used at Google BigTable, Cloudflare, and Netflix for efficient membership testing.

Topics: design, hash-table, system-design-coding, object-design

Companies: google, cloudflare, netflix, datadog, databricks, linkedin, stripe

Level: senior, staff

Bit array bloom filter with double hashing: Compute optimal size m and hash count k from n and p. Use double hashing (h1 + i*h2) for k positions. Bit array stored as bytearray for memory efficiency. Thread-safe with lock.

Time-Series Storage Python | Downsampling Retention Interview

Build a time-series store with downsampling and retention in Python. Core data engineering interview at Datadog, Splunk, and Snowflake.

Topics: system-design-coding, design, sorting, hash-table

Companies: datadog, splunk, netflix, cloudflare, stripe, snowflake, databricks

Level: senior, staff

Sorted list store with downsampling: Store (timestamp, value) sorted by timestamp using bisect for O(log n) insertion. query() slices by time range. downsample groups by interval floor and computes aggregates. Retention: remove on write.

Event Sourcing Python | CQRS Projections System Design Interview

Implement event sourcing with immutable event log and projections in Python. Advanced system design interview at Stripe, Palantir, and LinkedIn.

Topics: system-design-coding, design, object-design, hash-table

Companies: stripe, palantir, airbnb, linkedin, netflix, databricks, uber

Level: senior, staff

Event store with projection registry: Event store appends with auto-incrementing version. Aggregates expose apply(event) for each event type. Projections are registered callbacks updated on every append. rebuild() replays from version 0.

CQRS Python | Command Query Segregation System Design Interview

Implement CQRS with separate read and write models and eventual consistency in Python. Advanced system design interview at Stripe, Airbnb, and LinkedIn.

Topics: system-design-coding, design, object-design, hash-table

Companies: stripe, airbnb, linkedin, palantir, databricks, netflix, uber

Level: senior, staff

Command/Query buses with projections: CommandBus dispatches commands to handlers that validate, mutate write model, emit events. QueryBus reads from projection dict. Event bus links write side to projection updates maintaining eventual consistency.

Saga Pattern Python | Distributed Transaction Compensation Interview

Implement the Saga pattern with compensating transactions in Python. Core distributed systems interview at Stripe, Airbnb, and Uber for multi-service orchestration.

Topics: system-design-coding, design, design-patterns, object-design

Companies: stripe, airbnb, uber, linkedin, netflix, palantir, datadog

Level: senior, staff

Orchestration-based saga with compensation stack: Execute steps sequentially. Push each successful step onto compensation stack. On failure, pop and execute compensations in reverse order. Track state machine transitions.

Simple ORM Python | SQLite Metaclass Object-Relational Mapper Interview

Build a minimal ORM mapping Python classes to SQLite tables with CRUD operations. Advanced Python metaclass and SQL generation interview at Palantir, Stripe, and Airbnb.

Topics: design, object-design, oop, design-patterns

Companies: palantir, stripe, airbnb, databricks, linkedin, google, netflix

Level: senior, staff

Metaclass ORM with SQLite backend: ModelMeta collects Field instances from class body into _fields dict. Model.create() generates INSERT. Model.filter() generates SELECT WHERE. Model.save() generates UPDATE. Uses sqlite3 for actual execution.

Connection Multiplexer Python | HTTP2 gRPC Stream Multiplexing Interview

Implement TCP connection multiplexing with stream IDs in Python. Models HTTP/2 and gRPC internals for Cloudflare, Netflix, and Stripe system design interviews.

Topics: system-design-coding, design, concurrency, queue

Companies: cloudflare, stripe, netflix, uber, datadog, palantir, google

Level: senior, staff

Header-based stream multiplexer: Assign stream_id per send() call. Frame = struct.pack('!II', stream_id, len) + payload. Background reader parses frames and routes to per-stream asyncio.Queue. send() awaits its queue for the response.

Idempotency Keys Python | Request Deduplication API Safety Interview

Implement request deduplication with idempotency keys in Python. Critical API safety pattern at Stripe, Airbnb, and Uber for payment and booking systems.

Topics: system-design-coding, design, hash-table, caching

Companies: stripe, airbnb, uber, linkedin, netflix, cloudflare, datadog

Level: swe3, senior, staff

Per-key lock with response cache: Check if key exists and not expired: return cached response. If in-flight, wait using per-key Event. If new, execute fn(), store result with expiry, signal waiters. Thread-safe.

CDN Cache Hierarchy Python | Multi-Tier Caching System Design Interview

Simulate a 3-tier CDN with origin, regional, and leaf nodes in Python. Core content delivery interview at Cloudflare, Netflix, and Apple.

Topics: system-design-coding, caching, design, graph

Companies: cloudflare, netflix, akamai, stripe, datadog, apple, uber

Level: senior, staff

3-tier CDN simulation with LRU + TTL: CacheNode holds LRU cache with TTL. get() checks local, then parent recursively. On parent hit, populate local cache. Origin always has the content. Stats track hits and misses per node.

Task Dependency Graph Executor Python | DAG Parallel Execution Interview

Build an async task dependency executor with parallel execution and result passing in Python. Core system design at Airbnb Airflow, Databricks, and Stripe.

Topics: graph, concurrency, async-await, system-design-coding

Companies: airbnb, databricks, stripe, palantir, uber, linkedin, snowflake

Level: senior, staff

Async topological executor with result passing: Build adjacency list and dep count map. Use asyncio.Queue of ready tasks. Worker coroutine executes task with dep_results dict, decrements dep counts of dependents, enqueues newly ready ones.

Versioned Key-Value Store Python | MVCC Snapshot Isolation Interview

Build a versioned key-value store with MVCC and snapshot isolation in Python. Core database internals interview at Palantir, Snowflake, and Google.

Topics: system-design-coding, design, hash-table, sorting

Companies: palantir, snowflake, databricks, stripe, google, linkedin, datadog

Level: senior, staff

MVCC versioned store with snapshot transactions: Global version counter incremented on each put. Per-key list of (version, value) sorted by version. Binary search for point-in-time reads. Transaction holds snapshot version; reads see only versions <= snapshot.

Shopping Cart Service Python | Inventory Discount Checkout Interview

Build a shopping cart with inventory reservation and discount codes in Python. System design interview at Amazon, Stripe, and Airbnb covering concurrency and checkout logic.

Topics: system-design-coding, design, object-design, oop

Companies: amazon, stripe, airbnb, apple, linkedin, uber, adobe

Level: swe3, senior

Cart with optimistic inventory checkout: Cart holds items list and applied discount. checkout() validates discount, checks inventory atomically for all items, decrements on success or rolls back on partial failure. Returns detailed order.

Recommendation Engine Python | Collaborative Filtering Cosine Similarity Interview

Build a collaborative filtering recommendation engine with cosine similarity in Python. Core ML systems interview at Netflix, Spotify, and LinkedIn.

Topics: system-design-coding, design, hash-table, sorting

Companies: netflix, spotify, linkedin, amazon, twitter, airbnb, uber

Level: senior, staff

User-user collaborative filtering with cosine similarity: Store sparse ratings as dict of dicts. Cosine similarity between users based on co-rated items. For target user, find K most similar users, aggregate their ratings on unseen items (weighted by similarity).

Trapping Rain Water - Two Pointers + Stack | Python Q741

Solve Trapping Rain Water in Python with two-pointer O(1) space and monotonic stack O(n) approaches. Hard Google/Amazon interview question with full solutions.

Topics: two-pointers, monotonic-stack, array

Companies: google, amazon, meta, microsoft, bloomberg, adobe, uber

Level: senior, staff

Two Pointers O(1) Space: Two pointers converge inward. Always process the side with the smaller max because the other side guarantees at least that much water can be held. Track running left_max and right_max and accumulate water when current height is below the running max.

Monotonic Stack: Maintain a monotonic decreasing stack of indices. When a taller bar is found, pop the stack top as a valley floor, compute the water layer between the new bar and the new stack top as left wall, accumulate width * bounded_height.

Prefix/Suffix Max Arrays: Precompute left_max[i] and right_max[i] arrays in two passes. For each position, water trapped = min(left_max, right_max) - height[i]. Simple and intuitive but uses O(n) extra space.

Largest Rectangle in Histogram - Monotonic Stack | Python Q742

Find the largest rectangle in a histogram using monotonic stack O(n) in Python. Classic hard interview question for Google, Amazon, Meta with complete solutions.

Topics: monotonic-stack, array, divide-and-conquer

Companies: amazon, google, meta, microsoft, bloomberg, uber, adobe

Level: senior, staff

Monotonic Stack: Maintain a monotonically increasing stack of indices. When a shorter bar is found, pop taller bars and compute the rectangle they could form: width spans from current position back to the new stack top. Sentinel 0 ensures all bars are processed.

Divide and Conquer: Recursively split on the minimum-height bar. The minimum bar constrains the full-width rectangle. Recurse left and right of it for potentially taller but narrower rectangles. Use a sparse table for O(1) range minimum queries to achieve guaranteed O(n log n).

Maximal Rectangle Binary Matrix - Histogram DP | Python Q743

Find the maximal rectangle of 1s in a binary matrix using histogram and monotonic stack approach in Python. Hard interview question with O(m*n) solution.

Topics: monotonic-stack, dynamic-programming, array

Companies: google, amazon, microsoft, meta, bloomberg, apple, linkedin

Level: senior, staff

Histogram per Row with Monotonic Stack: For each row, update a heights array: increment if cell is "1", reset to 0 if "0". Run the largest rectangle in histogram algorithm on heights after each row. Overall time is O(m*n) since each histogram scan is O(n).

DP with Left, Right, Height Arrays: Track height, left boundary, and right boundary for each column. Left is the leftmost column that can extend a rectangle of current height; right is the rightmost. Area = height * (right - left). Update all three arrays in O(n) per row.

Count Ways to Climb N Stairs with 1 2 3 Steps | Python Q744

Count distinct ways to reach n stairs taking 1, 2, or 3 steps in Python. Tribonacci DP with O(1) space optimization. Classic interview question.

Topics: dynamic-programming, math, array

Companies: amazon, microsoft, google, apple, adobe, oracle, shopify

Level: swe3, senior

Bottom-Up DP O(n) Space: Standard tribonacci DP. dp[i] = number of ways to reach stair i. Recurrence: dp[i] = dp[i-1] + dp[i-2] + dp[i-3] because last step was 1, 2, or 3.

Space-Optimized O(1): Keep only the last three values. Roll them forward: new_c = a + b + c, then shift a=b, b=c, c=new_c. Avoids the full DP array while maintaining correctness.

Memoized Recursion: Top-down memoized recursion. Each subproblem computed once. The lru_cache handles memoization automatically. Clean and easy to reason about correctness.

Count Distinct Subsequences of S in T | Python Q745

Count distinct subsequences of string s matching string t using 2D and space-optimized DP in Python. Hard Google/Meta interview question.

Topics: dynamic-programming, string

Companies: google, amazon, meta, microsoft, bloomberg, goldman-sachs, stripe

Level: senior, staff

2D DP: dp[i][j] = number of ways to form t[:j] from s[:i]. Base: dp[i][0]=1 (empty t always matched). Transition: always carry forward dp[i-1][j]; if characters match, also add dp[i-1][j-1] for using s[i-1].

Space-Optimized 1D DP: Compress DP to 1D by processing s character by character. Iterate j right-to-left to ensure each s[i] is only used once per position. dp[j] accumulates ways to form t[:j].

Minimum Cost to Cut a Stick - Interval DP | Python Q746

Solve minimum cost to cut a stick using interval DP in Python. Hard Google/Amazon interview question similar to matrix chain multiplication.

Topics: dynamic-programming, divide-and-conquer, array

Companies: google, amazon, meta, microsoft, stripe, bloomberg, airbnb

Level: senior, staff

Interval DP Bottom-Up: Sort cuts with 0 and n as boundaries. dp[i][j] = minimum cost to perform all cuts strictly between cuts[i] and cuts[j]. For each interval length, try every internal cut point k. Cost = sub-interval costs + current stick length (cuts[j] - cuts[i]).

Memoized Top-Down: Top-down with memoization. dp(i, j) computes minimum cost for cuts strictly between positions cuts[i] and cuts[j]. Base case: adjacent boundaries need no cuts. Try all internal splits and pick minimum.

Strange Printer Minimum Turns - Interval DP | Python Q747

Solve Strange Printer minimum turns using interval DP in Python. Hard Google/Amazon interview question with O(n^3) solution explained.

Topics: dynamic-programming, string

Companies: google, amazon, meta, microsoft, bloomberg, apple, stripe

Level: senior, staff

Interval DP: dp[i][j] = min turns to print s[i..j]. Start with printing s[i] separately (+1). When s[k] == s[i] for k > i, we can extend the first print to cover position k for free, merging dp[i+1][k] (middle) + dp[k][j] (right part including k).

Memoized Recursion: Top-down memoized recursion. For interval [i, j], default is dp(i+1, j)+1. When s[k]==s[i], we handle positions i and k in the same print turn, reducing total turns. Cache ensures each subproblem is solved once.

Arithmetic Slices II Subsequence DP | Python Q748

Count all arithmetic subsequences using DP with hash maps in Python. Hard Google interview question with O(n^2) solution using difference dictionary.

Topics: dynamic-programming, array, math

Companies: google, amazon, meta, bloomberg, stripe, microsoft, linkedin

Level: senior, staff

DP with Hash Maps: For each pair (j, i), compute difference d. dp[i][d] counts arithmetic subsequences of length >= 2 ending at index i with difference d. Adding dp[j][d] to answer counts the new length-3+ subsequences formed by appending nums[i]. +1 accounts for the new pair (j, i) as a length-2 sequence.

Brute Force O(n^3) for Verification: Brute force triple loop checks all (i, j, k) triplets. This only counts length-3 arithmetic subsequences correctly. For subsequences of all lengths >= 3, the DP with hash maps approach is required. This solution is shown for illustration of the counting principle.

Count Palindromic Subsequences of Length 5 | Python Q749

Count palindromic subsequences of length 5 using DP with prefix character pair counts in Python. Hard interview question with modular arithmetic.

Topics: dynamic-programming, string, math

Companies: google, amazon, meta, microsoft, goldman-sachs, bloomberg, stripe

Level: senior, staff

DP with Prefix Character Pair Counts: For each middle position k, compute 2-character subsequence counts for the left part (pairs ab where a < b < k) and right part (pairs ab where k < a < b, reversed as ba). Multiply matching outer/inner pairs and sum over all character combinations. Works because length-5 palindrome = outer pair + inner pair + middle.

Brute Force O(n^5): Enumerate all 5-index subsequences (i,j,k,l,m) in order and check the palindrome condition: s[i]==s[m] and s[j]==s[l] (center k is unconstrained). Correct but too slow for large inputs. Shown to validate the prefix-DP approach for small test cases.

K-th Symbol in Grammar - Recursive Bit Trick | Python Q750

Find the k-th symbol in grammar using recursion and bit manipulation in Python. Medium Google interview question with O(1) bit-count solution.

Topics: math, divide-and-conquer, bit-manipulation

Companies: google, amazon, meta, microsoft, apple, adobe, shopify

Level: swe3, senior

Recursive Bit Flip: The k-th element of row n is generated from the ceil(k/2)-th element of row n-1. If k is odd, same value as parent. If k is even, flipped value. Recurse until row 1 which is always 0.

Bit Count in k-1: Mathematical insight: the k-th symbol (0-indexed k-1) equals the number of 1-bits in k-1 modulo 2. This follows from the fractal structure where each flip corresponds to a 1-bit in the binary representation of the position.

24 Game Backtracking All Combinations | Python Q751

Solve the 24 Game by backtracking all number pairs and operations in Python. Hard Google/Meta interview question with floating-point handling.

Topics: backtracking, math, divide-and-conquer

Companies: google, amazon, meta, microsoft, apple, bloomberg, uber

Level: senior, staff

Backtracking on Number Pairs: At each step, pick any two numbers, apply an operation, and recurse on the resulting list of 3 numbers. This implicitly handles all parenthesizations. Try all ordered pairs and all 4 operations. Use epsilon comparison for floating-point results.

Brute Force All Permutations and Operators: Enumerate all 24 permutations of cards and all 64 operator combinations. Evaluate left-to-right and with alternative groupings. The recursive pair approach is more complete for all parenthesizations; this shows the explicit enumeration approach.

Expression Add Operators Backtracking | Python Q752

Add operators to a number string to reach target using backtracking in Python. Hard Google/Amazon interview question with multiplication precedence tracking.

Topics: backtracking, math, string

Companies: google, amazon, meta, microsoft, bloomberg, stripe, uber

Level: senior, staff

Backtracking with Mult Tracking: Backtrack by trying each possible number from current position. Track cur_val (accumulated value) and last_val (the last multiplied operand). For multiplication, undo the last addition/subtraction and apply: cur - last + last * n. This handles operator precedence without expression tree parsing.

Backtracking with String Building: Alternative implementation using explicit dfs function with cleaner parameter names. Same algorithm: track path (expression string), value (current evaluated result), and last (last multiplication operand for precedence handling). The last parameter enables O(1) undoing of the last addition when multiplying.

Palindrome Partitioning II Minimum Cuts DP | Python Q753

Find minimum palindrome partition cuts using DP in Python. Hard Google/Amazon interview question with O(n^2) time and O(n) space solution.

Topics: dynamic-programming, string

Companies: google, amazon, meta, microsoft, bloomberg, goldman-sachs, apple

Level: senior, staff

DP with Palindrome Precomputation: Precompute is_pal[i][j] for all substrings using DP. Then compute dp[i] = min cuts for s[0..i]. If s[0..i] is itself a palindrome, dp[i]=0. Otherwise try all splits j where s[j..i] is a palindrome: dp[i] = min(dp[j-1]+1).

Expand Around Centers O(n^2) One Pass: Expand palindromes around each center. For each palindrome s[l..r] found, update dp[r+1] = min(dp[r+1], dp[l]+1). This uses a 1D dp array with sentinel dp[0]=-1, achieving O(n) space while remaining O(n^2) time.

Scramble String Memoized DP | Python Q754

Determine if one string is a scramble of another using memoized recursion and 3D DP in Python. Hard Google/Amazon interview question.

Topics: dynamic-programming, string, divide-and-conquer

Companies: google, amazon, meta, microsoft, bloomberg, apple, adobe

Level: senior, staff

Memoized Recursion: Memoize on pairs of substrings. For each split point k, check both no-swap and swap cases. Prune early with Counter comparison which is O(26). The string-keyed cache stores O(n^2) pairs each of length up to n, giving O(n^4) total states.

3D DP Bottom-Up: Bottom-up 3D DP. dp[len][i][j] = True if s1[i:i+len] is a scramble of s2[j:j+len]. Fill by increasing length. For each split k, check no-swap and swap variants using precomputed shorter subproblem answers.

Zuma Game Minimum Moves Interval DP | Python Q755

Solve Zuma game minimum moves using DFS with memoization in Python. Hard Google interview question with string compression and state caching.

Topics: dynamic-programming, string, divide-and-conquer

Companies: google, amazon, meta, microsoft, bloomberg, apple, stripe

Level: senior, staff

DFS with Memoization and String Compression: Compress board into runs. For each run, try completing it to 3 using hand balls. Use memoization on (board_state, hand_counts). After removing a completed group, recursively clean cascading removals. The state space is bounded by the small board/hand sizes.

BFS State Exploration: BFS over (board_state, available_hand) states. Enqueue initial state and explore all valid insertions level by level. First time we reach empty board gives minimum moves. Visited set prevents reprocessing the same (board, hand) configuration. Equivalent to DFS+memoization but explores breadth-first.

Strange Printer II Color Dependencies Topological Sort | Python Q756

Determine if a color grid is printable using topological sort of color dependencies in Python. Hard Google interview question.

Topics: graph, dynamic-programming, array

Companies: google, amazon, meta, microsoft, bloomberg, stripe, linkedin

Level: senior, staff

Bounding Box + Topological Sort: Find the bounding rectangle of each color. Within each color's bounding box, any cell of a different color creates a dependency: the outer color must be printed first, then the inner color on top. Build a directed graph of these dependencies and check for cycles using Kahn's topological sort.

DFS Cycle Detection: Same bounding box and dependency graph construction, but cycle detection uses DFS coloring (WHITE/GRAY/BLACK) instead of Kahn's BFS. GRAY marks nodes currently in the recursion stack; finding a GRAY neighbor indicates a back edge (cycle). Returns False if any cycle is found.

Cat and Mouse Game Minimax DP | Python Q757

Solve Cat and Mouse game using backward induction BFS minimax in Python. Hard Google staff-level interview question with game state graph.

Topics: dynamic-programming, graph, math

Companies: google, amazon, meta, microsoft, bloomberg, apple, stripe

Level: staff

Backward Induction BFS: Backward induction on the game state graph (mouse_pos, cat_pos, turn). Initialize terminal states (mouse at 0 = mouse wins, cat at mouse = cat wins). Propagate backward: a state is winning for the current player if any successor is winning; it is losing if all successors are losing (tracked via degree countdown). Unresolved states are draws.

Forward DP with Iterative Relaxation: Alternative formulation of the same backward induction: identifies the moving player at each parent state and checks whether the propagated result is a win for them (immediate coloring) or reduces their degree (all moves lead away from winning). Equivalent correctness to the first solution.

Maximum Score from Multiplications DP | Python Q758

Maximize score from pick-left or pick-right multiplications using interval DP in Python. Hard Amazon/Google interview question with O(m^2) solution.

Topics: dynamic-programming, array

Companies: amazon, google, meta, microsoft, bloomberg, stripe, airbnb

Level: senior, staff

Top-Down Memoized DP: State: (operation_index i, left_picks count). right_picks = i - left_picks. At each state, choose to pick from the left (nums[left]) or right (nums[n-1-right]). Maximize over both choices. The state space is O(m^2) since left <= i <= m.

Bottom-Up DP: Fill DP table bottom-up from operation m-1 down to 0. dp[i][left] stores max score starting at operation i with left elements taken from the left side. Process in reverse to avoid needing future values.

Minimum Refueling Stops Greedy Heap DP | Python Q759

Find minimum refueling stops using greedy max-heap and DP approaches in Python. Hard Amazon/Google interview question with two O(n log n) and O(n^2) solutions.

Topics: dynamic-programming, greedy, heap

Companies: amazon, google, meta, microsoft, bloomberg, uber, airbnb

Level: senior, staff

Greedy with Max Heap: Drive forward, adding each station's fuel to a max-heap as we pass it. When we run out of fuel, greedily take the largest available fuel from the heap (as if we had stopped there retroactively). Count stops taken. If heap is empty and still short, return -1.

DP on Number of Stops: dp[k] = maximum distance reachable using exactly k refueling stops. For each station, if we can reach it (dp[k] >= pos), we can add its fuel: dp[k+1] = max(dp[k+1], dp[k]+fuel). Traverse k in reverse to prevent using the same station twice. Return the first k where dp[k] >= target.

Split Array Largest Sum Binary Search DP | Python Q760

Minimize the largest subarray sum by splitting into k parts using binary search in Python. Hard Google/Amazon interview question with two solutions.

Topics: binary-search, dynamic-programming, greedy

Companies: google, amazon, meta, microsoft, bloomberg, stripe, linkedin

Level: senior, staff

Binary Search + Greedy Check: Binary search between max(nums) (minimum possible largest sum: all in one group) and sum(nums) (maximum: one group). For each mid, greedily check if we can form at most k subarrays where each sums at most mid. If yes, try smaller; if no, need larger.

Dynamic Programming: dp[i][j] = minimum largest subarray sum when splitting nums[0..i-1] into j parts. For each split point p, the last subarray is nums[p..i-1] with sum prefix[i]-prefix[p]. Take max with dp[p][j-1] and minimize over all p.

Dungeon Game Reverse DP Minimum Health | Python Q761

Find minimum initial health for dungeon game using reverse bottom-up DP in Python. Hard Amazon/Google interview question with space-optimized solution.

Topics: dynamic-programming, array, divide-and-conquer

Companies: amazon, google, meta, microsoft, bloomberg, apple, netflix

Level: senior, staff

Reverse DP from Bottom-Right: Fill DP table from bottom-right. dp[i][j] = minimum health needed entering cell (i,j) to guarantee reaching princess. From (i,j) you go right or down, so need = min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j]. Take max with 1 since health can never be 0 or negative.

Space-Optimized 1D DP: Compress DP to a single row by processing bottom to top, right to left. dp[j] represents the minimum health needed at column j for the current row, reusing the array in-place. Requires careful handling of the last row and column boundary conditions.

Maximal Square DP Binary Matrix | Python Q762

Find the largest square of 1s in a binary matrix using DP in Python. Medium Amazon/Google interview question with O(mn) time and O(n) space solutions.

Topics: dynamic-programming, array, math

Companies: amazon, google, meta, microsoft, apple, bloomberg, adobe

Level: swe3, senior

2D DP: dp[i][j] = side of largest all-1 square with bottom-right at (i,j). The minimum of three neighbors limits how large the square can be: the left, top, and diagonal constraint each independently bound the square size. The recurrence computes optimal side in O(1) per cell.

Space-Optimized 1D DP: Use a 1D dp array and a prev variable to track the diagonal predecessor (dp[i-1][j-1]). Before updating dp[j], save it as the new prev for the next iteration. This reduces space from O(mn) to O(n) while maintaining correctness.

Count Submatrices with All Ones DP | Python Q763

Count all-ones submatrices using height DP and monotonic stack in Python. Medium Google/Amazon interview question with O(mn) optimal solution.

Topics: dynamic-programming, array, monotonic-stack

Companies: google, amazon, meta, microsoft, bloomberg, adobe, linkedin

Level: swe3, senior

Height Array + Row DP: For each row, compute height[j] = number of consecutive 1s above and including current row in column j. For each ending column j, scan left tracking the minimum height seen. Each minimum height value contributes that many submatrices ending at (i, j) with that height.

Monotonic Stack O(mn): Use a monotonic stack to track (height, count) pairs as we scan each row's heights. When a shorter height is encountered, merge taller segments. Maintain row_sum = sum of contributions of all heights in the stack. After processing each column, add row_sum to answer. This gives O(n) per row.

Cherry Pickup Two-Robot Simultaneous DP | Python Q764

Maximize cherry pickup with two simultaneous robot traversals using 3D DP in Python. Hard Google/Amazon interview question with diagonal state compression.

Topics: dynamic-programming, array, divide-and-conquer

Companies: google, amazon, meta, microsoft, bloomberg, stripe, apple

Level: senior, staff

3D DP Simultaneous Two Robots: Two robots move simultaneously from (0,0) toward (n-1,n-1). At each step, both are on the same diagonal (r1+c1 = r2+c2 = t), so the state is (r1, c1, r2) with c2 derived. Collect cherries from both cells (count once if same cell). Try all 4 move combinations and take max. Return 0 if no valid path exists.

Bottom-Up 3D DP: Bottom-up DP iterating over diagonal steps t. At each step t, both robots are on the same diagonal (r+c=t). Iterate over all valid (r1, r2) pairs with r1 <= r2. Transition from all 4 combinations of previous (r1, r2) moves. Reduces top-down recursion to an iterative table fill.

Knight Dialer DP Phone Pad Paths | Python Q765

Count distinct phone numbers dialed by knight moves using DP in Python. Medium Google/Amazon interview question with O(n) and matrix exponentiation solutions.

Topics: dynamic-programming, math, array

Companies: google, amazon, meta, microsoft, bloomberg, apple, linkedin

Level: swe3, senior

DP with Adjacency List: Precompute which digits a knight can jump to from each digit. Start with dp[digit]=1 (one way to start at any digit). Each step, accumulate counts by propagating to reachable neighbors. After n-1 steps, sum all counts. Only O(1) space for the 10-element dp array.

Matrix Exponentiation for Very Large n: Build a 10x10 transition matrix T where T[i][j]=1 if knight can jump from i to j. Raise T to the (n-1)th power using fast matrix exponentiation. Sum all entries of the resulting matrix for the total count. Useful when n is astronomically large.

Soup Servings Probability DP | Python Q766

Calculate soup serving probability using DP with convergence optimization in Python. Medium Google interview question with mathematical insight.

Topics: dynamic-programming, math

Companies: google, amazon, meta, microsoft, bloomberg, stripe, goldman-sachs

Level: senior, staff

Scaled DP with Early Convergence: Scale all quantities by 25 to reduce state space. Use memoized recursion where dp(a,b) returns probability A empties first or 0.5 for simultaneous. Operations become (4,0), (3,1), (2,2), (1,3) in scaled units. For n >= 4800, return 1.0 as probability converges due to A being consumed faster on average.

Bottom-Up DP with Scaling: Forward DP propagating probabilities from (m, m) downward. For each state (a, b) with probability p, distribute p/4 to each of the 4 resulting states. When a state empties A (a=0), accumulate to result with weight 1.0 (or 0.5 if both zero). Equivalent to the memoized recursion but computed forward.

Frog Jump River Cross DP | Python Q767

Determine if a frog can cross a river using DP with hash map in Python. Hard Amazon/Google interview question with jump constraint tracking.

Topics: dynamic-programming, array, binary-search

Companies: amazon, google, meta, microsoft, bloomberg, apple, stripe

Level: senior, staff

DP with Hash Map: Create a dictionary mapping each stone to the set of jump sizes that can land on it. Start at stone 0 with jump 0. For each stone and each reachable jump size k, try jumps of k-1, k, k+1 to extend the path. The last stone is reachable if its jump set is non-empty.

BFS with Visited Set: BFS over states (position, last_jump). Explore k-1, k, k+1 jumps from each position. Use visited set to avoid reprocessing same states. Returns True if target stone is reached.

Integer Break DP Maximize Product | Python Q768

Maximize product of integer parts using DP and greedy math in Python. Medium Google/Amazon interview question with O(1) mathematical solution.

Topics: dynamic-programming, math, greedy

Companies: google, amazon, microsoft, meta, apple, bloomberg, adobe

Level: swe3, senior

Dynamic Programming: dp[i] = max product from breaking integer i. For each i, try all splits j and (i-j). The right part (i-j) can either stay as is (for product j*(i-j)) or be further broken (j*dp[i-j]). Take the max over all splits.

Greedy Math O(1): Mathematical insight: breaking into 3s is always optimal (3/3 > 2/2 > 1/1 in terms of product per unit). Avoid 1s. Handle remainder: if n%3==0, all 3s; if n%3==1, replace one 3 with two 2s (3+1 -> 2+2 is better productwise 4 vs 3); if n%3==2, append one 2.

Russian Doll Envelopes 2D LIS Patience Sort | Python Q769

Find maximum Russian doll envelope nesting using 2D LIS and patience sort in Python. Hard Google/Amazon interview question with O(n log n) solution.

Topics: dynamic-programming, binary-search, divide-and-conquer

Companies: google, amazon, meta, microsoft, bloomberg, apple, uber

Level: senior, staff

Sort + LIS with Binary Search O(n log n): Sort envelopes by width ascending; for equal widths, sort by height descending. This ensures that among envelopes of the same width, only one can appear in the LIS (since heights are decreasing for same width). Apply patience-sort LIS on heights only using binary search. The result is the longest chain of nested envelopes.

DP O(n^2): Standard LIS DP on sorted envelopes. dp[i] = longest chain ending at envelope i. For each i, check all j < i where both dimensions are strictly smaller. O(n^2) - works for smaller inputs but TLEs for n=10^5.

Make Array Strictly Increasing DP Binary Search | Python Q770

Find minimum replacements to make array strictly increasing using DP with binary search in Python. Hard Google interview question with dict-based state.

Topics: dynamic-programming, binary-search, array

Companies: google, amazon, meta, microsoft, bloomberg, stripe, apple

Level: senior, staff

DP with Dict and Binary Search: DP where state is a dictionary mapping the last value placed to the minimum operations. For each element in arr1, either keep it (if it maintains strictly increasing) or replace it with the smallest valid element from sorted arr2 using binary search. Propagate the minimum operation count for each reachable last value.

DP with Sorted Array and Index Tracking: Same DP with dictionary but with cleaner variable naming and explicit sorting + deduplication of arr2 upfront. For each element in arr1, maintain a dictionary of {last_value: min_ops}. Use bisect to find optimal replacement value in O(log m). This formulation is easier to reason about correctness for interviews.

Minimum Distance Two-Finger Keyboard DP | Python Q771

Find minimum typing distance with two fingers on keyboard using DP in Python. Hard Google interview question with O(n) space-optimized solution.

Topics: dynamic-programming, string, math

Companies: google, amazon, meta, microsoft, bloomberg, apple, linkedin

Level: senior, staff

DP Tracking Other Finger Position: State: after typing word[i], one finger is at word[i] (current) and the other can be anywhere (tracked). At each step, either move the current finger to the next char (other stays put) or move the other finger to the next char (current becomes the "other"). Transition costs are Manhattan distances.

3D DP Explicit: Explicit 27-element DP array where index represents the position of the non-active finger (26 = not yet placed). For each character, transition by moving either the active or inactive finger. Manhattan distance on 2x13 grid. O(n) time with O(1) space for the DP array.

Minimum XOR Sum Two Arrays Bitmask DP | Python Q772

Minimize XOR sum of two arrays using bitmask DP in Python. Hard Google/Amazon interview question with O(n * 2^n) solution for n <= 14.

Topics: dynamic-programming, bit-manipulation, array

Companies: google, amazon, meta, microsoft, bloomberg, stripe, goldman-sachs

Level: senior, staff

Bitmask DP: dp[mask] = minimum XOR sum when mask indicates which elements of nums2 have been assigned. The number of set bits in mask tells us the current position in nums1. For each unset bit j, try assigning nums2[j] to nums1[i] and update dp[mask | (1<<j)]. Answer is dp[(1<<n)-1].

Top-Down Memoized Bitmask DP: Top-down memoized DP where dp(i, mask) returns minimum XOR sum for nums1[i:] with nums2 elements indicated by mask already used. For each position i, try all unused nums2 elements (bit j not set in mask), recurse, and take minimum.

Painting Fence with K Colors DP | Python Q773

Count ways to paint a fence with k colors and no 3 adjacent same-color posts using DP in Python. Medium Google interview question with O(n) solution.

Topics: dynamic-programming, math

Companies: google, amazon, meta, microsoft, bloomberg, apple, adobe

Level: swe3, senior

DP Same/Different Tracking: Track same = ways where last two posts have the same color, diff = ways where they differ. Recurrence: new same = old diff (can only have same if the post before the last two was different); new diff = (old same + old diff) * (k-1) colors to pick differently. Roll forward without extra space.

Closed Form: Alternative recurrence: total(n) = (k-1) * (total(n-1) + total(n-2)). The (k-1) factor comes from choosing a different color for the new post, and the sum represents adding either a same or different previous pair. This collapses same and diff into total.

Restore IP Addresses Backtracking | Python Q774

Generate all valid IP addresses from a digit string using backtracking in Python. Medium Amazon/Google interview question with bounded O(1) complexity.

Topics: backtracking, string

Companies: amazon, google, meta, microsoft, bloomberg, apple, uber

Level: swe3, senior

Backtracking: Backtrack by trying segments of length 1, 2, or 3. Validate each segment for leading zeros and value <= 255. When 4 segments are formed and the entire string is consumed, add the IP to results. The search space is bounded at 3^4 since each of 4 segments can be 1-3 chars.

Iterative Three Loops: Use three nested loops to place three dots at positions i, j, k. Validate all four resulting segments. Since each segment is at most 3 chars, loops are bounded making this effectively O(1). Clean and non-recursive alternative to backtracking.

Stickers to Spell Word Bitmask DP | Python Q775

Find minimum stickers to spell a word using bitmask DP in Python. Hard Google/Amazon interview question with O(2^n * S * n) solution.

Topics: dynamic-programming, bit-manipulation, backtracking

Companies: google, amazon, meta, microsoft, bloomberg, stripe, apple

Level: senior, staff

Bitmask DP: dp[mask] = min stickers to cover target characters indicated by mask bits. For each mask, find the first uncovered character and only try stickers that cover it (pruning). Apply sticker greedily to cover as many uncovered characters as possible, compute new_mask, and minimize dp[new_mask].

BFS over Bitmask States: BFS over bitmask states guarantees minimum stickers (BFS gives shortest path in unweighted graph). Start from mask=0, expand by applying each sticker to the first uncovered character position. Use dist array for visited tracking. BFS level = number of stickers used.

Shortest Path Visiting All Nodes BFS Bitmask | Python Q776

Find shortest path visiting all graph nodes using BFS with bitmask in Python. Hard Google/Amazon interview question with O(n * 2^n) solution.

Topics: graph, bit-manipulation, dynamic-programming

Companies: google, amazon, meta, microsoft, bloomberg, uber, stripe

Level: senior, staff

BFS with Bitmask State: BFS over states (node, visited_mask). Initialize all n nodes as starting states. Level-by-level BFS ensures minimum distance. Use a visited set of (node, mask) pairs to prevent redundant exploration. When visited_mask equals full_mask (all nodes visited), return current distance.

DP with Bitmask: DP table dp[node][mask] = minimum steps to be at node with visited set = mask. Initialize all starting positions with 0 steps. Process using BFS-like updates. When full_mask is reached for any node, that distance is optimal. Equivalent to BFS but stored in DP table.

Minimum Steps to Make Two Strings Anagram | Python Q777

Find minimum character replacements to make two strings anagrams using frequency counting in Python. Medium Amazon/Google interview question.

Topics: string, math, greedy

Companies: amazon, google, meta, microsoft, bloomberg, apple, shopify

Level: swe3, senior

Frequency Count: Count character frequencies in both strings. For each character that appears more in t than s, the excess must be replaced. Sum all excess counts. This equals the minimum changes since each replacement converts one excess char to a needed char.

Array Count: Use a 26-element difference array. Increment for each character in s, decrement for t. Positive values in diff represent characters s needs more of (t must replace something with these). Sum positives = minimum steps.

Minimum Swaps to Group All 1s Sliding Window | Python Q778

Find minimum swaps to group binary array 1s using sliding window in Python. Medium Amazon/Google interview question with O(n) solution.

Topics: sliding-window, array, greedy

Companies: amazon, google, meta, microsoft, bloomberg, apple, adobe

Level: swe3, senior

Sliding Window: Window size = total count of 1s. Slide this window across the array, tracking the number of 1s inside. The window with the most 1s needs the fewest swaps. Swaps needed = (total_ones - max_ones_in_window) since each 0 in the optimal window needs one swap with a 1 outside.

Count Zeros in Optimal Window: Equivalent formulation: count zeros in each window of size total_ones. Minimum zeros = minimum swaps needed (each zero in the window must swap with a one outside). Slide the window counting zeros using (1 - data[i]) as the zero indicator. Simpler than tracking ones.

Longest Subarray with Abs Diff Limit Monotonic Deque | Python Q779

Find longest subarray with absolute difference at most limit using two monotonic deques in Python. Hard Google/Amazon interview question with O(n) solution.

Topics: sliding-window, monotonic-stack, array

Companies: google, amazon, meta, microsoft, bloomberg, stripe, airbnb

Level: senior, staff

Two Monotonic Deques: Maintain a sliding window [left, right]. Two deques track the maximum and minimum values in the window. When max-min > limit, advance left and remove stale deque entries. Each element enters and exits each deque at most once, giving amortized O(n) total.

Sorted Container (SortedList): Use a sorted container (balanced BST / sorted list) to maintain window elements. O(log n) insert/remove. Check max (last) minus min (first) in O(1). Simpler to implement than the deque solution but O(n log n) instead of O(n). Requires the sortedcontainers library.

Maximum Events Attended Greedy Heap | Python Q780

Maximize events attended using greedy min-heap scheduling in Python. Medium Amazon/Google interview question with O(n log n) solution.

Topics: greedy, heap, array

Companies: amazon, google, meta, microsoft, bloomberg, airbnb, uber

Level: swe3, senior

Greedy with Min Heap: Sort events by start day. Simulate day by day. Each day, add all events that started by today to a min-heap (keyed by end day). Remove expired events. Greedily attend the event with earliest end day (to preserve future flexibility). Advance day and repeat. If heap empty, jump to next event start to avoid O(max_day) simulation.

Greedy Sorted by Start and End: Iterate through each day from 1 to 100000. Add events starting on the current day to a min-heap. Remove expired events. If heap non-empty, pop the soonest-ending event and attend it. Simpler implementation but O(D log n) where D can be 10^5; effectively O(n log n) in practice since most days have no events.

Paint Fence with K Colors | DP Python No Three Consecutive Same

Count fence painting ways with no three consecutive same-color posts using DP. O(n) time O(1) space Python solution.

Topics: dynamic-programming, recursion

Companies: amazon, google, apple, linkedin, stripe, adobe, uber

Level: swe2, swe3, senior

DP same/diff state O(1) space: Track same (last two posts same color) and diff (different). At each step update both. Total = same + diff.

Closed-form DP with total ways: total[i] = (k-1) * (total[i-1] + total[i-2]). First term: any of k-1 different colors from i-1. Second term: match i-2 with any of k-1 colors != i-1.

Best Time to Buy Stock with Transaction Fee | DP Python

Maximize stock profit with unlimited transactions and per-trade fee using DP states. O(n) Python solution.

Topics: dynamic-programming, greedy, array

Companies: amazon, google, goldman-sachs, stripe, coinbase, jane-street, visa

Level: swe3, senior, staff

DP with cash and hold states: cash = max profit without stock today. hold = max profit holding stock today. Update both each day. Answer is cash.

Minimum Path Sum Grid with Obstacles | DP Python

Find minimum cost path in grid with blocked cells using DP with path reconstruction. Python solution.

Topics: dynamic-programming, matrix, graph

Companies: amazon, google, facebook, uber, stripe, linkedin, adobe

Level: swe2, swe3, senior

Grid DP with path reconstruction: Fill dp table: dp[i][j] = grid cost + min of top/left predecessor. Skip blocked (-1) cells. Backtrack from bottom-right to find path.

Word Break with Minimum Word Count | DP BFS Python

Find minimum number of words to segment string using DP or BFS shortest path. Python solutions.

Topics: dynamic-programming, hash-map, string, bfs

Companies: amazon, google, facebook, apple, stripe, linkedin, databricks

Level: senior, staff

DP minimum word count: dp[i] = minimum words to segment s[:i]. For each i, try all j < i where s[j:i] in word_set. dp[i] = min(dp[j] + 1). Return dp[n] or -1.

BFS shortest path: BFS from index 0. Level = number of words used. Add all positions reachable via a valid word from current position. First time we reach n is minimum words.

Palindrome Partitioning Minimum Cuts | DP Python

Find minimum cuts for palindrome partitioning using DP with palindrome precomputation. O(n^2) Python solution.

Topics: dynamic-programming, string, divide-and-conquer

Companies: amazon, google, facebook, stripe, palantir, jane-street, netflix

Level: senior, staff

DP with palindrome precomputation: Precompute is_pal[i][j] using DP. Then cuts[i] = 0 if s[:i+1] is palindrome, else min(cuts[j]+1) for valid palindrome suffix s[j+1:i+1].

Longest Arithmetic Subsequence | DP Hash Map Python

Find longest arithmetic subsequence using DP with per-index difference hash maps. O(n^2) Python solution.

Topics: dynamic-programming, hash-map, array

Companies: amazon, google, apple, linkedin, stripe, adobe, paypal

Level: swe3, senior, staff

DP with hash maps per index: For each index i, maintain dict dp[i] mapping common difference to LAS length ending at i. For all j < i, dp[i][diff] = dp[j].get(diff, 1) + 1.

Stone Game III: Two-Player Optimal Strategy | DP Python

Determine Stone Game III winner using minimax DP. O(n) Python solution for optimal two-player strategy.

Topics: dynamic-programming, greedy, array

Companies: google, amazon, facebook, jane-street, palantir, stripe, coinbase

Level: senior, staff

DP from right to left: dp[i] = max score current player gets from index i onward. For each choice k (1,2,3), score = sum of chosen + remaining total - dp[i+k] (opponent gets dp[i+k]). Compare dp[0] with total/2.

Maximum Profit in Job Scheduling | Weighted Interval DP Python

Solve weighted interval scheduling for maximum profit using DP and binary search. O(n log n) Python solution.

Topics: dynamic-programming, binary-search, sorting, heap

Companies: google, amazon, facebook, linkedin, stripe, databricks, palantir

Level: senior, staff

DP with binary search on end times: Sort by end time. dp[i] = max profit using first i jobs. For job i, binary search the latest job j with end[j] <= start[i]. dp[i] = max(dp[i-1], dp[j]+profit[i]).

Group Anagrams Together | Hash Map Python Solution

Group strings that are anagrams using sorted key or frequency tuple hash map. Python solutions with complexity analysis.

Topics: hash-map, string, sorting

Companies: amazon, google, facebook, apple, uber, linkedin, stripe

Level: new-grad, swe2, swe3

Sorted string as key: For each string, sort its characters to get the canonical key. Append original string to the group for that key.

Frequency tuple as key: Use a 26-element count tuple as key, avoiding sort. O(n*k) time.

Two Sum Variants: Sorted Array, BST, Streaming | Python

Solve Two Sum for sorted arrays with two pointers, BST with in-order, and streaming data with hash set. Python solutions.

Topics: hash-map, two-pointers, binary-search, array

Companies: amazon, google, apple, facebook, uber, stripe, paypal

Level: new-grad, swe2, swe3

Three variants implemented: Sorted: two pointers. BST: in-order into list then two pointers. Stream: maintain hash set, check complement on each add.

Find All Duplicates in Array | O(1) Space Index Hash Python

Find all duplicate elements using array index as hash with sign marking. O(n) time O(1) space Python solution.

Topics: hash-map, array, sorting

Companies: amazon, google, apple, linkedin, adobe, oracle, paypal

Level: swe2, swe3, senior

Index as hash with negation: For each num, check sign at index abs(num)-1. If negative, num is a duplicate; add to result. Otherwise, negate it to mark visited.

Sorting approach: Sort the array, then scan for adjacent duplicates. O(n log n) time, O(1) extra space but modifies input.

Product of Array Except Self | No Division O(n) Python

Compute product of array except each element without division using prefix-suffix passes. O(n) Python solution.

Topics: array, prefix-sum, two-pointers

Companies: amazon, google, facebook, apple, linkedin, stripe, uber

Level: new-grad, swe2, swe3

Two-pass prefix and suffix products: Left pass: output[i] = product of nums[:i]. Right pass: multiply output[i] by running product of nums[i+1:] tracked as a variable.

Maximum Product Subarray | Track Max Min DP Python

Find maximum product subarray tracking both max and min products to handle negatives. O(n) Python solution.

Topics: dynamic-programming, array

Companies: amazon, google, facebook, apple, nvidia, linkedin, adobe

Level: swe2, swe3, senior

Track max and min product: At each element, the new max is max(num, num*cur_max, num*cur_min) and min is the corresponding min. Update global result.

Find Minimum in Rotated Sorted Array with Duplicates | Python

Find minimum in rotated sorted array with duplicates using binary search with duplicate-safe shrinking. Python solution.

Topics: array, binary-search, divide-and-conquer

Companies: amazon, google, facebook, apple, stripe, linkedin, oracle

Level: swe3, senior, staff

Binary search with duplicate handling: Standard binary search but when nums[mid] == nums[right], decrement right (cannot determine half). When nums[mid] > nums[right], min is in right half; else left half.

Count of Range Sum | Merge Sort Prefix Sum Python

Count subarrays with sum in [lower, upper] using merge sort on prefix sums. O(n log n) Python solution.

Topics: array, prefix-sum, divide-and-conquer, sorting

Companies: google, amazon, stripe, palantir, jane-street, databricks, nvidia

Level: senior, staff

Merge sort on prefix sums: Build prefix sums. Use merge sort: during merge, for each element in right half count elements in left half within [lower+r, upper+r] range using two pointers. This is the key cross-half count.

Tower of Hanoi 3-Peg and 4-Peg Frame-Stewart | Python

Implement Tower of Hanoi for 3 pegs recursively and minimize moves for 4 pegs using Frame-Stewart DP. Python solutions.

Topics: recursion, divide-and-conquer

Companies: amazon, google, apple, stripe, jane-street, palantir, discord

Level: swe3, senior, staff

Classic 3-peg recursive + 4-peg Frame-Stewart: Recursively solve 3-peg. For 4-peg, try all split points k and use DP: min_moves4[n] = min over k of 2*min_moves4[k] + 2^(n-k)-1.

Generate Balanced Parentheses with K Types | Backtracking Python

Generate all valid bracket sequences with k types of brackets using backtracking with nesting stack. Python solution.

Topics: recursion, backtracking, string

Companies: google, amazon, facebook, stripe, palantir, discord, databricks

Level: senior, staff

Backtracking with nesting stack: Backtrack with current string, open count, and stack of open brackets. At each step, add any open bracket (if open < n) or add the closing bracket matching stack top.

Sort Array by Parity: Evens First | Two-Pointer Python

Move even elements before odd using two-pointer in-place or stable filter. Python solutions with complexity analysis.

Topics: two-pointers, array, sorting

Companies: amazon, google, apple, adobe, oracle, paypal, visa

Level: new-grad, swe2

Two-pointer in-place (unstable): Left pointer finds next odd, right pointer finds next even. Swap them. Continue until left >= right.

Filter partition (stable): Concatenate even elements followed by odd elements, maintaining original relative order within each group.

Interval List Intersections | Two-Pointer Python

Find all intersections of two sorted interval lists using two-pointer sweep. O(m+n) Python solution.

Topics: two-pointers, interval, array

Companies: amazon, google, facebook, apple, stripe, linkedin, discord

Level: swe2, swe3, senior

Two-pointer sweep: Use pointers i and j into both lists. Compute intersection as [max(starts), min(ends)]. If valid (start <= end), add to result. Advance pointer with smaller end.

Word Ladder Minimum Transformation | BFS Python

Find minimum single-letter transformations from begin to end word using BFS and bidirectional BFS. Python solutions.

Topics: bfs, hash-map, graph, string

Companies: amazon, google, facebook, apple, linkedin, stripe, airbnb

Level: swe3, senior, staff

BFS with neighbor generation: BFS from beginWord. For each word, try replacing each position with all 26 letters. If result is in word_set, add to queue and remove from set (visited). Return level when endWord found.

Bidirectional BFS: BFS simultaneously from beginWord and endWord. At each step expand the smaller frontier. When frontiers intersect, return total steps. Halves search depth on average.

Bellman-Ford Shortest Path | Negative Weights Python

Implement Bellman-Ford to find shortest paths with negative edge weights and detect negative cycles. Python solution.

Topics: graph, dynamic-programming

Companies: amazon, google, microsoft, imc, optiver, hrt

Level: swe3, senior

Bellman-Ford: Initialize dist[src]=0, others=inf. Relax every edge V-1 times. On pass V, if any relaxation succeeds, return [] (negative cycle). O(V*E) time.

Floyd-Warshall All-Pairs Shortest Paths | Python

Implement Floyd-Warshall algorithm to compute shortest paths between all pairs of vertices. Python O(V^3) solution.

Topics: graph, dynamic-programming, matrix

Companies: google, microsoft, amazon, renaissance, imc, optiver

Level: swe3, senior

Floyd-Warshall DP: For each intermediate vertex k from 0 to V-1, update dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j]) for all i,j. After V iterations all shortest paths are found.

Kruskal's MST Algorithm | Union-Find Python

Implement Kruskal's algorithm with Union-Find path compression to find the Minimum Spanning Tree. Python solution.

Topics: graph, union-find, greedy, sorting

Companies: google, amazon, microsoft, hrt, virtu, optiver

Level: swe2, swe3, senior

Kruskal's + Union-Find: Sort edges by weight. Use Union-Find with path compression. For each edge (u,v,w) in sorted order, if find(u) != find(v), add to MST and union(u,v). Stop after V-1 edges.

Kosaraju's SCC Algorithm | Python

Find all Strongly Connected Components using Kosaraju's two-pass DFS algorithm. Python implementation.

Topics: graph, dfs

Companies: google, meta, amazon, deepmind, anthropic

Level: swe3, senior, staff

Kosaraju's Two-Pass DFS: Build adjacency lists for original and transposed graphs. Pass 1: DFS on original, push to finish stack. Pass 2: pop from stack, DFS on transposed graph collecting each component.

Bridges in Graph - Tarjan's Algorithm | Python

Find all bridge edges in an undirected graph using DFS with discovery time and low arrays. Python solution.

Topics: graph, dfs

Companies: google, amazon, microsoft, cloudflare, openai

Level: swe3, senior, staff

Tarjan's Bridge Finding: DFS with disc[] and low[] arrays. For each DFS tree edge (u,v), low[u] = min(low[u], low[v]). For back edges to ancestor, low[u] = min(low[u], disc[neighbor]). Bridge condition: low[v] > disc[u].

Bipartite Graph Check 2-Coloring | Python BFS

Check if a graph is bipartite using BFS 2-coloring. Handles disconnected graphs. Python solution.

Topics: graph, bfs, dfs

Companies: amazon, google, microsoft, spotify, canva

Level: swe2, swe3

BFS 2-Coloring: For each unvisited vertex, BFS and assign alternating colors 0/1. If any neighbor already colored same as current, return False. Works on disconnected graphs.

Burst Balloons Interval DP | Python

Solve the burst balloons problem using interval dynamic programming. The key insight: think about which balloon to burst LAST.

Topics: dynamic-programming, divide-and-conquer

Companies: google, amazon, meta, anthropic, openai, deepmind

Level: senior, staff

Interval DP: Pad array with 1s on both ends. dp[i][j] = max coins from range (i, j) exclusive. For each subproblem, try every k as the LAST balloon burst between i and j.

Traveling Salesman Bitmask DP (Held-Karp) | Python

Solve TSP optimally for small n using Held-Karp bitmask dynamic programming. Python O(2^n * n^2) solution.

Topics: dynamic-programming, bit-manipulation, graph

Companies: google, renaissance, imc, optiver, jane-street, citadel

Level: senior, staff

Held-Karp Bitmask DP: dp[mask][i] = min cost to reach i visiting all cities in mask. Start at city 0. Iterate over all masks in increasing order. Final answer: min dp[full_mask][i] + dist[i][0].

Regular Expression Matching DP | Python

Implement regex matching with '.' and '*' using bottom-up 2D DP. Python solution to the classic hard interview problem.

Topics: dynamic-programming, strings, recursion

Companies: google, amazon, meta, microsoft, apple

Level: swe3, senior

Bottom-up DP: Build dp[len(s)+1][len(p)+1]. Base: dp[0][0]=True, handle leading '*' patterns. Transition: single char match or '.' → dp[i][j] = dp[i-1][j-1]. '*' → zero occurrences dp[i][j-2], or one+ if char matches dp[i-1][j].

LFU Cache O(1) Implementation | Python

Implement an LFU cache with O(1) get and put using three hash maps and OrderedDict. Python solution to the classic system design coding problem.

Topics: lfu-cache, hash-map, design-patterns, object-design

Companies: amazon, google, meta, microsoft, netflix, databricks, snowflake

Level: senior, staff

Three Hash Maps + OrderedDict: key_val: key->value. key_freq: key->frequency. freq_keys: freq->OrderedDict (insertion-order = LRU). min_freq tracks eviction target. All ops O(1) amortized.

Token Bucket Rate Limiter Python | System Design Coding

Implement a token bucket rate limiter with lazy refill strategy. Used in API gateways and Cloudflare. Python O(1) solution.

Topics: rate-limiting, design-patterns, system-design-coding

Companies: amazon, google, cloudflare, stripe, twilio, plaid, brex, retool

Level: swe2, swe3, senior

Lazy Refill Token Bucket: On each request, compute tokens to add since last call (elapsed * rate), cap at capacity. Deduct requested tokens if available. O(1) per call with no background thread needed.

Consistent Hashing Ring Python | System Design Coding

Implement consistent hashing with virtual nodes using a sorted ring and bisect. The algorithm behind DynamoDB and Cassandra. Python solution.

Topics: hash-map, system-design-coding, design-patterns

Companies: amazon, google, meta, databricks, snowflake, cloudflare, discord, rippling

Level: swe3, senior, staff

Sorted Ring + Bisect: Hash each virtual node position using MD5. Keep sorted list for O(log n) lookup via bisect. add_node inserts replicas entries; remove_node deletes them; get_node bisects to find nearest clockwise node.

Manacher's Algorithm Longest Palindrome | Python O(n)

Find the longest palindromic substring in O(n) using Manacher's algorithm. Python implementation with transform trick.

Topics: strings, string-matching

Companies: google, amazon, microsoft, meta, openai, deepmind

Level: senior, staff

Manacher's O(n): Transform string with '#' separators. Maintain center c and right boundary r. For each i, initialize p[i] from mirror if inside current palindrome. Expand around i. Update c,r when palindrome extends past r.

Expand Around Center O(n^2): For each center (and each gap between chars), expand outward while characters match. Track global max. Simpler to implement but O(n^2) — shown for contrast.

Rabin-Karp Rolling Hash Pattern Matching | Python

Implement Rabin-Karp rolling hash for string pattern matching. O(n+m) average. Python solution with collision handling.

Topics: strings, string-matching, hash-map

Companies: google, amazon, microsoft, bloomberg, anthropic, spotify

Level: swe2, swe3, senior

Rolling Hash: Use polynomial rolling hash with a large prime modulus. Slide window: remove leading char * high power, shift remaining left, add new char. Verify on hash match to handle collisions. Average O(n+m).

Z-Algorithm Pattern Matching | Python O(n+m)

Implement the Z-algorithm for linear-time string matching. Easier to implement than KMP, same O(n+m) complexity. Python solution.

Topics: strings, string-matching

Companies: google, amazon, microsoft, bloomberg, openai, deepmind

Level: swe2, swe3, senior

Z-Function: Build Z-array for pattern+"$"+text in O(n+m). Maintain l,r pointers. When Z[i] == m, record i - m - 1 as a match position in original text.

Trapping Rain Water II 3D Matrix | Python Heap BFS

Solve 3D trapping rain water using min-heap BFS from boundary inward. Python O(mn log(m+n)) solution.

Topics: heap, matrix, bfs

Companies: google, amazon, meta, microsoft, optiver, imc, hrt

Level: senior, staff

Min-Heap BFS from boundary: Initialize heap with all border cells. Visited set tracks processed cells. Pop min-height cell; for each unvisited neighbor, trapped water = max(0, current_level - neighbor_height). Push neighbor at max(current_level, neighbor_height).

Median of Two Sorted Arrays O(log n) | Python

Find median of two sorted arrays in O(log(min(m,n))) using binary search on partition. Python solution to the classic hard problem.

Topics: binary-search, array, divide-and-conquer

Companies: google, amazon, meta, microsoft, apple, bloomberg, jane-street, renaissance

Level: swe3, senior

Binary Search on Partition: Ensure nums1 is smaller. Binary search i in [0, m]. j = half - i. Find i where nums1[i-1] <= nums2[j] AND nums2[j-1] <= nums1[i]. Compute median from the four boundary values.

Count Smaller Numbers After Self | Merge Sort Python

Count smaller elements to the right using merge sort inversion counting or Fenwick Tree. Python O(n log n) solutions.

Topics: divide-and-conquer, sorting, binary-search, fenwick-tree

Companies: google, amazon, meta, bloomberg, citadel, imc, optiver

Level: swe3, senior

Modified Merge Sort: Carry (value, original_index) pairs through merge sort. During merge, when right element placed before left elements, add (remaining left count) to each left element's count. O(n log n).

Fenwick Tree (BIT): Coordinate compress values. Scan right to left. For each element, query BIT for sum of elements smaller than current (prefix sum up to current-1). Update BIT at current position.

Minimum Window Substring Sliding Window | Python

Find minimum window substring containing all target characters using sliding window. Classic hard interview problem. Python O(n) solution.

Topics: sliding-window, hash-map, strings

Companies: amazon, google, meta, microsoft, bloomberg, linkedin, spotify, canva

Level: swe2, swe3, senior

Sliding Window: Two pointers l, r. Expand r adding chars to window dict. When window covers t (have==need), record window and shrink l. Update have when shrinking makes a char unsatisfied.

Word Search II Trie Backtracking | Python

Find all words on a board using Trie + DFS backtracking with pruning. Python solution to the classic hard Trie problem.

Topics: trie, backtracking, dfs, matrix

Companies: amazon, google, meta, microsoft, bloomberg, anthropic, openai

Level: swe3, senior, staff

Trie + DFS Backtracking: Insert all words into Trie. For each board cell (r,c), DFS walking the Trie. On word end, add to result and prune Trie node. Mark cell as visited during DFS and restore after.

Largest Rectangle in Histogram Monotonic Stack | Python

Find the largest rectangle in a histogram using a monotonic stack in O(n). Python solution to the classic hard problem.

Topics: stack, monotonic-stack, array

Companies: amazon, google, meta, microsoft, bloomberg, optiver, virtu

Level: swe2, swe3, senior

Monotonic Stack: Append sentinel 0. For each bar, while stack top is taller than current bar, pop and compute area: height = popped bar, width = current_index - new_top - 1. Track global max.

Serialize Deserialize Binary Tree | Python

Design serialize/deserialize for a binary tree using DFS pre-order with null markers. Python solution to the classic hard design problem.

Topics: binary-tree, bfs, dfs, design-patterns

Companies: amazon, google, meta, microsoft, linkedin, databricks, rippling

Level: swe3, senior

DFS Pre-order: Serialize: DFS pre-order, append "N" for None. Join with ",". Deserialize: split by ",", use index pointer. If "N", return None. Else create node, recurse left then right.

Stock Buy Sell with Cooldown DP State Machine | Python

Maximize stock trading profit with 1-day cooldown using a DP state machine (held/sold/rest). Python O(n) solution.

Topics: dynamic-programming, array

Companies: amazon, google, bloomberg, goldman-sachs, adyen, klarna, brex

Level: swe2, swe3

DP State Machine: Three states: held (best profit while holding), sold (best profit after selling today, triggers cooldown), rest (best profit while resting). Transitions: held stays or buy from rest; sold = sell held; rest = max rest or come from sold cooldown.

Number of Islands II Dynamic Union-Find | Python

Solve dynamic island counting after each land addition using Union-Find with path compression. Python O(k*alpha(n)) solution.

Topics: union-find, matrix, graph

Companies: amazon, google, meta, microsoft, bloomberg, canva, n26, adyen

Level: swe3, senior

Union-Find (DSU): DSU with path compression and union by rank on flattened cells. land set tracks added cells. For each position: add 1, check 4 neighbors; if land and different root, union and subtract 1.

Thread-Safe Counter with Lock | Python Concurrency

Implement a thread-safe counter using threading.Lock in Python. Prevent race conditions when incrementing from multiple threads.

Topics: concurrency

Companies: google, amazon, microsoft, meta

Level: swe2, swe3

threading.Lock: Wrap the read-modify-write operation in a Lock. The with statement guarantees release even if an exception occurs.

Producer-Consumer Queue Python | threading.Queue

Implement producer-consumer pattern with threading.Queue in Python. Learn sentinel shutdown and daemon threads.

Topics: concurrency, queue

Companies: amazon, google, microsoft, netflix

Level: swe2, swe3

threading.Queue with sentinels: Use threading.Queue for safe inter-thread communication. Each consumer exits when it receives None. Producers put real items then one sentinel per consumer.

Semaphore Resource Pool Python | threading.Semaphore

Implement a bounded resource pool with threading.Semaphore in Python. Limit concurrent access to shared resources.

Topics: concurrency

Companies: google, amazon, stripe, microsoft

Level: swe3, senior

threading.Semaphore: Semaphore(n) counts down to 0 on acquire and blocks there, releasing when release() is called. This bounds concurrency to n.

asyncio gather Concurrent Fetch Python | Async Programming

Use asyncio.gather to fetch multiple URLs concurrently in Python. Learn async/await and event loop basics.

Topics: concurrency

Companies: google, meta, netflix, airbnb

Level: swe2, swe3

asyncio.gather: Schedule all coroutines with asyncio.gather which runs them on the event loop concurrently. Total time is the max of individual times, not the sum.

asyncio Queue Producer Consumer Python | Async Queue

Build an async producer-consumer pipeline with asyncio.Queue. Python coroutines, task_done, and gather.

Topics: concurrency, queue

Companies: google, netflix, amazon, uber

Level: swe3, senior

asyncio.Queue with task_done: asyncio.Queue provides coroutine-safe communication. Producers put items; consumers call task_done after processing. q.join() waits for all items.

ThreadPoolExecutor map Python | Parallel Processing

Use concurrent.futures.ThreadPoolExecutor.map for parallel task execution in Python. I/O-bound parallel processing.

Topics: concurrency

Companies: amazon, google, microsoft, salesforce

Level: new-grad, swe2

ThreadPoolExecutor.map: ThreadPoolExecutor manages a pool of threads. map() submits all tasks immediately and returns results in input order, blocking only when results are consumed.

ProcessPoolExecutor CPU Bound Python | Multiprocessing

Use concurrent.futures.ProcessPoolExecutor for CPU-bound parallel tasks in Python. Bypass GIL with multiprocessing.

Topics: concurrency

Companies: google, amazon, nvidia, intel

Level: swe3, senior

ProcessPoolExecutor.map: ProcessPoolExecutor spawns separate Python interpreter processes. Each process runs is_prime independently on a CPU core, giving true parallel speedup for CPU-bound work.

Async Context Manager Python | __aenter__ __aexit__

Implement async context managers with __aenter__ and __aexit__ in Python. Manage async resources safely.

Topics: concurrency, oop

Companies: google, airbnb, stripe, netflix

Level: swe3, senior

__aenter__ / __aexit__: Define async __aenter__ for setup and async __aexit__ for teardown. The runtime calls these automatically with "async with", guaranteeing cleanup.

threading.Event Condition Python | Thread Signaling

Use threading.Event and Condition to signal between threads in Python. Start gun pattern for concurrent workers.

Topics: concurrency

Companies: google, microsoft, amazon, bloomberg

Level: swe3, senior

threading.Event: threading.Event has internal flag. wait() blocks until the flag is True. set() turns it True and wakes all blocked threads simultaneously.

Deadlock Detection Resource Allocation Graph Python

Detect deadlocks using cycle detection on a resource allocation graph in Python. DFS-based wait-for graph algorithm.

Topics: concurrency, graph, dfs

Companies: google, microsoft, oracle, ibm

Level: senior, staff

DFS cycle detection on wait-for graph: Build adjacency list from wait-for edges. Run DFS with coloring: WHITE=0 unvisited, GRAY=1 in current path, BLACK=2 done. A back edge to GRAY node means cycle.

Singleton Pattern Python | __new__ Thread-Safe

Implement thread-safe Singleton pattern in Python using __new__ and double-checked locking.

Topics: oop, design-patterns

Companies: amazon, microsoft, google, oracle

Level: new-grad, swe2

__new__ override: Override __new__ to check if _instance already exists. If not, create it via super().__new__. Subsequent calls return the existing instance.

Observer Pattern Python | Publish Subscribe Event System

Implement Observer pattern in Python with subscribe/notify. Event-driven architecture using subject and observers.

Topics: oop, design-patterns

Companies: microsoft, amazon, google, salesforce

Level: swe2, swe3

Classic Observer: Subject holds a list of observers. When state changes (via property setter), it iterates the list calling update(). Observers implement update() to react.

Strategy Pattern Python | Pluggable Algorithms OOP

Implement Strategy design pattern in Python with interchangeable sort algorithms. ABC-based pluggable behaviors.

Topics: oop, design-patterns

Companies: amazon, google, microsoft, stripe

Level: new-grad, swe2

Strategy via ABC: Define SortStrategy ABC. Each concrete strategy implements sort(). Sorter delegates to strategy.sort() and can swap strategy at runtime.

Command Pattern Undo Redo Python | Design Patterns

Implement Command pattern with undo/redo stacks in Python. Text editor operations with full reversibility.

Topics: oop, design-patterns, stack

Companies: microsoft, adobe, google, apple

Level: swe2, swe3

Command with undo/redo stacks: Encapsulate each edit as a Command. Invoker keeps undo_stack and redo_stack. execute() runs the command and saves it; undo() reverses it and moves to redo_stack.

Builder Pattern Fluent API Python | HTTP Request Builder

Implement Builder pattern with method chaining in Python. Fluent HTTP request builder with validation.

Topics: oop, design-patterns

Companies: stripe, google, amazon, netflix

Level: new-grad, swe2

Fluent Builder: Each setter method stores data and returns self for chaining. build() validates and constructs the immutable result object.

Decorator Pattern Python | Logging Timing Wrappers

Implement logging and timing decorators in Python using functools.wraps. Stackable structural Decorator pattern.

Topics: oop, design-patterns, decorators

Companies: google, amazon, meta, netflix

Level: new-grad, swe2

functools.wraps decorators: Each decorator is a function returning a wrapper. functools.wraps preserves the original function metadata. Stack with @timed @logged syntax.

Factory Method Pattern Python | Shape Factory OOP

Implement Factory Method pattern in Python with a registry-based shape factory. Creational design pattern.

Topics: oop, design-patterns

Companies: amazon, microsoft, google, oracle

Level: new-grad, swe2

Registry-based Factory: A registry dict maps type strings to classes. Factory.create looks up the class and calls it with **kwargs. Adding new shapes only requires updating the registry.

Abstract Factory Pattern Python | Cross-Platform UI

Implement Abstract Factory pattern for cross-platform UI widgets in Python. ABC-based family of related objects.

Topics: oop, design-patterns

Companies: microsoft, apple, google, amazon

Level: swe2, swe3

Abstract Factory with ABC: UIFactory ABC declares creation methods. Two concrete factories implement all methods returning platform widgets. Client only imports UIFactory - swapping factory changes entire widget family.

Template Method Pattern Python | Data Pipeline

Implement Template Method design pattern for a data pipeline in Python. Fix the algorithm skeleton in base class.

Topics: oop, design-patterns

Companies: amazon, google, databricks, snowflake

Level: swe2, swe3

Template Method ABC: Base DataPipeline.run() calls abstract read(), optional transform(), abstract write() in sequence. Subclasses implement required abstract methods and optionally override transform().

Flyweight Pattern Python | Glyph Object Pool

Implement Flyweight pattern for shared glyph objects in Python. Separate intrinsic and extrinsic state.

Topics: oop, design-patterns

Companies: adobe, microsoft, google, apple

Level: swe3, senior

Flyweight with factory cache: GlyphFactory caches Glyph objects keyed by (char, font, size). Repeated get() calls return the same object. render() takes x,y extrinsic state without storing it.

Chain of Responsibility Python | Middleware Pipeline

Implement Chain of Responsibility as HTTP middleware in Python. Linked handler chain with fluent API.

Topics: oop, design-patterns

Companies: amazon, google, stripe, netflix

Level: swe2, swe3

Linked handler chain: Handler ABC with set_next for fluent linking. Each handler inspects the request and either processes it or calls self._next.handle(). Fluent chaining: auth.set_next(log).set_next(final).

Iterator Protocol Python | Custom Range __iter__ __next__

Implement Python iterator protocol with __iter__ and __next__. Custom range class and generator comparison.

Topics: oop, generators

Companies: google, amazon, microsoft, meta

Level: new-grad, swe2

Iterator protocol + generator: __iter__ returns self. __next__ increments current and raises StopIteration at end. Generator version is cleaner: yield each value in a loop.

Context Manager Protocol Python | DB Transaction

Implement __enter__ and __exit__ for a database transaction context manager in Python. Commit/rollback pattern.

Topics: oop, design-patterns

Companies: stripe, amazon, google, microsoft

Level: swe2, swe3

__enter__/__exit__ + contextmanager: __enter__ begins transaction and returns self. __exit__ checks exc_type: None means commit, non-None means rollback. contextmanager version splits on yield.

Descriptor Protocol Python | Validated Attribute

Implement Python descriptor protocol with __get__, __set__, __set_name__ for validated attributes.

Topics: oop, type-hints

Companies: google, microsoft, amazon, stripe

Level: swe3, senior

Data Descriptor with __set_name__: __set_name__ captures attribute name automatically. __set__ validates and stores in instance.__dict__ under a private key. __get__ retrieves from the same private key.

Metaclass Class Registry Python | Plugin Architecture

Use Python metaclass to auto-register subclasses. Plugin architecture with __init_subclass__ and RegistryMeta.

Topics: oop

Companies: google, stripe, amazon, deepmind

Level: senior, staff

Metaclass registry + __init_subclass__ alternative: RegistryMeta.__new__ adds each new class to registry dict, skipping the base. __init_subclass__ achieves the same without a metaclass and is preferred in modern Python.

Implement lru_cache from Scratch Python | OrderedDict Cache

Build functools.lru_cache from scratch using OrderedDict in Python. LRU eviction, decorator pattern.

Topics: functools, lru-cache, hash-map, design-patterns

Companies: google, meta, amazon, microsoft

Level: swe3, senior

OrderedDict LRU: Wrap function in a closure with an OrderedDict. On hit: move to end (most recent). On miss: call function, add to end; if over capacity, popitem(last=False) removes LRU.

functools.reduce Python | Fold Scan Operations

Use functools.reduce for fold and scan operations in Python. Product, max, scan with accumulate.

Topics: functools, recursion

Companies: google, amazon, microsoft, jane-street

Level: new-grad, swe2

functools.reduce examples: reduce applies binary function cumulatively. For scan, itertools.accumulate is the idiomatic choice.

itertools.groupby Python | Run Length Encoding

Use itertools.groupby to group consecutive elements in Python. Run-length encoding and key-based grouping.

Topics: itertools, strings

Companies: google, amazon, microsoft, bloomberg

Level: new-grad, swe2

itertools.groupby: groupby yields (key, group_iterator) pairs. Consume group with list() immediately before next iteration. For RLE: key is char, group count gives run length.

itertools combinations permutations Python | Combinatorics

Use itertools.combinations and permutations for combinatorial enumeration in Python.

Topics: itertools, combinatorics

Companies: google, amazon, jane-street, two-sigma

Level: new-grad, swe2

itertools combinatorics: itertools provides lazy generators for all combinatorial arrangements. Convert to list only when needed to avoid memory issues with large n.

collections.Counter Python | Top-K Anagram Grouping

Use collections.Counter for top-K frequency, anagram detection, and grouping in Python.

Topics: collections, hash-map, heap

Companies: google, amazon, meta, microsoft

Level: new-grad, swe2

collections.Counter: Counter is a dict subclass for frequency counting. most_common(k) uses heapq internally. Anagram check: Counter equality. Grouping: use sorted counter items as key.

collections.defaultdict Python | Nested Dict Builder

Use collections.defaultdict for nested dicts, adjacency lists, and frequency maps in Python.

Topics: collections, hash-map

Companies: amazon, google, microsoft, meta

Level: new-grad, swe2

defaultdict variants: defaultdict avoids KeyError and if-key-not-in-dict boilerplate. Nest with lambdas for multi-level grouping.

LRU Cache OrderedDict Python | collections.OrderedDict

Implement LRU Cache with collections.OrderedDict in Python. O(1) get and put with move_to_end.

Topics: collections, lru-cache, hash-map

Companies: google, amazon, meta, microsoft

Level: swe2, swe3

OrderedDict LRU: OrderedDict preserves insertion/access order. move_to_end() marks as recently used. popitem(last=False) removes LRU. Both ops are O(1).

heapq nlargest nsmallest Python | Streaming Top-K

Use heapq.nlargest and nsmallest for top-K queries in Python. Streaming top-K with min-heap of size k.

Topics: heap, collections

Companies: google, amazon, meta, bloomberg

Level: new-grad, swe2

heapq.nlargest + streaming min-heap: heapq.nlargest is convenient for batch. For streaming, maintain a min-heap of size k: push new element, pop if size exceeds k. Final heap contains k largest.

bisect Module Python | Sorted List Binary Search

Use Python bisect module for binary search on sorted lists. bisect_left, bisect_right, insort operations.

Topics: binary-search, sorting

Companies: google, amazon, microsoft, bloomberg

Level: new-grad, swe2

bisect module operations: bisect provides O(log n) binary search. insort inserts while maintaining sort. rank = bisect_right gives count of elements <= val.

dataclasses __slots__ Python | Memory-Efficient Records

Use Python dataclasses with __slots__ for memory-efficient record objects. Compare memory with and without slots.

Topics: oop, type-hints

Companies: google, amazon, stripe, databricks

Level: swe2, swe3

dataclass + __slots__: Regular dataclass has __dict__ overhead. Adding __slots__ = ("x","y","z") eliminates it. Python 3.10+ @dataclass(slots=True) automates this.

AVL Tree Insert Python | Self-Balancing BST Rotations

Implement AVL tree insertion with LL, RR, LR, RL rotations in Python. Self-balancing BST O(log n).

Topics: tree, binary-tree, recursion

Companies: google, amazon, microsoft, oracle

Level: swe3, senior

AVL rotations: Recursively insert, update height, check balance factor. Apply single or double rotation based on imbalance case. Return new subtree root after each rotation.

Red-Black Tree Insert Python | RB Tree Color Rotations

Implement Red-Black Tree insertion with color flips and rotations in Python. RB tree invariants and fixup.

Topics: tree, binary-tree

Companies: google, microsoft, amazon, oracle

Level: senior, staff

RB Tree insertion with fixup: Insert as in BST with red color. Fix up: if uncle is red, recolor and move up. If uncle is black, rotate toward uncle then away. Set root black at end.

Segment Tree Range Sum Python | Point Update O(log n)

Build a Segment Tree for range sum queries and point updates in Python. O(n) build, O(log n) operations.

Topics: segment-tree, tree

Companies: google, amazon, microsoft, two-sigma

Level: swe3, senior

Array-based Segment Tree: Store tree in array with 1-based indexing. Left child = 2*i, right = 2*i+1. Build bottom-up. Query splits range; update propagates changes up.

Segment Tree Lazy Propagation Python | Range Update Query

Segment tree with lazy propagation for O(log n) range updates and range queries in Python.

Topics: segment-tree, tree

Companies: google, two-sigma, citadel, bloomberg

Level: senior, staff

Lazy Propagation Segment Tree: lazy[node] holds pending addition. Before recursing, push lazy down to children. On range update, if segment is fully covered, update tree and lazy without recursing.

Fenwick Tree BIT Python | Point Update Prefix Sum O(log n)

Implement Fenwick Tree (Binary Indexed Tree) for O(log n) point updates and prefix sum queries in Python.

Topics: fenwick-tree, prefix-sum

Companies: google, amazon, two-sigma, jane-street

Level: swe3, senior

Fenwick Tree LSB trick: BIT stores partial sums indexed by LSB ranges. Update propagates up by adding LSB. Query accumulates down by stripping LSB. Convert to 1-indexed internally.

2D Fenwick Tree Python | Rectangle Sum Query

Implement 2D Fenwick Tree for O(log m log n) point updates and rectangle sum queries in Python.

Topics: fenwick-tree, matrix, prefix-sum

Companies: google, two-sigma, citadel, amazon

Level: senior, staff

2D BIT: Nested BIT: outer BIT over rows, inner BIT over columns. Each update touches O(log m * log n) cells. Prefix sum uses double loop stripping LSB.

Trie Insert Search StartsWith Python | Prefix Tree

Implement Trie with insert, search, and startsWith in Python. Prefix tree for string matching.

Topics: trie, strings

Companies: google, amazon, meta, microsoft

Level: swe2, swe3

Dict-based Trie: Each node holds a dict mapping char to child TrieNode. insert builds path. search checks path exists AND is_end. startsWith only checks path exists.

Trie Delete Python | Recursive Pruning

Implement Trie deletion with recursive pruning in Python. Remove nodes no longer needed after word deletion.

Topics: trie, strings, recursion

Companies: google, amazon, microsoft, meta

Level: swe3, senior

Post-order recursive delete: Recurse to end of word. Unmark is_end. On the way back, remove child reference if child has no children and is not a word end. Return True if current node is now deletable.

Trie Autocomplete Python | DFS Prefix Suggestions

Implement autocomplete with Trie and DFS in Python. Find all words with a prefix, ranked by frequency.

Topics: trie, dfs, strings

Companies: google, amazon, meta, linkedin

Level: swe2, swe3

Trie DFS autocomplete: Insert with frequency. For suggest, navigate to prefix node. DFS collects all (freq, word) pairs below. Sort by (-freq, word) and return top k.

Suffix Array Construction Python | O(n log^2 n)

Build a suffix array in O(n log^2 n) using prefix doubling in Python. Foundation for string matching algorithms.

Topics: string-matching, sorting, divide-and-conquer

Companies: google, amazon, bloomberg, two-sigma

Level: senior, staff

Prefix doubling O(n log^2 n): Assign initial ranks from chars. Repeatedly double the comparison window, sorting by (rank[i], rank[i+gap]). Reassign ranks. Stop when all unique.

Sparse Table RMQ Python | O(1) Range Minimum Query

Build Sparse Table for O(1) range minimum queries after O(n log n) preprocessing in Python.

Topics: divide-and-conquer, prefix-sum

Companies: google, two-sigma, citadel, imc

Level: senior, staff

Sparse Table O(1) RMQ: Precompute table[k][i] = min of 2^k elements from i. Query uses k = log2(r-l+1); take min of two overlapping windows of that size.

Cartesian Tree Python | BST Heap Property O(n)

Build a Cartesian tree from an array in O(n) using a stack. Combines BST index property with min-heap value property.

Topics: tree, binary-tree, stack

Companies: google, two-sigma, citadel, bloomberg

Level: senior, staff

Stack-based O(n) construction: Maintain a stack of right-spine nodes. For each new element, pop nodes with larger values (they become left children). New node becomes right child of new top.

Splay Tree Python | Amortized O(log n) Self-Adjusting BST

Implement Splay Tree with zig, zig-zig, zig-zag rotations in Python. Amortized O(log n) self-adjusting BST.

Topics: tree, binary-tree

Companies: google, two-sigma, jane-street, renaissance

Level: senior, staff

Splay Tree with parent pointers: After every access, splay the accessed node to root. Three rotation cases handle all relative positions of node, parent, and grandparent.

Egg Drop Problem Python | DP Binary Search O(k log n)

Solve the egg drop problem with optimized DP in Python. Find minimum trials with k eggs and n floors.

Topics: dynamic-programming, binary-search

Companies: google, amazon, microsoft, bloomberg

Level: swe3, senior

DP reformulation O(k log n): Reframe: dp[k][t] = max floors checkable with k eggs in t moves. Recurrence: dp[k][t] = dp[k-1][t-1] + dp[k][t-1] + 1. Find smallest t where dp[k][t] >= n.

Palindrome Partitioning Min Cuts Python | DP O(n^2)

Find minimum cuts for palindrome partitioning using DP in Python. Precompute palindrome table and minimize cuts.

Topics: dynamic-programming, string-matching

Companies: google, amazon, microsoft, meta

Level: swe3, senior

DP with palindrome table: Precompute is_pal[i][j] by expanding from center. Then cuts[i] = min number of cuts for s[:i+1]. For each i, try all j: if s[j..i] is palindrome, cuts[i] = min(cuts[i], cuts[j-1]+1).

Wildcard Matching Python DP | ? and * Pattern Match

Solve wildcard pattern matching with ? and * using DP in Python. O(mn) solution with 2D table.

Topics: dynamic-programming, string-matching

Companies: google, amazon, facebook, microsoft

Level: swe3, senior

DP O(mn): dp[i][j] means p[:j] matches s[:i]. For each cell: char match or ? gives dp[i-1][j-1]; * gives dp[i-1][j] (consume one s char) or dp[i][j-1] (use * as empty).

Edit Distance Levenshtein Python | DP Backtrack

Compute Levenshtein edit distance with DP and backtrack the edit operations in Python.

Topics: dynamic-programming, string-matching

Companies: google, amazon, microsoft, meta

Level: swe2, swe3

DP + backtrack: Standard edit distance DP. For backtrack, start from dp[m][n] and trace back: if chars matched, go diagonal; else find which operation was cheapest.

Longest Common Substring Python | DP O(mn)

Find the longest common substring (contiguous) of two strings using DP in Python. O(mn) solution.

Topics: dynamic-programming, strings

Companies: google, amazon, microsoft, bloomberg

Level: swe2, swe3

DP table O(mn): dp[i][j] = longest common substring ending at s1[i-1],s2[j-1]. Reset to 0 on mismatch. Track max and its position to extract the result.

Longest Palindromic Subsequence Python | Interval DP

Find longest palindromic subsequence using interval DP in Python. LPS via LCS or direct DP.

Topics: dynamic-programming, strings

Companies: amazon, google, microsoft, meta

Level: swe2, swe3

Interval DP: dp[i][j] = LPS length in s[i..j]. Base: dp[i][i]=1. If s[i]==s[j]: dp[i][j]=dp[i+1][j-1]+2. Else max(dp[i+1][j], dp[i][j-1]). Fill by increasing length.

Distinct Subsequences Python | Count Ways DP

Count distinct subsequences of s equal to t using DP in Python. O(mn) solution.

Topics: dynamic-programming, strings

Companies: google, amazon, meta, microsoft

Level: swe3, senior

DP O(mn): dp[i][j] = ways to form t[:j] from s[:i]. On char match, we can either use s[i] (add dp[i-1][j-1]) or skip it (add dp[i-1][j]). On mismatch, only skip.

Stone Game DP Python | Game Theory Interval DP

Solve Stone Game with interval DP and mathematical insight in Python. Optimal play game theory.

Topics: dynamic-programming, math

Companies: google, amazon, jane-street, two-sigma

Level: swe2, swe3

DP interval + math insight: Mathematical: Alice always wins (return True). DP proof: dp[i][j] = best score difference for current player over opponent. If dp[0][n-1] > 0, first player wins.

Strange Printer Python | Interval DP Minimum Turns

Solve strange printer problem with interval DP in Python. Minimum printing operations.

Topics: dynamic-programming

Companies: google, amazon, microsoft, meta

Level: senior, staff

Interval DP: dp[i][j] = min turns to print s[i..j]. Start with 1 turn per character. If s[k]==s[j], we can merge the j-th char printing into the k-th range, saving a turn.

Number of Music Playlists Python | Combinatorial DP

Count valid music playlists with constraints using DP in Python. Song replay restriction with modular arithmetic.

Topics: dynamic-programming, combinatorics

Companies: google, amazon, spotify, netflix

Level: swe3, senior

DP with song count constraint: dp[i][j] = playlists of exactly i songs using j distinct songs. Transitions: add new song (n-j+1 choices) or replay old (max(j-k,0) choices since k songs blocked).

Cherry Pickup II Python | Two Robots Grid DP

Solve Cherry Pickup II with two robots using 3D DP in Python. Maximize cherries collected simultaneously.

Topics: dynamic-programming, matrix

Companies: google, amazon, microsoft, meta

Level: senior, staff

3D DP row by row: dp[c1][c2] = max cherries when robots are at columns c1 and c2 at the current row. Process row by row, trying all 9 movement combinations.

Painting the Walls Python | Knapsack DP

Solve painting the walls problem with knapsack DP in Python. Minimize cost with free painter credits.

Topics: dynamic-programming

Companies: google, amazon, microsoft, meta

Level: swe3, senior

Knapsack DP: dp[j] = min cost to cover exactly j walls. For each wall i, it covers time[i]+1 walls at cost[i]. Fill from right like 0/1 knapsack.

Count Ways Build Good Strings Python | DP Modular

Count good strings of given length range using DP with modular arithmetic in Python.

Topics: dynamic-programming, math

Companies: google, amazon, meta, microsoft

Level: swe2, swe3

DP over lengths: dp[i] = number of ways to form a string of exactly length i. Add zero-block or one-block to shorter strings. Sum dp[low..high].

Minimum Cost Cut Stick Python | Interval DP

Solve minimum cost to cut a stick with interval DP in Python. Optimize cut order for minimum total cost.

Topics: dynamic-programming, intervals

Companies: google, amazon, microsoft, two-sigma

Level: swe3, senior

Interval DP: Add boundaries 0 and n. Sort cuts. dp[i][j] = min cost to cut all positions strictly between cuts[i] and cuts[j]. Try each cut k as the last cut in this interval.

Maximum Profit Job Scheduling Python | Weighted Interval DP

Solve maximum profit job scheduling with DP and binary search in Python. Weighted interval scheduling O(n log n).

Topics: dynamic-programming, binary-search, intervals

Companies: google, amazon, microsoft, bloomberg

Level: swe3, senior

DP + binary search: Sort jobs by endTime. dp[i] = max profit with first i jobs. For each job, binary search for latest non-overlapping job j (end[j] <= start[i]). dp[i] = max(dp[i-1], profit[i] + dp[j]).

Sieve of Eratosthenes Python | Prime Numbers O(n log log n)

Implement Sieve of Eratosthenes to find all primes up to N in Python. O(n log log n) prime enumeration.

Topics: math, number-theory

Companies: google, amazon, microsoft, jane-street

Level: new-grad, swe2

Sieve of Eratosthenes: Initialize all as prime. For each prime p, mark p^2, p^2+p, p^2+2p... as composite. Only iterate p up to sqrt(N).

Prime Factorization Python | Trial Division SPF Sieve

Implement prime factorization with trial division and smallest prime factor sieve in Python.

Topics: math, number-theory

Companies: google, amazon, jane-street, two-sigma

Level: new-grad, swe2

Trial division + SPF sieve: Trial division: divide out 2 then odd numbers up to sqrt(n). If n>1 remains, it is prime. SPF sieve enables fast batch factorization.

Extended Euclidean Algorithm Python | GCD Bezout Identity

Implement Extended Euclidean Algorithm to find GCD and Bezout coefficients in Python.

Topics: math, number-theory

Companies: google, jane-street, two-sigma, imc

Level: swe2, swe3

Extended Euclidean recursive: Recurse with extended_gcd(b, a%b). Unwind: x = y1, y = x1 - (a//b)*y1. Verify: a*x + b*y == gcd.

Modular Exponentiation Python | Fast Power Binary Exp

Implement modular exponentiation using binary fast power in Python. O(log n) exponentiation.

Topics: math, number-theory, bit-manipulation

Companies: google, amazon, jane-street, two-sigma

Level: new-grad, swe2

Binary exponentiation iterative: Process bits of exp from LSB to MSB. If bit is set, multiply result by current base. Square the base at each step.

Modular Inverse Python | Fermat Extended GCD

Compute modular inverse using Fermat little theorem and Extended GCD in Python.

Topics: math, number-theory

Companies: google, jane-street, two-sigma, imc

Level: swe2, swe3

Fermat + Extended GCD: Fermat: a^(p-1) ≡ 1 (mod p) => a^(p-2) ≡ a^(-1) (mod p). ExtGCD: solve a*x + m*y = 1; x mod m is the inverse.

Chinese Remainder Theorem Python | System of Congruences

Solve system of congruences using Chinese Remainder Theorem in Python. CRT implementation.

Topics: math, number-theory

Companies: jane-street, two-sigma, google, renaissance

Level: senior, staff

CRT construction: Compute M = product of all moduli. For each congruence i, compute Mi=M/mi and its inverse yi mod mi. Solution = sum(ri * Mi * yi) mod M.

Catalan Numbers Python | DP Formula BST Count

Compute Catalan numbers with DP and closed formula in Python. Count BSTs, parenthesizations.

Topics: math, combinatorics, dynamic-programming

Companies: google, amazon, jane-street, microsoft

Level: swe2, swe3

DP + closed form: DP: C[n] = sum of C[i]*C[n-1-i]. Formula: C(n) = C(2n,n)/(n+1). Both give same result; formula is O(n) with big integer arithmetic.

nCr mod p Python | Lucas Theorem Factorial Precompute

Compute C(n,r) mod prime p using factorial precomputation and Lucas theorem in Python.

Topics: math, combinatorics, number-theory

Companies: google, jane-street, two-sigma, renaissance

Level: senior, staff

Factorial precompute + Lucas: Precompute factorials and modular inverses up to MAXN. C(n,r) = fact[n] * inv_fact[r] * inv_fact[n-r] mod p. Lucas handles n >= p by recursing on digits base-p.

Matrix Exponentiation Fibonacci Python | O(log n)

Compute nth Fibonacci in O(log n) using matrix exponentiation in Python. Generalize to any linear recurrence.

Topics: math, divide-and-conquer

Companies: google, amazon, jane-street, two-sigma

Level: swe3, senior

Matrix exponentiation: Define matrix mult. Apply binary exponentiation to matrix [[1,1],[1,0]]. Extract F(n) from result[0][1].

FFT Polynomial Multiplication Python | O(n log n)

Multiply polynomials in O(n log n) using FFT in Python. Cooley-Tukey recursive FFT implementation.

Topics: math, divide-and-conquer

Companies: google, jane-street, two-sigma, renaissance

Level: staff

Cooley-Tukey FFT: Recursive Cooley-Tukey: split into even/odd, recurse, combine with twiddle factors. Inverse FFT conjugates twiddle and divides by n. Pointwise multiply in frequency domain.

Bloom Filter Python | Probabilistic Set Membership

Implement a Bloom filter with optimal parameters in Python. Space-efficient probabilistic data structure.

Topics: system-design-coding, bit-manipulation, hash-map

Companies: google, amazon, meta, databricks

Level: senior, staff

Bloom filter with optimal k and m: Compute optimal bit count m = -n*ln(p)/ln(2)^2 and hash count k = (m/n)*ln(2). Use k independent hash functions (seed variants of Python hash). Track bit array as bytearray.

Skip List Python | Probabilistic Ordered List O(log n)

Implement Skip List with random levels for O(log n) search, insert, delete in Python.

Topics: system-design-coding, design-patterns

Companies: google, amazon, redis, databricks

Level: senior, staff

Skip list with random levels: Header node links at all levels. Search descends levels. Insert finds update[] pointers, generates random level, splices in node. Delete finds and removes node from all levels.

Trie Autocomplete Service Python | Frequency Ranking Top-K

Build trie-based autocomplete with per-node top-k frequency cache in Python. Production-ready design.

Topics: trie, system-design-coding, heap

Companies: google, amazon, meta, linkedin

Level: swe3, senior

Trie with per-node top-k cache: Each node caches top-k (freq, word) pairs sorted by freq. On insert, traverse and update each node's heap. Query just returns the prefix node's cached list.

Write-Ahead Log WAL Python | Crash Recovery

Implement Write-Ahead Log for crash recovery in Python. Append, checkpoint, and replay WAL entries.

Topics: system-design-coding

Companies: amazon, google, databricks, snowflake

Level: senior, staff

WAL with checkpoint and replay: Append log entries with monotonically increasing LSN. Checkpoint saves state snapshot and LSN. Recovery restores checkpoint state then replays all log entries after checkpoint LSN.

Merkle Tree Python | Hash Tree Data Integrity

Implement Merkle Tree for data integrity verification in Python. Build, proof generation, and verification.

Topics: system-design-coding, tree

Companies: amazon, google, stripe, databricks

Level: senior, staff

Bottom-up Merkle tree: Compute leaf hashes. Repeatedly hash adjacent pairs (duplicate last if odd) until one root. Store all levels for proof generation. Proof = sibling hashes from leaf to root.

Inverted Index Python | Search Engine Build and Query

Build an inverted index and support AND/OR queries in Python. Foundation of search engines.

Topics: system-design-coding, hash-map, strings

Companies: google, amazon, elasticsearch, linkedin

Level: swe3, senior

Inverted index with merge-based AND/OR: Index maps term to sorted doc_id list. AND: intersect posting lists with two-pointer. OR: merge sorted lists with set. Start AND with smallest list for efficiency.

Count-Min Sketch Top-K Python | Heavy Hitters Stream

Implement Count-Min Sketch for streaming top-K heavy hitters in Python. Probabilistic frequency estimation.

Topics: system-design-coding, hash-map

Companies: google, amazon, meta, twitter

Level: senior, staff

Count-Min Sketch + heap top-K: For each of d rows, hash item to column and increment. Query returns minimum across all rows (overcount is possible, undercount is not). Combine with a counter for exact top-K in small domains.

Sliding Window Rate Limiter Python | Deque O(1)

Implement sliding window rate limiter with deque in Python. Accurate per-second request limiting.

Topics: rate-limiting, system-design-coding, queue

Companies: stripe, amazon, google, netflix

Level: swe3, senior

Deque-based sliding window: Deque stores timestamps of recent requests. On each request, evict timestamps outside the window. If remaining count < limit, allow and record; otherwise deny.

Snowflake ID Generator Python | Distributed Unique ID

Implement Twitter Snowflake 64-bit distributed ID generator in Python. Time-sortable unique IDs.

Topics: system-design-coding, bit-manipulation

Companies: twitter, amazon, meta, linkedin

Level: senior, staff

Snowflake 64-bit ID: Shift timestamp left by 22 bits, machine_id by 12 bits, OR with sequence. If same millisecond, increment sequence; overflow -> busy-wait for next ms.

Event Sourcing Store Python | Append Events Replay State

Implement event sourcing with append-only log, snapshot, and time-travel in Python.

Topics: system-design-coding

Companies: amazon, google, stripe, confluent

Level: senior, staff

Event sourcing with snapshots: Append-only event log. get_state replays all events or from last snapshot. Snapshot saves current state at event index. state_at replays events 0..t from nearest snapshot before t.

Convex Hull Graham Scan Python | O(n log n) Geometry

Compute convex hull using Graham Scan in Python. O(n log n) algorithm with cross product and stack.

Topics: geometry, sorting

Companies: google, amazon, nvidia, deepmind

Level: swe3, senior

Graham Scan: Find lowest y (then leftmost x) point. Sort rest by polar angle. Maintain stack: pop while cross product <= 0 (right turn or collinear). Stack is the hull.

Line Segment Intersection Python | Cross Product Orientation

Test if two line segments intersect using cross product orientation in Python. Handles collinear cases.

Topics: geometry, math

Companies: google, nvidia, amazon, deepmind

Level: swe3, senior

Orientation-based intersection test: Four orientation checks determine general intersection. Special cases: collinear points handled by on_segment check.

Closest Pair of Points Python | Divide and Conquer O(n log n)

Find closest pair of points in O(n log n) using divide and conquer in Python. Strip optimization.

Topics: geometry, divide-and-conquer, sorting

Companies: google, amazon, two-sigma, nvidia

Level: senior, staff

Divide and Conquer O(n log n): Sort by x. Divide at mid. Recurse on both halves. Get d = min(d_left, d_right). Check strip |x - mid_x| < d sorted by y; compare at most 7 forward neighbors.

Single Number III Python | Two Singles XOR Bit Manipulation

Find two single numbers in array using XOR partitioning in Python. O(n) O(1) bit manipulation.

Topics: bit-manipulation

Companies: google, amazon, microsoft, meta

Level: swe2, swe3

XOR partition trick: XOR all to get a^b. Isolate LSB of a^b. Partition: numbers with that bit set vs not. XOR each partition to extract a and b.

Reverse Bits Python | 32-bit Integer Bit Manipulation

Reverse all 32 bits of an integer in Python. Bit-by-bit reversal with 32-bit mask.

Topics: bit-manipulation

Companies: apple, google, amazon, microsoft

Level: new-grad, swe2

Bit-by-bit reversal: Loop 32 times. Each iteration: shift result left 1, OR in LSB of n, shift n right 1. Mask to 32 bits at end.

Hamming Weight Python | Brian Kernighan Bit Count

Count set bits (Hamming weight) using Brian Kernighan trick in Python. O(k) where k is popcount.

Topics: bit-manipulation

Companies: apple, google, amazon, microsoft

Level: new-grad, swe2

Brian Kernighan trick: Repeatedly clear the lowest set bit with n &= (n-1). Count iterations. This is O(k) where k is popcount, better than O(32) for sparse bits.

Bit Manipulation Tricks Python | XOR Swap LSB Power of 2

Master bit manipulation tricks in Python: swap, LSB, power of 2, set/clear bits, missing number.

Topics: bit-manipulation, math

Companies: google, amazon, microsoft, apple

Level: swe2, swe3

Bit manipulation toolkit: Collection of O(1) bit tricks. Each operation uses XOR, AND, OR, shift in a single expression.

XOR Linked List Python | Memory-Efficient Doubly Linked List

Implement XOR linked list with ctypes in Python. Memory-efficient doubly linked list using XOR pointers.

Topics: bit-manipulation, linked-list

Companies: google, amazon, microsoft, apple

Level: senior, staff

XOR linked list with ctypes: Store XOR of prev/next id in each node. Anchor nodes in a list to prevent GC. Use ctypes.cast to recover object from id. Traverse by XORing stored id with known prev id.

Gray Code Python | n-bit Gray Code Generation

Generate n-bit Gray codes using XOR formula in Python. Adjacent codes differ by exactly one bit.

Topics: bit-manipulation, math

Companies: apple, google, amazon, microsoft

Level: swe2, swe3

Formula: i XOR (i>>1): Direct formula: gray(i) = i ^ (i >> 1). Generate all 2^n values. Verify adjacency property. Decode with running XOR from MSB.

Subsets Bitmask Python | Enumerate All 2^n Subsets

Enumerate all 2^n subsets using bitmask iteration in Python. O(n * 2^n) iterative approach.

Topics: bit-manipulation, backtracking

Companies: google, amazon, microsoft, meta

Level: new-grad, swe2

Bitmask enumeration: For each mask in 0..2^n-1, include nums[i] if bit i is set. Result has 2^n subsets in consistent order.

Eulerian Path Circuit Python | Hierholzer Algorithm

Find Eulerian path and circuit with Hierholzer's algorithm in Python. O(E) directed graph traversal.

Topics: graph, dfs

Companies: google, amazon, microsoft, bloomberg

Level: swe3, senior

Hierholzer's algorithm: Build adjacency list. Find start node (out > in or node 0 for circuit). Iterative DFS: push to stack, follow edges. When node has no more edges, pop to result. Reverse result.

Hamiltonian Path Backtracking Python | NP-Complete

Find Hamiltonian path using backtracking with pruning in Python. NP-complete graph problem.

Topics: graph, backtracking

Companies: google, amazon, microsoft, two-sigma

Level: senior, staff

Backtracking with pruning: Build adjacency set. DFS from each start vertex. At each step try unvisited neighbors. Backtrack when no neighbors available and path is incomplete.

Max Flow Min Cut Python | Edmonds-Karp BFS Ford-Fulkerson

Find maximum flow using Edmonds-Karp algorithm in Python. BFS-based Ford-Fulkerson O(VE^2).

Topics: graph, bfs

Companies: google, amazon, microsoft, two-sigma

Level: senior, staff

Edmonds-Karp BFS: Build residual graph. BFS to find shortest augmenting path. Augment by bottleneck. Repeat. Total flow = sum of augmentations.

Hungarian Algorithm Python | Minimum Weight Bipartite Matching

Implement Hungarian algorithm for minimum weight bipartite matching in Python. O(n^3) assignment problem.

Topics: graph, dynamic-programming

Companies: google, amazon, two-sigma, renaissance

Level: staff

Hungarian algorithm O(n^3): Use scipy for clean O(n^3) solution. Manual implementation uses potential arrays and augmenting paths. Both return same optimal assignment.

Articulation Points Tarjan Python | Low-Link O(V+E)

Find articulation points using Tarjan low-link algorithm in Python. O(V+E) cut vertex detection.

Topics: graph, dfs

Companies: google, amazon, microsoft, bloomberg

Level: senior, staff

Tarjan low-link DFS: DFS assigns discovery times. low[u] = min reachable discovery time from subtree of u. Articulation point: root with 2+ DFS children, or non-root where any child v has low[v] >= disc[u].