Simplify Path — LeetCode 71 Python Solution

MediumStackString
Problem
#71
Pattern
Stack
Reading time
2 min

The problem

You are given an absolute path for a Unix-style file system, which always begins with a slash '/'. Your task is to transform this absolute path into its simplified canonical path.

Python solution

Python
class Solution:
    def simplifyPath(self, path: str) -> str:
        stk = []
        for s in path.split('/'):
            if not s or s == '.':
                continue
            if s == '..':
                if stk:
                    stk.pop()
            else:
                stk.append(s)
        return '/' + '/'.join(stk)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the length of the path auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 71. Simplify Path is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On a study list

This problem is on Top Interview 150.

Frequently asked questions

How hard is LeetCode 71. Simplify Path?
LeetCode 71. Simplify Path is rated Medium on LeetCode.
What is the time complexity of LeetCode 71. Simplify Path?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 71. Simplify Path?
The Python solution on this page uses O(n), where n is the length of the path auxiliary space.
What topics does LeetCode 71. Simplify Path cover?
LeetCode 71. Simplify Path is tagged Stack and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview