Fundamental Data Structures

The building blocks of efficient and organized software. Explore how data is structured to solve real-world problems.

Deep dive ready

Arrays

A collection of items stored at contiguous memory locations. Elements can be accessed randomly using indices.

Access

O(1)

Search

O(n)

Insert

O(n)

Delete

O(n)

Real-World Examples:

  • Playlists in Spotify or Apple Music.
  • A spreadsheet like Google Sheets.
  • Storing pixels of an image.
Deep dive ready

Linked Lists

A linear data structure where elements are not stored at contiguous memory locations but are linked using pointers.

Access

O(n)

Search

O(n)

Insert

O(1)

Delete

O(1)

Real-World Examples:

  • Web browser history (previous/next).
  • Undo functionality in text editors.
  • Image viewer slideshows.
Deep dive ready

Stacks

A LIFO (Last-In, First-Out) data structure. The last element added is the first one to be removed.

Access

O(n)

Search

O(n)

Insert

O(1)

Delete

O(1)

Real-World Examples:

  • The Undo (Ctrl+Z) feature in VS Code.
  • Function call stack in programming.
  • Reversing a word.
Deep dive ready

Queues

A FIFO (First-In, First-Out) data structure. The first element added is the first one to be removed.

Access

O(n)

Search

O(n)

Insert

O(1)

Delete

O(1)

Real-World Examples:

  • Managing print jobs.
  • Handling requests on a web server.
  • CPU task scheduling.
Deep dive ready

Trees

A hierarchical data structure with a root node and child nodes. Binary Search Trees (BSTs) are a common type for efficient searching.

Access

O(log n)

Search

O(log n)

Insert

O(log n)

Delete

O(log n)

Real-World Examples:

  • The file system on your computer.
  • The HTML DOM (Document Object Model).
  • Organizational charts.
Deep dive ready

Red-Black Trees

Self-balancing binary search trees that recolor and rotate to keep height logarithmic.

Access

O(log n)

Search

O(log n)

Insert

O(log n)

Delete

O(log n)

Real-World Examples:

  • Database indexes (MongoDB WiredTiger, RocksDB) that need predictable writes.
  • Linux scheduler run queues and virtual memory managers.
  • Compilers and IDEs powering symbol tables/autocomplete for large codebases.
Deep dive ready

Graphs

A non-linear data structure consisting of nodes (vertices) and edges that connect them. Can represent complex relationships.

Access

O(V+E)

Search

O(V+E)

Insert

O(1)

Delete

O(E)

Real-World Examples:

  • Google Maps pathfinding.
  • LinkedIn or Facebook social networks.
  • The World Wide Web.
Deep dive ready

Hash Tables

A data structure that stores key-value pairs. It uses a hash function to compute an index into an array of buckets, from which the desired value can be found.

Access

N/A

Search

O(1)

Insert

O(1)

Delete

O(1)

Real-World Examples:

  • Database indexing.
  • Caching systems (like a browser cache).
  • Dictionaries or phone books.
Deep dive ready

Heaps

Complete binary trees that keep the smallest or largest value at the root and support fast priority operations.

Access

O(1) for peek

Search

O(n)

Insert

O(log n)

Delete

O(log n)

Real-World Examples:

  • Task schedulers picking the next job by deadline.
  • Dijkstra's algorithm prioritizing the closest frontier node.
  • Stream processing dashboards keeping the top K metrics live.
Deep dive ready

Searching Algorithms

Techniques that help you locate the right data point quickly—from linear scans to binary search and index-assisted lookups.

Access

Dependent on backing structure

Search

O(log n) with binary search, O(n) linear

Insert

N/A

Delete

N/A

Real-World Examples:

  • Product search that ranks millions of SKUs in milliseconds.
  • Incident response teams sweeping terabytes of logs for indicators of compromise.
  • Navigation apps finding the closest open driver or scooter.
Deep dive ready

Sorting Algorithms

Organize collections so downstream algorithms—search, aggregation, compression—run dramatically faster.

