THN Interview Prep

071. Simplify Path

At a Glance

  • Topic: stack
  • Pattern: Stack (token processing)
  • Difficulty: Medium
  • Companies: Amazon, Google, Meta, Microsoft, Bloomberg
  • Frequency: Medium
  • LeetCode: 71

Problem (one-liner)

Given a Unix-style absolute path string, return its simplified canonical form: collapse ., resolve .. against parent, drop redundant slashes, keep leading /.

Recognition Cues

  • Slash-separated tokens
  • ".." pops parent directory
  • "" and "." are no-ops in most rules

Diagram

At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.

Loading diagram…

Approaches

  • Brute force — split, list manipulation with index pointer — O(n) but verbose.
  • Better — stack of path components — O(n) time / O(n) space.
  • Optimalsplit("/") + filter rules — same complexity, clearest.

Optimal Solution

Go

import "strings"

func simplifyPath(path string) string {
	parts := strings.Split(path, "/")
	stack := make([]string, 0, len(parts))
	for _, part := range parts {
		if part == "" || part == "." {
			continue
		}
		if part == ".." {
			if len(stack) > 0 {
				stack = stack[:len(stack)-1]
			}
		} else {
			stack = append(stack, part)
		}
	}
	return "/" + strings.Join(stack, "/")
}

JavaScript

function simplifyPath(path) {
	const parts = path.split('/');
	const stack = [];
	for (const part of parts) {
		if (part === '' || part === '.') {
			continue;
		}
		if (part === '..') {
			if (stack.length > 0) {
				stack.pop();
			}
		} else {
			stack.push(part);
		}
	}
	return '/' + stack.join('/');
}

Walkthrough

path = "/home//foo/" → parts ["", "home", "", "foo", ""] → push home, foo/home/foo

Invariant: stack is the current absolute path from root with no . or .. remaining.

Edge Cases

  • "/../""/"
  • Only slashes
  • Many consecutive .. at start

Pitfalls

  • Treating .. as a name (only pop when it is the whole token)
  • Forgetting leading / in output

Similar Problems

Variants

  • Relative path resolution with a current working directory.
  • Windows vs POSIX separators.

Mind-Map Tags

#stack #path #tokenize #normalize #unix-path

Last updated on

Spotted something unclear or wrong on this page?

On this page