All topics
Data structures and algorithms, visually
Every topic as a short animation you step through, with the running line of code highlighted. Every lesson has C# code, and the core ones also have Java, C++ and Python. Pick a topic to read the idea and the code, then watch it run.
Also: the 205-problem interview sheet and the courses: GenAI engineering , Claude certification prep , Security internship prep , ASP.NET Core Web API , AI engineer roadmap , Production AI on Azure .
Arrays Strings Hashing Sorting Stacks and queues Linked lists Trees Heaps Graphs Backtracking Dynamic programming Bit manipulation C# concepts OOP concepts Design patterns SOLID principles GenAI & Claude Web security High-level design Low-level design
Arrays Scans, two pointers, windows and prefix sums over contiguous data.
Linear search Check every element in order until the target turns up. The only search that works on unsorted data. O(n) Binary search On a sorted array, look at the middle and throw away the half that cannot contain the target. O(log n) Two pointers: pair sum Find two values in a sorted array that add up to a target by closing in from both ends. O(n) Sliding window: max sum of k Find the largest sum of any k consecutive elements without re-adding the whole window each time. O(n) Kadane's algorithm Largest sum of any contiguous subarray, including arrays with negative numbers. O(n) Prefix sums: range query Precompute running totals once, then answer any "sum from l to r" question with a single subtraction. O(n) build, O(1) query Dutch national flag: sort 0, 1, 2 Sort an array that only holds three distinct values in one pass with three pointers. O(n) Boyer-Moore majority vote Find the value that appears more than half the time, using one counter and no extra memory. O(n) Three sum Find every group of three numbers that adds up to 0: sort, fix one number, then close in on the other two with two pointers. O(n²) Container with most water Two walls and the water between them: close in from both ends, always moving the shorter wall. O(n) Trapping rain water Each bar traps water up to the shorter of the tallest wall on its left and its right, tracked with two pointers. O(n) Move zeroes Push every zero to the end in place, in one pass, without disturbing the order of the other values. O(n) Product of array except self For every index, multiply the product of everything to its left by the product of everything to its right. No division needed. O(n) Merge overlapping intervals Sort intervals by start, then merge any that overlap with the one before it in a single scan. O(n log n) Rotate array by k Rotate an array right by k positions in place using three reversals instead of a second array. O(n) Best time to buy and sell stock One pass, one buy and one sell: track the lowest price seen so far and the best profit it could unlock. O(n) Next permutation Find the next lexicographic arrangement of the array, in place, without listing every permutation. O(n) Spiral matrix traversal Read a matrix in a clockwise spiral by walking one shrinking ring of the border at a time. O(rows × cols) Search in Rotated Sorted Array Binary search a sorted array that was rotated: at every step one half is still sorted, so check whether the target can be inside that half. O(log n) Find Minimum in Rotated Sorted Array Find the smallest value of a rotated sorted array by comparing the middle with the right end and keeping the half that holds the drop. O(log n) Koko Eating Bananas Find the slowest eating speed that still finishes every pile within h hours, by binary searching on the speed itself. O(n log m), m = largest pile Find all duplicates in an array Every value is between 1 and n and appears once or twice. Use each value as an index and flip that slot negative; a slot that is already negative means the value is a repeat. O(n) First missing positive Find the smallest positive integer that is not in the array. Swap every value 1..n into its home index v - 1, then the first index that holds the wrong value names the answer. O(n) Squares of a sorted array Square every value of a sorted array and keep the result sorted. The largest square is always at one of the two ends, so fill the answer from the back. O(n) Boats to save people Each boat carries at most two people with a combined weight up to the limit. Sort, then always send the heaviest person, taking the lightest along whenever they fit. O(n log n) Fruit Into Baskets Pick the longest unbroken run of trees that has at most two fruit types, with a sliding window and a count per type. O(n) Minimum Size Subarray Sum Find the shortest run of positive numbers whose sum is at least target: grow the window until it is enough, then shrink it from the left. O(n) Max Consecutive Ones III Find the longest run of 1s you can make by flipping at most k zeros: a sliding window that may hold at most k zeros. O(n) Search a 2D Matrix Binary search a matrix whose rows continue each other in sorted order, by treating it as one flat sorted array and mapping each index back to a row and column. O(log(m · n)) Find Peak Element Find any element bigger than both neighbours in O(log n) by binary searching toward the higher neighbour. O(log n) Median of Two Sorted Arrays Binary search where to cut the shorter array. The cut in the longer array follows, and the cut is right when every value on the left is no bigger than every value on the right. O(log min(m, n)) Capacity To Ship Packages Within D Days Binary search on the ship capacity itself: a greedy pass counts the days a capacity needs, and more capacity never needs more days. O(n log(sum)) Find First and Last Position of Element in Sorted Array Two lower-bound binary searches: the first index holding a value >= target, and the first index holding a value > target. The run of target sits between them. O(log n) Non-overlapping Intervals Remove the fewest intervals so the rest never overlap: sort by end and greedily keep every interval that starts after the last kept one ends. O(n log n) Jump Game Decide whether the last index is reachable by tracking the farthest index any reachable position can jump to. O(n) Insert Interval Insert a new interval into a sorted, non-overlapping list in one pass: copy what ends before it, merge what overlaps it, copy the rest. O(n) Meeting Rooms II Find the fewest rooms for a set of meetings: take meetings by start time and keep a min-heap of the times each room frees up. O(n log n) Gas Station Find the station to start from to drive the whole circuit in one pass: restart just after any station where the tank runs dry. O(n) Partition Labels Cut a string into as many parts as possible so each letter appears in only one part, using each letter's last occurrence. O(n) Minimum Number of Arrows to Burst Balloons Shoot as few vertical arrows as possible to burst every balloon: sort by end and shoot at the end of the first balloon not yet burst. O(n log n) Strings Character-level versions of the pointer and counting patterns.
Palindrome check A string is a palindrome if it reads the same in both directions. Compare from the outside in. O(n) Longest substring without repeats A variable-size sliding window: grow on the right, and jump the left edge past any repeated character. O(n) Valid anagram Two words are anagrams if they use exactly the same letters. Count up for one word and down for the other. O(n) Longest common prefix Scan column by column across every word at once. The prefix ends the moment one word disagrees. O(n·m) String compression Run-length encode in place: count each run of identical characters, then write the character followed by its count. O(n) Reverse words in a string Split on whitespace to get the words, reverse their order with two pointers, then rejoin with single spaces. O(n) Minimum window substring A variable-size sliding window with a character-count map: grow the right edge until every needed letter is covered, then shrink the left edge as far as it will go. O(n) Longest palindromic substring Try every index as the center of a palindrome and expand outward while the characters match, once for an odd-length center and once for an even-length center. O(n²) String to integer (atoi) Skip leading spaces, read an optional sign, consume digits while clamping the running value, and stop at the first non-digit. O(n) ZigZag conversion Write the characters down the rows and diagonally back up in a zigzag, then read the result off row by row. O(n) Roman to integer Add each symbol's value, except when a smaller symbol sits just before a larger one: then subtract it instead. O(n) Valid palindrome II Close in from both ends as in a plain palindrome check, but the first mismatch gets one free pass: try skipping either side. O(n) Reverse vowels of a string Reverse only the vowels and leave every other character in place. Two pointers walk in from both ends, skip consonants, and swap whenever both rest on a vowel. O(n) Is subsequence Can s be made by deleting some characters of t without reordering the rest? Walk t once and tick off the characters of s in order. O(n), n = length of t Longest Repeating Character Replacement Find the longest substring that can be turned into one repeated letter with at most k changes, using a sliding window and the count of its most common letter. O(n) Permutation in String Decide whether s2 contains some rearrangement of s1 by sliding a window of length s1 over s2 and comparing letter counts. O(n) Hashing Trade memory for O(1) lookups with Dictionary and HashSet.
Two sum with a dictionary Find two numbers that add up to a target in an unsorted array, in a single pass. O(n) Subarray sum equals k Count the contiguous subarrays that add up to k. Prefix sums plus a dictionary, and it works with negatives. O(n) Contains duplicate Does any value appear twice in the array? A hash set answers in a single pass, no sorting required. O(n) Longest consecutive sequence Find the length of the longest run of consecutive integers, in O(n), without sorting. O(n) Top k frequent elements Return the k values that occur most often. Count with a dictionary, then drop each value into a bucket by its count. O(n) Group anagrams Group words that are anagrams of each other. Sorting each word's letters gives a key that every anagram shares. O(n * w log w) Isomorphic strings Can every character of one string be swapped for a fixed character in another, with the swap working both ways? O(n) Ransom note Can the ransom note be built using only the letters available in the magazine? Count, then spend. O(m + n) Valid Sudoku Check that no digit repeats in any row, column or 3x3 box of a partly filled board. One set per row, column and box; every filled cell is added to its three sets. O(1): always 81 cells Subarray sums divisible by K Count the contiguous subarrays whose sum is a multiple of k. Two prefix sums with the same remainder mod k enclose exactly such a subarray, so count remainders as you go. O(n) Time Based Key-Value Store A dictionary maps each key to its list of (timestamp, value) pairs. Timestamps only grow, so each list is sorted and get binary searches it for the latest timestamp <= t. O(1) set, O(log n) get Sorting The classic sorts, from quadratic to n log n to linear.
Bubble sort Swap neighbours that are out of order. After each pass the largest remaining value has floated to the end. O(n²) Selection sort Find the smallest remaining value and put it at the front of the unsorted part. Repeat. O(n²) Insertion sort Take the next value and slide it left into its place among the values already sorted, like sorting cards in your hand. O(n²) Merge sort Split the array in half, sort each half, then merge the two sorted halves. Divide and conquer. O(n log n) Quick sort Pick a pivot, move everything smaller to its left, then sort the two sides the same way. O(n log n) average Counting sort Sort small integers without comparing them: count how many of each value there are, then write them out in order. O(n + k) Shell sort Insertion sort done at a distance first: a shrinking gap moves far-out-of-place values close to home before the final, cheap pass. O(n log n) to O(n²), gap dependent Radix sort Sort integers digit by digit, from the ones place up, using a stable counting sort as the subroutine for each digit. O(d(n + b)) Bucket sort Scatter values into a handful of buckets by value range, sort each small bucket, then read the buckets back in order. O(n + k) average Cycle sort Place each value directly into its final sorted index, writing every element to the array at most once. O(n²) Stacks and queues Last in first out, first in first out, and the monotonic tricks.
Valid parentheses Check that every bracket closes in the right order. The textbook use of a stack. O(n) Monotonic stack: next greater For every element, find the first larger value to its right, in a single pass. O(n) Evaluate postfix (RPN) Evaluate an expression written with the operator after its operands, such as "3 4 +". No brackets or precedence rules needed. O(n) Queue from two stacks Build first in, first out behaviour using only two last in, first out stacks. O(1) amortised Sliding window maximum (deque) Report the largest value in every window of size k, using a double-ended queue that keeps only useful candidates. O(n) Min stack A stack that can also report its minimum value in O(1), using a second stack that tracks the running minimum. O(1) per operation Daily temperatures For each day, find how many days until a warmer one, using a monotonic stack of days still waiting for an answer. O(n) Largest rectangle in a histogram Find the biggest rectangle that fits under a histogram, using a monotonic stack of bar indices to size each bar's full width in one pass. O(n) Decode string Expand a run-length pattern like "3[a2[c]]" into "accaccacc", using a stack to remember what to return to when each bracket closes. O(n) Asteroid collision Simulate asteroids moving right (positive) or left (negative) along a line, where a collision destroys the smaller one, using a stack of survivors. O(n) Remove k digits Remove k digits from a number to leave the smallest possible result, using a monotonic increasing stack of digits. O(n) Design a circular queue A fixed-size queue backed by one array, where the head wraps around with modulo instead of ever shifting elements. O(1) per operation Online Stock Span For each new price, count the run of days up to today with a price no higher than today's. A stack of (price, span) pairs lets each call skip whole runs at once. O(1) amortised per call Basic Calculator II Evaluate + - * / without parentheses in one pass. Remember the operator in front of each number: push for + and -, combine with the stack top at once for * and /. O(n) Linked lists Pointer rewiring and the fast and slow runner.
Reverse a linked list Flip every next pointer so the list runs the other way, using three references and no extra memory. O(n) Middle of a list: fast and slow Find the middle node in one pass with two references moving at different speeds. O(n) Cycle detection (Floyd's) Decide whether a linked list loops back on itself, without storing the nodes you have visited. O(n) Merge two sorted lists Weave two sorted lists into one sorted list by always taking the smaller head. O(m + n) Remove the n-th node from the end Delete a node counted from the back in a single pass, by keeping two references a fixed distance apart. O(n) Add two numbers (digits in reverse order) Add two numbers stored as linked lists of digits, least-significant digit first, carrying into the next node like adding on paper. O(max(m, n)) Intersection of two linked lists Find the node where two lists merge into a shared tail, using two pointers that swap lists instead of measuring lengths. O(m + n) Palindrome linked list Check whether a list reads the same forwards and backwards by reversing its second half and comparing inward from both ends. O(n) Copy a list with a random pointer Deep-copy a list whose nodes carry a second, arbitrary 'random' pointer, without a dictionary mapping old nodes to new ones. O(n) Reorder a list: L0, Ln, L1, Ln-1, … Rearrange a list into the zigzag order L0, Ln, L1, Ln-1, … by splitting it in half, reversing the back half, and weaving the two together. O(n) Flatten a multilevel linked list Flatten a list whose nodes can each hang a child list off of them, splicing every child in depth-first so the result is one plain list. O(n) Sort a linked list (merge sort) Sort a linked list in n log n time by cutting it in half at the middle, sorting each half, and merging — merge sort adapted to pointers instead of array slices. O(n log n) LRU Cache A dictionary finds a key's node in O(1); a doubly linked list keeps the nodes in recency order, so moving a node to the front and evicting from the back are O(1) too. O(1) per get and put Reverse Linked List II Reverse only positions left to right, in one pass: stand just before the section and keep moving the node after curr to the front of it. O(n) Odd Even Linked List Group the nodes at odd positions first, then the nodes at even positions, by threading two chains through the list and joining them at the end. O(n) Swap Nodes in Pairs Swap every two adjacent nodes by moving pointers, not values. A dummy head gives every pair a node in front of it, even the first pair. O(n) Trees Binary search trees, the DFS orders, and level order.
Binary search tree: insert Build a BST one key at a time. Smaller keys go left, larger keys go right. O(h) Binary search tree: search Look up a key by walking down from the root, discarding a whole subtree at every step. O(h) Inorder traversal Left subtree, then the node, then the right subtree. On a BST this yields the keys in sorted order. O(n) Preorder traversal The node first, then its left subtree, then its right subtree. Parents always come before their children. O(n) Postorder traversal Both subtrees first, then the node. Children are always finished before their parent. O(n) Level order traversal (BFS) Visit the tree level by level, left to right, using a queue, and return each level as its own list. O(n) Height of a tree The number of nodes on the longest path from the root down to a leaf, computed bottom-up. O(n) Lowest common ancestor in a BST Find the deepest node that has both given keys beneath it (or is one of them). O(h) Diameter of a binary tree The longest path between any two nodes, found by combining subtree heights at every node. O(n) Check if a binary tree is height-balanced A post-order height check that stops early the moment any subtree is found unbalanced. O(n) Invert a binary tree Swap the left and right child at every node to produce the mirror image of the tree. O(n) Check if two binary trees are the same Walk both trees together, node by node, confirming every structure and value lines up. O(n) Check if a binary tree is symmetric A tree is a mirror of itself when its left and right subtrees mirror each other at every level. O(n) Path sum Does some root-to-leaf path add up to a target value? O(n) Lowest common ancestor (general binary tree) Find the deepest node with both targets beneath it, without relying on any BST ordering. O(n) Zigzag level order traversal Breadth-first, but alternate the reading direction of every level, left-to-right then right-to-left. O(n) Binary tree right side view What a tree looks like standing to its right: the last node visible on every level. O(n) Kth smallest element in a BST An inorder walk visits BST keys in sorted order, so stop as soon as the kth one is seen. O(h + k) Validate a binary search tree Pass an allowed (low, high) range down the tree. Every key must fit its range, not just beat its parent. O(n) Binary tree maximum path sum Postorder: each node hands its parent its best downward gain, and checks the best path that bends through it. O(n) Serialize and deserialize a binary tree Write the tree in preorder with # for every missing child, then rebuild it by reading the tokens back in the same order. O(n) Implement Trie (Prefix Tree) Each node holds up to 26 children and an end-of-word flag. Insert, search and startsWith all walk one child per letter. O(length) per operation Heaps Priority queues: always know the smallest or largest item.
Min-heap: insert and sift up A heap is a complete binary tree stored in an array, where every parent is smaller than its children. O(log n) per insert Heap sort Turn the array into a max-heap, then repeatedly move the largest value to the end. O(n log n) K-th largest element Find the k-th largest value without sorting everything, by keeping only the k biggest values seen so far. O(n log k) Merge K sorted lists Merge several already-sorted lists into one sorted result by always taking the smallest available head, using a min-heap of the current heads. O(n log k) K closest points to the origin Find the k points closest to the origin by keeping a max-heap of size k, evicting the farthest point whenever the heap grows too large. O(n log k) Last stone weight Repeatedly smash the two heaviest stones together using a max-heap, until at most one stone remains. O(n log n) Task scheduler with cooldown Greedily run the most frequent remaining task each tick, using a max-heap of task counts and a queue for tasks that are cooling down. O(n log m) Find median from a data stream Track the median of a growing stream with two heaps: a max-heap for the lower half, a min-heap for the upper half, kept balanced. O(log n) per insert, O(1) to find the median Kth Largest Element in a Stream Keep a min-heap of the k largest values seen so far. Its root, the smallest of them, is the k-th largest overall. O(log k) per add Top K Frequent Words Count every word, then keep a min-heap of the k strongest words, where a tie in count goes to the alphabetically earlier word. O(n log k) Graphs Traversal, shortest paths, ordering and spanning trees.
Breadth-first search Explore a graph in rings: all neighbours first, then their neighbours. Finds shortest paths when every edge costs the same. O(V + E) Depth-first search Follow one path as far as it goes, then back up and try the next branch. O(V + E) Dijkstra's shortest path Shortest distance from one node to every other node when edges have non-negative weights. O((V + E) log V) Topological sort (Kahn's) Order the nodes of a directed graph so every arrow points forward. Think build steps or course prerequisites. O(V + E) Kruskal's minimum spanning tree Connect every node with the cheapest possible set of edges. Uses union-find to avoid cycles. O(E log E) Number of islands (flood fill) Count groups of connected land cells in a grid. A grid is a graph where each cell links to its four neighbours. O(rows × cols) Clone a graph Deep-copy a connected graph. A map from original node to its clone stops cycles from causing infinite recursion. O(V + E) Course schedule (cycle detection) Decide whether every course can be finished. A directed graph can be fully ordered only if it has no cycle. O(V + E) Number of provinces Count the connected components of an undirected graph: groups of cities linked directly or indirectly. O(V + E) Union-find (disjoint set) Track groups of items as they merge, and answer "are these two already in the same group?" in near constant time. O(α(V)) per op Minimum spanning tree (Prim's) Grow one tree outward from a start node, always adding the cheapest edge that reaches a new node. O(E log V) Bellman-Ford shortest path Shortest distance from one source to every node, even with negative edge weights (as long as there is no negative cycle). O(V × E) Floyd-Warshall (all-pairs shortest path) Shortest distance between every pair of nodes at once, by letting each node in turn act as a stepping stone. O(V³) Rotting oranges Multi-source BFS on a grid: every rotten orange spreads to its fresh neighbours at the same time, one minute per layer. O(rows × cols) Surrounded regions Flip every 'O' to 'X' unless it connects back to the border. Flood fill from the border first, so you never have to guess. O(rows × cols) Word ladder Shortest chain from one word to another, changing one letter per step, always through words in the list. BFS over a graph of words. O(N × L²) Network delay time A signal leaves node k and travels along directed, timed edges. How long until every node has heard it? Dijkstra from k, then take the largest distance. O((V + E) log V) Number of connected components Count the separate groups in an undirected graph of n nodes. Start with n groups and let union-find merge them edge by edge. O(n + E · α(n)) Redundant connection A tree got one extra edge, which created exactly one cycle. Find that edge: the first one whose two ends are already connected. O(n · α(n)) Graph valid tree Do n nodes and these undirected edges form one tree? A tree has exactly n - 1 edges and no cycle; union-find spots the cycle. O(n · α(n)) Pacific Atlantic water flow Rain flows to neighbours that are not higher. Which cells drain into both oceans? Search backwards, uphill, from each ocean's coast and intersect the two reach sets. O(rows × cols) Backtracking Try a choice, recurse, undo it, try the next.
Subsets Generate every subset of a set. Each element is either in or out, so there are 2ⁿ of them. O(n · 2ⁿ) Permutations Generate every ordering of a set of values. O(n · n!) N-Queens Place n queens on an n × n board so that no two share a row, column or diagonal. O(n!) Combination Sum Pick numbers from a list, reusing any of them as often as needed, so they add up to a target. O(2ⁿ) Palindrome Partitioning Cut a string into pieces so that every piece reads the same forwards and backwards. O(n · 2ⁿ) Word Search Find a word hidden in a grid of letters, moving between side-by-side cells without reusing one. O(rows · cols · 4ᴸ) Generate Parentheses Build every string of n pairs of parentheses that is balanced, without ever generating an invalid one. O(4ⁿ / √n) Letter Combinations of a Phone Number Every word a string of phone-keypad digits could spell, one letter per digit. O(4ⁿ) Rat in a Maze Find a path of open cells from the top-left corner of a maze to the bottom-right corner. O(4^(n²)) Sudoku Solver Fill every empty cell of a tiny 4 × 4 Sudoku (four 2 × 2 boxes) so each row, column and box holds 1 to 4 once each. O(4^k) Subsets II List every subset of numbers that may contain duplicates, without listing the same subset twice. Sort, then never start two branches with the same value at one depth. O(n · 2ⁿ) Combination sum II Pick numbers that add up to a target, each number at most once, where the list may hold duplicates. Sort, skip repeated values at one depth, and stop as soon as a number is too big. O(2ⁿ) Dynamic programming Solve each subproblem once and reuse the answer.
Climbing stairs Count the ways to climb n steps taking 1 or 2 at a time. The gentlest introduction to DP. O(n) House robber Pick values from a row so that no two picks are next to each other, and the total is as large as possible. O(n) Coin change Fewest coins needed to make an amount. A case where the greedy choice gives the wrong answer. O(amount × coins) Longest increasing subsequence The longest run of values that keeps rising, where you may skip elements but not reorder them. O(n log n) Longest common subsequence Length of the longest sequence of characters that appears in both strings in the same order. The core of diff tools. O(m × n) Edit distance The fewest single-character inserts, deletes and replacements needed to turn one string into another. O(m × n) 0/1 knapsack Choose items with weights and values to maximise total value without exceeding a weight limit. Each item is used at most once. O(n × capacity) Unique paths in a grid Count the routes from the top-left to the bottom-right corner when you may only move right or down. O(rows × cols) Longest palindromic subsequence Length of the longest subsequence of a string that reads the same forwards and backwards. O(n²) Word break Decide whether a string can be split into a sequence of words taken from a dictionary. O(n²) Partition equal subset sum Decide whether an array can be split into two groups with equal totals. A subset-sum problem in disguise. O(n × sum) Maximum product subarray Largest product of a contiguous run of numbers. A negative value can turn the smallest product into the largest. O(n) Min cost climbing stairs Cheapest way to reach the top of a staircase, paying the cost of a step each time you leave it, moving 1 or 2 steps at a time. O(n) Decode ways Count the ways to decode a digit string into letters, where A is 1 and Z is 26. O(n) Subset sum Decide whether any subset of an array sums to a given target. The general table-building behind many knapsack-style problems. O(n × target) Egg drop puzzle Find the fewest drops needed, in the worst case, to find the highest floor an egg can be dropped from without breaking. O(eggs × floors²) House robber II The houses sit in a circle, so the first and last are neighbours too. Run house robber twice and keep the better result. O(n) Matrix chain multiplication Choose where to place the parentheses in a chain of matrix multiplications to minimise the total number of scalar multiplications. O(n³) Target sum Put + or - in front of every number so they add up to the target. Count the ways by turning it into a subset-sum count. O(n × P) Maximal square Find the largest square made only of 1s in a binary matrix. Each cell asks its three neighbours how big a square they end, and grows the smallest by one. O(rows × cols) Bit manipulation Working directly with the binary form of a number.
C# concepts How the language and runtime behave: memory, strings, LINQ, async and collections.
Value types and reference types Assigning a struct copies the data. Assigning a class instance copies only the reference to it. copy: O(size) Boxing and unboxing Storing a value type in an object variable wraps a copy of it in a heap object. Reading it back copies it out again. O(1) plus an allocation Passing by value, ref and out By default a method gets a copy of the argument. ref and out hand over the caller's variable itself. O(1) String immutability and StringBuilder A string can never be changed after it is created. "Modifying" one always builds a new string. s += x is O(n) Closures and the loop variable trap A lambda captures the variable, not the value it had at that moment. In a for loop that surprises almost everyone once. O(n) LINQ deferred execution A LINQ query is a recipe, not a result. It runs each time you enumerate it, against the data as it is then. runs on enumeration async and await await does not block the thread. It pauses the method, hands control back to the caller, and resumes when the work finishes. non-blocking How List<T> grows A List<T> is an array with spare room. When the room runs out it allocates an array twice as big and copies everything across. Add is O(1) amortised Inside a Dictionary: buckets and collisions A dictionary turns the key into a number, uses that number to choose a bucket, and only searches inside that one bucket. O(1) average try, catch and finally Follow the path through a try block when the code succeeds and when it throws. O(1) Iterators and yield return A method with yield return produces its values one at a time, pausing between them until the caller asks for the next. O(1) per item IQueryable vs IEnumerable in EF Core With IQueryable, EF Core can send the filter and limit to SQL. After ToList, the same LINQ operators run in memory. depends on query plan CancellationToken and async requests Cancellation is a signal the operation must observe. Passing a token to async I/O lets the caller request that work stop. cooperative OOP concepts Classes, encapsulation, inheritance, polymorphism and interfaces, shown as running code.
Design patterns Reusable ways to structure object creation, data access and interchangeable behaviour.
SOLID principles Five design principles for keeping object-oriented code easier to change and test.
GenAI & Claude How language models, prompts, tools, retrieval and agents work, shown step by step.
How a model writes: one token at a time A language model never writes a whole answer at once. It predicts the next token, adds it to the text, and repeats. O(n) Tokens and the context window Models read tokens, not words, and can only look at a limited window of them at once. Watch old tokens fall out. O(n) Temperature and sampling The same scores give a sharp or a flat probability list depending on temperature. Low means predictable, high means varied. O(k) A well-built prompt: task, context, rules, format Good prompts say what to do, give the data, set limits, and describe the answer shape. XML-style tags keep the parts apart. O(1) Few-shot examples steer the output Showing the model a few input and answer pairs teaches it the format and the labels, often better than describing them. O(1) The Messages API: request, response, history The model is stateless. Your app keeps the conversation, resends it on every call, and checks why the reply stopped. O(n) Tool use: the model asks, your app acts The model never runs anything. It asks for a tool call, your code validates and runs it, and returns the result. O(t) Embeddings and similarity search Embeddings turn text into points so that similar meanings land close together. Search is finding the nearest points. O(n × d) RAG: retrieve, ground, answer with sources Retrieval-augmented generation finds the relevant pieces of your documents first, then makes the model answer from them. O(n × d) The agent loop: think, act, observe, stop An agent repeats the tool-use loop toward a goal. Step limits and repeat checks keep it from running forever. O(s) Prompt injection: untrusted text, trusted code Text fetched from the web can contain instructions aimed at your model. Do not rely on the model to resist; enforce permissions in code. O(t) Evaluations: test cases, scores, regressions Prompts change behaviour in ways you cannot see by eye. Run fixed test cases against each version and compare case by case. O(c × p) Web security Linux, HTTP, auth, the OWASP Top 10, XSS and API security, shown as attacks and defences you can step through.
Linux permissions: who can read, write and run a file Every Linux file has an owner, a group and three sets of rwx bits. Reading them is the first skill on any server. O(1) What happens when you open a web page From typing a URL to seeing the page: DNS, TCP, TLS, the HTTP request, the app and the database. O(1) HTTPS: the TLS 1.3 handshake How a browser and server agree on secret keys over a public network, and how the certificate stops impostors. O(1) Authentication vs authorisation Authentication asks who you are. Authorisation asks what you may do. Mixing them up causes real breaches. O(1) JWT: what is inside a token, and what to check A JSON Web Token is header.payload.signature. Anyone can read it; only the server can sign it. O(1) Broken access control (IDOR) Changing an id in the URL should never show someone else’s data. The fix is one ownership check on the server. O(1) SQL injection and parameterised queries When user input is glued into SQL text, input can change the query’s meaning. Parameters keep data as data. O(1) Cross-site scripting (XSS) and output encoding If a page prints user input as HTML, that input can run as script in other users’ browsers. Encoding output stops it. O(1) CSRF and CORS Browsers attach cookies automatically, so another site can trigger requests to yours. SameSite cookies and tokens stop that. O(1) From finding to fix: assessment and reporting A vulnerability is only useful once it is verified, rated and written up so a developer can fix it. O(1) High-level design How large systems are built: load balancers, caches, queues, sharding and real case studies, traced request by request.
Anatomy of a scalable web request DNS, CDN, load balancer, stateless app servers, cache and database: the boxes almost every HLD answer starts from. O(1) per hop Load balancing: round robin and least connections How a load balancer picks a server, skips unhealthy ones, and why the choice of algorithm matters for slow requests. O(1) per pick Caching: cache-aside, TTL and invalidation Read through the cache, write to the database and delete the cached copy. Plus the two classic failure modes: stale data and the stampede. O(1) Sharding with consistent hashing Spread keys over many database or cache nodes so that adding a node moves only a small share of keys. O(log n) lookup Message queues: decouple, buffer and retry Why "place order" should not wait for email, invoices and analytics, and how a queue with retries and a dead-letter queue keeps work safe. O(1) per message Rate limiting with a token bucket Allow short bursts but cap the average rate per user, the algorithm behind most API rate limits. O(1) per request Replication, read replicas and the CAP trade-off Copy data to more machines for reads and for survival, then decide what happens when the copies cannot talk to each other. O(1) per write Case study: URL shortener end to end The most common HLD warm-up: create a short code, redirect fast, count clicks without slowing redirects. O(1) redirect Low-level design Class diagrams you can step through: relationships, patterns and classic designs like a parking lot, elevator and vending machine.
Class relationships: is-a, has-a, uses The six lines in a class diagram and the C# each one becomes: inheritance, implementation, composition, aggregation, association, dependency. — Strategy in a design: parking fees Keep the parking lot closed for change while fee rules keep changing, by putting the rule behind an interface. — Observer: one change, many listeners When a parking spot frees up, the display board, the app and the audit log all need to know, without the spot tracker knowing about each of them. — State pattern: vending machine Replace a status field and switch statements with one class per state, each deciding what happens next. — Case study: parking lot The classic LLD question, built one class at a time: lot, levels, spots, vehicles, tickets and fees, with a thread-safe spot. O(spots) to find a spot Case study: elevator system A controller that assigns hall calls and cars that serve their stops in one direction before turning. O(log s) per stop