Coding interview problems, explained by pattern

Coding interview problems are short algorithm tasks you solve and explain in roughly 30 to 45 minutes, and most of them are a familiar pattern wearing a new costume. This section walks through common problems one at a time: the idea in plain words, a brute force, the optimal approach with the pattern named, tested code in Python plus JavaScript or C++, and the follow-ups interviewers tend to ask.

By Published 48 min read

What this section is for

Technical screens at many software companies still include at least one live coding round. The interviewer shares a small problem, watches you reason about it, and asks you to write code that runs. The problems themselves are rarely secret. A short list of classics appears again and again because each one isolates a single idea: can you trade memory for speed with a hash map, can you see that a stack matches nested structure, can you keep a window over a string without rescanning it.

These pages treat each classic as a lesson in one pattern. The goal is not to memorize eight answers. It is to recognize the same shape when it shows up with different nouns, such as transactions instead of numbers or meeting rooms instead of intervals. Many of these problems are commonly practiced on LeetCode and similar judge sites; the statements and examples here are written fresh, so read the problem the way you would hear it from a person.

How to practice: pattern first, problem second

  1. Name the pattern before you write codeRead the prompt and ask which signal it gives. Pairs that must add up point to hashing. Nested brackets point to a stack. Contiguous runs point to a sliding window. Connected cells point to graph search.
  2. Say the brute force and its costDescribe the slow answer in one sentence and give its time and space. It proves you understand the task, and the repeated work inside it is usually where the faster idea comes from.
  3. Remove the repeated workAsk what the brute force recomputes. A lookup table, a sort, a pointer that never moves backward or a queue usually removes it. Name the new complexity before you start typing.
  4. Write it, then trace it by handCode the optimal version in your main language, then walk a tiny input through it line by line. Check the empty input, a single element and a case with duplicates.
  5. Rehearse the follow-upsEach walkthrough lists the questions interviewers add once the first version works: a sorted input, a stream, limited memory, many queries. Answering them is often what separates a pass from a strong pass.
  6. Space the repetitionsReturn to a problem a few days later and solve it cold. If you can rebuild it from the pattern name alone, it has stuck. If you only remember the code, it has not.

The problems, grouped by pattern

