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 978

Longest Turbulent Subarray (LeetCode 978)

Target Frequency:AmazonGoogleMicrosoft

You get an integer array arr. A subarray is a run of numbers that sit next to each other. A subarray is turbulent when its steps alternate: every step goes up or down, and each step goes the other way from the step before it.

Return the length of the longest turbulent subarray. A single number is a turbulent subarray of length 1.

Worked Examples

Example 1
Input:arr = [9,4,2,10,7,8,8,1,9]
Output:5
Explanation: The subarray [4, 2, 10, 7, 8] goes down, up, down, up. The equal pair 8, 8 ends it, and [8, 1, 9] has length 3.
Example 2
Input:arr = [4,8,12,16]
Output:2
Explanation: Every step goes up, so no subarray has two steps that alternate. The longest has one step, which is 2 numbers.
Example 3
Input:arr = [100]
Output:1
Explanation: A single number is a turbulent subarray of length 1.

⚖️Formal Constraints & Bounds

  • 1 <= arr.length <= 4 * 104

  • 0 <= arr[i] <= 109

Deep-Dive & Conceptual Insights

Core Insight

A run is turbulent only if each step goes the other way from the step before, so keep two lengths per position, one for runs whose last step went up and one for runs whose last step went down: a step up extends the run that ended with a step down, and an equal step restarts both.

Real-World Scenario & Production Applications

A price that keeps swinging, such as a sensor reading that rises, falls, rises again: the longest stretch of strict swings is the longest turbulent subarray, and one flat reading or one second rise in a row breaks it.

Step-by-Step Execution Trace Table

Trace of Example 1: arr = [9, 4, 2, 10, 7, 8, 8, 1, 9]. up = down = best = 1.

iStepupdownbest
19 to 4, down122
24 to 2, down122
32 to 10, up313
410 to 7, down144
57 to 8, up515
68 to 8, equal115
78 to 1, down125
81 to 9, up315

At i = 2 the second step down cannot extend the run, so down restarts from up + 1 = 2. At i = 6 the equal step restarts both lengths.

Code Shape
Archetype Code Shape
Python
1up = down = best = 1
2for i in range(1, len(arr)):
3 step up: up, down = down + 1, 1; step down: up, down = 1, up + 1; equal: up = down = 1
4 best = max(best, up, down)
5return best

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A subarray is turbulent when its steps alternate: up, down, up, down, or the other way around. Kadane's Algorithm keeps the best run ending here. For this problem the run needs one more piece of information: the direction of its last step, because the next step must go the other way. So this variant keeps two lengths per position, up and down.

➗ What Is Added To Kadane

Kadane's Algorithm chooses between extending the run and starting fresh. This variant extends the run only when the new step flips the direction, and starts fresh at length 2 or 1 otherwise. The state is split by the direction of the last step.

🔑 The Key Idea in the Code

A step up extends down, not up: up, down = down + 1, 1. Extending the wrong length would count two steps in the same direction as turbulent.

  • Extending the same direction: up, down = up + 1, 1 for a step up counts two steps up in a row as turbulent. A step up extends the run whose last step went down.

  • Treating an equal step as a step down: arr[i] == arr[i - 1] is neither up nor down, so both runs restart at 1.

  • Tracking only one of the two lengths: the longest run may end with a step up or with a step down, so best takes the larger of both.

  • Forgetting that a single number counts: the smallest answer is 1, so up, down and best start at 1, not 0.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"The longest subarray whose steps alternate": a best value over contiguous runs, like Kadane's Algorithm, but a run can only grow when the new step goes the opposite way from its last step. That means the state must remember the direction of the last step.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

up is the length of the longest turbulent subarray ending at arr[i] whose last step went up, and down is the same for a last step down. A step up gives up = down + 1, down = 1. A step down gives down = up + 1, up = 1. An equal step gives both 1.

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 Kadane's Algorithm and the direction of the last step as extra state. A turbulent run can only grow when the next step goes the other way, so I keep up and down, the longest turbulent run ending at the current number whose last step went up or down. A step up gives up equals down plus one and resets down to one. A step down is the mirror. An equal step is neither, so both go back to one. I keep the largest of up and down in best. That is one pass, order N time and order 1 space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the loop. for i in range(1, len(arr)) visits each neighbouring pair once. Each visit does one comparison, one assignment of up and down, and one max, which is constant work. That is N - 1 steps, so time is O(N).

SPACE COMPLEXITY

O(1)

The code keeps three variables, up, down and best, whatever the length of arr is. There is no table and no recursion, so space is O(1).

Formal Recurrence Relation

T(N)=N−1=O(N)T(N) = N - 1 = O(N)T(N)=N−1=O(N)

Derivation Progression

Passes

N−1 pairsN - 1 \text{ pairs}N−1 pairs

for i in range(1, len(arr)) visits each neighbouring pair once.

Work per pair

1 = O(1)

One comparison, one assignment of up and down, and one max.

Total

N - 1 = O(N)

Pairs times a constant amount of work.

Variable Definitions

NNN

Length of arr

upupup

Longest turbulent subarray ending here whose last step went up

downdowndown

Longest turbulent subarray ending here whose last step went down

Memory Architecture & Bounds

🟣 Call Stack

O(1): a loop only, no recursion

🔵 Auxiliary Heap

O(1): the variables up, down and best

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): the loop always visits every pair.

Average Case

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

Worst Case

O(N)O(N)O(N): the same count.

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: "each step goes the other way from the step before". A best length over contiguous runs is Kadane's Algorithm, and the alternating rule means the state must remember the direction of the last step.

CONSTRAINTS & BOUNDS

N≤4×104N \le 4 \times 10^4N≤4×104 and values up to 10910^9109. A loop over all start positions with an inner scan is 1.6×1091.6 \times 10^91.6×109 steps in the worst case. One pass is O(N)O(N)O(N). Only comparisons are used, so large values need no special handling.

FAANG PRODUCTION TRAPS & EDGE CASES

Equal neighbours are neither up nor down, so they must reset both lengths. Comparing arr[i] with arr[i - 2] instead of using the direction of the last step makes the code harder to check and misses the case of an equal pair.

Theory Context•Dynamic Programming
MediumLC 978

Longest Turbulent Subarray (LeetCode 978)

Target Frequency:AmazonGoogleMicrosoft

You get an integer array arr. A subarray is a run of numbers that sit next to each other. A subarray is turbulent when its steps alternate: every step goes up or down, and each step goes the other way from the step before it.

Return the length of the longest turbulent subarray. A single number is a turbulent subarray of length 1.

Worked Examples

Example 1
Input:arr = [9,4,2,10,7,8,8,1,9]
Output:5
Explanation: The subarray [4, 2, 10, 7, 8] goes down, up, down, up. The equal pair 8, 8 ends it, and [8, 1, 9] has length 3.
Example 2
Input:arr = [4,8,12,16]
Output:2
Explanation: Every step goes up, so no subarray has two steps that alternate. The longest has one step, which is 2 numbers.
Example 3
Input:arr = [100]
Output:1
Explanation: A single number is a turbulent subarray of length 1.

⚖️Formal Constraints & Bounds

  • 1 <= arr.length <= 4 * 104

  • 0 <= arr[i] <= 109

Deep-Dive & Conceptual Insights

Core Insight

A run is turbulent only if each step goes the other way from the step before, so keep two lengths per position, one for runs whose last step went up and one for runs whose last step went down: a step up extends the run that ended with a step down, and an equal step restarts both.

Real-World Scenario & Production Applications

A price that keeps swinging, such as a sensor reading that rises, falls, rises again: the longest stretch of strict swings is the longest turbulent subarray, and one flat reading or one second rise in a row breaks it.

Step-by-Step Execution Trace Table

Trace of Example 1: arr = [9, 4, 2, 10, 7, 8, 8, 1, 9]. up = down = best = 1.

iStepupdownbest
19 to 4, down122
24 to 2, down122
32 to 10, up313
410 to 7, down144
57 to 8, up515
68 to 8, equal115
78 to 1, down125
81 to 9, up315

At i = 2 the second step down cannot extend the run, so down restarts from up + 1 = 2. At i = 6 the equal step restarts both lengths.

