Problem · String

Parse Query String

MediumAirbnbFULLTIMEPHONE SCREEN

Given a GET request query string, parse the key-value pairs into a normalized string serialization.

The input may start with ?. Parameters are separated by &. A parameter has one of the following forms:

  • key=value — stores the parsed value for key.
  • !key — stores the boolean value true for key. The ! prefix must appear at the start of a parameter (i.e., immediately after & or after the leading ?). The forms !!key and !key=value are not valid inputs.

Keys may repeat. If a key appears more than once, all of its values are preserved in insertion order.

Value types

  • Integer — a sequence of digit characters, e.g., 42.
  • Boolean — the literal string true or false.
  • Quoted string — a value surrounded by double-quote characters, e.g., "abc". The surrounding double quotes are removed when storing the value.
  • List literal — a value of the form [item1,item2,...] where items are separated by commas with no surrounding whitespace. Each item is treated as an individual value for the key, in order. Items within a list literal are plain (unquoted) strings. An empty list [] contributes no values for the key.

Output format

Return a String[] with one entry per distinct key, in the order the keys first appear in the query string. Each entry has one of the following forms:

  • key=value if the key has exactly one associated value.
  • key=value1|value2|... if the key has two or more associated values, listed in insertion order.
Examples
01 · Example 1
query = "?key1=1&key1=\"abc\"&key2=value1&!isBooleanField"
return = ["key1=1|abc","key2=value1","isBooleanField=true"]

key1 appears twice, so both values are preserved. The boolean shorthand !isBooleanField stores true.

02 · Example 2
query = "page=2&active=false&tags=[red,blue]&page=3"
return = ["page=2|3","active=false","tags=red|blue"]
The list literal [red,blue] expands into two separate values red and blue for the key tags. Because page appears twice (values 2 and 3), its entry uses the pipe-separated multi-value format. Keys are ordered by first appearance: page, active, tags.
Constraints

  • 0 <= query.length <= 105
  • Keys are non-empty and contain only letters, digits, underscores, or hyphens.
  • Values do not contain unescaped &.
  • The !key boolean shorthand appears only as a standalone parameter (i.e., the parameter contains no = sign and the key is prefixed with exactly one !).
  • List literal items are separated by commas with no whitespace; items are plain strings (not quoted).
  • Inputs are well-formed; invalid forms such as !!key, !key=value, or nested list literals do not appear.

More Airbnb problems
drafts saved locally
public String[] parseQueryString(String query) {
    // write your code here
}
query"?key1=1&key1=\"abc\"&key2=value1&!isBooleanField"
expected["key1=1|abc", "key2=value1", "isBooleanField=true"]
checking account