VOOZH about

URL: https://www.geeksforgeeks.org/dsa/simplify-directory-path-unix-like/

⇱ Simplify the directory path (Unix like) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Simplify the directory path (Unix like)

Last Updated : 2 Nov, 2023

Given an absolute path for a file (Unix-style), simplify it. Note that absolute path always begin with ‘/’ ( root directory ), a dot in path represent current directory and double dot represents parent directory.

Examples: 

"/a/./" --> means stay at the current directory 'a'
"/a/b/.." --> means jump to the parent directory
from 'b' to 'a'
"////" --> consecutive multiple '/' are a valid
path, they are equivalent to single "/".
Input : /home/
Output : /home
Input : /a/./b/../../c/
Output : /c
Input : /a/..
Output:/
Input : /a/../
Output : /
Input : /../../../../../a
Output : /a
Input : /a/./b/./c/./d/
Output : /a/b/c/d
Input : /a/../.././../../.
Output:/
Input : /a//b//c//////d
Output : /a/b/c/d

Note: The given input will always have a valid absolute path.

Approach 1: By looking at examples we can see that the above simplification process just behaves like a stack. Whenever we encounter any file's name, we simply push it into the stack. when we come across " . " we do nothing. When we find ".." in our path, we simply pop the topmost element as we have to jump back to parent's directory. 

When we see multiple "////" we just ignore them as they are equivalent to one single "/". After iterating through the whole string the elements remaining in the stack is our simplified absolute path. We have to create another stack to reverse the elements stored inside the original stack and then store the result inside a string.

Implementation:


Output
/c

Time Complexity: O(length of string).

Approach 2:

  1. In approach 1, the directories so formed, are first pushed into the stack and then the stack is reversed to form the canonical path.
  2. The only optimization here is to reduce the number of stack operations and this can be done by using vectors in place of a stack.
  3. Push and pop operations can be done in vector using push_back() and pop_back() functions respectively and the canonical path can be generated by simply traversing the vector from left to right.

Below is the implementation of approach 1 using vectors.


Output
/c

Time Complexity:O(length of string).

Using Queue:

  • If there are two dots then if size of deque is greater than 0 than remove one directory.
  • If there is only one dot then ignore it.
  • If there are more than two dots than consider it as directory name and put it into deque.
  • Ignore all slashes and add in front at the end while popping out directories from deque.

Output
/c

Time Complexity: O(length of the string).
Space Complexity: O(length of string).

This article is contributed by .

Comment
Article Tags:
Article Tags: