[Problem Link]

  • Tokenize the string with ‘/’ as a delimiter.
  • Create a graph where nodes have pointers to parent nodes.
  • Keep moving up(& down) the graph depending on the directory.
  • If you see a directory, create (or move) to the node (depending on if it exists or not)!
  • Make sure you don’t move above the root node because “Going one level up from the root directory is a no-op”.
  • When you’re done, traverse up to the root node (while creating the path).
  • If the path is empty, return “/”
/**
 * @param {string} path
 * @return {string}
 */
 
function node(val, parent) {
  this.val = val;
  this.parent = parent;
  this.children = [];
 
  this.findChild = function(val) {
    var result = this.children.filter((child) => child.val === val);
    return result && result.length === 1 && result[0];
  }
}
 
var simplifyPath = function(path) {
  var root = new node('', null);
  path.split("/").forEach((dir) => {
    if ( dir ) {
      if ( dir === '..' ) {
        if (root.parent) {
          root = root.parent;
        }
      } else if ( dir !== '.' ) {
        var child = root.findChild(dir);
        if (!child) {
          child = new node('/' + dir, root);
          root.children.push(child);
        }
        root = child;
      }
    }
  })
 
  var ret = '';
  var curr = root;
  while (curr) {
    ret = curr.val + ret;
    curr = curr.parent;
  }
 
  return ret ? ret : '/';
};