Problem · String
Parse Query String
Learn this problemProblem statement
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=valuestores the parsed value forkey.!keystores the boolean valuetrueforkey. The prefix must appear at the start of a parameter. The forms!!keyand!key=valueare invalid.
Keys may repeat. Preserve all values in insertion order.
Value types
- Integer: a sequence of digits.
- Boolean:
trueorfalse. - Quoted string: remove the surrounding double quotes.
- List literal: expand
[item1,item2,...]into separate values in order.
Practice rule: An empty list [] still creates the key but adds no values. If that key receives no other values, serialize it as key=.
Return one entry per distinct key in first-appearance order. Use key=value for one value and key=value1|value2|... for multiple values.
Function
parseQueryString(query: String) → String[]Examples
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.
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
!keyboolean 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.