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).

12 Core Algorithmic Patterns & 175 Practice Problems

  • 1. Two Pointers (9 Paradigms, 32 Problems): Converging pointers, sorted pair sums, container with most water, trapping rain water, 3Sum, plus the Sliding Window and Fast & Slow Pointers paradigms (Floyd cycle detection, monotonic window invariants, longest substrings, minimum window).
  • 2. Binary Search (8 Paradigms, 12 Problems): Monotonic predicate partitioning, boundary searching, rotated arrays, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 8 Problems): Bitmasking, XOR tricks, counting set bits, subset enumeration via bitmasks.
  • 4. Math & Geometry (6 Paradigms, 12 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (10 Paradigms, 19 Problems): Path sums, lowest common ancestor, tree diameter, subtree serialization, validating BSTs.
  • 6. Tree/Graph Breadth-First Search (4 Paradigms, 11 Problems): Level-order traversals, shortest path, rotting oranges, word ladders.
  • 7. Graphs (7 Paradigms, 15 Problems): Topological sort, cycle detection, Dijkstra, bipartite validation, network delay.
  • 8. Backtracking (5 Paradigms, 13 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens.
  • 9. Dynamic Programming (9 Paradigms, 16 Problems): Memoization vs tabulation, knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (8 Paradigms, 10 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (5 Paradigms, 13 Problems): Trie, Union-Find, LRU Cache, LFU Cache, Monotonic Stacks.
  • 12. Intervals & Stack / Miscellaneous (7 Paradigms, 14 Problems): Merge intervals, daily temperatures, largest rectangle in histogram, trapping rain water via stack.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Multi-language Rosetta Stone contrasting abstract invariants with concrete solutions across Python, C#, Java, TypeScript, C++, Go, and Rust.
  2. Stage 2 (Active Recall): Reconstruct algorithmic template invariants from memory with real-time feedback before looking at solutions.
  3. Stage 3 (Senior SWE AI Mock Coach): Simulated senior mock interview evaluating Big-O space/time tradeoffs, edge cases, and code reviews in Monaco Editor.
  4. Stage 4 (Solve on Your Own): Timed sandbox challenges verified against automated test suites in Python, C#, Java, and TypeScript.

Equipped with SM-2 Spaced Repetition Review Hub, Studio Cockpit workspace layout, and interactive study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Compute Coins: 40 free coins upon signup, +20 daily login bonus, +25 referral bonus.
  • 24-Hour AI Coaching Pass: 5 compute coins unlocks unlimited senior SWE AI coaching for a full 24 hours.
  • BYOK (Bring Your Own Key): Completely free unlimited AI coaching if using your own Gemini/OpenAI API key.
  • Refund & Subscription Policy: No recurring charges, no subscription traps, and no paid paywalls. Free tier provides full learning path.
  • Platform Operator: Hi👋WebEnterprise Inc. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

187Items
Theory Context•Math & Geometry
MediumLC 469

Convex Polygon (LeetCode 469)

You will see how the sign of one integer per corner tells whether a polygon has a dent.

Target Frequency:GoogleAmazonMeta

points lists the corners of a polygon in the order you meet them when you walk along its edge: each point is joined to the next one, and the last point is joined back to the first. The polygon is guaranteed to be simple: every corner touches exactly two edges, and no two edges meet or cross anywhere else.

Return true if the polygon is convex and false if it is not. A convex polygon has no dent: walking around it, you always turn the same way (only left turns, or only right turns). Three corners in a row may lie on one straight line; such a straight corner is not a turn, so it never makes the polygon non-convex.

Worked Examples

Example 1
Input:points = [[0,0],[0,5],[5,5],[5,0]]
Output:true
(0, 0)(0, 5)(5, 5)(5, 0)
Explanation: A square. Going from `(0,0)` up to `(0,5)`, across to `(5,5)`, down to `(5,0)` and back, every corner is a right turn, so there is no dent.
Example 2
Input:points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
Output:false
(0, 0)(0, 10)(10, 10)(10, 0)(5, 5)
Explanation: The corners `(0,10)`, `(10,10)` and `(10,0)` are right turns, but at `(5,5)` the edge turns left: that corner points into the shape, so it has a dent. This turn is one of the two that close the loop, found only by wrapping around from the last point to the first.

⚖️Formal Constraints & Bounds

  • 3 <= points.length <= 104

  • points[i].length == 2

  • -104 <= xi, yi <= 104

  • All the given points are unique.

Deep-Dive & Conceptual Insights

Why It Works & Core Invariant

One integer, cross(o, a, b), says whether the edge turns left or right at a corner. A polygon is convex exactly when every non-zero turn has the same sign, and a turn of 0 (a straight corner) changes nothing.

Real-World Scenario & Production Applications

A map or CAD tool checking that a drawn outline (a building footprint, a delivery zone, a collision shape in a game) has no dent before handing it to an algorithm that only works on convex shapes, such as a fast point-in-polygon test or a separating-axis collision check.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Mathematical Boundary & State Invariant

Establish 4-wall perimeter bounding (top, bottom, left, right) or binary exponent halving state x^n = (x^2)^(n/2).

Mathematical Recurrence / Code Invariant
top, bottom = 0, R - 1
left, right = 0, C - 1
res = []

Step-by-Step Execution Trace Table

Example 2, points = [[0,0],[0,10],[10,10],[10,0],[5,5]] (n = 5):

StepiCorner points[(i + 1) % n]turnprev beforeResult
10(0,10)cross((0,0), (0,10), (10,10)) = -1000first turn: prev = -100 (right)
21(10,10)cross((0,10), (10,10), (10,0)) = -100-100same sign: prev = -100
32(10,0)cross((10,10), (10,0), (5,5)) = -50-100same sign: prev = -50
43(5,5)cross((10,0), (5,5), (0,0)) = 50-50opposite sign: return False
Scroll horizontally to see all columns, or expand to full screen

The dent is found at i = 3, whose third point points[(3 + 2) % 5] is points[0]: without the wrap-around the loop would stop at i = 2 and answer true.

Core Invariant Specification & Code Shape
Archetype Code Shape
Python
1The sign of `cross(o, a, b)` tells which way `o -> a -> b` turns: positive left, negative right, 0 straight. A convex polygon turns the same way at every corner.
2Keep `prev`, the last non-zero turn; the polygon is convex exactly when no non-zero `turn` has the opposite sign.
3For `i` in `range(n)`: `turn = cross(points[i], points[(i + 1) % n], points[(i + 2) % n])`; skip a 0; return `False` if `prev != 0 and (turn > 0) != (prev > 0)`; else `prev = turn`. Return `True` after the loop.
4The trap: `if turn == 0: continue` before any comparison, and never store a 0 in `prev`: a straight corner is allowed, and forgetting the direction there lets a dent right after it slip through.

Target: Convex Polygon (LeetCode 469). Twice the signed area of the triangle `o, a, b`: positive for a left turn, negative for a right turn, 0 for three points on one line.

Boundary Model: 4-Pointer Boundary Box Contraction [top, bottom, left, right]

Boundary pointers contract inward after each directional sweep; modular arithmetic bounds state cyclically.

Loop Invariant Termination

while top <= bottom and left <= right: sweep right, down, left, up, contracting respective pointer.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Convexity sounds like a question about angles, but it only needs directions: a polygon is convex exactly when walking along its edge you always turn the same way. The Cross Product measures a turn with one integer and no angle: cross(o, a, b) is positive when the path o -> a -> b turns left, negative when it turns right, and 0 when the three points lie on one line. So is_convex walks the corners once, computes turn at each one, and keeps prev, the last non-zero turn: the first turn whose sign differs from prev is a dent.

🚗 The Analogy: Driving Around a Block

Picture driving once around a city block that has no dents: at every corner you turn the same way, say always right. If you ever have to turn left, the block must bend inward there. Driving straight through a junction is no turn at all, so it tells you nothing: you keep remembering that your turns so far were right turns. The cross product is the steering wheel read as a number: positive for a left turn, negative for a right turn, zero when you go straight on.

🪄 The Mathematical Harmony / Magic Trick
Code / Blueprint
turn = cross(points[i], points[(i + 1) % n], points[(i + 2) % n])
if turn == 0:
continue
if prev != 0 and (turn > 0) != (prev > 0):
return False
prev = turn
 

cross(o, a, b) is (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]), twice the signed area of the triangle o, a, b. Its sign changes exactly when b moves from one side of the line through o and a to the other, so it measures the turn at a with integer multiplication and subtraction only: no division by zero on a vertical edge, no rounding. The % n indices make the last two turns, at points[n - 1] and points[0], part of the same loop. A turn of 0 is skipped before prev is touched, so a straight corner can neither be mistaken for a dent nor erase the direction the edge was turning.

💡 Summary

Compute turn = cross(...) at every corner with % n wrap-around, skip turns of 0, and return False as soon as a turn's sign differs from prev. One pass: O(N)O(N)O(N) time, O(1)O(1)O(1) extra space.

  • Straight corners: write if turn == 0: continue before comparing. A straight corner is allowed, and storing its 0 in prev forgets the direction: in [[6,6],[4,12],[0,12],[0,0],[12,0],[12,12],[8,12],[7,9]] the dent at [6,6], checked right after the straight corner [7,9], would pass.

  • No wrap-around: use points[(i + 1) % n] and points[(i + 2) % n]. The last two turns sit at points[n - 1] and points[0], and in [[0,0],[0,10],[10,10],[10,0],[5,5]] the dent at [5,5] is one of them.

  • Multiplying signs: compare with (turn > 0) != (prev > 0), not prev * turn < 0. Each cross product reaches about 8 * 10^8, so the product of two overflows a 32-bit integer in Java or C++.

  • Slopes or angles: dy / dx divides by zero on a vertical edge and atan2 rounds; the cross product stays in exact integers.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

You will see how a senior engineer turns "no dent" into "every turn has the same sign" and says so out loud.

Pattern Recognition Signals

The 10-second spot

"Each point is joined to the next one, and the last point is joined back to the first", "you always turn the same way (only left turns, or only right turns)", "a straight corner is not a turn", and whole-number corners [x, y]: a question about which way the edge turns between points in the plane. That is the signal for the Cross Product: one integer per corner says left, right or straight, with no angle and no division.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

turn = cross(points[i], points[(i + 1) % n], points[(i + 2) % n]) is the turn at points[(i + 1) % n]: positive for left, negative for right, 0 for straight. prev holds the last non-zero turn, and the polygon is convex exactly when no non-zero turn has the opposite sign to prev.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • A turn of 0 is a straight corner: if turn == 0: continue before any comparison. Treating it as a change of direction rejects convex polygons with extra points on an edge, and storing it in prev forgets the direction, so the dent at [6,6] in [[6,6],[4,12],[0,12],[0,0],[12,0],[12,12],[8,12],[7,9]], checked right after the straight corner [7,9], would pass.

  • Wrap around with % n: the turns at points[n - 1] and points[0] close the loop, and in [[0,0],[0,10],[10,10],[10,0],[5,5]] the dent at [5,5] is one of them.

  • Compare signs with (turn > 0) != (prev > 0), not prev * turn < 0: the product can reach about 6.4 * 1017 and overflows a 32-bit integer in Java or C++.

  • No slopes or angles: dy / dx divides by zero on a vertical edge and atan2 rounds, while cross stays in exact integers.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use the Cross Product orientation test. For three points o, a and b, the cross product of a minus o with b minus o is positive when the path turns left, negative when it turns right, and zero when the three points are on one line. A polygon is convex exactly when its edge always turns the same way, so I walk the corners once, compute the turn at each one, and wrap around with modulo n so the two turns that close the loop are checked too. I keep prev, the last non-zero turn, and return false the moment a turn has the opposite sign. The trap is a turn of zero: that's a straight corner, which is allowed, so I skip it instead of calling it a dent or letting it erase prev. Everything stays in integers, with no division and no angles. That's O(N) time and O(1) extra space.

So: one cross product per corner, % n wrap-around, straight corners skipped, and the first sign change is the dent.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Count the work in is_convex. The loop for i in range(n) runs once per corner, N times. Each pass calls cross once, which does four subtractions, two multiplications and one more subtraction: O(1) whatever the coordinates. The test turn == 0, the sign comparison with prev and the assignment prev = turn are O(1) too. Nothing else loops, so the total is at most N passes of constant work: O(N). A dent can stop the loop early, but a convex polygon (the worst case) visits every corner.

SPACE COMPLEXITY

O(1)

is_convex keeps n, i, turn and prev, and each call to cross keeps three references and returns one integer: O(1). The % n indices read points[0] and points[1] again instead of copying them to the end of a new list, so nothing grows with N.

Formal Recurrence Relation

T(N) = N · (one cross product + two comparisons) = O(N)

Count the work in is_convex. The loop for i in range(n) runs once per corner, N times. Each pass calls cross once, which does four subtractions, two multiplications and one more subtraction: O(1) whatever the coordinates. The test turn == 0, the sign comparison with prev and the assignment prev = turn are O(1) too. Nothing else loops, so the total is at most N passes of constant work: O(N). A dent can stop the loop early, but a convex polygon (the worst case) visits every corner.

Derivation Progression

One pass over the corners

N

for i in range(n) runs once per corner; the % n indices reach the two turns that close the loop without a second pass.

One cross product per corner

O(1)

cross does a fixed number of subtractions and two multiplications, whatever the coordinates.

Compare with prev

O(1)

turn == 0 and (turn > 0) != (prev > 0) are two comparisons; prev = turn is one assignment.

Total

O(N)

N passes of constant work; a dent can only stop the loop sooner.

Variable Definitions

NNN

Number of corners, len(points) (at most 10^4)

Memory Architecture & Bounds

🟣 Call Stack

O(1): one call to cross at a time, no recursion

🔵 Auxiliary Heap

O(1): n, i, turn, prev

🟢 Output Space

O(1): one boolean

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1): the second turn already goes the other way

Average Case

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

Worst Case

O(N)O(N)O(N): a convex polygon, where every corner is checked

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "you always turn the same way", "no dent", "a straight corner is not a turn", whole-number corners [x, y] joined in order. A question about the direction of turns between integer points: Cross Product, the sign of one integer per corner.

CONSTRAINTS & BOUNDS

Up to 10410^4104 corners with coordinates in [−104,104][-10^4, 10^4][−104,104]. Each difference is below 2⋅1042 \cdot 10^42⋅104, so one cross product stays below 8⋅1088 \cdot 10^88⋅108 and fits a 32-bit integer, but the product of two does not. One pass is 10410^4104 cross products; testing every corner against every edge would be 10810^8108.

FAANG PRODUCTION TRAPS & EDGE CASES

Real coordinates (GPS, CAD, game physics) are floating-point numbers: the cross product of three nearly collinear points can round to the wrong sign, so two tests can disagree about the same corner. Production geometry code uses exact or adaptive-precision arithmetic for this test, or snaps coordinates to an integer grid first, instead of a loose tolerance. A polygon streamed from disk only needs its first two corners (for the wrap-around) and the current three in memory.

Core Algorithmic State Invariants

1. The Sign Is the Turn

`cross(o, a, b)` is twice the signed area of the triangle `o, a, b`: positive for a left turn, negative for a right turn, 0 for three points on one line. One integer answers the question with no angle.

2. Straight Corners Are Skipped

`if turn == 0: continue` runs before `prev` is compared or changed, so a straight corner neither flags a dent nor makes the loop forget the direction before the next one.

3. One Pass, Wrapped Around

`% n` checks the two turns that close the loop; `N` cross products and four variables give O(N) time and O(1) extra space.

Theory Context•Math & Geometry
MediumLC 469

Convex Polygon (LeetCode 469)

You will see how the sign of one integer per corner tells whether a polygon has a dent.

Target Frequency:GoogleAmazonMeta

points lists the corners of a polygon in the order you meet them when you walk along its edge: each point is joined to the next one, and the last point is joined back to the first. The polygon is guaranteed to be simple: every corner touches exactly two edges, and no two edges meet or cross anywhere else.

Return true if the polygon is convex and false if it is not. A convex polygon has no dent: walking around it, you always turn the same way (only left turns, or only right turns). Three corners in a row may lie on one straight line; such a straight corner is not a turn, so it never makes the polygon non-convex.

Worked Examples

Example 1
Input:points = [[0,0],[0,5],[5,5],[5,0]]
Output:true
(0, 0)(0, 5)(5, 5)(5, 0)
Explanation: A square. Going from `(0,0)` up to `(0,5)`, across to `(5,5)`, down to `(5,0)` and back, every corner is a right turn, so there is no dent.
Example 2
Input:points = [[0,0],[0,10],[10,10],[10,0],[5,5]]
Output:false
(0, 0)(0, 10)(10, 10)(10, 0)(5, 5)
Explanation: The corners `(0,10)`, `(10,10)` and `(10,0)` are right turns, but at `(5,5)` the edge turns left: that corner points into the shape, so it has a dent. This turn is one of the two that close the loop, found only by wrapping around from the last point to the first.

⚖️Formal Constraints & Bounds

  • 3 <= points.length <= 104

  • points[i].length == 2

  • -104 <= xi, yi <= 104

  • All the given points are unique.

Deep-Dive & Conceptual Insights

Why It Works & Core Invariant

One integer, cross(o, a, b), says whether the edge turns left or right at a corner. A polygon is convex exactly when every non-zero turn has the same sign, and a turn of 0 (a straight corner) changes nothing.

Real-World Scenario & Production Applications

A map or CAD tool checking that a drawn outline (a building footprint, a delivery zone, a collision shape in a game) has no dent before handing it to an algorithm that only works on convex shapes, such as a fast point-in-polygon test or a separating-axis collision check.

Subproblems & Recurrence Decomposition3 Phases

🧩Subproblem 1: Mathematical Boundary & State Invariant

Establish 4-wall perimeter bounding (top, bottom, left, right) or binary exponent halving state x^n = (x^2)^(n/2).

Mathematical Recurrence / Code Invariant
top, bottom = 0, R - 1
left, right = 0, C - 1
res = []

Step-by-Step Execution Trace Table

Example 2, points = [[0,0],[0,10],[10,10],[10,0],[5,5]] (n = 5):

StepiCorner points[(i + 1) % n]turnprev beforeResult
10(0,10)cross((0,0), (0,10), (10,10)) = -1000first turn: prev = -100 (right)
21(10,10)cross((0,10), (10,10), (10,0)) = -100-100same sign: prev = -100
32(10,0)cross((10,10), (10,0), (5,5)) = -50-100same sign: prev = -50
43(5,5)cross((10,0), (5,5), (0,0)) = 50-50opposite sign: return False
Scroll horizontally to see all columns, or expand to full screen

The dent is found at i = 3, whose third point points[(3 + 2) % 5] is points[0]: without the wrap-around the loop would stop at i = 2 and answer true.

Core Invariant Specification & Code Shape
Archetype Code Shape
Python
1The sign of `cross(o, a, b)` tells which way `o -> a -> b` turns: positive left, negative right, 0 straight. A convex polygon turns the same way at every corner.
2Keep `prev`, the last non-zero turn; the polygon is convex exactly when no non-zero `turn` has the opposite sign.
3For `i` in `range(n)`: `turn = cross(points[i], points[(i + 1) % n], points[(i + 2) % n])`; skip a 0; return `False` if `prev != 0 and (turn > 0) != (prev > 0)`; else `prev = turn`. Return `True` after the loop.
4The trap: `if turn == 0: continue` before any comparison, and never store a 0 in `prev`: a straight corner is allowed, and forgetting the direction there lets a dent right after it slip through.

Target: Convex Polygon (LeetCode 469). Twice the signed area of the triangle `o, a, b`: positive for a left turn, negative for a right turn, 0 for three points on one line.

Boundary Model: 4-Pointer Boundary Box Contraction [top, bottom, left, right]

Boundary pointers contract inward after each directional sweep; modular arithmetic bounds state cyclically.

Loop Invariant Termination

while top <= bottom and left <= right: sweep right, down, left, up, contracting respective pointer.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Convexity sounds like a question about angles, but it only needs directions: a polygon is convex exactly when walking along its edge you always turn the same way. The Cross Product measures a turn with one integer and no angle: cross(o, a, b) is positive when the path o -> a -> b turns left, negative when it turns right, and 0 when the three points lie on one line. So is_convex walks the corners once, computes turn at each one, and keeps prev, the last non-zero turn: the first turn whose sign differs from prev is a dent.

🚗 The Analogy: Driving Around a Block

Picture driving once around a city block that has no dents: at every corner you turn the same way, say always right. If you ever have to turn left, the block must bend inward there. Driving straight through a junction is no turn at all, so it tells you nothing: you keep remembering that your turns so far were right turns. The cross product is the steering wheel read as a number: positive for a left turn, negative for a right turn, zero when you go straight on.

🪄 The Mathematical Harmony / Magic Trick
Code / Blueprint
turn = cross(points[i], points[(i + 1) % n], points[(i + 2) % n])
if turn == 0:
continue
if prev != 0 and (turn > 0) != (prev > 0):
return False
prev = turn
 

cross(o, a, b) is (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]), twice the signed area of the triangle o, a, b. Its sign changes exactly when b moves from one side of the line through o and a to the other, so it measures the turn at a with integer multiplication and subtraction only: no division by zero on a vertical edge, no rounding. The % n indices make the last two turns, at points[n - 1] and points[0], part of the same loop. A turn of 0 is skipped before prev is touched, so a straight corner can neither be mistaken for a dent nor erase the direction the edge was turning.

💡 Summary

Compute turn = cross(...) at every corner with % n wrap-around, skip turns of 0, and return False as soon as a turn's sign differs from prev. One pass: O(N)O(N)O(N) time, O(1)O(1)O(1) extra space.

  • Straight corners: write if turn == 0: continue before comparing. A straight corner is allowed, and storing its 0 in prev forgets the direction: in [[6,6],[4,12],[0,12],[0,0],[12,0],[12,12],[8,12],[7,9]] the dent at [6,6], checked right after the straight corner [7,9], would pass.

  • No wrap-around: use points[(i + 1) % n] and points[(i + 2) % n]. The last two turns sit at points[n - 1] and points[0], and in [[0,0],[0,10],[10,10],[10,0],[5,5]] the dent at [5,5] is one of them.

  • Multiplying signs: compare with (turn > 0) != (prev > 0), not prev * turn < 0. Each cross product reaches about 8 * 10^8, so the product of two overflows a 32-bit integer in Java or C++.

  • Slopes or angles: dy / dx divides by zero on a vertical edge and atan2 rounds; the cross product stays in exact integers.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

You will see how a senior engineer turns "no dent" into "every turn has the same sign" and says so out loud.

Pattern Recognition Signals

The 10-second spot

"Each point is joined to the next one, and the last point is joined back to the first", "you always turn the same way (only left turns, or only right turns)", "a straight corner is not a turn", and whole-number corners [x, y]: a question about which way the edge turns between points in the plane. That is the signal for the Cross Product: one integer per corner says left, right or straight, with no angle and no division.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

