Canonical Path Cleanup Plus Overlapping Range Union
Greedy & IntervalsAuto-graded · 22 test casesLast updated
Combine stack-based Unix path normalization with sort-and-sweep merging of overlapping or touching closed ranges, returning both results in one list.
Canonical Path Cleanup Plus Overlapping Range Union
Write one function that solves two small independent tasks and returns both answers together.
Task A: Canonical path
You are given path, an absolute Unix-style path as a string. Produce its canonical form.
Interpret the path as a series of components separated by /:
- An empty component (from repeated, leading, or trailing slashes) is ignored, so any run of slashes counts as one separator.
- A component equal to
.means "stay in the current directory" and is ignored. - A component equal to
..means "go up one level". If you are already at the root, it has no effect. - Any other component is a normal directory name and moves you one level down. This includes names such as
...or..a, which are ordinary names and not special.
The canonical path must:
- start with exactly one
/, - separate directory names with exactly one
/, - have no trailing
/(except when the result is just the root/).
Task B: Merge ranges
You are given intervals, a list of closed ranges [start, end] with start <= end. The list is not necessarily sorted. Merge every group of ranges that overlap or touch (for example, [1, 3] and [3, 5] become [1, 5]) and return the resulting disjoint ranges sorted by start in ascending order.
If intervals is empty, the merged result is an empty list.
Output
Return a list of two elements: [canonical_path, merged_ranges], where canonical_path is a string and merged_ranges is a list of [start, end] lists.
Constraints
pathis a non-empty string beginning with/.0 <= len(intervals) <= 10^4- Each interval has exactly two integers with
start <= end. - Values may be negative or zero.
- Touching ranges (end of one equals start of another) must be merged.
Examples
Example 1
Input: normalize_path_and_union_ranges('/a/./b/../../c/', [[1, 3], [2, 6], [8, 10], [15, 18]])
Output: ['/c', [[1, 6], [8, 10], [15, 18]]]
Example 2
Input: normalize_path_and_union_ranges('/home//foo/', [[1, 4], [4, 5]])
Output: ['/home/foo', [[1, 5]]]
Example 3
Input: normalize_path_and_union_ranges('/../', [[0, 0]])
Output: ['/', [[0, 0]]]
Example 4
Input: normalize_path_and_union_ranges('/a//b////c/d//././/..', [[5, 7], [1, 2], [2, 4], [10, 12], [11, 15]])
Output: ['/a/b/c', [[1, 4], [5, 7], [10, 15]]]
Hints
Hint 1
For the path, split on '/' and process the components from left to right while keeping a stack of directory names.
Hint 2
Decide what to do for each component: skip empty and '.', pop on '..' only if the stack is non-empty, and push everything else (even '...').
Hint 3
For the ranges, sort by start; then you only ever need to compare the next range with the last merged one. Merge when next start <= last end, and take the max of the ends.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two tasks are independent, so we solve each separately and return them as a pair.
Task A: path normalization with a stack
Split the path on /. Every run of slashes produces empty strings, which we skip. Then process each component in order while maintaining a stack of directory names:
''or.: do nothing...: pop the stack if it is not empty (at the root, stay at the root).- anything else: push it as a directory name. Names like
...are normal names.
The answer is '/' followed by the stack joined with /. An empty stack gives just /, and there is never a trailing slash.
Why it is correct: after each component, the stack holds exactly the directories on the route from the root to the current location. Ignored tokens do not change the location, .. moves up one level, and a name moves down one level.
Task B: merging ranges
Sort the ranges by start. After sorting, any range that overlaps or touches the current merged block must follow it directly, so we only compare against the last merged block:
- If
start > last_end, there is a real gap, so begin a new block. - Otherwise, extend the last block's end to
max(last_end, end).
The max handles nested ranges such as [1, 10] followed by [2, 3]. The strict > means touching ranges are merged.
Why it is correct: by induction, after processing the first k sorted ranges, the merged list is their sorted disjoint union. The next range starts no earlier than any previous one, so it can only interact with the last block; earlier blocks end before the last block begins.
We build new [start, end] lists so the input is never mutated.
Complexity
- Task A: O(n) time and O(n) space, where n is the length of the path.
- Task B: O(m log m) time because of the sort, and O(m) space, where m is the number of ranges.
- Overall: O(n + m log m) time, O(n + m) space.
Reference solution
from typing import List
def normalize_path_and_union_ranges(path: str, intervals: List[List[int]]) -> List:
# Task A: stack of directory names
stack = []
for component in path.split('/'):
if component == '' or component == '.':
continue
if component == '..':
if stack:
stack.pop()
else:
stack.append(component)
canonical = '/' + '/'.join(stack)
# Task B: sort by start, then sweep
merged = []
for start, end in sorted(intervals, key=lambda iv: (iv[0], iv[1])):
if not merged or start > merged[-1][1]:
merged.append([start, end])
else:
merged[-1][1] = max(merged[-1][1], end)
return [canonical, merged]