Which clue in the prompt points to which pattern, and where it is practiced here
PatternClue in the promptWalkthrough
Hash map lookupFind two items that relate to each other, fastTwo Sum
Counting plus bucket or heapThe most common or the k largest of somethingTop K Frequent Elements
StackThings that open and must close in reverse orderValid Parentheses
Sort, then sweepRanges, bookings or time spans that may overlapMerge Intervals
Sliding windowThe longest or shortest contiguous run with a ruleLongest Substring Without Repeating Characters
Design with two structuresConstant-time get and put with an eviction ruleLRU Cache
Graph search on a gridCount or measure connected regionsNumber of Islands
Breadth-first search on a treeAnything reported row by row or by distanceBinary Tree Level Order Traversal
Erase the lowest set bitCount the 1s in a binary valueNumber of 1 Bits
Reuse a smaller answer by shiftingA bit count for every number up to nCounting Bits
Shift and mask at a fixed widthMirror a value's 32-bit patternReverse Bits
Compare with the complete set (sum or XOR)One value absent from a known rangeMissing Number
XOR plus shifted carryArithmetic without the arithmetic operatorsSum of Two Integers
Overflow check before each stepRebuild a number digit by digit inside 32 bitsReverse Integer
Length-prefix framingPack many strings into one and split them back safelyEncode and Decode Strings
Sets keyed by row, column and boxSpot repeats across overlapping groups of a gridValid Sudoku
Hash set membershipHas this value, or this node, been seen before?Contains Duplicate
Sort, then two pointersSeveral values that must add up to a target, without repeats3Sum
Two pointers from both endsChoose a left and a right boundary to maximize a scoreContainer With Most Water
Running minimumThe best later value to pair with an earlier oneBest Time to Buy and Sell Stock
Kadane's algorithmThe best contiguous run by sumMaximum Subarray
Prefix and suffix productsEverything except the current position, without divisionProduct of Array Except Self
One-dimensional dynamic programmingCount the ways to reach a step from smaller stepsClimbing Stairs
Linked list pointer rewiringTurn a chain of nodes around in placeReverse Linked List
Dummy head and mergeCombine already sorted sequences into oneMerge Two Sorted Lists
Fast and slow pointersA chain that might loop back on itselfLinked List Cycle
Sliding window with a letter countThe longest stretch you can make uniform with a few editsLongest Repeating Character Replacement
Fixed-size counting windowDoes any block of the text use exactly these letters?Permutation in String
Stack with a running extra valueUndo-style storage that must also report its minimum instantlyMin Stack
Stack as an evaluatorOperators that act on the last two values producedEvaluate Reverse Polish Notation
Backtracking with countersList every string or arrangement that obeys a ruleGenerate Parentheses
Monotonic stackFor each item, the next one that is largerDaily Temperatures
Sort, then sweep arrival timesObjects that cannot pass each other and merge into groupsCar Fleet
Monotonic stack with widthsThe biggest area under a skyline of barsLargest Rectangle in Histogram
Post-order with a side resultThe longest path anywhere in a treeDiameter of Binary Tree
Post-order with a sentinelA rule that must hold at every node of a treeBalanced Binary Tree
Two trees in lockstepAre these two structures identical?Same Tree
Search plus comparison, or serializationDoes one tree appear whole inside another?Subtree of Another Tree
Recursion that reports what it foundThe deepest node shared by two othersLowest Common Ancestor
Breadth-first search, last of each levelWhat can be seen from one side of a treeBinary Tree Right Side View
Depth-first search carrying a value downCompare each node with everything above itCount Good Nodes in Binary Tree
Depth-first search with boundsOrdering rules that reach past a node's own childrenValidate Binary Search Tree
Dynamic programming on two prefixesCan two sequences be merged, in order, into a third?Interleaving String
Greedy farthest reachCan you get from the first square to the last?Jump Game
Breadth-first search in bandsThe fewest moves when each square limits how far you goJump Game II
Greedy with a resetWhere to start on a loop so a running total never goes negativeGas Station
Greedy boundary extensionCut a sequence into the most pieces under a sharing rulePartition Labels
Linear sweep over sorted rangesAdd one booking to a calendar that is already cleanInsert Interval
Greedy by earliest endDrop the fewest bookings so nothing clashesNon-overlapping Intervals
Sort, then check neighborsIs there any clash at all in a schedule?Meeting Rooms
Bit operations and masksPairs that cancel, powers of two, subsets of a small setBit manipulation tricks
Binary search on a conditionAny local high point, in logarithmic timeFind Peak Element
Depth-first search with an explicit stackVisit a tree left, node, right without recursionBinary Tree Inorder Traversal
Two subtrees in mirrored lockstepDoes the tree read the same flipped left to right?Symmetric Tree
Depth-first search carrying a remainderDoes some root-to-leaf path hit a target?Path Sum
Backtracking on a treeList every root-to-leaf path that hits a targetPath Sum II
Breadth-first search with alternating rowsRead a tree level by level, snaking back and forthBinary Tree Zigzag Level Order Traversal
Pointer rewiring in preorderTurn a tree into a chain without extra memoryFlatten Binary Tree to Linked List
Counting tableTwo inputs that must hold the same items in any orderValid Anagram
Canonical key in a hash mapSort many items into buckets of equivalentsGroup Anagrams
Hash set with run startsThe longest unbroken run of values, input unsortedLongest Consecutive Sequence
Two pointers from both endsCompare or combine the outside items, then move inwardValid Palindrome
Converging pointers on sorted dataA pair with a target sum, input already in orderTwo Sum on a sorted array
Running maximum from each sideHow much fills the gaps between taller itemsTrapping Rain Water
Monotonic dequeThe largest value in every fixed-size windowSliding Window Maximum
Variable window with a count tableThe shortest stretch that covers a required setMinimum Window Substring
Binary searchFind a value or a boundary in sorted dataBinary Search
Binary search on a reshaped inputA grid whose rows continue one another in orderSearch a 2D Matrix
Binary search on the answerThe smallest value that makes a yes/no check passKoko Eating Bananas
Binary search with a twistSorted data that was cut and swappedFind Minimum in Rotated Sorted Array
Binary search with a sorted-half checkLook up a value in rotated sorted dataSearch in Rotated Sorted Array
Hash map of sorted historiesValues that change over time, read at a past momentTime Based Key-Value Store
Binary search on a partitionA middle value across two sorted inputsMedian of Two Sorted Arrays
Fast and slow pointers, reversalRearrange a linked list from both endsReorder List
Sliding window (pattern guide)Any contiguous run with a rule that only gets harder as it growsSliding window pattern
Grid DP, countingCount routes that only move right or downUnique Paths II
DP folded from the bottom rowCheapest route down a triangle of numbersTriangle
Grid DP, min of three neighborsThe largest solid square in a 0/1 gridMaximal Square
Stack of indexes with a barrierThe longest balanced run of bracketsLongest Valid Parentheses
Two-index DP on text and patternFull match with a star that repeats one characterRegular Expression Matching
Prefix DP or last-star greedyFull match with a star that matches any runWildcard Matching
Interval DP on the last choiceOrder of removals where neighbors change the scoreBurst Balloons
Variable window on positive valuesThe shortest stretch whose total reaches a targetMinimum Size Subarray Sum
Total minus a running prefixA position where both sides add up the sameFind Pivot Index
Voting with two candidatesEvery value that appears more than a third of the timeMajority Element II
Counting buckets capped at nThe largest h with at least h items scoring h or moreH-Index
One pass from each sideNeighbors with higher scores must receive moreCandy
Two maps for a one-to-one matchLetters of a pattern standing for words of a sentenceWord Pattern
First-seen or last-seen positionsA consistent character substitution between two stringsIsomorphic Strings
Count a supply, then spend itBuild one string from the letters of anotherRansom Note
Which clue in the prompt points to which pattern, and where it is practiced here. Scroll sideways on a small screen.

