Open In App

Simplify the directory path (Unix like)

Last Updated : 02 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




/* C++ program to simplify a Unix
   styled absolute path of a file */
#include <bits/stdc++.h>
using namespace std;
 
// function to simplify a Unix - styled
// absolute path
string simplify(string A)
{
    // stack to store the file's names.
    stack<string> st;
 
    // temporary string which stores the extracted
    // directory name or commands("." / "..")
    // Eg. "/a/b/../."
    // dir will contain "a", "b", "..", ".";
    string dir;
 
    // contains resultant simplifies string.
    string res;
 
    // every string starts from root directory.
    res.append("/");
 
    // stores length of input string.
    int len_A = A.length();
 
    for (int i = 0; i < len_A; i++) {
 
        // we will clear the temporary string
        // every time to accommodate new directory
        // name or command.
        dir.clear();
 
        // skip all the multiple '/' Eg. "/////""
        while (A[i] == '/')
            i++;
 
        // stores directory's name("a", "b" etc.)
        // or commands("."/"..") into dir
        while (i < len_A && A[i] != '/') {
            dir.push_back(A[i]);
            i++;
        }
 
        // if dir has ".." just pop the topmost
        // element if the stack is not empty
        // otherwise ignore.
        if (dir.compare("..") == 0) {
            if (!st.empty())
                st.pop();           
        }
 
        // if dir has "." then simply continue
        // with the process.
        else if (dir.compare(".") == 0)
            continue;
         
        // pushes if it encounters directory's
        // name("a", "b").
        else if (dir.length() != 0)
            st.push(dir);       
    }
 
    // a temporary stack  (st1) which will contain
    // the reverse of original stack(st).
    stack<string> st1;
    while (!st.empty()) {
        st1.push(st.top());
        st.pop();
    }
 
    // the st1 will contain the actual res.
    while (!st1.empty()) {
        string temp = st1.top();
         
        // if it's the last element no need
        // to append "/"
        if (st1.size() != 1)
            res.append(temp + "/");
        else
            res.append(temp);
 
        st1.pop();
    }
 
    return res;
}
 
// Driver code.
int main()
{
    // absolute path which we have to simplify.
    string str("/a/./b/../../c/");
    string res = simplify(str);
    cout << res;
    return 0;
}


Java





Python3




# Python program to simplify a Unix
# styled absolute path of a file
 
# function to simplify a Unix - styled
# absolute path
 
 
def simplify(A):
    # stack to store the file's names.
    st = []
 
    # temporary string which stores the extracted
    # directory name or commands("." / "..")
    # Eg. "/a/b/../."
    # dir will contain "a", "b", "..", ".";
    dir = ""
 
    # contains resultant simplifies string.
    res = ""
 
    # every string starts from root directory.
    res += "/"
 
    # stores length of input string.
    len_A = len(A)
    i = 0
    while i < len_A:
 
        # we will clear the temporary string
        # every time to accommodate new directory
        # name or command.
        dir_str = ""
 
        # skip all the multiple '/' Eg. "##/""
        while (i < len_A and A[i] == '/'):
            i += 1
 
        # stores directory's name("a", "b" etc.)
        # or commands("."/"..") into dir
        while (i < len_A and A[i] != '/'):
            dir_str += A[i]
            i += 1
 
        # if dir has ".." just pop the topmost
        # element if the stack is not empty
        # otherwise ignore.
        if dir_str == "..":
            if len(st):
                st.pop()
 
        # if dir has "." then simply continue
        # with the process.
        elif dir_str == '.':
            continue
 
        # pushes if it encounters directory's
        # name("a", "b").
        elif len(dir_str) > 0:
            st.append(dir_str)
 
        i += 1
 
    # a temporary stack (st1) which will contain
    # the reverse of original stack(st).
    st1 = []
    while len(st):
        st1.append(st[-1])
        st.pop()
 
    # the st1 will contain the actual res.
    while len(st1):
        temp = st1[-1]
 
        # if it's the last element no need
        # to append "/"
        if (len(st1) != 1):
            res += (temp + "/")
        else:
            res += temp
        st1.pop()
 
    return res
 
 
# Driver code.
 
# absolute path which we have to simplify.
string = "/a/./b/../../c/"
res = simplify(string)
print(res)
 
# This code is contributed by ankush_953


C#





Javascript




