FastPrepFinal Task From Unordered Server-Split Logs

Final Task From Unordered Server-Split Logs

Google logoGoogle● HardNEW GRADONSITE INTERVIEW
Learn

Problem statement

There are serverCount tasks numbered from 0 to serverCount - 1. Initially server 0 stores all tasks in order and every other server is empty.

A transfer [from,to] moves the back half of from's current contiguous task block to the empty server to, preserving order. Transfers continue until every server stores one task. You receive all transfers in arbitrary order.

The input is guaranteed to describe one valid complete split process, and serverCount is a power of two. Return the final task number stored on serverId.

Function

finalTaskForServer(serverCount: int, transfers: int[][], serverId: int) → int

Examples

Example 1

serverCount = 4transfers = [[0,2],[2,1],[0,3]]serverId = 1return = 3

The process ends with servers 0,3,2,1 holding tasks 0,1,2,3, respectively.

Example 2

serverCount = 4transfers = [[2,1],[0,3],[0,2]]serverId = 2return = 2

Log order does not matter. Server 2 retains task 2.

Example 3

serverCount = 8transfers = [[4,5],[0,1],[2,3],[0,4],[6,7],[0,2],[4,6]]serverId = 7return = 7

The parent chain 0 → 4 → 6 → 7 contributes block offsets 4 + 2 + 1.

Constraints

  • 2 <= serverCount <= 1048576 and it is a power of two.
  • transfers.length == serverCount - 1.
  • Every transfer contains two distinct server IDs in [0,serverCount-1].
  • The transfers form a valid complete process rooted at server 0.
  • 0 <= serverId < serverCount.

More Google problems

See Google hiring insights
public int finalTaskForServer(int serverCount, int[][] transfers, int serverId) {
    // Write your code here.
}
serverCount4
transfers[[0,2],[2,1],[0,3]]
serverId1
expected3
Checking account…