Access

N/A

Search

O(log n) after sorting

Insert

O(n log n) to re-sort

Delete

O(n log n) to re-sort

Real-World Examples:

  • Streaming analytics ordering events before computing rolling metrics.
  • Financial exchanges sequencing trades before clearing.
  • Build systems resolving dependency order before compilation.

Interview Readiness Roadmap

Every pattern, mapped in order.

Each node builds on the one above it. 45 guided interview simulations across 11 patterns here; the same patterns are drilled against hidden test suites in the AlgoMindset 75.

You are here

Arrays & Hashing

Sign in and this tracks your real position on the graph.

Interview Toolkit

Pattern Playbook for Tricky Algorithm Concepts

These story-driven blocks explain when to reach for popular techniques, how to narrate them to a recruiter, and include deep dives with code in three languages — all of it free, including the annotated deep dives.

Dynamic range tracking

Sliding Window

Two pointers stretch and shrink a window while maintaining running stats. Perfect when you must find the best contiguous subarray or substring under a constraint.

Imagine laying a picture frame over a long strip of numbers or letters and gently sliding it left and right. You only care about what sits inside the frame, so you keep tiny notes (such as the sum or which characters are present) and adjust the frame whenever the rules are broken. Because the frame never jumps backward, every element is touched a small number of times.

Prompts that ask for the “longest”, “shortest”, or “exactly k-length” stretch of a string or array almost always benefit from a window.Rules that say “at most k mismatches”, “no duplicates”, or “sum must stay under T” hint that you grow the window until it breaks the rule, then shrink it.If an interviewer stresses that the solution should be near-linear time despite tricky constraints, a sliding window prevents nested loops.

How to Spot This Pattern

  • Sketch a small window over the input and ask: “Can my answer be expressed as elements that sit next to each other?” If yes, sliding the window is promising.
  • Look for limits such as “at most k repeats”, “total must stay under budget”, or “must include every letter in the pattern”. These limits tell you when to widen or shrink the frame.
  • Notice when the interviewer expects you to stream data or handle very long strings. Sliding windows shine because they examine each character once instead of restarting from scratch.

Algorithm Example

Longest Substring Without Repeating Characters

Keep a hash set for the current window; shrink from the left whenever you see a duplicate.

"Longest substring" plus "without repeating" screams sliding window with a set or frequency map.

O(n) time · O(min(n, alphabet)) space

Algorithm Example

Minimum Window Substring

Grow the window until you cover all targets, then shrink to find the tightest range.

Need smallest substring that covers a multiset of characters.

O(n) time · O(k) space (k distinct tracked chars)

Algorithm Example

Max Consecutive Ones III / Fixed Window

Maintain counts while sliding a fixed or almost fixed window when the question says "size k".

Fixed-length or streaming questions with running average/median style output.

O(n) time · O(1) extra space

Converging or diverging cursors

Two Pointer Patterns

Run two indices over a sorted array, opposite ends of a container, or different speeds through a linked list to remove extra loops.

Visualize two fingers walking over a line of numbers: sometimes they start together and drift apart, other times they begin at distant ends and march toward the middle. Each move discards a chunk of the search space with a simple rule like “move the pointer that sits on the smaller wall”. Because both fingers only walk forward, the method is swift and easy to explain aloud.

Whenever the goal is to find two numbers that meet a requirement (sum to a target, squeeze the most volume, verify symmetry), try walking from both ends toward the answer.Problems that talk about removing duplicates or partitioning data in-place typically rely on a read pointer and a write pointer so you never allocate extra memory.Cycle-detection or midpoint questions mention different “speeds” or “laps”, which is another flavor of the same idea.

How to Spot This Pattern

  • Ask if the data can be sorted or already arrives sorted. Once ordering matters, two pointers can step through it without backtracking.
  • See whether the prompt compares values near the front and back simultaneously (palindromes, container area, pair sums). That symmetry is a big clue.
  • For linked lists, listen for phrases like “slow and fast runner” or “find the middle without knowing the length”; that is the tortoise-and-hare variant of the pattern.

