Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Maybe not as clean but more space efficient?

krishi87

Feb 24, 2025

class Solution: def simplifyPath(self, path): stack = [] for index in range(len(path)): char = path[index] if stack: if char == "." and index != len(path)-1 and path[index+1] == char: # Go back a dir, pop twice stack.pop() if stack: stack.pop() # Always check for underflow while popping elif char == "/" and ((index != len(path)-1 and path[index+1] == char) or stack[-1] == char): # Simplify // to / by not pushing anything to stack continue if char not in ["."]: # Ignore . and push char to stack stack.append(char) return "".join(stack).rstrip("/") if len(stack)>1 else "/" # read stack

0

0

Comments
Comments

On this page