# Changelog

All notable changes to CodeTutor are documented here.

## [Unreleased]

### Added

- Progress Dashboard with tracking and spaced repetition:
  - New /progress page showing learning statistics and review suggestions
  - Extended progress data structure with attempt counts, time tracking, and pattern metadata
  - Time tracker singleton that monitors active practice time with pause/resume on tab switching
  - SM-2 inspired spaced repetition algorithm for intelligent review suggestions
  - Progress by pattern visualization showing completion rates per pattern
  - Export/import functionality for backing up and transferring progress data
  - Automatic migration from legacy progress format to new format
  - Progress link added to main navigation

- "Why This Pattern?" educational content system:
  - New `pattern_comparison` field on Explanation model for comparing alternative patterns
  - Database migration (007) adding pattern_comparison column to explanations table
  - Purple "Why This Pattern?" callout in question detail and workspace views
  - Pattern comparison content for 8 key questions:
    - top-k-frequent-elements: Bucket sort O(n) vs Heap O(n log k)
    - kth-largest-element-in-an-array: Heap O(n log k) vs Quickselect O(n)
    - network-delay-time: Dijkstra vs BFS for weighted graphs
    - task-scheduler: Math formula O(n) vs Heap simulation
    - reorganize-string: Heap greedy vs odd-even placement
    - two-sum: Hash map O(n) vs Sort+Two Pointers O(n log n)
    - valid-anagram: Counting array vs Hash map vs Sorting
    - contains-duplicate: Hash set vs Sorting trade-offs

- Learning progression updates on pattern pages:
  - Green checkmark icons for completed questions (from localStorage)
  - Gold star "Optimal" badge for questions where the current pattern is optimal
  - Progress counters per tier (e.g., "2/5" completed)
  - `is_optimal` field added to LearningQuestion API response

### Changed

- Migrated all 392 questions to new pattern format with is_optimal flag:
  - Batch 1 (heap-tagged): Fixed misclassified patterns (top-k-frequent-elements, task-scheduler, contains-duplicate, design-hashmap/hashset, detect-squares) and added is_optimal markers to correctly tagged heap questions
  - Batch 2-7: Migrated remaining 373 questions across all pattern types (two-pointers, dynamic-programming, backtracking, bfs/dfs, greedy, monotonic-stack, union-find, trie, prefix-sum, etc.)
  - Pattern priority system determines optimal pattern for multi-pattern questions based on algorithmic complexity and specificity
  - 9 questions have empty patterns (design problems without algorithmic patterns)

### Added

- 8 new pattern definitions to complete pattern taxonomy:
  - Topological Sort: DAG ordering for dependency resolution
  - Bit Manipulation: XOR tricks, bit counting, bitmasks
  - Counting / Bucket Sort: Bounded range sorting and frequency grouping
  - Cyclic Sort: Place elements at correct indices for [1,n] range problems
  - Divide and Conquer: Split, solve recursively, combine results
  - Hashing: O(1) lookup for duplicates, frequency, grouping
  - Matrix Manipulation: Rotation, transposition, in-place transforms
  - Synchronization: Thread coordination with locks and barriers

- Pattern taxonomy system:
  - 4 new algorithm patterns: Counting/Bucket Sort, Cyclic Sort, Topological Sort, Divide and Conquer
  - Pattern classification with pattern_type (algorithm, technique, data_structure) and display_order
  - is_optimal flag on question-pattern relationships to indicate optimal patterns for each question
  - Database migration (006) for pattern taxonomy fields
  - Backward-compatible YAML format supporting both string and dict pattern references
  - Frontend patterns page now groups patterns by type with dedicated sections
  - Question cards show optimal pattern indicator (green star)

- Production deployment configuration in deploy/ directory:
  - Docker Compose orchestration with PostgreSQL, backend, frontend, nginx, and Cloudflare Tunnel
  - nginx reverse proxy configuration routing /api to backend
  - Environment template (.env.example)
  - Deployment documentation (readme.md)

