Airbnb questions

URL Query-String Parser

AirbnbPhone screenEasy

You are parsing the query string of a URL into a map. The query string is everything after the first ?. It is a list of parameters separated by &, and each parameter is either key=value or just key.

Write parse_query(url).

Part 1: Keys and values

Return a map built from the query string:

  • A parameter key=value splits at its first =; the value is the text after it, which may be empty or contain more = characters.
  • A parameter that is only a key, with no =, has the value true.
  • When a key appears more than once, its value is a list of every value in order of appearance. A key that appears once is not wrapped in a list.
  • Empty parameters (from && or a leading or trailing &) and parameters with an empty key (such as =x) are ignored.
  • A URL with no ?, or nothing after it, gives an empty map.

For example, "?a=b&c=d" gives {"a": "b", "c": "d"}, "?sd" gives {"sd": true}, and "?a=b&a=c&a=d" gives {"a": ["b", "c", "d"]}.

  1. Example 1
    url
    "?a=b&c=d"
    Output
    {"a":"b","c":"d"}

    Why: Both keys appear once, so each maps to a plain string.

  2. Example 2
    url
    "?sd&a=b&a=c&a=d&sd"
    Output
    {"sd":[true,true],"a":["b","c","d"]}

    Why: sd has no =, so its value is true. a appears three times, so its values are collected in order: ["b", "c", "d"]. sd appears twice with no value each time, giving [true, true].

Constraints

  • 1 <= len(url) <= 10^5
  • url contains only ASCII letters, digits and the characters / : . ? & = - _
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question