Skip to main content
under engineered

Simplify Paths

Hi! Today I'll go through the problem simplify paths and see how best to solve it!

The premise is simple, you're given a unix like path and it is to be simplified. This means

input = '/a/../b/'
output = '/b'

curb your temptations! #

You might get tempted to do it the same way you're probably thinking right now.

But this isn't so easy as you'll have to keep track of previous element too. As both ., .. and /, // are to be processed differently. We want the solution to be simple and lazy.

some examples #

You can see the path segments (stuff between the slashes /) will always be a valid path. It can be just these things

You need something to go and keep track of directory/nesting level. I'm going to use an array to solve this.

concept #

code #

var simplifyPath = function (path) {
  const paths = path.split("/").filter((segment) => segment && segment !== "."); // ignoring . and empty for samples like //
  const result = [];

  paths.forEach((segment) => {
    if (segment == "..") {
      result.pop();
      return;
    }

    result.push(segment);
  });

  return "/" + result.join("/");
};

practise #

You can practise this question on leetcode

discuss on twitter, because why not?