Drill

ProblemsGo › patterns

Tidy up a file path

hardpatternsStacksStringsParsingGo

A storage service is handed paths with stray slashes and dot segments in them, and stores exactly one canonical form.

tidyPath(raw: string) → string

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func tidyPath(raw string) string {
	
}

Worked examples

CallResult
tidyPath("/home//user/")"/home/user"
tidyPath("/a/./b/../c")"/a/c"
tidyPath("/../")"/"
tidyPath("/")"/"

Hint

Split on the slash and push each real segment onto a stack; ".." pops instead. Joining the stack back up gives the answer.

Reference solution in Go
func tidyPath(raw string) string {
	kept := []string{}
	for _, part := range strings.Split(raw, "/") {
	    if part == "" || part == "." {
	        continue
	    }
	    if part == ".." {
	        if len(kept) > 0 {
	            kept = kept[:len(kept)-1]
	        }
	    } else {
	        kept = append(kept, part)
	    }
	}
	return "/" + strings.Join(kept, "/")
}

The same problem in another language

More patterns problems in Go