Problem: 10,000 contacts - search by typing first few letters instantly
Store all contacts in array
Time: O(n * m) - Check every contact
Result: Slow for large lists
Search "Joh" in 10k contacts = 10,000 comparisons = ~500ms delay
Store in tree structure by letters
Time: O(m) - Only length of search
Result: Instant search
Search "Joh" in 10k contacts = 3 lookups (J-o-h) = ~1ms instant!
Try it: Type names like ALICE, BOB, ALEX, JOHN, JANE and click "Add Word" to build the tree. Click "Search" to highlight the path. Gold nodes mark complete words.
class TrieNode:
def __init__(self):
self.children = {} # Map: character -> TrieNode
self.is_end_of_word = False
class Trie:
"""Trie for autocomplete and prefix search - O(m) operations"""
def __init__(self):
self.root = TrieNode()
def insert(self, word: str):
"""Insert word - Time: O(m) where m = word length"""
node = self.root
for char in word.lower():
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def search(self, word: str) -> bool:
"""Search exact word - Time: O(m)"""
node = self._find_node(word.lower())
return node is not None and node.is_end_of_word
def starts_with(self, prefix: str) -> bool:
"""Check if prefix exists - Time: O(m)"""
return self._find_node(prefix.lower()) is not None
def autocomplete(self, prefix: str, limit: int = 10) -> list:
"""Get suggestions - Time: O(p + n) where p=prefix, n=results"""
node = self._find_node(prefix.lower())
if not node:
return []
results = []
self._dfs_words(node, prefix.lower(), results, limit)
return results
def _find_node(self, prefix: str):
node = self.root
for char in prefix:
if char not in node.children:
return None
node = node.children[char]
return node
def _dfs_words(self, node, prefix, results, limit):
if len(results) >= limit:
return
if node.is_end_of_word:
results.append(prefix)
for char, child in sorted(node.children.items()):
self._dfs_words(child, prefix + char, results, limit)
# Usage Example:
trie = Trie()
trie.insert("Alice")
trie.insert("Alex")
trie.insert("Bob")
print(trie.search("Alice")) # True
print(trie.autocomplete("Al")) # ['alex', 'alice']
Problem: Check if username exists among 1 billion users instantly (1ms vs 200ms DB query)
Try it: Add "mike", then check "mike" (taken). Check "sara" (available). Key insight: If ANY bit is 0, username is DEFINITELY available. If all bits are 1, it's POSSIBLY taken (need DB check).
import hashlib
class BloomFilter:
"""Probabilistic membership testing - O(k) operations
Standard implementation with 64-bit array and 3 hash functions
"""
def __init__(self, size: int = 64, hash_count: int = 3):
self.size = size # 64 bits is standard for small-medium datasets
self.hash_count = hash_count # k=3 minimizes false positive rate
self.bit_array = [0] * size
def _hash(self, item: str, seed: int) -> int:
"""Generate hash with seed using MD5"""
h = hashlib.md5(f"{item}{seed}".encode())
return int(h.hexdigest(), 16) % self.size
def add(self, item: str):
"""Add item - Time: O(k) where k = hash_count"""
for i in range(self.hash_count):
index = self._hash(item, i)
self.bit_array[index] = 1
def might_contain(self, item: str) -> bool:
"""Check membership - Time: O(k)
Returns:
True = MIGHT exist (could be false positive)
False = DEFINITELY doesn't exist (no false negatives)
False Positive Rate: (1 - e^(-kn/m))^k
where k=hash_count, n=items, m=size
For k=3, n=5, m=64: FP rate ≈ 0.8%
"""
for i in range(self.hash_count):
index = self._hash(item, i)
if self.bit_array[index] == 0:
return False # Definitely not in set
return True # Might be in set
# Usage Example:
bf = BloomFilter(size=64, hash_count=3)
bf.add("alice")
bf.add("bob")
print(bf.might_contain("alice")) # True (taken)
print(bf.might_contain("charlie")) # False (available)
# Why k=3? Optimal k ≈ (m/n) * ln(2)
# For m=64, n=10: k_optimal ≈ 4.4, so k=3 or k=4 both work well
Problem: Store recently viewed videos in limited memory (capacity: 10)
Try it: Type "V4" and click "PUT" to add. Type "V1" and click "GET" to watch - it moves to MRU. Add more videos (V5, V6, V7...) to see HashMap expand. After 10 videos, oldest gets evicted!
Add "V5" when full to see LRU eviction. Both operations are O(1)!class Node:
"""Doubly Linked List Node"""
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
"""LRU Cache with O(1) operations - HashMap + Doubly Linked List"""
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = {} # key -> Node
self.head = Node(0, 0) # MRU (Most Recently Used)
self.tail = Node(0, 0) # LRU (Least Recently Used)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key: int) -> int:
"""Get value and move to MRU - Time: O(1)"""
if key not in self.cache:
return -1
node = self.cache[key]
self._remove(node)
self._add_to_head(node) # Move to MRU
return node.value
def put(self, key: int, value):
"""Add/update and evict LRU if full - Time: O(1)"""
if key in self.cache:
self._remove(self.cache[key])
node = Node(key, value)
self.cache[key] = node
self._add_to_head(node)
if len(self.cache) > self.capacity:
lru = self.tail.prev # Get LRU
self._remove(lru)
del self.cache[lru.key]
def _add_to_head(self, node):
"""Add node after head (MRU position)"""
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def _remove(self, node):
"""Remove node from list"""
node.prev.next = node.next
node.next.prev = node.prev
# Usage Example:
cache = LRUCache(3)
cache.put(1, "Video1")
cache.put(2, "Video2")
cache.put(3, "Video3")
print(cache.get(1)) # Video1 (moves to MRU)
cache.put(4, "Video4") # Evicts 2 (was LRU)
print(cache.get(2)) # -1 (evicted)
Problem: Find 2nd-degree connections for suggestions
Try it: Click "Start BFS" then "Next Step" to see level-by-level traversal. Gold = YOU, Blue = Visited, Green = Queue.
from collections import deque, defaultdict
class Graph:
"""Graph with BFS traversal for social networks - O(V+E)"""
def __init__(self):
self.graph = defaultdict(list) # Adjacency list
def add_edge(self, u: str, v: str):
"""Add undirected edge (bidirectional)"""
self.graph[u].append(v)
self.graph[v].append(u)
def bfs(self, start: str) -> list:
"""Breadth-First Search - Time: O(V+E)"""
visited = set([start])
queue = deque([start])
result = []
while queue:
node = queue.popleft()
result.append(node)
for neighbor in self.graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return result
def shortest_path(self, start: str, end: str) -> list:
"""Find shortest path - Time: O(V+E)"""
if start == end:
return [start]
visited = set([start])
queue = deque([(start, [start])]) # (node, path)
while queue:
node, path = queue.popleft()
for neighbor in self.graph[node]:
if neighbor == end:
return path + [neighbor]
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, path + [neighbor]))
return None # No path found
# Usage Example:
g = Graph()
# Build 4-level social network (16 people, 5 levels 0-4)
g.add_edge("YOU", "Alice")
g.add_edge("YOU", "Bob")
g.add_edge("Alice", "Dave")
g.add_edge("Alice", "Emma")
g.add_edge("Bob", "Frank")
g.add_edge("Dave", "Jack") # Level 3
g.add_edge("Frank", "Leo") # Level 3
g.add_edge("Jack", "Nina") # Level 4
print(g.bfs("YOU")) # BFS traversal from YOU
print(g.shortest_path("YOU", "Nina")) # Shortest path: YOU→Alice→Dave→Jack→Nina
Challenge: Find 5 nearest drivers among 100,000+ in <5ms (naive O(n) approach = 200ms)
How it works: Map divided into 4 quadrants (NW, NE, SW, SE). When searching, only the user's quadrant is checked first - avoiding 75% of calculations! Real Uber uses S2 geometry with deeper hierarchies. O(log n) vs O(n) = 40x faster at scale.
import math
class Point:
"""2D Point with data"""
def __init__(self, x: float, y: float, data=None):
self.x, self.y, self.data = x, y, data
def distance_to(self, other) -> float:
return math.sqrt((self.x - other.x)**2 + (self.y - other.y)**2)
class Rectangle:
"""Bounding box for QuadTree"""
def __init__(self, x: float, y: float, width: float, height: float):
self.x, self.y = x, y
self.width, self.height = width, height
def contains(self, point: Point) -> bool:
return (self.x - self.width/2 <= point.x <= self.x + self.width/2 and
self.y - self.height/2 <= point.y <= self.y + self.height/2)
def intersects(self, other) -> bool:
return not (other.x - other.width/2 > self.x + self.width/2 or
other.x + other.width/2 < self.x - self.width/2 or
other.y - other.height/2 > self.y + self.height/2 or
other.y + other.height/2 < self.y - self.height/2)
class QuadTree:
"""QuadTree for 2D spatial queries - O(log n) operations"""
def __init__(self, boundary: Rectangle, capacity: int = 4):
self.boundary = boundary
self.capacity = capacity
self.points = []
self.divided = False
self.nw = self.ne = self.sw = self.se = None
def insert(self, point: Point) -> bool:
"""Insert point - Time: O(log n) average"""
if not self.boundary.contains(point):
return False
if len(self.points) < self.capacity:
self.points.append(point)
return True
if not self.divided:
self.subdivide()
return (self.nw.insert(point) or self.ne.insert(point) or
self.sw.insert(point) or self.se.insert(point))
def subdivide(self):
"""Split into 4 quadrants"""
x, y, w, h = self.boundary.x, self.boundary.y, self.boundary.width/2, self.boundary.height/2
self.nw = QuadTree(Rectangle(x-w/2, y-h/2, w, h), self.capacity)
self.ne = QuadTree(Rectangle(x+w/2, y-h/2, w, h), self.capacity)
self.sw = QuadTree(Rectangle(x-w/2, y+h/2, w, h), self.capacity)
self.se = QuadTree(Rectangle(x+w/2, y+h/2, w, h), self.capacity)
self.divided = True
def query(self, range_rect: Rectangle) -> list:
"""Find all points in range - Time: O(log n + k)"""
found = []
if not self.boundary.intersects(range_rect):
return found
for point in self.points:
if range_rect.contains(point):
found.append(point)
if self.divided:
found.extend(self.nw.query(range_rect))
found.extend(self.ne.query(range_rect))
found.extend(self.sw.query(range_rect))
found.extend(self.se.query(range_rect))
return found
# Usage Example:
qt = QuadTree(Rectangle(500, 500, 1000, 1000))
qt.insert(Point(100, 100, "Driver1"))
qt.insert(Point(150, 150, "Driver2"))
user = Point(120, 120)
search_range = Rectangle(120, 120, 100, 100)
nearby = qt.query(search_range) # Find drivers near user
Patients triaged by severity (not arrival time). Critical = top of heap.
Chrome's history uses two stacks (back stack, forward stack).
Office printer processes jobs in order (FIFO = First In, First Out).
Binary Search Tree maintains sorted order for fast range queries.
Python's dict is a hash table - O(1) lookup makes it blazing fast.
Shortest path with traffic uses DP (overlapping subproblems).
"Show sales from Jan-Mar" = range query. Segment tree handles it in O(log n).
You're starting with less programming background, so spend extra time on:
THE interview prep platform. 2500+ problems, company tags, discuss solutions
Start: LeetCode 75 Study Plan
Learn coding through GAMES! Visual puzzles, multiplayer battles, fun challenges
Best for: Making DSA fun
Simple, free Java/Python practice. Instant feedback, perfect for beginners
Great for: First 50 problems
Good for beginners, certification tests. Many companies use for screening
Practice their test format
FREE mentorship! Real humans review your code. 60+ languages
Unique: Human mentors
Gamified learning with ranks (Kyu/Dan). Community-created challenges
Level up like a game
Animated visualizations of ALL data structures. See how algorithms work step-by-step!
Essential tool
Interactive animations, edit code and see changes. Open source!
Code + visualization
University of San Francisco's tool. Trees, graphs, sorting - all animated
Academic quality
Weekly contests, rating system. Builds speed & advanced problem-solving
After 200+ LeetCode
Japanese platform, excellent beginner contests. Clean problem statements
Beginner-friendly CP
OG competitive programming. SRMs (Single Round Matches), cash prizes
For CP veterans
Complete free course by Raj Vikramaditya. Best for Indian students - covers everything!
YouTube + Website, Hindi/English
Curated 150 essential problems + video solutions. Perfect roadmap for beginners
Blind 75: Must-solve list
Structured learning paths, mock interviews, company-specific prep. Indian startup!
Free tier available
Indian site with articles, practice, interview experiences. Great reference
Best for theory + prep
Gayle McDowell. THE interview Bible. 189 problems + patterns
Must-read book
MIT textbook. Deep theory, proofs. Reference for advanced topics
Advanced/Academic
Aditya Bhargava. Visual, beginner-friendly. Fun illustrations!
Perfect for starters
Clear explanations, visual diagrams, covers LeetCode patterns. Concise & effective
Indian accent, detailed, A-Z complete course, best for beginners. Hindi/English mix
Theory-focused, animations, great for understanding fundamentals. Classic!
Medium-hard problems, DP expert, great for depth. Indian creator
Graph algorithms specialist. Clear animations, computer science depth
Interview-focused, whiteboard-style explanations. Practical approach
Spend 70% time CODING (LeetCode, CodinGame, CodingBat) and 30% learning theory (YouTube, books, visualizers). Too much theory without practice = waste!
Best for:
Best for:
Best for:
Free for students!
Best for:
NEVER do this:
| Complexity | Name | Example Algorithm | n=100 Operations | Interview Frequency |
|---|---|---|---|---|
| O(1) | Constant | Array access, HashMap get/put | 1 | Very Common |
| O(log n) | Logarithmic | Binary search, Balanced BST ops | ~7 | Very Common |
| O(n) | Linear | Single loop, Array traversal | 100 | Most Common! |
| O(n log n) | Linearithmic | Merge sort, Quick sort (avg) | ~700 | Common |
| O(n^2) | Quadratic | Nested loops, Bubble sort | 10,000 | Common (avoid if n>1000) |
| O(2^n) | Exponential | Recursive Fibonacci (naive) | 1.27 × 10^30 | Rare (only small n) |
| O(n!) | Factorial | Traveling salesman (brute force) | 9.3 × 10^157 | Very Rare |
Good for n ≤ 10^5:
Never acceptable:
When: Sorted array, pairs/triplets
Example: Two Sum II, Remove Duplicates
When: Subarray/substring problems
Example: Longest Substring Without Repeating
When: Linked list cycles, middle element
Example: Detect cycle, Find middle
When: Count occurrences, anagrams
Example: Group Anagrams, Two Sum
When: Shortest path, level traversal
Example: Binary tree level order, Word Ladder
When: Explore all paths, backtracking
Example: Number of Islands, Path Sum
When: Overlapping subproblems, optimization
Example: Climbing Stairs, Coin Change
When: Sorted data, search in range
Example: Search in rotated array
When: Locally optimal = globally optimal
Example: Jump Game, Meeting Rooms
When: Find K largest/smallest
Example: Kth Largest, Top K Frequent
In interviews, ask yourself:
Result: Interview disaster!
Result: Interview confidence!
Free peer-to-peer mock interviews
Anonymous interviews with engineers
Company-specific mock tests
Form study groups on campus
Before applying to companies:
Best starter list - Covers all patterns, 150 essential problems organized by topic
Start here if you're a beginner
Most important 75 problems - If you can solve these, you can crack 80% interviews
Time-limited? Do these first
180 problems - Indian context, covers service + product companies
Best for Indian campus placements
150 most asked in real interviews - Directly from LeetCode data
Proven track record
Week-by-week study plan - Adaptive difficulty, customizable by time available
Good for structured learners
Top 50 per company - Google, Amazon, Microsoft, etc.
Paid but worth it for target company
I commit to:
Let's discuss your specific doubts, company targets, and study plans
"Success in DSA is not about talent. It's about showing up daily, struggling through problems, and refusing to quit."