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?- A. /srv/logs/old/app / /a/b
- B. /srv/./logs/app / /a/b
- C. /srv/logs/app /.. /a/.../b
- 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
- Problem: Find the minimum number of brackets to insert so that a string of '(' and ')' becomes balanced. python def minadd(s): open = add…
- Problem: Parcels 1..5 are pushed onto a loading stack in that order (pops may happen at any time). Decide whether a given pop order is…
- Problem: People queue at a single counter; person i wants t[i] tickets, buys one per second and, if still needing more, goes to the back…
- Problem: Regroup a linked list so that all nodes at odd positions (1st, 3rd, …) come first, followed by the even positions, keeping…
- Problem: Rotate a linked list to the right by k places (k may exceed the length). python class Node: def init(self, v, nxt=None): self.v…
- Problem: Each rescue boat carries at most two people and at most limit kg. Find the minimum number of boats (greedy: pair the heaviest…