Leetcode 71: Simplify Path

grid47
grid47
Exploring patterns and algorithms
Oct 30, 2024 5 min read

A smooth, glowing path being simplified, with unnecessary elements fading away.
Solution to LeetCode 71: Simplify Path Problem

Given an absolute path for a Unix-style file system, simplify the path by following Unix file system rules. Handle ‘.’ and ‘..’ as current and parent directories, and multiple slashes as a single slash. Return the simplified canonical path.
Problem
Approach
Steps
Complexity
Input: A string representing the absolute path of a file or directory in a Unix-style file system.
Example: Input: path = "/home//docs/"
Constraints:
• 1 <= path.length <= 3000
• path consists of English letters, digits, period '.', slash '/', or '_'.
• The path is a valid absolute Unix path.
Output: Return the simplified canonical path as a string.
Example: Output: "/home/docs"
Constraints:
• The output must be a valid simplified absolute path.
Goal: Simplify the absolute Unix path by handling '.' and '..' according to file system rules.
Steps:
• Split the path by the '/' character.
• Iterate through each segment of the path.
• Push valid directory names onto a stack, and pop the stack when encountering '..'.
• Ignore '.' and empty segments.
• Finally, reconstruct the canonical path from the stack.
Goal: The input path must be a valid absolute path, and the function must handle all possible edge cases efficiently.
Steps:
• 1 <= path.length <= 3000
• The input path must be a valid Unix absolute path.
Assumptions:
• The input path is well-formed and always starts with a slash ('/').
• The path is an absolute Unix-style file system path.
Input: Input: path = "/home//docs/"
Explanation: Multiple consecutive slashes are treated as a single slash, resulting in the simplified path '/home/docs'.

Input: Input: path = "/home/user/../data/files/"
Explanation: The '..' refers to the parent directory, simplifying the path to '/home/data/files'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus