Similar Problems

Similar Problems not available

Simplify Path - Leetcode Solution

LeetCode:  Simplify Path Leetcode Solution

Difficulty: Medium

Topics: string stack  

Problem Statement:

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 '/'.
  • Any two directories are separated by a single slash '/'.
  • The path does not end with a trailing '/'.
  • The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')

Return the simplified canonical path.

Solution:

This problem can be solved using a stack data structure. We can first split the given string path using the '/' character as the delimiter. This will give us an array of directories, which we can then process one at a time.

We can use a stack to keep track of the directories that we want to keep in our simplified canonical path. We will iterate over the directories, and for each directory in the path, we will do the following:

  1. If the directory is a period '.', we can ignore it as it refers to the current directory.
  2. If the directory is a double period '..', we need to go up one level in the directory hierarchy. We can do this by popping the top element from the stack. If the stack is empty, we do not need to do anything as we are already at the root directory.
  3. If the directory is not a period or a double period, we can simply push it onto the stack.

After iterating over all the directories, we can pop the elements from the stack and append them to a string variable, forming the simplified canonical path.

Finally, we need to reverse the string as the stack order is in the reverse order of the path, and return the path by checking if the stack is empty or not.

Code:

class Solution: def simplifyPath(self, path: str) -> str: stack = [] for directory in path.split('/'): if directory == '.' or directory == '': continue elif directory == '..': if stack: stack.pop() else: stack.append(directory) return '/' + '/'.join(stack[::-1]) if stack else '/'

Simplify Path Solution Code

1