Problem · Array

Parse Command-Line Tokens

Learn this problem
MediumSamsara logoSamsaraFULLTIMEONSITE INTERVIEW

Problem statement

Parse an already-tokenized command line tokens and return occurrence-ordered rows.

  • A long option begins with --; a short option begins with one -.
  • --name=value and -n=value produce [name, value].
  • An option without = consumes the next token as its value only when that token does not begin with -; otherwise its value is true.
  • The token -- ends option parsing and is not returned. Every later token is positional.
  • A positional token produces ["", token].

Preserve option and positional occurrences exactly; do not merge repeated names.

Function

parseCommandLine(tokens: String[]) → String[][]

Examples

Example 1

tokens = ["--host=api","-p","8080","file.txt"]return = [["host","api"],["p","8080"],["","file.txt"]]

The first option uses equals, the short option consumes its following value, and the filename is positional.

Example 2

tokens = ["--verbose","--","-x","tail"]return = [["verbose","true"],["","-x"],["","tail"]]

The flag has value true; after the terminator, option-looking tokens are positional.

Constraints

  • 0 <= tokens.length <= 100000.
  • Every token is nonempty.
  • Option names before = are nonempty.

More Samsara problems

drafts saved locally
public String[][] parseCommandLine(String[] tokens) {
    // Write your code here.
}
tokens["--host=api","-p","8080","file.txt"]
expected[["host", "api"], ["p", "8080"], ["", "file.txt"]]
checking account