<div id="highlighter_882263" class="syntaxhighlighter nogutter  "><table border="0" cellpadding="0" cellspacing="0"><tbody><tr><td class="code"><div class="container"><div class="line number1 index0 alt2"><code class="plain"><script></code></div><div class="line number2 index1 alt1"><code class="undefined spaces">    </code><code class="comments">// Javascript program to simplify a Unix</code></div><div class="line number3 index2 alt2"><code class="undefined spaces">    </code><code class="comments">// styled absolute path of a file</code></div><div class="line number4 index3 alt1"><code class="undefined spaces">    </code> </div><div class="line number5 index4 alt2"><code class="undefined spaces">    </code><code class="comments">// function to simplify a Unix - styled</code></div><div class="line number6 index5 alt1"><code class="undefined spaces">    </code><code class="comments">// absolute path</code></div><div class="line number7 index6 alt2"><code class="undefined spaces">    </code><code class="keyword">function</code> <code class="plain">simplify(A)</code></div><div class="line number8 index7 alt1"><code class="undefined spaces">    </code><code class="plain">{</code></div><div class="line number9 index8 alt2"><code class="undefined spaces">        </code><code class="comments">// Stack to store the file's names.</code></div><div class="line number10 index9 alt1"><code class="undefined spaces">        </code><code class="plain">let st = [];</code></div><div class="line number11 index10 alt2"><code class="undefined spaces"> </code> </div><div class="line number12 index11 alt1"><code class="undefined spaces">        </code><code class="comments">// temporary String which stores the extracted</code></div><div class="line number13 index12 alt2"><code class="undefined spaces">        </code><code class="comments">// directory name or commands("." / "..")</code></div><div class="line number14 index13 alt1"><code class="undefined spaces">        </code><code class="comments">// Eg. "/a/b/../."</code></div><div class="line number15 index14 alt2"><code class="undefined spaces">         </code> </div><div class="line number16 index15 alt1"><code class="undefined spaces">        </code><code class="comments">// contains resultant simplifies String.</code></div><div class="line number17 index16 alt2"><code class="undefined spaces">        </code><code class="plain">let res = </code><code class="string">""</code><code class="plain">;</code></div><div class="line number18 index17 alt1"><code class="undefined spaces"> </code> </div><div class="line number19 index18 alt2"><code class="undefined spaces">        </code><code class="comments">// every String starts from root directory.</code></div><div class="line number20 index19 alt1"><code class="undefined spaces">        </code><code class="plain">res += </code><code class="string">"/"</code><code class="plain">;</code></div><div class="line number21 index20 alt2"><code class="undefined spaces"> </code> </div><div class="line number22 index21 alt1"><code class="undefined spaces">        </code><code class="comments">// stores length of input String.</code></div><div class="line number23 index22 alt2"><code class="undefined spaces">        </code><code class="plain">let len_A = A.length;</code></div><div class="line number24 index23 alt1"><code class="undefined spaces"> </code> </div><div class="line number25 index24 alt2"><code class="undefined spaces">        </code><code class="keyword">for</code> <code class="plain">(let i = 0; i < len_A; i++)</code></div><div class="line number26 index25 alt1"><code class="undefined spaces">        </code><code class="plain">{</code></div><div class="line number27 index26 alt2"><code class="undefined spaces"> </code> </div><div class="line number28 index27 alt1"><code class="undefined spaces">            </code><code class="comments">// we will clear the temporary String</code></div><div class="line number29 index28 alt2"><code class="undefined spaces">            </code><code class="comments">// every time to accommodate new directory</code></div><div class="line number30 index29 alt1"><code class="undefined spaces">            </code><code class="comments">// name or command.</code></div><div class="line number31 index30 alt2"><code class="undefined spaces">            </code><code class="comments">// dir will contain "a", "b", "..", ".";</code></div><div class="line number32 index31 alt1"><code class="undefined spaces">            </code><code class="plain">let dir = </code><code class="string">""</code><code class="plain">;</code></div><div class="line number33 index32 alt2"><code class="undefined spaces"> </code> </div><div class="line number34 index33 alt1"><code class="undefined spaces">            </code><code class="comments">// skip all the multiple '/' Eg. "/////""</code></div><div class="line number35 index34 alt2"><code class="undefined spaces">            </code><code class="keyword">while</code> <code class="plain">(i < len_A && A[i] == '/</code><code class="string">')</code></div><div class="line number36 index35 alt1"><code class="undefined spaces">                </code><code class="string">i++;</code></div><div class="line number37 index36 alt2"><code class="undefined spaces"> </code> </div><div class="line number38 index37 alt1"><code class="undefined spaces">            </code><code class="string">// stores directory'</code><code class="plain">s name("a</code><code class="string">", "</code><code class="plain">b</code><code class="string">" etc.)</code></div><div class="line number39 index38 alt2"><code class="undefined spaces">            </code><code class="string">// or commands("</code><code class="plain">.</code><code class="string">"/"</code><code class="plain">..</code><code class="string">") into dir</code></div><div class="line number40 index39 alt1"><code class="undefined spaces">            </code><code class="string">while (i < len_A && A[i] != '/')</code></div><div class="line number41 index40 alt2"><code class="undefined spaces">            </code><code class="string">{</code></div><div class="line number42 index41 alt1"><code class="undefined spaces">                </code><code class="string">dir += A[i];</code></div><div class="line number43 index42 alt2"><code class="undefined spaces">                </code><code class="string">i++;</code></div><div class="line number44 index43 alt1"><code class="undefined spaces">            </code><code class="string">}</code></div><div class="line number45 index44 alt2"><code class="undefined spaces"> </code> </div><div class="line number46 index45 alt1"><code class="undefined spaces">            </code><code class="string">// if dir has "</code><code class="plain">..</code><code class="string">" just pop the topmost</code></div><div class="line number47 index46 alt2"><code class="undefined spaces">            </code><code class="string">// element if the Stack is not empty</code></div><div class="line number48 index47 alt1"><code class="undefined spaces">            </code><code class="string">// otherwise ignore.</code></div><div class="line number49 index48 alt2"><code class="undefined spaces">            </code><code class="string">if (dir == "</code><code class="plain">..</code><code class="string">")</code></div><div class="line number50 index49 alt1"><code class="undefined spaces">            </code><code class="string">{</code></div><div class="line number51 index50 alt2"><code class="undefined spaces">                </code><code class="string">if (st.length!=0)</code></div><div class="line number52 index51 alt1"><code class="undefined spaces">                    </code><code class="string">st.pop();    </code></div><div class="line number53 index52 alt2"><code class="undefined spaces">            </code><code class="string">}</code></div><div class="line number54 index53 alt1"><code class="undefined spaces"> </code> </div><div class="line number55 index54 alt2"><code class="undefined spaces">            </code><code class="string">// if dir has "</code><code class="plain">.</code><code class="string">" then simply continue</code></div><div class="line number56 index55 alt1"><code class="undefined spaces">            </code><code class="string">// with the process.</code></div><div class="line number57 index56 alt2"><code class="undefined spaces">            </code><code class="string">else if (dir == "</code><code class="plain">.</code><code class="string">")</code></div><div class="line number58 index57 alt1"><code class="undefined spaces">                </code><code class="string">continue;</code></div><div class="line number59 index58 alt2"><code class="undefined spaces">             </code> </div><div class="line number60 index59 alt1"><code class="undefined spaces">            </code><code class="string">// pushes if it encounters directory's</code></div><div class="line number61 index60 alt2"><code class="undefined spaces">            </code><code class="string">// name("</code><code class="plain">a</code><code class="string">", "</code><code class="plain">b</code><code class="string">").</code></div><div class="line number62 index61 alt1"><code class="undefined spaces">            </code><code class="string">else if (dir.length != 0)</code></div><div class="line number63 index62 alt2"><code class="undefined spaces">                </code><code class="string">st.push(dir);</code></div><div class="line number64 index63 alt1"><code class="undefined spaces">        </code><code class="string">}</code></div><div class="line number65 index64 alt2"><code class="undefined spaces"> </code> </div><div class="line number66 index65 alt1"><code class="undefined spaces">        </code><code class="string">// a temporary Stack (st1) which will contain</code></div><div class="line number67 index66 alt2"><code class="undefined spaces">        </code><code class="string">// the reverse of original Stack(st).</code></div><div class="line number68 index67 alt1"><code class="undefined spaces">        </code><code class="string">let st1 = [];</code></div><div class="line number69 index68 alt2"><code class="undefined spaces">        </code><code class="string">while (st.length!=0)</code></div><div class="line number70 index69 alt1"><code class="undefined spaces">        </code><code class="string">{</code></div><div class="line number71 index70 alt2"><code class="undefined spaces">             </code> </div><div class="line number72 index71 alt1"><code class="undefined spaces">            </code><code class="string">st1.push(st[st.length - 1]);</code></div><div class="line number73 index72 alt2"><code class="undefined spaces">            </code><code class="string">st.pop();</code></div><div class="line number74 index73 alt1"><code class="undefined spaces">        </code><code class="string">}</code></div><div class="line number75 index74 alt2"><code class="undefined spaces">         </code> </div><div class="line number76 index75 alt1"><code class="undefined spaces"> </code> </div><div class="line number77 index76 alt2"><code class="undefined spaces">        </code><code class="string">// the st1 will contain the actual res.</code></div><div class="line number78 index77 alt1"><code class="undefined spaces">        </code><code class="string">while (st1.length!=0)</code></div><div class="line number79 index78 alt2"><code class="undefined spaces">        </code><code class="string">{</code></div><div class="line number80 index79 alt1"><code class="undefined spaces">             </code> </div><div class="line number81 index80 alt2"><code class="undefined spaces">            </code><code class="string">// if it's the last element no need</code></div><div class="line number82 index81 alt1"><code class="undefined spaces">            </code><code class="string">// to append "</code><code class="plain">/</code><code class="string">"</code></div><div class="line number83 index82 alt2"><code class="undefined spaces">            </code><code class="string">if (st1.length!= 1)</code></div><div class="line number84 index83 alt1"><code class="undefined spaces">            </code><code class="string">{</code></div><div class="line number85 index84 alt2"><code class="undefined spaces">                </code><code class="string">res += (st1[st1.length - 1] + "</code><code class="plain">/</code><code class="string">");</code></div><div class="line number86 index85 alt1"><code class="undefined spaces">                </code><code class="string">st.pop();</code></div><div class="line number87 index86 alt2"><code class="undefined spaces">            </code><code class="string">}</code></div><div class="line number88 index87 alt1"><code class="undefined spaces">            </code><code class="string">else</code></div><div class="line number89 index88 alt2"><code class="undefined spaces">            </code><code class="string">{</code></div><div class="line number90 index89 alt1"><code class="undefined spaces">                </code><code class="string">res += st1[st1.length - 1];</code></div><div class="line number91 index90 alt2"><code class="undefined spaces">                </code><code class="string">st1.pop();</code></div><div class="line number92 index91 alt1"><code class="undefined spaces">            </code><code class="string">}</code></div><div class="line number93 index92 alt2"><code class="undefined spaces">        </code><code class="string">}</code></div><div class="line number94 index93 alt1"><code class="undefined spaces">        </code><code class="string">return res;</code></div><div class="line number95 index94 alt2"><code class="undefined spaces">    </code><code class="string">}</code></div><div class="line number96 index95 alt1"><code class="undefined spaces">    </code> </div><div class="line number97 index96 alt2"><code class="undefined spaces">    </code><code class="string">// absolute path which we have to simplify.</code></div><div class="line number98 index97 alt1"><code class="undefined spaces">    </code><code class="string">let str = ("</code><code class="plain">/a/./b/../../c/");</code></div><div class="line number99 index98 alt2"><code class="undefined spaces">    </code><code class="plain">let res = simplify(str);</code></div><div class="line number100 index99 alt1"><code class="undefined spaces">    </code><code class="plain">document.write(res);</code></div><div class="line number101 index100 alt2"><code class="undefined spaces">    </code> </div><div class="line number102 index101 alt1"><code class="undefined spaces">    </code><code class="comments">// This code is contributed by divyesh072019.</code></div><div class="line number103 index102 alt2"><code class="plain"></script></code></div></div></td></tr></tbody></table></div>


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.

C++




// C++ implementation of optimized Approach 1
#include <bits/stdc++.h>
using namespace std;
 
// function to simplify a Unix - styled
// absolute path
string simplify(string path)
{
    // using vector in place of stack
    vector<string> v;
    int n = path.length();
    string ans;
    for (int i = 0; i < n; i++) {
        string dir = "";
        // forming the current directory.
        while (i < n && path[i] != '/') {
            dir += path[i];
            i++;
        }
 
        // if ".." , we pop.
        if (dir == "..") {
            if (!v.empty())
                v.pop_back();
        }
        else if (dir == "." || dir == "") {
            // do nothing (added for better understanding.)
        }
        else {
            // push the current directory into the vector.
            v.push_back(dir);
        }
    }
 
    // forming the ans
    for (auto i : v) {
        ans += "/" + i;
    }
 
    // vector is empty
    if (ans == "")
        return "/";
 
    return ans;
}
 
// Driver Code
int main()
{
    // absolute path which we have to simplify.
    string str("/a/./b/../../c/");
    string res = simplify(str);
    cout << res;
    return 0;
}
 
// This code is contributed by yashbeersingh42


Java




// Java implementation of optimized Approach 1
import java.util.*;
public class Main
{
    // function to simplify a Unix - styled
    // absolute path
    static String simplify(String path)
    {
        
        // using vector in place of stack
        Vector<String> v = new Vector<String>();
        int n = path.length();
        String ans = "";
        for (int i = 0; i < n; i++) {
            String dir = "";
            
            // forming the current directory.
            while (i < n && path.charAt(i) != '/') {
                dir += path.charAt(i);
                i++;
            }
       
            // if ".." , we pop.
            if (dir.equals("..")) {
                if (v.size() != 0)
                {
                    v.remove(v.size() - 1);
                }
            }
            else if (dir.equals(".") || dir.equals("")) {
                // do nothing (added for better understanding.)
            }
            else {
                // push the current directory into the vector.
                v.add(dir);
            }
        }
       
        // forming the ans
        for(String i : v) {
            ans += "/" + i;
        }
       
        // vector is empty
        if (ans == "")
            return "/";
       
        return ans;
    }
     
