Simplify Path in TypeScript: Parse Components, Not Dots

Paths are easy to misread when punctuation starts doing two jobs. A dot can be a directory instruction or an ordinary part of a name. A slash can separate names or repeat an existing separator. Trying to tidy the whole string with a succession of replacements tends to blur those distinctions.
For LeetCode's Simplify Path problem, I split the path into components and interpret each complete component. A stack then holds the names that survive. It is a small parsing exercise, and keeping the grammar small is most of the solution.
There is an important limit before we start: this is lexical simplification under the problem's rules. We aren't asking a real filesystem where a symbolic link points, whether a directory exists, or whether the caller may access it. A tidy string is not a security decision.
Give Each Component Exactly One Meaning
The input is an absolute Unix‑style path, so it begins at the root. Splitting on / produces directory names and sometimes empty strings. Empty components represent repeated, leading, or trailing separators, and can be ignored.
A component equal to . means stay in the current directory. A component equal to .. means move to its parent. Any other component is a literal name. That includes ..., ...., .cache, and file.txt: punctuation inside a name isn't an invitation to reinterpret part of it.
The output starts with one slash, places one slash between surviving names, and has no trailing slash unless the result is the root itself. Constructing that format once at the end is easier than maintaining a partially formatted path throughout the scan.
The stack contains the current surviving names in order. Reading a normal name pushes it. Reading a parent instruction pops the latest name. If the stack is empty, another parent instruction leaves it empty, because the problem does not allow travelling above the root.
const simplifyPath = (path: string): string => {
const directories: string[] = [];
for (const part of path.split('/')) {
if (part === '' || part === '.') continue;
if (part === '..') directories.pop();
else directories.push(part);
}
return `/${directories.join('/')}`;
};Calling pop on an empty array returns undefined and leaves the array unchanged, which gives us exactly the root behaviour we need. We aren't using that return value, so there is no missing name to handle afterwards.
The final template string also handles the root naturally. Joining an empty array produces an empty string, and the leading slash makes the result /. No special trailing‑slash cleanup is needed because the join only places separators between names.
A Path with Several Kinds of Dots
Take /work//drafts/../.cache/./.../. Splitting produces empty components around the separators as well as the six meaningful names or instructions. After work, the stack contains work. After drafts, it contains work and drafts.
The parent instruction removes drafts. The name .cache is then appended unchanged. The single dot does nothing, and the triple dot is appended as a real name. The trailing empty component does nothing. The result is /work/.cache/....
This trace is useful because a broad "remove dots" rule would damage two legitimate names. A regular expression that looks only for a dot substring cannot decide whether that substring is an entire component without rebuilding the same grammar indirectly.
Now consider /../../notes/../. The first two parent instructions encounter an empty stack and leave it there. notes is added, then removed by the final parent instruction, so the answer is /. Keeping unresolved .. components would be reasonable for some relative‑path algorithms, but it would be wrong for this absolute‑path problem.
Why the Stack Describes the Processed Prefix
After processing any number of components, the stack is the simplified path for exactly that prefix of the input. Initially, the empty prefix represents the root and the stack is empty.
Ignoring an empty component or a single dot preserves that path. A normal name extends it by one level. A parent instruction removes its last level when one exists, or leaves the root unchanged. Each branch therefore preserves the meaning of the processed prefix.
When every component has been processed, the stack describes the whole path. Formatting it with a leading slash and joined separators gives the required canonical text. The proof follows the same four cases as the code, which is a useful sign that the representation fits the problem.
There is no need to scan backwards looking for the directory to remove. The last surviving directory is already at the top of the stack. That is the useful property, rather than simply the fact that a stack happens to be a fashionable answer to parsing questions.
Linear Work, Including the Strings
Let n be the input's character length. Splitting scans the input and creates component strings. The loop inspects every component once, and each component is pushed at most once and popped at most once. Joining the surviving components writes at most O(n) characters.
The overall runtime is O(n), with O(n) auxiliary storage for the split components, stack, and output under ordinary string‑storage accounting. Describing the space as only the maximum directory depth would ignore the names themselves and the array created by split.
A streaming character scanner could avoid materialising the entire split array. It would still need to identify the current component and retain the surviving path names, and it would make this short solution harder to inspect. For the exercise's input size, I would choose the explicit components unless allocation measurements gave me a reason to do otherwise.
Similar Library Functions Have Different Promises
Node.js provides path normalisation utilities, but their behaviour isn't identical to this exercise. In particular, path.normalize preserves trailing separators, and the default path implementation depends on the operating system. path.posix selects Unix‑style behaviour explicitly.
Those distinctions matter when using a library as a test reference. A reference can normalise with the explicit Unix variant, then remove trailing separators except at root to match this exercise. Comparing against the default platform function without accounting for those differences can produce a test failure in the test rather than in the solution.
Real filesystem resolution is a further step. Symbolic links can make textually collapsing a name followed by .. differ from resolving the path against actual directories. If a path is part of access control, validation must follow the application's filesystem and permission rules, not merely pass this interview solution through a reassuringly named helper.
I would also reject the temptation to decode escaped input, accept relative paths, or support Windows drive names inside this function without changing its documented input. Each addition introduces another grammar and another set of tests. The exercise gives us a narrow problem; we should solve that problem accurately.
Small Tests with Useful Variety
I check /, repeated separators, a trailing separator, repeated parent instructions at root, ordinary names containing dots, and a path that reduces entirely to root. The triple‑dot name deserves its own test because it catches substring‑based shortcuts immediately.
Idempotence is another useful property: simplifying an already simplified result should leave it unchanged. The output should begin with a slash, contain no repeated separators, and have no complete . or .. components. These properties complement exact expected outputs; they don't replace them, since the constant result / would satisfy several of them whilst losing every useful name.
My Decode String walkthrough uses a stack to remember suspended parsing contexts, whereas this stack stores surviving path components. My circular queue article explores a different removal order altogether. Here, the latest name is precisely the one a parent instruction cancels. Once that relationship is clear, the implementation has very little left to argue about.