Skip to content

Commit

Permalink
Merge pull request neetcode-gh#2614 from aadil42/patch-60
Browse files Browse the repository at this point in the history
  • Loading branch information
aakhtar3 authored Jul 4, 2023
2 parents 6e9bbd9 + f65d073 commit cf13469
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions javascript/0071-simplify-path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

/**
* Stack
* Time O(N) | Space O(N)
* https://leetcode.com/problems/simplify-path
* @param {string} path
* @return {string}
*/
var simplifyPath = (path, slash = '/', stack = []) => {
const paths = path.split(slash).filter(Boolean);

for (const _path of paths) traversePath(_path, stack);

return `${slash}${stack.join(slash)}`;
};

const traversePath = (path, stack) => {
if (canPush(path)) return stack.push(path);

if (canPop(path, stack)) stack.pop();
};

const canPush = (path) => !(
isCurrentDirectory(path) ||
isParentDirectory(path)
);

const canPop = (path, stack) =>
isParentDirectory(path) &&
!isEmpty(stack);

const isCurrentDirectory = (path) => (path === '.');

const isParentDirectory = (path) => (path === '..');

const isEmpty = ({ length }) => (0 === length);

0 comments on commit cf13469

Please sign in to comment.