    public static void main(String[] args) {
        // absolute path which we have to simplify.
        String str = "/a/./b/../../c/";
        String res = simplify(str);
        System.out.print(res);
    }
}
 
// This code is contributed by decode2207.


Python3




# Python3 implementation of optimized Approach 1
 
# function to simplify a Unix - styled
# absolute path
def simplify(path):
   
    # using vector in place of stack
    v = []
    n = len(path)
    ans = ""
    for i in range(n):
        Dir = ""
         
        # forming the current directory.
        while (i < n and path[i] != '/'):
            Dir += path[i]
            i+=1
  
        # if ".." , we pop.
        if (Dir == "..") :
            if (len(v) > 0):
                v.pop()
        elif (Dir == "." or Dir == ""):
            # do nothing (added for better understanding.)
            continue
        else:
            # push the current directory into the vector.
            v.append(Dir)
  
    # forming the ans
    for i in v:
        ans += "/" + i
  
    # vector is empty
    if (ans == ""):
        return "/"
  
    return ans
 
# absolute path which we have to simplify.
Str = "/a/./b/../../c/"
res = simplify(Str)
print(res)
 
# This code is contributed by rameshtravel07


C#




using System;
using System.Collections.Generic;
using System.IO;
 
class Solution {
    public static string SimplifyPath(string path)
    {
        // Create a stack to hold directory names
        Stack<string> stack = new Stack<string>();
        string[] tokens = path.Split('/');
 
        foreach(string token in tokens)
        {
            if (token == "..") {
                // Popping if ".." is found
                if (stack.Count > 0) {
                    stack.Pop();
                }
            }
            else if (!string.IsNullOrEmpty(token)
                     && token != ".") {
                // Pushing valid directory names onto the
                // stack
                stack.Push(token);
            }
        }
 
        // Build the final simplified path
        string finalPath = "";
        if (stack.Count == 0) {
            // Adding '/' to the final string if the stack
            // is empty
            finalPath = "/";
        }
        else {
            // Building the final simplified path from the
            // stack
            string[] directories = stack.ToArray();
            Array.Reverse(directories);
            finalPath = "/" + string.Join("/", directories);
        }
 
        return finalPath;
    }
 
