Simplify Path — Day 70(Python)

Image for post
Image for post
Photo by John Thomas on Unsplash

Today’s question is based on stacks. It is a common question among Facebook interviewers. I took this problem statement from February’s daily leetcode challenge. Let us look into the problem statement.

71. Simplify Path

Given a string path, which is an absolute path (starting with a slash '/') to a file or directory in a Unix-style file system, convert it to the simplified canonical path.

In a Unix-style file system, a period '.' refers to the current directory, a double period '..' refers to the directory up a level, and any multiple consecutive slashes (i.e. '//') are treated as a single slash '/'. For this problem, any other format of periods such as '...' are treated as file/directory names.

The canonical path should have the following format:

  • The path starts with a single slash '/'.

Return the simplified canonical path.

The first task is to split the given input based on “/”. When we split the path, we can get separate folder names and “.” as well as “..” which represent the current directory and previous directory respectively.

We need a stack that keeps track of which folders need to be visited and what folders have to be skipped in the canonical path.

After we have finished splits the input path, we would have to compare each word with few things. If the word is empty or a “.”, it means we will be in the current folder itself. We would not be adding or removing any folder. If the current word is “..” we will have to pop the topmost folder from the stack. If the word is none of the above words, then we will be pushed into the stack.

Let us look into the code snippet.

class SimplePathFinder:
def simplifyPath(self, path: str) -> str:
path_split = path.split('/')
output = ""
stack = []
for words in path_split:
if words == "" or words == ".":
continue
elif words == "..":
if stack:
stack.pop()
else:
stack.append(words)

for word in stack:
output = output + "/" + word
return output if output else "/"

Complexity analysis.

Time Complexity

We are visiting each folder in the path after we split based on “/”. Hence the time complexity is O(N), where N is the number of words.

Space Complexity.

We are using a stack inorder to store the names of the folders. Hence the space complexity is O(N), where N is the number of folders.

Software Engineer. Find me @ www.linkedin.com/in/annamariya-jt

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store