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=valuesplits 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 valuetrue. - 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"]}.
- Example 1
- url
"?a=b&c=d"- Output
{"a":"b","c":"d"}
Why: Both keys appear once, so each maps to a plain string.
- Example 2
- url
"?sd&a=b&a=c&a=d&sd"- Output
{"sd":[true,true],"a":["b","c","d"]}
Why:
sdhas no=, so its value istrue.aappears three times, so its values are collected in order:["b", "c", "d"].sdappears twice with no value each time, giving[true, true].
Constraints
1 <= len(url) <= 10^5urlcontains 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.