- Sprint 14: Bit Manipulation Visualization Components:
  - BitState and BitManipulationState type definitions in types.ts
  - BitDisplay primitive for rendering binary representations with individual bit cells
  - BitManipulationView data structure showing XOR operations with operands and result
  - BitManipulationVisualization algorithm component for bit manipulation problems
  - Algorithm definition for Single Number (LeetCode 136) with ~19 steps
  - Visual states: normal, highlighted, comparing, result, cancelled
  - Binary representation shows 4-8 bit cells with state-based styling
  - XOR visualization with operation symbol and result divider
  - Pair cancellation visually highlighted with strikethrough effect
  - Pattern page integration at /patterns/bit-manipulation
  - Pattern YAML file with XOR properties, code templates, and common mistakes

- Sprint 13: Union-Find Visualization Components:
  - UnionFindNodeState and UnionFindState type definitions in types.ts
  - UnionFindNode primitive for rendering disjoint set nodes with rank badge and root indicator
  - UnionFindView data structure with forest layout and upward parent pointers
  - UnionFindVisualization algorithm component for union-find problems
  - Algorithm definition for Redundant Connection (LeetCode 684) with ~25 steps
  - Visual states: normal, root, finding, compressing, merging, highlighted, cycle
  - Parent pointers drawn upward with arrowheads showing union relationships
  - Rank badges showing union by rank optimization
  - Pattern page integration at /patterns/union-find

- Sprint 12: Trie Visualization Components:
  - TrieNodeState and TrieState type definitions in types.ts
  - TrieNode primitive for rendering trie nodes with character display and end-of-word marker
  - TrieView data structure with N-ary tree layout and edge character labels
  - TrieVisualization algorithm component for trie-based problems
  - Algorithm definition for Implement Trie (LeetCode 208) with ~25 steps
  - Visual states: normal, current, found, notfound, highlighted, creating
  - Path highlighting during traversal operations
  - Pattern page integration at /patterns/trie

- Sprint 11: Matrix Traversal Visualization Components:
  - MatrixTraversalVisualization algorithm component reusing GridView
  - Algorithm definition for Number of Islands (LeetCode 200) with ~22 steps
  - DFS exploration of 2D grid showing connected components
  - Visual states for water (dimmed), unvisited land (normal), current cell (highlighted), exploring (computing), visited (success)
  - Pattern page integration at /patterns/matrix-traversal

- Sprint 10: Intervals Visualization Components:
  - IntervalState and IntervalListState type definitions in types.ts
  - IntervalBar primitive for rendering interval bars on a timeline
  - IntervalView data structure with timeline and number line
  - IntervalsVisualization algorithm component for interval-based problems
  - Algorithm definition for Merge Intervals (LeetCode 56) with ~18 steps
  - Pattern page integration at /patterns/intervals

- Sprint 9: Greedy Visualization Components:
  - GreedyVisualization algorithm component reusing ArrayView and Pointer primitives
  - Algorithm definition for Jump Game (LeetCode 55) with ~20 steps
  - Greedy pattern shows reachable range extending as max_reach grows
  - Pattern page integration at /patterns/greedy

- Sprint 8: Heap Visualization Components:
  - HeapNodeState and HeapState type definitions in types.ts
  - HeapNode primitive with comparing/swapping/settled/highlighted/removing states
  - HeapView data structure rendering heap as tree + array representation
  - HeapVisualization algorithm component for heap-based problems
  - Algorithm definition for Kth Largest Element (LeetCode 215) with ~23 steps
  - Pattern page integration at /patterns/heap

- Sprint 3: Monotonic Stack Visualization Components:
  - StackElement primitive with push/pop animation states
  - StackView data structure with vertical layout and AnimatePresence
  - MonotonicStackVisualization algorithm component
  - Algorithm definition for Next Greater Element problem
  - Pattern page integration at /patterns/monotonic-stack

### Changed

- Visualization layout improvements:
  - Removed max-width constraint on pattern pages for full-width layout
  - Widened visualization panel grid ratio for more space
  - Fixed min-height on monotonic stack to prevent layout jumping
  - Redesigned explanation panel with side-by-side decision point display

