If this was an interview question, then it most likely goes towards sorting and data structure.
First of all, take your mind off the clock and the planner. No problem here. It extinguishes every time interval (say, the second), so every second you will need to find out what tasks to perform.
So you really need a data structure where for x
elapsed seconds you can find out what tasks to perform. What else do you need? The problem says “getting tasks”, so you should also insert new objects at some point y
. It is also probably wise to delete completed tasks. Then, I don’t think it is reasonable to check only t == x
for equality, since it may be that tast took longer than the time interval. If the tasks to be performed are deleted during execution, then you can safely perform all tasks with t <= x
.
To summarize, you will need the following operations (I assume that time is a long integer):
insertTask(int time, Task t)
Collection<Task> getTasksScheduledBefore(int time)
removeTasksScheduledBefore(t)
What should be used for this? The answer to this question depends on where you have the interview. :)
The simplest would be to use something like TreeMap>:
insertTask
trivial with put
getTasksScheduledBefore
- headMap(t).values()
removeTasksScheduledBefore
- headMap(t).clear()
If you are interviewing Google and Co., then they are likely to come up with something that makes you come up with their own data structures. The trees here are good, but with some assumptions, you can also do tricks with arrays, linked lists, and so on. For example, if you only need to plan ahead one day, then Set<Task>[86400]
will also be great. :)
With Google, you can also keep track of things like whole overflows, etc. You may need to use BigInteger
instead of long
. Make sure that you check your assumptions with the interviewer (for example, this time is really a whole, how you should respond to invalid values, etc.).