    static void Main()
    {
        // Absolute path that needs to be simplified
        string str = "/a/./b/../../c/";
        string res = SimplifyPath(str);
        Console.WriteLine(res);
    }
}


Javascript




function simplifyPath(path) {
    const stack = [];
    const tokens = path.split('/');
 
    for (const token of tokens) {
        if (token === "..") {
            // Popping if ".." is found
            if (stack.length > 0) {
                stack.pop();
            }
        } else if (token && token !== ".") {
            // Pushing valid directory names onto the stack
            stack.push(token);
        }
    }
 
    let finalPath = "/";
    if (stack.length > 0) {
        // Building the final simplified path from the stack
        finalPath += stack.join('/');
    }
 
    return finalPath;
}
 
// Absolute path that needs to be simplified
const str = "/a/./b/../../c/";
const res = simplifyPath(str);
console.log(res);


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.

C++




#include <iostream>
#include <deque>
#include <sstream>
#include <vector>
 
using namespace std; // Import the standard namespace
 
string simplifyPath(string path) {
    deque<string> stack;
    istringstream iss(path);
    string token;
 
    // Split the input path into tokens using '/' as a delimiter
    while (getline(iss, token, '/')) {
        if (token == "..") {
            // Popping if ".." is found
            if (!stack.empty()) {
                stack.pop_back();
            }
        } else if (!token.empty() && token != ".") {
            // Pushing valid directory names onto the stack
            stack.push_back(token);
        }
    }
 
    string finalPath;
    if (stack.empty()) {
        // Adding '/' to the final string if the stack is empty
        finalPath += "/";
    } else {
        // Building the final simplified path from the stack
        for (const string& dir : stack) {
            finalPath += "/";
            finalPath += dir;
        }
    }
 
    return finalPath;
}
 
