{"id":24448942,"url":"https://github.com/hakeemsalman/javascript-dsa-kit","last_synced_at":"2025-10-28T06:17:27.582Z","repository":{"id":270836608,"uuid":"911604451","full_name":"hakeemsalman/javascript-dsa-kit","owner":"hakeemsalman","description":null,"archived":false,"fork":false,"pushed_at":"2025-01-03T12:11:03.000Z","size":8,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-10T04:15:16.692Z","etag":null,"topics":["coding","data-structures","dsa","javascript","maang-preparation"],"latest_commit_sha":null,"homepage":"https://hakeemsalman.github.io/javascript-dsa-kit/","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hakeemsalman.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2025-01-03T12:09:21.000Z","updated_at":"2025-01-15T12:43:24.000Z","dependencies_parsed_at":"2025-01-03T13:30:25.122Z","dependency_job_id":null,"html_url":"https://github.com/hakeemsalman/javascript-dsa-kit","commit_stats":null,"previous_names":["hakeemsalman/javascript-dsa-kit"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakeemsalman%2Fjavascript-dsa-kit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakeemsalman%2Fjavascript-dsa-kit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakeemsalman%2Fjavascript-dsa-kit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakeemsalman%2Fjavascript-dsa-kit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hakeemsalman","download_url":"https://codeload.github.com/hakeemsalman/javascript-dsa-kit/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243532531,"owners_count":20306152,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["coding","data-structures","dsa","javascript","maang-preparation"],"created_at":"2025-01-21T00:35:25.416Z","updated_at":"2025-10-28T06:17:27.576Z","avatar_url":"https://github.com/hakeemsalman.png","language":null,"readme":"# Data structures in Javascript\n\n\u003e *Click \u0026#9733; if you like the project. Your contributions are heartily \u0026#9825; welcome.*\n\u003e This notes was taken from *Freecodecamp.org* [youtube](https://www.youtube.com/watch?v=t2CEgPsws3U) video by [Beau Carnes](https://x.com/carnesbeau)\n\n- [Data structures in Javascript](#data-structures-in-javascript)\n- [Stack](#stack)\n- [Sets](#sets)\n- [Queue](#queue)\n- [Binary Search Tree](#binary-search-tree)\n  - [Basic Operations](#basic-operations)\n    - [1. Search](#1-search)\n    - [2. Insert](#2-insert)\n    - [3. Delete](#3-delete)\n  - [Example Binary Search Tree](#example-binary-search-tree)\n    - [Visualization](#visualization)\n    - [Step-by-Step Construction](#step-by-step-construction)\n  - [Traversals in BST](#traversals-in-bst)\n    - [1. In-Order Traversal (Left, Root, Right)](#1-in-order-traversal-left-root-right)\n    - [2. Pre-Order Traversal (Root, Left, Right)](#2-pre-order-traversal-root-left-right)\n    - [3. Post-Order Traversal (Left, Right, Root)](#3-post-order-traversal-left-right-root)\n  - [Applications of BST](#applications-of-bst)\n- [Binary Search Tree: Traversal and Height](#binary-search-tree-traversal-and-height)\n- [Hashtables](#hashtables)\n  - [Definition](#definition)\n\n\n# Stack\n\n- **Definition:** Array follows the stack approach, which is LIFO method (Last In First Out).\n\n## Uses\n\n- Undo/Redo functionality - [StackOVerflow](https://stackoverflow.com/a/54416376) - [Problem link](https://github.com/hakeemsalman/javascript-practice-questions/blob/main/README.md#undoredo-functionality)\n- Navigation / Routing\n- Matching Brackets - [Problem Link](https://github.com/hakeemsalman/javascript-practice-questions/blob/main/README.md#matching-brackets)\n- Min Stack - [Problem Link](https://github.com/hakeemsalman/javascript-practice-questions/edit/main/README.md#min-stack)\n\n1. **push**: Add value at the top of the stack\n1. **pop**: Delete value from the top of the stack and return it.\n1. **size**: Get length of the stack\n1. **peek**: Get top value from the stack.\n\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003cth\u003e\n    ES5 functional based code    \n  \u003c/th\u003e\n  \u003cth\u003e\n    ES6 Modern Class based code(Preferred)\n  \u003c/th\u003e\n  \u003c/tr\u003e\n  \u003ctr\u003e\n    \u003ctd\u003e\n\n```js\nlet Stack = function (){\n  this.storage = {};\n  this.count = 0;\n\n  this.push = function(value) {\n    this.storage[this.count] = value;\n    this.count++;\n    // return this.storage;\n  }\n\n  this.pop = function(value){\n    if(this.count === 0) return undefined;\n\n    this.count--;\n    let result = this.storage[this.count];\n    delete this.storage[this.count]\n    return result;\n  }\n\n  this.size = function(){\n    return this.count;\n  }\n\n  this.peek = function(){\n    return this.storage[this.count-1];\n  }\n}\n\nlet myStack = new Stack();\n\nmyStack.push(1)\nmyStack.push(2)\nmyStack.push(3)\nconsole.log(myStack.size());\nconsole.log(myStack.pop());\nconsole.log(myStack.peek());\n```\n      \n  \u003c/td\u003e\n    \n  \u003ctd\u003e\n\n```js\nclass Stack {\n  constructor() {\n    this.storage = {};\n    this.count = 0;\n  }\n\n  push(value) {\n    this.storage[this.count++] = value;\n  }\n\n  pop() {\n    if (this.count === 0) return undefined;\n    const result = this.storage[--this.count];\n    delete this.storage[this.count];\n    return result;\n  }\n\n  size() {\n    return this.count;\n  }\n\n  peek() {\n    return this.storage[this.count - 1];\n  }\n}\n\nconst myStack = new Stack();\n```\n    \n  \u003c/td\u003e\n    \n  \u003c/tr\u003e\n\u003c/table\u003e\n\n\n# Sets\n\n- `Set` is similar to an `Array` excepts having duplicate items in it.\n- ES6 has built-in option for the `Set`.\n- Built-in methods in `Sets`\n  1. **add()**\n  2. **delete()**\n  3. **size**\n\n```js\nfunction mySet(){\n  // a collection will hold the set\n  let collection = [];\n\n  this.has = function(element){\n    return (collection.indexOf(element) !== -1)\n  }\n\n  this.values = function(){\n    return collection;\n  }\n\n  this.add = function(element){\n    if(!this.has(element)){\n      collection.push(element);\n      return true;\n    }\n    return false;\n  }\n\n  this.remove = function(element){\n    if(this.has(element)){\n      index = collection.indexOf(element);\n      collection.splice(index, 1);\n      return true;\n    }\n    return false;\n  }\n\n  this.size = function() {\n    return collection.length;\n  }\n\n  this.union = function(otherSet){\n    var unionSet = new mySet();\n    let firstSet = this.values();\n    let secondSet = otherSet.values();\n    firstSet.forEach(function(e){\n      unionSet.add(e);\n    })\n    secondSet.forEach(function(e){\n      unionSet.add(e);\n    })\n    return unionSet;\n  }\n\n  this.intersection = function(){\n    \n  }\n  \n}\nvar setA = new mySet();\nvar setB = new mySet();\nsetA.add(\"a\");\nsetB.add(\"b\");\nsetB.add(\"c\");\nsetB.add(\"a\");\nsetB.add(\"d\");\nconsole.log(setA.subset(setB));\nconsole.log(setA.intersection(setB).values());\nconsole.log(setB.difference(setA).values());\n\nvar setC = new Set();\nvar setD = new Set();\nsetC.add(\"a\");\nsetD.add(\"b\");\nsetD.add(\"c\");\nsetD.add(\"a\");\nsetD.add(\"d\");\nconsole.log(setD.values());\nsetD.delete(\"a\");\nconsole.log(setD.has(\"a\"));\nconsole.log(setD.add(\"d\"));\n```\n\n# Queue\n\n- It is similar to stack but it follows FIFO method, First In First Out.\n- In real world example, People is standing for cash payment in super market. So first person get first serve.\n\n```js\nfunction Queue () { \n    collection = [];\n    this.print = function() {\n        console.log(collection);\n    };\n    this.enqueue = function(element) {\n        collection.push(element);\n    };\n    this.dequeue = function() {\n        return collection.shift(); \n    };\n    this.front = function() {\n        return collection[0];\n    };\n    this.size = function() {\n        return collection.length; \n    };\n    this.isEmpty = function() {\n        return (collection.length === 0); \n    };\n}\n\nvar q = new Queue(); \nq.enqueue('a'); \nq.enqueue('b');\nq.enqueue('c');\nq.print();\nq.dequeue();\nconsole.log(q.front());\nq.print();\n\nfunction PriorityQueue () {\n    var collection = [];\n    this.printCollection = function() {\n      (console.log(collection));\n    };\n    this.enqueue = function(element){\n        if (this.isEmpty()){ \n            collection.push(element);\n        } else {\n            var added = false;\n            for (var i=0; i\u003ccollection.length; i++){\n                 if (element[1] \u003c collection[i][1]){ //checking priorities\n                    collection.splice(i,0,element);\n                    added = true;\n                    break;\n                }\n            }\n            if (!added){\n                collection.push(element);\n            }\n        }\n    };\n    this.dequeue = function() {\n        var value = collection.shift();\n        return value[0];\n    };\n    this.front = function() {\n        return collection[0];\n    };\n    this.size = function() {\n        return collection.length; \n    };\n    this.isEmpty = function() {\n        return (collection.length === 0); \n    };\n}\n\nvar pq = new PriorityQueue(); \npq.enqueue(['Beau Carnes', 2]); \npq.enqueue(['Quincy Larson', 3]);\npq.enqueue(['Ewa Mitulska-Wójcik', 1])\npq.enqueue(['Briana Swift', 2])\npq.printCollection();\npq.dequeue();\nconsole.log(pq.front());\npq.printCollection();\n```\n\n# Binary Search Tree\n\nA **Binary Search Tree (BST)** is a type of binary tree where each node satisfies the following properties:\n\n1. A **node** is a fundamental unit of a binary tree. Each node contains:\n  1. **Value**: The data stored in the node.\n  2. **Left Child**: A pointer/reference to the left subtree.\n  3. **Right Child**: A pointer/reference to the right subtree.\n2. The **left subtree** of a node contains only nodes with values **less than** the node's value.\n3. The **right subtree** of a node contains only nodes with values **greater than** the node's value.\n4. Both left and right subtrees must also be binary search trees.\n\n---\n\n## Basic Operations\n\n\n### 1. Search\n- Begin at the root.\n- Compare the target value with the current node's value:\n  - If equal, the value is found.\n  - If smaller, search the left subtree.\n  - If larger, search the right subtree.\n- Repeat until the value is found or the subtree is empty.\n\n### 2. Insert\n- Start at the root and compare the value to be inserted.\n- Traverse to the left or right child based on comparison:\n  - If the target position is empty, insert the new node there.\n\n### 3. Delete\n- Locate the node to delete.\n- Handle three cases:\n  1. **Node has no children**: Simply remove the node.\n  2. **Node has one child**: Replace the node with its child.\n  3. **Node has two children**: Replace the node with its in-order successor (smallest node in the right subtree).\n\n---\n\n## Example Binary Search Tree\n\nLet’s construct a BST by inserting the following values in order: `50, 30, 70, 20, 40, 60, 80`.\n\n### Visualization\n\n```mermaid\ngraph TB\n    50 --\u003e 30\n    50 --\u003e 70\n    30 --\u003e 20\n    30 --\u003e 40\n    70 --\u003e 60\n    70 --\u003e 80\n```\n\n### Step-by-Step Construction\n1. Insert `50`: Becomes the root.\n2. Insert `30`: Goes to the left of `50`.\n3. Insert `70`: Goes to the right of `50`.\n4. Insert `20`: Goes to the left of `30`.\n5. Insert `40`: Goes to the right of `30`.\n6. Insert `60`: Goes to the left of `70`.\n7. Insert `80`: Goes to the right of `70`.\n\n---\n\n## Traversals in BST\n### 1. In-Order Traversal (Left, Root, Right)\n- Visits nodes in ascending order for a BST.\n- Example for the above tree: `20, 30, 40, 50, 60, 70, 80`.\n\n### 2. Pre-Order Traversal (Root, Left, Right)\n- Example: `50, 30, 20, 40, 70, 60, 80`.\n\n### 3. Post-Order Traversal (Left, Right, Root)\n- Example: `20, 40, 30, 60, 80, 70, 50`.\n\n---\n\n## Applications of BST\n1. **Searching and Sorting**: Efficiently retrieve or organize data.\n2. **Dynamic Sets**: Maintain data that changes frequently (e.g., insertion/deletion).\n3. **Database Indexing**: Store keys in databases for quick lookups.\n\n\n```js\n/* Binary Search Tree */\n\nclass Node {\n  constructor(data, left = null, right = null) {\n    this.data = data;\n    this.left = left;\n    this.right = right;\n  }\n}\n\nclass BST {\n  constructor() {\n    this.root = null;\n  }\n  add(data) {\n    const node = this.root;\n    if (node === null) {\n      this.root = new Node(data);\n      return;\n    } else {\n      const searchTree = function(node) {\n        if (data \u003c node.data) {\n          if (node.left === null) {\n            node.left = new Node(data);\n            return;\n          } else if (node.left !== null) {\n            return searchTree(node.left);\n          }\n        } else if (data \u003e node.data) {\n          if (node.right === null) {\n            node.right = new Node(data);\n            return;\n          } else if (node.right !== null) {\n            return searchTree(node.right);\n          }\n        } else {\n          return null;\n        }\n      };\n      return searchTree(node);\n    }\n  }\n  findMin() {\n    let current = this.root;\n    while (current.left !== null) {\n      current = current.left;\n    }\n    return current.data;\n  }\n  findMax() {\n    let current = this.root;\n    while (current.right !== null) {\n      current = current.right;\n    }\n    return current.data;\n  }\n  find(data) {\n    let current = this.root;\n    while (current.data !== data) {\n      if (data \u003c current.data) {\n        current = current.left;\n      } else {\n        current = current.right;\n      }\n      if (current === null) {\n        return null;\n      }\n    }\n    return current;\n  }\n  isPresent(data) {\n    let current = this.root;\n    while (current) {\n      if (data === current.data) {\n        return true;\n      }\n      if (data \u003c current.data) {\n        current = current.left;\n      } else {\n        current = current.right;\n      }\n    }\n    return false;\n  }\n  remove(data) {\n    const removeNode = function(node, data) {\n      if (node == null) {\n        return null;\n      }\n      if (data == node.data) {\n        // node has no children \n        if (node.left == null \u0026\u0026 node.right == null) {\n          return null;\n        }\n        // node has no left child \n        if (node.left == null) {\n          return node.right;\n        }\n        // node has no right child \n        if (node.right == null) {\n          return node.left;\n        }\n        // node has two children \n        var tempNode = node.right;\n        while (tempNode.left !== null) {\n          tempNode = tempNode.left;\n        }\n        node.data = tempNode.data;\n        node.right = removeNode(node.right, tempNode.data);\n        return node;\n      } else if (data \u003c node.data) {\n        node.left = removeNode(node.left, data);\n        return node;\n      } else {\n        node.right = removeNode(node.right, data);\n        return node;\n      }\n    }\n    this.root = removeNode(this.root, data);\n  }\n  isBalanced() {\n    return (this.findMinHeight() \u003e= this.findMaxHeight() - 1)\n  }\n}\n\n\n\nconst bst = new BST();\n\nbst.add(9);\nbst.add(4);\nbst.add(17);\nbst.add(3);\nbst.add(6);\nbst.add(22);\nbst.add(5);\nbst.add(7);\nbst.add(20);\n\nconsole.log(bst.findMinHeight());\nconsole.log(bst.findMaxHeight());\nconsole.log(bst.isBalanced());\nbst.add(10);\nconsole.log(bst.findMinHeight());\nconsole.log(bst.findMaxHeight());\nconsole.log(bst.isBalanced());\n```\n\n# Binary Search Tree: Traversal and Height\n\n```js\nclass Node {\n  constructor(data, left = null, right = null) {\n    this.data = data;\n    this.left = left;\n    this.right = right;\n  }\n}\n\nclass BSTheight{\n\n  findMinHeight(node = this.root) {\n      if (node == null) {\n          return -1;\n      };\n      let left = this.findMinHeight(node.left);\n      let right = this.findMinHeight(node.right);\n      if (left \u003c right) {\n          return left + 1;\n      } else {\n          return right + 1;\n      };\n  }\n  findMaxHeight(node = this.root) {\n      if (node == null) {\n          return -1;\n      };\n      let left = this.findMaxHeight(node.left);\n      let right = this.findMaxHeight(node.right);\n      if (left \u003e right) {\n          return left + 1;\n      } else {\n          return right + 1;\n      };\n  }\n  inOrder() {\n    if (this.root == null) {\n      return null;\n    } else {\n      var result = new Array();\n      function traverseInOrder(node) {       \n        node.left \u0026\u0026 traverseInOrder(node.left);\n        result.push(node.data);\n        node.right \u0026\u0026 traverseInOrder(node.right);\n      }\n      traverseInOrder(this.root);\n      return result;\n    };\n  }\n  preOrder() {\n    if (this.root == null) {\n      return null;\n    } else {\n      var result = new Array();\n      function traversePreOrder(node) {\n        result.push(node.data);\n        node.left \u0026\u0026 traversePreOrder(node.left);\n        node.right \u0026\u0026 traversePreOrder(node.right);\n      };\n      traversePreOrder(this.root);\n      return result;\n    };\n  }\n  postOrder() {\n    if (this.root == null) {\n      return null;\n    } else {\n      var result = new Array();\n      function traversePostOrder(node) {\n        node.left \u0026\u0026 traversePostOrder(node.left);\n        node.right \u0026\u0026 traversePostOrder(node.right);\n        result.push(node.data);\n      };\n      traversePostOrder(this.root);\n      return result;\n    }\n  }\n  \n  levelOrder() {\n      let result = [];\n      let Q = []; \n      if (this.root != null) {\n          Q.push(this.root);\n          while(Q.length \u003e 0) {\n              let node = Q.shift();\n              result.push(node.data);\n              if (node.left != null) {\n                  Q.push(node.left);\n              };\n              if (node.right != null) {\n                  Q.push(node.right);\n              };\n          };\n          return result;\n      } else {\n          return null;\n      };\n  };\n}\n\nconsole.log('inOrder: ' + bst.inOrder());\nconsole.log('preOrder: ' + bst.preOrder());\nconsole.log('postOrder: ' + bst.postOrder());\n\nconsole.log('levelOrder: ' + bst.levelOrder());\n```\n\n# Hashtables\n\n## Definition\n\n- Hash-table is used to implement associative arrays or mapping of key value pairs.\n- Hash tables are common way to implement the map data structures or objects.\n\n| Algorithm \t| Average \t| Worst case \t|\n|:---------:\t|:-------:\t|:----------:\t|\n|   Space   \t|   O(n)  \t|    O(n)    \t|\n|   Search  \t|   O(1)  \t|    O(n)    \t|\n|   Insert  \t|   O(1)  \t|    O(n)    \t|\n|   Delete  \t|   O(1)  \t|    O(n)    \t|\n\n\n\n```js\n/* Hash Table */\n\nvar hash = (string, max) =\u003e {\n  var hash = 0;\n  for (var i = 0; i \u003c string.length; i++) {\n    hash += string.charCodeAt(i);\n  }\n  return hash % max;\n};\n\nlet HashTable = function() {\n\n  let storage = [];\n  const storageLimit = 14;\n  \n  this.print = function() {\n    console.log(storage)\n  }\n\n  this.add = function(key, value) {\n    var index = hash(key, storageLimit);\n    if (storage[index] === undefined) {\n      storage[index] = [\n        [key, value]\n      ];\n    } else {\n      var inserted = false;\n      for (var i = 0; i \u003c storage[index].length; i++) {\n        if (storage[index][i][0] === key) {\n          storage[index][i][1] = value;\n          inserted = true;\n        }\n      }\n      if (inserted === false) {\n        storage[index].push([key, value]);\n      }\n    }\n  };\n\n  this.remove = function(key) {\n    var index = hash(key, storageLimit);\n    if (storage[index].length === 1 \u0026\u0026 storage[index][0][0] === key) {\n      delete storage[index];\n    } else {\n      for (var i = 0; i \u003c storage[index].length; i++) {\n        if (storage[index][i][0] === key) {\n          delete storage[index][i];\n        }\n      }\n    }\n  };\n\n  this.lookup = function(key) {\n    var index = hash(key, storageLimit);\n    if (storage[index] === undefined) {\n      return undefined;\n    } else {\n      for (var i = 0; i \u003c storage[index].length; i++) {\n        if (storage[index][i][0] === key) {\n          return storage[index][i][1];\n        }\n      }\n    }\n  };\n\n};\n\n\nconsole.log(hash('quincy', 10))\n\nlet ht = new HashTable();\nht.add('beau', 'person');\nht.add('fido', 'dog');\nht.add('rex', 'dinosour');\nht.add('tux', 'penguin')\nconsole.log(ht.lookup('tux'))\nht.print();\n```\n\n\n\n\n\n\n\n\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhakeemsalman%2Fjavascript-dsa-kit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhakeemsalman%2Fjavascript-dsa-kit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhakeemsalman%2Fjavascript-dsa-kit/lists"}