OpenAI questions

Change Directory with Symlinks

OpenAIPhone screenMedium

Simulate the Unix cd command. Implement resolve_path(cwd, command, links), which returns the absolute path of the directory you end up in after running cd command from cwd.

Paths use / as a separator. Component names are non-empty strings with no /. cwd is an absolute, canonical path: it starts with / and contains no ., .., empty components or symbolic links.

The result always starts with /, has no ., .. or empty components, and has no trailing slash except for the root itself, which is /.

Part 1: Dots and slashes

Handle plain directories; links is empty in this part.

A command may contain . (this directory), .. (the parent directory; the root's parent is the root) and empty components from repeated or trailing slashes, such as a//b/. A command starting with / is absolute and ignores cwd; any other command is relative to cwd. An empty command stays in cwd.

  1. Example 1
    cwd
    "/foo/bar"
    links
    {}
    command
    "boo/./../doe"
    Output
    "/foo/bar/doe"

    Why: Append boo, . stays in /foo/bar/boo, .. goes back up to /foo/bar, then append doe.

  2. Example 2
    cwd
    "/a/b"
    links
    {}
    command
    "/x//y/"
    Output
    "/x/y"

    Why: The command starts with /, so it is absolute and cwd /a/b is ignored. The empty component from the double slash and the trailing slash are dropped, leaving /x/y.

Constraints

  • 1 <= len(cwd) <= 10^4
  • 0 <= len(command) <= 10^4
  • cwd is absolute and canonical (no ., .. or empty components)
  • links is empty