int main() {
    // Absolute path that needs to be simplified
    string str = "/a/./b/../../c/";
    string res = simplifyPath(str);
    cout << res;
    return 0;
}


Java




import java.util.*;
class GFG {
  // function to simplify a Unix - styled
// absolute path
    public static String simplify(String path) {
        Deque<String> stack = new ArrayDeque<>();
        String[] dirs = path.split("/");
        for(String dir : dirs){
            if(!dir.equals("") && !dir.equals(".")){
              //popping if .. is found
                if(!dir.equals("..")) stack.add(dir);
              //pushing if stack is not empty
                else if(!stack.isEmpty()) stack.pollLast();
            }
        }
        String finalPath = "";
        if(stack.isEmpty()){
          //adding / to the final string
            finalPath += "/";
        } else {
          //traversing through whole queue and adding to the final answer
            for(String str : stack){
                finalPath += "/";
                finalPath += str;
            }
        }
        return finalPath;
    }
   
   public static void main(String[] args) {
        // absolute path which we have to simplify.
        String str = "/a/./b/../../c/";
        String res = simplify(str);
        System.out.print(res);
    }
   
}


Python




def simplifyPath(path):
    stack = []
    tokens = path.split('/')
 
    # Split the input path into tokens using '/' as a delimiter
    for token in tokens:
        if token == "..":
            # Popping if ".." is found
            if stack:
                stack.pop()
        elif token and token != ".":
            # Pushing valid directory names onto the stack
            stack.append(token)
 
    finalPath = ""
    if not stack:
        # Adding '/' to the final string if the stack is empty
        finalPath += "/"
    else:
        # Building the final simplified path from the stack
        finalPath += "/" + "/".join(stack)
 
    return finalPath
 
 
# Main function
if __name__ == "__main__":
    # Absolute path that needs to be simplified
    path = "/a/./b/../../c/"
    result = simplifyPath(path)
    print(result)


C#




using System;
using System.Collections.Generic;
using System.IO;
 
class Solution {
    public static string SimplifyPath(string path)
    {
        // Create a stack to hold directory names
        Stack<string> stack = new Stack<string>();
        string[] tokens = path.Split('/');
 
        foreach(string token in tokens)
        {
            if (token == "..") {
                // Popping if ".." is found
                if (stack.Count > 0) {
                    stack.Pop();
                }
            }
            else if (!string.IsNullOrEmpty(token)
                     && token != ".") {
                // Pushing valid directory names onto the
                // stack
                stack.Push(token);
            }
        }
 
        // Build the final simplified path
        string finalPath = "";
        if (stack.Count == 0) {
            // Adding '/' to the final string if the stack
            // is empty
            finalPath = "/";
        }
        else {
            // Building the final simplified path from the
            // stack
            string[] directories = stack.ToArray();
            Array.Reverse(directories);
            finalPath = "/" + string.Join("/", directories);
        }
 
        return finalPath;
    }
 
    static void Main()
    {
        // Absolute path that needs to be simplified
        string str = "/a/./b/../../c/";
        string res = SimplifyPath(str);
        Console.WriteLine(res);
    }
}


Javascript




function simplifyPath(path) {
    const stack = [];
    const tokens = path.split('/');
 
    for (const token of tokens) {
        if (token === "..") {
            // Popping if ".." is found
            if (stack.length > 0) {
                stack.pop();
            }
        } else if (token && token !== ".") {
            // Pushing valid directory names onto the stack
            stack.push(token);
        }
    }
 
    let finalPath = "/";
    if (stack.length > 0) {
        // Building the final simplified path from the stack
        finalPath += stack.join('/');
    }
 
    return finalPath;
}
 
// Absolute path that needs to be simplified
const str = "/a/./b/../../c/";
const res = simplifyPath(str);
console.log(res);


Output

/c





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

This article is contributed by arshpreet soodan.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads