Home/Data Structures & Algorithms/Arrays, Strings & Cache Memory

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.
In-place array algorithms, string parsing, cache-line locality, SIMD vectorization, and contiguous memory architectures.
Why does std::views::filter on temporary containers trigger undefined behavior and dangling references in C++20?
Direct Technical Solution: In C++20, range view adaptors (like std::views::filter, std::views::transform, and std::views::take) are strictly non-owning view wrappers. They do not duplicate or take ownership of the underlying container; they only store iterators pointing directly into the underlyingRead more
Direct Technical Solution: In C++20, range view adaptors (like
std::views::filter,std::views::transform, andstd::views::take) are strictly non-owning view wrappers. They do not duplicate or take ownership of the underlying container; they only store iterators pointing directly into the underlying sequence.In your code,
getTemperatures()returns a temporarystd::vector<int>by value. At the semicolon ending the initialization expressionauto warm_days = getTemperatures() | ...;, the temporary vector reaches the end of its full-expression lifetime and is immediately destructed. Consequently, the iterators stored insidewarm_daysbecome dangling pointers into deallocated stack/heap memory, causing undefined behavior upon iteration.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 to rotate an array in-place with O(1) space and zero cache misses?
This is a classic problem where the textbook solution and the production solution diverge. When you are moving 10 million integers in memory, allocating a temp slice or doing naive cyclic swaps will kill your performance due to cache misses. The cleanest, most battle-tested way to do this in productRead more
This is a classic problem where the textbook solution and the production solution diverge. When you are moving 10 million integers in memory, allocating a temp slice or doing naive cyclic swaps will kill your performance due to cache misses.
The cleanest, most battle-tested way to do this in production is the 3-Reversal Trick (often called the Reversal Algorithm). It requires zero extra memory and traverses contiguous memory sequentially, which modern CPU prefetchers love.
1. The Intuition (Why 3 Reversals Work)
Suppose you have the array
[1, 2, 3, 4, 5, 6, 7]and you want to rotate right byk = 3(so[5, 6, 7, 1, 2, 3, 4]).Notice the split: the last
kelements need to move to the front, and the firstn - kelements move to the back. If you reverse the whole thing first, everything is in the right neighborhood but backwards:[7, 6, 5, 4, 3, 2, 1][5, 6, 7, 4, 3, 2, 1][5, 6, 7, 1, 2, 3, 4]Done! Every element is now in its exact final position.
2. Production C++20 Implementation
3. Python 3.12 Clean Version
4. Complexity Breakdown
O(N)total time. Step 1 doesn/2swaps, Step 2 doesk/2swaps, and Step 3 does(n-k)/2swaps. Total swaps = exactlynswaps. You can't beat linear time because every element must change position.O(1)auxiliary space. Just two index pointers living directly in CPU registers.5. Real-World Gotchas to Watch Out For
- When k > n: Always take
- Negative k (Left Rotation): If your system asks for a left rotation by
- Empty or Single Element Arrays: Check
See lessk = k % n. Forgetting this causes out-of-bounds pointer crashes whenk = 15on an array of length 5.k, simply transform it: a left rotation bykis equivalent to a right rotation by(n - (k % n)) % n.n <= 1upfront to prevent unsigned integer underflow onn - 1.