Toptal | Live Interview | Minimum Shopping Time
1750

Customers come into a shop. All queued in a single line.
There are 3 cashiers. Next customer goes to the cashier who gets free.
Find when all customers will be done

Input format: Array of tuples

Each item in array is of this form [minutesSinceOpen, durationInMinutes]
minutesSinceOpen - time at which this customer enters
durationInMinutes - time taken by the customer

This needs to be solved completely in 15 minutes

Test Cases

{
   		input: [
   			[0, 7],
   			[1, 3],
   			[1, 4],
   		],
   		output: 7,
   	},
   	{
   		input: [
   			[0, 2],
   			[0, 5],
   			[1, 3],
   			[2, 2],
   		],
   		output: 5,
   	},

Solution

 function minimumShoppingTime(array) {
	// track when each queue will be free next
	const queues = {
		1: 0,
		2: 0,
		3: 0,
	}

	array.forEach(([minutesSinceOpen, durationInMinutes]) => {
		let min = Infinity
		let minIndex = 0
		for (let i = 1; i <= 3; i++) {
			if (queues[i] <= minutesSinceOpen) {
				const localMin = queues[i] + durationInMinutes
				if (localMin < min) {
					min = localMin
					minIndex = i
				}
			}
		}
		queues[minIndex] = min
	})

	return Object.values(queues).sort((a, b) => {
		if (a > b) return 1
		else return -1
	})[2]
}
Comments (5)