Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

13 Core Algorithmic Patterns & 225 Practice Problems

  • 1. Two Pointers (16 Paradigms, 43 Problems): Opposite ends, sorted pair sums, palindrome verification, trapping rain water, 3Sum, container with most water — includes the Sliding Window and Fast & Slow Pointers paradigms (contiguous subarray invariants, longest substrings, Floyd's cycle detection, linked list middle).
  • 2. Binary Search (9 Paradigms, 14 Problems): Monotonic predicate partitioning (feasible(x)), boundary search, rotated sorted arrays, square roots, minimum ship capacity, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 11 Problems): Counting set bits, XOR cancellation, bit reversal, bitmask pairing, maximum XOR with a bitwise trie.
  • 4. Math & Geometry (8 Paradigms, 14 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (15 Paradigms, 24 Problems): Path sums, lowest common ancestor, tree diameter, validating BSTs, tree DP (House Robber III, Binary Tree Cameras).
  • 6. Tree/Graph Breadth-First Search (5 Paradigms, 12 Problems): Level-order traversals, shortest path in unweighted graphs, zig-zag traversals, rotting oranges, word ladders.
  • 7. Graphs (12 Paradigms, 22 Problems): Topological sort, cycle detection, Dijkstra's algorithm, bipartite graph validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens, Sudoku solver.
  • 9. Dynamic Programming (13 Paradigms, 28 Problems): Memoization vs tabulation, 0/1 knapsack, unbounded knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (9 Paradigms, 11 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (7 Paradigms, 17 Problems): Trie (prefix tree), Union-Find (Disjoint Set Union), LRU Cache, LFU Cache, range-sum queries with updates.
  • 12. Stack (5 Paradigms, 9 Problems): Next greater element, largest rectangle in histogram, remove k digits, decode string, min stack.
  • 13. Intervals & Greedy (2 Paradigms, 6 Problems): Merge intervals, interval scheduling, meeting rooms by sweep line, jump game.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Read the pattern's mental model, loop invariant and Big-O proof, compare the pattern's template with the problem's solution side by side, and use the step-by-step debugger. The solution can also be shown in C#, Java, TypeScript, C++, Go or Rust for almost every problem.
  2. Stage 2 (Active Recall): Rebuild the solution from memory in a code editor, with an invariant checklist and optional progressive hints, and check it against a judged test suite.
  3. Stage 3 (AI Interview Coach, coming soon): A mock-interview stage still in development; for now, students go straight from Stage 2 to Stage 4.
  4. Stage 4 (Solve on Your Own): Solve a new problem on your own against a 15-minute timer; your code is graded against a test suite. Python and TypeScript run in your browser and C# runs on our server (design problems grade in Python and TypeScript).

Equipped with a spaced-repetition review hub on a fixed 7-step schedule (1 day up to 90 days), a two-pane Studio workspace, and study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Coins: New accounts get 40 free coins once, the daily claim adds +20 coins once a day, and inviting a friend earns you +25 coins when they complete their first practice step. These are the only ways to earn coins.
  • AI Coach: Each AI coach question costs 1-5 coins, priced by the server according to its size.
  • BYOK (Bring Your Own Key): AI coaching is free with your own Google Gemini, OpenAI or OpenRouter API key (BYOK).
  • Extras: Coins also unlock extras for 24 hours: a Recall hint level (1 coin), a Solve solution reveal (2), a LeetCode problem card's solutions (1) and a pattern's extra canonical problems (1).
  • Payments & Refunds: Nothing on the site is sold for money: coins can only be earned, never bought. There are no subscriptions or charges, so there is nothing to refund.
  • Platform Operator: Hi👋WebEnterprise. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

Arena
238Items
Theory Context•Dynamic Programming
MediumLC 122

Best Time to Buy and Sell Stock II (LeetCode 122)

Target Frequency:AmazonBloombergMicrosoft

You get an integer array prices: on day i, one share of a stock costs prices[i]. On each day you may buy a share, sell the share you own, or both, but you can never own more than one share at a time. Selling and then buying again on the same day is allowed, and there is no limit on the number of trades.

Return the largest total profit you can make. If no trade helps, the answer is 0.

Worked Examples

Example 1
Input:prices = [7,1,5,3,6,4]
Output:7
701152336445buysellbuysell
Explanation: Buy on day 1 at 1 and sell on day 2 at 5 for +4, then buy on day 3 at 3 and sell on day 4 at 6 for +3. Total 7.
Example 2
Input:prices = [1,2,3,4,5]
Output:4
1021324354buysell
Explanation: Buy on day 0 at 1 and sell on day 4 at 5 for +4. Selling and buying back every day adds up to the same 4.
Example 3
Input:prices = [7,6,4,3,1]
Output:0
7061423314
Explanation: The price only falls, so every trade loses money. Never buying keeps the profit at 0.

⚖️Formal Constraints & Bounds

  • 1 <= prices.length <= 3 * 104

  • 0 <= prices[i] <= 104

Deep-Dive & Conceptual Insights

Core Insight

Only two facts matter at the end of a day: whether you own a share, and the best profit for each case. Each day's two values come from yesterday's two, so one pass finds the best plan.

Real-World Scenario & Production Applications

Any system that moves between a few modes step by step, and pays or earns on each switch: a battery that charges or discharges against hourly power prices, a machine that runs or idles, a position that is open or closed. Keeping the best value for each mode finds the best plan in one pass.

Step-by-Step Execution Trace Table

Day iphold = max(hold, cash - p)cash = max(cash, hold + p)What the states mean
07-7 (start)0 (start)Bought on day 0 / own nothing
11max(-7, 0 - 1) = -1max(0, -7 + 1) = 0Buying at 1 beats keeping the share bought at 7
25max(-1, 0 - 5) = -1max(0, -1 + 5) = 4Selling at 5 locks in +4
33max(-1, 4 - 3) = 1max(4, -1 + 3) = 4Buy again at 3 with the 4 in hand
46max(1, 4 - 6) = 1max(4, 1 + 6) = 7Selling at 6 adds +3
54max(1, 7 - 4) = 3max(7, 1 + 4) = 7Nothing beats 7; return cash = 7
Code Shape
Archetype Code Shape
Python
1At the end of each day you either own one share (`hold`) or none (`cash`): keep the best profit for each state.
2`hold = max(hold, cash - p)` keeps the share or buys today; `cash = max(cash, hold + p)` stays out or sells today. Both read yesterday's values.
3Start `hold = -prices[0]` and `cash = 0`, update both once for every later day with one tuple assignment, then `return cash`.
4The trap: `hold` starts at `-prices[0]`, not `0`, or `cash` sells a share you never paid for.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A trading plan looks like a huge search: on every day you could buy, sell or wait, so there are exponentially many plans. State Machine DP collapses it. At the end of any day you are in exactly one of two states: you own a share (hold) or you don't (cash). Tomorrow's best profit in each state depends only on today's two numbers, never on how you got there. So you carry two numbers through the array and update them once per day.

🏟️ The Analogy: A Light Switch With a Price Tag

Picture a switch that is either on (you own a share) or off (you don't). Each day the switch can stay where it is at no cost, or flip: flipping on costs today's price, flipping off pays today's price. You don't need to remember the whole history of flips; you only need the best balance you could have right now with the switch on, and the best balance with it off.

🔑 Why It Works

The tuple assignment evaluates both right-hand sides with yesterday's hold and cash before either changes. Every legal plan is a path of switch flips, and each max keeps only the best way to arrive at a state, so the final cash is the best plan of all.

  • Starting hold at 0: hold = 0 means owning a share you never paid for, so on day 1 cash = max(0, 0 + p) sells it for a free profit. On [7,1,5,3,6,4] that returns 8 instead of 7. Start with hold = -prices[0].

  • Reading a value that already changed today: the tuple assignment hold, cash = max(hold, cash - p), max(cash, hold + p) computes both right-hand sides from yesterday's values. In this problem two separate lines happen to give the same answer, but with a cooldown they don't, so build the habit here.

  • Returning max(hold, cash): holding a share at the end means money was spent on something never sold; cash is always at least as large, so return cash.

  • Treating it as "one best trade": that is Best Time to Buy and Sell Stock (LC 121). Here trades are unlimited, so every profitable rise can be taken, and the state machine takes them all automatically.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Buy and sell as many times as you like" and "own at most one share at a time": at the end of every day you are in one of two modes (own a share or not), and each day's choices depend only on that mode. A few modes with day-by-day moves between them is the signal for State Machine DP.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

After each day, hold is the best profit so far while owning one share and cash the best profit so far while owning none: hold = max(hold, cash - p) (keep or buy) and cash = max(cash, hold + p) (keep or sell), both reading yesterday's values.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

This problem's traps are in Common Pitfalls above.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd solve this with State Machine DP. At the end of any day I'm in one of two states: I own a share, or I don't. I keep the best profit for each, hold and cash. Each new price allows two moves: hold becomes the better of keeping my share or buying today out of cash, and cash becomes the better of staying out or selling today out of hold. I compute both from yesterday's values in one tuple assignment. It's correct because every legal plan of trades is a path through these two states, and each update keeps the best way to reach each state. The trap is the start: hold must be minus the first price, not zero, or I'd sell a share I never paid for. At the end I return cash, since ending with a share is never better. One pass, so O(N) time and O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the code: after setting hold and cash, the loop for i in range(1, len(prices)) runs once for each of the other N - 1 days, and its body reads one price and does one tuple assignment with two max calls, a constant amount of work. Total: O(N).

SPACE COMPLEXITY

O(1)

The code keeps only hold, cash, i and p, whatever the input size, and returns one integer: O(1) extra space.

Formal Recurrence Relation

T(N) = O(1) + (N - 1) · O(1) = O(N)

Derivation Progression

Start states

O(1)

hold = -prices[0] and cash = 0 are two assignments.

Daily loop

(N - 1) iterations

for i in range(1, len(prices)) visits every day after day 0 exactly once.

Per-day update

O(1) per iteration

One tuple assignment with two max calls, whatever N is.

Total

O(N)

Constant work per day over N days.

Variable Definitions

NNN

Number of days, len(prices)

ppp

Today's price, prices[i]

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative, no recursion

🔵 Auxiliary Heap

O(1): hold, cash, i, p

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): every day is visited even when prices only fall

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "trade as many times as you like", "never own more than one share". Every day ends in one of two modes, owning a share or not, and the next day's options depend only on the mode: State Machine DP with states hold and cash.

CONSTRAINTS & BOUNDS

N≤3×104N \le 3 \times 10^4N≤3×104 days, prices ≤104\le 10^4≤104. The profit is at most the sum of all rises, below 3×1083 \times 10^83×108, so it fits a 32-bit integer. Budget: O(N)O(N)O(N) time, O(1)O(1)O(1) space; the loop also works on a live price stream, since it keeps no history.

FAANG PRODUCTION TRAPS & EDGE CASES

In a streaming service, the state is only two numbers, but it must be updated once per price in order: replaying or reordering ticks changes the answer, so process each tick exactly once.

Theory Context•Dynamic Programming
MediumLC 122

Best Time to Buy and Sell Stock II (LeetCode 122)

Target Frequency:AmazonBloombergMicrosoft

You get an integer array prices: on day i, one share of a stock costs prices[i]. On each day you may buy a share, sell the share you own, or both, but you can never own more than one share at a time. Selling and then buying again on the same day is allowed, and there is no limit on the number of trades.

Return the largest total profit you can make. If no trade helps, the answer is 0.

Worked Examples

Example 1
Input:prices = [7,1,5,3,6,4]
Output:7
701152336445buysellbuysell
Explanation: Buy on day 1 at 1 and sell on day 2 at 5 for +4, then buy on day 3 at 3 and sell on day 4 at 6 for +3. Total 7.
Example 2
Input:prices = [1,2,3,4,5]
Output:4
1021324354buysell
Explanation: Buy on day 0 at 1 and sell on day 4 at 5 for +4. Selling and buying back every day adds up to the same 4.
Example 3
Input:prices = [7,6,4,3,1]
Output:0
7061423314
Explanation: The price only falls, so every trade loses money. Never buying keeps the profit at 0.

⚖️Formal Constraints & Bounds

  • 1 <= prices.length <= 3 * 104

  • 0 <= prices[i] <= 104

Deep-Dive & Conceptual Insights

Core Insight

Only two facts matter at the end of a day: whether you own a share, and the best profit for each case. Each day's two values come from yesterday's two, so one pass finds the best plan.

Real-World Scenario & Production Applications

Any system that moves between a few modes step by step, and pays or earns on each switch: a battery that charges or discharges against hourly power prices, a machine that runs or idles, a position that is open or closed. Keeping the best value for each mode finds the best plan in one pass.

Step-by-Step Execution Trace Table

Day iphold = max(hold, cash - p)cash = max(cash, hold + p)What the states mean
07-7 (start)0 (start)Bought on day 0 / own nothing
11max(-7, 0 - 1) = -1max(0, -7 + 1) = 0Buying at 1 beats keeping the share bought at 7
25max(-1, 0 - 5) = -1max(0, -1 + 5) = 4Selling at 5 locks in +4
33max(-1, 4 - 3) = 1max(4, -1 + 3) = 4Buy again at 3 with the 4 in hand
46max(1, 4 - 6) = 1max(4, 1 + 6) = 7Selling at 6 adds +3
54max(1, 7 - 4) = 3max(7, 1 + 4) = 7Nothing beats 7; return cash = 7
Code Shape
Archetype Code Shape
Python
1At the end of each day you either own one share (`hold`) or none (`cash`): keep the best profit for each state.
2`hold = max(hold, cash - p)` keeps the share or buys today; `cash = max(cash, hold + p)` stays out or sells today. Both read yesterday's values.
3Start `hold = -prices[0]` and `cash = 0`, update both once for every later day with one tuple assignment, then `return cash`.
4The trap: `hold` starts at `-prices[0]`, not `0`, or `cash` sells a share you never paid for.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A trading plan looks like a huge search: on every day you could buy, sell or wait, so there are exponentially many plans. State Machine DP collapses it. At the end of any day you are in exactly one of two states: you own a share (hold) or you don't (cash). Tomorrow's best profit in each state depends only on today's two numbers, never on how you got there. So you carry two numbers through the array and update them once per day.

🏟️ The Analogy: A Light Switch With a Price Tag

Picture a switch that is either on (you own a share) or off (you don't). Each day the switch can stay where it is at no cost, or flip: flipping on costs today's price, flipping off pays today's price. You don't need to remember the whole history of flips; you only need the best balance you could have right now with the switch on, and the best balance with it off.

🔑 Why It Works

The tuple assignment evaluates both right-hand sides with yesterday's hold and cash before either changes. Every legal plan is a path of switch flips, and each max keeps only the best way to arrive at a state, so the final cash is the best plan of all.

  • Starting hold at 0: hold = 0 means owning a share you never paid for, so on day 1 cash = max(0, 0 + p) sells it for a free profit. On [7,1,5,3,6,4] that returns 8 instead of 7. Start with hold = -prices[0].

  • Reading a value that already changed today: the tuple assignment hold, cash = max(hold, cash - p), max(cash, hold + p) computes both right-hand sides from yesterday's values. In this problem two separate lines happen to give the same answer, but with a cooldown they don't, so build the habit here.

  • Returning max(hold, cash): holding a share at the end means money was spent on something never sold; cash is always at least as large, so return cash.

  • Treating it as "one best trade": that is Best Time to Buy and Sell Stock (LC 121). Here trades are unlimited, so every profitable rise can be taken, and the state machine takes them all automatically.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"Buy and sell as many times as you like" and "own at most one share at a time": at the end of every day you are in one of two modes (own a share or not), and each day's choices depend only on that mode. A few modes with day-by-day moves between them is the signal for State Machine DP.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

After each day, hold is the best profit so far while owning one share and cash the best profit so far while owning none: hold = max(hold, cash - p) (keep or buy) and cash = max(cash, hold + p) (keep or sell), both reading yesterday's values.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

This problem's traps are in Common Pitfalls above.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd solve this with State Machine DP. At the end of any day I'm in one of two states: I own a share, or I don't. I keep the best profit for each, hold and cash. Each new price allows two moves: hold becomes the better of keeping my share or buying today out of cash, and cash becomes the better of staying out or selling today out of hold. I compute both from yesterday's values in one tuple assignment. It's correct because every legal plan of trades is a path through these two states, and each update keeps the best way to reach each state. The trap is the start: hold must be minus the first price, not zero, or I'd sell a share I never paid for. At the end I return cash, since ending with a share is never better. One pass, so O(N) time and O(1) space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the code: after setting hold and cash, the loop for i in range(1, len(prices)) runs once for each of the other N - 1 days, and its body reads one price and does one tuple assignment with two max calls, a constant amount of work. Total: O(N).

SPACE COMPLEXITY

O(1)

The code keeps only hold, cash, i and p, whatever the input size, and returns one integer: O(1) extra space.

Formal Recurrence Relation

T(N) = O(1) + (N - 1) · O(1) = O(N)

Derivation Progression

Start states

O(1)

hold = -prices[0] and cash = 0 are two assignments.

Daily loop

(N - 1) iterations

for i in range(1, len(prices)) visits every day after day 0 exactly once.

Per-day update

O(1) per iteration

One tuple assignment with two max calls, whatever N is.

Total

O(N)

Constant work per day over N days.

Variable Definitions

NNN

Number of days, len(prices)

ppp

Today's price, prices[i]

Memory Architecture & Bounds

🟣 Call Stack

O(1) Iterative, no recursion

🔵 Auxiliary Heap

O(1): hold, cash, i, p

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): every day is visited even when prices only fall

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N)

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology

State-Space & Subproblem DAG(Directed Acyclic Graph) Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "trade as many times as you like", "never own more than one share". Every day ends in one of two modes, owning a share or not, and the next day's options depend only on the mode: State Machine DP with states hold and cash.

CONSTRAINTS & BOUNDS

N≤3×104N \le 3 \times 10^4N≤3×104 days, prices ≤104\le 10^4≤104. The profit is at most the sum of all rises, below 3×1083 \times 10^83×108, so it fits a 32-bit integer. Budget: O(N)O(N)O(N) time, O(1)O(1)O(1) space; the loop also works on a live price stream, since it keeps no history.

FAANG PRODUCTION TRAPS & EDGE CASES

In a streaming service, the state is only two numbers, but it must be updated once per price in order: replaying or reordering ticks changes the answer, so process each tick exactly once.

© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•