JuniorCodeCommonNot answered yet
Normalize a Unix file path (handle ., .., and //)
Normalize an absolute Unix path: collapse repeated slashes, drop . (current directory), and resolve .. (parent) against the preceding component. Going above the root is a no-op. For example /foo/bar/../baz// → /foo/baz.
Requirements:
- One pass with a stack of components.
std::string normalizePath(const std::string& path) {
// your code here
}
Write the implementation.
Split the path on /. Push each component onto a stack; skip empty components (from //) and .; on .. pop the stack if it is non-empty (above-root is ignored). Finally join the stack with /, prefixed by a leading /. One pass, O(n) time.
- ✗Popping the stack on
..when it is already empty (climbing above root) - ✗Forgetting that consecutive slashes produce empty components to skip
- ✗Character-level edits that mishandle a
..whose parent is multi-character
- →Why split into components rather than editing the raw character string?
- →How would relative paths (no leading slash) change the
..-above-root rule?
Contents
Task
Normalize an absolute Unix path (., .., //) in one pass with a component stack.
Solution
std::string normalizePath(const std::string& path) {
std::vector<std::string> stack;
std::stringstream ss(path);
std::string part;
while (std::getline(ss, part, '/')) {
if (part.empty() || part == ".") continue; // // and .
if (part == "..") { if (!stack.empty()) stack.pop_back(); } // above root — no-op
else stack.push_back(part);
}
std::string out;
for (const auto& c : stack) out += "/" + c;
return out.empty() ? "/" : out;
}
Key points
- Empty components (from
//) and.are simply skipped. ..pops only when the stack is non-empty — going above root is ignored.- Working at the component level, not characters, correctly handles multi-character parents.
Contents