Amazon Interview Question
Software Engineer / DevelopersCountry: -
Interview Type: Phone Interview
Heap might not work, as removing an only max or min which ever condition is used to build the heap is allowed to be removed not any element.
Hash would be an ideal data structure. Park the car sequentially in the hash array and return the index and the car number. while taking the car way just pass the car number and index to the car away. parking O(n) and removing O(1)
Stack:
Slot # = 1 2 3 4 5… n
All slots are free currently....
FreeStack = n n-1 n-2 n-3….. 1 // Note its the reverse of Slot # which are free
-------------------------------- Arrivals----------------
1st car – Slot 1
FreeStack.Pop()
.
.
Nth car – Slot N
FreeStack.Pop()
ParkingFull =1;
------------------------------------------Car Leaving----------------------------------------------
Car at Slot #‘i1’ leaves:
FreeStack.Push(i1); ParkingFull =0;
.
.
Car Slot # ‘i8’ leaves:
FreeStack.Push(i8)
-------------------------------------------New car Arrives----------------------------------------
Goes to the Slot # pointed by the top of the stack (FreeStack.Top()).
FreeStack.Push();
O(1) Complexity..
How about a link list of free parking numbers. Whenever we need a parking, delete the first/last node and whenever we get a parking back, add it at the front/end.
- Anonymous November 11, 2011