🎓 Welcome to CSE Helper
Choose a course to start learning algorithms, data structures, and SQL
Data Structures
Arrays, Stacks, Queues, Linked Lists, Trees, Heaps
Algorithms
Sorting, Pathfinding, Algorithm Analysis & Racing
Database Systems
SQL Lab, Practice Challenges, Lessons & Visualizer
⚡ Sorting Algorithms
⚡ Quick Sort
Quick Sort picks a "pivot" element and partitions the array into two sub-arrays: elements less than pivot vs. elements greater. It then recursively sorts the sub-arrays. Efficient and widely used!
Time Complexity
function quickSort(arr, lo = 0, hi = arr.length - 1) {
if (lo < hi) {
const pivot = arr[hi];
let i = lo - 1;
for (let j = lo; j < hi; j++) {
if (arr[j] <= pivot) {
i++;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
}
[arr[i + 1], arr[hi]] = [arr[hi], arr[i + 1]];
const p = i + 1;
quickSort(arr, lo, p - 1);
quickSort(arr, p + 1, hi);
}
return arr;
}
🧪 Your Coding World
This is YOUR space! Write code, experiment freely, and watch your algorithms come to life. You're in control here — make mistakes, learn from them, and grow! 🚀
📝 Your Code
🫧 Bubble Sort
Like bubbles rising in water, larger elements "bubble up" to the end of the array. We repeatedly step through the list, compare adjacent elements, and swap them if they're in the wrong order.
🏁 Algorithm Race
Watch two sorting algorithms compete head-to-head on the same data set!
⚙️ Race Setup
Merge Sort
ReadyBubble Sort
ReadyWinner!
Stats here
🔍 Searching
📖 The Library Story
You're in a library. A massive one. Your book is somewhere among 1,000 shelves...
The Slow Way (Linear Search): Check every single book. One by one. Starting from aisle one. You might be here all day—or all week.
The Smart Way (Binary Search): Books are alphabetized. Open to the middle—is your book before or after? Cut the remaining books in half. Repeat. 1,000 books? That's about 10 checks. A billion books? Only 30 checks. That's the power of logarithms.
🧠 Think First Challenge
Before we dive in, try this: You have a sorted list of 1 million numbers. How many comparisons would you need to find any number using:
Linear Search?
Binary Search?
📖 Reveal Answer
Linear: Up to 1,000,000 comparisons (worst case). Binary: Only ~20 comparisons! (log₂ of 1 million ≈ 20). That's why understanding algorithms matters.
📋 Linear Search
Check each element one by one until found. Works on any list.
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i # Found!
return -1 # Not found
⚡ Binary Search
Repeatedly divide the search space in half. Requires sorted array!
def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
🎯 When to Use What?
| Scenario | Best Choice | Why |
|---|---|---|
| Unsorted small list | Linear Search | Sorting overhead not worth it |
| Sorted array, search once | Binary Search | O(log n) is much faster |
| Unsorted, many searches | Sort first, then Binary | O(n log n) sort + O(log n) × searches |
✂️ Divide and Conquer
The oldest trick in the algorithm book: got a huge problem? Split it. Solve the pieces. Combine the answers. Merge Sort, Quick Sort, Binary Search—they all use this pattern.
🍕 The Pizza Problem
You've got a pizza the size of a table. How do you count every pepperoni? Don't stare at the whole thing—cut it in half. Count each half separately. Add them up.
Still too big? Cut again. Keep going until counting is easy. Then work backwards and combine your counts. That's Divide and Conquer: split → solve → combine.
If this feels like recursion, that's because it is. D&C and recursion are best friends.
🔑 The Three Steps
Break problem into smaller subproblems
Solve subproblems recursively
Merge solutions together
🔀 Merge Sort (Classic D&C)
Divide array in half, sort each half, merge sorted halves.
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid]) # Divide
right = merge_sort(arr[mid:]) # Divide
return merge(left, right) # Combine
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
⚡ Quick Sort
Pick pivot, partition around it, recursively sort partitions.
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
🔄 Recursion Fundamentals
A function that calls itself. Every recursive function needs TWO parts:
The condition that STOPS recursion. Without it = infinite loop!
if n <= 1: return n
The function calls itself with a SMALLER problem.
return n * factorial(n-1)
| Pattern | Description | Example |
|---|---|---|
| Linear | One recursive call per level | factorial(n) |
| Binary | Two recursive calls (tree shape) | fibonacci(n) |
| Tail | Return is the recursive call itself | loop(n, acc) |
| Mutual | A calls B, B calls A | isEven/isOdd |
✂️ Interactive D&C Visualizer
Watch how the algorithm divides the array, conquers subproblems, and combines results step-by-step.
Click "Start" to visualize the algorithm
💻 Code Implementation
📈 Dynamic Programming
DP trips up everyone at first. If you're confused, welcome to the club. The core idea? Remember what you've already computed so you don't calculate it twice. That's it. Let's see why that's powerful.
📚 Before you start: Make sure you understand recursion first. DP builds directly on recursive thinking.
🧠 Think First Challenge
Calculate fib(5) by hand. How many times do you calculate fib(2)?
fib(4) = fib(3) + fib(2)
fib(3) = fib(2) + fib(1)
...keep going...
📖 Reveal The Problem
You
calculate fib(2) 3 times, fib(3) 2 times. This
is the duplicate work DP eliminates. By storing results, each fib(n) is calculated only once. That's
memoization.
🪜 The Staircase Problem
You're climbing a staircase with n steps. You can take 1 or 2 steps at a time. How many distinct ways can you reach the top?
The insight: To reach step n, you either came from step n-1 (took 1 step) or step n-2 (took 2 steps). So: ways(n) = ways(n-1) + ways(n-2). Wait—that's Fibonacci!
Once this clicks, you'll start seeing DP problems everywhere. It clicked for me on the third example.
🔄 Top-Down (Memoization)
Recursive approach with caching. "Remember what you've computed."
def climb_stairs(n, memo={}):
if n in memo:
return memo[n]
if n <= 2:
return n
memo[n] = climb_stairs(n-1, memo) + climb_stairs(n-2, memo)
return memo[n]
# Without memo: O(2^n) - exponential!
# With memo: O(n) - linear!
📊 Bottom-Up (Tabulation)
Iterative approach building up from base cases. Often more efficient.
def climb_stairs(n):
if n <= 2:
return n
dp = [0] * (n + 1)
dp[1] = 1
dp[2] = 2
for i in range(3, n + 1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
# Time: O(n), Space: O(n)
# Can optimize to O(1) space!
🎒 Classic DP Problems
| Problem | Key Insight | Complexity |
|---|---|---|
| Fibonacci | F(n) = F(n-1) + F(n-2) | O(n) |
| 0/1 Knapsack | Include item or skip it | O(n × W) |
| Longest Common Subsequence | Match chars or skip | O(m × n) |
| Coin Change | Min coins for each amount | O(n × amount) |
⚔️ Memoization vs Tabulation
| Aspect | Top-Down (Memo) | Bottom-Up (Tab) |
|---|---|---|
| Approach | Recursive + cache | Iterative + table |
| Computes | Only needed subproblems | All subproblems |
| Stack Usage | O(depth) - can overflow | O(1) - no recursion |
| Best When | Not all subproblems needed | Need all / optimize space |
💡 Interview tip: Start with memoization (easier to write), optimize to tabulation if needed!
💰 Greedy Algorithms
The lazy genius strategy: at each step, just take the best option available right now. Sometimes it works perfectly. Sometimes it completely fails. The trick is knowing when it's safe to be greedy.
🪙 The Coin Change Story
You're a cashier. Someone needs $0.63 in change. You want to use as few coins as possible. What do you do?
The greedy instinct: Grab the biggest coin that fits! Quarter (25¢) → Quarter (25¢) → Dime (10¢) → Penny → Penny → Penny = 6 coins. Pretty good!
⚠️ Plot twist: Greedy doesn't always win. With coins [1, 3, 4] for amount 6: greedy picks 4+1+1 = 3 coins. But 3+3 = 2 coins is better! Sometimes you need DP.
📅 Activity Selection
Given activities with start/end times, select max non-overlapping activities.
def activity_selection(activities):
# Sort by end time (greedy choice!)
activities.sort(key=lambda x: x[1])
selected = [activities[0]]
last_end = activities[0][1]
for start, end in activities[1:]:
if start >= last_end:
selected.append((start, end))
last_end = end
return selected
# Why it works: Earliest finish leaves
# most room for other activities!
🎒 Fractional Knapsack
Unlike 0/1 knapsack, you can take fractions of items.
def fractional_knapsack(items, capacity):
# Sort by value/weight ratio
items.sort(key=lambda x: x[0]/x[1], reverse=True)
total_value = 0
for value, weight in items:
if capacity >= weight:
total_value += value
capacity -= weight
else:
# Take fraction
total_value += value * (capacity / weight)
break
return total_value
✅ When Greedy Works
- Greedy Choice Property: A locally optimal choice leads to globally optimal solution
- Optimal Substructure: Optimal solution contains optimal solutions to subproblems
- Common examples: Huffman coding, Dijkstra's shortest path, Prim's/Kruskal's MST
🧭 BFS Simulation (Breadth-First Search)
Google Maps, social network "friend suggestions", and web crawlers all use graph algorithms. Watch BFS explore a graph level by level—once you see it, you'll understand why it always finds the shortest path.
Understanding Algorithm Colors
BFS uses Queue (FIFO) — explores level by level, always finds shortest path in unweighted graphs
🎲 Random Graph Generator
📝 Edge List Input
LIVE SYNC💡 Type edges here and they'll appear on the canvas instantly. Format: "u v [w]"
🌊 The Two Explorers
Imagine two explorers trying to find treasure in a maze:
BFS (The Cautious Explorer) checks every room at each distance level before going deeper. She's systematic—first all rooms 1 step away, then 2 steps, then 3. This guarantees finding the shortest path!
DFS (The Adventurous Explorer) picks a path and follows it as deep as possible before backtracking. He might find the treasure quickly if he's lucky, but his path isn't always the shortest.
[5, 12, 8, 3, 15, 7]
What is an Array?
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together.
Comparisons
| Structure | Access | Search | Insert | Delete |
|---|---|---|---|---|
| Array | O(1) | O(n) | O(n) | O(n) |
| Linked List | O(n) | O(n) | O(1)* | O(1)* |
🎯 Scenario: Music Playlist
Manage a playlist of 100 songs:
- Play song #42: Instant O(1). Great!
- Add song at #1: Slow O(n). Must shift 99 songs.
- Shuffle: Easy O(n) swaps.
Solution
Use Arrays when you need fast random access and size doesn't change often. For frequent insertions/deletions, consider a Linked List.
[15]
What is a Stack?
Your browser's back button? A stack. Every function call in your code? A stack. The undo feature in every app? Stack. Last In, First Out (LIFO)—the data structure that's secretly everywhere.
📊 Stack vs Queue Comparison
| Aspect | Stack (LIFO) | Queue (FIFO) |
|---|---|---|
| Principle | Last In, First Out | First In, First Out |
| Add | push() → Top |
enqueue() → Back |
| Remove | pop() ← Top |
dequeue() ← Front |
| Peek | peek() → Top |
front() → Front |
| Use Cases | Undo, Recursion, Parentheses | BFS, Scheduling, Print Queue |
🎯 Scenario: Browser Back Button
You visit these pages in order:
- google.com
- youtube.com
- youtube.com/video123
- twitter.com
You press "Back" twice. Where are you now?
Solution: youtube.com
Browsers use a stack for history!
[3]
What is a Queue?
Print jobs, customer service lines, web requests—anything that needs "First In, First Out" (FIFO) uses a queue. It's the only data structure that is actually fair.
Key Operations
- enqueue(x) Add x to the BACK (Wait in line).
- dequeue() Remove from the FRONT (Next please!).
- front() Look at who is first without removing them.
🎯 Scenario: Printer Spooler
Three people send documents to print:
- Alice sends "Resume.pdf" (10:00 AM)
- Bob sends "Photo.jpg" (10:01 AM)
- Charlie sends "Homework.docx" (10:02 AM)
If the printer jams on the first job, which file is stuck?
Solution: Resume.pdf
Queues are FIFO. Alice was first in, so she is first out (to the printer).
The Classic Chain
Unlike arrays, Linked Lists don't need contiguous memory. Each node holds data and a pointer to the next one. Great for insertions where you don't want to shift everything!
🔗 Variants Comparison
| Variant | Prev Ptr | Circular | Best Use |
|---|---|---|---|
| Singly | ❌ | ❌ | Stacks, Simple lists |
| Doubly | ✅ | ❌ | Browser History |
| Circular | ❌ | ✅ | Music Playlists |
🎯 Scenario: Music Playlist
You want a "Repeat All" mode where the last song plays the first song next. Which structure is best?
Solution: Circular Linked List
50
The Self-Organizing Tree
Everything to the left is smaller. Everything to the right is bigger. This simple rule turns searching from O(n) into O(log n). It's like a dictionary that organizes itself!
🌲 BST Properties
- L Left Subtree: All nodes are < than root.
- R Right Subtree: All nodes are > than root.
- U Unique: Ideally no duplicate values.
*Worst case O(n) if unbalanced (like a line)
🚶 Traversal Types
Left, Root, Right
(Sorted!)
Root, Left, Right
(Copy)
Left, Right, Root
(Delete)
⛰️ Heaps
The "King of the Hill" data structure. Always gives you the max (or min) element instantly.
[]
📐 Array Index Formulas
Heaps are complete binary trees stored efficiently in arrays:
| Left Child | 2*i + 1 |
| Right Child | 2*i + 2 |
| Parent | floor((i-1)/2) |
Why Arrays?
Because heaps are Complete Binary Trees (filled left-to-right), we don't need pointers! We can just use math index calculations. This makes heaps extremely memory efficient and cache-friendly.
0
The O(1) Magic
Arrays are fast if you know the index. But what if the index is a name? Hash Tables use a math function to turn "Alice" into an index like `4`. Instant access!
⚡ Speed & Efficiency
Perfect for lookups (Maps, Sets, Caches).
*Worst case happens when many keys collide (end up in same bucket)
💥 Handling Collisions
What if "Mom" and "Mike" both go to bin 'M'?
Just make a list! Both letters stay in bin 'M', one after another.
"Bin 'M' is full? I'll try 'N' next." (Linear Probing)
🎯 Scenario: Phone Contacts
You have 500 contacts. When you tap "Alice", how does it find her number instantly without checking 500 names?
Step 2: Go to Index 42
🕸️ Graphs
🕸️ Interactive Graph Editor
Build, visualize, and explore graphs with real-time feedback
📝 Edge List Input
Live Sync📊 Properties
The Social Network
Facebook friend suggestions? That's graph theory! Each person is a node, each friendship is an edge.
"People you may know" = friends of friends = nodes 2 edges away!
📋 Graph Terminology
| Vertex (Node) | A point in the graph |
| Edge | Connection between two vertices |
| Directed | Edges have direction (A→B) |
| Undirected | Edges go both ways (A↔B) |
| Weighted | Edges have values (distances) |
| Degree | Number of edges connected to a node |
🗃️ How to Store Graphs
Each node stores list of neighbors. Space: O(V+E)
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
'D': ['B', 'C']
}
2D array where matrix[i][j]=1 if edge exists. Space: O(V²)
📊 Adjacency List vs Matrix Comparison
| Operation | Adjacency List | Adjacency Matrix |
|---|---|---|
| Space | O(V + E) | O(V²) |
| Check Edge (A→B)? | O(degree) | O(1) |
| Find All Neighbors | O(degree) | O(V) |
| Add Edge | O(1) | O(1) |
| Best For | Sparse graphs (few edges) | Dense graphs (many edges) |
*Floyd-Warshall algorithm for all-pairs shortest paths.
🌊 BFS (Breadth-First Search)
Explore level by level. Uses a queue. Good for shortest path in unweighted graphs.
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node) # Process node
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
🏔️ DFS (Depth-First Search)
Go deep before backtracking. Uses a stack (or recursion). Good for detecting cycles.
def dfs(graph, node, visited=None):
if visited is None:
visited = set()
visited.add(node)
print(node) # Process node
for neighbor in graph[node]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
🎯 BFS vs DFS
| Aspect | BFS | DFS |
|---|---|---|
| Data Structure | Queue | Stack / Recursion |
| Shortest Path | Yes (unweighted) | No |
| Space | O(width of graph) | O(depth of graph) |
| Use Case | Shortest path, level order | Cycle detection, topological sort |
🔄 Cycle Detection
Detecting cycles is crucial for many algorithms!
| Undirected | DFS: if you visit a node already in your path |
| Directed | Track "in-progress" nodes (gray color in 3-color scheme) |
| Linked List | Floyd's Tortoise & Hare (slow/fast pointer) |
🗺️ Common Graph Algorithms
| Dijkstra's | Shortest path (weighted, non-negative) |
| Bellman-Ford | Shortest path (negative weights OK) |
| Topological Sort | DAG ordering (prerequisites, build order) |
| MST (Prim/Kruskal) | Minimum spanning connections |
🎯 Scenario: Course Prerequisites
You have courses with prerequisites: CSE110 → CSE220 → CSE300. How do you find a valid course order?
Solution: Topological Sort!
Model courses as nodes, prerequisites as directed edges. Topological sort gives a valid order!
🧪 Your DS Playground
This is YOUR space! Experiment with data structures, see how they work internally, and build confidence through hands-on practice! 🚀
🎮 Choose Your Data Structure
[5, 12, 8, 3, 15]
🧪 SQL Lab
SQL is the most in-demand skill on job postings. Seriously—look it up. Practice real queries in your browser, no setup required. Make mistakes. That's how you learn.
☕ The Coffee Shop Database
You’re helping a cozy coffee shop understand customers, orders, and sales. This dataset is small but realistic—perfect for learning.
Tip: Press Ctrl/Cmd +
Enter to run your query.
Click Run to see the first 10 products.
🧾 Entity-Relationship Diagram
🔑 = Primary Key 🔗 = Foreign Key
🔍 Dataset Preview
See a few rows so you can write queries confidently.
📊 Results
🧭 SQL Lab Guide
Use the Lab when you want to explore freely. For structured challenges with validation and hints, go to SQL Practice.
🎯 Mini Challenge
Question: Which customers placed orders in 2025?
Hint: join customers → orders and
filter by date.
Try it in the editor. If you get stuck, go to SQL Practice for guided hints.
🏁 SQL Practice
Short, story-based challenges with premium feedback: validation, diffs, hints, and explanations.
Solve it, then hit Check Answer. Your progress saves automatically.
Loading…
🧩 Hints (progressive)
🎯 Expected Output
Your result must match this output (columns + rows). Some challenges allow any order.
📊 Your Output
🧾 Diff (premium feedback)
🏆 How you win
Fast onboarding, instant feedback, and tiny tasks. Don’t aim for perfection—aim for reps.
🧠 Active Recall Tip
After you solve a challenge, reset and re-type the query from memory. This is one of the fastest ways to build real skill—especially if you’re not confident with coding yet.
📘 SQL Lessons
Learn SQL step-by-step with interactive examples and visual explanations.
📖 Lesson 1: SELECT Basics
SELECT is how you retrieve data from a database. Think of it like asking a question.
Syntax
SELECT column1, column2
FROM table_name;
SELECT name, price_cents FROM products;
📖 Lesson 2: Filtering with WHERE
WHERE filters rows based on conditions. Only matching rows are returned.
Syntax
SELECT * FROM products
WHERE category = 'Coffee';
📖 Lesson 3: JOIN - Combining Tables
JOIN connects rows from different tables using a common column (like customer_id).
INNER JOIN
Only matching rows from both tables
LEFT JOIN
All from left table + matching from right
RIGHT JOIN
Matching from left + all from right
Rarely used—just swap table order with LEFT JOIN
FULL OUTER JOIN
All from both tables, NULL where no match
Great for finding orphan records
Syntax
SELECT c.name, o.order_date
FROM customers c
JOIN orders o ON o.customer_id = c.id;
📖 Lesson 4: GROUP BY - Aggregations
GROUP BY combines rows with the same value, allowing you to use aggregate functions.
Aggregate Functions
COUNT(*) - rowsSUM(col) - totalAVG(col) - averageMIN(col) - smallestMAX(col) - largestCOUNT(DISTINCT) - uniqueExample
SELECT category, COUNT(*) AS total
FROM products
GROUP BY category;
🧠 SQL Interview Drills
Interview-style drills are coming soon. For now, build fundamentals in SQL Practice.
Coming soon
Timed drills + common patterns (joins, group by, subqueries) with fast feedback.
👁️ SQL Visualizer
Write SQL queries and watch them transform your data in real-time. See changes instantly!
✍️ Write Your Query
📊 Live Data Table
💡 Run INSERT, UPDATE, or DELETE to see changes instantly!
📝 Quick SQL Reference
INSERT INTO table (col1, col2) VALUES (val1, val2);
UPDATE table SET col = value WHERE condition;
DELETE FROM table WHERE condition;
📊 Entity-Relationship Diagrams
Design and visualize database structures using ERD notation. Learn to identify entities, attributes, relationships, and cardinality.
🎮 Interactive ERD Builder
📐 ERD Components
| Symbol | Name | Purpose |
|---|---|---|
| ▭ Rectangle | Entity | A "thing" we store data about |
| ◇ Diamond | Relationship | How entities connect |
| ⬭ Ellipse | Attribute | Properties of an entity |
| Underline | Primary Key | Unique identifier |
🔢 Cardinality Notations
| Type | Chen | Example |
|---|---|---|
| One-to-One | 1 : 1 | Person → Passport |
| One-to-Many | 1 : N | Department → Employees |
| Many-to-Many | M : N | Students ↔ Courses |
🎯 Design Challenge
Scenario: Design an ERD for a Library System with:
- Books (ISBN, title, author, year)
- Members (ID, name, email, join_date)
- Loans (book borrowed, member, due_date)
💡 Hint: What's the relationship between Members and Books?
Solution Insight
Members ← BORROWS → Books is a M:N relationship!
One member can borrow many books, and one book can be borrowed by many members (over time). The LOANS table captures this relationship with additional attributes.
🔷 Enhanced ER Diagrams (EERD)
Extend basic ERD concepts with specialization, generalization, and inheritance hierarchies for more complex data modeling.
🎮 EERD Hierarchy Builder
💡 Tip: Drag entities to reposition. The sample shows PERSON specializing into STUDENT, EMPLOYEE, and INSTRUCTOR.
📐 EER Concepts
| Specialization | Top-down: Define subclasses from superclass |
| Generalization | Bottom-up: Combine entities into superclass |
| Inheritance | Subclass inherits all superclass attributes |
| ISA Relationship | "STUDENT is a PERSON" |
🔒 Specialization Constraints
Disjoint vs Overlapping
| d | Disjoint: Entity can belong to only ONE subclass |
| o | Overlapping: Entity can belong to MULTIPLE subclasses |
Total vs Partial
| ══ | Total: Every superclass instance MUST be in a subclass |
| ── | Partial: Superclass instance MAY exist without subclass |
🎯 Modeling Challenge
Scenario: A university system has VEHICLES. Some are CARS (with num_doors), some are MOTORCYCLES (with engine_cc). A vehicle cannot be both.
Question: Is this disjoint or overlapping? Total or partial?
Solution
Disjoint (d) — A vehicle is either a car OR motorcycle, not both.
Partial — Could have other vehicles (trucks, bikes) not yet modeled.
🔢 Relational Algebra
Master the mathematical foundation of SQL queries with interactive visualizations
📊 Sample Tables
These tables are used for all operations below.
👤 Students
| id | name | major | gpa |
|---|---|---|---|
| 1 | Alice | CS | 3.8 |
| 2 | Bob | Math | 3.5 |
| 3 | Carol | CS | 3.9 |
| 4 | David | Physics | 3.2 |
📚 Enrollments
| student_id | course | grade |
|---|---|---|
| 1 | DB101 | A |
| 1 | AI201 | B+ |
| 2 | DB101 | A- |
| 3 | AI201 | A |
| 4 | PHY101 | B |
📖 Operator Reference
σ Selection (Filter Rows)
Like SQL's WHERE clause - keeps rows matching a condition.
π Projection (Select Columns)
Like SQL's SELECT column list - picks specific columns.
⨝ Natural Join
Combines tables on matching column values (Students.id = Enrollments.student_id).
🧩 Combined Expression
Try chaining operations like a real query:
This is equivalent to:
SELECT name, course, grade FROM Students JOIN Enrollments ON id = student_id WHERE major = 'CS'
🔄 Relational Algebra ↔ SQL Mapping
| Relational Algebra | SQL Equivalent | Purpose |
|---|---|---|
| σmajor='CS'(Students) | SELECT * FROM Students WHERE major = 'CS' |
Filter rows |
| πname, gpa(Students) | SELECT name, gpa FROM Students |
Select columns |
| Students ⨝ Enrollments | SELECT * FROM Students JOIN Enrollments ON id = student_id |
Combine tables |
| Students ∪ Alumni | SELECT * FROM Students UNION SELECT * FROM Alumni |
Combine row sets |
🔐 Transactions & ACID
Visualize database transactions, concurrency problems, and isolation levels
🔒 ACID Properties
📊 Isolation Levels
| Level | Dirty Read | Non-Repeatable | Phantom |
|---|---|---|---|
| READ UNCOMMITTED | ❌ Possible | ❌ Possible | ❌ Possible |
| READ COMMITTED | ✅ Prevented | ❌ Possible | ❌ Possible |
| REPEATABLE READ | ✅ Prevented | ✅ Prevented | ❌ Possible |
| SERIALIZABLE | ✅ Prevented | ✅ Prevented | ✅ Prevented |
🎮 Transaction Simulator
Watch two transactions execute concurrently and see potential anomalies.
📦 Database State
🅰️ Transaction A
🅱️ Transaction B
📖 Dirty Read Explained
A Dirty Read occurs when Transaction B reads data that Transaction A has modified but not yet committed. If A rolls back, B has read "phantom" data that never existed.
🌳 B-Tree Index Visualizer
Understand how database indexes work with interactive B+ Tree operations
🎮 Operations
📊 Tree Statistics
🌳 B+ Tree Visualization
💡 Tip: Insert values and watch nodes split when they overflow!
📝 Operation Log
📖 B-Tree Properties
🔢 Order (m)
- Max m children per node
- Max m-1 keys per node
- Min ⌈m/2⌉ children (except root)
⚡ Complexity
- Search: O(log n)
- Insert: O(log n)
- Delete: O(log n)
💾 Database Use
- CREATE INDEX uses B-Trees
- Leaf nodes store row pointers
- Non-leaf nodes are navigation aids
🍃 Introduction to NoSQL
Beyond rows and columns: Document, Key-Value, Graph, and Column-family stores
🤔 Why NoSQL?
Relational databases (SQL) are great for structured data and complex queries, but they struggle with:
- 📉 Scalability: Hard to scale horizontally (sharding is complex).
- 🔄 Flexibility: Schema changes require downtime or migrations.
- ⚡ Speed: Joins can be slow for massive datasets.
NoSQL (Not Only SQL) databases emerged to solve these problems by trading ACID guarantees for performance and scalability (CAP Theorem).
📦 Types of NoSQL
📄 Document Stores (e.g., MongoDB)
Data is stored as JSON-like documents. Flexible schema.
Best for: Content management, catalogs, user profiles.
{
"_id": 1,
"name": "Alice",
"skills": ["Java", "Python"]
}
🔑 Key-Value Stores (e.g., Redis)
Simple hash table. Extremely fast.
Best for: Caching, session management, leaderboards.
🕸️ Graph Databases (e.g., Neo4j)
Nodes and edges. Optimized for relationships.
Best for: Social networks, recommendation engines.
📊 Column-Family (e.g., Cassandra)
Wide-column stores. High write throughput.
Best for: Time-series data, IoT logs.
🆚 SQL vs NoSQL
| Feature | SQL (Relational) | NoSQL (Non-Relational) |
|---|---|---|
| Schema | Fixed, rigid | Dynamic, flexible |
| Scaling | Vertical (bigger server) | Horizontal (more servers) |
| Data | Structured (Tables) | Unstructured (Docs, Graphs) |
| Transactions | ACID (Strong consistency) | BASE (Eventual consistency) |
🏗️ Three-Level Schema Architecture
Understand the ANSI/SPARC three-level database architecture: External, Conceptual, and Internal schemas with data independence.
🎮 Schema Level Viewer
📐 Three-Level Architecture
| Level | Purpose | Users |
|---|---|---|
| External | User views, subsets of data | End users, Apps |
| Conceptual | Logical structure, entities, relationships | DBAs, Designers |
| Internal | Physical storage, indexes, files | System, DBMS |
🔓 Data Independence
| Logical Independence | Change conceptual schema without affecting external views |
| Physical Independence | Change internal storage without affecting conceptual schema |
💡 This is why you can add indexes or move files without rewriting SQL queries!
🎯 Quick Check
Question: A company wants to switch from HDD storage to SSD. Which level changes, and does the SQL code need to be rewritten?
Answer
Only the Internal Level changes (file storage location).
No SQL changes needed! Physical independence protects the conceptual and external levels from storage changes.
🔧 Database Normalization
Learn to eliminate data redundancy and anomalies by decomposing tables through normal forms: 1NF → 2NF → 3NF → BCNF.
🎮 Step-by-Step Normalization
📐 Normal Forms
| Form | Rule |
|---|---|
| 1NF | Atomic values only (no repeating groups) |
| 2NF | 1NF + No partial dependencies on PK |
| 3NF | 2NF + No transitive dependencies |
| BCNF | Every determinant is a candidate key |
🔗 Functional Dependencies
A functional dependency X → Y means: if you know X, you can determine Y.
| Full FD | Y depends on ALL of X (no subset) |
| Partial FD | Y depends on only PART of composite PK |
| Transitive FD | X → Y → Z (indirect dependency) |
⚠️ Data Anomalies
| Insert | Can't add data without adding unrelated data |
| Update | Must update same info in multiple places |
| Delete | Deleting one thing removes unrelated info |
🎯 Quick Practice
Table: StudentCourse(StudentID, CourseID, StudentName, CourseName, Grade)
PK: (StudentID, CourseID)
Question: Is StudentName a partial or full dependency?
Show Answer
Partial dependency! StudentName depends only on StudentID, not the full composite key (StudentID, CourseID). This violates 2NF.
🧠 Quiz Mode
Test your knowledge with interactive quizzes. Earn XP and track your mastery!
📚 Choose a Topic
Loading question...
Correct!
Explanation here
+10 XP
Quiz Complete!
+80 XP earned!
🎯 Daily Challenge
Complete today's challenge to maintain your streak and earn bonus XP!
Loading today's challenge...
Please wait while we fetch your daily challenge.
📅 Your Challenge Calendar
📜 Recent Challenges
Complete today's challenge to start your history!
🔄 The Tale of Recursion
Recursion is either the most elegant concept in programming or the most confusing. Usually both at once. If it doesn't click immediately, watch the Tower of Hanoi three times. Then try explaining it to someone. That's when it clicks.
🏯 The Tower of Hanoi
In an ancient temple, monks must move 64 golden disks from one pillar to another. But there are sacred rules: only one disk at a time, and a larger disk can never rest on a smaller one.
The head monk realized a profound truth: "To move 64 disks, I must first move 63 disks. To move 63 disks, I must first move 62..." This is recursion—solving a big problem by solving smaller versions of itself!
🧠 The Recursion Pattern
// Base case: simplest problem
if (problem is tiny) {
return simple solution
}
// Recursive case: break down
smaller = makeProblemSmaller(problem)
return solveRecursively(smaller)
}
🎯 Key Insight
Every recursive function needs:
- Base case: When to stop (prevents infinite loop!)
- Recursive case: How to make the problem smaller
- Progress: Each call must move toward base case
🧪 Recursion Sandbox: Fibonacci Call Stack
Watch how recursive calls stack up and unwind. Enter a number to see fib(n) visualized!
💡 Notice: fib(5) makes 15 calls! Each increase in n nearly doubles the calls. This is why recursive Fibonacci is O(2ⁿ) - exponential time! Memoization can fix this.
🏎️ The Great Algorithm Race
Big O is THE interview topic. "What's the time complexity?" will be asked in every coding interview. Master this, and you're ahead of 80% of candidates. The difference between O(n) and O(n²) is the difference between 1 second and 3 hours.
🏁 Race Day at Algorithm Stadium
Five racers compete on a special track. The track's length is determined by the input size (n). With a small input (n=10), all racers finish quickly. But watch what happens as n grows...
🏆 The Contestants
💡 The Lesson
At n=10, all racers seem similar.
At n=100, differences become clear.
At n=1000, slow algorithms become unusable!
Big O tells us how algorithms scale. Always pick the fastest racer for your track!
Selection Sort
Beginner • 10 minSelect the smallest element each pass.
Insertion Sort
Beginner • 10 minInsert each element into sorted position.
Heap Sort
Intermediate • 12 minBuild a heap and extract elements.
Linear Search
Beginner • 8 minCheck every element one by one.
Breadth-First Search
Intermediate • 12 minExplore level by level for shortest path.
Depth-First Search
Intermediate • 11 minDive deep before backtracking.
Dijkstra's Algorithm
Intermediate • 14 minWeighted shortest path algorithm.
A* Pathfinding
Advanced • 14 minSmart heuristic-guided pathfinding.
Greedy Best-First
Intermediate • 10 minFast heuristic-only pathfinding.
🧠 Practice Problems with Walkthroughs
Click any problem to see both Naive (O(n²)) and Optimal solutions visualized step-by-step!
Two Sum
Find two numbers that add up to target
Binary Search
Find target in sorted array
Contains Duplicate
Check if array has duplicates
Algorithm Masterclass
Deep dive into the logic behind the code. Watch step-by-step visual walkthroughs, analyze time complexity, and master the fundamentals of computer science.
Bubble Sort
The foundations of sorting. Learn how adjacent swapping ripples data into place.
Quick Sort
Master the industry-standard sorting algorithm using pivot partitioning logic.
Merge Sort
Learn stable sorting by recursively splitting and merging sorted subarrays.
Binary Search
Eliminate half the data at every step. The gold standard for sorted search.
Breadth-First Search
Explore graphs layer by layer. Essential for finding shortest paths.
Data Structure Deep Dive
Understand how data is organized, managed, and stored. Master the building blocks of efficient software, from Linked Lists to complex Graphs.
Stack Operations
Master LIFO (Last-In-First-Out) with Push, Pop, and Peek operations.
Linked List Traversal
Navigate node chains manually. Understand pointers and dynamic memory.
Binary Tree Traversal
Explore Pre-order, In-order, and Post-order recursive patterns.
Queue Operations
Master FIFO (First-In-First-Out) with Enqueue and Dequeue logic.
Hash Table Magic
Understand key-value mapping, collisions, and O(1) average lookup.
Array Deep Dive
Memory layout, resizing logic, and multi-dimensional array access.
Heap & Priority Queue
Intermediate • 15 minMin/Max heap, heapify, and applications.
BFS - Level by Level
Intermediate • 12 minBreadth-first search with queue visualization.
DFS - Go Deep First
Intermediate • 12 minDepth-first search with recursion animation.
🎓 SQL E-Lectures
Master SQL with step-by-step explanations, code examples, and visual demonstrations
🌱 Beginner Level
SELECT Basics
Beginner • 12 minQuerying data with SELECT, WHERE, ORDER BY, DISTINCT, and aliases.
DDL Operations
Beginner • 10 minCREATE, ALTER, DROP, TRUNCATE - defining database structure.
DML Operations
Beginner • 10 minINSERT, UPDATE, DELETE - manipulating data in tables.
📈 Intermediate Level
JOIN Operations
Intermediate • 18 minINNER, LEFT, RIGHT, FULL, CROSS, and SELF joins explained.
Aggregate Functions
Intermediate • 15 minCOUNT, SUM, AVG, GROUP BY, and HAVING for data analysis.
Subqueries
Intermediate • 14 minNested queries, correlated subqueries, IN, and EXISTS.
🚀 Advanced Level
Window Functions
Advanced • 20 minROW_NUMBER, RANK, LAG, LEAD, and running totals.
Common Table Expressions
Advanced • 14 minWITH clause and recursive CTEs for cleaner queries.
Transactions & ACID
Advanced • 16 minCOMMIT, ROLLBACK, isolation levels, and data integrity.
Indexes & Performance
Advanced • 16 minB-trees, composite indexes, EXPLAIN, and optimization.
Views
Advanced • 12 minVirtual tables and materialized views for reusability.