FastPrepResilient Fake API Client
Problem · String

Resilient Fake API Client

Learn this problem
MediumTesla logoTeslaFULLTIMEPHONE SCREEN

Problem statement

A fake API provides one response per attempt through parallel arrays statuses and bodies. Process at most maxAttempts responses in order.

  • A status from 200 through 299 is successful. Parse its body using the closed JSON grammar below. Return SUCCESS: followed by the object with keys sorted lexicographically, or JSON_ERROR when parsing fails.
  • Status 429 and every status from 500 through 599 are retryable while attempts remain.
  • Every other status is terminal; return HTTP_n, where n is the status.
  • If every permitted attempt is retryable, return EXHAUSTED.

An accepted body is exactly {} or a whitespace-free object such as {"b":"two","a":"1"}. Keys are unique, nonempty strings. Values may be empty. Key and value characters are limited to ASCII letters, digits, underscores, and hyphens. Escapes, nesting, arrays, numbers, booleans, null, and whitespace are invalid.

Function

handleResponses(statuses: int[], bodies: String[], maxAttempts: int) → String

Examples

Example 1

statuses = [429,503,200]bodies = ["ignored","ignored","{\"b\":\"two\",\"a\":\"1\"}"]maxAttempts = 3return = "SUCCESS:{\"a\":\"1\",\"b\":\"two\"}"

The client retries the rate limit and server failure. The successful body is valid and its keys are canonicalized.

Example 2

statuses = [500,429,503,200]bodies = ["","","","{}"]maxAttempts = 3return = "EXHAUSTED"

Only three attempts are permitted, and all three observed statuses are retryable. The later success is not consumed.

Example 3

statuses = [200]bodies = ["{\"a\":  \"b\"}"]maxAttempts = 1return = "JSON_ERROR"

Whitespace is outside the accepted grammar, so a successful HTTP status still produces a parse error.

Constraints

  • 1 <= statuses.length == bodies.length <= 100000.
  • 1 <= maxAttempts <= statuses.length.
  • 100 <= statuses[i] <= 599.
  • 0 <= bodies[i].length <= 1000.
  • A body is parsed only for the first successful status.
  • Accepted object keys are unique and the total output fits in memory.

More Tesla problems

drafts saved locally
public String handleResponses(int[] statuses, String[] bodies, int maxAttempts) {
    // Write your solution here.
}
statuses[429,503,200]
bodies["ignored","ignored","{\"b\":\"two\",\"a\":\"1\"}"]
maxAttempts3
expected"SUCCESS:{\"a\":\"1\",\"b\":\"two\"}"
checking account