turn = cross(points[i], points[(i + 1) % n], points[(i + 2) % n]) is the turn at points[(i + 1) % n]: positive for left, negative for right, 0 for straight. prev holds the last non-zero turn, and the polygon is convex exactly when no non-zero turn has the opposite sign to prev.

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • A turn of 0 is a straight corner: if turn == 0: continue before any comparison. Treating it as a change of direction rejects convex polygons with extra points on an edge, and storing it in prev forgets the direction, so the dent at [6,6] in [[6,6],[4,12],[0,12],[0,0],[12,0],[12,12],[8,12],[7,9]], checked right after the straight corner [7,9], would pass.

  • Wrap around with % n: the turns at points[n - 1] and points[0] close the loop, and in [[0,0],[0,10],[10,10],[10,0],[5,5]] the dent at [5,5] is one of them.

  • Compare signs with (turn > 0) != (prev > 0), not prev * turn < 0: the product can reach about 6.4 * 1017 and overflows a 32-bit integer in Java or C++.

  • No slopes or angles: dy / dx divides by zero on a vertical edge and atan2 rounds, while cross stays in exact integers.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use the Cross Product orientation test. For three points o, a and b, the cross product of a minus o with b minus o is positive when the path turns left, negative when it turns right, and zero when the three points are on one line. A polygon is convex exactly when its edge always turns the same way, so I walk the corners once, compute the turn at each one, and wrap around with modulo n so the two turns that close the loop are checked too. I keep prev, the last non-zero turn, and return false the moment a turn has the opposite sign. The trap is a turn of zero: that's a straight corner, which is allowed, so I skip it instead of calling it a dent or letting it erase prev. Everything stays in integers, with no division and no angles. That's O(N) time and O(1) extra space.

