├── Arrays ├── Dynamic Arrays │ ├── dynamic-array-cpp.cpp │ ├── dynamic-array-java.java │ ├── dynamic-array-javascript.js │ └── dynamic-array-python.py ├── Stacks │ ├── stacks-cpp.cpp │ ├── stacks-java.java │ ├── stacks-javascript.js │ └── stacks-python.py └── Static Array │ ├── static-array-cpp.cpp │ ├── static-array-java.java │ ├── static-array-javascript.js │ └── static-array-python.py ├── Backtracking └── Tree Maze │ ├── tree-maze-cpp.cpp │ ├── tree-maze-java.java │ ├── tree-maze-javascript.js │ └── tree-maze-python.py ├── Binary Search └── Search Array │ ├── search-array-cpp.cpp │ ├── search-array-java.java │ ├── search-array-javascript.js │ └── search-array-python.py ├── Bit Manipulation └── Bit Operator │ ├── bit-operator-cpp.cpp │ ├── bit-operator-java.java │ ├── bit-operator-javascript.js │ └── bit-operator-python.py ├── Dynamic Programming ├── 1-dimension-dp │ ├── 1-dimension-dp-cpp.cpp │ ├── 1-dimension-dp-java.java │ ├── 1-dimension-dp-javascript.js │ └── 1-dimension-dp-python.py └── 2-dimension-dp │ ├── 2-dimension-dp-cpp.cpp │ ├── 2-dimension-dp-java.java │ ├── 2-dimension-dp-javascript.js │ └── 2-dimension-dp-python.py ├── Graphs ├── Adjacency List │ ├── adjacency-list-cpp.cpp │ ├── adjacency-list-java.java │ ├── adjacency-list-javascript.js │ └── adjacency-list-python.py ├── Matrix BFS │ ├── matrix-bfs-cpp.cpp │ ├── matrix-bfs-java.java │ ├── matrix-bfs-javascript.js │ └── matrix-bfs-python.py └── Matrix DFS │ ├── matrix-dfs-cpp-.cpp │ ├── matrix-dfs-java.java │ ├── matrix-dfs-javascript.js │ └── matrix-dfs-python.py ├── Hashing ├── Hash Implementation │ ├── hash-implementation-cpp.cpp │ ├── hash-implementation-java.java │ ├── hash-implementation-javascript.js │ └── hash-implementation-python.py └── Hash Usage │ ├── hash-usage-cpp.cpp │ ├── hash-usage-java.java │ ├── hash-usage-javascript.js │ └── hash-usage-python.py ├── Heap Priority Queue ├── Heapify │ ├── heapify-cpp.cpp │ ├── heapify-java.java │ ├── heapify-javascript.js │ └── heapify-python.py └── Push and Pop │ ├── push-and-pop-cpp.cpp │ ├── push-and-pop-java.java │ ├── push-and-pop-javascript.js │ └── push-and-pop-python.py ├── LICENSE ├── Linked Lists ├── Doubly Linked Lists │ ├── double-linked-java.java │ ├── double-linked-python.py │ ├── doubly-linked-cpp.cpp │ └── doubly-linked-javascript.js ├── Queues │ ├── queues-cpp.cpp │ ├── queues-java.java │ ├── queues-javascript.js │ └── queues-python.py └── Singly Linked Lists │ ├── singly-linked-cpp.cpp │ ├── singly-linked-java.java │ ├── singly-linked-javascript.js │ └── singly-linked-python.py ├── README.md ├── Recursion ├── Factorial │ ├── factorial-cpp.cpp │ ├── factorial-java.java │ ├── factorial-javascript.js │ └── factorial-python.py └── Fibonacci │ ├── fibonacci-cpp.cpp │ ├── fibonacci-java.java │ ├── fibonacci-javascript.js │ └── fibonacci-python.py ├── Sorting ├── Bucket Sort │ ├── bucket-sort-cpp.cpp │ ├── bucket-sort-java.java │ ├── bucket-sort-javascript.js │ └── bucket-sort-python.py ├── Insertion Sort │ ├── insertion-sort-cpp.cpp │ ├── insertion-sort-java.java │ ├── insertion-sort-javascript.js │ └── insertion-sort-python.py ├── Merge Sort │ ├── merge-sort-cpp.cpp │ ├── merge-sort-java.java │ ├── merge-sort-javascript.js │ └── merge-sort-python.py └── Quick Sort │ ├── quick-sort-cpp.cpp │ ├── quick-sort-java.java │ ├── quick-sort-javascript.js │ └── quick-sort-python.py └── Trees ├── BST Insert and Remove ├── bst-insert-and-remove-cpp.cpp ├── bst-insert-and-remove-java.java ├── bst-insert-and-remove-javascript.js └── bst-insert-and-remove-python.py ├── Binary Search Trees ├── binary-search-trees-cpp.cpp ├── binary-search-trees-java.java ├── binary-search-trees-javascript.js └── binary-search-trees-python.py ├── Breadth First Search ├── breadth-first-search-cpp.cpp ├── breadth-first-search-java.java ├── breadth-first-search-javascript.js └── breadth-first-search-python.py └── Depth First Search ├── depth-first-search-cpp.cpp ├── depth-first-search-java.java ├── depth-first-search-javascript.js └── depth-first-search-python.py /Arrays/ Dynamic Arrays/dynamic-array-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | 6 | // Example implementation of a resizable array (i.e. a vector). 7 | class Array { 8 | public: 9 | int capacity = 2; 10 | int length = 0; 11 | int *arr = new int[2]; // Array of capacity = 2 12 | 13 | Array(){}; 14 | 15 | // Insert n in the last position of the array 16 | void pushback(int n) 17 | { 18 | if (length == capacity) 19 | { 20 | resize(); 21 | } 22 | // insert at next empty position 23 | arr[length++] = n; 24 | } 25 | 26 | void resize() 27 | { 28 | // Create new array of double capacity 29 | capacity = 2 * capacity; 30 | int *newArr = new int[capacity]; 31 | 32 | // Copy elements to newArr 33 | for (int i = 0; i < length; i++) 34 | { 35 | newArr[i] = arr[i]; 36 | } 37 | arr = newArr; 38 | // Normally we would use smart pointers or free the old arr's memory 39 | } 40 | 41 | // Remove the last element in the array 42 | void popback() { 43 | if (length > 0) { 44 | length--; 45 | } 46 | } 47 | 48 | // Get value at i-th index 49 | int get(int i) { 50 | if (i < length) { 51 | return arr[i]; 52 | } 53 | // Here we would throw an out of bounds exception 54 | } 55 | 56 | // Insert n at i-th index 57 | void insert(int i, int n) { 58 | if (i < length) { 59 | arr[i] = n; 60 | return; 61 | } 62 | // Here we would throw an out of bounds exception 63 | } 64 | 65 | void print() { 66 | for (int i = 0; i < length; i++) { 67 | cout << arr[i] << ' '; 68 | } 69 | cout << endl; 70 | } 71 | }; 72 | -------------------------------------------------------------------------------- /Arrays/ Dynamic Arrays/dynamic-array-java.java: -------------------------------------------------------------------------------- 1 | public class DynamicArray { 2 | int capacity; 3 | int length;; 4 | int[] arr; 5 | 6 | public DynamicArray() { 7 | capacity = 2; 8 | length = 0; 9 | arr = new int[2]; 10 | } 11 | 12 | // Insert n in the last position of the array 13 | public void pushback(int n) { 14 | if (length == capacity) { 15 | this.resize(); 16 | } 17 | 18 | // insert at next empty position 19 | arr[length] = n; 20 | length++; 21 | } 22 | 23 | public void resize() { 24 | // Create new array of double capacity 25 | capacity = 2 * capacity; 26 | int[] newArr = new int[capacity]; 27 | 28 | // Copy elements to newArr 29 | for (int i = 0; i < length; i++) { 30 | newArr[i] = arr[i]; 31 | } 32 | arr = newArr; 33 | } 34 | 35 | // Remove the last element in the array 36 | public void popback() { 37 | if (length > 0) { 38 | length--; 39 | } 40 | } 41 | 42 | // Get value at i-th index 43 | public int get(int i) { 44 | if (i < length) { 45 | return arr[i]; 46 | } 47 | // Here we would throw an out of bounds exception 48 | return -1; 49 | } 50 | 51 | // Insert n at i-th index 52 | public void insert(int i, int n) { 53 | if (i < length) { 54 | arr[i] = n; 55 | return; 56 | } 57 | return; 58 | // Here we would throw an out of bounds exception 59 | } 60 | 61 | public void print() { 62 | for (int i = 0; i < length; i++) { 63 | System.out.println(arr[i]); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Arrays/ Dynamic Arrays/dynamic-array-javascript.js: -------------------------------------------------------------------------------- 1 | class DynamicArray { 2 | constructor() { 3 | this.capacity = 2; 4 | this.length = 0; 5 | this.arr = new Array(2); 6 | } 7 | 8 | // Insert n in the last position of the array 9 | pushback(n) { 10 | if (this.length == this.capacity) { 11 | this.resize(); 12 | } 13 | 14 | // insert at next empty position 15 | this.arr[this.length] = n; 16 | this.length++; 17 | } 18 | 19 | resize() { 20 | // Create new array of double capacity 21 | this.capacity = 2 * this.capacity; 22 | const newArr = new Array(this.capacity); 23 | 24 | // Copy elements to newArr 25 | for (let i = 0; i < this.length; i++) { 26 | newArr[i] = this.arr[i]; 27 | } 28 | this.arr = newArr; 29 | } 30 | 31 | // Remove the last element in the array 32 | popback() { 33 | if (this.length > 0) { 34 | this.length--; 35 | } 36 | } 37 | 38 | // Get value at i-th index 39 | get(i) { 40 | if (i < this.length) { 41 | return this.arr[i]; 42 | } 43 | // Here we would throw an out of bounds exception 44 | return; 45 | } 46 | 47 | // Insert n at i-th index 48 | insert(i, n) { 49 | if (i < this.length) { 50 | this.arr[i] = n; 51 | return; 52 | } 53 | return; 54 | // Here we would throw an out of bounds exception 55 | } 56 | 57 | print() { 58 | let s = ""; 59 | for (let i = 0; i < this.length; i++) { 60 | s+= this.arr[i] + " "; 61 | } 62 | console.log(s); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /Arrays/ Dynamic Arrays/dynamic-array-python.py: -------------------------------------------------------------------------------- 1 | # Python arrays are dynamic by default, but this is an example of resizing. 2 | class Array: 3 | def __init__(self): 4 | self.capacity = 2 5 | self.length = 0 6 | self.arr = [0] * 2 # Array of capacity = 2 7 | 8 | # Insert n in the last position of the array 9 | def pushback(self, n): 10 | if self.length == self.capacity: 11 | self.resize() 12 | 13 | # insert at next empty position 14 | self.arr[self.length] = n 15 | self.length += 1 16 | 17 | def resize(self): 18 | # Create new array of double capacity 19 | self.capacity = 2 * self.capacity 20 | newArr = [0] * self.capacity 21 | 22 | # Copy elements to newArr 23 | for i in range(self.length): 24 | newArr[i] = self.arr[i] 25 | self.arr = newArr 26 | 27 | # Remove the last element in the array 28 | def popback(self): 29 | if self.length > 0: 30 | self.length -= 1 31 | 32 | # Get value at i-th index 33 | def get(self, i): 34 | if i < self.length: 35 | return self.arr[i] 36 | # Here we would throw an out of bounds exception 37 | 38 | # Insert n at i-th index 39 | def insert(self, i, n): 40 | if i < self.length: 41 | self.arr[i] = n 42 | return 43 | # Here we would throw an out of bounds exception 44 | 45 | def print(self): 46 | for i in range(self.length): 47 | print(self.arr[i]) 48 | print() 49 | -------------------------------------------------------------------------------- /Arrays/Stacks /stacks-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::vector; 4 | 5 | // Implementing a stack is trivial using a dynamic array 6 | // (which we implemented earlier). 7 | class Stack { 8 | public: 9 | vector stack_; 10 | 11 | Stack() {}; 12 | 13 | void push(int n) { 14 | stack_.push_back(n); 15 | } 16 | 17 | int pop() { 18 | int res = stack_[stack_.size() - 1]; 19 | stack_.pop_back(); 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /Arrays/Stacks /stacks-java.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | // Implementing a stack is trivial using a dynamic array 4 | // (which we implemented earlier). 5 | public class Stack { 6 | 7 | ArrayList stack = new ArrayList(); 8 | 9 | public Stack() { 10 | } 11 | 12 | public void push(int n) { 13 | stack.add(n); 14 | } 15 | 16 | public int pop() { 17 | return stack.remove(stack.size() - 1); 18 | } 19 | 20 | public int size() { 21 | return stack.size(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Arrays/Stacks /stacks-javascript.js: -------------------------------------------------------------------------------- 1 | // Implementing a stack is trivial using a dynamic array 2 | // (which we implemented earlier). 3 | class Stack { 4 | constructor() { 5 | this.stack = new Array(); 6 | } 7 | 8 | push(n) { 9 | this.stack.push(n); 10 | } 11 | 12 | pop() { 13 | return this.stack.pop(); 14 | } 15 | 16 | size() { 17 | return this.stack.length; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Arrays/Stacks /stacks-python.py: -------------------------------------------------------------------------------- 1 | # Implementing a stack is trivial using a dynamic array 2 | # (which we implemented earlier). 3 | class Stack: 4 | def __init__(self): 5 | self.stack = [] 6 | 7 | def push(self, n): 8 | self.stack.append(n) 9 | 10 | def pop(self): 11 | return self.stack.pop() 12 | -------------------------------------------------------------------------------- /Arrays/Static Array/static-array-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | 6 | // Insert n into arr at the next open position. 7 | // Length is the number of 'real' values in arr, and capacity 8 | // is the size (aka memory allocated for the fixed size array). 9 | void insertEnd(int arr[], int n, int length, int capacity) { 10 | if (length < capacity) { 11 | arr[length] = n; 12 | } 13 | } 14 | 15 | // Remove from the last position in the array if the array 16 | // is not empty (i.e. length is non-zero). 17 | void removeEnd(int arr[], int length) { 18 | if (length > 0) { 19 | arr[length - 1] = 0; 20 | } 21 | } 22 | 23 | // Insert n into index i after shifting elements to the right. 24 | // Assuming i is a valid index and arr is not full. 25 | void insertMiddle(int arr[], int i, int n, int length) { 26 | for (int index = length - 1; index >= i; index--) { 27 | arr[index + 1] = arr[index]; 28 | } 29 | arr[i] = n; 30 | } 31 | 32 | // Remove value at index i before shifting elements to the left. 33 | // Assuming i is a valid index. 34 | void removeMiddle(int arr[], int i, int length) { 35 | for (int index = i + 1; index < length; index++) { 36 | arr[index - 1] = arr[index]; 37 | } 38 | } 39 | 40 | void printArr(int arr[], int capacity) { 41 | for (int i = 0; i < capacity; i++) { 42 | cout << arr[i] << ' '; 43 | } 44 | cout << endl; 45 | } 46 | -------------------------------------------------------------------------------- /Arrays/Static Array/static-array-java.java: -------------------------------------------------------------------------------- 1 | public class StaticArray { 2 | 3 | // Insert n into arr at the next open position. 4 | // Length is the number of 'real' values in arr, and capacity 5 | // is the size (aka memory allocated for the fixed size array). 6 | public void insertEnd(int[] arr, int n, int length, int capacity) { 7 | if (length < capacity) { 8 | arr[length] = n; 9 | } 10 | } 11 | 12 | // Remove from the last position in the array if the array 13 | // is not empty (i.e. length is non-zero). 14 | public void removeEnd(int[] arr, int length) { 15 | if (length > 0) { 16 | // Overwrite last element with some default value. 17 | // We would also the length to decreased by 1. 18 | arr[length - 1] = 0; 19 | length--; 20 | } 21 | } 22 | 23 | // Insert n into index i after shifting elements to the right. 24 | // Assuming i is a valid index and arr is not full. 25 | public void insertMiddle(int[] arr, int i, int n, int length) { 26 | // Shift starting from the end to i. 27 | for (int index = length - 1; index > i - 1; index--) { 28 | arr[index + 1] = arr[index]; 29 | } 30 | //Insert at i 31 | arr[i] = n; 32 | } 33 | 34 | // Remove value at index i before shifting elements to the left. 35 | // Assuming i is a valid index. 36 | public void removeMiddle(int[] arr, int i, int length) { 37 | // Shift starting from i + 1 to end. 38 | for (int index = i + 1; index < length; index++) { 39 | arr[index - 1] = arr[index]; 40 | } 41 | // No need to 'remove' arr[i], since we already shifted 42 | } 43 | 44 | public void printArr(int[] arr, int length) { 45 | for (int i = 0; i < length; i++) { 46 | System.out.print(arr[i] + " "); 47 | } 48 | System.out.println(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Arrays/Static Array/static-array-javascript.js: -------------------------------------------------------------------------------- 1 | class StaticArray { 2 | 3 | // Insert n into arr at the next open position. 4 | // Length is the number of 'real' values in arr, and capacity 5 | // is the size (aka memory allocated for the fixed size array). 6 | insertEnd(arr, n, length, capacity) { 7 | if (length < capacity) { 8 | arr[length] = n; 9 | } 10 | } 11 | 12 | // Remove from the last position in the array if the array 13 | // is not empty (i.e. length is non-zero). 14 | removeEnd(arr, length) { 15 | if (length > 0) { 16 | // Overwrite last element with some default value. 17 | // We would also the length to decreased by 1. 18 | arr[length - 1] = 0; 19 | length--; 20 | } 21 | } 22 | 23 | // Insert n into index i after shifting elements to the right. 24 | // Assuming i is a valid index and arr is not full. 25 | insertMiddle(arr, i, n, length) { 26 | // Shift starting from the end to i. 27 | for (let index = length - 1; index > i - 1; index--) { 28 | arr[index + 1] = arr[index]; 29 | } 30 | //Insert at i 31 | arr[i] = n; 32 | } 33 | 34 | // Remove value at index i before shifting elements to the left. 35 | // Assuming i is a valid index. 36 | removeMiddle(arr, i, length) { 37 | // Shift starting from i + 1 to end. 38 | for (let index = i + 1; index < length; index++) { 39 | arr[index - 1] = arr[index]; 40 | } 41 | // No need to 'remove' arr[i], since we already shifted 42 | } 43 | 44 | printArr(arr, length) { 45 | let s = ""; 46 | for (let i = 0; i < length; i++) { 47 | s+= arr[i] + " "; 48 | } 49 | console.log(s); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Arrays/Static Array/static-array-python.py: -------------------------------------------------------------------------------- 1 | # Insert n into arr at the next open position. 2 | # Length is the number of 'real' values in arr, and capacity 3 | # is the size (aka memory allocated for the fixed size array). 4 | def insertEnd(arr, n, length, capacity): 5 | if length < capacity: 6 | arr[length] = n 7 | 8 | # Remove from the last position in the array if the array 9 | # is not empty (i.e. length is non-zero). 10 | def removeEnd(arr, length): 11 | if length > 0: 12 | # Overwrite last element with some default value. 13 | # We would also the length to decreased by 1. 14 | arr[length - 1] = 0 15 | 16 | # Insert n into index i after shifting elements to the right. 17 | # Assuming i is a valid index and arr is not full. 18 | def insertMiddle(arr, i, n, length): 19 | # Shift starting from the end to i. 20 | for index in range(length - 1, i - 1, -1): 21 | arr[index + 1] = arr[index] 22 | 23 | # Insert at i 24 | arr[i] = n 25 | 26 | # Remove value at index i before shifting elements to the left. 27 | # Assuming i is a valid index. 28 | def removeMiddle(arr, i, length): 29 | # Shift starting from i + 1 to end. 30 | for index in range(i + 1, length): 31 | arr[index - 1] = arr[index] 32 | # No need to 'remove' arr[i], since we already shifted 33 | 34 | def printArr(arr, capacity): 35 | for i in range(capacity): 36 | print(arr[i]) 37 | 38 | -------------------------------------------------------------------------------- /Backtracking/Tree Maze/tree-maze-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::vector; 4 | 5 | class TreeNode { 6 | public: 7 | int val_; 8 | TreeNode* left = nullptr; 9 | TreeNode* right = nullptr; 10 | 11 | TreeNode(int val) { 12 | val_ = val; 13 | } 14 | }; 15 | 16 | bool canReachLeaf(TreeNode *root) { 17 | if (!root || root->val_ == 0) { 18 | return false; 19 | } 20 | if (!root->left && !root->right) { 21 | return true; 22 | } 23 | if (canReachLeaf(root->left)) { 24 | return true; 25 | } 26 | if (canReachLeaf(root->right)) { 27 | return true; 28 | } 29 | return false; 30 | } 31 | 32 | bool leafPath(TreeNode* root, vector* path) { 33 | if (!root || root->val_ == 0) { 34 | return false; 35 | } 36 | path->push_back(root->val_); 37 | 38 | if (!root->left && !root->right) { 39 | return true; 40 | } 41 | if (leafPath(root->left, path)) { 42 | return true; 43 | } 44 | if (leafPath(root->right, path)) { 45 | return true; 46 | } 47 | path->pop_back(); 48 | return false; 49 | } -------------------------------------------------------------------------------- /Backtracking/Tree Maze/tree-maze-java.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | // Definition of TreeNode: 4 | // public class TreeNode { 5 | // 6 | // int val; 7 | // TreeNode left; 8 | // TreeNode right; 9 | // 10 | // public TreeNode(int val) { 11 | // this.val = val; 12 | // this.left= null; 13 | // this.right = null; 14 | // } 15 | // } 16 | 17 | public class TreeMaze { 18 | 19 | public boolean canReachLeaf(TreeNode root) { 20 | if (root == null || root.val == 0) { 21 | return false; 22 | } 23 | if (root.left == null && root.right == null) { 24 | return true; 25 | } 26 | if (canReachLeaf(root.left)) { 27 | return true; 28 | } 29 | if (canReachLeaf(root.right)) { 30 | return true; 31 | } 32 | return false; 33 | } 34 | 35 | public boolean leafPath(TreeNode root, ArrayList path) { 36 | if (root == null || root.val == 0) { 37 | return false; 38 | } 39 | path.add(root.val); 40 | 41 | if (root.left == null && root.right == null) { 42 | return true; 43 | } 44 | if (leafPath(root.left, path)) { 45 | return true; 46 | } 47 | if (leafPath(root.right, path)) { 48 | return true; 49 | } 50 | path.remove(path.size() - 1); 51 | return false; 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /Backtracking/Tree Maze/tree-maze-javascript.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | function canReachLeaf(root) { 10 | if (root == null || root.val == 0) { 11 | return false; 12 | } 13 | if (root.left == null && root.right == null) { 14 | return true; 15 | } 16 | if (canReachLeaf(root.left)) { 17 | return true; 18 | } 19 | if (canReachLeaf(root.right)) { 20 | return true; 21 | } 22 | return false; 23 | } 24 | 25 | function leafPath(root, path) { 26 | if (root == null || root.val == 0) { 27 | return false; 28 | } 29 | path.push(root.val); 30 | 31 | if (root.left == null && root.right == null) { 32 | return true; 33 | } 34 | if (leafPath(root.left, path)) { 35 | return true; 36 | } 37 | if (leafPath(root.right, path)) { 38 | return true; 39 | } 40 | path.remove(path.size() - 1); 41 | return false; 42 | } -------------------------------------------------------------------------------- /Backtracking/Tree Maze/tree-maze-python.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.left = None 5 | self.right = None 6 | 7 | def canReachLeaf(root): 8 | if not root or root.val == 0: 9 | return False 10 | 11 | if not root.left and not root.right: 12 | return True 13 | if canReachLeaf(root.left): 14 | return True 15 | if canReachLeaf(root.right): 16 | return True 17 | return False 18 | 19 | def leafPath(root, path): 20 | if not root or root.val == 0: 21 | return False 22 | path.append(root.val) 23 | 24 | if not root.left and not root.right: 25 | return True 26 | if leafPath(root.left, path): 27 | return True 28 | if leafPath(root.right, path): 29 | return True 30 | path.pop() 31 | return False -------------------------------------------------------------------------------- /Binary Search/Search Array/search-array-cpp.cpp: -------------------------------------------------------------------------------- 1 | using std::vector; 2 | 3 | int binarySearch(vector arr, int target) { 4 | int L = 0, R = arr.size(); 5 | 6 | while (L <= R) { 7 | int mid = (L + R) / 2; 8 | 9 | if (target > arr[mid]) { 10 | L = mid + 1; 11 | } else if (target < arr[mid]) { 12 | R = mid - 1; 13 | } else { 14 | return mid; 15 | } 16 | } 17 | return -1; 18 | } 19 | -------------------------------------------------------------------------------- /Binary Search/Search Array/search-array-java.java: -------------------------------------------------------------------------------- 1 | public class Array { 2 | public static int binarySearch(int[] arr, int target) { 3 | int L = 0, R = arr.length - 1; 4 | int mid; 5 | 6 | while (L <= R) { 7 | mid = (L + R) / 2; 8 | if (target > arr[mid]) { 9 | L = mid + 1; 10 | } else if (target < arr[mid]) { 11 | R = mid - 1; 12 | } else { 13 | return mid; 14 | } 15 | } 16 | return - 1; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Binary Search/Search Array/search-array-javascript.js: -------------------------------------------------------------------------------- 1 | function binarySearch(arr, target) { 2 | let L = 0, R = arr.length - 1; 3 | 4 | while (L <= R) { 5 | let mid = Math.floor((L + R) / 2); 6 | 7 | if (target > arr[mid]) { 8 | L = mid + 1; 9 | } else if (target < arr[mid]) { 10 | R = mid - 1; 11 | } else { 12 | return mid; 13 | } 14 | } 15 | return -1; 16 | } -------------------------------------------------------------------------------- /Binary Search/Search Array/search-array-python.py: -------------------------------------------------------------------------------- 1 | arr = [1, 3, 3, 4, 5, 6, 7, 8] 2 | 3 | # Python implementation of Binary Search 4 | def binarySearch(arr, target): 5 | L, R = 0, len(arr) - 1 6 | 7 | while L <= R: 8 | mid = (L + R) // 2 9 | 10 | if target > arr[mid]: 11 | L = mid + 1 12 | elif target < arr[mid]: 13 | R = mid - 1 14 | else: 15 | return mid 16 | return -1 -------------------------------------------------------------------------------- /Bit Manipulation/Bit Operator/bit-operator-cpp.cpp: -------------------------------------------------------------------------------- 1 | int main() { 2 | // AND 3 | int n = 1 & 1; 4 | 5 | // OR 6 | n = 1 | 0; 7 | 8 | // XOR 9 | n = 0 ^ 1; 10 | 11 | // NOT (negation) 12 | n = ~n; 13 | 14 | // Bit Shifting 15 | n = 1; 16 | n = n << 1; 17 | n = n >> 1; 18 | 19 | return 0; 20 | } 21 | 22 | // Counting Bits 23 | int countBits(int n) { 24 | int count = 0; 25 | while (n > 0) { 26 | if ((n & 1) == 1) { 27 | count++; 28 | } 29 | n = n >> 1; // same as n / 2 30 | } 31 | return count; 32 | } 33 | -------------------------------------------------------------------------------- /Bit Manipulation/Bit Operator/bit-operator-java.java: -------------------------------------------------------------------------------- 1 | public class CountingBits { 2 | public static void operations() { 3 | // AND 4 | int n = 1 & 1; 5 | 6 | // OR 7 | n = 1 | 0; 8 | 9 | // XOR 10 | n = 0 ^ 1; 11 | 12 | // NOT (negation) 13 | n = ~n; 14 | 15 | // Bit Shifting 16 | n = 1; 17 | n = n << 1; 18 | n = n >> 1; 19 | 20 | return; 21 | } 22 | 23 | // Count the number of 1 bits in an int 24 | public static int countBits(int n) { 25 | int count = 0; 26 | while (n > 0) { 27 | if ((n & 1) == 1) { 28 | count++; 29 | } 30 | n = n >> 1; // same as n / 2 31 | } 32 | return count; 33 | } 34 | } -------------------------------------------------------------------------------- /Bit Manipulation/Bit Operator/bit-operator-javascript.js: -------------------------------------------------------------------------------- 1 | /* operations 2 | // AND 3 | let n = 1 & 1; 4 | 5 | // OR 6 | n = 1 | 0; 7 | 8 | // XOR 9 | n = 0 ^ 1; 10 | 11 | // NOT (negation) 12 | n = ~n; 13 | 14 | // Bit Shifting 15 | n = 1; 16 | n = n << 1; 17 | n = n >> 1; 18 | */ 19 | 20 | // Count the number of 1 bits 21 | function countBits(n) { 22 | let count = 0; 23 | while (n > 0) { 24 | if ((n & 1) == 1) { 25 | count++; 26 | } 27 | n = n >> 1; // same as n / 2 28 | } 29 | return count; 30 | } 31 | -------------------------------------------------------------------------------- /Bit Manipulation/Bit Operator/bit-operator-python.py: -------------------------------------------------------------------------------- 1 | # AND 2 | n = 1 & 1 3 | 4 | # OR 5 | n = 1 | 0 6 | 7 | # XOR 8 | n = 0 ^ 1 9 | 10 | # NOT (negation) 11 | n = ~n 12 | 13 | # Bit shifting 14 | n = 1 15 | n = n << 1 16 | n = n >> 1 17 | 18 | # Counting Bits 19 | def countBits(n): 20 | count = 0 21 | while n > 0: 22 | if n & 1 == 1: 23 | count += 1 24 | n = n >> 1 # same as n // 2 25 | return count -------------------------------------------------------------------------------- /Dynamic Programming/1-dimension-dp/1-dimension-dp-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::unordered_map; 4 | 5 | // Brute Force 6 | int bruteForce(int n) { 7 | if (n <= 1) { 8 | return n; 9 | } 10 | return bruteForce(n - 1) + bruteForce(n - 2); 11 | } 12 | 13 | // Memoization 14 | int memoization(int n, unordered_map *cache) { 15 | if (n <= 1) { 16 | return n; 17 | } 18 | if (cache->count(n)) { 19 | return (*cache)[n]; 20 | } 21 | return memoization(n - 1, cache) + memoization(n - 2, cache); 22 | } 23 | 24 | // Dynamic Programming 25 | int dp(int n) { 26 | if (n < 2) { 27 | return n; 28 | } 29 | 30 | int dp[] = {0, 1}; 31 | int i = 2; 32 | while (i <= n) { 33 | int tmp = dp[1]; 34 | dp[1] = dp[0] + dp[1]; 35 | dp[0] = tmp; 36 | i++; 37 | } 38 | return dp[1]; 39 | } 40 | -------------------------------------------------------------------------------- /Dynamic Programming/1-dimension-dp/1-dimension-dp-java.java: -------------------------------------------------------------------------------- 1 | public class Fibonacci { 2 | 3 | // Brute Force 4 | public static int bruteForce(int n) { 5 | if (n <= 1) { 6 | return n; 7 | } 8 | return bruteForce(n - 1) + bruteForce(n - 2); 9 | } 10 | 11 | // Memoization 12 | public static int memoization(int n, int[] cache) { 13 | if (n <= 1) { 14 | return n; 15 | } 16 | if (cache[n] != 0) { 17 | return cache[n]; 18 | } 19 | cache[n] = memoization(n - 1, cache) + memoization(n - 2, cache); 20 | return cache[n]; 21 | } 22 | 23 | // Dynamic Programming 24 | public static int dp(int n) { 25 | if (n < 2) { 26 | return n; 27 | } 28 | 29 | int[] dp = {0,1}; 30 | int i = 2; 31 | while (i <= n) { 32 | int tmp = dp[1]; 33 | dp[1] = dp[0] + dp[1]; 34 | dp[0] = tmp; 35 | i++; 36 | } 37 | return dp[1]; 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /Dynamic Programming/1-dimension-dp/1-dimension-dp-javascript.js: -------------------------------------------------------------------------------- 1 | // Brute Force 2 | function bruteForce(n) { 3 | if (n <= 1) { 4 | return n; 5 | } 6 | return bruteForce(n - 1) + bruteForce(n - 2); 7 | } 8 | 9 | // Memoization 10 | function memoization(n, cache) { 11 | if (n <= 1) { 12 | return n; 13 | } 14 | if (cache[n] != 0) { 15 | return cache[n]; 16 | } 17 | cache[n] = memoization(n - 1, cache) + memoization(n - 2, cache); 18 | return cache[n]; 19 | } 20 | 21 | // Dynamic Programming 22 | function dp(n) { 23 | if (n < 2) { 24 | return n; 25 | } 26 | let dp = [0,1] 27 | let i = 2; 28 | while (i <= n) { 29 | let tmp = dp[1]; 30 | dp[1] = dp[0] + dp[1]; 31 | dp[0] = tmp; 32 | i++; 33 | } 34 | return dp[1]; 35 | } 36 | -------------------------------------------------------------------------------- /Dynamic Programming/1-dimension-dp/1-dimension-dp-python.py: -------------------------------------------------------------------------------- 1 | # Brute Force 2 | def bruteForce(n): 3 | if n <= 1: 4 | return n 5 | return bruteForce(n - 1) + bruteForce(n - 2) 6 | 7 | # Memoization 8 | def memoization(n, cache): 9 | if n <= 1: 10 | return n 11 | if n in cache: 12 | return cache[n] 13 | 14 | cache[n] = memoization(n - 1) + memoization(n - 2) 15 | return cache[n] 16 | 17 | # Dynamic Programming 18 | def dp(n): 19 | if n < 2: 20 | return n 21 | 22 | dp = [0, 1] 23 | i = 2 24 | while i <= n: 25 | tmp = dp[1] 26 | dp[1] = dp[0] + dp[1] 27 | dp[0] = tmp 28 | i += 1 29 | return dp[1] -------------------------------------------------------------------------------- /Dynamic Programming/2-dimension-dp/2-dimension-dp-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::vector; 4 | 5 | // Brute Force - Time: O(2 ^ (n + m)), Space: O(n + m) 6 | int bruteForce(int r, int c, int rows, int cols) { 7 | if (r == rows or c == cols) { 8 | return 0; 9 | } 10 | if (r == rows - 1 or c == cols - 1) { 11 | return 1; 12 | } 13 | return bruteForce(r + 1, c, rows, cols) + 14 | bruteForce(r, c + 1, rows, cols); 15 | } 16 | 17 | // Memoization - Time and Space: O(n * m) 18 | int memoization(int r, int c, int rows, int cols, vector>& cache) { 19 | if (r == rows or c == cols) { 20 | return 0; 21 | } 22 | if (cache[r][c] > 0) { 23 | return cache[r][c]; 24 | } 25 | if (r == rows - 1 or c == cols - 1) { 26 | return 1; 27 | } 28 | cache[r][c] = memoization(r + 1, c, rows, cols, cache) + 29 | memoization(r, c + 1, rows, cols, cache); 30 | return cache[r][c]; 31 | } 32 | 33 | // Dynamic Programming - Time: O(n * m), Space: O(m), where m is num of cols 34 | int dp(int rows, int cols) { 35 | int *prevRow = new int[cols](); 36 | 37 | for (int r = rows - 1; r >= 0; r--) { 38 | int* curRow = new int[cols](); 39 | curRow[cols - 1] = 1; 40 | for (int c = cols - 2; c >= 0; c--) { 41 | curRow[c] = curRow[c + 1] + prevRow[c]; 42 | } 43 | prevRow = curRow; 44 | } 45 | return prevRow[0]; 46 | } 47 | -------------------------------------------------------------------------------- /Dynamic Programming/2-dimension-dp/2-dimension-dp-java.java: -------------------------------------------------------------------------------- 1 | public class CountPaths { 2 | 3 | // Brute Force - Time: O(2 ^ (n + m)), Space: O(n + m) 4 | public static int bruteForce(int r, int c, int rows, int cols) { 5 | if (r == rows || c == cols) { 6 | return 0; 7 | } 8 | if (r == rows - 1 && c == cols - 1) { 9 | return 1; 10 | } 11 | return (bruteForce(r + 1, c, rows, cols) + 12 | bruteForce(r, c + 1, rows, cols)); 13 | } 14 | 15 | // Memoization - Time and Space: O(n * m) 16 | public static int memoization(int r, int c, int rows, int cols, int[][] cache) { 17 | if (r == rows || c == cols) { 18 | return 0; 19 | } 20 | if (cache[r][c] > 0) { 21 | return cache[r][c]; 22 | } 23 | if (r == rows - 1 && c == cols - 1) { 24 | return 1; 25 | } 26 | cache[r][c] = (memoization(r + 1, c, rows, cols, cache) + 27 | memoization(r, c + 1, rows, cols, cache)); 28 | return cache[r][c]; 29 | } 30 | 31 | // Dynamic Programming - Time: O(n * m), Space: O(m), where m is num of cols 32 | public static int dp(int rows, int cols) { 33 | int[] prevRow = new int[cols]; 34 | 35 | for (int i = rows - 1; i >= 0; i--) { 36 | int[] curRow = new int[cols]; 37 | curRow[cols - 1] = 1; 38 | for (int j = cols - 2; j >= 0; j--) { 39 | curRow[j] = curRow[j + 1] + prevRow[j]; 40 | } 41 | prevRow = curRow; 42 | } 43 | return prevRow[0]; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Dynamic Programming/2-dimension-dp/2-dimension-dp-javascript.js: -------------------------------------------------------------------------------- 1 | // Brute Force - Time: O(2 ^ (n + m)), Space: O(n + m) 2 | function bruteForce(r, c, rows, cols) { 3 | if (r == rows || c == cols) { 4 | return 0; 5 | } 6 | if (r == rows - 1 && c == cols - 1) { 7 | return 1; 8 | } 9 | return (bruteForce(r + 1, c, rows, cols) + 10 | bruteForce(r, c + 1, rows, cols)); 11 | } 12 | 13 | // Memoization - Time and Space: O(n * m) 14 | function memoization(r, c, rows, cols, cache) { 15 | if (r == rows || c == cols) { 16 | return 0; 17 | } 18 | if (cache[r][c] > 0) { 19 | return cache[r][c]; 20 | } 21 | if (r == rows - 1 && c == cols - 1) { 22 | return 1; 23 | } 24 | cache[r][c] = (memoization(r + 1, c, rows, cols, cache) + 25 | memoization(r, c + 1, rows, cols, cache)); 26 | return cache[r][c]; 27 | } 28 | 29 | // Dynamic Programming - Time: O(n * m), Space: O(m), where m is num of cols 30 | function dp(rows, cols) { 31 | let prevRow = new Array(cols).fill(0); 32 | for (let i = rows - 1; i >= 0; i--) { 33 | let curRow = new Array(cols).fill(0); 34 | curRow[cols - 1] = 1; 35 | for (let j = cols - 2; j >= 0; j--) { 36 | curRow[j] = curRow[j + 1] + prevRow[j]; 37 | } 38 | prevRow = curRow; 39 | } 40 | return prevRow[0]; 41 | } -------------------------------------------------------------------------------- /Dynamic Programming/2-dimension-dp/2-dimension-dp-python.py: -------------------------------------------------------------------------------- 1 | # Brute Force - Time: O(2 ^ (n + m)), Space: O(n + m) 2 | def bruteForce(r, c, rows, cols): 3 | if r == rows or c == cols: 4 | return 0 5 | if r == rows - 1 and c == cols - 1: 6 | return 1 7 | 8 | return (bruteForce(r + 1, c, rows, cols) + 9 | bruteForce(r, c + 1, rows, cols)) 10 | 11 | print(bruteForce(0, 0, 4, 4)) 12 | 13 | # Memoization - Time and Space: O(n * m) 14 | def memoization(r, c, rows, cols, cache): 15 | if r == rows or c == cols: 16 | return 0 17 | if cache[r][c] > 0: 18 | return cache[r][c] 19 | if r == rows - 1 and c == cols - 1: 20 | return 1 21 | 22 | cache[r][c] = (memoization(r + 1, c, rows, cols, cache) + 23 | memoization(r, c + 1, rows, cols, cache)) 24 | return cache[r][c] 25 | 26 | print(memoization(0, 0, 4, 4, [[0] * 4 for i in range(4)])) 27 | 28 | # Dynamic Programming - Time: O(n * m), Space: O(m), where m is num of cols 29 | def dp(rows, cols): 30 | prevRow = [0] * cols 31 | 32 | for r in range(rows - 1, -1, -1): 33 | curRow = [0] * cols 34 | curRow[cols - 1] = 1 35 | for c in range(cols - 2, -1, -1): 36 | curRow[c] = curRow[c + 1] + prevRow[c] 37 | prevRow = curRow 38 | return prevRow[0] -------------------------------------------------------------------------------- /Graphs/Adjacency List/adjacency-list-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using std::vector; 8 | using std::queue; 9 | using std::string; 10 | using std::unordered_map; 11 | using std::unordered_set; 12 | 13 | // GraphNode used for adjacency list 14 | class GraphNode { 15 | public: 16 | string& val_; 17 | vector neighbors_; 18 | 19 | GraphNode(string& val) : val_(val) {} 20 | }; 21 | 22 | // Or use a HashMap 23 | // unordered_map> adjList = 24 | // {{"A", vector{}}, {"B", vector{}}}; 25 | 26 | // Given directed edges, build an adjacency list 27 | unordered_map> buildAdjList() { 28 | vector> edges = 29 | {{"A", "B"}, {"B", "C"}, {"B", "E"}, {"C", "E"}, {"E", "D"}}; 30 | unordered_map> adjList; 31 | 32 | for (vector edge: edges) { 33 | string src = edge[0], dst = edge[1]; 34 | adjList[src].push_back(dst); 35 | } 36 | return adjList; 37 | } 38 | 39 | // Count paths (backtracking) 40 | int dfs(string& node, string& target, unordered_map>& adjList, 41 | unordered_set& visit) { 42 | if (visit.count(node)) { 43 | return 0; 44 | } 45 | if (node == target) { 46 | return 1; 47 | } 48 | int count = 0; 49 | visit.insert(node); 50 | for (string neighbor: adjList[node]) { 51 | count += dfs(neighbor, target, adjList, visit); 52 | } 53 | visit.erase(node); 54 | return count; 55 | } 56 | 57 | // Shortest path from node to target. 58 | int bfs(string& node, string& target, unordered_map>& adjList) { 59 | int length = 0; 60 | unordered_set visit; 61 | queue queue; 62 | visit.insert(node); 63 | queue.push(node); 64 | 65 | while (queue.size()) { 66 | int queueLength = queue.size(); 67 | for (int i = 0; i < queueLength; i++) { 68 | string curr = queue.front(); 69 | queue.pop(); 70 | if (curr == target) { 71 | return length; 72 | } 73 | for (string neighbor: adjList[curr]) { 74 | if (visit.count(neighbor) == 0) { 75 | visit.insert(neighbor); 76 | queue.push(neighbor); 77 | } 78 | } 79 | } 80 | length++; 81 | } 82 | return length; 83 | } -------------------------------------------------------------------------------- /Graphs/Adjacency List/adjacency-list-java.java: -------------------------------------------------------------------------------- 1 | // GraphNode used for adjacency list 2 | /* 3 | public class GraphNode { 4 | int val; 5 | List neighbors; 6 | 7 | public GraphNode(int val) { 8 | this.val = val; 9 | this.neighbors = new ArrayList(); 10 | } 11 | } 12 | */ 13 | 14 | import java.util.ArrayList; 15 | import java.util.HashMap; 16 | import java.util.HashSet; 17 | import java.util.Queue; 18 | import java.util.LinkedList; 19 | 20 | public class AdjacencyList { 21 | 22 | public HashMap> buildAdjList() { 23 | HashMap> adjList = new HashMap<>(); 24 | 25 | String[][] edges = {{"A", "B"}, {"B", "C"}, {"B", "E"}, {"C", "E"}, {"E", "D"}}; 26 | HashSet visit = new HashSet<>(); 27 | 28 | adjList.put("A", new ArrayList()); 29 | adjList.put("B", new ArrayList()); 30 | 31 | for (String[] edge: edges) { 32 | String src = edge[0], dst = edge[1]; 33 | if (!adjList.containsKey(src)) { 34 | adjList.put(src, new ArrayList()); 35 | } 36 | if (!adjList.containsKey(dst)) { 37 | adjList.put(dst, new ArrayList()); 38 | } 39 | adjList.get(src).add(dst); 40 | } 41 | return adjList; 42 | } 43 | 44 | // Count paths (backtracking) 45 | public int dfs(String node, String target, HashMap> adjList, HashSet visit) { 46 | if (visit.contains(node)) { 47 | return 0; 48 | } 49 | if (node == target) { 50 | return 1; 51 | } 52 | int count = 0; 53 | visit = new HashSet(); 54 | visit.add(node); 55 | for (String neighbor: adjList.get(node)) { 56 | count+=dfs(neighbor, target, adjList, visit); 57 | } 58 | visit.remove(node); 59 | return count; 60 | } 61 | 62 | // Shortest path from node to target. 63 | public int bfs(String node, String target, HashMap> adjList) { 64 | int length = 0; 65 | HashSet visit = new HashSet(); 66 | Queue q = new LinkedList(); 67 | visit.add(node); 68 | q.add(node); 69 | 70 | while (q.size() != 0) { 71 | int queueLength = q.size(); 72 | for (int i = 0; i < queueLength; i++) { 73 | String curr = q.peek(); 74 | q.poll(); 75 | if (curr.equals(target)) { 76 | return length; 77 | } 78 | for (String neighbor: adjList.get(curr)) { 79 | if (!visit.contains(neighbor)) { 80 | visit.add(neighbor); 81 | q.add(neighbor); 82 | } 83 | } 84 | } 85 | length++; 86 | } 87 | return length; 88 | } 89 | } -------------------------------------------------------------------------------- /Graphs/Adjacency List/adjacency-list-javascript.js: -------------------------------------------------------------------------------- 1 | // GraphNode used for adjacency list 2 | class GraphNode { 3 | constructor(val) { 4 | this.val = val; 5 | this.neighbors = new Array(); 6 | } 7 | } 8 | 9 | function buildAdjList() { 10 | let adjList = new Map(); 11 | let edges = [["A", "B"], ["B", "C"], ["B", "E"], ["C", "E"], ["E", "D"]]; 12 | adjList.set("A", new Array()); 13 | adjList.set("B", new Array()); 14 | 15 | for (let edge of edges) { 16 | let src = edge[0], dst = edge[1]; 17 | if (!adjList.has(src)) { 18 | adjList.set(src, new Array()); 19 | } 20 | if (!adjList.has(dst)) { 21 | adjList.set(dst, new Array()); 22 | } 23 | adjList.get(src).push(dst); 24 | } 25 | return adjList; 26 | } 27 | 28 | // Count paths (backtracking) 29 | function dfs(node, target, adjList, visit) { 30 | if (visit.has(node)) { 31 | return 0; 32 | } 33 | if (node == target) { 34 | return 1; 35 | } 36 | let count = 0; 37 | visit = new Set(); 38 | visit.add(node); 39 | for (let neighbor of adjList.get(node)) { 40 | count+=dfs(neighbor, target, adjList, visit); 41 | } 42 | visit.delete(node); 43 | return count; 44 | } 45 | 46 | // Shortest path from node to target. 47 | function bfs(node, target, adjList) { 48 | let length = 0; 49 | let visit = new Set(); 50 | let q = []; 51 | visit.add(node); 52 | q.push(node); 53 | 54 | while (q.length != 0) { 55 | let queueLength = q.length; 56 | 57 | for (let i = 0; i < queueLength; i++) { 58 | let curr = q.shift(); 59 | if (curr === target) { 60 | return length; 61 | } 62 | for (let neighbor of adjList.get(curr)) { 63 | if (!visit.has(neighbor)) { 64 | visit.add(neighbor); 65 | q.push(neighbor); 66 | } 67 | } 68 | } 69 | length++; 70 | } 71 | return length; 72 | } -------------------------------------------------------------------------------- /Graphs/Adjacency List/adjacency-list-python.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | # GraphNode used for adjacency list 4 | class GraphNode: 5 | def __init__(self, val): 6 | self.val = val 7 | self.neighbors = [] 8 | 9 | # Or use a HashMap 10 | adjList = { "A": [], "B": [] } 11 | 12 | # Given directed edges, build an adjacency list 13 | edges = [["A", "B"], ["B", "C"], ["B", "E"], ["C", "E"], ["E", "D"]] 14 | 15 | adjList = {} 16 | 17 | for src, dst in edges: 18 | if src not in adjList: 19 | adjList[src] = [] 20 | if dst not in adjList: 21 | adjList[dst] = [] 22 | adjList[src].append(dst) 23 | 24 | 25 | # Count paths (backtracking) 26 | def dfs(node, target, adjList, visit): 27 | if node in visit: 28 | return 0 29 | if node == target: 30 | return 1 31 | 32 | count = 0 33 | visit.add(node) 34 | for neighbor in adjList[node]: 35 | count += dfs(neighbor, target, adjList, visit) 36 | visit.remove(node) 37 | 38 | return count 39 | 40 | # Shortest path from node to target 41 | def bfs(node, target, adjList): 42 | length = 0 43 | visit = set() 44 | visit.add(node) 45 | queue = deque() 46 | queue.append(node) 47 | 48 | while queue: 49 | for i in range(len(queue)): 50 | curr = queue.popleft() 51 | if curr == target: 52 | return length 53 | 54 | for neighbor in adjList[curr]: 55 | if neighbor not in visit: 56 | visit.add(neighbor) 57 | queue.append(neighbor) 58 | length += 1 59 | return length -------------------------------------------------------------------------------- /Graphs/Matrix BFS/matrix-bfs-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using std::vector; 7 | using std::queue; 8 | using std::pair; 9 | using std::min; 10 | 11 | 12 | // Shortest path from top left to bottom right 13 | int bfs(vector>& grid) { 14 | int ROWS = grid.size(), COLS = grid[0].size(); 15 | // In cpp it's easier to use a 2D array than a hashset 16 | vector> visit(4, vector(4)); 17 | queue> queue; 18 | queue.push(pair(0, 0)); 19 | visit[0][0] = 1; 20 | 21 | int length = 0; 22 | while (queue.size()) { 23 | int queueLength = queue.size(); 24 | for (int i = 0; i < queueLength; i++) { 25 | pair curPair = queue.front(); 26 | queue.pop(); 27 | int r = curPair.first, c = curPair.second; 28 | if (r == ROWS - 1 && c == COLS - 1) { 29 | return length; 30 | } 31 | 32 | // We can directly build the four neighbors 33 | int neighbors[4][2] = {{r, c + 1}, {r, c - 1}, {r + 1, c}, {r - 1, c}}; 34 | for (int j = 0; j < 4; j++) { 35 | int newR = neighbors[j][0], newC = neighbors[j][1]; 36 | if (min(newR, newC) < 0 || newR == ROWS || newC == COLS 37 | || visit[newR][newC] || grid[newR][newC]) { 38 | continue; 39 | } 40 | queue.push(pair(newR, newC)); 41 | visit[newR][newC] = 1; 42 | } 43 | } 44 | length++; 45 | } 46 | } -------------------------------------------------------------------------------- /Graphs/Matrix BFS/matrix-bfs-java.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayDeque; 2 | import java.util.Deque; 3 | import java.util.HashSet; 4 | import java.util.Set; 5 | import java.lang.Math; 6 | 7 | public class MatrixBFS { 8 | 9 | //Matrix (2D Grid) 10 | int[][] grid = {{0, 0, 0, 0}, 11 | {1, 1, 0, 0}, 12 | {0, 0, 0, 1}, 13 | {0, 1, 0, 0}}; 14 | 15 | // Shortest path from top left to bottom right 16 | public int bfs(int[][] grid) { 17 | int ROWS = grid.length; 18 | int COLS = grid[0].length; 19 | int[][] visit = new int[4][4]; 20 | Deque queue = new ArrayDeque<>(); 21 | 22 | queue.add(new int[2]); // Add {0, 0} 23 | visit[0][0] = 1; 24 | 25 | int length = 0; 26 | while (!queue.isEmpty()) { 27 | int queueLength = queue.size(); 28 | for (int i = 0; i < queueLength; i++) { 29 | int pair[] = queue.poll(); 30 | int r = pair[0], c = pair[1]; 31 | if (r == ROWS - 1 && c == COLS - 1) { 32 | return length; 33 | } 34 | // We can directly build the four neighbors 35 | int[][] neighbors = {{r, c + 1}, {r, c - 1}, {r + 1, c}, {r - 1, c}}; 36 | for (int j = 0; j < 4; j++) { 37 | int newR = neighbors[j][0], newC = neighbors[j][1]; 38 | if (Math.min(newR, newC) < 0 || newR == ROWS || newC == COLS 39 | || visit[newR][newC] == 1 || grid[newR][newC] == 1) { 40 | continue; 41 | } 42 | queue.add(neighbors[j]); 43 | visit[newR][newC] = 1; 44 | } 45 | } 46 | length++; 47 | } 48 | return length; // This should never be called 49 | } 50 | } -------------------------------------------------------------------------------- /Graphs/Matrix BFS/matrix-bfs-javascript.js: -------------------------------------------------------------------------------- 1 | // Matrix (2D Grid) 2 | let grid = [[0, 0, 0, 0], 3 | [1, 1, 0, 0], 4 | [0, 0, 0, 1], 5 | [0, 1, 0, 0]]; 6 | 7 | // Shortest path from top left to bottom right 8 | function bfs(grid) { 9 | let ROWS = grid.length; 10 | let COLS = grid[0].length; 11 | let visit = new Array(4).fill(0).map(() => Array(4).fill(0)); // 4x4 2d array 12 | let queue = new Array(); 13 | 14 | queue.push(new Array(2).fill(0)); // Add {0, 0} 15 | visit[0][0] = 1; 16 | 17 | let length = 0; 18 | while (queue.length > 0) { 19 | let queueLength = queue.length; 20 | for (let i = 0; i < queueLength; i++) { 21 | let pair = queue.shift(); 22 | let r = pair[0], c = pair[1]; 23 | 24 | if (r == ROWS - 1 && c == COLS - 1) { 25 | return length; 26 | } 27 | // We can directly build the four neighbors 28 | let neighbors = [[r, c + 1], [r, c - 1], [r + 1, c], [r - 1, c]]; 29 | for (let j = 0; j < 4; j++) { 30 | let newR = neighbors[j][0], newC = neighbors[j][1]; 31 | if (Math.min(newR, newC) < 0 || newR == ROWS || newC == COLS 32 | || visit[newR][newC] == 1 || grid[newR][newC] == 1) { 33 | continue; 34 | } 35 | queue.push(neighbors[j]); 36 | visit[newR][newC] = 1; 37 | } 38 | } 39 | length++; 40 | } 41 | return length; // This should never be called 42 | } 43 | -------------------------------------------------------------------------------- /Graphs/Matrix BFS/matrix-bfs-python.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | # Matrix (2D Grid) 4 | grid = [[0, 0, 0, 0], 5 | [1, 1, 0, 0], 6 | [0, 0, 0, 1], 7 | [0, 1, 0, 0]] 8 | 9 | # Shortest path from top left to bottom right 10 | def bfs(grid): 11 | ROWS, COLS = len(grid), len(grid[0]) 12 | visit = set() 13 | queue = deque() 14 | queue.append((0, 0)) 15 | visit.add((0, 0)) 16 | 17 | length = 0 18 | while queue: 19 | for i in range(len(queue)): 20 | r, c = queue.popleft() 21 | if r == ROWS - 1 and c == COLS - 1: 22 | return length 23 | 24 | neighbors = [[0, 1], [0, -1], [1, 0], [-1, 0]] 25 | for dr, dc in neighbors: 26 | if (min(r + dr, c + dc) < 0 or 27 | r + dr == ROWS or c + dc == COLS or 28 | (r + dr, c + dc) in visit or grid[r + dr][c + dc] == 1): 29 | continue 30 | queue.append((r + dr, c + dc)) 31 | visit.add((r + dr, c + dc)) 32 | length += 1 -------------------------------------------------------------------------------- /Graphs/Matrix DFS/matrix-dfs-cpp-.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::vector; 5 | using std::min; 6 | 7 | // Count paths (backtracking) 8 | // In C++ it's easier to use a 2D array for visit rather than a hashset. 9 | int dfs(vector>& grid, int r, int c, vector>& visit) { 10 | int ROWS = grid.size(), COLS = grid[0].size(); 11 | if (min(r, c) < 0 || r == ROWS || c == COLS || 12 | visit[r][c] || grid[r][c]) { 13 | return 0; 14 | } 15 | if (r == ROWS - 1 && c == COLS - 1) { 16 | return 1; 17 | } 18 | 19 | visit[r][c] = 1; 20 | 21 | int count = 0; 22 | count += dfs(grid, r + 1, c, visit); 23 | count += dfs(grid, r - 1, c, visit); 24 | count += dfs(grid, r, c + 1, visit); 25 | count += dfs(grid, r, c - 1, visit); 26 | 27 | visit[r][c] = 0; 28 | return count; 29 | } 30 | -------------------------------------------------------------------------------- /Graphs/Matrix DFS/matrix-dfs-java.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.Set; 3 | import java.lang.Math; 4 | 5 | public class MatrixDFS { 6 | // Count paths (backtracking) 7 | int dfs(int[][] grid, int r, int c, int[][] visit) { 8 | int ROWS = grid.length, COLS = grid[0].length; 9 | 10 | if (Math.min(r, c) < 0 || r == ROWS || c == COLS || 11 | visit[r][c] == 1 || grid[r][c] == 1 ) { 12 | return 0; 13 | } 14 | if (r == ROWS - 1 && c == COLS - 1) { 15 | return 1; 16 | } 17 | visit[r][c] = 1; 18 | 19 | int count = 0; 20 | count += dfs(grid, r + 1, c, visit); 21 | count += dfs(grid, r - 1, c, visit); 22 | count += dfs(grid, r, c + 1, visit); 23 | count += dfs(grid, r, c - 1, visit); 24 | 25 | visit[r][c] = 0; 26 | return count; 27 | } 28 | } -------------------------------------------------------------------------------- /Graphs/Matrix DFS/matrix-dfs-javascript.js: -------------------------------------------------------------------------------- 1 | // Count paths (backtracking) 2 | function dfs(grid, r, c, visit) { 3 | let ROWS = grid.length, COLS = grid[0].length; 4 | 5 | if (Math.min(r, c) < 0 || r == ROWS || c == COLS || 6 | visit[r][c] == 1 || grid[r][c] == 1) { 7 | return 0; 8 | } 9 | if (r == ROWS - 1 && c == COLS - 1) { 10 | return 1; 11 | } 12 | visit[r][c] = 1; 13 | 14 | let count = 0; 15 | count += dfs(grid, r + 1, c, visit); 16 | count += dfs(grid, r - 1, c, visit); 17 | count += dfs(grid, r, c + 1, visit); 18 | count += dfs(grid, r, c - 1, visit); 19 | 20 | visit[r][c] = 0; 21 | return count; 22 | } 23 | -------------------------------------------------------------------------------- /Graphs/Matrix DFS/matrix-dfs-python.py: -------------------------------------------------------------------------------- 1 | # Matrix (2D Grid) 2 | grid = [[0, 0, 0, 0], 3 | [1, 1, 0, 0], 4 | [0, 0, 0, 1], 5 | [0, 1, 0, 0]] 6 | 7 | # Count paths (backtracking) 8 | def dfs(grid, r, c, visit): 9 | ROWS, COLS = len(grid), len(grid[0]) 10 | if (min(r, c) < 0 or 11 | r == ROWS or c == COLS or 12 | (r, c) in visit or grid[r][c] == 1): 13 | return 0 14 | if r == ROWS - 1 and c == COLS - 1: 15 | return 1 16 | 17 | visit.add((r, c)) 18 | 19 | count = 0 20 | count += dfs(grid, r + 1, c, visit) 21 | count += dfs(grid, r - 1, c, visit) 22 | count += dfs(grid, r, c + 1, visit) 23 | count += dfs(grid, r, c - 1, visit) 24 | 25 | visit.remove((r, c)) 26 | return count -------------------------------------------------------------------------------- /Hashing/Hash Implementation/hash-implementation-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using std::vector; 7 | using std::string; 8 | using std::pair; 9 | using std::cout; 10 | using std::endl; 11 | 12 | class HashMap { 13 | public: 14 | int size_ = 0; 15 | int capacity_ = 2; 16 | vector*> map_; 17 | 18 | HashMap() { 19 | map_ = *(new vector*> {0, 0}); 20 | } 21 | 22 | int hash(string& key) { 23 | int index = 0; 24 | for (char &c: key) { 25 | index += int(c); 26 | } 27 | return index % capacity_; 28 | } 29 | 30 | string* get(string& key) { 31 | int index = hash(key); 32 | while (map_[index]) { 33 | if (map_[index]->first == key) { 34 | return &map_[index]->second; 35 | } 36 | index++; 37 | index = index % capacity_; 38 | } 39 | return nullptr; 40 | } 41 | 42 | void put(string& key, string& val) { 43 | int index = hash(key); 44 | while (true) { 45 | if (map_[index] == 0) { 46 | map_[index] = new pair(key, val); 47 | size_++; 48 | if (size_ >= capacity_ / 2) { 49 | rehash(); 50 | } 51 | return; 52 | } else if (map_[index]->first == key) { 53 | map_[index]->second = val; 54 | return; 55 | } 56 | index++; 57 | index = index % capacity_; 58 | } 59 | } 60 | 61 | void remove(string& key) { 62 | if (!get(key)) { 63 | return; 64 | } 65 | int index = hash(key); 66 | while (true) { 67 | if (map_[index]->first == key) { 68 | // Removing an element using open-addressing actually causes a bug, 69 | // because we may create a hole in the list, and our get() may 70 | // stop searching early when it reaches this hole. 71 | map_[index] = 0; 72 | size_--; 73 | return; 74 | } 75 | index++; 76 | index = index % capacity_; 77 | } 78 | } 79 | 80 | void rehash() { 81 | capacity_ = 2 * capacity_; 82 | vector*> newMap = *(new vector*>()); 83 | 84 | for (int i = 0; i < capacity_; i++) { 85 | newMap.push_back(0); 86 | } 87 | vector*> oldMap = map_; 88 | map_ = newMap; 89 | size_ = 0; 90 | for (auto& pair: oldMap) { 91 | if (pair != 0) { 92 | put(pair->first, pair->second); 93 | } 94 | } 95 | } 96 | 97 | void print() { 98 | cout << "Printing size=" << size_ << endl; 99 | for (auto& pair: map_) { 100 | if (pair) { 101 | cout << pair->first << ' ' << pair->second << '-'; 102 | } 103 | cout << endl; 104 | } 105 | } 106 | }; -------------------------------------------------------------------------------- /Hashing/Hash Implementation/hash-implementation-java.java: -------------------------------------------------------------------------------- 1 | /* 2 | public class Pair { 3 | String key; 4 | String val; 5 | 6 | public Pair(String key, String val) { 7 | this.key = key; 8 | this.val = val; 9 | } 10 | } 11 | */ 12 | 13 | public class HashMap { 14 | int size; 15 | int capacity; 16 | Pair[] map; 17 | 18 | public HashMap() { 19 | this.size = 0; 20 | this.capacity = 2; 21 | this.map = new Pair[2]; 22 | 23 | } 24 | 25 | public int hash(String key) { 26 | int index = 0; 27 | for (int i = 0; i < key.length(); i++) { 28 | index+= (int) key.charAt(i); 29 | } 30 | return index % this.capacity; 31 | } 32 | 33 | public String get(String key) { 34 | int index = this.hash(key); 35 | while (this.map[index] != null) { 36 | if (this.map[index].key == key) { 37 | return this.map[index].val; 38 | } 39 | index += 1; 40 | index = index % this.capacity; 41 | } 42 | return null; 43 | } 44 | 45 | public void put(String key, String val) { 46 | int index = this.hash(key); 47 | 48 | while (true) { 49 | if (this.map[index] == null) { 50 | this.map[index] = new Pair(key, val); 51 | this.size += 1; 52 | if (this.size >= this.capacity / 2) { 53 | this.rehash(); 54 | } 55 | return; 56 | } else if (this.map[index].key == key) { 57 | this.map[index].val = val; 58 | return; 59 | } 60 | index += 1; 61 | index = index % this.capacity; 62 | } 63 | } 64 | 65 | public void remove(String key) { 66 | if (this.get(key) == null) { 67 | return; 68 | } 69 | 70 | int index = this.hash(key); 71 | while (true) { 72 | if (this.map[index].key == key) { 73 | // Removing an element using open-addressing actually causes a bug, 74 | // because we may create a hole in the list, and our get() may 75 | // stop searching early when it reaches this hole. 76 | this.map[index] = null; 77 | this.size -= 1; 78 | return; 79 | } 80 | index += 1; 81 | index = index % this.capacity; 82 | } 83 | } 84 | 85 | public void rehash() { 86 | this.capacity = 2 * this.capacity; 87 | Pair[] newMap = new Pair[this.capacity]; 88 | 89 | Pair[] oldMap = this.map; 90 | this.map = newMap; 91 | this.size = 0; 92 | for (Pair p: oldMap) { 93 | if (p != null) { 94 | this.put(p.key, p.val); 95 | } 96 | } 97 | } 98 | 99 | public void print() { 100 | for (Pair p : this.map) { 101 | if (p != null) { 102 | System.out.println(p.key + " " + p.val); 103 | } 104 | } 105 | } 106 | } -------------------------------------------------------------------------------- /Hashing/Hash Implementation/hash-implementation-javascript.js: -------------------------------------------------------------------------------- 1 | class Pair { 2 | constructor(key, val) { 3 | this.key = key; 4 | this.val = val; 5 | } 6 | } 7 | 8 | class HashMap { 9 | constructor() { 10 | this.size = 0; 11 | this.capacity = 2; 12 | this.map = new Array(this.capacity).fill(null);; 13 | } 14 | 15 | hash(key) { 16 | let index = 0; 17 | for (let i = 0; i < key.length; i++) { 18 | index+= key.charCodeAt(i); 19 | } 20 | return index % this.capacity; 21 | } 22 | 23 | get(key) { 24 | let index = this.hash(key); 25 | while (this.map[index] != null) { 26 | if (this.map[index].key == key) { 27 | return this.map[index].val; 28 | } 29 | index += 1; 30 | index = index % this.capacity; 31 | } 32 | return null; 33 | } 34 | 35 | put(key, val) { 36 | let index = this.hash(key); 37 | 38 | while (true) { 39 | if (this.map[index] == null) { 40 | this.map[index] = new Pair(key, val); 41 | this.size += 1; 42 | if (this.size >= this.capacity / 2) { 43 | this.rehash(); 44 | } 45 | return; 46 | } else if (this.map[index].key == key) { 47 | this.map[index].val = val; 48 | return; 49 | } 50 | index += 1; 51 | index = index % this.capacity; 52 | } 53 | } 54 | 55 | remove(key) { 56 | if (this.get(key) == null) { 57 | return; 58 | } 59 | 60 | let index = this.hash(key); 61 | while (true) { 62 | if (this.map[index].key == key) { 63 | // Removing an element using open-addressing actually causes a bug, 64 | // because we may create a hole in the list, and our get() may 65 | // stop searching early when it reaches this hole. 66 | this.map[index] = null; 67 | this.size -= 1; 68 | return; 69 | } 70 | index += 1; 71 | index = index % this.capacity; 72 | } 73 | } 74 | 75 | rehash() { 76 | this.capacity = 2 * this.capacity; 77 | let newMap = new Array(this.capacity).fill(null); 78 | let oldMap = this.map; 79 | this.map = newMap; 80 | this.size = 0; 81 | for (let i = 0; i < oldMap.length; i++) { 82 | if (oldMap[i]) { 83 | this.put(oldMap[i].key, oldMap[i].val) 84 | } 85 | } 86 | } 87 | 88 | print() { 89 | for (let i = 0; i < this.map.length; i++) { 90 | if (this.map[i]) { 91 | console.log(this.map[i].key + " " + this.map[i].val) 92 | } 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /Hashing/Hash Implementation/hash-implementation-python.py: -------------------------------------------------------------------------------- 1 | class Pair: 2 | def __init__(self, key, val): 3 | self.key = key 4 | self.val = val 5 | 6 | class HashMap: 7 | def __init__(self): 8 | self.size = 0 9 | self.capacity = 2 10 | self.map = [None, None] 11 | 12 | def hash(self, key): 13 | index = 0 14 | for c in key: 15 | index += ord(c) 16 | return index % self.capacity 17 | 18 | def get(self, key): 19 | index = self.hash(key) 20 | 21 | while self.map[index] != None: 22 | if self.map[index].key == key: 23 | return self.map[index].val 24 | index += 1 25 | index = index % self.capacity 26 | return None 27 | 28 | def put(self, key, val): 29 | index = self.hash(key) 30 | 31 | while True: 32 | if self.map[index] == None: 33 | self.map[index] = Pair(key, val) 34 | self.size += 1 35 | if self.size >= self.capacity // 2: 36 | self.rehash() 37 | return 38 | elif self.map[index].key == key: 39 | self.map[index].val = val 40 | return 41 | 42 | index += 1 43 | index = index % self.capacity 44 | 45 | def remove(self, key): 46 | if not self.get(key): 47 | return 48 | 49 | index = self.hash(key) 50 | while True: 51 | if self.map[index].key == key: 52 | # Removing an element using open-addressing actually causes a bug, 53 | # because we may create a hole in the list, and our get() may 54 | # stop searching early when it reaches this hole. 55 | self.map[index] = None 56 | self.size -= 1 57 | return 58 | index += 1 59 | index = index % self.capacity 60 | 61 | def rehash(self): 62 | self.capacity = 2 * self.capacity 63 | newMap = [] 64 | for i in range(self.capacity): 65 | newMap.append(None) 66 | 67 | oldMap = self.map 68 | self.map = newMap 69 | self.size = 0 70 | for pair in oldMap: 71 | if pair: 72 | self.put(pair.key, pair.val) 73 | 74 | def print(self): 75 | for pair in self.map: 76 | if pair: 77 | print(pair.key, pair.val) -------------------------------------------------------------------------------- /Hashing/Hash Usage/hash-usage-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using std::vector; 6 | using std::string; 7 | using std::unordered_map; 8 | 9 | int main() { 10 | vector names = {"alice", "brad", "collin", "brad", "dylan", "kim"}; 11 | unordered_map countMap; 12 | 13 | for (string& name: names) { 14 | if (countMap.count(name) == 0) { 15 | countMap[name] = 1; 16 | } else { 17 | countMap[name]++; 18 | } 19 | } 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /Hashing/Hash Usage/hash-usage-java.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | 3 | public class Counting { 4 | public static void main(String[] args) { 5 | String[] names = {"alice", "brad", "collin", "brad", "dylan", "kim"}; 6 | HashMap countMap = new HashMap<>(); 7 | 8 | for (String name: names) { 9 | // If countMap does not contain name 10 | if (!countMap.containsKey(name)) { 11 | countMap.put(name, 1); 12 | } else { 13 | countMap.put(name, countMap.get(name) + 1); 14 | } 15 | } 16 | System.out.println(countMap); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Hashing/Hash Usage/hash-usage-javascript.js: -------------------------------------------------------------------------------- 1 | const names = ["alice", "brad", "collin", "brad", "dylan", "kim"]; 2 | const countMap = new Map() 3 | 4 | for (let i = 0; i < names.length; i++) { 5 | // If countMap does not contain name 6 | if (!countMap.has(names[i])) { 7 | countMap.set(names[i], 1); 8 | } else { 9 | countMap.set(names[i], countMap.get(names[i]) + 1); 10 | } 11 | } -------------------------------------------------------------------------------- /Hashing/Hash Usage/hash-usage-python.py: -------------------------------------------------------------------------------- 1 | names = ["alice", "brad", "collin", "brad", "dylan", "kim"] 2 | 3 | countMap = {} 4 | for name in names: 5 | # If countMap does not contain name 6 | if name not in countMap: 7 | countMap[name] = 1 8 | else: 9 | countMap[name] += 1 -------------------------------------------------------------------------------- /Heap Priority Queue/Heapify/heapify-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::vector; 4 | 5 | // Min Heap 6 | class Heap { 7 | public: 8 | vector heap_; 9 | 10 | Heap() { 11 | heap_.push_back(0); 12 | } 13 | // ... not showing push, pop to save space. 14 | 15 | void heapify(vector& arr) { 16 | // 0-th position is moved to the end 17 | arr.push_back(arr[0]); 18 | 19 | heap_ = arr; 20 | int cur = (heap_.size() - 1) / 2; 21 | while (cur > 0) { 22 | // Percolate down 23 | int i = cur; 24 | while (2 * i < heap_.size()) { 25 | if (2 + i + 1 < heap_.size() && 26 | heap_[2 + i + 1] < heap_[2 * i] && 27 | heap_[i] > heap_[2 * i + 1]) { 28 | // Swap right child 29 | int tmp = heap_[i]; 30 | heap_[i] = heap_[2 * i + 1]; 31 | heap_[2 * i + 1] = tmp; 32 | i = 2 * i + 1; 33 | } else if (heap_[i] > heap_[2 * i]) { 34 | // Swap left child 35 | int tmp = heap_[i]; 36 | heap_[i] = heap_[2 * i]; 37 | heap_[2 * i] = tmp; 38 | i = 2 * i; 39 | } else { 40 | break; 41 | } 42 | } 43 | cur--; 44 | } 45 | } 46 | }; -------------------------------------------------------------------------------- /Heap Priority Queue/Heapify/heapify-java.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | import java.util.Arrays; 4 | 5 | // leftChild = heap[2 * i] 6 | // rightChild = heap[(2 * i) + 1] 7 | // parent = heap[i // 2] 8 | 9 | public class Heap { 10 | 11 | List heap; 12 | 13 | public Heap() { 14 | heap = new ArrayList(); 15 | heap.add(0); 16 | } 17 | // ... not showing push, pop to save space. 18 | 19 | public void heapify(ArrayList arr) { 20 | // 0-th position is moved to the end 21 | arr.add(arr.get(0)); 22 | 23 | heap = arr; 24 | int cur = (heap.size() - 1) / 2; 25 | while (cur > 0) { 26 | // Percolate Down 27 | int i = cur; 28 | while (2 * i < heap.size()) { 29 | if (2 + i + 1 < heap.size() && 30 | heap.get(2 + i + 1) < heap.get(2 * i) && 31 | heap.get(i) > heap.get(2 * i + 1)) { 32 | // Swap right child 33 | int tmp = heap.get(i); 34 | heap.set(i, heap.get(2 * i + 1)); 35 | heap.set(2 * i + 1, tmp); 36 | i = 2 * i + 1; 37 | } else if (heap.get(i) > heap.get(2 * i)) { 38 | // Swap left child 39 | int tmp = heap.get(i); 40 | heap.set(i, heap.get(2 * i)); 41 | heap.set(2 * i, tmp); 42 | i = 2 * i; 43 | } else { 44 | break; 45 | } 46 | } 47 | cur--; 48 | } 49 | return; 50 | } 51 | } -------------------------------------------------------------------------------- /Heap Priority Queue/Heapify/heapify-javascript.js: -------------------------------------------------------------------------------- 1 | // leftChild = heap[2 * i] 2 | // rightChild = heap[(2 * i) + 1] 3 | // parent = heap[i // 2] 4 | 5 | class Heap { 6 | 7 | constructor() { 8 | this.heap = new Array(); 9 | this.heap.push(0); 10 | } 11 | // ... not showing push, pop to save space. 12 | 13 | heapify(arr) { 14 | // 0-th position is moved to the end 15 | arr.push(arr[0]); 16 | 17 | this.heap = arr; 18 | let cur = Math.floor((this.heap.length- 1) / 2); 19 | while (cur > 0) { 20 | // Percolate Down 21 | let i = cur; 22 | while (2 * i < this.heap.length) { 23 | if (2 + i + 1 < this.heap.length && 24 | this.heap[2 + i + 1] < this.heap[2 * i] && 25 | this.heap[i] > this.heap[2 * i + 1]) { 26 | // Swap right child 27 | let tmp = this.heap[i]; 28 | this.heap[i] = this.heap[2 * i + 1]; 29 | this.heap[2 * i + 1] = tmp; 30 | i = 2 * i + 1; 31 | } else if (this.heap[i] > this.heap[2 * i]) { 32 | // Swap left child 33 | let tmp = this.heap[i]; 34 | this.heap[i] = this.heap[2 * i]; 35 | this.heap[2 * i] = tmp; 36 | i = 2 * i; 37 | } else { 38 | break; 39 | } 40 | } 41 | cur--; 42 | } 43 | return; 44 | } 45 | } -------------------------------------------------------------------------------- /Heap Priority Queue/Heapify/heapify-python.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | # Min Heap 4 | class Heap: 5 | # ... not showing push, pop to save space. 6 | 7 | def heapify(self, arr): 8 | # 0-th position is moved to the end 9 | arr.append(arr[0]) 10 | 11 | self.heap = arr 12 | cur = (len(self.heap) - 1) // 2 13 | while cur > 0: 14 | # Percolate down 15 | i = cur 16 | while 2 * i < len(self.heap): 17 | if (2 * i + 1 < len(self.heap) and 18 | self.heap[2 * i + 1] < self.heap[2 * i] and 19 | self.heap[i] > self.heap[2 * i + 1]): 20 | # Swap right child 21 | tmp = self.heap[i] 22 | self.heap[i] = self.heap[2 * i + 1] 23 | self.heap[2 * i + 1] = tmp 24 | i = 2 * i + 1 25 | elif self.heap[i] > self.heap[2 * i]: 26 | # Swap left child 27 | tmp = self.heap[i] 28 | self.heap[i] = self.heap[2 * i] 29 | self.heap[2 * i] = tmp 30 | i = 2 * i 31 | else: 32 | break 33 | cur -= 1 -------------------------------------------------------------------------------- /Heap Priority Queue/Push and Pop/push-and-pop-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::vector; 4 | 5 | // Min Heap 6 | class Heap { 7 | public: 8 | vector heap_; 9 | 10 | Heap() { 11 | heap_.push_back(0); 12 | } 13 | 14 | void push(int val) { 15 | heap_.push_back(val); 16 | int i = heap_.size() - 1; 17 | 18 | // Percolate up 19 | while (i > 1 && heap_[i] < heap_[i / 2]) { 20 | int tmp = heap_[i]; 21 | heap_[i] = heap_[i / 2]; 22 | heap_[i / 2] = tmp; 23 | i = i / 2; 24 | } 25 | } 26 | 27 | int pop() { 28 | if (heap_.size() == 1) { 29 | // Normally we would throw an exception if heap is empty. 30 | return -1; 31 | } 32 | if (heap_.size() == 2) { 33 | int res = heap_[heap_.size() - 1]; 34 | heap_.pop_back(); 35 | return res; 36 | } 37 | 38 | int res = heap_[1]; 39 | // Move last value to root 40 | heap_[1] = heap_[heap_.size() - 1]; 41 | heap_.pop_back(); 42 | int i = 1; 43 | // Percolate down 44 | while (2 * i < heap_.size()) { 45 | if (2 * i + 1 < heap_.size() && 46 | heap_[2 * i + 1] < heap_[2 * i] && 47 | heap_[i] > heap_[2 * i + 1]) { 48 | // Swap right child 49 | int tmp = heap_[i]; 50 | heap_[i] = heap_[2 * i + 1]; 51 | heap_[2 * i + 1] = tmp; 52 | i = 2 * i + 1; 53 | } else if (heap_[i] > heap_[2 * i]) { 54 | // Swap left child 55 | int tmp = heap_[i]; 56 | heap_[i] = heap_[2 * i]; 57 | heap_[2 * i] = tmp; 58 | i = 2 * i; 59 | } else { 60 | break; 61 | } 62 | } 63 | return res; 64 | } 65 | 66 | int top() { 67 | if (heap_.size() > 1) { 68 | return heap_[1]; 69 | } 70 | // Normally we would throw an exception if heap is empty. 71 | return -1; 72 | } 73 | }; -------------------------------------------------------------------------------- /Heap Priority Queue/Push and Pop/push-and-pop-java.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | 4 | // leftChild = heap[2 * i] 5 | // rightChild = heap[(2 * i) + 1] 6 | // parent = heap[i // 2] 7 | 8 | public class Heap { 9 | 10 | List heap; 11 | 12 | public Heap() { 13 | heap = new ArrayList(); 14 | heap.add(0); 15 | } 16 | 17 | public void push(int val) { 18 | heap.add(val); 19 | int i = heap.size() - 1; 20 | 21 | // Percolate up 22 | while (i > 1 && heap.get(i) < heap.get(i / 2)) { 23 | int tmp = heap.get(i); 24 | heap.set(i, heap.get(i / 2)); 25 | heap.set(i / 2, tmp); 26 | i = i / 2; 27 | } 28 | } 29 | 30 | public int pop() { 31 | if (heap.size() == 1) { 32 | //return null; 33 | } 34 | if (heap.size() == 2) { 35 | return heap.remove(heap.size() - 1); // equivalent to heap.remove(1) 36 | } 37 | 38 | int res = heap.get(1); 39 | // Move last value to root 40 | heap.set(1, heap.remove(heap.size() - 1)) ; 41 | int i = 1; 42 | // Percolate down 43 | while(2 * i < heap.size()) { 44 | if (2*i + 1 < heap.size() && 45 | heap.get(2 * i + 1) < heap.get(2 * i) && 46 | heap.get(i) > heap.get(2 * i + 1)) { 47 | // Swap right child 48 | int tmp = heap.get(i); 49 | heap.set(i, heap.get(2 * i + 1)); 50 | heap.set(2 * i + 1, tmp); 51 | i = 2 * i + 1; 52 | } else if (heap.get(i) > heap.get(2 * i)) { 53 | // Swap left child 54 | int tmp = heap.get(i); 55 | heap.set(i, heap.get(2 * i)); 56 | heap.set(2 * i, tmp); 57 | i = 2 * i; 58 | } else { 59 | break; 60 | } 61 | } 62 | return res; 63 | } 64 | } -------------------------------------------------------------------------------- /Heap Priority Queue/Push and Pop/push-and-pop-javascript.js: -------------------------------------------------------------------------------- 1 | // leftChild = heap[2 * i] 2 | // rightChild = heap[(2 * i) + 1] 3 | // parent = heap[i // 2] 4 | 5 | class Heap { 6 | constructor() { 7 | this.heap = new Array(); 8 | this.heap.push(0); 9 | } 10 | 11 | push(val) { 12 | this.heap.push(val); 13 | let i = this.heap.length - 1; 14 | 15 | // Percolate up 16 | while (i > 1 && this.heap[i] < this.heap[Math.floor(i / 2)]) { 17 | let tmp = this.heap[i]; 18 | this.heap[i] = this.heap[Math.floor(i / 2)]; 19 | this.heap[Math.floor(i / 2)] = tmp; 20 | i = Math.floor(i / 2); 21 | } 22 | } 23 | 24 | pop() { 25 | if (this.heap.length == 1) { 26 | // Normally we would throw an exception if heap is empty. 27 | return -1; 28 | } 29 | if (this.heap.length == 2) { 30 | return this.heap.pop(); 31 | } 32 | 33 | let res = this.heap[1]; 34 | // Move last value to root 35 | this.heap[1] = this.heap.pop(); 36 | let i = 1; 37 | // Percolate down 38 | while(2 * i < this.heap.length) { 39 | if (2*i + 1 < heap.length && 40 | this.heap[2 * i + 1] < this.heap[2 * i] && 41 | this.heap[i] > this.heap[2 * i + 1]) { 42 | // Swap right child 43 | let tmp = this.heap[i]; 44 | this.heap[i]= this.heap[2 * i + 1]; 45 | this.heap[2 * i + 1] = tmp; 46 | i = 2 * i + 1; 47 | } else if (this.heap[i] > this.heap[2 * i]) { 48 | // Swap left child 49 | let tmp = this.heap[i]; 50 | this.heap[i] = this.heap[2 * i]; 51 | this.heap[2 * i] = tmp; 52 | i = 2 * i; 53 | } else { 54 | break; 55 | } 56 | } 57 | return res; 58 | } 59 | } -------------------------------------------------------------------------------- /Heap Priority Queue/Push and Pop/push-and-pop-python.py: -------------------------------------------------------------------------------- 1 | # Min Heap 2 | class Heap: 3 | def __init__(self): 4 | self.heap = [0] 5 | 6 | def push(self, val): 7 | self.heap.append(val) 8 | i = len(self.heap) - 1 9 | 10 | # Percolate up 11 | while i > 1 and self.heap[i] < self.heap[i // 2]: 12 | tmp = self.heap[i] 13 | self.heap[i] = self.heap[i // 2] 14 | self.heap[i // 2] = tmp 15 | i = i // 2 16 | 17 | def pop(self): 18 | if len(self.heap) == 1: 19 | return None 20 | if len(self.heap) == 2: 21 | return self.heap.pop() 22 | 23 | res = self.heap[1] 24 | # Move last value to root 25 | self.heap[1] = self.heap.pop() 26 | i = 1 27 | # Percolate down 28 | while 2 * i < len(self.heap): 29 | if (2 * i + 1 < len(self.heap) and 30 | self.heap[2 * i + 1] < self.heap[2 * i] and 31 | self.heap[i] > self.heap[2 * i + 1]): 32 | # Swap right child 33 | tmp = self.heap[i] 34 | self.heap[i] = self.heap[2 * i + 1] 35 | self.heap[2 * i + 1] = tmp 36 | i = 2 * i + 1 37 | elif self.heap[i] > self.heap[2 * i]: 38 | # Swap left child 39 | tmp = self.heap[i] 40 | self.heap[i] = self.heap[2 * i] 41 | self.heap[2 * i] = tmp 42 | i = 2 * i 43 | else: 44 | break 45 | return res 46 | 47 | def top(self): 48 | if len(self.heap) > 1: 49 | return self.heap[1] 50 | return None 51 | 52 | def heapify(self, arr): 53 | # 0-th position is moved to the end 54 | arr.append(arr[0]) 55 | 56 | self.heap = arr 57 | cur = (len(self.heap) - 1) // 2 58 | while cur > 0: 59 | # Percolate down 60 | i = cur 61 | while 2 * i < len(self.heap): 62 | if (2 * i + 1 < len(self.heap) and 63 | self.heap[2 * i + 1] < self.heap[2 * i] and 64 | self.heap[i] > self.heap[2 * i + 1]): 65 | # Swap right child 66 | tmp = self.heap[i] 67 | self.heap[i] = self.heap[2 * i + 1] 68 | self.heap[2 * i + 1] = tmp 69 | i = 2 * i + 1 70 | elif self.heap[i] > self.heap[2 * i]: 71 | # Swap left child 72 | tmp = self.heap[i] 73 | self.heap[i] = self.heap[2 * i] 74 | self.heap[2 * i] = tmp 75 | i = 2 * i 76 | else: 77 | break 78 | cur -= 1 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or 4 | distribute this software, either in source code form or as a compiled 5 | binary, for any purpose, commercial or non-commercial, and by any 6 | means. 7 | 8 | In jurisdictions that recognize copyright laws, the author or authors 9 | of this software dedicate any and all copyright interest in the 10 | software to the public domain. We make this dedication for the benefit 11 | of the public at large and to the detriment of our heirs and 12 | successors. We intend this dedication to be an overt act of 13 | relinquishment in perpetuity of all present and future rights to this 14 | software under copyright law. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 18 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 19 | IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 20 | OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 21 | ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | 24 | For more information, please refer to 25 | -------------------------------------------------------------------------------- /Linked Lists/Doubly Linked Lists/double-linked-java.java: -------------------------------------------------------------------------------- 1 | /* 2 | public class DoublyLinkedListNode { 3 | 4 | int val; 5 | DoublyLinkedListNode next; 6 | DoublyLinkedListNode prev; 7 | 8 | public DoublyLinkedListNode(int val) { 9 | this.val = val; 10 | this.next = null; 11 | this.prev = null; 12 | } 13 | } 14 | */ 15 | 16 | // Implementation for Doubly Linked List 17 | public class DoublyLinkedList { 18 | DoublyLinkedListNode head; 19 | DoublyLinkedListNode tail; 20 | 21 | public DoublyLinkedList() { 22 | head = new DoublyLinkedListNode(-1); 23 | tail = new DoublyLinkedListNode(-1); 24 | head.next = tail; 25 | tail.prev = head; 26 | } 27 | 28 | public void insertFront(int val) { 29 | DoublyLinkedListNode newNode = new DoublyLinkedListNode(val); 30 | newNode.prev = head; 31 | newNode.next = head.next; 32 | 33 | head.next.prev = newNode; 34 | head.next = newNode; 35 | } 36 | 37 | public void insertEnd(int val) { 38 | DoublyLinkedListNode newNode = new DoublyLinkedListNode(val); 39 | newNode.next = tail; 40 | newNode.prev = tail.prev; 41 | 42 | tail.prev.next = newNode; 43 | tail.prev = newNode; 44 | } 45 | 46 | public void removeFront() { 47 | head.next.next.prev = head; 48 | head.next = head.next.next; 49 | } 50 | 51 | public void removeEnd() { 52 | tail.prev.prev.next = tail; 53 | tail.prev = tail.prev.prev; 54 | } 55 | 56 | public void print() { 57 | DoublyLinkedListNode curr = head.next; 58 | while (curr != tail) { 59 | System.out.print(curr.val + " -> "); 60 | curr = curr.next; 61 | } 62 | System.out.println(); 63 | } 64 | } -------------------------------------------------------------------------------- /Linked Lists/Doubly Linked Lists/double-linked-python.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.next = None 5 | self.prev = None 6 | 7 | # Implementation for Doubly Linked List 8 | class LinkedList: 9 | def __init__(self): 10 | # Init the list with 'dummy' head and tail nodes which makes 11 | # edge cases for insert & remove easier. 12 | self.head = ListNode(-1) 13 | self.tail = ListNode(-1) 14 | self.head.next = self.tail 15 | self.tail.prev = self.head 16 | 17 | def insertFront(self, val): 18 | newNode = ListNode(val) 19 | newNode.prev = self.head 20 | newNode.next = self.head.next 21 | 22 | self.head.next.prev = newNode 23 | self.head.next = newNode 24 | 25 | def insertEnd(self, val): 26 | newNode = ListNode(val) 27 | newNode.next = self.tail 28 | newNode.prev = self.tail.prev 29 | 30 | self.tail.prev.next = newNode 31 | self.tail.prev = newNode 32 | 33 | # Remove first node after dummy head (assume it exists) 34 | def removeFront(self): 35 | self.head.next.next.prev = self.head 36 | self.head.next = self.head.next.next 37 | 38 | # Remove last node before dummy tail (assume it exists) 39 | def removeEnd(self): 40 | self.tail.prev.prev.next = self.tail 41 | self.tail.prev = self.tail.prev.prev 42 | 43 | def print(self): 44 | curr = self.head.next 45 | while curr != self.tail: 46 | print(curr.val, " -> ") 47 | curr = curr.next 48 | print() 49 | -------------------------------------------------------------------------------- /Linked Lists/Doubly Linked Lists/doubly-linked-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | 6 | class ListNode { 7 | public: 8 | int val_; 9 | ListNode* next = nullptr; 10 | ListNode* prev = nullptr; 11 | 12 | ListNode(int val) { 13 | val_ = val; 14 | } 15 | }; 16 | 17 | // Implementation for Doubly Linked List 18 | class LinkedList { 19 | public: 20 | ListNode* head; 21 | ListNode* tail; 22 | 23 | LinkedList() { 24 | // Init the list with a 'dummy' node which makes 25 | // removing a node from the beginning of list easier. 26 | head = new ListNode(-1); 27 | tail = new ListNode(-1); 28 | head->next = tail; 29 | tail->prev = head; 30 | } 31 | 32 | void insertFront(int val) { 33 | ListNode* newNode = new ListNode(val); 34 | newNode->prev = head; 35 | newNode->next = head->next; 36 | 37 | head->next->prev = newNode; 38 | head->next = newNode; 39 | } 40 | 41 | void insertEnd(int val) { 42 | ListNode* newNode = new ListNode(val); 43 | newNode->next = tail; 44 | newNode->prev = tail->prev; 45 | 46 | tail->prev->next = newNode; 47 | tail->prev = newNode; 48 | } 49 | 50 | // Remove first node after dummy head (assume it exists) 51 | void removeFront() { 52 | head->next->next->prev = head; 53 | head->next = head->next->next; 54 | } 55 | 56 | // Remove last node before dummy tail (assume it exists) 57 | void removeEnd() { 58 | tail->prev->prev->next = tail; 59 | tail->prev = tail->prev->prev; 60 | } 61 | 62 | void print() { 63 | ListNode* curr = head->next; 64 | while (curr != tail) { 65 | cout << curr->val_ << " -> "; 66 | curr = curr->next; 67 | } 68 | cout << endl; 69 | } 70 | }; 71 | -------------------------------------------------------------------------------- /Linked Lists/Doubly Linked Lists/doubly-linked-javascript.js: -------------------------------------------------------------------------------- 1 | class DoublyListNode { 2 | constructor (val) { 3 | this.val = val; 4 | this.next = null; 5 | } 6 | } 7 | 8 | // Implementation for Doubly Linked List 9 | class DoublyLinkedList { 10 | constructor() { 11 | // Init the list with 'dummy' head and tail nodes which makes 12 | // edge cases for insert & remove easier. 13 | this.head = new DoublyListNode(-1); 14 | this.tail = new DoublyListNode(-1); 15 | this.head.next = this.tail; 16 | this.tail.prev = this.head; 17 | } 18 | 19 | insertFront(val) { 20 | const newNode = new DoublyListNode(val); 21 | newNode.prev = this.head; 22 | newNode.next = this.head.next; 23 | 24 | this.head.next.prev = newNode; 25 | this.head.next = newNode; 26 | } 27 | 28 | insertEnd(val) { 29 | const newNode = new DoublyListNode(val); 30 | newNode.next = this.tail; 31 | newNode.prev = this.tail.prev; 32 | 33 | this.tail.prev.next = newNode; 34 | this.tail.prev = newNode; 35 | } 36 | 37 | // Remove first node after dummy head (assume it exists) 38 | removeFront() { 39 | this.head.next.next.prev = this.head; 40 | this.head.next = this.head.next.next; 41 | } 42 | 43 | // Remove last node before dummy tail (assume it exists) 44 | removeEnd() { 45 | this.tail.prev.prev.next = this.tail; 46 | this.tail.prev = this.tail.prev.prev; 47 | } 48 | 49 | print() { 50 | let curr = this.head.next; 51 | let s = ""; 52 | while (curr != this.tail) { 53 | s+= curr.val + "->"; 54 | curr = curr.next; 55 | } 56 | console.log(s); 57 | } 58 | } -------------------------------------------------------------------------------- /Linked Lists/Queues/queues-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | 6 | class ListNode { 7 | public: 8 | int val_; 9 | ListNode* next = nullptr; 10 | 11 | ListNode(int val) { 12 | val_ = val; 13 | } 14 | }; 15 | 16 | class Queue { 17 | public: 18 | // Implementing this with dummy nodes would be easier! 19 | ListNode* left = nullptr; 20 | ListNode* right = nullptr; 21 | 22 | Queue() {} 23 | 24 | void enqueue(int val) { 25 | ListNode* newNode = new ListNode(val); 26 | 27 | // Queue is non-empty 28 | if (right != nullptr) { 29 | right->next = newNode; 30 | right = right->next; 31 | } 32 | // Queue 33 | else { 34 | left = right = newNode; 35 | } 36 | } 37 | 38 | int dequeue() { 39 | // Queue is empty 40 | if (left == nullptr) { 41 | return -1; // Better to throw an exception 42 | } 43 | // Remove left node and return value 44 | int val = left->val_; 45 | left = left->next; 46 | return val; 47 | } 48 | 49 | void print() { 50 | ListNode* curr = left; 51 | while (curr != nullptr) { 52 | cout << curr->val_ << " -> "; 53 | curr = curr->next; 54 | } 55 | cout << endl; 56 | } 57 | }; -------------------------------------------------------------------------------- /Linked Lists/Queues/queues-java.java: -------------------------------------------------------------------------------- 1 | // public class ListNode { 2 | // int val; 3 | // ListNode next; 4 | // 5 | // public ListNode(int val) { 6 | // this.val = val; 7 | // this.next = null; 8 | // } 9 | // } 10 | 11 | public class Queue { 12 | ListNode left; // front of Queue front -> [1,2,3] 13 | ListNode right; // back of Queue [1,2,3] <- back 14 | 15 | public Queue() { 16 | this.left = null; 17 | this.right = null; 18 | } 19 | 20 | public void enqueue(int val) { 21 | ListNode newNode = new ListNode(val); 22 | if (this.right != null) { 23 | // Queue is not empty 24 | this.right.next = newNode; 25 | this.right = this.right.next; 26 | } else { 27 | // Queue is empty 28 | this.left = newNode; 29 | this.right = newNode; 30 | } 31 | } 32 | 33 | public int dequeue() { 34 | if (this.left == null) { 35 | // Queue is empty 36 | System.exit(0); 37 | } 38 | int val = this.left.val; 39 | this.left = this.left.next; 40 | return val; 41 | 42 | } 43 | 44 | public void print() { 45 | ListNode cur = this.left; 46 | while(cur != null) { 47 | System.out.print(cur.val + " -> "); 48 | cur = cur.next; 49 | } 50 | System.out.println(); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Linked Lists/Queues/queues-javascript.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor (val) { 3 | this.val = val; 4 | this.next = null; 5 | } 6 | } 7 | 8 | class Queue { 9 | 10 | // Implementing this with dummy nodes would be easier! 11 | constructor() { 12 | this.left = null; 13 | this.right = null; 14 | } 15 | 16 | enqueue(val) { 17 | const newNode = new ListNode(val); 18 | if (this.right != null) { 19 | // Queue is not empty 20 | this.right.next = newNode; 21 | this.right = this.right.next; 22 | } else { 23 | // Queue is empty 24 | this.left = newNode; 25 | this.right = newNode; 26 | } 27 | } 28 | 29 | dequeue() { 30 | if (this.left == null) { 31 | // Queue is empty 32 | return; 33 | } 34 | // Remove left node and return value 35 | const val = this.left.val; 36 | this.left = this.left.next; 37 | return val; 38 | } 39 | 40 | print() { 41 | let cur = this.left; 42 | let s = ""; 43 | while(cur != null) { 44 | s+= cur.val + "->"; 45 | cur = cur.next; 46 | } 47 | console.log(s) 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Linked Lists/Queues/queues-python.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.next = None 5 | 6 | class Queue: 7 | # Implementing this with dummy nodes would be easier! 8 | def __init__(self): 9 | self.left = self.right = None 10 | 11 | def enqueue(self, val): 12 | newNode = ListNode(val) 13 | 14 | # Queue is non-empty 15 | if self.right: 16 | self.right.next = newNode 17 | self.right = self.right.next 18 | # Queue is empty 19 | else: 20 | self.left = self.right = newNode 21 | 22 | def dequeue(self): 23 | # Queue is empty 24 | if not self.left: 25 | return None 26 | 27 | # Remove left node and return value 28 | val = self.left.val 29 | self.left = self.left.next 30 | return val 31 | 32 | def print(self): 33 | cur = self.left 34 | while cur: 35 | print(cur.val, ' -> ', end ="") 36 | cur = cur.next 37 | print() # new line -------------------------------------------------------------------------------- /Linked Lists/Singly Linked Lists/singly-linked-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | 6 | class ListNode { 7 | public: 8 | int val_; 9 | ListNode* next = nullptr; 10 | 11 | ListNode(int val) { 12 | val_ = val; 13 | } 14 | }; 15 | 16 | // Implementation for Singly Linked List 17 | class LinkedList { 18 | public: 19 | ListNode* head; 20 | ListNode* tail; 21 | 22 | LinkedList() { 23 | // Init the list with a 'dummy' node which makes 24 | // removing a node from the beginning of list easier. 25 | head = new ListNode(-1); 26 | tail = head; 27 | } 28 | 29 | void insertEnd(int val) { 30 | tail->next = new ListNode(val); 31 | tail = tail->next; 32 | } 33 | 34 | void remove(int index) { 35 | int i = 0; 36 | ListNode* curr = head; 37 | while (i < index && curr) { 38 | i++; 39 | curr = curr->next; 40 | } 41 | 42 | // Remove the node ahead of curr 43 | if (curr) { 44 | curr->next = curr->next->next; 45 | } 46 | } 47 | 48 | void print() { 49 | ListNode* curr = head->next; 50 | while (curr) { 51 | cout << curr->val_ << " -> "; 52 | curr = curr->next; 53 | } 54 | cout << endl; 55 | } 56 | }; 57 | -------------------------------------------------------------------------------- /Linked Lists/Singly Linked Lists/singly-linked-java.java: -------------------------------------------------------------------------------- 1 | /* 2 | public class ListNode { 3 | int val; 4 | ListNode next; 5 | 6 | public ListNode(int val) { 7 | this.val = val; 8 | this.next = null; 9 | } 10 | } 11 | */ 12 | 13 | // Implementation for Singly Linked List 14 | public class SinglyLinkedList { 15 | ListNode head; 16 | ListNode tail; 17 | 18 | public SinglyLinkedList() { 19 | head = new ListNode(-1); 20 | tail = head; 21 | } 22 | 23 | public void insertEnd(int val) { 24 | tail.next = new ListNode(val); 25 | tail = tail.next; 26 | } 27 | 28 | public void remove(int index) { 29 | int i = 0; 30 | ListNode curr = head; 31 | while (i < index && curr != null) { 32 | i++; 33 | curr = curr.next; 34 | } 35 | 36 | // Remove the node ahead of curr 37 | if (curr != null) { 38 | curr.next = curr.next.next; 39 | } 40 | } 41 | 42 | public void print() { 43 | ListNode curr = head.next; 44 | while (curr != null) { 45 | System.out.print(curr.val + " -> "); 46 | curr = curr.next; 47 | } 48 | 49 | System.out.println(); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /Linked Lists/Singly Linked Lists/singly-linked-javascript.js: -------------------------------------------------------------------------------- 1 | class ListNode { 2 | constructor (val) { 3 | this.val = val; 4 | this.next = null; 5 | } 6 | } 7 | 8 | class LinkedList { 9 | constructor() { 10 | // Init the list with a 'dummy' node which makes 11 | // removing a node from the beginning of list easier. 12 | this.head = new ListNode(-1); 13 | this.tail = this.head; 14 | } 15 | 16 | insertEnd(val) { 17 | this.tail.next = new ListNode(val); 18 | this.tail = this.tail.next; 19 | } 20 | 21 | remove(index) { 22 | let i = 0; 23 | let curr; 24 | curr = this.head; 25 | while(i < index && curr != null) { 26 | i++; 27 | curr = curr.next; 28 | } 29 | 30 | // Remove the node ahead of curr 31 | if (curr != null) { 32 | curr.next = curr.next.next; 33 | } 34 | } 35 | 36 | print() { 37 | let curr = this.head.next; 38 | let s = ""; 39 | while (curr != null) { 40 | s+= curr.val + "->"; 41 | curr = curr.next; 42 | } 43 | console.log(s); 44 | } 45 | } -------------------------------------------------------------------------------- /Linked Lists/Singly Linked Lists/singly-linked-python.py: -------------------------------------------------------------------------------- 1 | class ListNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.next = None 5 | 6 | # Implementation for Singly Linked List 7 | class LinkedList: 8 | def __init__(self): 9 | # Init the list with a 'dummy' node which makes 10 | # removing a node from the beginning of list easier. 11 | self.head = ListNode(-1) 12 | self.tail = self.head 13 | 14 | def insertEnd(self, val): 15 | self.tail.next = ListNode(val) 16 | self.tail = self.tail.next 17 | 18 | def remove(self, index): 19 | i = 0 20 | curr = self.head 21 | while i < index and curr: 22 | i += 1 23 | curr = curr.next 24 | 25 | # Remove the node ahead of curr 26 | if curr: 27 | curr.next = curr.next.next 28 | 29 | def print(self): 30 | curr = self.head.next 31 | while curr: 32 | print(curr.val, ' -> ') 33 | curr = curr.next 34 | print() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Structure-and-Advance-Algorithm 2 | 3 | *don't follow me chickens >=<* 4 | 5 | | **Category** | **LeetCode Problems** |✅| 6 | |--------------------------|--------------------------------------------------------------------------------------------------------------------------|-------| 7 | | **Static Array** | [Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/)
[Remove Element](https://leetcode.com/problems/remove-element/)
[Shuffle the Array](https://leetcode.com/problems/shuffle-the-array/) | | 8 | | **Dynamic Array** | [Concatenation of Array](https://leetcode.com/problems/concatenation-of-array/) | 9 | | **Stacks** | [Baseball Game](https://leetcode.com/problems/baseball-game/)
[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)
[Min Stack](https://leetcode.com/problems/min-stack/) | 10 | | **Singly Linked Lists** | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)
[Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/) | 11 | | **Doubly Linked Lists** | [Design Linked List](https://leetcode.com/problems/design-linked-list/)
[Design Browser History](https://leetcode.com/problems/design-browser-history/) | 12 | | **Queues** | [Number of Students Unable to Eat Lunch](https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/)
[Implement Stack using Queues](https://leetcode.com/problems/implement-stack-using-queues/) | 13 | | **Factorial** | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | 14 | | **Fibonacci** | [Fibonacci Number](https://leetcode.com/problems/fibonacci-number/)
[Climbing Stairs](https://leetcode.com/problems/climbing-stairs/) | 15 | | **Insertion Sort** | [Sort an Array](https://leetcode.com/problems/sort-an-array/) | 16 | | **Merge Sort** | [Sort an Array](https://leetcode.com/problems/sort-an-array/)
[Merge k Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/) | 17 | | **Quick Sort** | [Sort an Array](https://leetcode.com/problems/sort-an-array/)
[Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | 18 | | **Bucket Sort** | [Sort Colors](https://leetcode.com/problems/sort-colors/) | 19 | | **Search Array** | [Binary Search](https://leetcode.com/problems/binary-search/)
[Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/) | 20 | | **Binary Search Trees** | [Search in a Binary Search Tree](https://leetcode.com/problems/search-in-a-binary-search-tree/)
[Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) | 21 | | **BST Insert and Remove**| [Insert into a Binary Search Tree](https://leetcode.com/problems/insert-into-a-binary-search-tree/)
[Delete Node in a BST](https://leetcode.com/problems/delete-node-in-a-bst/) | 22 | | **Depth First Search** | [Binary Tree Inorder Traversal](https://leetcode.com/problems/binary-tree-inorder-traversal/)
[Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)
[Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) | 23 | | **Breadth First Search** | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
[Binary Tree Right Side View](https://leetcode.com/problems/binary-tree-right-side-view/) | 24 | | **Tree Maze** | [Path Sum](https://leetcode.com/problems/path-sum/)
[Subsets](https://leetcode.com/problems/subsets/)
[Combination Sum](https://leetcode.com/problems/combination-sum/) | 25 | | **Push and Pop** | [Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/) | 26 | | **Heapify** | [Last Stone Weight](https://leetcode.com/problems/last-stone-weight/)
[K Closest Points to Origin](https://leetcode.com/problems/k-closest-points-to-origin/)
[Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | 27 | | **Hash Usage** | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
[Two Sum](https://leetcode.com/problems/two-sum/)
[LRU Cache](https://leetcode.com/problems/lru-cache/) | 28 | | **Hash Implementation** | [Design HashSet](https://leetcode.com/problems/design-hashset/)
[Design HashMap](https://leetcode.com/problems/design-hashmap/) | 29 | | **Matrix DFS** | [Number of Islands](https://leetcode.com/problems/number-of-islands/)
[Max Area of Island](https://leetcode.com/problems/max-area-of-island/) | 30 | | **Matrix BFS** | [Shortest Path in Binary Matrix](https://leetcode.com/problems/shortest-path-in-binary-matrix/)
[Rotting Oranges](https://leetcode.com/problems/rotting-oranges/) | 31 | | **Adjacency List** | [Clone Graph](https://leetcode.com/problems/clone-graph/)
[Course Schedule](https://leetcode.com/problems/course-schedule/) | 32 | | **1-Dimension DP** | [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)
[House Robber](https://leetcode.com/problems/house-robber/) | 33 | | **2-Dimension DP** | [Unique Paths](https://leetcode.com/problems/unique-paths/)
[Unique Paths II](https://leetcode.com/problems/unique-paths-ii/)
[Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/) | 34 | | **Bit Operator** | [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)
[Counting Bits](https://leetcode.com/problems/counting-bits/)
[Reverse Bits](https://leetcode.com/problems/reverse-bits/) | 35 | 36 | -------------------------------------------------------------------------------- /Recursion/Factorial/factorial-cpp.cpp: -------------------------------------------------------------------------------- 1 | // Recursive implementation of n! (n-factorial) calculation 2 | int factorial(int n) { 3 | // Base case: n = 0 or 1 4 | if (n <= 1) { 5 | return 1; 6 | } 7 | // Recursive case: n! = n * (n - 1)! 8 | return n * factorial(n - 1); 9 | } -------------------------------------------------------------------------------- /Recursion/Factorial/factorial-java.java: -------------------------------------------------------------------------------- 1 | // Recursive implementation of n! (n-factorial) calculation 2 | public class Factorial { 3 | 4 | public static int factorial(int n) { 5 | 6 | // Base case: n = 0 or 1 7 | if (n <= 1) { 8 | return 1; 9 | } 10 | 11 | // Recursive case: n! = n * (n - 1)! 12 | return n * factorial(n-1); 13 | } 14 | } -------------------------------------------------------------------------------- /Recursion/Factorial/factorial-javascript.js: -------------------------------------------------------------------------------- 1 | function factorial(n) { 2 | if (n <= 1) { 3 | return 1; 4 | } 5 | return n * factorial(n - 1); 6 | } 7 | console.log(factorial(5)); -------------------------------------------------------------------------------- /Recursion/Factorial/factorial-python.py: -------------------------------------------------------------------------------- 1 | # Recursive implementation of n! (n-factorial) calculation 2 | def factorial(n): 3 | # Base case: n = 0 or 1 4 | if n <= 1: 5 | return 1 6 | 7 | # Recursive case: n! = n * (n - 1)! 8 | return n * factorial(n - 1) -------------------------------------------------------------------------------- /Recursion/Fibonacci/fibonacci-cpp.cpp: -------------------------------------------------------------------------------- 1 | // Recursive implementation to calculate the n-th Fibonacci number 2 | int fibonacci(int n) { 3 | // Base case: n = 0 or 1 4 | if (n <= 1) { 5 | return n; 6 | } 7 | // Recursive case: fib(n) = fib(n - 1) + fib(n - 1) 8 | return fibonacci(n - 1) + fibonacci(n - 2); 9 | } -------------------------------------------------------------------------------- /Recursion/Fibonacci/fibonacci-java.java: -------------------------------------------------------------------------------- 1 | // Recursive implementation to calculate the n-th Fibonacci number 2 | public class Fibonacci { 3 | 4 | // Base case: n = 0 or 1 5 | public static int fibonacci(int n) { 6 | if (n <= 1) { 7 | return n; 8 | } 9 | 10 | // Recursive case: fib(n) = fib(n - 1) + fib(n - 1) 11 | return fibonacci(n-1) + fibonacci(n-2); 12 | } 13 | } -------------------------------------------------------------------------------- /Recursion/Fibonacci/fibonacci-javascript.js: -------------------------------------------------------------------------------- 1 | // Recursive implementation to calculate the n-th Fibonacci number 2 | function fibonacci(n) { 3 | // Base case: n = 0 or 1 4 | if (n <= 1) { 5 | return n; 6 | } 7 | // Recursive case: fib(n) = fib(n - 1) + fib(n - 2) 8 | return fibonacci(n - 1) + fibonacci(n - 2); 9 | } -------------------------------------------------------------------------------- /Recursion/Fibonacci/fibonacci-python.py: -------------------------------------------------------------------------------- 1 | # Recursive implementation to calculate the n-th Fibonacci number 2 | def fibonacci(n): 3 | # Base case: n = 0 or 1 4 | if n <= 1: 5 | return n 6 | 7 | # Recursive case: fib(n) = fib(n - 1) + fib(n - 1) 8 | return fibonacci(n - 1) + fibonacci(n - 2) -------------------------------------------------------------------------------- /Sorting/Bucket Sort/bucket-sort-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::vector; 4 | 5 | vector bucketSort(vector& arr) { 6 | // Assuming arr only contains 0, 1 or 2 7 | int counts[] = {0, 0, 0}; 8 | 9 | // Count the quantity of each val in arr 10 | for (int n: arr) { 11 | counts[n]++; 12 | } 13 | 14 | int i = 0; 15 | for (int n = 0; n < 3; n++) { 16 | for (int j = 0; j < counts[n]; j++) { 17 | arr[i] = n; 18 | i++; 19 | } 20 | } 21 | return arr; 22 | } 23 | -------------------------------------------------------------------------------- /Sorting/Bucket Sort/bucket-sort-java.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class BucketSort { 4 | 5 | // Java implementation of Bucket Sort 6 | public static int[] bucketSort(int[] arr) { 7 | // Assuming arr only contains 0, 1 or 2 8 | int[] counts = {0, 0, 0}; 9 | 10 | // Count the quantity of each val in arr 11 | for (int num: arr) { 12 | counts[num] += 1; 13 | } 14 | 15 | // Fill each bucket in the original array 16 | int i = 0; 17 | for (int n = 0; n < counts.length; n++) { 18 | for (int j = 0; j < counts[n]; j++) { 19 | arr[i] = n; 20 | i++; 21 | } 22 | } 23 | return arr; 24 | } 25 | } -------------------------------------------------------------------------------- /Sorting/Bucket Sort/bucket-sort-javascript.js: -------------------------------------------------------------------------------- 1 | function bucketSort(arr) { 2 | // Assuming arr only contains 0, 1 or 2 3 | const counts = [0, 0, 0]; 4 | 5 | // Count the quantity of each val in arr 6 | for (let i = 0; i < arr.length; i++) { 7 | counts[arr[i]] += 1; 8 | } 9 | 10 | // Fill each bucket in the original array 11 | let i = 0; 12 | for (let n = 0; n < counts.length; n++) { 13 | for (let j = 0; j < counts[n]; j++) { 14 | arr[i] = n; 15 | i++; 16 | } 17 | } 18 | return arr; 19 | } -------------------------------------------------------------------------------- /Sorting/Bucket Sort/bucket-sort-python.py: -------------------------------------------------------------------------------- 1 | def bucketSort(arr): 2 | # Assuming arr only contains 0, 1 or 2 3 | counts = [0, 0, 0] 4 | 5 | # Count the quantity of each val in arr 6 | for n in arr: 7 | counts[n] += 1 8 | 9 | # Fill each bucket in the original array 10 | i = 0 11 | for n in range(len(counts)): 12 | for j in range(counts[n]): 13 | arr[i] = n 14 | i += 1 15 | return arr -------------------------------------------------------------------------------- /Sorting/Insertion Sort/insertion-sort-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::vector; 4 | 5 | vector insertionSort(vector& arr) { 6 | for (int i = 1; i < arr.size(); i++) { 7 | int j = i - 1; 8 | while (j >= 0 && arr[j + 1] < arr[j]) { 9 | int tmp = arr[j + 1]; 10 | arr[j + 1] = arr[j]; 11 | arr[j] = tmp; 12 | j--; 13 | } 14 | } 15 | return arr; 16 | } -------------------------------------------------------------------------------- /Sorting/Insertion Sort/insertion-sort-java.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class InsertionSort { 4 | public static int[] insertionSort(int[] arr) { 5 | for (int i = 1; i < arr.length; i++) { 6 | int j = i - 1; 7 | while (j >= 0 && arr[j+1] < arr[j]) { 8 | int tmp = arr[j + 1]; 9 | arr[j + 1] = arr[j]; 10 | arr[j] = tmp; 11 | j--; 12 | } 13 | } 14 | return arr; 15 | } 16 | } -------------------------------------------------------------------------------- /Sorting/Insertion Sort/insertion-sort-javascript.js: -------------------------------------------------------------------------------- 1 | function insertionSort(arr) { 2 | for (let i = 1; i < arr.length; i++) { 3 | let j = i - 1; 4 | while (j >= 0 && arr[j+1] < arr[j]) { 5 | let tmp = arr[j + 1]; 6 | arr[j + 1] = arr[j]; 7 | arr[j] = tmp; 8 | j--; 9 | } 10 | } 11 | return arr; 12 | } 13 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/insertion-sort-python.py: -------------------------------------------------------------------------------- 1 | # Python implementation of Insertion Sort 2 | def insertionSort(arr): 3 | # Traverse through 1 to len(arr) 4 | for i in range(1, len(arr)): 5 | j = i - 1 6 | while j >= 0 and arr[j + 1] < arr[j]: 7 | # arr[j] and arr[j + 1] are out of order so swap them 8 | tmp = arr[j + 1] 9 | arr[j + 1] = arr[j] 10 | arr[j] = tmp 11 | j -= 1 12 | return arr -------------------------------------------------------------------------------- /Sorting/Merge Sort/merge-sort-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::vector; 4 | 5 | void merge(vector& arr, int s, int m, int e) { 6 | // Copy the sorted left & right halfs to temp arrays 7 | vector L = {arr.begin() + s, arr.begin() + m + 1}; 8 | vector R = {arr.begin() + m + 1, arr.begin() + e + 1}; 9 | 10 | int i = 0; // index for L 11 | int j = 0; // index for R 12 | int k = s; // index for arr 13 | 14 | while (i < L.size() && j < R.size()) { 15 | if (L[i] <= R[j]) { 16 | arr[k] = L[i++]; 17 | } else { 18 | arr[k] = R[j++]; 19 | } 20 | k++; 21 | } 22 | 23 | // One of the halfs will have elements remaining 24 | while (i < L.size()) { 25 | arr[k++] = L[i++]; 26 | } 27 | while (j < R.size()) { 28 | arr[k++] = R[j++]; 29 | } 30 | } 31 | 32 | vector mergeSort(vector& arr, int s, int e) { 33 | if (e - s + 1 <= 1) { 34 | return arr; 35 | } 36 | // The middle index of the array 37 | int m = (s + e) / 2; 38 | 39 | // Sort the left half 40 | mergeSort(arr, s, m); 41 | 42 | // Sort the right half 43 | mergeSort(arr, m + 1, e); 44 | 45 | // Merge sorted halfs 46 | merge(arr, s, m, e); 47 | 48 | return arr; 49 | } -------------------------------------------------------------------------------- /Sorting/Merge Sort/merge-sort-java.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class MergeSort { 4 | 5 | public static int[] mergeSort(int[] arr, int l, int r) { // array, starting index of array, last index of array 6 | if (l < r) { 7 | 8 | // Find the middle point of arr 9 | int m = (l + r) / 2; 10 | 11 | mergeSort(arr, l, m); // sort left half 12 | mergeSort(arr, m+1, r); // sort right half 13 | merge(arr, l, m, r); // merge sorted halfs 14 | } 15 | return arr; 16 | } 17 | 18 | // Merges two subarrays of arr[]. 19 | // First subarray is arr[l..m] 20 | // Second subarray is arr[m+1..r] 21 | public static void merge(int[] arr, int l, int m, int r) { 22 | 23 | // Find lengths of two subarrays to be merged 24 | int length1 = m - l + 1; 25 | int length2 = r - m; 26 | 27 | // Create temp arrays 28 | int L[] = new int[length1]; 29 | int R[] = new int[length2]; 30 | 31 | // Copy the sorted left & right halfs to temp arrays 32 | for (int i = 0; i < length1; i++) { 33 | L[i] = arr[l + i]; 34 | } 35 | 36 | for (int j = 0; j < length2; j++) { 37 | R[j] = arr[m + 1 + j]; 38 | } 39 | 40 | // initial indexes of left and right sub-arrays 41 | int i = 0; // index for left 42 | int j = 0; // index for right 43 | int k = l; // Initial index of merged subarray array 44 | 45 | // Merge the two sorted halfs into the original array 46 | while(i < length1 && j < length2) { 47 | if (L[i] <= R[j]) { 48 | arr[k] = L[i]; 49 | i++; 50 | } else { 51 | arr[k] = R[j]; 52 | j++; 53 | } 54 | k++; 55 | } 56 | // One of the halfs will have elements remaining 57 | 58 | // Copy remaining elements of L[] if any 59 | while (i < length1) { 60 | arr[k] = L[i]; 61 | i++; 62 | k++; 63 | } 64 | 65 | // Copy remaining elements of R[] if any 66 | while (j < length2) { 67 | arr[k] = R[j]; 68 | j++; 69 | k++; 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /Sorting/Merge Sort/merge-sort-javascript.js: -------------------------------------------------------------------------------- 1 | function mergeSort(arr, l, r) { 2 | if (l < r) { 3 | // Find the middle point of arr 4 | let m = Math.floor((l + r) / 2); 5 | 6 | mergeSort(arr, l, m); // sort left half 7 | mergeSort(arr, m+1, r); // sort right half 8 | merge(arr, l, m, r); // merge sorted halfs 9 | } 10 | return arr; 11 | } 12 | 13 | // Merges two subarrays of arr[]. 14 | // First subarray is arr[l..m] 15 | // Second subarray is arr[m+1..r] 16 | function merge(arr, l, m, r) { 17 | 18 | // Find lengths of two subarrays to be merged 19 | let length1 = m - l + 1; 20 | let length2 = r - m; 21 | 22 | // Create temp arrays 23 | let L = new Array(length1); 24 | let R = new Array(length2); 25 | 26 | // Copy the sorted left & right halfs to temp arrays 27 | for (let i = 0; i < length1; i++) { 28 | L[i] = arr[l + i]; 29 | } 30 | 31 | for (let j = 0; j < length2; j++) { 32 | R[j] = arr[m + 1 + j]; 33 | } 34 | 35 | // initial indexes of left and right sub-arrays 36 | let i = 0; // index for left 37 | let j = 0; // index for right 38 | let k = l; // Initial index of merged subarray array 39 | 40 | // Merge the two sorted halfs leto the original array 41 | while (i < length1 && j < length2) { 42 | if (L[i] <= R[j]) { 43 | arr[k] = L[i]; 44 | i++; 45 | } else { 46 | arr[k] = R[j]; 47 | j++; 48 | } 49 | k++; 50 | } 51 | // One of the halfs will have elements remaining 52 | while (i < length1) { 53 | arr[k] = L[i]; 54 | i++; 55 | k++; 56 | } 57 | while (j < length2) { 58 | arr[k] = R[j]; 59 | j++; 60 | k++; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/merge-sort-python.py: -------------------------------------------------------------------------------- 1 | # Implementation of MergeSort 2 | def mergeSort(arr, s, e): 3 | if e - s + 1 <= 1: 4 | return arr 5 | 6 | # The middle index of the array 7 | m = (s + e) // 2 8 | 9 | # Sort the left half 10 | mergeSort(arr, s, m) 11 | 12 | # Sort the right half 13 | mergeSort(arr, m + 1, e) 14 | 15 | # Merge sorted halfs 16 | merge(arr, s, m, e) 17 | 18 | return arr 19 | 20 | # Merge in-place 21 | def merge(arr, s, m, e): 22 | # Copy the sorted left & right halfs to temp arrays 23 | L = arr[s: m + 1] 24 | R = arr[m + 1: e + 1] 25 | 26 | i = 0 # index for L 27 | j = 0 # index for R 28 | k = s # index for arr 29 | 30 | # Merge the two sorted halfs into the original array 31 | while i < len(L) and j < len(R): 32 | if L[i] <= R[j]: 33 | arr[k] = L[i] 34 | i += 1 35 | else: 36 | arr[k] = R[j] 37 | j += 1 38 | k += 1 39 | 40 | # One of the halfs will have elements remaining 41 | while i < len(L): 42 | arr[k] = L[i] 43 | i += 1 44 | k += 1 45 | while j < len(R): 46 | arr[k] = R[j] 47 | j += 1 48 | k += 1 -------------------------------------------------------------------------------- /Sorting/Quick Sort/quick-sort-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::vector; 4 | 5 | vector quickSort(vector& arr, int s, int e) { 6 | if (e - s + 1 <= 1) { 7 | return arr; 8 | } 9 | 10 | int pivot = arr[e]; 11 | int left = s; // pointer for left side 12 | 13 | // Partition: elements smaller than pivot on the left side. 14 | for (int i = s; i < e; i++) { 15 | if (arr[i] < pivot) { 16 | int tmp = arr[left]; 17 | arr[left] = arr[i]; 18 | arr[i] = tmp; 19 | left++; 20 | } 21 | } 22 | // Move pivot in-between left & right sides 23 | arr[e] = arr[left]; 24 | arr[left] = pivot; 25 | 26 | // Quick sort left side 27 | quickSort(arr, s, left - 1); 28 | 29 | // Quick sort right side 30 | quickSort(arr, left + 1, e); 31 | 32 | return arr; 33 | } 34 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/quick-sort-java.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class QuickSort { 4 | public static int[] quickSort(int[] arr, int s, int e) { 5 | if (e - s + 1 <= 1) { 6 | return arr; 7 | } 8 | 9 | int pivot = arr[e]; 10 | int left = s; // pointer for left side 11 | 12 | // Partition: elements smaller than pivot on left side 13 | for (int i = s; i < e; i++) { 14 | if (arr[i] < pivot) { 15 | int tmp = arr[left]; 16 | arr[left] = arr[i]; 17 | arr[i] = tmp; 18 | left++; 19 | } 20 | } 21 | 22 | // Move pivot in-between left & right sides 23 | arr[e] = arr[left]; 24 | arr[left] = pivot; 25 | 26 | // Quick sort left side 27 | quickSort(arr, s, left - 1); 28 | 29 | // Quick sort right side 30 | quickSort(arr, left + 1, e); 31 | 32 | return arr; 33 | } 34 | } -------------------------------------------------------------------------------- /Sorting/Quick Sort/quick-sort-javascript.js: -------------------------------------------------------------------------------- 1 | function quickSort(arr, s, e) { 2 | if (e - s + 1 <= 1) { 3 | return arr; 4 | } 5 | 6 | let pivot = arr[e]; 7 | let left = s; // pointer for left side 8 | 9 | // Partition: elements smaller than pivot on left side 10 | for (let i = s; i < e; i++) { 11 | if (arr[i] < pivot) { 12 | let tmp = arr[left]; 13 | arr[left] = arr[i]; 14 | arr[i] = tmp; 15 | left++; 16 | } 17 | } 18 | 19 | // Move pivot in-between left & right sides 20 | arr[e] = arr[left]; 21 | arr[left] = pivot; 22 | 23 | // Quick sort left side 24 | quickSort(arr, s, left - 1); 25 | 26 | // Quick sort right side 27 | quickSort(arr, left + 1, e); 28 | 29 | return arr; 30 | } 31 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/quick-sort-python.py: -------------------------------------------------------------------------------- 1 | # Implementation of QuickSort 2 | def quickSort(arr, s, e): 3 | if e - s + 1 <= 1: 4 | return 5 | 6 | pivot = arr[e] 7 | left = s # pointer for left side 8 | 9 | # Partition: elements smaller than pivot on left side 10 | for i in range(s, e): 11 | if arr[i] < pivot: 12 | tmp = arr[left] 13 | arr[left] = arr[i] 14 | arr[i] = tmp 15 | left += 1 16 | 17 | # Move pivot in-between left & right sides 18 | arr[e] = arr[left] 19 | arr[left] = pivot 20 | 21 | # Quick sort left side 22 | quickSort(arr, s, left - 1) 23 | 24 | # Quick sort right side 25 | quickSort(arr, left + 1, e) 26 | 27 | return arr 28 | 29 | -------------------------------------------------------------------------------- /Trees/BST Insert and Remove/bst-insert-and-remove-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::queue; 7 | 8 | class TreeNode { 9 | public: 10 | int val_; 11 | TreeNode* left = nullptr; 12 | TreeNode* right = nullptr; 13 | 14 | TreeNode(int val) { 15 | val_ = val; 16 | } 17 | }; 18 | 19 | // Insert a new node and return the root of the tree. 20 | TreeNode* insert(TreeNode* root, int val) { 21 | if (!root) { 22 | return new TreeNode(val); 23 | } 24 | 25 | if (val > root->val_) { 26 | root->right = insert(root->right, val); 27 | } else if (val < root->val_) { 28 | root->left = insert(root->left, val); 29 | } 30 | return root; 31 | } 32 | 33 | // Return the minimum value node of the BST. 34 | TreeNode* minValueNode(TreeNode* root) { 35 | TreeNode* curr = root; 36 | while (curr && curr->left) { 37 | curr = curr->left; 38 | } 39 | return curr; 40 | } 41 | 42 | // Remove a node and return the root of the tree. 43 | TreeNode* remove(TreeNode* root, int val) { 44 | if (!root) { 45 | return new TreeNode(val); 46 | } 47 | 48 | if (val > root->val_) { 49 | root->right = remove(root->right, val); 50 | } else if (val < root->val_) { 51 | root->left = remove(root->left, val); 52 | } else { 53 | if (!root->left) { 54 | return root->right; 55 | } else if (!root->right) { 56 | return root->left; 57 | } else { 58 | TreeNode* minNode = minValueNode(root->right); 59 | root->val_ = minNode->val_; 60 | root->right = remove(root->right, minNode->val_); 61 | } 62 | } 63 | return root; 64 | } 65 | -------------------------------------------------------------------------------- /Trees/BST Insert and Remove/bst-insert-and-remove-java.java: -------------------------------------------------------------------------------- 1 | // Definiton of TreeNode in Java 2 | /* 3 | public class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | 8 | public TreeNode(int val) { 9 | this.val = val; 10 | left = null; 11 | right = null; 12 | } 13 | } 14 | */ 15 | 16 | public class InsertAndRemove { 17 | 18 | // Insert a new node and return the root of the BST. 19 | public TreeNode insert(TreeNode root, int val) { 20 | if (root == null) { 21 | return new TreeNode(val); 22 | } 23 | 24 | if (val > root.val) { 25 | root.right = insert(root.right, val); 26 | } else if (val < root.val) { 27 | root.left = insert(root.left, val); 28 | } 29 | return root; 30 | } 31 | 32 | // Return the minimum value node of the BST. 33 | public TreeNode minValueNode(TreeNode root) { 34 | TreeNode curr = root; 35 | while(curr != null && curr.left != null) { 36 | curr = curr.left; 37 | } 38 | return curr; 39 | } 40 | 41 | // Remove a node and return the root of the BST. 42 | public TreeNode remove(TreeNode root, int val) { 43 | if (root == null) { 44 | return null; 45 | } 46 | if (val > root.val) { 47 | root.right = remove(root.right, val); 48 | } else if (val < root.val) { 49 | root.left = remove(root.left, val) ; 50 | } else { 51 | if (root.left == null) { 52 | return root.right; 53 | } else if (root.right == null) { 54 | return root.left; 55 | } else { 56 | TreeNode minNode = minValueNode(root.right); 57 | root.val = minNode.val;; 58 | root.right = remove(root.right, minNode.val); 59 | } 60 | } 61 | return root; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Trees/BST Insert and Remove/bst-insert-and-remove-javascript.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | // Insert a new node and return the root of the BST. 10 | function insert(root, val) { 11 | if (root == null) { 12 | return new TreeNode(val); 13 | } 14 | 15 | if (val > root.val) { 16 | root.right = insert(root.right, val); 17 | } else if (val < root.val) { 18 | root.left = insert(root.left, val); 19 | } 20 | return root; 21 | } 22 | 23 | // Return the minimum value node of the BST. 24 | function minValueNode(root) { 25 | let curr = root; 26 | while(curr != null && curr.left != null) { 27 | curr = curr.left; 28 | } 29 | return curr; 30 | } 31 | 32 | // Remove a node and return the root of the BST. 33 | function remove(root, val) { 34 | if (root == null) { 35 | return null; 36 | } 37 | if (val > root.val) { 38 | root.right = remove(root.right, val); 39 | } else if (val < root.val) { 40 | root.left = remove(root.left, val) ; 41 | } else { 42 | if (root.left == null) { 43 | return root.right; 44 | } else if (root.right == null) { 45 | return root.left; 46 | } else { 47 | let minNode = minValueNode(root.right); 48 | root.val = minNode.val;; 49 | root.right = remove(root.right, minNode.val); 50 | } 51 | } 52 | return root; 53 | } -------------------------------------------------------------------------------- /Trees/BST Insert and Remove/bst-insert-and-remove-python.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.left = None 5 | self.right = None 6 | 7 | # Insert a new node and return the root of the BST. 8 | def insert(root, val): 9 | if not root: 10 | return TreeNode(val) 11 | 12 | if val > root.val: 13 | root.right = insert(root.right, val) 14 | elif val < root.val: 15 | root.left = insert(root.left, val) 16 | return root 17 | 18 | # Return the minimum value node of the BST. 19 | def minValueNode(root): 20 | curr = root 21 | while curr and curr.left: 22 | curr = curr.left 23 | return curr 24 | 25 | # Remove a node and return the root of the BST. 26 | def remove(root, val): 27 | if not root: 28 | return None 29 | 30 | if val > root.val: 31 | root.right = remove(root.right, val) 32 | elif val < root.val: 33 | root.left = remove(root.left, val) 34 | else: 35 | if not root.left: 36 | return root.right 37 | elif not root.right: 38 | return root.left 39 | else: 40 | minNode = minValueNode(root.right) 41 | root.val = minNode.val 42 | root.right = remove(root.right, minNode.val) 43 | return root -------------------------------------------------------------------------------- /Trees/Binary Search Trees/binary-search-trees-cpp.cpp: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | public: 3 | int val_; 4 | TreeNode* left = nullptr; 5 | TreeNode* right = nullptr; 6 | 7 | TreeNode(int val) { 8 | val_ = val; 9 | } 10 | }; 11 | 12 | bool search(TreeNode* root, int target) { 13 | if (!root) { 14 | return false; 15 | } 16 | 17 | if (target > root->val_) { 18 | return search(root->right, target); 19 | } else if (target < root->val_) { 20 | return search(root->left, target); 21 | } else { 22 | return true; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Trees/Binary Search Trees/binary-search-trees-java.java: -------------------------------------------------------------------------------- 1 | // Definiton of TreeNode in Java 2 | /* 3 | public class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | 8 | public TreeNode(int val) { 9 | this.val = val; 10 | left = null; 11 | right = null; 12 | } 13 | } 14 | */ 15 | 16 | public class Search { 17 | 18 | public boolean search(TreeNode root, int target) { 19 | if (root == null) { 20 | return false; 21 | } 22 | 23 | if (target > root.val) { 24 | return search(root.right, target); 25 | } else if (target < root.val) { 26 | return search(root.left, target); 27 | } else { 28 | return true; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Trees/Binary Search Trees/binary-search-trees-javascript.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | function search(root, target) { 10 | if (root == null) { 11 | return false; 12 | } 13 | 14 | if (target > root.val) { 15 | return search(root.right, target); 16 | } else if (target < root.val) { 17 | return search(root.left, target); 18 | } else { 19 | return true; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Trees/Binary Search Trees/binary-search-trees-python.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.left = None 5 | self.right = None 6 | 7 | def search(root, target): 8 | if not root: 9 | return False 10 | 11 | if target > root.val: 12 | return search(root.right, target) 13 | elif target < root.val: 14 | return search(root.left, target) 15 | else: 16 | return True -------------------------------------------------------------------------------- /Trees/Breadth First Search/breadth-first-search-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using std::cout; 5 | using std::endl; 6 | using std::queue; 7 | 8 | class TreeNode { 9 | public: 10 | int val_; 11 | TreeNode* left = nullptr; 12 | TreeNode* right = nullptr; 13 | 14 | TreeNode(int val) { 15 | val_ = val; 16 | } 17 | }; 18 | 19 | void bfs(TreeNode* root) { 20 | queue queue; 21 | 22 | if (root) { 23 | queue.push(root); 24 | } 25 | 26 | int level = 0; 27 | while (queue.size() > 0) { 28 | cout << "level: " << level << endl; 29 | int length = queue.size(); 30 | for (int i = 0; i < length; i++) { 31 | TreeNode* curr = queue.front(); 32 | queue.pop(); 33 | cout << curr->val_ << ' '; 34 | if (curr->left) { 35 | queue.push(curr->left); 36 | } 37 | if (curr->right) { 38 | queue.push(curr->right); 39 | } 40 | } 41 | level++; 42 | cout << endl; 43 | } 44 | } -------------------------------------------------------------------------------- /Trees/Breadth First Search/breadth-first-search-java.java: -------------------------------------------------------------------------------- 1 | // Definiton of TreeNode in Java 2 | /* 3 | public class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | 8 | public TreeNode(int val) { 9 | this.val = val; 10 | left = null; 11 | right = null; 12 | } 13 | } 14 | */ 15 | 16 | import java.util.ArrayDeque; 17 | import java.util.Deque; 18 | 19 | public class BFS { 20 | 21 | public void bfs(TreeNode root) { 22 | Deque queue = new ArrayDeque(); 23 | if (root != null) { 24 | queue.add(root); 25 | } 26 | int level = 0; 27 | while(!queue.isEmpty()) { 28 | System.out.print("level " + level + ": "); 29 | int levelLength = queue.size(); 30 | for (int i = 0; i < levelLength; i++) { 31 | TreeNode curr = queue.removeFirst(); 32 | System.out.print(curr.val + " "); 33 | if(curr.left != null) { 34 | queue.add(curr.left); 35 | } 36 | if(curr.right != null) { 37 | queue.add(curr.right); 38 | } 39 | } 40 | level++; 41 | System.out.println(); 42 | } 43 | 44 | } 45 | } -------------------------------------------------------------------------------- /Trees/Breadth First Search/breadth-first-search-javascript.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | function bfs(root) { 10 | let queue = []; 11 | if (root != null) { 12 | queue.push(root); 13 | } 14 | let level = 0; 15 | while(queue.length > 0) { 16 | console.log("level " + level + ": "); 17 | let levelLength = queue.length; 18 | for (let i = 0; i < levelLength; i++) { 19 | let curr = queue.shift(); 20 | console.log(curr.val + " "); 21 | if(curr.left != null) { 22 | queue.push(curr.left); 23 | } 24 | if(curr.right != null) { 25 | queue.push(curr.right); 26 | } 27 | } 28 | level++; 29 | console.log(); 30 | } 31 | } -------------------------------------------------------------------------------- /Trees/Breadth First Search/breadth-first-search-python.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class TreeNode: 4 | def __init__(self, val): 5 | self.val = val 6 | self.left = None 7 | self.right = None 8 | 9 | def bfs(root): 10 | queue = deque() 11 | 12 | if root: 13 | queue.append(root) 14 | 15 | level = 0 16 | while len(queue) > 0: 17 | print("level: ", level) 18 | for i in range(len(queue)): 19 | curr = queue.popleft() 20 | print(curr.val) 21 | if curr.left: 22 | queue.append(curr.left) 23 | if curr.right: 24 | queue.append(curr.right) 25 | level += 1 -------------------------------------------------------------------------------- /Trees/Depth First Search/depth-first-search-cpp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using std::cout; 4 | using std::endl; 5 | 6 | class TreeNode { 7 | public: 8 | int val_; 9 | TreeNode* left = nullptr; 10 | TreeNode* right = nullptr; 11 | 12 | TreeNode(int val) { 13 | val_ = val; 14 | } 15 | }; 16 | 17 | void inorder(TreeNode* root) { 18 | if (!root) { 19 | return; 20 | } 21 | inorder(root->left); 22 | cout << root->val_ << endl; 23 | inorder(root->right); 24 | } 25 | 26 | void preorder(TreeNode* root) { 27 | if (!root) { 28 | return; 29 | } 30 | cout << root->val_ << endl; 31 | preorder(root->left); 32 | preorder(root->right); 33 | } 34 | 35 | void postorder(TreeNode* root) { 36 | if (!root) { 37 | return; 38 | } 39 | postorder(root->left); 40 | postorder(root->right); 41 | cout << root->val_ << endl; 42 | } -------------------------------------------------------------------------------- /Trees/Depth First Search/depth-first-search-java.java: -------------------------------------------------------------------------------- 1 | // Definiton of TreeNode in Java 2 | /* 3 | public class TreeNode { 4 | int val; 5 | TreeNode left; 6 | TreeNode right; 7 | 8 | public TreeNode(int val) { 9 | this.val = val; 10 | left = null; 11 | right = null; 12 | } 13 | } 14 | */ 15 | 16 | public class DFS { 17 | 18 | public void inorder(TreeNode root) { 19 | if (root == null) { 20 | return; 21 | } 22 | inorder(root.left); 23 | System.out.println(root.val); 24 | inorder(root.right); 25 | } 26 | 27 | public void preorder(TreeNode root) { 28 | if (root == null) { 29 | return; 30 | } 31 | System.out.println(root.val); 32 | preorder(root.left); 33 | preorder(root.right); 34 | } 35 | 36 | public void postorder(TreeNode root) { 37 | if (root == null) { 38 | return; 39 | } 40 | postorder(root.left); 41 | postorder(root.right); 42 | System.out.println(root.val); 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /Trees/Depth First Search/depth-first-search-javascript.js: -------------------------------------------------------------------------------- 1 | class TreeNode { 2 | constructor(val) { 3 | this.val = val; 4 | this.left = null; 5 | this.right = null; 6 | } 7 | } 8 | 9 | function inorder(root) { 10 | if (root == null) { 11 | return; 12 | } 13 | inorder(root.left); 14 | console.log(root.val); 15 | inorder(root.right); 16 | } 17 | 18 | function preorder(root) { 19 | if (root == null) { 20 | return; 21 | } 22 | console.log(root.val); 23 | preorder(root.left); 24 | preorder(root.right); 25 | } 26 | 27 | function postorder(root) { 28 | if (root == null) { 29 | return; 30 | } 31 | postorder(root.left); 32 | postorder(root.right); 33 | console.log(root.val); 34 | } -------------------------------------------------------------------------------- /Trees/Depth First Search/depth-first-search-python.py: -------------------------------------------------------------------------------- 1 | class TreeNode: 2 | def __init__(self, val): 3 | self.val = val 4 | self.left = None 5 | self.right = None 6 | 7 | def inorder(root): 8 | if not root: 9 | return 10 | inorder(root.left) 11 | print(root.val) 12 | inorder(root.right) 13 | 14 | def preorder(root): 15 | if not root: 16 | return 17 | print(root.val) 18 | preorder(root.left) 19 | preorder(root.right) 20 | 21 | def postorder(root): 22 | if not root: 23 | return 24 | postorder(root.left) 25 | postorder(root.right) 26 | print(root.val) 27 | --------------------------------------------------------------------------------