Problem · Heap

Execute Tasks by Priority

Learn this problem
MediumSnowflake logoSnowflakeFULLTIMEONSITE INTERVIEW
See Snowflake hiring insights

Problem statement

Process a finite sequence of task-manager operations.

  • An add operation inserts one task with its identifier, integer priority, and timestamp.
  • An execute operation removes and returns the pending task with the highest priority.

For this exercise, assume a larger integer means a higher priority. Break equal-priority ties by earlier timestamp, then by smaller task identifier. Task identifiers are unique, and a completed task cannot execute again. Return one value for each execute operation, in operation order; return -1 when no task is pending.

Function

executeTasks(operations: String[], taskIds: int[], priorities: int[], timestamps: int[]) → int[]

Examples

Example 1

operations = ["add","add","execute","execute","execute"]taskIds = [101,102,0,0,0]priorities = [2,5,0,0,0]timestamps = [10,10,0,0,0]return = [102,101,-1]

Task 102 has the higher priority, then task 101 runs. The final execution finds no pending task.

Example 2

operations = ["add","add","add","execute","execute"]taskIds = [9,4,7,0,0]priorities = [3,3,3,0,0]timestamps = [8,8,6,0,0]return = [7,4]

Task 7 has the earliest timestamp. Tasks 4 and 9 then tie on timestamp, so the smaller identifier wins.

Constraints

  • 1 <= operations.length <= 10^5
  • All four input arrays have the same length.
  • Each operation is add or execute.
  • Task identifiers used by add are unique positive integers.
  • Fields at an execute position are ignored.

More Snowflake problems

drafts saved locally
public int[] executeTasks(String[] operations, int[] taskIds, int[] priorities, int[] timestamps) {
    // Your code here
}
operations["add","add","execute","execute","execute"]
taskIds[101,102,0,0,0]
priorities[2,5,0,0,0]
timestamps[10,10,0,0,0]
expected[102,101,-1]
checking account