π "Find two numbers in an array that sum to a target." β Two-pointer or hash map approach. O(n) time.
π "Rotate an array k positions to the right." β Reverse entire array, then reverse first k and last n-k elements.
π "Find the maximum subarray sum." β Kadane's algorithm: track current_sum and max_sum as you scan.
# Python Array (list) operations# Insert at indexdefinsert(arr, idx, val):
arr.insert(idx, val) # O(n) β shifts elements right# Delete at indexdefdelete(arr, idx):
return arr.pop(idx) # O(n) β shifts elements left# Linear searchdefsearch(arr, val):
for i, x in enumerate(arr):
if x == val: return i
return -1 # O(n)# Bubble sortdefbubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# O(nΒ²) time, O(1) space
Linked List Visualization
Ready. Choose an operation.
Step Mode
Operation
Time
Space
Access/Search
O(n)
O(1)
Insert at head
O(1)
O(1)
Insert at tail (with tail ptr)
O(1)
O(1)
Insert at position
O(n)
O(1)
Delete at head
O(1)
O(1)
Reverse
O(n)
O(1)
π "Reverse a linked list." β Three pointers: prev, curr, next. Iterate and reassign. O(n) time, O(1) space.
π "Detect a cycle in a linked list." β Floyd's tortoise-and-hare: fast (2 steps) and slow (1 step) meet inside cycle.
π "Find the middle of a linked list." β Two pointers: slow moves 1, fast moves 2. When fast reaches end, slow is at middle.
classListNode:
def__init__(self, val=0, next=None):
self.val = val; self.next = next
classLinkedList:
def__init__(self):
self.head = Nonedefappend(self, val):
node = ListNode(val)
if not self.head: self.head = node; return
curr = self.head
while curr.next: curr = curr.next
curr.next = node
defreverse(self):
prev, curr = None, self.head
while curr:
nxt = curr.next
curr.next = prev
prev = curr; curr = nxt
self.head = prev
defhas_cycle(self):
slow = fast = self.head
while fast and fast.next:
slow = slow.next; fast = fast.next.next
if slow == fast: return Truereturn False
Stack Visualization (LIFO)
Ready. Push some values.
Operation
Time
Space
Push
O(1)
O(1)
Pop
O(1)
O(1)
Peek/Top
O(1)
O(1)
Search
O(n)
O(1)
π "Valid Parentheses." β Push open brackets; pop and match when close bracket seen. Return stack.isEmpty() at end.
π "Next Greater Element." β Monotonic decreasing stack. Pop when you find a larger element β that larger element is the answer.
π "Min Stack β support getMin() in O(1)." β Maintain a second stack tracking minimums. Push current min alongside each value.
classStack:
def__init__(self): self._data = []
defpush(self, val): self._data.append(val) # O(1)defpop(self):
if not self._data: raise IndexError("Empty stack")
return self._data.pop() # O(1)defpeek(self):
if not self._data: raise IndexError("Empty stack")
return self._data[-1] # O(1)defis_empty(self): return len(self._data) == 0
# Classic: Valid Parenthesesdefis_valid(s):
stack, match = [], {')':'(', ']':'[', '}':'{'}
for c in s:
if c in"([{": stack.append(c)
elif not stack or stack[-1] != match[c]: return Falseelse: stack.pop()
return not stack
Queue Visualization (FIFO)
β FRONT (Dequeue)REAR (Enqueue) β
Ready. Enqueue some values.
Operation
Time
Space
Enqueue
O(1)
O(1)
Dequeue
O(1) with deque
O(1)
Peek
O(1)
O(1)
BFS traversal
O(V+E)
O(V)
π "Level order traversal of a binary tree." β Use a queue. Process each node and enqueue its children. Each level is one BFS iteration.
π "Implement a queue using two stacks." β Stack1 for enqueue. For dequeue, if Stack2 empty, pop everything from Stack1 into Stack2, then pop Stack2.
π "Sliding window maximum." β Use a deque (monotonic decreasing). Remove smaller elements as window slides right.
from collections import deque
classQueue:
def__init__(self): self._q = deque()
defenqueue(self, val): self._q.append(val) # O(1)defdequeue(self):
if not self._q: raise IndexError("Empty queue")
return self._q.popleft() # O(1)defpeek(self): return self._q[0] if self._q else None# BFS skeletondefbfs(graph, start):
visited, q = {start}, deque([start])
while q:
node = q.popleft()
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor); q.append(neighbor)
Binary Search TreeBalanced β
Ready. Insert nodes to build the tree.
Step Mode
Operation
Average
Worst (degenerate)
Search/Insert/Delete
O(log n)
O(n)
Min/Max
O(log n)
O(n)
In-order traversal
O(n)
O(n)
π "Validate a BST." β Pass min/max bounds down recursively: left subtree values must be < node, right must be > node.
π "Find Lowest Common Ancestor of two nodes in a BST." β If both values < node go left; if both > go right; otherwise current node is LCA.
π "Convert sorted array to BST." β Recursively pick midpoint as root, left half as left subtree, right half as right subtree. O(n).
classBST:
classNode:
def__init__(self,v): self.v=v; self.l=self.r=Nonedef__init__(self): self.root=Nonedefinsert(self, v):
def _ins(n,v):
if not n: return self.Node(v)
if v < n.v: n.l = _ins(n.l,v)
elif v > n.v: n.r = _ins(n.r,v)
return n
self.root = _ins(self.root, v)
definorder(self):
result=[]
def _io(n):
if not n: return
_io(n.l); result.append(n.v); _io(n.r)
_io(self.root); return result
Heap Visualization
Array representation:
Ready. Insert values.
Step Mode
Operation
Time
Space
Insert
O(log n)
O(1)
Extract min/max
O(log n)
O(1)
Peek min/max
O(1)
O(1)
Build from array
O(n)
O(1)
Heapsort
O(n log n)
O(1)
π "Find the K largest elements." β Min-heap of size K. For each element, if larger than heap min, replace and heapify down. O(n log k).
π "Merge K sorted lists." β Push first element of each list into min-heap. Extract min, push next from that list. O(n log k).
π "Find the median from a data stream." β Two heaps: max-heap for lower half, min-heap for upper half. Balance sizes after each insert.
π "Two Sum." β Hash map from value β index. For each num, check if target-num is in map. O(n).
π "Group Anagrams." β Hash map from sorted string β list of originals. O(nΒ·k log k) where k = max word length.
π "Longest Consecutive Sequence." β Put all nums in a set. For each num that has no num-1 in set, expand right. O(n).
# Python dict is a hash map
ht = {}
ht["name"] = "Alice"# Insert O(1)
val = ht.get("name") # Get O(1)del ht["name"] # Delete O(1)# Two Sum β classic hash map problemdeftwo_sum(nums, target):
seen = {}
for i, n in enumerate(nums):
complement = target - n
if complement in seen:
return [seen[complement], i]
seen[n] = i
return [] # O(n) time, O(n) space# Collision handling (chaining concept)defhash_fn(key, size):
return sum(ord(c) for c in str(key)) % size
Trie Visualization
Ready. Insert words to build the trie.
Step Mode
Operation
Time
Space
Insert word (len L)
O(L)
O(L)
Search word
O(L)
O(1)
Prefix search
O(P)
O(1)
Space total
β
O(total chars)
π "Implement autocomplete." β Insert all words into Trie. For prefix, find the prefix node, then DFS to collect all complete words below it.
π "Word Search II (find all words in a board)." β Build trie of target words, then DFS on board following trie edges. Prune branches not in trie.
π "Replace words with root in a sentence." β Build trie of root words. For each sentence word, find shortest prefix in trie and replace.
classTrieNode:
def__init__(self):
self.children = {} # char β TrieNode
self.is_end = FalseclassTrie:
def__init__(self): self.root = TrieNode()
definsert(self, word): # O(L)
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_end = Truedefsearch(self, word): # O(L)
node = self.root
for ch in word:
if ch not in node.children: return False
node = node.children[ch]
return node.is_end
defstarts_with(self, prefix): # O(P)
node = self.root
for ch in prefix:
if ch not in node.children: return False
node = node.children[ch]
return True