Pattern guides

Hashing and counting

Stacks and ordering

Windows over sequences

Designing a data structure

Graph and tree traversal

Bit manipulation and integer limits

Careful bookkeeping

Two pointers

Running values and dynamic programming

Linked lists

More sliding windows

More stacks

More binary trees

Greedy choices and dynamic programming

More intervals

Tree traversals and paths

Bits and binary search

Prefix sums and two-pass scans

Binary search

Dynamic programming

If you are short on time, a sensible order is Two Sum, Valid Parentheses, Merge Intervals, Longest Substring, Top K Frequent Elements, Binary Tree Level Order Traversal, Number of Islands and LRU Cache last, since the cache combines two structures and invites the longest follow-up discussion.

Every problem, A to Z

The full list of walkthroughs in alphabetical order, with the key idea for each in a few words.

0-9 and A to C

D to G

H to L

M to P

Q to S

T to Z

What a typical coding round rewards

Signals interviewers often score in a live coding round
SignalWhat you can do to show it
Clarifying the taskAsk about input size, empty input, duplicates and what to return when nothing matches before you plan anything.
Problem solvingOffer a brute force, explain why it is slow, and move to a better idea with a stated complexity.
Working codeWrite code that runs on the first trace, with clear names and no unused branches.
TestingPick your own small cases, including at least one edge case, and walk them through the code.
CommunicationNarrate decisions as you make them and check in when you change direction.
Signals interviewers often score in a live coding round. Scroll sideways on a small screen.

Exact rubrics differ between companies, so treat this as a common shape rather than a rule. The software engineer interview questions guide covers the full loop around the coding round, and the system design hub covers the architecture round that usually follows for mid-level and senior candidates. For every role and question type, start at the interview questions hub. If you want a schedule, the four-week interview prep plan shows how to fit pattern practice around everything else.

Practicing with Natively

Natively is a desktop assistant for Mac and Windows. In practice sessions it can read one of these problems from a screenshot of your screen and suggest which pattern fits and how you might approach it, and it transcribes a mock round so you can reread where you rushed past the brute force or forgot an edge case. Sessions are saved with their transcript and notes. The AI assistant for coding interviews page shows the coding features in more detail.

Questions people ask

Which coding problems should I practice first?

Start with problems that each teach one pattern: Two Sum for hash maps, Valid Parentheses for stacks, Merge Intervals for sorting, then a sliding window, a graph search and a design problem such as an LRU cache.

Is it better to practice many problems or a few patterns?

Patterns. Interviewers change the story around a problem, so recognizing hashing, stacks, windows or breadth-first search transfers further than remembering any single answer.

How long should a coding interview problem take?

Many live rounds give about 30 to 45 minutes for one or two problems, including questions, a brute force, the optimal code and testing. Practice with a timer so the pace feels normal.

Which language should I use in a coding interview?

The one you write fastest without looking things up. Python is popular because it is short, but Java, JavaScript and C++ are all widely accepted. Ask the recruiter if the company has a preference.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP