TheGrind
Coding interview preparation: lessons, solved problems and exercises, organised by topic.
- Algorithms and data structures: the NeetCode 150 problems, solved in Java, Python, C++, JavaScript, Go, Rust and C, and being extended towards NeetCode 250 and beyond.
- Lessons: the techniques behind the problems, from complexity analysis to dynamic programming and bit manipulation, with worked examples.
- SQL and databases: a PostgreSQL lesson series and LeetCode database problems.
- Practical problems: staged specs for non-algorithmic rounds, such as a ledger, a rate limiter, a B+ tree and write-ahead log recovery, with tests for each stage.
- Low-level design: object-oriented design lessons and LLD problems in Java (in progress).
Lessons
To pick a technique for a new problem, start with pattern recognition. It maps problem signals to the lessons below.
Foundations
- Complexity analysis: Big-O, the common complexity classes, and how to analyse your own solutions.
- Pattern recognition: which technique a problem wants, from its constraints and wording.
- P, NP, NP-hard and NP-complete: the complexity classes, reductions, and pseudo-polynomial algorithms.
Data structures
- Hashing: hash maps and sets, collisions, load factor, and the ordered versions.
- Array and hashing problems: Product Except Self, Longest Consecutive Sequence, length-prefixed encoding, the Sudoku box index, anagram keys, and four ways to find the top K.
- Prefix sums: range sums with one subtraction, Subarray Sum Equals K with a hash map, prefix products, and 2D prefix sums.
- Stacks: LIFO, matching brackets, undo, and deferred evaluation.
- Monotonic stack: nearest greater or smaller element in one pass; Daily Temperatures, Largest Rectangle, Trapping Rain Water, Car Fleet and Max Chunks.
- Queues and deques: FIFO, BFS queues, and deques.
- Heaps and priority queues: binary heaps, top-K, two-heap medians, and lazy deletion.
- Heap problems: a heap kept at size k, Last Stone Weight, Task Scheduler with its formula, two heaps for the median, and merging feeds in Design Twitter.
- Tries: prefix trees for word and prefix lookups.
- Trie problems: Implement Trie, wildcard search that branches at each
., and Word Search II with one grid search pruned by the trie.
Two pointers
- Two pointers from opposite ends: why moving one pointer is safe; Two Sum II, Container With Most Water, 3Sum and Trapping Rain Water.
- Two pointers in the same direction: read/write pointers for in-place filtering, and merging from the back.
Sliding window
- Fixed-size sliding windows: add one element, remove one, and track letter counts with a match counter.
- Variable-size sliding windows: longest vs shortest windows, why the cost is O(n), and when a window does not work.
- Sliding window maximum: the monotonic deque, traced step by step.
Sorting and searching
- Sorting: the comparison-sort lower bound, stability, counting and radix sort, and quickselect.
- Bucket sort: sorting by using the key as an index, as in Top K Frequent Elements.
- Binary search: monotonic predicates, boundary searches, floor vs. ceiling, binary search on the answer, and rotated arrays.
Linked lists
- Linked list basics: nodes, the dummy head, why removal needs the previous node, Remove Nth From End and Merge Two Sorted Lists.
- Reversing a linked list: the three-pointer loop drawn step by step, the recursive version, and Reverse Nodes in k-Group.
- Reordering and merging lists: Reorder List, Add Two Numbers, and three ways to Merge k Sorted Lists.
- Copy list and LRU cache: Copy List with Random Pointer with a map or by weaving, and the LRU cache's map plus doubly linked list.
- Floyd's cycle detection: finding a cycle and its entrance in O(1) space, on lists, arrays and number sequences.
Trees
- Tree basics and traversals: terms, height in nodes or edges, iterative DFS with a stack, BFS by level, and Right Side View.
- Recursion on trees: passing information down or up, a special return value for Balanced Tree, and Diameter and Max Path Sum.
- Binary search trees: the ordering rule, Validate BST with bounds, Kth Smallest by inorder, and LCA in a BST.
- Building and serialising trees: rebuilding from preorder and inorder, and preorder with null markers.
Backtracking
- Backtracking basics: choose, explore, undo; the decision tree drawn two ways for Subsets; why paths are copied; and the cost.
- Combinations, permutations and duplicates: reuse with
ivsi + 1, skipping equal values in Subsets II and Combination Sum II, and permutations by swapping. - Backtracking with constraints: pruning in Generate Parentheses, N-Queens diagonals, Word Search marking, and Palindrome Partitioning.
Greedy
- Greedy and how to prove it: the exchange argument and greedy-stays-ahead, with counterexamples that break wrong greedy rules.
- Greedy problems: Kadane, Jump Game I and II, Gas Station, Hand of Straights, Merge Triplets, Partition Labels and Valid Parenthesis String, each proved and traced.
Intervals
- Overlap, merging and inserting: the overlap test, touching intervals, Merge Intervals, Insert Interval in one pass, and Meeting Rooms.
- Scheduling, rooms and queries: Non-overlapping Intervals, Meeting Rooms II with a heap or a sweep, and offline queries with lazy deletion.
Graphs
- Graphs, BFS and DFS: representations, traversals, grids, and connected components.
- Topological sort: ordering a DAG with Kahn's algorithm or DFS post-order, and directed cycle detection.
- Union-Find: disjoint sets with path compression and union by size, for connectivity and undirected cycles.
- Dijkstra: single-source shortest paths with non-negative weights, and its variants.
- Bellman-Ford: shortest paths with negative weights, negative cycles, and paths with at most
kedges. - Minimum spanning tree: Prim and Kruskal, and how an MST differs from shortest paths.
- Eulerian paths and Hierholzer's algorithm: using every edge exactly once.
Dynamic programming
- Dynamic programming: memoization, tabulation, and the common state shapes.
- 1D vs 2D DP: how many dimensions the table needs, and how to shrink it.
- Knapsack: 0/1 and unbounded, counting and min/max variants, and disguised knapsacks.
- String DP: two-sequence tables for LCS, Edit Distance, Distinct Subsequences, Interleaving String and Regex Matching.
- Interval DP: answers for every range
[i, j], filled by length; shrink-the-ends and split-point recurrences.
Bit manipulation
- Integer representation: bit positions, two's complement, and integer type limits in each language.
- Overflow: what each language does on overflow, negating the smallest value, and division of negative numbers.
- Operators and shifts:
& | ^ ~, logical and arithmetic shifts, oversized shifts, and precedence. - Masking: single-bit and multi-bit masks, 32-bit masking in Python, and an integer as a set.
- Bit tricks: XOR cancellation,
x & (x - 1),x & -x, and step-by-step walkthroughs of the bit problems.
Math and geometry
- Math and geometry: matrix rotation, overflow, modular arithmetic, and other non-structural problems.
- Integer formulas: splitting a count in halves, ceiling division, an overflow-free midpoint, flattening a grid index, counting formulas, and the k-largest heap rule.
- Number theory: Euclid's GCD and why it works, LCM without overflow, modular arithmetic and the modular inverse, fast exponentiation, and primes.
Strings
- String basics: what building a string costs in each language, comparing characters, counting with fixed arrays. (draft)
- Pattern matching: naive search, the KMP prefix function, the Z-function. (draft)
- Rolling hash: Rabin-Karp, base and modulus, collisions, double hashing. (draft)
- Palindromes: expanding from the centre, and Manacher in O(n). (draft)
Databases
- SQL basics: the example schema, filtering and sorting, undefined order on ties, NULL and three-valued logic, and the order clauses are evaluated in.
- Joins: inner, outer and self-joins, conditions in ON vs WHERE, anti-joins and the NOT IN trap, and joins that inflate totals.
- Grouping and aggregates: GROUP BY, aggregates and NULL, count(*) after a left join, WHERE vs HAVING, and FILTER.
- Subqueries, CTEs and set operations: scalar and correlated subqueries, EXISTS, derived tables, CTE inlining, recursive CTEs, and UNION/EXCEPT.
- Window functions: aggregates next to each row, ranking and top N per group, running totals, lag and lead, and frames.
- Views and virtual tables: views, updatable views and CHECK OPTION, materialized views, temporary tables, VALUES, generate_series and LATERAL.
- Changing data and transactions: INSERT/UPDATE/DELETE with RETURNING, upserts, constraints, transactions and savepoints, isolation levels and lost updates.
- Triggers: BEFORE, AFTER and INSTEAD OF, row and statement level, audit logs, derived counters, recursion, and simpler alternatives.
- SQL query planning and indexes: how a query becomes an execution plan, and how indexes change it.
- PL/SQL: blocks, variables and control flow: anonymous and named blocks, %TYPE and %ROWTYPE, SELECT INTO, static and dynamic SQL, IF, CASE and loops.
- PL/SQL: cursors: explicit cursors and attributes, cursor FOR loops, parameters, FOR UPDATE, SYS_REFCURSOR, BULK COLLECT and FORALL.
- PL/SQL: procedures, functions, packages and exceptions: parameter modes, functions in SQL, packages and session state, raising and handling exceptions, what an unhandled error rolls back.
- PL/SQL: triggers, and loops vs set-based SQL: Oracle trigger syntax, logging changes, the mutating table error and compound triggers, and a cursor loop vs one MERGE.
Object-oriented design
- The LLD round: an order of work for the round, from requirements to entities to code, and how to absorb an extension.
- OOP principles and SOLID: the four pillars, and each SOLID principle as a violation and its fix.
- Class diagrams: the small part of UML needed in an interview.
- Creational patterns: simple factory, factory method, abstract factory, builder, and thread-safe singletons vs injection.
- Structural patterns: decorator, adapter, facade, composite and proxy.
- Behavioral patterns: strategy, observer, state, command, chain of responsibility, template method, iterator, mediator and memento.
- Concurrency for LLD: races, locks and atomics, blocking queues, and testing concurrent code.
Data modeling and persistence
- Entities and keys: entities to tables, natural vs surrogate keys, identity columns, sequences, UUIDs, key tables and hi-lo, and reading the generated id in JDBC.
- Relationships in tables: 1:1, 1:N and N:N, join tables with attributes, self-references, and what each ON DELETE option does.
- Normalization: update, insert and delete anomalies, functional dependencies, 1NF to BCNF, and denormalizing on purpose.
- Mapping objects to tables: foreign keys vs collections, one-way and two-way N:N, association classes, equality, and inheritance mapping.
- Data access patterns: DTO, DAO and DAO factory, the JDBC method skeleton, the mapping DAO for N:N, Repository, Active Record vs Data Mapper.
- Loading related data: eager vs lazy, lazy loading with a Proxy, the N+1 problem and its fixes, identity map.
- Transactions in application code: autocommit, transaction boundaries in the service, unit of work, optimistic and pessimistic locking.
- JPA and Hibernate: entities and ids, owning side and mappedBy, cascade, fetch types, JOIN FETCH, the persistence context, @Version, inheritance.
- Schema patterns and anti-patterns: soft delete, audit columns, enumerations, polymorphic associations, EAV, and migrations.
Document databases
- Documents and queries: BSON and _id, find and update operators, $elemMatch, single-document atomicity, the aggregation pipeline and $lookup.
- Embedding vs referencing: the questions that decide, each cardinality from 1:1 to 1:squillions and N:M, copies of embedded data, and a design method.
- Relationship patterns: extended reference, subset, outlier, computed and bucket.
- Structure patterns: polymorphic, attribute, four ways to store trees, and schema versioning.
- Sizing and cost estimation: aggregate notation, document length and pages, documents and pages read per query, and a worked exam exercise.
- Indexes, validation and transactions: explain, compound and multikey indexes, partial unique indexes, $jsonSchema, multi-document transactions and write conflicts.
Other problem sets
- SQL problems: LeetCode database problems solved in PostgreSQL, each linked to its lesson.
- PL/SQL problems: procedures and functions on Oracle, with schema, example data and expected output.
- Practical coding problems: staged specs for non-algorithmic interviews, with solutions and tests per stage. Business logic in Python, storage in Java.
- Low-level design problems: object-oriented design problems in Java, with staged requirements and checks per stage.
- HackerRank problems: three HackerRank problems, each with the nearest LeetCode problem.