~/problems / Stacks / Stack: path parsing

OA: cd with ~ and symlinks

hard 3 levels ~60 min OpenAI

Level 1 Relative paths

Write cd(current_dir, destination, home_dir=None, symlinks=None): the directory you'd be in after running cd destination from current_dir and then pwd. It returns a string. You'll need home_dir from level 2 and symlinks from level 3. Ignore them for now.

In this level destination is always relative, and current_dir is an absolute, already normalized path such as /srv/app.

  • Split on /. Empty pieces (from //, or a leading or trailing slash) and . do nothing.
  • .. moves up one directory. At / it stays at / and doesn't raise an error.
  • Anything else is a directory name to step into.
  • The result is always absolute and normalized. It starts with /, has no ., .. or empty pieces, and has no trailing slash. The root is exactly "/", never "".
cd("/srv/app", "logs")             # "/srv/app/logs"
cd("/srv/app", "../lib//x/")       # "/srv/lib/x"
cd("/srv/app", "./a/b/../")        # "/srv/app/a"
cd("/srv", "../../../..")          # "/"
cd("/", "..")                      # "/"

Don't touch the real filesystem. This is pure path processing.

Show hint

keep the directory names you're currently inside as a list, and push or pop as you read each piece.

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Topic: Stack: path parsing. Resolve ., .. and symlinks with a stack.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc