Tensorum
YouTubeसीखना शुरू करें
LeetCode 71 · Stack Simulation / String Processing

Simplify Path

LeetCode 71 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Stack of directory names.

मध्यमStringStack

मैंने Simplify Path (LeetCode 71) ऐसे हल किया — Stack Simulation / String Processing पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

Split the path on '/' and process the pieces with a stack: '..' pops a directory, '.' and empty pieces do nothing, anything else is a directory name to push.

Approach

  1. 1

    Split by '/'.

  2. 2

    Skip '' and '.'.

  3. 3

    '..' → pop if possible.

  4. 4

    Push other names; join with '/' and prefix '/'.

मैंने कैसे हल किया

Stack of componentsPythonO(n) time
class Solution:
    def simplifyPath(self, path: str) -> str:
        #/.../a/../b/c/../d/./
        #/directory_name/ [a/..] - >/directory_name/
        #/directory_name/b/c/.. ->/directory_name/b/
        #/directory_name/b/d/. -> /.../b/d

        #intuition is - 
        #/d/./ -> /d
        #if it's single dot (.) we just ignoring . and taking the previous path /d
        #/user/Documents/.. ->/user
        #if it's a double dot then we are removing Documents

        #approach
        #have a stack
        #split string by /
        #if cur string is . no need to do anything
        #if cur string is .. pop from stack
        #rest - add to stack
        #finally join by / and return 
        stack =[]
        components = path.split("/")
        for component in components:
            if component=="." or component=="":
                continue
            elif component=="..":
                if len(stack)>0:
                    stack.pop()
            else:
                stack.append(component)
        return "/"+"/".join(stack)
स्टेप-थ्रू लोड हो रहा है…

Simplify Path — अक्सर पूछे जाने वाले प्रश्न

Simplify Path के पीछे intuition क्या है?

Split the path on '/' and process the pieces with a stack: '..' pops a directory, '.' and empty pieces do nothing, anything else is a directory name to push.

Simplify Path (LeetCode 71) कैसे हल करें?

1. Split by '/'. 2. Skip '' and '.'. 3. '..' → pop if possible. 4. Push other names; join with '/' and prefix '/'.

Simplify Path की time और space complexity क्या है?

Time: O(n)। Space: O(n)। (Accepted approach: Stack of components।)

Simplify Path में आम गलतियाँ क्या हैं?

'...' is a valid directory name, not a parent reference.