1.Coding
“Given a list of stock updates, return the latest quantity for each product. Updates can arrive out of order.”
Choose Coding Interview and capture the written prompt with screenshot analysis. Keep the latest update for each product in a map keyed by product ID. In this example, assume the first update wins when timestamps match. Ask Hiintly how the result changes if the interviewer wants the last update to win ties instead.
function latestQuantities(updates) {
const latest = new Map();
for (const [id, quantity, timestamp] of updates) {
const current = latest.get(id);
if (!current || timestamp > current.timestamp) {
latest.set(id, { quantity, timestamp });
}
}
return Object.fromEntries(
Array.from(latest, ([id, { quantity }]) => [id, quantity]),
);
}
// Each update is [product ID, quantity, timestamp].
const updates = [
['A', 4, 8],
['A', 6, 12], // Newer: replace quantity 4.
['B', 3, 9],
['A', 9, 10], // Older: keep quantity 6.
['A', 7, 12], // Same timestamp: keep quantity 6.
];
console.log(JSON.stringify(latestQuantities(updates)));
// {"A":6,"B":3}The scan takes O(n) expected time for n updates and uses O(k) space for k distinct products.
What if the interviewer asks for the quantity at a specific time?
A map with only the latest update discards history. Compare keeping sorted updates per product, which supports a binary search for the latest update at or before the requested time, with scanning all updates for each lookup. Ask Hiintly to vary the workload: many reads favor indexing, while frequent out-of-order writes add a cost to maintaining the sorted history.
Work through coding interview problems