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.