Simplify Path Solution in Python


  • 0
    M

    The idea is to split the given path with the split separator "/" and then loop through the list and handle the different possibilities we can encounter in a Unix path.

    We keep a current list holding the final path.

    If we encounter a '.', it means the current directory so we can ignore it.

    If we encounter a '..', it means we need to pop the last element of the list as we have to go one folder back

    Then if we encounter the name of a folder, we just add it to the list.

    Finally, we join our list using the separator "/".

    def simplifyPath(self, path):
            
            result = []
            levels = path.split("/")
    
            for l in levels:
                if l == ".":
                    continue
                elif result and l == "..":
                    result.pop(-1)
                elif l == "":
                    continue
                else:
                    # If the result list is empty but the current level we are dealing with is '..', make sure we don't add it to the result list
                    if l != '..':
                        result.append(l)
            # If the given path was "/", we want to return "/"
            if not result:
                result.append("/")
            # with this we make sure that the first element of the path is "/"
            else:
                result.insert(0,'')
            final_result = "/".join(result)
    
            return final_result
    

    The time complexity is simply O(n), with n the size of the splitted path.
    The space is also O(n) as for the worst case we have to store in our result list all the path.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.