I recently attended an interview in which I was asked this question:
Given start time in an array: [1, 2, 3, 2]
and their durations [3, 4, 4, 3]
Find and return the order in which the task get completed. For this example end time are : [4, 6, 7, 5]
so the value returned should be [1, 3, 4, 2]
.
My approach/solution:
Create a data-structure to represent each class as Task object having following attributes:
- Start time
- End time
- Duration
- Finish Index
Then sort the array on end time of each object. Compare each element with original array index and return the finish index in the original task order.
Please suggest any better solutions. Implementation of this approach is difficult to achieve without errors in an interview( using whiteboard and marker). what would be the easiest way to implement this, if no better solution is possible. Better solution = Better time complexity.
Finish Index
to theTask
object sound wired. This is only known after allTask
objects were created and sorted by end time. It would also prevent you to insert a newTask
inbetween two existing ones. You would need to update theFinish Index
for allTask
objects after insert position. – SubOptimal