FastPrepFirst Successful Concurrent API Result Before a Timeout

First Successful Concurrent API Result Before a Timeout

Apple logoApple● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

All backend calls start concurrently at time 0. Call i completes after latencies[i] milliseconds, succeeds exactly when succeeds[i] is true, and yields values[i].

Return the value of the successful call with the smallest completion time that finishes no later than the shared timeoutMs. If several successful calls finish together, choose the smaller input index. Return the empty string when no successful call finishes before the timeout.

Function

firstSuccessfulResult(latencies: int[], succeeds: boolean[], values: String[], timeoutMs: int) → String

Examples

Example 1

latencies = [120,40,75]succeeds = [true,false,true]values = ["slow","error","winner"]timeoutMs = 100return = "winner"

The call at 40 ms fails. The call at 75 ms is the first success before the timeout.

Example 2

latencies = [50,50,10]succeeds = [true,true,false]values = ["left","right","bad"]timeoutMs = 50return = "left"

The two successful calls tie at the inclusive timeout, so the smaller index wins.

Example 3

latencies = [5,90]succeeds = [false,true]values = ["x","y"]timeoutMs = 80return = ""

The early call fails and the successful call completes too late.

Constraints

  • 1 <= latencies.length <= 100000.
  • succeeds.length = values.length = latencies.length.
  • 0 <= latencies[i], timeoutMs <= 10^9.
  • Each value contains at most 200 visible ASCII characters.

More Apple problems

See Apple hiring insights
public String firstSuccessfulResult(int[] latencies, boolean[] succeeds, String[] values, int timeoutMs) {
    // Write your solution here.
}
latencies[120,40,75]
succeeds[true,false,true]
values["slow","error","winner"]
timeoutMs100
expected"winner"
Checking account…