├── Binary-Search ├── iterative-method.js ├── simpleMethod.js └── test.js ├── Bubble-Sorting └── bubble-sort.js ├── Insertion-Sorting └── insertion-sort.js ├── Linear-Search ├── linear-search.js └── tempCodeRunnerFile.js ├── Linked List └── singly linked list.js ├── Queue ├── array.js ├── demo.js ├── demoqueue.js ├── linkedList.js └── tempCodeRunnerFile.js ├── README.md ├── Stack ├── array.js ├── demo.js └── linkedList.js ├── data ├── demo.js └── tempCodeRunnerFile.js ├── graph ├── BFS.js ├── DFS.js ├── graph.js ├── problem1.js └── problem2.js ├── hashTable ├── hashTableSimple.js ├── hashtable.js └── test.js ├── heaps ├── checkheap.js ├── heap.js ├── max-heap.js ├── min-heap.js ├── operations.js └── test.js ├── recursion ├── fibonacci.js ├── prime.js └── singlePrime.js ├── sorting ├── allsort │ └── allsort.js ├── bubbleSort │ ├── algorithm │ ├── bubble sort.js │ ├── optimised_method.js │ └── sort.js ├── heapSort │ ├── heapSortLarge.js │ ├── heapSortSmall.js │ └── test.js ├── insertionSort │ ├── insertionSort.js │ └── sort.js ├── mergeSort │ ├── mergeSort.js │ ├── sort.js │ └── text.js ├── quickSort │ ├── quickSort.js │ ├── quickSort2.js │ ├── sort.js │ └── test.js └── selectionSort │ ├── selectionsort.js │ └── test.js ├── string ├── sting.js └── test.js ├── tree ├── algorithumFor(BTS).txt ├── closest value.js ├── test.js ├── tree(BTS).js ├── treeWorkout.js └── workout.js └── trie ├── prifixTrie.js ├── problem1.js └── sufixTrie.js /Binary-Search/iterative-method.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(array){ 2 | let n = array.length 3 | let i, j, temp 4 | for(i=0; i< n ; i++){ 5 | for(j=0 ; j< array.length-i-1 ; j++){ 6 | if(array[j] > array[j+1]){ 7 | temp = array[j+1] 8 | array[j+1] =array[j] 9 | array[j]= temp 10 | } 11 | } 12 | } 13 | return array 14 | } 15 | 16 | 17 | const binarySearch = (arr,x) => { 18 | bubbleSort(arr) 19 | let l = 0; 20 | let r = arr.length-1; 21 | let mid; 22 | while( r >= l) { 23 | mid = l + Math.floor((r-l)/2) 24 | 25 | if (arr[mid] ==x){ 26 | return mid 27 | } 28 | if(arr[mid] > x){ 29 | r = mid-1; 30 | }else{ 31 | l = mid+1; 32 | } 33 | } 34 | return -1 35 | } 36 | 37 | let arr = [10,23,30,40,45,50,2,60,4,420] 38 | let x = 10 39 | let result = binarySearch(arr,x) 40 | result == -1 ? console.log("NO Founded") : console.log(result) 41 | console.log(arr) 42 | -------------------------------------------------------------------------------- /Binary-Search/simpleMethod.js: -------------------------------------------------------------------------------- 1 | 2 | function bubbleSort(array){ 3 | let i , j, temp 4 | for(i=0 ; i< array.length ; i++){ 5 | for(j=0 ; j array[j+1]){ 7 | temp = array[j+1] 8 | array[j+1]= array[j] 9 | array[j]= temp 10 | } 11 | } 12 | } 13 | return array 14 | } 15 | 16 | function binarySearch(arr, value, start, end) { 17 | bubbleSort(arr) 18 | if (end < start) { 19 | return false 20 | } 21 | let mid = Math.floor((start + end) / 2) 22 | if (arr[mid] === value) { 23 | console.log(mid) 24 | } 25 | 26 | if (arr[mid] < value) { 27 | return binarySearch(arr, value, mid + 1, end) 28 | } else { 29 | return binarySearch(arr, value, start, mid - 1) 30 | } 31 | 32 | } 33 | 34 | let arr = [2, 1, 3, 7, 4, 9, 8] 35 | let start = 0 36 | let end = arr.length - 1 37 | binarySearch(arr, 8, start, end) 38 | console.log(arr) -------------------------------------------------------------------------------- /Binary-Search/test.js: -------------------------------------------------------------------------------- 1 | function sort ( array){ 2 | let i ,j , temp 3 | let n= array.length 4 | for(i = 0 ; i < n-1 ; i++){ 5 | let small = i 6 | for(j =i+1 ; j x){ 29 | r = mid-1 30 | }else{ 31 | l = mid +1 32 | } 33 | } 34 | return -1 35 | 36 | } 37 | 38 | let arr =[3,2,4,6,8,4,22,1,2,4] 39 | let target = 22 40 | let result = binarySearch(arr,target) 41 | 42 | result == -1 ? console.log("nodata") : console.log(result) 43 | console.log(arr) -------------------------------------------------------------------------------- /Bubble-Sorting/bubble-sort.js: -------------------------------------------------------------------------------- 1 | let arr = [1, 2, 3, 4,1, 5]; 2 | 3 | let isSorted = true; 4 | 5 | for (let i = 0; i < arr.length - 1; i++) { 6 | if (arr[i] > arr[i+1]) { 7 | isSorted = false; 8 | break; 9 | } 10 | } 11 | 12 | if (isSorted) { 13 | console.log("The array is sorted in ascending order."); 14 | } else { 15 | console.log("The array is not sorted in ascending order."); 16 | } 17 | -------------------------------------------------------------------------------- /Insertion-Sorting/insertion-sort.js: -------------------------------------------------------------------------------- 1 | const insertionSort = (array) => { 2 | for (let i=1; i current ){ 6 | array[j+1] = array[j]; 7 | j--; 8 | } 9 | array[j+1] = current; 10 | } 11 | return array 12 | } 13 | 14 | let arr = [18, 48, 58, 9, 4, 67, 30] 15 | const result = insertionSort(arr); 16 | result.forEach(element => { 17 | console.log(element) 18 | }); -------------------------------------------------------------------------------- /Linear-Search/linear-search.js: -------------------------------------------------------------------------------- 1 | 2 | // function search(arr, n, x) { 3 | // let i; 4 | // for (i = 0; i < n; i++) { 5 | // if (arr[i] == x) { 6 | // return i; 7 | // } 8 | // } 9 | // return -1; 10 | // } 11 | // let arr = [0, 4, 5, 2, 5, 1]; 12 | // let n = arr.length; 13 | // let x = 1; 14 | // let result = search(arr, n, x); 15 | 16 | // console.log(result); 17 | 18 | 19 | 20 | function ls(array ){ 21 | let n= array.length 22 | for(let i=0 ;i { 15 | let current = head; 16 | while ( current != null){ 17 | console.log(current.data+" ") 18 | current = current.next; 19 | } 20 | } 21 | 22 | // insert value biginning 23 | 24 | const push = (newData)=>{ 25 | let newNode = new Node(newData) 26 | newNode.next = head 27 | head = newNode 28 | 29 | } 30 | 31 | // insert Value After Node 32 | 33 | const insertAfterNode = (prevData, newData)=>{ 34 | if(prevData == null){ 35 | console.log("Please give previous node data") 36 | return 37 | } 38 | const newNode = new Node(newData) 39 | newNode.next = prevData.next 40 | prevData.next = newNode 41 | 42 | } 43 | 44 | // Insert Value to End 45 | 46 | const append =(newData)=>{ 47 | if (head == null){ 48 | const head = new Node(newData) 49 | return 50 | } 51 | const newNode = new Node(newData) 52 | newNode.next = null 53 | 54 | let last = head 55 | while( last.next != null){ 56 | last = last.next 57 | } 58 | last.next = newNode 59 | 60 | } 61 | 62 | var head = new Node(1) 63 | const second = new Node(2) 64 | const third = new Node(3) 65 | 66 | head.next = second 67 | second.next = third 68 | 69 | 70 | console.log('Lists') 71 | printList() 72 | console.log('Inserted begining') 73 | push(5) 74 | printList() 75 | console.log('Inserted after second') 76 | insertAfterNode(second,5) 77 | printList() 78 | console.log('Inserted to end') 79 | append(6) 80 | printList() 81 | -------------------------------------------------------------------------------- /Queue/array.js: -------------------------------------------------------------------------------- 1 | class Queue{ 2 | constructor(){ 3 | this.items = []; 4 | } 5 | 6 | 7 | enqueue(element) { 8 | this.items.push(element) 9 | console.log(element+"enqueued to queue") 10 | } 11 | dequeue() { 12 | if ( this.items.length == 0){ 13 | return "Underflow" 14 | } 15 | return this.items.shift() 16 | } 17 | print(){ 18 | let i = 0 19 | while(i < this.items.length){ 20 | console.log( this.items[i]) 21 | i++ 22 | } 23 | } 24 | 25 | 26 | } 27 | var queue = new Queue(); 28 | 29 | queue.enqueue(40) 30 | queue.enqueue(10) 31 | queue.enqueue(20) 32 | queue.enqueue(30) 33 | queue.dequeue() 34 | 35 | queue.print() -------------------------------------------------------------------------------- /Queue/demo.js: -------------------------------------------------------------------------------- 1 | class Queue { 2 | constructor(){ 3 | this.item=[] 4 | } 5 | 6 | 7 | enqueue(element){ 8 | this.item.push(element) 9 | console.log(element); 10 | } 11 | dequeue(){ 12 | if(this.item.length==0){ 13 | console.log("i am not hear"); 14 | return "underflow" 15 | }else{ 16 | return this.item.shift() 17 | } 18 | } 19 | print (){ 20 | let i=0 21 | while(i < this.item.length){ 22 | console.log(this.item[i]); 23 | i++; 24 | 25 | } 26 | } 27 | } 28 | 29 | 30 | 31 | 32 | let queue = new Queue(); 33 | 34 | queue.enqueue(23); 35 | queue.enqueue(67); 36 | queue.dequeue(); 37 | queue.print() -------------------------------------------------------------------------------- /Queue/demoqueue.js: -------------------------------------------------------------------------------- 1 | class Queue{ 2 | constructor(){ 3 | this.items = {} 4 | this.frond = 0 5 | this.back = 0 6 | 7 | } 8 | enqueue(item){ 9 | this.items[this.back]=item 10 | this.back++ 11 | return item + 'data added' 12 | 13 | } 14 | 15 | dequeue(){ 16 | 17 | const item=this.items[this.frond] 18 | delete this.items[this.frond] 19 | this.frond++ 20 | return item + 'first data delete' 21 | 22 | } 23 | 24 | peek(){ 25 | return this.items[this.frond]+ 'pic the first one' 26 | } 27 | get data(){ 28 | return this.items 29 | } 30 | 31 | check(){ 32 | if( this.items.lenght==0){ 33 | console.log("empty"); 34 | }else{ 35 | console.log("dataadsad"); 36 | } 37 | } 38 | } 39 | 40 | 41 | 42 | const queue = new Queue() 43 | 44 | console.log(queue.enqueue(7)); 45 | console.log(queue.enqueue(7)); 46 | console.log(queue.enqueue(7)); 47 | console.log(queue.dequeue(7)); 48 | console.log(queue.peek()); 49 | const data=queue.data 50 | console.log(data); 51 | queue.check() 52 | -------------------------------------------------------------------------------- /Queue/linkedList.js: -------------------------------------------------------------------------------- 1 | 2 | class Queue { 3 | constructor() { 4 | this.items = {} 5 | this.front = 0 6 | this.back = 0 7 | } 8 | enqueue(item) { 9 | this.items[this.back] = item 10 | this.back++ 11 | return item + ' inserted' 12 | } 13 | dequeue() { 14 | const item = this.items[this.front] 15 | delete this.items[this.front] 16 | this.front++ 17 | return item + ' deleted front' 18 | } 19 | peek() { 20 | return this.items[this.front] + " pic first One" 21 | } 22 | get printQueue() { 23 | return this.items; 24 | } 25 | } 26 | const queue = new Queue() 27 | console.log(queue.enqueue(7)) 28 | console.log(queue.enqueue(2)) 29 | console.log(queue.enqueue(6)) 30 | console.log(queue.enqueue(4)) 31 | console.log(queue.enqueue(6)) 32 | console.log(queue.dequeue()) 33 | console.log(queue.peek()) 34 | console.log(queue.peek()) 35 | var str = queue.printQueue; 36 | console.log(str) 37 | -------------------------------------------------------------------------------- /Queue/tempCodeRunnerFile.js: -------------------------------------------------------------------------------- 1 | 23 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🌐 DataStructure.js 2 | 3 | ## 📚 Overview 4 | 5 | A comprehensive JavaScript library implementing fundamental data structures and algorithms, designed to provide efficient and reusable solutions for developers. 6 | 7 | ## 🚀 Features 8 | 9 | ### Data Structures 10 | - 📊 Arrays 11 | - 🌳 Trees 12 | - Binary Tree 13 | - Binary Search Tree 14 | - AVL Tree 15 | - Red-Black Tree 16 | - 📦 Stacks 17 | - 📮 Queues 18 | - Standard Queue 19 | - Priority Queue 20 | - Circular Queue 21 | - 🔗 Linked Lists 22 | - Singly Linked List 23 | - Doubly Linked List 24 | - Circular Linked List 25 | - 🕸️ Graphs 26 | - Adjacency List 27 | - Adjacency Matrix 28 | - 🗺️ Hash Tables 29 | - 🌲 Heaps 30 | - Min Heap 31 | - Max Heap 32 | 33 | ### Algorithms 34 | - 🔍 Searching 35 | - Linear Search 36 | - Binary Search 37 | - 🔢 Sorting 38 | - Bubble Sort 39 | - Quick Sort 40 | - Merge Sort 41 | - Insertion Sort 42 | - 🗺️ Graph Algorithms 43 | - Dijkstra's Shortest Path 44 | - Breadth-First Search 45 | - Depth-First Search 46 | - 🌳 Tree Traversals 47 | - In-order 48 | - Pre-order 49 | - Post-order 50 | 51 | ## 🛠 Installation 52 | 53 | ```bash 54 | # Clone the repository 55 | git clone https://github.com/AjmalDevala/DataStructure_js.git 56 | 57 | # Navigate to project directory 58 | cd DataStructure-js 59 | 60 | # Install dependencies 61 | npm install 62 | ``` 63 | 64 | ## 💻 Usage Example 65 | 66 | ```javascript 67 | // Create a Binary Search Tree 68 | const bst = new BinarySearchTree(); 69 | bst.insert(10); 70 | bst.insert(5); 71 | bst.insert(15); 72 | 73 | // Perform operations 74 | console.log(bst.search(5)); // Returns the node 75 | bst.delete(10); 76 | ``` 77 | 78 | ## 🤝 Contributing 79 | 80 | 1. Fork the repository 81 | 2. Create your feature branch (`git checkout -b feature/AmazingFeature`) 82 | 3. Commit your changes (`git commit -m 'Add some AmazingFeature'`) 83 | 4. Push to the branch (`git push origin feature/AmazingFeature`) 84 | 5. Open a Pull Request 85 | 86 | ## 👤 Author 87 | # Ajmal Devala 👨‍💻 88 | [![LinkedIn](https://img.shields.io/badge/LinkedIn-blue?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/ajmal-devala/) 89 | [![GitHub](https://img.shields.io/badge/GitHub-black?style=for-the-badge&logo=github&logoColor=white)](https://github.com/AjmalDevala) 90 | [![Email](https://img.shields.io/badge/Email-D14836?style=for-the-badge&logo=gmail&logoColor=white)](mailto:ajmaldevala@gmail.com) 91 | 92 | ## 📄 License 93 | 94 | Distributed under the MIT License. See `LICENSE` for more information. 95 | -------------------------------------------------------------------------------- /Stack/array.js: -------------------------------------------------------------------------------- 1 | let top = -1; 2 | let max = 100; 3 | let a = Array(max) 4 | 5 | 6 | 7 | const push = (data) =>{ 8 | if ( top > max ){ 9 | console.log("Stack Overflow") 10 | return false 11 | }else{ 12 | top += 1; 13 | a[top] = data 14 | console.log("Pushed to Stack"); 15 | return true 16 | } 17 | } 18 | 19 | const pop = () =>{ 20 | if (top < 0 ){ 21 | console.log ("Stack Underflow") 22 | return 0 ; 23 | }else { 24 | let temp = a[top] 25 | top -= 1 26 | return temp 27 | } 28 | } 29 | 30 | const print =()=>{ 31 | i = top 32 | while(i>=0){ 33 | console.log(a[i]+"") 34 | i-- 35 | } 36 | } 37 | 38 | 39 | push(10) 40 | push(20) 41 | pop(10) 42 | print() 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Stack/demo.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AjmalDevala/DataStructure_js/87c47241a2bed224047ce0890ae50227833b1013/Stack/demo.js -------------------------------------------------------------------------------- /Stack/linkedList.js: -------------------------------------------------------------------------------- 1 | let root; 2 | 3 | class StackNode { 4 | constructor(data){ 5 | this.data = data 6 | this.next = null 7 | } 8 | } 9 | 10 | const push = (data) =>{ 11 | const newNode = new StackNode(data) 12 | if (root == null){ 13 | root = newNode; 14 | }else{ 15 | let temp = root 16 | root = newNode 17 | newNode.next = temp 18 | } 19 | console.log("Pushed to Stack") 20 | } 21 | 22 | const pop = () =>{ 23 | if (root == null){ 24 | console.log("Stack Underflow") 25 | return 26 | }else{ 27 | var popped = root.data 28 | root = root.next; 29 | } 30 | return popped 31 | } 32 | 33 | const print = ()=>{ 34 | let current = root 35 | while(current != null){ 36 | console.log(current.data) 37 | current = current.next 38 | } 39 | } 40 | 41 | push(10) 42 | push(10) 43 | push(10) 44 | pop(1) 45 | print() -------------------------------------------------------------------------------- /data/demo.js: -------------------------------------------------------------------------------- 1 | let root 2 | class StackNode{ 3 | constructor(data){ 4 | this.data=data 5 | this.next=null 6 | } 7 | } 8 | const push =(data)=>{ 9 | const newNode=new StackNode(data) 10 | if(root==null){ 11 | root=new StackNode 12 | }else{ 13 | let temp=root 14 | root =newNode 15 | newNode.next=temp 16 | } 17 | console.log("pushed to stack"); 18 | } 19 | 20 | const print=()=>{ 21 | let current=root 22 | while(current!= null){ 23 | console.log(current.data); 24 | current=current.next 25 | } 26 | } 27 | 28 | push(12) 29 | push(2) 30 | 31 | print() -------------------------------------------------------------------------------- /data/tempCodeRunnerFile.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AjmalDevala/DataStructure_js/87c47241a2bed224047ce0890ae50227833b1013/data/tempCodeRunnerFile.js -------------------------------------------------------------------------------- /graph/BFS.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor() { 3 | this.adjacencyList = {}; 4 | } 5 | 6 | addVertex(vertex) { 7 | if (!this.adjacencyList[vertex]) {this.adjacencyList[vertex] = []; 8 | } 9 | } 10 | 11 | addEdge(v1, v2) { 12 | this.adjacencyList[v1].push(v2); 13 | this.adjacencyList[v2].push(v1); 14 | } 15 | 16 | // BFS Traversing from a to small 17 | breadthFirst(start) { 18 | const queue = [start]; 19 | const result = []; 20 | const visited = {}; 21 | let currentVertex; 22 | visited[start] = true; 23 | 24 | while (queue.length) { 25 | currentVertex = queue.shift(); 26 | result.push(currentVertex); 27 | 28 | this.adjacencyList[currentVertex].forEach((neighbor) => { 29 | if (!visited[neighbor]) { 30 | visited[neighbor] = true; 31 | queue.push(neighbor); 32 | } 33 | }); 34 | } 35 | return result; 36 | } 37 | 38 | // BFS Traversing from a to big 39 | // breadthFirstSecond(start) { 40 | // const queue = [start]; 41 | // const result = []; 42 | // const visited = {}; 43 | // let currentVertex; 44 | // visited[start] = true; 45 | 46 | // while (queue.length) { 47 | // currentVertex = queue.shift(); 48 | // result.push(currentVertex); 49 | 50 | // this.adjacencyList[currentVertex] 51 | // .slice() 52 | // .reverse() 53 | // .forEach((neighbor) => { 54 | // if (!visited[neighbor]) { 55 | // visited[neighbor] = true; 56 | // queue.push(neighbor); 57 | // } 58 | // }); 59 | // } 60 | // return result; 61 | // } 62 | } 63 | 64 | 65 | 66 | var g = new Graph(); 67 | 68 | g.addVertex("A"); 69 | g.addVertex("B"); 70 | g.addVertex("C"); 71 | g.addVertex("D"); 72 | g.addVertex("E"); 73 | g.addVertex("F"); 74 | 75 | g.addEdge("A", "B"); 76 | g.addEdge("A", "C"); 77 | g.addEdge("B", "D"); 78 | g.addEdge("C", "E"); 79 | g.addEdge("D", "E"); 80 | g.addEdge("D", "F"); 81 | g.addEdge("E", "F"); 82 | 83 | console.log(g.breadthFirst("A")); 84 | // console.log(g.breadthFirstSecond("A")); -------------------------------------------------------------------------------- /graph/DFS.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor() { 3 | this.adjacencyList = {}; 4 | } 5 | 6 | addVertex(vertex) { 7 | if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = []; 8 | } 9 | 10 | addEdge(v1, v2) { 11 | this.adjacencyList[v1].push(v2); 12 | this.adjacencyList[v2].push(v1); 13 | } 14 | 15 | // DFS Traversing Recursive 16 | 17 | depthFirstRecursive(start) { 18 | const result = []; 19 | const visited = {}; 20 | const adjacencyList = this.adjacencyList; 21 | 22 | (function dfs(vertex) { 23 | if (!vertex) return null; 24 | visited[vertex] = true; 25 | result.push(vertex); 26 | adjacencyList[vertex].forEach((neighbour) => { 27 | if (!visited[neighbour]) { 28 | return dfs(neighbour); 29 | } 30 | }); 31 | })(start); 32 | return result; 33 | } 34 | } 35 | 36 | var g = new Graph(); 37 | 38 | g.addVertex("A"); 39 | g.addVertex("B"); 40 | g.addVertex("C"); 41 | g.addVertex("D"); 42 | g.addVertex("E"); 43 | g.addVertex("F"); 44 | 45 | g.addEdge("A", "B"); 46 | g.addEdge("A", "C"); 47 | g.addEdge("B", "D"); 48 | g.addEdge("C", "E"); 49 | g.addEdge("D", "E"); 50 | g.addEdge("D", "F"); 51 | g.addEdge("E", "F"); 52 | 53 | // g.depthFirstRecursive("E"); 54 | console.log(g.depthFirstRecursive("D")); -------------------------------------------------------------------------------- /graph/graph.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor(noOfVertices) { 3 | this.noOfVertices = noOfVertices; 4 | this.adj = new Map(); 5 | } 6 | addVertex(v) { 7 | this.adj.set(v, []); 8 | } 9 | addEdges(v, e) { 10 | this.adj.get(v).push(e); 11 | } 12 | printGraph() { 13 | let keys = this.adj.keys(); 14 | for (let i of keys) { 15 | let getValues = this.adj.get(i); 16 | let edge = ""; 17 | 18 | for (let j of getValues) { 19 | edge += j + " "; 20 | } 21 | 22 | console.log(i + "-->" + edge); 23 | } 24 | } 25 | 26 | breadthFirst(start) { 27 | const queue = [start]; 28 | const result = []; 29 | const visited = {}; 30 | let currentVertex; 31 | visited[start] = true; 32 | 33 | while (queue.length) { 34 | currentVertex = queue.shift(); 35 | result.push(currentVertex); 36 | 37 | this.adj.get(currentVertex).forEach((neighbor) => { 38 | if (!visited[neighbor]) { 39 | visited[neighbor] = true; 40 | queue.push(neighbor); 41 | } 42 | }); 43 | } 44 | return result; 45 | } 46 | 47 | dfs(startingNode) { 48 | var visited = {}; 49 | this.dfsHelper(startingNode, visited); 50 | let keys =this.adj.keys 51 | 52 | for(let value in keys){ 53 | this.adj.get(value).forEach((elem)=>{ 54 | if(!visited[elem]){ 55 | return false 56 | } 57 | }) 58 | } 59 | return true 60 | } 61 | dfsHelper(vert, visited) { 62 | visited[vert] = true; 63 | // console.log(vert); 64 | 65 | var get_neighbours = this.adj.get(vert); 66 | 67 | for (var i in get_neighbours) { 68 | var get_elem = get_neighbours[i]; 69 | if (!visited[get_elem]) { 70 | this.dfsHelper(get_elem, visited); 71 | } 72 | } 73 | } 74 | } 75 | 76 | const g = new Graph(6); 77 | 78 | g.addVertex("A"); 79 | g.addVertex("B"); 80 | g.addVertex("C"); 81 | g.addVertex("D"); 82 | 83 | g.addEdges("A", "B"); 84 | g.addEdges("C", "D"); 85 | g.addEdges("A", "D"); 86 | 87 | g.printGraph() 88 | 89 | console.log(g.breadthFirst("A")) 90 | console.log(g.dfs('A')) -------------------------------------------------------------------------------- /graph/problem1.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor() { 3 | this.vertices = {}; 4 | } 5 | 6 | addVertex(vertex) { 7 | this.vertices[vertex] = {}; 8 | } 9 | 10 | addEdge(vertex1, vertex2, weight) { 11 | this.vertices[vertex1][vertex2] = weight; 12 | this.vertices[vertex2][vertex1] = weight; 13 | } 14 | 15 | dijkstra(start, end) { 16 | const distances = {}; 17 | const visited = {}; 18 | const previous = {}; 19 | const queue = new PriorityQueue(); 20 | 21 | for (const vertex in this.vertices) { 22 | distances[vertex] = Infinity; 23 | visited[vertex] = false; 24 | previous[vertex] = null; 25 | } 26 | 27 | distances[start] = 0; 28 | queue.enqueue([start, 0]); 29 | 30 | while (!queue.isEmpty()) { 31 | const [vertex, distance] = queue.dequeue(); 32 | 33 | if (vertex === end) { 34 | break; 35 | } 36 | 37 | if (visited[vertex]) { 38 | continue; 39 | } 40 | 41 | visited[vertex] = true; 42 | 43 | for (const neighbor in this.vertices[vertex]) { 44 | const newDistance = distances[vertex] + this.vertices[vertex][neighbor]; 45 | 46 | if (newDistance < distances[neighbor]) { 47 | distances[neighbor] = newDistance; 48 | previous[neighbor] = vertex; 49 | queue.enqueue([neighbor, newDistance]); 50 | } 51 | } 52 | } 53 | 54 | return { distances, previous }; 55 | } 56 | } 57 | 58 | class PriorityQueue { 59 | constructor() { 60 | this.queue = []; 61 | } 62 | 63 | enqueue(element) { 64 | this.queue.push(element); 65 | this.queue.sort((a, b) => a[1] - b[1]); 66 | } 67 | 68 | dequeue() { 69 | return this.queue.shift(); 70 | } 71 | 72 | isEmpty() { 73 | return this.queue.length === 0; 74 | } 75 | } 76 | 77 | 78 | const graph = new Graph() 79 | graph.addVertex('A') 80 | graph.addVertex('B') 81 | graph.addVertex('C') 82 | graph.addVertex('D') 83 | graph.addVertex('E') 84 | graph.addEdge('A','B',3) 85 | graph.addEdge('C','B',5) 86 | graph.addEdge('A','C',10) 87 | graph.addEdge('C','D',22) 88 | graph.addEdge('D','E',7) 89 | graph.addEdge('A','E',11) 90 | console.log(graph.dijkstra('A','B')) -------------------------------------------------------------------------------- /graph/problem2.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor() { 3 | this.adjacencyList = {}; 4 | } 5 | 6 | addVertex(vertex) { 7 | if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = []; 8 | } 9 | 10 | addEdge(v1, v2) { 11 | this.adjacencyList[v1].push(v2); 12 | this.adjacencyList[v2].push(v1); 13 | } 14 | 15 | removeEdge(v1, v2) { 16 | this.adjacencyList[v1] = this.adjacencyList[v1].filter((v) => v !== v2); 17 | this.adjacencyList[v2] = this.adjacencyList[v2].filter((v) => v !== v1); 18 | } 19 | 20 | removeVertex(vertex) { 21 | while (this.adjacencyList[vertex].length) { 22 | const adjacentVertex = this.adjacencyList[vertex].pop(); 23 | this.removeEdge(vertex, adjacentVertex); 24 | } 25 | delete this.adjacencyList[vertex] 26 | } 27 | } 28 | 29 | var g = new Graph(); 30 | g.addVertex("Dallas"); 31 | g.addVertex("Tokyo"); 32 | g.addVertex("Aspen"); 33 | g.addVertex("Los Angeles"); 34 | g.addVertex("Hong Kong") 35 | 36 | 37 | g.addEdge("Dallas", "Tokyo"); 38 | g.addEdge("Dallas", "Aspen"); 39 | g.addEdge("Hong Kong", "Tokyo"); 40 | g.addEdge("Hong Kong", "Dallas"); 41 | g.addEdge("Los Angeles", "Hong Kong"); 42 | g.addEdge("Los Angeles", "Aspen"); 43 | 44 | g.removeEdge("Dallas","Tokyo") 45 | g.removeVertex("Dallas") 46 | console.log(g); -------------------------------------------------------------------------------- /hashTable/hashTableSimple.js: -------------------------------------------------------------------------------- 1 | class hashTable { 2 | constructor(){ 3 | this.table = new Array(100) 4 | this.size = 0 5 | } 6 | hash(key){ 7 | let total = 0 8 | for (let i = 0; i < key.length; i++) { 9 | total += key.charCodeAt(i) 10 | } 11 | return total % this.table.length 12 | } 13 | set(key, value){ 14 | const index = this.hash(key) 15 | this.table[index] = [key, value] 16 | this.size++ 17 | } 18 | get(key){ 19 | const index = this.hash(key) 20 | return this.table[index] 21 | } 22 | remove(key){ 23 | const index = this.hash(key) 24 | this.table[index] = [] 25 | } 26 | 27 | } 28 | const ht = new hashTable() 29 | ht.set("ajmal", 4) 30 | ht.set("fsl", 94) 31 | ht.set("ameer", 4) 32 | 33 | // console.log(table.get("phone")); 34 | ht.remove("ameer") 35 | console.log(ht) -------------------------------------------------------------------------------- /hashTable/hashtable.js: -------------------------------------------------------------------------------- 1 | class HashTable { 2 | constructor() { 3 | this.table = new Array(100); 4 | this.size = 0; 5 | } 6 | 7 | _hash(key) { 8 | let hash = 0; 9 | for (let i = 0; i < key.length; i++) { 10 | hash += key.charCodeAt(i); 11 | } 12 | return hash % this.table.length; 13 | } 14 | 15 | set(key, value) { 16 | const index = this._hash(key); 17 | this.table[index] = [key, value]; 18 | this.size++; 19 | } 20 | 21 | get(key) { 22 | const target = this._hash(key); 23 | return this.table[target]; 24 | } 25 | 26 | remove(key) { 27 | const index = this._hash(key); 28 | if (this.table[index] && this.table[index].length) { 29 | this.table[index] = []; 30 | this.size--; 31 | return true; 32 | } else { 33 | return false; 34 | } 35 | } 36 | } 37 | 38 | const ht = new HashTable(); 39 | 40 | ht.set("Canada", 300); 41 | ht.set("France", 100); 42 | ht.set("India", 100); 43 | 44 | console.log(ht.get("Canada")); 45 | console.log(ht.get("France")); 46 | console.log(ht.get("India")); 47 | console.log(ht.remove("India")); 48 | console.log(ht.get("Canada")); 49 | console.log(ht) 50 | -------------------------------------------------------------------------------- /hashTable/test.js: -------------------------------------------------------------------------------- 1 | // class HashTable { 2 | // constructor(){ 3 | // this.table = new Array(100) 4 | // this.size = 0 5 | 6 | // } 7 | 8 | // _hash(key){ 9 | // let hash=[] 10 | // for(let i=0 ; i leftChild && root > rightChild) { 11 | console.log("max heap"); 12 | } else { 13 | console.log("Min heap"); 14 | } 15 | } 16 | } 17 | 18 | let arr = [1, 5, 10, 6, 8, 12, 15] 19 | let a = new heap(arr); 20 | a.check(); 21 | 22 | let ar = [20,15,18,10,8,16,17] 23 | let b = new heap(ar) 24 | b.check(); -------------------------------------------------------------------------------- /heaps/heap.js: -------------------------------------------------------------------------------- 1 | function heapify(arr) { 2 | const n = arr.length; 3 | for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { 4 | heapifyHelper(arr, n, i); 5 | } 6 | } 7 | 8 | function heapifyHelper(arr, n, i) { 9 | let smallest = i; 10 | const left = 2 * i + 1; 11 | const right = 2 * i + 2; 12 | 13 | if (left < n && arr[left] < arr[smallest]) { 14 | smallest = left; 15 | } 16 | 17 | if (right < n && arr[right] < arr[smallest]) { 18 | smallest = right; 19 | } 20 | 21 | if (smallest != i) { 22 | [arr[i], arr[smallest]] = [arr[smallest], arr[i]]; 23 | heapifyHelper(arr, n, smallest); 24 | } 25 | } 26 | 27 | function insert(arr, value) { 28 | arr.push(value); 29 | let index = arr.length - 1; 30 | while (index > 0) { 31 | const parentIndex = Math.floor((index - 1) / 2); 32 | if (arr[parentIndex] > arr[index]) { 33 | [arr[parentIndex], arr[index]] = [arr[index], arr[parentIndex]]; 34 | index = parentIndex; 35 | } else { 36 | break; 37 | } 38 | } 39 | } 40 | 41 | function getMin(arr) { 42 | if (arr.length === 0) { 43 | return null; 44 | } 45 | const min = arr[0]; 46 | arr[0] = arr[arr.length - 1]; 47 | arr.pop(); 48 | heapifyHelper(arr, arr.length, 0); 49 | return min; 50 | } 51 | 52 | function remove(arr, value) { 53 | const index = arr.indexOf(value); 54 | if (index === -1) { 55 | return false; // value not found in the heap 56 | } 57 | arr[index] = arr[arr.length - 1]; // swap the element in end 58 | arr.pop(); 59 | heapifyHelper(arr, arr.length, index); 60 | return true; // value removed successfully 61 | } 62 | 63 | 64 | 65 | // Example usage: 66 | const arr=[7,87,6,3,2,-4] 67 | heapify(arr); 68 | console.log(arr); // [1, 2, 9, 5, 7] 69 | // insert(arr, -6); 70 | remove(arr,87); // removed the location 71 | console.log(arr); // [1, 2, 3, 5, 7, 9] 72 | // console.log(getMin(arr)); // 1 73 | console.log(arr); // [2, 5, 3, 9, 7] -------------------------------------------------------------------------------- /heaps/max-heap.js: -------------------------------------------------------------------------------- 1 | function buildHeap(arr) { 2 | const n = arr.length; 3 | for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { 4 | heapify(arr, i, n); // i will be last parent node 5 | } 6 | } 7 | 8 | function heapify(arr, i, n) { 9 | let largest = i; 10 | let leftChild = 2 * i + 1; 11 | let rightChild = 2 * i + 2; 12 | 13 | if (leftChild < n && arr[leftChild] > arr[largest]) { 14 | largest = leftChild; 15 | } 16 | 17 | if (rightChild < n && arr[rightChild] > arr[largest]) { 18 | largest = rightChild; 19 | } 20 | 21 | if (largest != i) { 22 | [arr[largest], arr[i]] = [arr[i], arr[largest]]; 23 | heapify(arr, largest, n); 24 | } 25 | } 26 | 27 | const arr= [3,5,6,3,23,1,3,6] 28 | 29 | buildHeap(arr); 30 | console.log(arr); -------------------------------------------------------------------------------- /heaps/min-heap.js: -------------------------------------------------------------------------------- 1 | function buildHeap(arr) { 2 | const n = arr.length; 3 | for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { 4 | heapify(arr, i, n); // i will be last the parent node 5 | } 6 | } 7 | 8 | function heapify(arr, i, n) { 9 | let smallest = i; 10 | let leftChild = 2 * i + 1; 11 | let rightChild = 2 * i + 2; 12 | 13 | if (leftChild < n && arr[leftChild] < arr[smallest]) { 14 | smallest = leftChild; 15 | } 16 | 17 | if (rightChild < n && arr[rightChild] < arr[smallest]) { 18 | smallest = rightChild; 19 | } 20 | 21 | if (smallest != i) { 22 | [arr[smallest], arr[i]] = [arr[i], arr[smallest]]; 23 | heapify(arr, smallest, n); 24 | } 25 | } 26 | 27 | const arr= [4,2,1,4,6,7,-1] 28 | 29 | buildHeap(arr); 30 | console.log(arr); -------------------------------------------------------------------------------- /heaps/operations.js: -------------------------------------------------------------------------------- 1 | function insert(heap, value) { 2 | heap.push(value); 3 | let currIndx = heap.length - 1; 4 | 5 | while (currIndx > 0) { 6 | let parent = Math.floor((currIndx - 1) / 2); 7 | if (heap[currIndx] < heap[parent]) { 8 | [heap[currIndx], heap[parent]] = [heap[parent], heap[currIndx]]; 9 | currIndx = parent; 10 | } else { 11 | break; 12 | } 13 | } 14 | } 15 | 16 | function remove(heap) { 17 | const n = heap.length; 18 | [heap[0], heap[n - 1]] = [heap[n - 1], heap[0]]; 19 | const removeValu = heap.pop(); 20 | 21 | let currIndx = 0; 22 | // shift down moving 23 | while (2 * currIndx + 1 < heap.length) { 24 | // there check left child exist or not 25 | let leftChild = 2 * currIndx + 1; 26 | let rightChild = 2 * currIndx + 2; 27 | let minChildIndx = rightChild < heap.length && heap[rightChild] < heap[leftChild] 28 | ? rightChild 29 | : leftChild; 30 | 31 | if (heap[minChildIndx] < heap[currIndx]) { 32 | [heap[currIndx], heap[minChildIndx]] = [heap[minChildIndx],heap[currIndx],]; 33 | currIndx = minChildIndx; 34 | } else { 35 | break; 36 | } 37 | } 38 | return removeValu; 39 | } 40 | 41 | function secondLargest(heap){ 42 | if (heap[1] > heap[2] ){ 43 | return heap[1] 44 | }else{ 45 | return heap[2] 46 | } 47 | } 48 | 49 | let heap = [2, 4, 25, 67, 10]; 50 | insert(heap, 50); 51 | insert(heap, 87); 52 | insert(heap, 15); 53 | insert(heap, 3); 54 | remove(heap); 55 | console.log(heap) 56 | console.log(secondLargest(heap)) -------------------------------------------------------------------------------- /heaps/test.js: -------------------------------------------------------------------------------- 1 | function heap(array) { 2 | let n = array.length 3 | for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { 4 | heapify(array, i, n) 5 | } 6 | } 7 | function heapify(array, i, n) { 8 | let smallest = i 9 | let leftchild = 2 * i + 1 10 | let rightchild = 2 * i + 2 11 | if (leftchild < n && array[leftchild] < array[smallest]) { 12 | smallest = leftchild 13 | } 14 | if (rightchild < n && array[rightchild] < array[smallest]) { 15 | smallest = rightchild 16 | } 17 | if (smallest != i) { 18 | [array[i], array[smallest]] = [array[smallest], array[i]] 19 | heapify(array, smallest, n) 20 | } 21 | } 22 | 23 | function insert(array, value) { 24 | array.push(value) 25 | let n = array.length - 1 26 | while (n > 0) { 27 | const pi = Math.floor((n - 1) / 2) 28 | if(array[pi] > array[n]){ 29 | [array[pi],array[n]] =[array[n],array[pi]] 30 | n =pi 31 | }else{ 32 | break; 33 | } 34 | 35 | } 36 | } 37 | 38 | const a = [3, 54, 6, 3, 1, 23, 45, 6, 7, 7] 39 | heap(a) 40 | console.log(a) 41 | insert(a,- 1) 42 | // remove(a,54) 43 | console.log(a) -------------------------------------------------------------------------------- /recursion/fibonacci.js: -------------------------------------------------------------------------------- 1 | function fibonacci(n) { 2 | if(n < 2) { 3 | return n 4 | } 5 | return fibonacci(n-1) + fibonacci(n-2) 6 | } 7 | 8 | function printFib(n) { 9 | for(let i = 0; i <= n; i++) { 10 | console.log(fibonacci(i)) 11 | } 12 | } 13 | 14 | printFib(8) -------------------------------------------------------------------------------- /recursion/prime.js: -------------------------------------------------------------------------------- 1 | 2 | // Function to check if a number is prime 3 | 4 | function isPrime(num) { 5 | if (num <= 1) { 6 | return false; 7 | } 8 | for (let i = 2; i <= Math.sqrt(num); i++) { 9 | if (num % i === 0) { 10 | return false; 11 | } 12 | } 13 | return true; 14 | } 15 | 16 | const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 17 | 18 | for (let i = 0; i < numbers.length; i++) { 19 | if (isPrime(numbers[i])) { 20 | console.log(numbers[i]+" is prime number"); 21 | } 22 | } 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /recursion/singlePrime.js: -------------------------------------------------------------------------------- 1 | function isPrime(num) { 2 | if(num < 2) { 3 | return false 4 | } 5 | return primeHelper(num, num - 1) 6 | } 7 | 8 | function primeHelper(num, i) { 9 | if(i === 1) { 10 | return true 11 | } else if(num%i === 0) { 12 | return false 13 | } else { 14 | return primeHelper(num, i - 1) 15 | } 16 | } 17 | 18 | console.log(isPrime(29)) -------------------------------------------------------------------------------- /sorting/allsort/allsort.js: -------------------------------------------------------------------------------- 1 | // bubble sort 2 | function bubbleSort(arr, n) { 3 | let i, j, swapped, temp; 4 | for (i = 0; i < n - 1; i++) { 5 | swapped = false; 6 | for (j = 0; j < n - i - 1; j++) { 7 | if (arr[j] > arr[j + 1]) { 8 | temp = arr[j]; 9 | arr[j] = arr[j + 1]; 10 | arr[j + 1] = temp; 11 | swapped = true; 12 | } 13 | } 14 | if (swapped == false) { 15 | break; 16 | } 17 | } 18 | } 19 | 20 | // selection sort 21 | function swap(arr, x, y) { 22 | let temp = arr[x]; 23 | arr[x] = arr[y]; 24 | arr[y] = temp; 25 | } 26 | function selectionSort(arr, n) { 27 | let i, j, min_index; 28 | for (i = 0; i < n - 1; i++) { 29 | min_index = i; 30 | for (j = i + 1; j < n; j++) { 31 | if (arr[j] < arr[min_index]) { 32 | min_index = j; 33 | } 34 | } 35 | swap(arr, min_index, i); 36 | } 37 | } 38 | 39 | // insertion sort 40 | function insertionSort(arr, n) { 41 | let i, j, key; 42 | for (i = 1; i < n; i++) { 43 | key = arr[i]; 44 | j = i - 1; 45 | 46 | while (j >= 0 && arr[j] > key) { 47 | arr[j + 1] = arr[j]; 48 | j = j - 1; 49 | } 50 | arr[j + 1] = key; 51 | } 52 | } 53 | 54 | // selection swap 55 | function swap(arr, x, y) { 56 | var temp = arr[x]; 57 | arr[x] = arr[y]; 58 | arr[y] = temp; 59 | } 60 | function selectionSort(arr, n) { 61 | let i, j, min_index; 62 | for (i = 0; i < n - 1; i++) { 63 | min_index = i; 64 | for (j = i + 1; j < n; j++) { 65 | if (arr[j] < arr[min_index]) { 66 | min_index = j; 67 | } 68 | } 69 | swap(arr, min_index, i); 70 | } 71 | } 72 | 73 | // bubble sort 74 | function bubbleSort(arr, n) { 75 | let i, j, swapped, temp; 76 | for (i = 0; i < n - 1; i++) { 77 | swapped = false; 78 | for (j = 0; j < n - i - 1; j++) { 79 | if (arr[j] > arr[j + 1]) { 80 | temp = arr[j]; 81 | arr[j] = arr[j + 1]; 82 | arr[j + 1] = temp; 83 | swapped = true; 84 | } 85 | } 86 | if (swapped == false) { 87 | break; 88 | } 89 | } 90 | } 91 | 92 | function insertionSort(arr, n) { 93 | let i, j, key; 94 | for (i = 0; i < n; i++) { 95 | key = arr[i]; 96 | j = i - 1; 97 | while (j >= 0 && arr[j] > key) { 98 | arr[j + 1] = arr[j]; 99 | j = j - 1; 100 | } 101 | arr[j + 1] = key; 102 | } 103 | } 104 | 105 | function bubbleSort(arr, n) { 106 | let i, j, swapped, temp; 107 | for (i = 0; i < n - 1; i++) { 108 | swapped = false; 109 | for (j = 0; j < n - i - 1; j++) { 110 | if (arr[j] > arr[j + 1]) { 111 | temp = arr[j]; 112 | arr[j] = arr[j + 1]; 113 | arr[j + 1] = temp; 114 | swapped = true; 115 | } 116 | } 117 | if (swapped == false) { 118 | break; 119 | } 120 | } 121 | } 122 | 123 | function insertionSort(arr, n) { 124 | let i, j, key; 125 | for (i = 0; i < n; i++) { 126 | key = arr[i]; 127 | j = i - 1; 128 | while (j >= 0 && arr[j] > key) { 129 | arr[j + 1] = arr[j]; 130 | j = j - 1; 131 | } 132 | arr[j + 1] = key; 133 | } 134 | } 135 | 136 | function selectionSort(arr, n){ 137 | let i,j,min_index 138 | for(i=0;i array[j+1]){ 6 | temp = array[j+1] 7 | array[j+1]= array[j] 8 | array[j]= temp 9 | } 10 | } 11 | } 12 | return array 13 | } 14 | 15 | 16 | console.log(bubbleSort([4,3,4,23,5,2,1])) 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /sorting/bubbleSort/optimised_method.js: -------------------------------------------------------------------------------- 1 | // Optimized javaScript implementation 2 | // of Bubble sort 3 | // An optimized version of Bubble Sort 4 | 5 | function bubbleSort(arr, n) { 6 | let swapped, i, j, temp; 7 | for (i = 0; i < n - 1; i++) { 8 | // console.log(i); 9 | swapped = false; 10 | for (j = 0; j < n - i - 1; j++) { 11 | // console.log(j+"j"); 12 | if (arr[j] > arr[j + 1]) { 13 | //swap arr[j] and arr[j+1] 14 | temp = arr[j]; 15 | arr[j] = arr[j + 1]; 16 | arr[j + 1] = temp; 17 | swapped = true; 18 | } 19 | // IF no two elements were 20 | // swapped by inner loop, then break 21 | } 22 | if (swapped == false) { 23 | console.log("swap false"); 24 | break; 25 | } 26 | } 27 | } 28 | 29 | function printArray(arr, n) { 30 | let i; 31 | for (i = 0; i < n; i++) { 32 | console.log(arr[i]); 33 | } 34 | } 35 | 36 | let arr = [1, 23, 65, 3, 2, 1]; 37 | let n = arr.length; 38 | 39 | bubbleSort(arr, n); 40 | printArray(arr, n); -------------------------------------------------------------------------------- /sorting/bubbleSort/sort.js: -------------------------------------------------------------------------------- 1 | 2 | function bubbleSort(array){ 3 | let n= array.length 4 | let i,j,temp 5 | for(i=0 ; i< n ; i++){ 6 | for(j=0 ; j< n ; j++){ 7 | if( array[j] > array[j+1] ){ 8 | temp= array[j] 9 | array[j]= array[j+1] 10 | array[j+1]=temp 11 | } 12 | } 13 | } 14 | return array 15 | } 16 | 17 | const array= [5,5,23,32,3,2,1,3,5,6] 18 | console.log(bubbleSort(array)) -------------------------------------------------------------------------------- /sorting/heapSort/heapSortLarge.js: -------------------------------------------------------------------------------- 1 | function buildHeap(arr) { 2 | const n = arr.length; 3 | for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { 4 | heapify(arr, i, n); // i will be last the parent node 5 | } 6 | } 7 | 8 | function heapify(arr, i, n) { 9 | let largest = i; 10 | let leftChild = 2 * i + 1; 11 | let rightChild = 2 * i + 2; 12 | 13 | if (leftChild < n && arr[leftChild] < arr[largest]) { 14 | largest = leftChild; 15 | } 16 | 17 | if (rightChild < n && arr[rightChild] < arr[largest]) { 18 | largest = rightChild; 19 | } 20 | 21 | if (largest != i) { 22 | swap(arr, largest, i) 23 | heapify(arr, largest, n); 24 | } 25 | } 26 | 27 | function swap(array, leftIndex, rightIndex) { 28 | [array[leftIndex], array[rightIndex]] = [array[rightIndex], array[leftIndex]]; 29 | } 30 | 31 | const heapSort = (array) => { 32 | buildHeap(array); 33 | let n = array.length - 1; 34 | while (n >= 1) { 35 | swap(array, 0, n); 36 | heapify(array, 0, n); 37 | n--; 38 | } 39 | return array; 40 | }; 41 | 42 | const arr = [13, 1, 9, 7, 6, 3, 8, 88]; 43 | 44 | console.log(heapSort(arr)); -------------------------------------------------------------------------------- /sorting/heapSort/heapSortSmall.js: -------------------------------------------------------------------------------- 1 | function heap(array){ 2 | let n=array.length 3 | for( let i= Math.floor(n/2)-1 ;i>=0 ;i--){ 4 | heapify(array,i ,n) 5 | } 6 | } 7 | 8 | function heapify(array,i ,n){ 9 | let smallest = i 10 | const leftChild =2*i+1 11 | const rightChild =2*i+2 12 | if(leftChild < n && array[leftChild ] > array[smallest]){ 13 | smallest =leftChild 14 | } 15 | if(rightChild < n && array[rightChild] > array[smallest]){ 16 | smallest =rightChild 17 | } 18 | if(smallest != i){ 19 | swap(array,smallest ,i) 20 | heapify(array ,smallest ,n) 21 | } 22 | } 23 | 24 | function swap (array,left,right){ 25 | [array[left] ,array[right]] = [array[right] ,array[left]] 26 | } 27 | 28 | function heapSort(array){ 29 | heap(array) 30 | let n =array.length-1 31 | while(n > 0){ 32 | swap(array ,0 , n) 33 | heapify(array, 0 , n) 34 | n-- 35 | } 36 | return array 37 | } 38 | 39 | const array=[3,5,6,3,3,3,11,31,1] 40 | heapSort (array) 41 | console.log(array) -------------------------------------------------------------------------------- /sorting/heapSort/test.js: -------------------------------------------------------------------------------- 1 | function heap ( array){ 2 | let n = array.length 3 | for(let i = Math.floor(n/2)-1 ; i>=0 ; i--){ 4 | heapify(array,i,n) 5 | } 6 | } 7 | 8 | function heapify(array ,i , n){ 9 | let smallest = i 10 | let left = 2* i +1 11 | let right = 2* i+2 12 | if(left < n && array[left] < array[smallest]){ 13 | smallest = left 14 | } 15 | if(right < n&& array[right] < array[smallest]){ 16 | smallest =right 17 | } 18 | if(smallest != i){ 19 | swap(array,smallest,i) 20 | heapify(array,smallest,n) 21 | } 22 | } 23 | 24 | function swap(array,left,right){ 25 | [array[left],array[right]] = [array[right],array[left]] 26 | } 27 | 28 | function heapSort(array){ 29 | heap(array) 30 | let n= array.length-1 31 | while(n >=0){ 32 | swap(array,0,n) 33 | heapify(array,0,n) 34 | n-- 35 | } 36 | return array 37 | } 38 | 39 | const arr=[5,4,3,2,6,4,3,2] 40 | console.log(heapSort(arr)) -------------------------------------------------------------------------------- /sorting/insertionSort/insertionSort.js: -------------------------------------------------------------------------------- 1 | function insertionSort(arr) { 2 | let i,j 3 | for ( i = 1; i < arr.length; i++) { 4 | let currentVal = arr[i]; 5 | for (j = i-1 ; arr[j] > currentVal; j--) { 6 | arr[j + 1] = arr[j]; 7 | } 8 | arr[j + 1] = currentVal; 9 | } 10 | return arr; 11 | } 12 | 13 | const arr =[9,-7,6,5,4,4,43] 14 | const result = insertionSort(arr) 15 | console.log(result); -------------------------------------------------------------------------------- /sorting/insertionSort/sort.js: -------------------------------------------------------------------------------- 1 | function insertionSort(array){ 2 | let i, j ,currentVal 3 | let n= array.length 4 | for(i=1 ; i < n ; i++){ 5 | currentVal=array[i] 6 | for( j=i-1 ; array[j] > currentVal ; j--){ 7 | array[j+1 ] = array [j] 8 | } 9 | array[j+1] =currentVal 10 | } 11 | return array 12 | } 13 | 14 | console.log(insertionSort([3,4,655,1,3,55,62])) -------------------------------------------------------------------------------- /sorting/mergeSort/mergeSort.js: -------------------------------------------------------------------------------- 1 | // split array 2 | // find mid 3 | // arr splice 4 | // once arr.length is 1 5 | // run merge and sort 6 | 7 | const merge = (arr1, arr2) => { 8 | let sorted = []; 9 | while (arr1.length && arr2.length) { 10 | if (arr1[0] < arr2[0]) sorted.push(arr1.shift()); 11 | else sorted.push(arr2.shift()); 12 | } 13 | return [...sorted, ...arr1, ...arr2]; 14 | }; 15 | 16 | const mergeSort = (arr) => { 17 | if (arr.length <= 1) return arr; 18 | let mid = Math.floor(arr.length / 2), 19 | left = mergeSort(arr.slice(0, mid)), 20 | right = mergeSort(arr.slice(mid)); 21 | return merge(left, right); 22 | }; 23 | 24 | let unsortedArr = [2, 35, 6, 3, 68, 1, 56, 7]; 25 | console.log(mergeSort(unsortedArr)); -------------------------------------------------------------------------------- /sorting/mergeSort/sort.js: -------------------------------------------------------------------------------- 1 | function mergeSort(arr) { 2 | if (arr.length <= 1) return arr; 3 | let mid = Math.floor(arr.length / 2) 4 | let left = mergeSort(arr.slice(0, mid)) 5 | let right = mergeSort(arr.slice(mid)); 6 | return merge(left, right); 7 | } 8 | function merge(arr1, arr2) { 9 | let joinedArr = []; 10 | while (arr1.length && arr2.length) { 11 | if (arr1[0] < arr2[0]) { 12 | joinedArr.push(arr1.shift()); 13 | } 14 | else { 15 | joinedArr.push(arr2.shift()); 16 | } 17 | 18 | } 19 | return [...joinedArr, ...arr1, ...arr2]; 20 | } 21 | const array = [3, 4, 2, 4, 5, 2, 1, 9] 22 | console.log(mergeSort(array)) -------------------------------------------------------------------------------- /sorting/mergeSort/text.js: -------------------------------------------------------------------------------- 1 | // working 2 | //find mid index 3 | //[seperate left and right array index] 4 | //and impliment and find recursive functon and get the single array 5 | //and seperate the array and call function for check the condition 6 | //create an empty array [] 7 | //and puch to array in side an array 8 | // and merge the array 9 | // and return the arrray 10 | 11 | function mergeSort(array) { 12 | if (array.length <= 1) { 13 | return array 14 | } 15 | let mid = Math.floor(array.length / 2) 16 | let left = mergeSort(array.slice(0, mid)) 17 | let right = mergeSort(array.slice(mid)) 18 | return sort(left, right) 19 | } 20 | function sort(left, right) { 21 | let sorted = [] 22 | while (left.length && right.length) { 23 | if (left[0] < right[0]) { 24 | sorted.push(left.shift()) 25 | } else { 26 | sorted.push(right.shift()) 27 | } 28 | } 29 | return [...sorted, ...left, ...right] 30 | } 31 | 32 | const array = [4, 3, 2, 5, 6, 7, 2, 1] 33 | console.log(mergeSort(array)) -------------------------------------------------------------------------------- /sorting/quickSort/quickSort.js: -------------------------------------------------------------------------------- 1 | function swap(items, leftIndex, rightIndex) { 2 | let temp = items[leftIndex]; 3 | items[leftIndex] = items[rightIndex]; 4 | items[rightIndex] = temp; 5 | } 6 | function partition(items, left, right) { 7 | var pivot = items[Math.floor((right + left) / 2)], 8 | i = left, 9 | j = right; 10 | 11 | while (i <= j) { 12 | while (items[i] < pivot) { 13 | i++; 14 | } 15 | while (items[j] > pivot) { 16 | j--; 17 | } 18 | if (i <= j) { 19 | swap(items, i, j); 20 | i++; 21 | j--; 22 | } 23 | } 24 | return i; 25 | } 26 | 27 | function quickSort(items, left, right) { 28 | var index=[] 29 | if (items.length > 1) { 30 | index = partition(items, left, right); 31 | if (left < index - 1) { 32 | quickSort(items, left, index - 1); 33 | } 34 | if (index < right) { 35 | quickSort(items, index, right); 36 | } 37 | } 38 | return items; 39 | } 40 | 41 | var items = [5,3,63, 3, 7, 6, 2,7,5,2 ,3,9]; 42 | var sortedArray = quickSort(items, 0, items.length - 1); 43 | console.log(sortedArray); -------------------------------------------------------------------------------- /sorting/quickSort/quickSort2.js: -------------------------------------------------------------------------------- 1 | function quickSort(array){ 2 | if(array.length <= 1) return array 3 | let pivot =array[array.length-1] 4 | let left = [] 5 | let right =[] 6 | for( let i = 0 ; i < array.length-1 ;i++){ 7 | if(array[i] < pivot ) 8 | { 9 | left.push(array[i]) 10 | }else{ 11 | right.push(array[i]) 12 | } 13 | } 14 | return [...quickSort(left),pivot,...quickSort(right)] 15 | } 16 | 17 | const array=[2,2,4,5632,2312] 18 | 19 | console.log(quickSort(array)) -------------------------------------------------------------------------------- /sorting/quickSort/sort.js: -------------------------------------------------------------------------------- 1 | function swap(array, leftIndex, rightIndex) { 2 | [array[leftIndex], array[rightIndex]] = [ array[rightIndex], array[leftIndex]] 3 | } 4 | 5 | const partition = (array, left, right) => { 6 | let pivotIdx = right; 7 | let startIdx = left; 8 | let endIdx = right; 9 | while(startIdx < endIdx){ 10 | while(array[startIdx] <= array[pivotIdx]){ 11 | startIdx++ 12 | } 13 | while(array[endIdx] > array[pivotIdx]){ 14 | endIdx-- 15 | } 16 | if(startIdx < endIdx){ 17 | swap(array, startIdx, endIdx) 18 | } 19 | } 20 | swap(array, pivotIdx, endIdx) 21 | return endIdx 22 | } 23 | 24 | function quickSort(array, left, right){ 25 | var keyIdx=[] 26 | if(left < right){ 27 | keyIdx = partition(array, left, right) 28 | quickSort(array, left, keyIdx-1) 29 | quickSort(array, keyIdx+1, right) 30 | } 31 | return array 32 | } 33 | 34 | let array = [300, 44, 56, 34, 78,100, 2, 10] 35 | let sortedArray = quickSort(array, 0, array.length - 1); 36 | console.log(sortedArray); -------------------------------------------------------------------------------- /sorting/quickSort/test.js: -------------------------------------------------------------------------------- 1 | function quickSort(array,left,right){ 2 | if(left < right){ 3 | keyin =partition(array,left,right) 4 | quickSort(array,left,keyin-1) 5 | quickSort(array,keyin+1,right) 6 | } 7 | return array 8 | } 9 | 10 | function partition(array,left,right){ 11 | let pivotIdx =right 12 | let startIdx =left 13 | let endIdx =right 14 | while(startIdx < endIdx){ 15 | while(array[startIdx] <= array [pivotIdx]){ 16 | startIdx++ 17 | } 18 | while(array[endIdx] > array [pivotIdx]){ 19 | endIdx -- 20 | } 21 | if(startIdx < endIdx){ 22 | swap(array,startIdx,endIdx) 23 | } 24 | 25 | } 26 | swap(array,pivotIdx,endIdx) 27 | return endIdx 28 | } 29 | 30 | 31 | function swap(array,left,right){ 32 | [array[left],array[right]] = [array[right],array[left]] 33 | } 34 | 35 | 36 | const array =[5,4,3,2,1,8,8,9] 37 | console.log(quickSort(array,0,array.length-1)) -------------------------------------------------------------------------------- /sorting/selectionSort/selectionsort.js: -------------------------------------------------------------------------------- 1 | const selectionSort =(Array)=>{ 2 | const n= array.length 3 | let i,j 4 | for (i=0;i= 0 ; i--){ 39 | temp += str[i] 40 | } 41 | return temp 42 | } 43 | console.log(reverse ("ajmal")) 44 | 45 | 46 | -------------------------------------------------------------------------------- /tree/algorithumFor(BTS).txt: -------------------------------------------------------------------------------- 1 | Is Valid Binary Search: 2 | ---------------------- 3 | STEP 1: Define the min and max value the current node can have 4 | STEP 2: If a node's value is not within those bounds, return false 5 | STEP 3: Recursively validate the node's left children, with the max bound set to the node's value 6 | STEP 4: Recursively validate the nodes's right children, with the min bound set to the node's value. 7 | 8 | Find Binary Tree Max Depth: 9 | -------------------------- 10 | STEP 1: If the node is null, we return 0 as it does not add any depth. 11 | STEP 2: Else we add +1 to our current depth (We traversed one level). 12 | STEP 3: Recursively calculate the depth of node's children and return the maximum sum between node.left and node.right 13 | 14 | Find Lowest Common Ancestor Between Two Tree Nodes: 15 | --------------------------------------------------- 16 | STEP 1: Verify if p or q is found in the left subtree or the right subtree 17 | STEP 2: Then, verify if the current node is p or q. 18 | STEP 3: If one of p or q is found in the left or right subtree, and one of p or q is the node itself, we have found the LCA 19 | STEP 4: If both p and q are found in the left or right subtree, we have found the LCA. 20 | 21 | InOrder Traversal: 22 | ----------------- 23 | STEP 1: If the node is null, do nothing - else, recursively call the function on the node's left child. 24 | STEP 2: Then, do some operation on the node after traversing through all the left child. Our current node is guarenteed to be the leftest node. 25 | STEP 3: Finally, call the function on node.right. 26 | 27 | PostOrder Traversal: 28 | ------------------- 29 | STEP 1: If the node is null, do nothing - else recursively call the function on the node's left child. 30 | STEP 2: When there are no more left children, call the function on node.right. 31 | STEP 3: Finally do some operation on the node. 32 | 33 | PreOrder Traversal: 34 | ------------------ 35 | STEP 1: If the ndoe is null, do nothing - else do some operation on the node. 36 | STEP 2: Traverse to left child of the node and repeat. 37 | STEP 3: Traverse to right child of the node and repeat. -------------------------------------------------------------------------------- /tree/closest value.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | constructor(value) { 3 | this.value = value; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | function findClosestValueInBst(tree, target) { 10 | return findClosestValueInBstHelper(tree, target, Infinity); 11 | } 12 | 13 | function findClosestValueInBstHelper(node, target, closest) { 14 | if (node === null) { 15 | return closest; 16 | } 17 | if (Math.abs(target - node.value) < Math.abs(target - closest)) { 18 | closest = node.value; 19 | } 20 | if (target < node.value) { 21 | return findClosestValueInBstHelper(node.left, target, closest); 22 | } else if (target > node.value) { 23 | return findClosestValueInBstHelper(node.right, target, closest); 24 | } else { 25 | return closest; 26 | } 27 | } 28 | const tree = new Node(10); 29 | tree.left = new Node(5); 30 | tree.right = new Node(15); 31 | tree.left.left = new Node(2); 32 | tree.left.right = new Node(5); 33 | tree.right.left = new Node(13); 34 | tree.right.right = new Node(22); 35 | tree.left.left.left = new Node(1); 36 | tree.right.left.right = new Node(14); 37 | 38 | console.log(findClosestValueInBst(tree, 12)); // 13 39 | -------------------------------------------------------------------------------- /tree/test.js: -------------------------------------------------------------------------------- 1 | class node { 2 | constructor (value){ 3 | this.value = value 4 | this.left = null 5 | this.right = null 6 | } 7 | } 8 | 9 | class BinerySearchTree { 10 | constructor() { 11 | this.root = null 12 | } 13 | isEmpty() { 14 | return this.root === null 15 | } 16 | 17 | insert(value) { 18 | const newNode = new node(value) 19 | if (this.isEmpty()) { 20 | this.root = newNode 21 | } else { 22 | this.childnode(this.root, newNode) 23 | } 24 | } 25 | childnode(root, newNode) { 26 | if (newNode.value < root.value) { 27 | if (root.left === null) { 28 | root.left = newNode 29 | } else { 30 | this.childnode(root.left, newNode) 31 | } 32 | } else { 33 | if (root.right === null) { 34 | root.right = newNode 35 | } else { 36 | this.childnode(root.right, newNode) 37 | } 38 | } 39 | } 40 | 41 | preOrder(root) { 42 | if (root) { 43 | console.log(root.value) 44 | this.preOrder(root.left) 45 | this.preOrder(root.right) 46 | } 47 | } 48 | 49 | search(root, value) { 50 | if (!root) { 51 | return false 52 | } else { 53 | if (root.value === value) { 54 | return true 55 | } else if (value < root.value) { 56 | return this.search(root.left, value) 57 | } else { 58 | return this.search(root.right,value) 59 | } 60 | } 61 | } 62 | min(root) { 63 | if (!root.left) { 64 | return root.value 65 | } else { 66 | return this.min(root.left) 67 | } 68 | } 69 | 70 | max(root) { 71 | if (!root.right) { 72 | return root.value 73 | } else { 74 | return this.max(root.right) 75 | } 76 | } 77 | 78 | delete(value){ 79 | this.root = this.deleteNode(this.root ,value) 80 | } 81 | 82 | deleteNode(root ,value){ 83 | if(root=== null){ 84 | return null 85 | }if(value < root.value){ 86 | root.left =this.deleteNode(root.left,value) 87 | }else if(value > root.value){ 88 | root.right =this.deleteNode(root.right,value) 89 | }else{ 90 | if(!root.left && !root.right){ 91 | return null 92 | } 93 | if(!root.left){ 94 | return root.right 95 | }else if(!root.right){ 96 | return root.left 97 | } 98 | root.value =this.min(root.right) 99 | root.right =this.deleteNode(root.right ,value) 100 | } 101 | return root 102 | } 103 | 104 | } 105 | 106 | 107 | const bst = new BinerySearchTree() 108 | bst.insert(56) 109 | bst.insert(6) 110 | bst.insert(5) 111 | bst.insert(63) 112 | bst.insert(76) 113 | bst.insert(1) 114 | bst.insert(6) 115 | // bst.preOrder(bst.root) 116 | // console.log(bst.search(bst.root, 7)) 117 | // console.log(bst.min(bst.root)) 118 | // console.log(bst.max(bst.root)) 119 | // bst.delete(56) 120 | bst.preOrder(bst.root) 121 | -------------------------------------------------------------------------------- /tree/tree(BTS).js: -------------------------------------------------------------------------------- 1 | class node { 2 | constructor(value) { 3 | this.value = value 4 | this.left = null 5 | this.right = null 6 | } 7 | } 8 | 9 | class BinerySearchTree { 10 | constructor() { 11 | this.root = null 12 | } 13 | isEmpty() { 14 | return this.root === null 15 | } 16 | 17 | insert(value) { 18 | const newNode = new node(value) 19 | if (this.isEmpty()) { 20 | this.root = newNode 21 | } else { 22 | this.insertNode(this.root, newNode) 23 | } 24 | } 25 | 26 | insertNode(root, newNode) { 27 | if (newNode.value < root.value) { 28 | if (root.left === null) { 29 | root.left = newNode 30 | } else { 31 | this.insertNode(root.left, newNode) 32 | } 33 | } else { 34 | if (root.right === null) { 35 | root.right = newNode 36 | } else { 37 | this.insertNode(root.right, newNode) 38 | } 39 | } 40 | } 41 | 42 | search(root, value) { 43 | if (!root) { 44 | return false 45 | } else { 46 | if (root.value === value) { 47 | return true 48 | } else if (value < root.value) { 49 | return this.search(root.left, value) 50 | } else { 51 | return this.search(root.right, value) 52 | } 53 | } 54 | } 55 | 56 | 57 | preOrder(root) { 58 | if (root) { 59 | console.log(root.value) 60 | this.preOrder(root.left) 61 | this.preOrder(root.right) 62 | } 63 | } 64 | 65 | inOrder(root) { 66 | if (root) { 67 | this.inOrder(root.left) 68 | console.log(root.value) 69 | this.inOrder(root.right) 70 | } 71 | } 72 | postOrder(root) { 73 | if (root) { 74 | this.postOrder(root.left) 75 | this.postOrder(root.right) 76 | console.log(root.value) 77 | } 78 | } 79 | 80 | min(root) { 81 | if (!root.left) { 82 | return root.value 83 | } else { 84 | return this.min(root.left) 85 | } 86 | } 87 | 88 | 89 | max(root) { 90 | if (!root.right) { 91 | return root.value 92 | } else { 93 | return this.max(root.right) 94 | } 95 | } 96 | 97 | delete(value) { 98 | this.root = this.deleteNode(this.root, value) 99 | } 100 | 101 | deleteNode(root, value) { 102 | if (root === null) { 103 | return null 104 | } 105 | if (value < root.value) { 106 | root.left = this.deleteNode(root.left, value) 107 | } else if (value > root.value) { 108 | root.right = this.deleteNode(root.right, value) 109 | } else { 110 | if(!root.left && !root.right) { 111 | return null 112 | } 113 | if (!root.left) { 114 | return root.right 115 | } else if (!root.right) { 116 | return root.left 117 | } 118 | root.value = this.min(root.right) 119 | root.right = this.deleteNode(root.right, root.value) 120 | } 121 | return root 122 | } 123 | } 124 | 125 | const bts = new BinerySearchTree() 126 | // console.log(`tree Empty`,bts.isEmpty) 127 | bts.insert(12) 128 | bts.insert(23) 129 | bts.insert(5) 130 | bts.insert(34) 131 | bts.insert(2) 132 | 133 | bts.delete(23) 134 | bts.postOrder(bts.root) 135 | // console.log(bts.search(bts.root ,12)) 136 | // // bts.inOrder(bts.root) 137 | // // bts.postOrder(bts.root) 138 | // console.log(bts.min(bts.root)) 139 | // console.log(bts.max(bts.root)) -------------------------------------------------------------------------------- /tree/treeWorkout.js: -------------------------------------------------------------------------------- 1 | function TreeNode(val, left, right) { 2 | this.val = val; 3 | this.left = left; 4 | this.right = right; 5 | } 6 | 7 | // TRAVERSAL 8 | // In Order traversal 9 | const inorder = (root) => { 10 | const nodes = []; 11 | if (root) { 12 | nodes.push(...inorder(root.left)); 13 | nodes.push(root.val); 14 | nodes.push(...inorder(root.right)); 15 | } 16 | return nodes; 17 | }; 18 | 19 | // Post Order traversal 20 | const postorder = (root) => { 21 | const nodes = []; 22 | if (root) { 23 | nodes.push(...postorder(root.left)); 24 | nodes.push(...postorder(root.right)); 25 | nodes.push(root.val); 26 | } 27 | return nodes; 28 | }; 29 | 30 | // Pre Order traversal 31 | const preorder = (root) => { 32 | const nodes = []; 33 | if (root) { 34 | nodes.push(root.val); 35 | nodes.push(...preorder(root.left)); 36 | nodes.push(...preorder(root.right)); 37 | } 38 | return nodes; 39 | }; 40 | 41 | // IS VALID BINARY SEARCH TREE 42 | const isValidBST = (root) => { 43 | const helper = (node, min, max) => { 44 | if (!node) return true; 45 | if (node.val <= min || node.val >= max) return false; 46 | return ( 47 | helper(node.left, min, node.val) && helper(node.right, node.val, max) 48 | ); 49 | }; 50 | return helper(root, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER); 51 | }; 52 | 53 | // FIND MAX-DEPTH 54 | const maxDepth = (root) => { 55 | const calc = (node) => { 56 | if (!node) return 0; 57 | return Math.max(1 + calc(node.left), 1 + calc(node.right)); 58 | }; 59 | return calc(root); 60 | }; 61 | 62 | // FIND LOWEST COMMON ANCESTOR BETWEEN TWO NODES 63 | const lowestCommonAncestor = (root, p, q) => { 64 | let lca = null; 65 | const isCommonPath = (node) => { 66 | if (!node) return false; 67 | const isLeft = isCommonPath(node.left); 68 | const isRight = isCommonPath(node.right); 69 | const isMid = node === p || node === q; 70 | if ((isMid && isLeft) || (isMid && isRight) || (isLeft && isRight)) { 71 | lca = node; 72 | } 73 | return isLeft || isRight || isMid; 74 | }; 75 | isCommonPath(root); 76 | return lca; 77 | }; 78 | 79 | const tree = new TreeNode( 80 | 5, new TreeNode(3, new TreeNode(2), new TreeNode(4)), 81 | new TreeNode(7, new TreeNode(6), new TreeNode(8)) 82 | ); 83 | 84 | console.log(inorder(tree)); // [2, 3, 4, 5, 6, 7, 8] 85 | console.log(postorder(tree)); // [2, 4, 3, 6, 8, 7, 5] 86 | console.log(preorder(tree)); // [5, 3, 2, 4, 7, 6, 8] 87 | console.log(isValidBST(tree)); // true 88 | console.log(maxDepth(tree)); // 3 89 | console.log(lowestCommonAncestor(tree, tree.left.left, tree.left.right)); // -------------------------------------------------------------------------------- /tree/workout.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | constructor(value) { 3 | this.value = value; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | function getHeight(root) { 10 | if (!root) { 11 | // If the root node is null, the height is 0. 12 | return 0; 13 | } 14 | 15 | // Recursively compute the height of the left and right subtrees. 16 | const leftHeight = getHeight(root.left); 17 | const rightHeight = getHeight(root.right); 18 | 19 | // The height of the binary tree is the maximum of the heights of the left and right subtrees, 20 | // plus one for the root node. 21 | return Math.max(leftHeight, rightHeight) + 1; 22 | } 23 | 24 | // Example usage: 25 | const root = new Node(1); 26 | root.left = new Node(2); 27 | root.right = new Node(3); 28 | root.left.left = new Node(4); 29 | root.left.right = new Node(5); 30 | 31 | console.log(getHeight(root)); // Output: 3 32 | -------------------------------------------------------------------------------- /trie/prifixTrie.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | constructor(value) { 3 | this.value = value; 4 | this.isEndOfWord = false; 5 | this.children = {}; 6 | } 7 | } 8 | 9 | class Trie { 10 | insert(word) { 11 | this.root = new Node(null) 12 | let current = this.root; 13 | 14 | for (let char of word) { 15 | if (!current.children[char]) { 16 | current.children[char] = new Node(char); 17 | } 18 | current = current.children[char]; 19 | } 20 | current.isEndOfWord = true; 21 | } 22 | 23 | search(word) { 24 | let current = this.root; 25 | 26 | for (let char of word) { 27 | if (!current.children[char]) { 28 | return false; 29 | } 30 | current = current.children[char]; 31 | } 32 | return current.isEndOfWord; 33 | } 34 | } 35 | 36 | const trie = new Trie(); 37 | 38 | trie.insert("hello"); 39 | trie.insert("hai"); 40 | trie.insert("demo"); 41 | 42 | console.log(trie.search("demo")); -------------------------------------------------------------------------------- /trie/problem1.js: -------------------------------------------------------------------------------- 1 | class Node { 2 | constructor(value) { 3 | this.value = value; 4 | this.isEndOfWord = false; // false by default, a green node means this flag is true 5 | this.children = {}; // children are stored as Map, where key is the letter and value is a TrieNode for that letter 6 | } 7 | } 8 | 9 | class Trie { 10 | constructor() { 11 | this.root = new Node(null); 12 | } 13 | 14 | insert(word) { 15 | let current = this.root; 16 | // iterate through all the characters of word 17 | for (let character of word) { 18 | // if node doesn't have the current character as child, insert it 19 | if (current.children[character] === undefined) { 20 | current.children[character] = new Node(character); 21 | } 22 | // move down, to insert next character 23 | current = current.children[character]; 24 | } 25 | // mark the last inserted character as end of the word 26 | current.isEndOfWord = true; 27 | } 28 | 29 | search(word) { 30 | let current = this.root; 31 | // iterate through all the characters of word 32 | for (let character of word) { 33 | if (current.children[character] === undefined) { 34 | // could not find this character in sequence, return false 35 | return false; 36 | } 37 | // move down, to match next character 38 | current = current.children[character]; 39 | } 40 | // found all characters, return true if last character is end of a word 41 | return current.isEndOfWord; 42 | } 43 | } 44 | 45 | const trie = new Trie(); 46 | 47 | // insert few words 48 | trie.insert("CAT"); 49 | trie.insert("DOG"); 50 | 51 | // search something 52 | console.log(trie.search("MAT")); // false 53 | console.log(trie.search("DOGr")); // true -------------------------------------------------------------------------------- /trie/sufixTrie.js: -------------------------------------------------------------------------------- 1 | class TrieNode { 2 | constructor() { 3 | this.children = {}; 4 | this.isEndOfWord = false; 5 | } 6 | } 7 | 8 | class Trie { 9 | constructor() { 10 | this.root = new TrieNode(); 11 | } 12 | 13 | insert(word) { 14 | let currentNode = this.root; 15 | 16 | for (let i = word.length - 1; i >= 0; i--) { 17 | const char = word[i]; 18 | 19 | if (!currentNode.children[char]) { 20 | currentNode.children[char] = new TrieNode(); 21 | } 22 | 23 | currentNode = currentNode.children[char]; 24 | } 25 | 26 | currentNode.isEndOfWord = true; 27 | } 28 | 29 | search(suffix) { 30 | let currentNode = this.root; 31 | 32 | for (let i = suffix.length - 1; i >= 0; i--) { 33 | const char = suffix[i]; 34 | 35 | if (!currentNode.children[char]) { 36 | return false; 37 | } 38 | 39 | currentNode = currentNode.children[char]; 40 | } 41 | 42 | return true; 43 | } 44 | } 45 | 46 | // Usage Example 47 | const trie = new Trie(); 48 | 49 | trie.insert("apple"); 50 | trie.insert("banana"); 51 | trie.insert("orange"); 52 | 53 | console.log(trie.search("le")); // Output: true 54 | console.log(trie.search("na")); // Output: true 55 | console.log(trie.search("pea")); // Output: false --------------------------------------------------------------------------------