
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.
0/1 Knapsack: Why does reverse iteration turn O(N*W) space into O(W) space?
This is one of the most fundamental 'aha!' moments in dynamic programming. Let's walk through the memory mechanics so you never forget it. 1. The 2D State Transition In the classic 0/1 Knapsack, the formula is: dp[i][w] = max( dp[i-1][w], // Option A: Skip item i (take answer from previous row) dp[iRead more
This is one of the most fundamental ‘aha!’ moments in dynamic programming. Let’s walk through the memory mechanics so you never forget it.
1. The 2D State Transition
In the classic 0/1 Knapsack, the formula is:
Notice the critical detail: in Option B,
dp[i-1][w - weight[i]]comes from rowi-1(before itemiwas even considered). That is what guarantees you only take itemiat most once.2. Compressing to a 1D Array
Notice that to compute row
i, you only ever look at rowi-1. You don’t need rowsi-2,i-3, etc. So we can just reuse a single 1D array:dp[w].What happens if you iterate FORWARD (w = weight[i] to W)?
Suppose item 1 has
weight = 2, value = 10and capacity is6.w = 2:dp[2] = dp[0] + 10 = 10.w = 4:dp[4] = dp[4 - 2] + 10 = dp[2] + 10 = 10 + 10 = 20! (Wait, you just reused item 1 twice!)w = 6:dp[6] = dp[4] + 10 = 30! (You used item 1 three times!)Because you updated smaller weights first, larger weights read the already updated values from the current item. That turns it into Unbounded Knapsack (infinite items)!
What happens if you iterate BACKWARD (w = W down to weight[i])?
w = 6: readsdp[4](which is still 0 from the previous item!).dp[6] = 0 + 10 = 10.w = 4: readsdp[2](which is still 0!).dp[4] = 0 + 10 = 10.w = 2: readsdp[0](which is 0!).dp[2] = 0 + 10 = 10.By sweeping backwards, whenever you query
w - weight[i], that smaller index has not yet been touched for the current item. It still holds the pristine value from itemi-1!Production Python 3.12 Implementation
Summary Rule of Thumb
- 0/1 Knapsack (items used at most once) → Iterate Backward (
- Unbounded Knapsack / Coin Change (items can be reused infinitely) → Iterate Forward (
See lessW → weight).weight → W).Why does standard std::priority_queue in Dijkstra cause memory bloating, and how to fix it?
You have hit on one of the most critical differences between competitive programming hacks and real-world systems engineering. In standard textbook Dijkstra, because std::priority_queue does not support a native decrease_key() operation, engineers take the lazy route: they just push duplicate entrieRead more
You have hit on one of the most critical differences between competitive programming hacks and real-world systems engineering.
In standard textbook Dijkstra, because
std::priority_queuedoes not support a nativedecrease_key()operation, engineers take the lazy route: they just push duplicate entries into the heap and skip stale ones withif (d > dist[u]) continue;. This is called Lazy Deletion Dijkstra.While lazy Dijkstra works fine on small graphs, on dense graphs with 10 million edges, your heap stores up to 10 million items instead of 1 million nodes, blowing through your CPU’s L3 cache.
The Solution: Indexed Priority Queue
An Indexed Binary Heap (Indexed Priority Queue) maintains an internal inverse lookup array (
pos[u]) that tracks the exact heap index of every nodeu.When a shorter path to node
uis discovered:uis already in the heap, you don’t insert a duplicate—you calldecrease_key(u, new_dist), which directly updates the value in-place and sifts it up inO(log V)time!High-Performance C++20 Indexed Min-Heap Dijkstra
Performance Benchmark Comparison
By enforcing an explicit upper bound of
See lessVelements in the heap, the entire indexed heap fits cleanly inside modern CPU L2/L3 caches, drastically accelerating routing throughput!How to design a thread-safe LRU Cache in O(1) without memory leaks?
Building an LRU cache from scratch is one of the best ways to understand how data structures combine in real systems. The industry standard pattern is combining two complementary structures: A Hash Map: Gives you O(1) key-to-node lookups. A Doubly Linked List (DLL) with Dummy Head & Tail: GivesRead more
Building an LRU cache from scratch is one of the best ways to understand how data structures combine in real systems. The industry standard pattern is combining two complementary structures:
O(1)key-to-node lookups.O(1)node insertion at the front (most recent) andO(1)node removal from the back (least recent).The secret trick that eliminates 90% of bug-prone null checks is using sentinel (dummy) head and tail nodes. Instead of constantly checking
if (head == null)orif (node->prev == null), the dummy head and tail are always linked together:head <-> tail. Any real data node always lives safely in between them!Architectural Diagram
Clean, Idiomatic Python 3.12 Implementation
Why Storing the Key Inside the Node is Crucial
Notice that the
Nodeclass stores bothkeyandval. Many developers forget to storekeyin the node and only storeval. But when the cache reaches full capacity and you evicttail.prev, how do you delete that entry from the hash map? Withoutnode.key, you’d have to search the entire hash map inO(N)time, destroying yourO(1)guarantee!Thread Safety in Production
If multiple threads access this cache concurrently:
- In Python, use
- In Go or C++, a Read-Write Lock (
See lessthreading.Lock()aroundgetandput.sync.RWMutex/std::shared_mutex) is often tempting, but remember: even aget()operation mutates the linked list (to move the accessed item to the front)! Therefore, standard read locks are not enough—you must acquire an exclusive lock or use lock striping across multiple shards.What is a database?
A database refers to a structured body of information which is in electronic form to allow effortless accessibility, management and modification. It assists in storing the information in tables with rows and columns and is handled by a Database Management System (DBMS) such as MySQL or MongoDB.
A database refers to a structured body of information which is in electronic form to allow effortless accessibility, management and modification. It assists in storing the information in tables with rows and columns and is handled by a Database Management System (DBMS) such as MySQL or MongoDB.
See less