Algorithm Example

Container With Most Water

Evaluate area formed by the two lines and move the smaller line inward.

Question mentions maximizing area/volume using two ends of an array.

O(n) time · O(1) space

Algorithm Example

3Sum and 4Sum

Sort, anchor one index, then walk the remaining array with low/high pointers to avoid duplicates.

Need unique combinations of numbers adding to a target with n up to 10^4.

O(n^2) time after sorting · O(1) extra space

Algorithm Example

Valid Palindrome

Compare characters from both ends while skipping punctuation.

Symmetry plus tolerance for skipping characters indicates front/back pointers.

O(n) time · O(1) space

Make the locally optimal decision

Greedy Reasoning

Pick the best move at each step to avoid backtracking. Greedy works when a problem has the matroid/exchange property or a proof that local optima extend globally.

Think about standing in a buffet line with a single plate: you always grab the tastiest item available now, trusting that this choice cannot hurt future options. Greedy algorithms formalize that instinct by proving that each immediate best move leads to the overall best plan. You keep simple state—like the furthest place you can jump to or how many meeting rooms are occupied—and update it as you march forward.

Interviewers hint at sorting or using a priority queue to repeatedly grab the “best so far”—that is a classic greedy tell.Targets that sound like resource allocation (“fewest jumps”, “maximum tasks”, “minimum number of platforms”) typically reward making the most helpful immediate move.When memory budgets are tight and re-evaluating the entire past would be too slow, a greedy one-pass update keeps the solution practical.

How to Spot This Pattern

  • Look for problems that ask for a maximum or minimum result while presenting clear, comparable options (e.g., pick intervals, choose jumps, schedule tasks).
  • Notice when dynamic programming feels like overkill because subproblems barely overlap. Greedy often replaces heavy tables with a single counter or pointer.
  • Ask yourself: “If I sort by finish time, start time, value, or ratio, would choosing items in that order ever hurt me?” If the answer is no, you have the exchange proof intuition you need.

Algorithm Example

Jump Game

Track the furthest index you can reach; if the current index is beyond it, fail.

"Return true/false" plus ability distances often imply greedy reachability.

O(n) time · O(1) space

Algorithm Example

Activity Selection / Meeting Rooms

Sort by finish time so the schedule always leaves as much room as possible for later events.

Intervals that can be sorted and compared by one dimension.

O(n log n) time due to sorting · O(1) extra space

Algorithm Example

Gas Station

Maintain running surplus; when it drops below zero shift the start because any earlier start would be worse.

Circular arrays where prefix sums reveal feasibility.

O(n) time · O(1) space

Prefix sum without storing everything

Kadane's Algorithm

Maintain a running best subarray ending at the current index and drop any prefix that hurts you. Often rephrased as dynamic programming on arrays.

Picture walking across a boardwalk with a backpack. Each plank you step on either adds weight (a negative number) or gives you energy (a positive number). If the backpack becomes too heavy, you simply drop everything and start fresh at the current plank. Kadane’s algorithm encodes that intuition: it tracks the best score ending “here” and resets whenever the past becomes a burden.

Maximum or minimum “subarray” or “substring” sums nearly always map to this running-sum reset pattern.Stock profit, delta-based scoring, or “best span” stories become easier once you treat differences as the input to Kadane.If the interviewer emphasizes that you cannot allocate large DP arrays, highlight Kadane as the constant-memory solution.

How to Spot This Pattern

  • Scan the wording for “contiguous” or “in a row”. Kadane only works when the winning answer sits in a single continuous block.
  • Check whether the input size is huge. The algorithm shines when you must finish in linear time with constant memory.
  • Translate wordy domains like “profit over days” or “temperature changes” into simple gains and losses; Kadane works on any running-sum storyline.

Algorithm Example

Maximum Subarray

Keep best ending here vs starting new from current number.

"Contiguous" plus "maximum sum" with negative numbers allowed.

O(n) time · O(1) space

