
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Next.js 15: Error: Route used “params” without awaiting it (Asynchronous Page Props Fix)
Direct Technical Solution: In Next.js 15, dynamic route parameters (params) and search parameters (searchParams) transitioned from synchronous plain JavaScript objects to native Promises. This breaking change was implemented to support React 19 Server Components and the new Partial Prerendering (PPRRead more
Direct Technical Solution: In Next.js 15, dynamic route parameters (
params) and search parameters (searchParams) transitioned from synchronous plain JavaScript objects to native Promises. This breaking change was implemented to support React 19 Server Components and the new Partial Prerendering (PPR) model, where the server renders the static page skeleton before dynamic parameters resolve.1. Server Component Migration (Async/Await)
In all Next.js 15 Server Components (the default in the
app/directory), typeparamsas aPromiseand explicitlyawaitit before accessing any key:2. Client Component Migration (React 19 `use()` Hook)
If your page file uses
"use client", you cannot make the component functionasync. Instead, unwrap theparamsPromise using React 19’s nativeReact.use()hook:3. Comparison: Next.js 14 vs Next.js 15
{ slug: string }(Synchronous Object)Promise<{ slug: string }>(Async Promise)params.slug)const { slug } = await params;useParams()hookuse(params)oruseParams()Daily Temperatures: How to use an Index-Tracking Monotonic Stack for next warmer day in O(N)
This problem is the cleanest introductory template for the Monotonic Decreasing Stack pattern. Let's look at why storing indices unlocks the distance calculation. 1. The Mental Model Imagine people waiting in line holding temperature tickets. If temperatures are dropping: [73, 71, 69], nobody has foRead more
This problem is the cleanest introductory template for the Monotonic Decreasing Stack pattern. Let’s look at why storing indices unlocks the distance calculation.
1. The Mental Model
Imagine people waiting in line holding temperature tickets. If temperatures are dropping:
[73, 71, 69], nobody has found a warmer day yet! So everyone has to stay waiting in line.Now, a warm day arrives:
72!69sees72 > 69. Their wait is over! They step out of line.71sees72 > 71. Their wait is over! They step out of line.73sees72 < 73.72is not warm enough for them! The person with73stays waiting in line, and the day with72joins the line behind them.2. Why Store Indices Instead of Values?
If you only push temperature numbers (e.g.
69) onto the stack, when a warmer day72pops69, you know that a warmer day happened, but you don’t know how many days elapsed!By pushing the array index
prev_dayonto the stack:You calculate the exact time difference in $O(1)$ and write directly to the output array!
Clean Python 3.12 Implementation
Complexity Breakdown
- Time Complexity:
- Space Complexity:
See lessO(N). Every index is pushed onto the stack once and popped at most once. Total operations: $le 2N$.O(N)for the stack in the worst-case of strictly decreasing temperatures (e.g.[100, 90, 80, 70]).Subarray Sum Equals K: Why Two Pointers fails with negative numbers and Hash Map is mandatory
This is a classic trap that catches even intermediate developers. Let's see why two pointers collapse and why prefix math is the ultimate solution. 1. Why Two Pointers Fails on Negative Numbers A sliding window relies on a fundamental monotonic invariant: If the current sum is too small, expanding tRead more
This is a classic trap that catches even intermediate developers. Let’s see why two pointers collapse and why prefix math is the ultimate solution.
1. Why Two Pointers Fails on Negative Numbers
A sliding window relies on a fundamental monotonic invariant:
The moment you introduce negative numbers, this invariant is destroyed! Expanding the right pointer might add
-10, making the sum smaller. Shrinking the left pointer might drop-5, making the sum larger. You can no longer make greedy left/right decisions!2. The Prefix Sum Invariant
Let
prefix[i]be the cumulative sum from index 0 toi.The sum of any contiguous subarray from index
j + 1toiis given by:sum(j+1 ... i) = prefix[i] - prefix[j].We want this subarray sum to equal
k:The Breakthrough: As you iterate through the array maintaining a running prefix sum
curr_sum, you simply ask the hash map: ‘How many times have we already seen a prefix sum equal tocurr_sum - kin the past?’Every time you find that value in the hash map, you have found a valid subarray that sums exactly to
k!Clean Python 3.12 Implementation
Why prefix_counts[0] = 1 is Critical
If you forget
prefix_counts[0] = 1, any subarray that starts at index 0 and sums tok(e.g.nums = [3, ...], k = 3) will producecurr_sum = 3, and look forcurr_sum - k = 0in the map. Without the base case, it would fail to count that valid subarray!Complexity Breakdown
- Time Complexity:
- Space Complexity:
See lessO(N). Single pass through the array withO(1)hash map lookups.O(N)to store prefix sum frequencies.Minimum Window Substring: Why an integer frequency array beats HashMap in low-latency parsers
Minimum Window Substring is the crown jewel of sliding window problems. The difference between a junior solution and a staff engineer solution comes down to how window validation is tracked. 1. The Trap: Comparing Two Hash Maps In naive implementations, developers maintain two hash maps: target_counRead more
Minimum Window Substring is the crown jewel of sliding window problems. The difference between a junior solution and a staff engineer solution comes down to how window validation is tracked.
1. The Trap: Comparing Two Hash Maps
In naive implementations, developers maintain two hash maps:
target_countsandwindow_counts. Whenever the window slides, they loop through the keys oftarget_countsto see if the window is valid. That turns an $O(N)$ algorithm into $O(N cdot |Sigma|)$ with heavy hash table overhead!2. The Staff Engineer Pattern: Single Vector + Deficit Counter
We can optimize this down to bare metal with two simple tricks:
required): We setrequired = len(t). When expanding the window with pointerr, ifcounts[s[r]] > 0, that character was actively needed, so we decrementrequired--. Whenrequired == 0, the window is 100% valid! We don’t have to check any other variables!Clean Python 3.12 Implementation
Complexity Breakdown
- Time Complexity:
- Space Complexity:
See lessO(|s| + |t|). Therightpointer advances|s|times. Theleftpointer advances at most|s|times. Total pointer advances =2|s|.O(1)auxiliary space. Exactly 128 integers on the stack.How to find the Single Number when all others appear 3 times using a Digital Logic State Machine?
This problem is a masterpiece of digital circuit design translated into software code. Let's design the state machine from first principles. 1. The Three States of a Bit For any bit position, as we scan numbers in the array, how many times can we see a 1? Seen 0 times → Count = 0 Seen 1 timeRead more
This problem is a masterpiece of digital circuit design translated into software code. Let’s design the state machine from first principles.
1. The Three States of a Bit
For any bit position, as we scan numbers in the array, how many times can we see a
1?To represent 3 distinct states (0, 1, and 2), we need 2 bits of memory! Let’s name them:
twos(the high bit)ones(the low bit)2. The Truth Table
When a new bit
xarrives from the current number:3. Deriving the Logic Gates
From the truth table:
ones = (ones ^ x) & (~twos)twos = (twos ^ x) & (~ones)When the full array has been scanned:
ones!Clean Python 3.12 Implementation
Complexity Breakdown
- Time Complexity:
- Space Complexity:
See lessO(N). We touch each number once with 4 single-cycle bitwise operations.O(1). Exactly two integer variables living in registers.How does a Fenwick Tree (Binary Indexed Tree) query and update prefix sums in O(log N) using i & (-i)?
The Fenwick Tree (invented by Peter Fenwick in 1994) is one of the most compact data structures ever devised. It gives you the full power of a dynamic segment tree in just one flat array of size N with 10 lines of code. 1. The Secret: Powers of 2 Range Decomposition Any positive integer can be uniquRead more
The Fenwick Tree (invented by Peter Fenwick in 1994) is one of the most compact data structures ever devised. It gives you the full power of a dynamic segment tree in just one flat array of size N with 10 lines of code.
1. The Secret: Powers of 2 Range Decomposition
Any positive integer can be uniquely represented as a sum of powers of 2. For example:
13 = 8 + 4 + 1.Fenwick took this idea and applied it to prefix ranges: instead of storing every single element,
tree[i]stores the sum of a contiguous range of length equal to its lowest set bit!The length of the range responsible by index
iis given by:lowbit(i) = i & (-i).i = 12 (1100_2):lowbit(12) = 4. Sotree[12]stores the sum of 4 elements: indices[9, 10, 11, 12]!i = 8 (1000_2):lowbit(8) = 8. Sotree[8]stores the sum of the first 8 elements:[1 ... 8]!2. The Two Operations
A. Prefix Sum Query: `i -= (i & -i)`
To calculate the prefix sum up to index
13:tree[13](covers index 13).13 - lowbit(13) = 13 - 1 = 12.tree[12](covers indices 9 through 12).12 - lowbit(12) = 12 - 4 = 8.tree[8](covers indices 1 through 8).8 - lowbit(8) = 8 - 8 = 0(Done!).Total reads: only 3 steps to sum 13 numbers! At each step, you strip off one binary bit, taking at most
O(log N)operations.B. Point Update: `i += (i & -i)`
When you add delta to element
i, which parent ranges need to be updated? Every index whose range coversi! You navigate up the tree simply by adding the lowest set bit:i += (i & -i)!Clean C++20 Implementation
Why Fenwick Beats Segment Trees in Production
Floyd’s Tortoise and Hare: Mathematical proof of why meeting point resolves cycle origin
Floyd's cycle algorithm is pure mathematical poetry. Let's write out the distances with simple algebra so the proof is crystal clear. 1. Defining the Variables Let's map out the linked list into three distinct segments: L: Distance from the head to the cycle entrance. C: Total length (circumference)Read more
Floyd’s cycle algorithm is pure mathematical poetry. Let’s write out the distances with simple algebra so the proof is crystal clear.
1. Defining the Variables
Let’s map out the linked list into three distinct segments:
L: Distance from theheadto the cycle entrance.C: Total length (circumference) of the cycle.x: Distance from the cycle entrance to the meeting point inside the cycle.2. Distance Traveled by Each Pointer
When the Tortoise (slow) and Hare (fast) meet:
Dist_slow = L + xDist_fast = L + n * C + x(wherenis how many full laps fast ran around the cycle).Because the fast pointer moves at twice the speed of slow:
Now subtract
L + xfrom both sides:3. What does L = (n – 1) * C + (C – x) mean?
Look carefully at that equation:
Lis the distance from head to the cycle entrance.(C - x)is the distance from the meeting point to the cycle entrance!(n - 1) * Cis just zero or more full loops around the cycle!Conclusion: If you place Pointer 1 at
head(which must travel distanceL) and Pointer 2 atmeeting_point(which travels distance(C - x)plus some optional full laps), both pointers will meet at the EXACT same node: the cycle entrance!Clean Python 3.12 Implementation
Complexity Breakdown
- Time Complexity:
- Space Complexity:
See lessO(N). Phase 1 takes at most $2N$ steps. Phase 2 takes at most $N$ steps.O(1). No hash set or memory allocation.How does the Dutch National Flag 3-way partition work in a single pass with zero branch mispredictions?
The Dutch National Flag algorithm (invented by Edsger W. Dijkstra) is the secret weapon that makes 3-way QuickSort resilient against duplicate keys. 1. The 3 Pointer Invariant We divide the array into 4 distinct regions using 3 pointers: low, mid, and high: [ 0 ... low-1 ] -> All elements strictlRead more
The Dutch National Flag algorithm (invented by Edsger W. Dijkstra) is the secret weapon that makes 3-way QuickSort resilient against duplicate keys.
1. The 3 Pointer Invariant
We divide the array into 4 distinct regions using 3 pointers:
low,mid, andhigh:Initially,
low = 0,mid = 0, andhigh = n - 1. The entire array is initially inside theUNKNOWNregion.2. The 3 State Transitions
While
mid <= high, inspectnums[mid]:nums[mid] == 0: Swapnums[low]withnums[mid]. Increment BOTHlow++andmid++.Why can we increment
midhere? Because whatever was sitting atlowwas already processed (it was guaranteed to be a1).nums[mid] == 1: It’s already in the right spot! Just incrementmid++.nums[mid] == 2: Swapnums[mid]withnums[high]. Decrementhigh--.THE CRITICAL CATCH: Do NOT increment
midhere! Whatever came fromhighwas unknown—it might be a0, a1, or another2! We must inspect it on the next loop iteration!Clean Python 3.12 Implementation
Complexity Breakdown
- Time Complexity:
- Space Complexity:
See lessO(N). In every single step, eithermidincreases orhighdecreases. The unknown window(high - mid)strictly shrinks to zero in at mostNsteps.O(1). No extra memory allocated.How does a Count-Min Sketch estimate heavy-hitter item frequencies under bounded RAM?
The Count-Min Sketch (CMS) is the gold-standard probabilistic algorithm for tracking frequencies in massive, unconstrained data streams (used extensively in Apache Spark, network switches, and Google search analytics). 1. Architectural Layout A Count-Min Sketch consists of a 2D matrix of integer couRead more
The Count-Min Sketch (CMS) is the gold-standard probabilistic algorithm for tracking frequencies in massive, unconstrained data streams (used extensively in Apache Spark, network switches, and Google search analytics).
1. Architectural Layout
A Count-Min Sketch consists of a 2D matrix of integer counters with
drows (depth) andwcolumns (width), paired withdindependent hash functions:2. The Operations
A. Add Item `x` (Increment):
For each row
ifrom0tod - 1, compute column indexcol = h_i(x) % w, and increment that counter:B. Query Frequency of `x` (Point Query):
Because multiple items might collide at the same counter bucket, hash collisions can only increase a counter, never decrease it!
Therefore, to get the best possible estimate, we take the MINIMUM across all d rows:
The Golden Invariant: A Count-Min Sketch NEVER underestimates the true count! True frequency is always $le$ estimated frequency.
3. Mathematical Dimensioning Rules
If you want an error bound within $epsilon cdot N$ with confidence probability $1 – delta$:
ceil pprox lceil rac{2.718}{epsilon}
ceil$
ceil$
For example, to guarantee $le 0.1%$ error with $99%$ confidence, you need only $w = 2718$ columns and $d = 5$ rows. That’s just 13,590 integer counters (~54 KB of RAM) to monitor billions of events!
Clean Python 3.12 Implementation
Complexity Breakdown
- Add Time:
- Query Time:
- Memory Footprint:
See lessO(d)— strictly constant time ($5$ hash calculations and memory writes).O(d)— strictly constant time ($5$ lookups).O(w * d)— strictly fixed in size. Bounded memory that never grows regardless of how many billions of packets arrive!How does a 32-bit Binary Trie find the Maximum XOR of Two Numbers in O(N) time?
The Maximum XOR problem is the ultimate showcase of how bit manipulation and trees blend together. Once you see the greedy nature of binary numbers, the Binary Trie solution becomes second nature. 1. The Greedy Bit Principle In binary numbers, the Most Significant Bit (MSB) has more numerical valueRead more
The Maximum XOR problem is the ultimate showcase of how bit manipulation and trees blend together. Once you see the greedy nature of binary numbers, the Binary Trie solution becomes second nature.
1. The Greedy Bit Principle
In binary numbers, the Most Significant Bit (MSB) has more numerical value than all lower bits combined! For example, bit 30 ($2^{30} pprox 1.07 imes 10^9$) is strictly greater than the sum of all bits from 0 to 29 combined ($2^{30} – 1$).
Therefore, to maximize an XOR sum, you must be greedy from left to right (MSB down to LSB):
numis1, you desperately want to pair it with a number whose corresponding bit is0(because1 ^ 0 = 1).numis0, you want to pair it with a number whose corresponding bit is1(because0 ^ 1 = 1).2. Why a Binary Trie?
A Binary Trie is just a tree where every node has at most two children:
0(left) and1(right).x, you walk down the Trie. At each bitb, you ask: ‘Does the opposite branch (1 - b) exist?’1.b), so that bit in your XOR result becomes0.Because you made the best possible choice at every single bit position starting from the highest power of 2, the final accumulated number is mathematically guaranteed to be the global maximum XOR!
Clean Python 3.12 Implementation
Complexity Breakdown
- Time Complexity:
- Space Complexity:
See lessO(31 * N) = O(N). InsertingNnumbers takes31 * Noperations. QueryingNnumbers takes31 * Noperations. Total time is strictly linear in the number of elements.O(31 * N)worst-case node allocations. In practice, prefix branches overlap heavily, keeping memory around a few megabytes.