Dodi and Jaya from the two ends of the floor: how many weighings until a pair of sacks matches the target, against nested loops and a Map that really run?…
Why it matters
The two-pointer pattern turns up in many problems: a pair summing to a target, dropping duplicates, reversing an array, merging two sorted lists. It is O(n) time and O(1) memory, but only when the order makes every step throw something away for sure.
The key idea
Every weighing throws away one sack with all its pairs
Common mistakes
Two pointers on an unsorted array It must be sorted. On unsorted data the rule for moving left or right means nothing, and the answer can be wrong without an error. Sort first (O(n log n)) or use a Map.
Forgetting when to move lo or hi Sum too small: lo++ (it needs heavier). Too big: hi--. The row’s order is what makes this rule right.
Using a Map and wondering at the memory A Map is O(n) time but also O(n) memory: one entry per sack it passes. Two pointers are O(1) memory, as long as the row is sorted. Choose by your limits.
Dropping twins on an unsorted row An in-place dedupe only compares neighbours, so twins far apart slip through. Sort first, or use new Set(a) (with O(n) memory).
Try it in this playground
Pinch until found A sorted row, two pointers: watch the tarp cover one sack per step.
Compare with nested loops Run the nested loops on the same problem and count the pairs.
An unsorted row fools it Two pointers on an unsorted row walk past a pair that is there.
Sri’s ledger The Map finds a pair in any order, by writing things down.