Part 2: The Reality Check Explained (Google WSE)
#GoogleWSE#Series#Intermediate
Part 2: The Reality Check Explained (Google WSE) --- Google WSE Interview Series: 1. Part 1: Map & Heap Deep Dive 2. Part 2: The Reality Check Explained 3. Part
Part 2: The Reality Check Explained (Google WSE) --- Google WSE Interview Series: 1. Part 1: Map & Heap Deep Dive 2. Part 2: The Reality Check Explained 3. Part 3: Advanced Follow-up Solutions 4. Visual Explanation: Process Flow --- The "Reality Check" is the logic inside the getMinPrice() method that ensures the heap's suggestion actually exists in our data. In our code, it looks like this: --- Why is this necessary? Think of the Heap as a bulletin board where sellers pin their lowest prices. Think of the Map as a digital database that tracks the actual current state. Scenario: The Price Update 1. 09:00 AM: Seller A lists a laptop for $1000 (Timestamp: 10). - Map: {10 - 1000} - Heap: 1000 (t:10) 2. 09:15 AM: Seller A sees a competitor and drops their price to $900. - Map Updates: {10 - 900} (Instant $O(1)$ change). - Heap: 900 (t:10), 1000 (t:10) (Note: We added $900, but the $1000 is still sitting there deeper in the heap!). 3. 09:20 AM: Someone asks for getMinPrice(). - The heap correctly shows $900 at the top. The "Reality Check" confirms: "Does Timestamp 10 still have a price of $900 in the Map?" Yes. 4. 10:00 AM: Seller A sells the laptop and removes the listing. - Map: EMPTY - Heap: 900 (t:10), 1000 (t:10) (The heap still has two entries for Timestamp 10!) --- How the "Reality Check" Handles the Mess When getMinPrice() is called after the listing is removed: 1. Check 1: System looks at the top of the heap: $900 (t:10). - Reality Check: "Does Map have t:10?" - No. - Action: heapPop() (Throws away the $900). 2. Check 2: System looks at the new top of the heap: $1000 (t:10). - Reality Check: "Does Map have t:10?" - No. - Action: heapPop() (Throws away the $1000). 3. Result: The heap is now empty. System returns null. --- Summary of Roles | Component | Responsibility | Performance | | :--- | :--- | :--- | | Map | Knows exactly what exists right now. It is the source of truth. | $O(1)$ lookup. | | Heap | Guesses the minimum. I