Code Shape
Archetype Code Shape
Python
1up = down = best = 1
2for i in range(1, len(arr)):
3 step up: up, down = down + 1, 1; step down: up, down = 1, up + 1; equal: up = down = 1
4 best = max(best, up, down)
5return best

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

A subarray is turbulent when its steps alternate: up, down, up, down, or the other way around. Kadane's Algorithm keeps the best run ending here. For this problem the run needs one more piece of information: the direction of its last step, because the next step must go the other way. So this variant keeps two lengths per position, up and down.

➗ What Is Added To Kadane

Kadane's Algorithm chooses between extending the run and starting fresh. This variant extends the run only when the new step flips the direction, and starts fresh at length 2 or 1 otherwise. The state is split by the direction of the last step.

🔑 The Key Idea in the Code

A step up extends down, not up: up, down = down + 1, 1. Extending the wrong length would count two steps in the same direction as turbulent.

  • Extending the same direction: up, down = up + 1, 1 for a step up counts two steps up in a row as turbulent. A step up extends the run whose last step went down.

  • Treating an equal step as a step down: arr[i] == arr[i - 1] is neither up nor down, so both runs restart at 1.

  • Tracking only one of the two lengths: the longest run may end with a step up or with a step down, so best takes the larger of both.

  • Forgetting that a single number counts: the smallest answer is 1, so up, down and best start at 1, not 0.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

Pattern Recognition Signals

The 10-second spot

"The longest subarray whose steps alternate": a best value over contiguous runs, like Kadane's Algorithm, but a run can only grow when the new step goes the opposite way from its last step. That means the state must remember the direction of the last step.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

up is the length of the longest turbulent subarray ending at arr[i] whose last step went up, and down is the same for a last step down. A step up gives up = down + 1, down = 1. A step down gives down = up + 1, up = 1. An equal step gives both 1.

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 Kadane's Algorithm and the direction of the last step as extra state. A turbulent run can only grow when the next step goes the other way, so I keep up and down, the longest turbulent run ending at the current number whose last step went up or down. A step up gives up equals down plus one and resets down to one. A step down is the mirror. An equal step is neither, so both go back to one. I keep the largest of up and down in best. That is one pass, order N time and order 1 space.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Look at the loop. for i in range(1, len(arr)) visits each neighbouring pair once. Each visit does one comparison, one assignment of up and down, and one max, which is constant work. That is N - 1 steps, so time is O(N).

SPACE COMPLEXITY

O(1)

The code keeps three variables, up, down and best, whatever the length of arr is. There is no table and no recursion, so space is O(1).

Formal Recurrence Relation

T(N)=N−1=O(N)T(N) = N - 1 = O(N)T(N)=N−1=O(N)

Derivation Progression

Passes

N−1 pairsN - 1 \text{ pairs}N−1 pairs

for i in range(1, len(arr)) visits each neighbouring pair once.

Work per pair

1 = O(1)

One comparison, one assignment of up and down, and one max.

Total

N - 1 = O(N)

Pairs times a constant amount of work.

Variable Definitions

NNN

Length of arr

upupup

Longest turbulent subarray ending here whose last step went up

downdowndown

Longest turbulent subarray ending here whose last step went down

Memory Architecture & Bounds

🟣 Call Stack

O(1): a loop only, no recursion

🔵 Auxiliary Heap

O(1): the variables up, down and best

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): the loop always visits every pair.

Average Case

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

Worst Case

O(N)O(N)O(N): the same count.

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: "each step goes the other way from the step before". A best length over contiguous runs is Kadane's Algorithm, and the alternating rule means the state must remember the direction of the last step.

CONSTRAINTS & BOUNDS

N≤4×104N \le 4 \times 10^4N≤4×104 and values up to 10910^9109. A loop over all start positions with an inner scan is 1.6×1091.6 \times 10^91.6×109 steps in the worst case. One pass is O(N)O(N)O(N). Only comparisons are used, so large values need no special handling.

FAANG PRODUCTION TRAPS & EDGE CASES

Equal neighbours are neither up nor down, so they must reset both lengths. Comparing arr[i] with arr[i - 2] instead of using the direction of the last step makes the code harder to check and misses the case of an equal pair.

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