- Interactive Algorithm Visualization System:
  - Step-through animations showing how patterns work on example data
  - ArrayVisualizer component with SVG-based rendering and CSS transitions
  - LinkedListVisualizer for linked list with node chains and pointer support
  - StackVisualizer for LIFO stack with top indicator
  - TreeVisualizer for binary trees with level-order layout and edges
  - CodePane component for syntax-highlighted code with line highlighting
  - Playback controls with Play/Pause/Prev/Next and keyboard navigation
  - Speed control (0.5x, 1x, 2x) for animation playback
  - Variables pane showing current state values at each step
  - Step descriptions explaining what happens at each point
  - Visualization examples data format supporting arrays, linked lists, stacks, trees, pointers, and annotations
  - Added visualization_examples field to Pattern model and API
  - Database migration for visualization_examples column
  - Two Pointers pattern includes interactive visualization example (find pair with sum)
  - Sliding Window pattern includes visualization example (max sum subarray of size k)
  - Binary Search pattern includes visualization example (find target in sorted array)
  - Fast & Slow Pointers pattern includes visualization examples (find middle, detect cycle)
  - LinkedList Reversal pattern includes visualization example (reverse entire list)
  - Monotonic Stack pattern includes visualization example (next greater element)
  - CSS custom properties for visualization states (active, comparing, found, visited, swapping)
  - Keyboard shortcuts: arrow keys for stepping, space for play/pause
  - Progressive fallback: falls back to static ASCII visualization if no examples available

- Full tutorial content for 14 additional algorithmic patterns:
  - Graph/Tree Traversal: BFS, DFS, Binary Tree Traversal, Matrix Traversal
  - Pointer/Array Techniques: Fast & Slow Pointers, Prefix Sum, LinkedList In-Place Reversal, Overlapping Intervals
  - Data Structures: Monotonic Stack, Heap / Priority Queue, Union Find, Trie
  - Strategy Patterns: Backtracking, Greedy
  - Each tutorial includes metaphors, core concepts, visualizations, code templates, recognition signals, common mistakes, and variations

- Pattern Tutorial System for rich, visual learning experiences:
  - New pattern tutorial endpoint (GET /api/patterns/{slug}/tutorial)
  - Visual walkthroughs with ASCII diagrams showing algorithm progression
  - Core concept explanations with the "aha!" insight that makes patterns click
  - Relatable metaphors using real-world analogies
  - Reusable code templates for each pattern
  - Recognition signals (keywords/clues to identify when to use a pattern)
  - Common mistakes with explanations and fixes
  - Pattern variations showing different flavors of each technique
  - Learning progression with warmup/core/challenge question sequences
  - Related and prerequisite pattern connections
  - Difficulty levels (1-5) for pattern learning curves
  - Frontend components: RecognitionSignals, PatternVariations, LearningProgression, RelatedPatterns, CommonMistakesList
  - Individual pattern YAML files with full tutorial content (starting with Two Pointers)
  - Database migration adding tutorial fields to patterns table
- Progress tracking with localStorage:
  - Completed questions stored in localStorage
  - Green checkmark shown on question cards for completed problems
  - Progress persists across browser sessions
- Submit UX improvements:
  - Auto-switch to Results tab after Submit
  - Big O complexity display in Results tab
  - Success message with "Back to Questions" navigation when all tests pass

- Additional hidden test cases for 56 questions bringing coverage to 307/401:
  - Linked list: add-two-numbers, merge-two-sorted-lists, reverse-linked-list, linked-list-cycle
  - Array: two-sum, best-time-to-buy-and-sell-stock, container-with-most-water, product-of-array-except-self, contains-duplicate, number-of-islands, subarray-sum-equals-k, rotate-array, majority-element, missing-number, counting-bits, find-the-duplicate-number
  - Tree: clone-graph, invert-binary-tree, maximum-depth-of-binary-tree, same-tree, validate-binary-search-tree, kth-smallest-element-in-a-bst, subtree-of-another-tree, lowest-common-ancestor-of-a-binary-search-tree
  - String: letter-combinations-of-a-phone-number, longest-substring-without-repeating, valid-palindrome, valid-anagram, group-anagrams
  - Dynamic programming: climbing-stairs, house-robber, coin-change, maximum-subarray, longest-common-subsequence, longest-increasing-subsequence, unique-paths, decode-ways, partition-equal-subset-sum, min-cost-climbing-stairs, word-break
  - Binary search: binary-search, search-in-rotated-sorted-array, find-minimum-in-rotated-sorted-array
  - Backtracking: combination-sum, permutations, word-search
  - Graph: course-schedule, pacific-atlantic-water-flow, rotting-oranges
  - Interval: merge-intervals, insert-interval
  - Other: three-sum, top-k-frequent-elements, trapping-rain-water, jump-game, building-h2o

