The challenge
Return the canonical form of an absolute Unix path.
Path starts with /. Empty segments and . are ignored; .. removes one directory if possible. Other names, including ..., are literal.
Example
/a/./b/../../c/ → /c.
Use the walkthrough below to inspect the input and each state change.
See Simplify Unix Path, step by step
Inspect each push, pop, and recorded answer. Entries such as 2: 5 mean index: value.
Zero-based input · top labeled explicitlyLIFO
- Current input index
- —
- Main stack size
- 0
Step 01 / 10
Start with an empty stack
Read the input in order. The stack keeps only the state needed to resolve the next item.
Answer so far
Not recorded yet
- Main stack · bottom → top
- Empty
- Auxiliary stack · bottom → top
- Empty
View exact input and state
Input: ["","a",".","b","..","..","c",""]
Main stack: []. Auxiliary stack · bottom → top: [].
Put it into code
Read slash-separated names and keep the current directory chain.
Indices are zero-based. C++ uses C++17 or later.
def solve(segments):
# segments = absolute_path.split('/')
stack = []
for name in segments:
if name == '..':
if stack: stack.pop()
elif name and name != '.':
stack.append(name)
return '/' + '/'.join(stack)
#include <algorithm>
#include <optional>
#include <utility>
#include <string>
#include <vector>
using namespace std;
string solve(const vector<string>& segments) {
// Supply the absolute path split on '/'.
vector<string> stack;
for (const auto& name : segments) {
if (name == "..") { if (!stack.empty()) stack.pop_back(); }
else if (!name.empty() && name != ".") stack.push_back(name);
}
string path;
for (const auto& name : stack) path += "/" + name;
return path.empty() ? "/" : path;
}