Problem · Heap

Priority Task Execution with Duplicate IDs

Learn this problem
MediumSnowflake logoSnowflakeFULLTIMEONSITE INTERVIEW
See Snowflake hiring insights

Problem statement

Process a finite ordered sequence of task-manager operations. The four input arrays describe the same sequence position by position.

  • For "ADD", add one occurrence carrying taskIds[i], priorities[i], and timestamps[i].
  • For "EXECUTE", select the eligible queued occurrence with the higher numeric priority, then the earlier timestamp, then the lexicographically smaller task ID.

A task ID may be added more than once. As soon as any occurrence of an ID executes, that ID is permanently completed: every other queued occurrence and every later-added occurrence with the same ID is ineligible and must be skipped.

Return one string for each "EXECUTE", in operation order. Use the selected task ID when one exists, and use the empty string to encode null when no eligible task remains. Task IDs are nonempty, so the encoding is unambiguous.

Function

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

Examples

Example 1

operations = ["ADD","ADD","ADD","EXECUTE","EXECUTE","EXECUTE"]taskIds = ["A","B","A","","",""]priorities = [2,5,9,0,0,0]timestamps = [10,10,20,0,0,0]return = ["A","B",""]

The priority-9 occurrence executes ID A, which permanently suppresses the other queued A. Then B executes, and the final request has no eligible task.

Example 2

operations = ["ADD","ADD","ADD","EXECUTE","EXECUTE","ADD","EXECUTE"]taskIds = ["z","a","m","","","m",""]priorities = [3,3,3,0,0,100,0]timestamps = [8,8,6,0,0,1,0]return = ["m","a","z"]

ID m wins the first equal-priority comparison by timestamp. ID a then wins the equal-priority and equal-timestamp tie against z. The later priority-100 occurrence of completed ID m is skipped, so z executes last.

Example 3

operations = ["EXECUTE","ADD","EXECUTE","ADD","EXECUTE"]taskIds = ["","X","","X",""]priorities = [0,1,0,10,0]timestamps = [0,5,0,0,0]return = ["","X",""]

The first execution is empty. After X executes, adding X again cannot make that completed ID eligible.

Constraints

  • 1 <= operations.length <= 200000.
  • All four input arrays have the same length.
  • Every operation is exactly "ADD" or "EXECUTE".
  • At each "ADD", the task ID is a nonempty string of at most 50 ASCII letters or digits, and priority and timestamp fit in signed 32-bit integers.
  • Fields at an "EXECUTE" position are ignored.
  • Task IDs may repeat before or after the ID executes.

More Snowflake problems

drafts saved locally
public String[] executeTasksWithDuplicateIds(String[] operations, String[] taskIds, int[] priorities, int[] timestamps) {
    // Write your code here.
}
operations["ADD","ADD","ADD","EXECUTE","EXECUTE","EXECUTE"]
taskIds["A","B","A","","",""]
priorities[2,5,9,0,0,0]
timestamps[10,10,20,0,0,0]
expected["A", "B", ""]
checking account