Algorithm Example

Maximum Circular Subarray

Compute standard Kadane plus min-subarray to handle wrap-around.

Array is circular and you can wrap to start again.

O(n) time · O(1) space

Algorithm Example

Best Time to Buy and Sell Stock

Transform prices into day-to-day deltas; Kadane identifies most profitable segment.

Max profit with single transaction equals max subarray of daily gains.

O(n) time · O(1) space

Sort endpoints once

Sweep Line / Interval Reasoning

Turn intervals into timeline events, walk from left to right, and keep lightweight counts to answer overlap questions.

Imagine dragging a vertical laser from the left edge of a calendar to the right. Meetings only matter when the laser hits a start or an end time, so you can ignore every minute in between. By logging those event points, you can track how many rooms are occupied, when sky lines rise or fall, or whether a new interval fits without clashing.

Schedules, booking systems, road trips, or skyline outlines all revolve around start/end events, which screams sweep line.Whenever you need the “current” count of overlapping intervals, scanning sorted endpoints is simpler than juggling heaps of individual intervals.Interviewers who emphasize deterministic tie-breaking (“if a meeting ends exactly when another starts...”) expect you to reason in terms of ordered events.

How to Spot This Pattern

  • Underline any mention of “intervals”, “ranges”, or “start and end” coordinates—the sweep line was born for these stories.
  • Problems asking for “how many overlap at once” or “merge the busy slots” are solved easiest when you convert each interval to +1 (start) and -1 (end) events.
  • If sorting the endpoints once (O(n log n)) is acceptable but nested loops would be too slow, sweeping keeps the pass count predictable.

Algorithm Example

Merge Intervals

Sort by start, then greedily extend the last merged interval.

"Combine overlapping intervals" is the textbook sweep-line entry point.

O(n log n) time · O(1) extra (beyond output)

Algorithm Example

Meeting Rooms II

Sort starts and ends separately, sweep to count parallel meetings.

Asks for minimum rooms/CPUs/servers needed simultaneously.

O(n log n) time · O(n) storage for sorted endpoints

Algorithm Example

Skyline Problem

Convert buildings into start/end events and use a multiset to track the current tallest.

Heights change only at known event points.

O(n log n) time using a heap

Divide a problem into sub-decisions

Recursion & Backtracking

Break problems into repeated subproblems, let the call stack remember context, and explore search trees with pruning.

Think of solving a maze by leaving breadcrumbs at every fork: you move forward, and if you reach a dead end, you follow the breadcrumbs back to the previous choice and try a new direction. Recursion with backtracking does the same in code—it explores one decision path at a time while the call stack remembers what came before.

Generation problems (“list every parentheses string”, “return all subsets”) almost always rely on recursive branching with backtracking.When each choice depends on earlier choices (like balancing parentheses), recursion tracks that state for you with very little extra code.Interviewers bring up recursion when they want to hear about base cases, pruning branches early, and the trade-offs versus iterative loops.

How to Spot This Pattern

  • If the problem wants “all possible arrangements” or “every valid combination”, you are probably climbing a decision tree that screams recursion.
  • Small input sizes (n ≤ 15) plus exponential numbers of answers are a giveaway: brute force is allowed, but you need structure to manage it.
  • Tree and graph questions that depend on ancestor information feel natural to solve by recursing on the node and letting the stack carry context downwards.

Algorithm Example

Generate Parentheses

Decision tree: place "(" if you still can, ")" only when it keeps balance.

"Return all valid strings" with symmetrical constraints.

O(Cn) time where Cn is the nth Catalan number · O(n) recursion depth

Algorithm Example

Subsets / Combinations

Each element is either picked or skipped; recursion handles the branching cleanly.

Power set style tasks, often with sorted input for deduping.

O(2^n) time · O(n) stack space

Algorithm Example

Binary Tree Traversals

Recursion mirrors the tree structure, letting you reason in terms of left/right children.

Any question that says "for each node, compute X from its children".

O(n) time · O(height) space