Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Normalise a Unix-style absolute path: collapse repeated slashes, drop '.', and let '..' go up one directory (never above root).

Problem: Normalise a Unix-style absolute path: collapse repeated slashes, drop '.', and let '..' go up one directory (never above root).
def simplify(path):
    st = []
    for part in path.split("/"):
        if part == "..":
            if st: st.pop()
        elif part and part != ".":
            st.append(part)
    return "/" + "/".join(st)
print(simplify("/srv/./logs//old/../app/"), simplify("/../.."), simplify("/a/.../b"))
What is printed?
  1. A. /srv/logs/old/app / /a/b
  2. B. /srv/./logs/app / /a/b
  3. C. /srv/logs/app /.. /a/.../b
  4. D. /srv/logs/app / /a/.../b

Correct answer: D. /srv/logs/app / /a/.../b

Splitting on '/' yields empty strings for repeated or trailing slashes (skipped), '.' (skipped) and '..' (pop if possible). "old" is pushed and then popped by '..'. '..' at the root does nothing, so "/../.." is "/". Three dots is an ordinary directory name, not a navigation token. O(n).

More Coding Interview Problems questions

Exams that ask this topic