So: one cross product per corner, % n wrap-around, straight corners skipped, and the first sign change is the dent.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

Count the work in is_convex. The loop for i in range(n) runs once per corner, N times. Each pass calls cross once, which does four subtractions, two multiplications and one more subtraction: O(1) whatever the coordinates. The test turn == 0, the sign comparison with prev and the assignment prev = turn are O(1) too. Nothing else loops, so the total is at most N passes of constant work: O(N). A dent can stop the loop early, but a convex polygon (the worst case) visits every corner.

SPACE COMPLEXITY

O(1)

is_convex keeps n, i, turn and prev, and each call to cross keeps three references and returns one integer: O(1). The % n indices read points[0] and points[1] again instead of copying them to the end of a new list, so nothing grows with N.

Formal Recurrence Relation

T(N) = N · (one cross product + two comparisons) = O(N)

Count the work in is_convex. The loop for i in range(n) runs once per corner, N times. Each pass calls cross once, which does four subtractions, two multiplications and one more subtraction: O(1) whatever the coordinates. The test turn == 0, the sign comparison with prev and the assignment prev = turn are O(1) too. Nothing else loops, so the total is at most N passes of constant work: O(N). A dent can stop the loop early, but a convex polygon (the worst case) visits every corner.

Derivation Progression

One pass over the corners

N

for i in range(n) runs once per corner; the % n indices reach the two turns that close the loop without a second pass.

One cross product per corner

O(1)

cross does a fixed number of subtractions and two multiplications, whatever the coordinates.

Compare with prev

O(1)

turn == 0 and (turn > 0) != (prev > 0) are two comparisons; prev = turn is one assignment.

Total

O(N)

N passes of constant work; a dent can only stop the loop sooner.

Variable Definitions

NNN

Number of corners, len(points) (at most 10^4)

Memory Architecture & Bounds

🟣 Call Stack

O(1): one call to cross at a time, no recursion

🔵 Auxiliary Heap

O(1): n, i, turn, prev

🟢 Output Space

O(1): one boolean

Boundary Best / Worst Cases

Best Case

O(1)O(1)O(1): the second turn already goes the other way

Average Case

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

Worst Case

O(N)O(N)O(N): a convex polygon, where every corner is checked

Recurrence Tree Topology

Recurrence Tree Topology
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: "you always turn the same way", "no dent", "a straight corner is not a turn", whole-number corners [x, y] joined in order. A question about the direction of turns between integer points: Cross Product, the sign of one integer per corner.

CONSTRAINTS & BOUNDS

Up to 10410^4104 corners with coordinates in [−104,104][-10^4, 10^4][−104,104]. Each difference is below 2⋅1042 \cdot 10^42⋅104, so one cross product stays below 8⋅1088 \cdot 10^88⋅108 and fits a 32-bit integer, but the product of two does not. One pass is 10410^4104 cross products; testing every corner against every edge would be 10810^8108.

FAANG PRODUCTION TRAPS & EDGE CASES

Real coordinates (GPS, CAD, game physics) are floating-point numbers: the cross product of three nearly collinear points can round to the wrong sign, so two tests can disagree about the same corner. Production geometry code uses exact or adaptive-precision arithmetic for this test, or snaps coordinates to an integer grid first, instead of a loose tolerance. A polygon streamed from disk only needs its first two corners (for the wrap-around) and the current three in memory.

Core Algorithmic State Invariants

1. The Sign Is the Turn

`cross(o, a, b)` is twice the signed area of the triangle `o, a, b`: positive for a left turn, negative for a right turn, 0 for three points on one line. One integer answers the question with no angle.

2. Straight Corners Are Skipped

`if turn == 0: continue` runs before `prev` is compared or changed, so a straight corner neither flags a dent nor makes the loop forget the direction before the next one.

3. One Pass, Wrapped Around

`% n` checks the two turns that close the loop; `N` cross products and four variables give O(N) time and O(1) extra space.

Rosetta Dual-Monaco Comparison
Python 3
CANONICAL INVARIANT TEMPLATE
Loading...
CONCRETE: CONVEX POLYGON (LEETCODE 469)
T = O(N)S = O(1)
Loading...
Pattern Implementation Mapping TableCanonical Invariant ⟷ Concrete Code ⟷ Engineering Rationale
Canonical InvariantConcrete CodeEngineering Rationale
Orientation test: the sign of one integer is the turnreturn (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])Twice the signed area of the triangle `o, a, b`: positive for a left turn, negative for a right turn, 0 for three points on one line.
Remember the last real turnprev = 00 means no turn has been seen yet; after that it always holds the last non-zero turn.
Visit every corner, wrapping aroundfor i in range(n): turn = cross(points[i], points[(i + 1) % n], points[(i + 2) % n])`% n` makes the turns at `points[n - 1]` and `points[0]`, which close the loop, part of the same pass.
A straight corner is not a turn (the trap)if turn == 0: continueIt is skipped before `prev` is touched: it never counts as a dent and never erases the direction.
A turn the other way is a dentif prev != 0 and (turn > 0) != (prev > 0): return FalseComparing signs instead of multiplying keeps the test exact and free of overflow.
Carry the direction forwardprev = turn return TrueOnly non-zero turns reach this line; if the loop ends, every turn went the same way.
© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•