Resolve a cd Path Against the Current Directory
MetaSoftware Engineer · OnsiteLast updated
Implement simplified Unix-style cd path resolution for absolute and relative inputs containing repeated separators, dot components, and parent-directory steps. The challenge focuses on component semantics, root boundaries, empty arguments, exact normalization, and linear processing of long paths without filesystem lookups.
Resolve a cd Path Against the Current Directory
Implement path resolution for a simplified Unix-like cd command.
cwd is a normalized absolute path. argument may be absolute or relative and may contain repeated / separators, . components, and .. components. Resolving .. at the root keeps the result at the root. Return a normalized absolute path with no trailing slash unless the result is /.
Do not implement symbolic links, environment variables, ~, wildcard expansion, or filesystem existence checks.
Function Signature
def resolve_cd(cwd: str, argument: str) -> str:
...
Constraints
1 <= len(cwd), len(argument) <= 200_000cwdstarts with/and is already normalized.- Empty components created by repeated separators are ignored; every ordinary component contains non-slash characters.
- An empty string argument leaves the current directory unchanged. Any argument beginning with
/starts from the root, so/and////both resolve to/.
Examples
Input: cwd = "/home/alex/projects", argument = "../docs/./api"
Output: "/home/alex/docs/api"
Input: cwd = "/a/b", argument = "/x//y/../../z"
Output: "/z"
Input: cwd = "/", argument = "../../../tmp"
Output: "/tmp"
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.