Simplify Path
LeetCode 71 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু
Stack of directory names.
আমি 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
Split by '/'.
- 2
Skip '' and '.'.
- 3
'..' → pop if possible.
- 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.