- Extended test runner supporting all 401 problem types:
  - Tree problems: Array-to-TreeNode and TreeNode-to-array conversion
  - LinkedList problems: Array-to-ListNode and ListNode-to-array conversion
  - Class-based design problems: Operations/args format execution
  - Flexible output comparison for unordered arrays (subsets, permutations)
- Panel maximize/minimize view in problem workspace
- Separate Solutions tab in problem workspace (moved from Explanation tab)
- Big O complexity estimator in test results:
  - Analyzes user code using Python AST
  - Detects loops, recursion, sorting, and common patterns
  - Shows estimated complexity with explanation of how it was calculated
- Python helper utilities module (python-helpers.ts) for problem type detection
- SEO improvements:
  - Dynamic sitemap generation (sitemap.xml) for all pages
  - robots.txt configuration
  - Open Graph and Twitter Card metadata
  - Per-page metadata for questions and patterns
- Test cases for 23 additional questions bringing total to 175:
  - Graph: min-cost-to-connect-all-points, minimum-height-trees, bricks-falling-when-hit
  - Dynamic programming: minimum-path-sum, build-array-where-you-can-find-the-maximum-exactly-k-comparisons, check-if-an-original-string-exists-given-two-encoded-strings, regular-expression-matching
  - Sliding window: minimum-size-subarray-sum
  - Math: multiply-strings, powx-n
  - BFS: open-the-lock, path-with-minimum-effort
  - String: palindromic-substrings, reorganize-string, check-if-string-is-transformable-with-substring-sort-operations
  - Backtracking: partition-to-k-equal-sum-subsets, permutations-ii
  - Greedy: merge-triplets-to-form-target-triplet
  - Heap: minimum-interval-to-include-each-query
  - Binary search: search-a-2d-matrix, search-in-rotated-sorted-array-ii
  - Linked list: remove-nth-node-from-end-of-list, reverse-linked-list-ii

- Test cases for 32 additional questions bringing total to 152:
  - Array/Hash: check-if-array-pairs-are-divisible-by-k, check-if-every-row-and-column-contains-all-numbers
  - String: check-if-a-string-can-break-another-string, check-if-a-string-contains-all-binary-codes-of-size-k, check-if-a-parentheses-string-can-be-valid, check-if-binary-string-has-at-most-one-segment-of-ones, check-if-word-equals-summation-of-two-words, check-if-word-occurs-as-prefix, check-if-word-is-valid-after-substitutions, brace-expansion-ii
  - Math: check-if-number-is-a-sum-of-powers-of-three, check-if-it-is-a-good-array, building-boxes, check-if-point-is-reachable
  - Matrix: check-if-move-is-legal, check-if-there-is-a-valid-path-in-a-grid, check-if-word-can-be-placed-in-crossword, check-knight-tour-configuration, check-if-there-is-a-valid-parentheses-string-path, construct-quad-tree
  - Dynamic programming: check-if-there-is-a-valid-partition-for-the-array, maximum-sum-circular-subarray
  - Graph: build-a-matrix-with-conditions, checking-existence-of-edge-length-limited-paths
  - Heap: merge-k-sorted-lists, car-fleet-ii
  - Greedy: maximum-length-of-pair-chain, change-minimum-characters-to-satisfy-one-of-three-conditions
  - Prefix sum: can-you-eat-your-favorite-candy-on-your-favorite-day
  - Sliding window: maximum-fruits-harvested-after-at-most-k-steps
  - JavaScript: check-if-object-instance-of-class
  - Stack: check-if-number-has-equal-digit-count-and-digit-value

- Test cases for 32 additional questions bringing total to 120:
  - Backtracking: subsets, subsets-ii, permutations, combination-sum-ii, palindrome-partitioning
  - Dynamic programming: edit-distance, target-sum, coin-change-ii, unique-paths-ii, jump-game-ii, maximum-product-subarray, perfect-squares, burst-balloons, integer-break
  - Stack/Monotonic: daily-temperatures, decode-string, sliding-window-maximum, largest-rectangle-in-histogram, evaluate-reverse-polish-notation
  - Graph: word-ladder, course-schedule-ii, reconstruct-itinerary, network-delay-time, redundant-connection
  - Greedy: partition-labels, gas-station, candy, task-scheduler
  - Linked list/Tree: reorder-list, diameter-of-binary-tree, kth-largest-element-in-an-array
  - Math: reverse-integer

- Test cases for 62 additional questions bringing total to 88:
  - Array/Two-pointer: remove-duplicates-from-sorted-array, remove-element, merge-sorted-array, rotate-array, group-anagrams, product-of-array-except-self, three-sum, container-with-most-water, longest-consecutive-sequence, rotate-image, spiral-matrix, set-matrix-zeroes, four-sum, sort-colors
  - Linked list: linked-list-cycle, find-the-duplicate-number, reverse-linked-list, merge-two-sorted-lists, add-two-numbers
  - Binary tree: invert-binary-tree, maximum-depth-of-binary-tree, validate-binary-search-tree, same-tree, subtree-of-another-tree, kth-smallest-element-in-a-bst, lowest-common-ancestor-of-a-binary-search-tree, binary-tree-level-order-traversal
  - Graph: clone-graph, course-schedule, pacific-atlantic-water-flow, rotting-oranges, number-of-islands
  - Sliding window/String: longest-substring-without-repeating, minimum-window-substring, permutation-in-string, top-k-frequent-elements, backspace-string-compare, basic-calculator-ii, asteroid-collision
  - Dynamic programming: house-robber, longest-increasing-subsequence, coin-change, jump-game, combination-sum, longest-common-subsequence, word-break, partition-equal-subset-sum, unique-paths, decode-ways, min-cost-climbing-stairs
  - Binary search: search-in-rotated-sorted-array, find-minimum-in-rotated-sorted-array, median-of-two-sorted-arrays
  - Backtracking: generate-parentheses, letter-combinations-of-a-phone-number, combinations, word-search
  - Intervals: merge-intervals, insert-interval
  - Other: longest-palindromic-substring, trapping-rain-water, subarray-sum-equals-k

## [0.6.0] - 2025-07-05

### Added

- Interactive code editor with Pyodide (Python WebAssembly) for client-side code execution
- Monaco Editor integration for syntax highlighting and code editing
- Test case support with visible tests (shown to user) and hidden tests (validated server-side)
- Database migration adding function_signature and test_cases columns to questions table
- Submission endpoint (POST /api/questions/{slug}/submit) for validating hidden test outputs
- usePyodide React hook for loading and executing Python code in the browser
- ProblemWorkspace component with split-panel layout (problem description + code editor)
- TestRunner component for running visible tests locally and submitting hidden tests
- TestResults component for displaying test pass/fail status
- CodeEditor component wrapping Monaco Editor for Python editing
- Test cases for 26 questions: Two Sum, Valid Parentheses, Best Time to Buy and Sell Stock, Maximum Subarray, Contains Duplicate, Valid Anagram, Climbing Stairs, Binary Search, Palindrome Number, Longest Common Prefix, Roman to Integer, Single Number, Missing Number, Plus One, Happy Number, Majority Element, Search Insert Position, Valid Palindrome, Sqrt(x), Counting Bits, Number of 1 Bits, Reverse Bits, Add Binary, Add Strings, Add Digits, Excel Sheet Column Title

### Changed

- Question detail page now conditionally renders interactive workspace for questions with test cases
- QuestionDetail type extended with function_signature, visible_test_cases, and hidden_test_inputs
- Data loader now handles function_signature and test_cases YAML fields

## [0.5.0] - 2025-06-07

### Added

- Color-coded callout components for different content types (warning, success, info, insight)
- Collapsible component for hiding non-optimal solutions by default
- Icons throughout question detail page using lucide-react
- Inter font for improved typography
- ApproachBox component for visually distinct wrong/correct approach styling
- Badge variants for categories (teal), patterns (indigo), and optimal (green)
- CSS variables for consistent badge colors across light and dark modes

### Changed

- Approach section now uses blue info callout with ClipboardList icon
- Intuition section now uses purple insight callout with Brain icon
- Common Pitfalls section now uses orange warning callout with AlertTriangle icon
- Key Takeaways section now uses green success callout with Lightbulb icon
- Non-optimal solutions are now collapsed by default to focus learners on optimal approach
- Improved line-height (1.7) for prose content sections
- Badge component now uses variant prop instead of className for colors
- Category badges now use teal color scheme
- Pattern badges now use indigo color scheme
- Difficulty badges use dedicated variants (difficulty-easy/medium/hard)

### Fixed

- CodeBlock test now uses proper matcher for syntax-highlighted content

## [0.4.0] - 2025-05-24

### Added

- CI/CD pipeline with GitHub Actions (.github/workflows/ci.yml)
- Production Docker Compose configuration (docker-compose.prod.yml) with Traefik
- Frontend tests for QuestionCard and QuestionFilters components
- Database connection pool configuration (pool_size, max_overflow, pool_recycle)
- Search parameter validation with max_length=100

### Changed

- Health check endpoint now verifies database connectivity
- Difficulty colors moved from hardcoded Tailwind classes to CSS variables

### Infrastructure

- Traefik reverse proxy for HTTPS with Let's Encrypt
- Resource limits on all production containers
- Health checks on all production services

## [0.3.0] - 2025-05-10

### Security

- Removed hardcoded database credentials from config.py (now required env var)
- Replaced actual credentials in .env.example with placeholder values
- Docker Compose now requires POSTGRES_PASSWORD environment variable
- Restricted database port binding to localhost only (127.0.0.1:5432)
- Added non-root user to backend Dockerfile for container security
- Removed credentials from alembic.ini (uses env.py override)

### Added

- Request logging middleware with method, path, status, and duration
- Loading states (skeleton UI) for all async pages via loading.tsx files
- QuestionFilters client component for proper client-side navigation
- aria-live region for copy feedback in CodeBlock component
- aria-label on code block pre elements for screen readers

### Changed

- Improved color contrast for muted-foreground (#5f6368) to meet WCAG AA

### Fixed

- Filter dropdowns in questions page now use client-side navigation instead of window.location

## [0.2.0] - 2025-04-19

### Added

- Service dependency injection in API routes for improved testability
- Security headers middleware (CSP, X-Frame-Options, X-Content-Type-Options)
- Global exception handlers for SQLAlchemyError and generic exceptions
- Accessibility improvements (skip links, form labels, aria-labels, keyboard nav)
- Frontend test infrastructure with Vitest and React Testing Library
- Tests for utils, API client, Badge, and CodeBlock components
- Additional backend service tests (get_question_by_id, combined filters, pagination)
- ApiError class for structured error handling in frontend

### Changed

- CORS configuration restricted to read-only methods (GET, HEAD, OPTIONS)
- Questions page uses Promise.allSettled for resilient data fetching
- Categories and patterns pages now handle API errors gracefully

### Fixed

- Missing htmlFor/id attributes on form labels in questions filter
- Copy button in CodeBlock now keyboard accessible
- Difficulty badges now have aria-labels for screen readers
- External links have descriptive aria-labels

## [0.1.0] - 2025-04-12

### Added

- Initial project structure with FastAPI backend and Next.js frontend
- PostgreSQL database schema with Alembic migrations
- SQLAlchemy models for questions, explanations, solutions, categories, patterns
- Pydantic schemas for API request/response validation
- Service layer for database operations
- API routes for questions, categories, patterns, and stats
- YAML-based content system for questions
- Docker Compose configuration for local development
- Category definitions (15 categories)
- Pattern definitions (13 algorithmic patterns)
- Full question set (15 questions: 5 easy, 7 medium, 3 hard)
- Data loading and validation scripts
- Backend unit tests with 97% coverage
- Next.js frontend with App Router
- Question browser with difficulty, category, and pattern filters
- Question detail pages with explanations and solutions
- Category and pattern browsing pages
- Tailwind CSS styling with dark mode support
- React Query for data fetching
