├── .DS_Store ├── .vscode ├── c_cpp_properties.json ├── launch.json ├── settings.json └── tasks.json ├── C++ ├── .DS_Store ├── BFS │ ├── LevelOrderSuccessor.cpp │ ├── LevelOrderTraversal.cpp │ ├── MinimumDepth.cpp │ ├── RightView.cpp │ └── ZigZagTraversal.cpp ├── BinaryTree │ ├── BinaryTreeTraversal.cpp │ ├── ConstructingBinaryTree.cpp │ ├── InorderTraversal.cpp │ ├── NumberOfFullNodes.cpp │ ├── NumberOfLeafNodes.cpp │ ├── NumberOfNodesInBinaryTree.cpp │ ├── NumberOfNonLeafNodes.cpp │ └── PostorderTraversal.cpp ├── DFS │ ├── BinaryTreePathSum.cpp │ ├── BurningTree.cpp │ ├── CP01_BinaryTree.cpp │ ├── LowestCommonAncestorBT.cpp │ ├── MergeTwoTrees.cpp │ ├── PathWithGivenSequence.cpp │ ├── PathWithMaximumSum.cpp │ ├── Subordinates.cpp │ ├── SumOfPathNumbers.cpp │ ├── SymmetricTree.cpp │ └── TreeDiameter.cpp ├── DynamicProgramming │ └── BudgetHiring.cpp ├── Graph │ ├── .DS_Store │ ├── BreadthFirstSearch.cpp │ ├── DepthFirstSearch.cpp │ ├── Graph-Representation-Adjacency-List-2.cpp │ ├── Graph-Representation-Adjacency-List.cpp │ └── ShortestReachHackerRank.cpp ├── Heap │ ├── KClosestPointToOrigin.cpp │ ├── KthLargestElement.cpp │ ├── KthSmallestElement.cpp │ ├── Largest_K_Elements.cpp │ ├── MaxHeap.cpp │ ├── ReorganizeString.cpp │ ├── Smallest_K_Elements.cpp │ ├── SortCharactersByFrequency.cpp │ └── TopKFrequentElements.cpp ├── LinkedList │ ├── LinkedListDeletion.cpp │ ├── LinkedListInsertion.cpp │ ├── LinkedListNthFromEnd.cpp │ ├── LoopDetection.cpp │ ├── MiddleOfLinkedList.cpp │ └── StartingOfLoop.cpp ├── MergeIntervals │ ├── InsertInterval.cpp │ └── IntervalsIntersection.cpp ├── Queue │ ├── QueueUsingArray.cpp │ └── QueueUsingLinkedList.cpp ├── Recursion │ ├── Fibonacci.cpp │ └── Handshake.cpp ├── Stack │ ├── BalancedParenthesis.cpp │ ├── MaximumAreaHistogram.cpp │ ├── NGEL.cpp │ ├── NGER.cpp │ ├── NSEL.cpp │ ├── NSER.cpp │ ├── StackArray.cpp │ ├── StackLinkedList.cpp │ ├── StockSpan.cpp │ └── StockSpan2.cpp ├── TopologicalSort │ └── TopologicalSort.cpp └── TreeConstructions │ └── TreeFromInorderPostorder.cpp ├── Java ├── .DS_Store ├── BFS │ ├── LevelOrderSuccessor.java │ ├── LevelOrderTraversal.java │ ├── MinimumDepth.java │ ├── RightView.java │ └── ZigZagTraversal.java ├── BinaryTree │ ├── BinaryTreeTraversal.java │ ├── ConstructingBinaryTree.java │ ├── InorderTraversal.java │ ├── NumberOfFullNodes.java │ ├── NumberOfLeafNodes.java │ ├── NumberOfNodesInBinaryTree.java │ ├── NumberOfNonLeafNodes.java │ └── PostorderTraversal.java ├── DFS │ ├── BinaryTreePathSum.java │ ├── BurningTree.java │ ├── CP01_BinaryTree.java │ ├── LowestCommonAncestorBT.java │ ├── MergeTwoTrees.java │ ├── PathWithGivenSequence.java │ ├── PathWithMaximumSum.java │ ├── SumOfPathNumbers.java │ ├── SymmetricTree.java │ └── TreeDiameter.java ├── DisjointSetUnion │ ├── DSU.java │ ├── DSU2.java │ ├── DSU_PathCompression.java │ └── DSU_Rank.java ├── DynamicProgramming │ ├── CountSubset.java │ ├── KnapsackMemoized.java │ ├── KnapsackTabulation.java │ ├── LongestCommonSubsequence.java │ ├── LongestCommonSubstring.java │ └── SubsetSumTabulation.java ├── Graph │ ├── .DS_Store │ ├── ArticulationPoint.java │ ├── BreadthFirstSearch.java │ ├── CycleDetectionUndirectedGraph.java │ ├── DepthFirstSearch.java │ ├── DijkstrasAlgorithm.class │ ├── DijkstrasAlgorithm.java │ ├── Graph-Representation-Adjacency-List-2.java │ ├── Graph-Representation-Adjacency-List.java │ ├── Pair.class │ ├── PrimsAlgorithm.class │ ├── PrimsAlgorithm.java │ └── ShortestReachHackerRank.java ├── Heap │ ├── KClosestPointToOrigin.java │ ├── KthLargestElement.java │ ├── KthSmallestElement.java │ ├── Largest_K_Elements.java │ ├── MaxHeap.java │ ├── ReorganizeString.java │ ├── Smallest_K_Elements.java │ └── SortCharactersByFrequency.java ├── LinkedList │ ├── LinkedListDeletion.java │ ├── LinkedListInsertion.java │ ├── LinkedListNthFromEnd.java │ ├── LoopDetection.java │ ├── MiddleOfLinkedList.java │ └── StartingOfLoop.java ├── MergeIntervals │ ├── InsertInterval.java │ └── IntervalsIntersection.java ├── Queue │ ├── QueueUsingArray.java │ └── QueueUsingLinkedList.java ├── Recursion │ ├── CountSubset.java │ ├── Fibonacci.class │ ├── Fibonacci.java │ ├── Handshake.java │ ├── Knapsack.java │ └── SubsetSum.java ├── SlidingWindow │ ├── MaxSubarraySum.java │ ├── MinimumLengthSubarrayWithGivenSum.java │ └── SubarrayAverage.java ├── Sorting │ ├── InversionCount.java │ └── MergeSort.java ├── Stack │ ├── BalancedParenthesis.java │ ├── MaximumAreaHistogram.java │ ├── NGEL.java │ ├── NGER.java │ ├── NSEL.java │ ├── NSER.java │ ├── StackArray.java │ ├── StackLinkedList.java │ ├── StockSpan.java │ └── StockSpan2.java ├── TopologicalSort │ ├── AlienDictionary.class │ ├── AlienDictionary.java │ └── TopologicalSort.java └── TreeConstructions │ └── TreeFromInorderPostorder.java ├── JavaScript └── code.js ├── Python ├── .DS_Store ├── BFS │ ├── LevelOrderSuccessor.py │ ├── LevelOrderTraversal.py │ ├── MinimumDepth.py │ ├── RightView.py │ └── ZigZagTraversal.py ├── BinarySearch │ └── Cabs.py ├── BinaryTree │ ├── BinarySearchTree_Search.py │ ├── BinaryTreeTraversal.py │ ├── ConstructingBinaryTree.py │ ├── InorderTraversal.py │ ├── NumberOfFullNodes.py │ ├── NumberOfLeafNodes.py │ ├── NumberOfNodesInBinaryTree.py │ ├── NumberOfNonLeafNodes.py │ └── PostorderTraversal.py ├── DFS │ ├── BinaryTreePathSum.py │ ├── BurningTree.py │ ├── CP01_BinaryTree.py │ ├── CountPathsForASum.py │ ├── LowestCommonAncestorBT.py │ ├── MergeTwoTrees.py │ ├── PathWithGivenSequence.py │ ├── PathWithMaximumSum.py │ ├── Subordinates.py │ ├── SumOfPathNumbers.py │ ├── SymmetricTree.py │ └── TreeDiameter.py ├── DynamicProgramming │ └── BudgetHiring.py ├── Graph │ ├── .DS_Store │ ├── AdjacencyList.py │ ├── BreadthFirstSearch.py │ ├── ConnectedCell_Hackerrank.py │ ├── CycleDetectionUsingBFS.py │ ├── CycleDetectionUsingDFS.py │ ├── DFS.py │ ├── DSU.py │ ├── DSUOptimized.py │ ├── DepthFirstSearch.py │ ├── Emas_Supercomputer.py │ ├── Graph-Representation-Adjacency-List-2.py │ ├── Graph-Representation-Adjacency-List.py │ ├── GraphAdjacencyList.py │ ├── JourneyToTheMoon.py │ ├── NumberOfIslands.py │ ├── Roads_And_Libraries.py │ ├── RottenOranges.py │ └── ShortestReachHackerRank.py ├── Heap │ ├── KClosestPointToOrigin.py │ ├── KthLargestElement.py │ ├── KthSmallestElement.py │ ├── Largest_K_Elements.py │ ├── MaxHeap.py │ ├── RearrangeString.py │ ├── RearrangeStringKDistanceApart.py │ ├── ReorganizeString.py │ ├── Smallest_K_Elements.py │ ├── SortCharactersByFrequency.py │ └── TopKFrequentElements.py ├── LinkedList │ ├── LinkedListDeletion.py │ ├── LinkedListInsertion.py │ ├── LinkedListNthFromEnd.py │ ├── LoopDetection.py │ ├── MiddleOfLinkedList.py │ └── StartingOfLoop.py ├── MergeIntervals │ ├── InsertInterval.py │ └── IntervalsIntersection.py ├── Queue │ ├── QueueUsingArray.py │ └── QueueUsingLinkedList.py ├── Recursion │ ├── Fiboanacci.py │ ├── Handshake.py │ └── LCS.py ├── Stack │ ├── BalancedParenthesis.py │ ├── MaximumAreaHistogram.py │ ├── NGEL.py │ ├── NGER.py │ ├── NSEL.py │ ├── NSER.py │ ├── StackArray.py │ ├── StackLinkedList.py │ ├── StockSpan.py │ └── StockSpan2.py ├── TopologicalSort │ ├── AlienDictionary.py │ └── TopologicalSort.py └── TreeConstructions │ └── TreeFromInorderPostorder.py ├── go └── LinkedList │ ├── linkedlist_deletion │ ├── delete_linked_list.go │ ├── go.mod │ └── main.go │ └── linkedlist_insertion │ ├── go.mod │ ├── insert_linked_list.go │ └── main.go └── javascript └── HelloWorld.js /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/.DS_Store -------------------------------------------------------------------------------- /.vscode/c_cpp_properties.json: -------------------------------------------------------------------------------- 1 | { 2 | "configurations": [ 3 | { 4 | "name": "Mac", 5 | "includePath": [ 6 | "${workspaceFolder}/**" 7 | ], 8 | "defines": [], 9 | "macFrameworkPath": [ 10 | "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks" 11 | ], 12 | "compilerPath": "/usr/bin/clang", 13 | "cStandard": "c17", 14 | "cppStandard": "c++98", 15 | "intelliSenseMode": "macos-clang-x64" 16 | } 17 | ], 18 | "version": 4 19 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [] 7 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "vector": "cpp", 4 | "iosfwd": "cpp", 5 | "iterator": "cpp", 6 | "ostream": "cpp" 7 | } 8 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": [ 3 | { 4 | "type": "cppbuild", 5 | "label": "C/C++: cpp build active file", 6 | "command": "/usr/bin/cpp", 7 | "args": [ 8 | "-fdiagnostics-color=always", 9 | "-g", 10 | "${file}", 11 | "-o", 12 | "${fileDirname}/${fileBasenameNoExtension}" 13 | ], 14 | "options": { 15 | "cwd": "${fileDirname}" 16 | }, 17 | "problemMatcher": [ 18 | "$gcc" 19 | ], 20 | "group": { 21 | "kind": "build", 22 | "isDefault": true 23 | }, 24 | "detail": "Task generated by Debugger." 25 | } 26 | ], 27 | "version": "2.0.0" 28 | } -------------------------------------------------------------------------------- /C++/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/C++/.DS_Store -------------------------------------------------------------------------------- /C++/BFS/LevelOrderSuccessor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 6 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | struct Node { 13 | int data; 14 | struct Node *left, *right; 15 | Node(int data) { 16 | this->data = data; 17 | left = right = NULL; 18 | } 19 | }; 20 | 21 | struct Node *root = NULL; 22 | 23 | Node* levelOrderSuccessor(struct Node *root, int key) { 24 | if(root == NULL) 25 | return NULL; 26 | queue queue; 27 | queue.push(root); 28 | while(!queue.empty()) { 29 | Node *current = queue.front(); 30 | queue.pop(); 31 | 32 | if(current->left != NULL) 33 | queue.push(current->left); 34 | if(current->right != NULL) 35 | queue.push(current->right); 36 | 37 | if(current->data == key) { 38 | break; 39 | } 40 | } 41 | return queue.front(); 42 | } 43 | 44 | int main(int argc, char const *argv[]) { 45 | root = new Node(1); 46 | root->left = new Node(2); 47 | root->right = new Node(3); 48 | root->left->left = new Node(4); 49 | root->right->left = new Node(6); 50 | root->right->right = new Node(7); 51 | root->right->right->left = new Node(8); 52 | Node *ans = levelOrderSuccessor(root, 4); 53 | cout << ans->data << endl; 54 | } 55 | -------------------------------------------------------------------------------- /C++/BFS/LevelOrderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 1 7 | * 2 3 8 | * 4 5 6 7 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | struct Node { 15 | int data; 16 | struct Node *left, *right; 17 | Node(int data) { 18 | this->data = data; 19 | left = right = NULL; 20 | } 21 | }; 22 | 23 | struct Node *root = NULL; 24 | 25 | vector> traverse(struct Node *root) { 26 | vector> bfs; 27 | if(root == NULL) 28 | return bfs; 29 | queue queue; 30 | queue.push(root); 31 | while(!queue.empty()) { 32 | int levelSize = queue.size(); 33 | vector currentLevel; 34 | for(int i = 0; i < levelSize; i++) { 35 | Node *current = queue.front(); 36 | queue.pop(); 37 | currentLevel.push_back(current->data); 38 | if(current->left != NULL) 39 | queue.push(current->left); 40 | if(current->right != NULL) 41 | queue.push(current->right); 42 | } 43 | bfs.push_back(currentLevel); 44 | } 45 | return bfs; 46 | } 47 | 48 | int main(int argc, char const *argv[]) { 49 | root = new Node(1); 50 | root->left = new Node(2); 51 | root->right = new Node(3); 52 | root->left->left = new Node(4); 53 | root->left->right = new Node(5); 54 | root->right->left = new Node(6); 55 | root->right->right = new Node(7); 56 | vector> ans = traverse(root); 57 | for(auto level : ans) { 58 | for(auto num : level) { 59 | cout << num << " "; 60 | } 61 | cout << endl; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /C++/BFS/MinimumDepth.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 3 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | struct Node { 13 | int data; 14 | struct Node *left, *right; 15 | Node(int data) { 16 | this->data = data; 17 | left = right = NULL; 18 | } 19 | }; 20 | 21 | struct Node *root = NULL; 22 | 23 | int findMinimumDepth(struct Node *root) { 24 | int minimumDepth = 0; 25 | bool leftToRight = true; 26 | if(root == NULL) 27 | return minimumDepth; 28 | queue queue; 29 | queue.push(root); 30 | while(!queue.empty()) { 31 | minimumDepth++; 32 | int levelSize = queue.size(); 33 | for(int i = 0; i < levelSize; i++) { 34 | Node *current = queue.front(); 35 | queue.pop(); 36 | 37 | if(current->left == NULL && current->right == NULL) { 38 | return minimumDepth; 39 | } 40 | 41 | if(current->left != NULL) 42 | queue.push(current->left); 43 | if(current->right != NULL) 44 | queue.push(current->right); 45 | } 46 | } 47 | return minimumDepth; 48 | } 49 | 50 | int main(int argc, char const *argv[]) { 51 | root = new Node(1); 52 | root->left = new Node(2); 53 | root->right = new Node(3); 54 | root->left->left = new Node(4); 55 | root->right->left = new Node(6); 56 | root->right->right = new Node(7); 57 | root->right->right->left = new Node(8); 58 | int ans = findMinimumDepth(root); 59 | cout << ans << endl; 60 | } 61 | -------------------------------------------------------------------------------- /C++/BFS/RightView.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 12 1 5 3 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | struct Node { 13 | int data; 14 | struct Node *left, *right; 15 | Node(int data) { 16 | this->data = data; 17 | left = right = NULL; 18 | } 19 | }; 20 | 21 | struct Node *root = NULL; 22 | 23 | vector rightView(struct Node *root) { 24 | vector result; 25 | if(root == NULL) 26 | return result; 27 | queue queue; 28 | queue.push(root); 29 | while(!queue.empty()) { 30 | int levelSize = queue.size(); 31 | for(int i = 0; i < levelSize; i++) { 32 | Node *current = queue.front(); 33 | queue.pop(); 34 | 35 | if(i == levelSize - 1) { 36 | result.push_back(current->data); 37 | } 38 | 39 | if(current->left != NULL) 40 | queue.push(current->left); 41 | if(current->right != NULL) 42 | queue.push(current->right); 43 | } 44 | } 45 | return result; 46 | } 47 | 48 | int main(int argc, char const *argv[]) { 49 | root = new Node(12); 50 | root->left = new Node(7); 51 | root->right = new Node(1); 52 | root->left->left = new Node(9); 53 | root->right->left = new Node(10); 54 | root->right->right = new Node(5); 55 | root->left->left->left = new Node(3); 56 | vector ans = rightView(root); 57 | for (auto node : ans) { 58 | cout << node << " "; 59 | } 60 | cout << endl; 61 | } 62 | -------------------------------------------------------------------------------- /C++/BinaryTree/ConstructingBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * @author 4 | * Aakash Verma 5 | * 6 | */ 7 | 8 | 9 | /* 10 | Creating a structure for the node. 11 | Initializing the node's data upon calling its constructor. 12 | */ 13 | 14 | #include 15 | using namespace std; 16 | 17 | struct Node { 18 | int data; 19 | struct Node *left, *right; 20 | Node(int data) { 21 | this->data = data; 22 | left = right = NULL; 23 | } 24 | }; 25 | 26 | 27 | /* Creating a root node for the Tree and setting it as null */ 28 | struct Node *root = NULL; 29 | 30 | /* main method */ 31 | int main(int argc, char const *argv[]) { 32 | root = new Node(1); 33 | root->left = new Node(2); 34 | root->right = new Node(3); 35 | root->left->left = new Node(4); 36 | root->left->right = new Node(5); 37 | root->right->left = new Node(6); 38 | root->right->right = new Node(7); 39 | } 40 | -------------------------------------------------------------------------------- /C++/BinaryTree/InorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @author 3 | * aakash.verma 4 | * 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | vector inorderTraversal(TreeNode* root) { 13 | vector inorder; 14 | stack stack; 15 | if(root == NULL) { 16 | return inorder; 17 | } 18 | 19 | TreeNode *curr = root; 20 | while(curr != NULL || stack.size() != 0) { 21 | while(curr != NULL) { 22 | stack.push(curr); 23 | curr = curr->left; 24 | } 25 | curr = stack.top(); 26 | stack.pop(); 27 | inorder.push_back(curr->val); 28 | curr = curr->right; 29 | } 30 | return inorder; 31 | } 32 | }; 33 | 34 | int main() { 35 | . 36 | . 37 | . 38 | } -------------------------------------------------------------------------------- /C++/BinaryTree/NumberOfLeafNodes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * @author 4 | * Aakash Verma 5 | * 6 | * Problem: Given a Binary Tree, count the total number of leaf nodes present in BT. 7 | * 8 | * Output: 9 | * Traversal is: 1 2 4 5 3 6 7 10 | * Number Of Leaf Nodes: 4 11 | * 12 | */ 13 | 14 | 15 | 16 | /* 17 | Creating a structure for the node. 18 | Initializing the node's data upon calling its constructor. 19 | */ 20 | 21 | #include 22 | using namespace std; 23 | 24 | struct Node { 25 | int data; 26 | struct Node *left, *right; 27 | Node(int data) { 28 | this->data = data; 29 | left = right = NULL; 30 | } 31 | }; 32 | 33 | 34 | /* Creating a root node for the Tree and setting it as null */ 35 | struct Node *root = NULL; 36 | 37 | /* Pre Order Traversal */ 38 | void preOrder(struct Node *root) { 39 | if(root == NULL) 40 | return; 41 | cout << root->data << " "; 42 | preOrder(root->left); 43 | preOrder(root->right); 44 | } 45 | 46 | 47 | /* Counting number Of Leaf Nodes */ 48 | int numLeafNodes(struct Node *root) { 49 | if(root == NULL) 50 | return 0; 51 | if(root->left == NULL && root->right == NULL) 52 | return 1; 53 | return numLeafNodes(root->left) + numLeafNodes(root->right); 54 | } 55 | 56 | /* main method */ 57 | int main(int argc, char const *argv[]) { 58 | root = new Node(1); 59 | root->left = new Node(2); 60 | root->right = new Node(3); 61 | root->left->left = new Node(4); 62 | root->left->right = new Node(5); 63 | root->right->left = new Node(6); 64 | root->right->right = new Node(7); 65 | cout << "Pre Order Traversal is: "; 66 | preOrder(root); 67 | cout << endl; 68 | cout << "Number Of Leaf Nodes: " << numLeafNodes(root); 69 | } 70 | -------------------------------------------------------------------------------- /C++/BinaryTree/NumberOfNodesInBinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * @author 4 | * Aakash Verma 5 | * 6 | * Problem: Given a Binary Tree, count the total number of nodes present in BT. 7 | * 8 | * Output: 9 | * Traversal is: 1 2 4 5 3 6 7 10 | * Number Of Nodes: 7 11 | */ 12 | 13 | 14 | /* 15 | Creating a structure for the node. 16 | Initializing the node's data upon calling its constructor. 17 | */ 18 | 19 | #include 20 | using namespace std; 21 | 22 | struct Node { 23 | int data; 24 | struct Node *left, *right; 25 | Node(int data) { 26 | this->data = data; 27 | left = right = NULL; 28 | } 29 | }; 30 | 31 | 32 | 33 | 34 | /* Creating a root node for the Tree and setting it as null */ 35 | struct Node *root = NULL; 36 | 37 | /* Pre Order Traversal */ 38 | void preOrder(struct Node *root) { 39 | if(root == NULL) { 40 | return; 41 | } 42 | cout << root->data << " "; 43 | preOrder(root->left); 44 | preOrder(root->right); 45 | } 46 | 47 | 48 | /* Counting number Of Nodes */ 49 | int numNodes(struct Node *root) { 50 | if(root == NULL) { 51 | return 0; 52 | } 53 | return 1 + numNodes(root->left) + numNodes(root->right); 54 | } 55 | 56 | /* main method */ 57 | int main(int argc, char const *argv[]) { 58 | root = new Node(1); 59 | root->left = new Node(2); 60 | root->right = new Node(3); 61 | root->left->left = new Node(4); 62 | root->left->right = new Node(5); 63 | root->right->left = new Node(6); 64 | root->right->right = new Node(7); 65 | cout << "Pre Order Traversal is: "; 66 | preOrder(root); 67 | cout << endl; 68 | cout << "Number Of Nodes: " << numNodes(root); 69 | } 70 | -------------------------------------------------------------------------------- /C++/BinaryTree/NumberOfNonLeafNodes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * @author 4 | * Aakash Verma 5 | * 6 | * Problem: Given a Binary Tree, count the total number of non-leaf nodes present in BT. 7 | * 8 | * Output: 9 | * Traversal is: 1 2 4 5 3 6 7 10 | * Number Of non-Leaf Nodes: 3 11 | * 12 | */ 13 | 14 | 15 | 16 | /* 17 | Creating a structure for the node. 18 | Initializing the node's data upon calling its constructor. 19 | */ 20 | 21 | #include 22 | using namespace std; 23 | 24 | struct Node { 25 | int data; 26 | struct Node *left, *right; 27 | Node(int data) { 28 | this->data = data; 29 | left = right = NULL; 30 | } 31 | }; 32 | 33 | 34 | 35 | 36 | /* Creating a root node for the Tree and setting it as null */ 37 | struct Node *root = NULL; 38 | 39 | /* Pre Order Traversal */ 40 | void preOrder(struct Node *root) { 41 | if(root == NULL) 42 | return; 43 | cout << root->data << " "; 44 | preOrder(root->left); 45 | preOrder(root->right); 46 | } 47 | 48 | 49 | /* Counting number Of non-Leaf Nodes */ 50 | int numNonLeafNodes(struct Node *root) { 51 | if(root == NULL) 52 | return 0; 53 | if(root->left == NULL && root->right == NULL) 54 | return 0; 55 | return 1 + numNonLeafNodes(root->left) + numNonLeafNodes(root->right); 56 | } 57 | 58 | /* main method */ 59 | int main(int argc, char const *argv[]) { 60 | root = new Node(1); 61 | root->left = new Node(2); 62 | root->right = new Node(3); 63 | root->left->left = new Node(4); 64 | root->left->right = new Node(5); 65 | root->right->left = new Node(6); 66 | root->right->right = new Node(7); 67 | cout << "Pre Order Traversal is: "; 68 | preOrder(root); 69 | cout << endl; 70 | cout << "Number Of non-Leaf Nodes: " << numNonLeafNodes(root); 71 | } 72 | -------------------------------------------------------------------------------- /C++/BinaryTree/PostorderTraversal.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * @author 3 | * aakash.verma 4 | * 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | class Solution { 11 | public: 12 | vector postorderTraversal(TreeNode* root) { 13 | vector postorder; 14 | stack stack1; 15 | stack stack2; 16 | if(root == NULL) return postorder; 17 | stack1.push(root); 18 | while(!stack1.empty()) { 19 | TreeNode *current = stack1.top(); 20 | stack1.pop(); 21 | stack2.push(current); 22 | if(current->left != NULL) stack1.push(current->left); 23 | if(current->right != NULL) stack1.push(current->right); 24 | } 25 | while(stack2.size() != 0) { 26 | postorder.push_back(stack2.top()->val); 27 | stack2.pop(); 28 | } 29 | return postorder; 30 | } 31 | }; 32 | 33 | int main() { 34 | . 35 | . 36 | . 37 | } -------------------------------------------------------------------------------- /C++/DFS/BinaryTreePathSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * true 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | struct Node { 13 | int data; 14 | struct Node *left, *right; 15 | Node(int data) { 16 | this->data = data; 17 | left = right = NULL; 18 | } 19 | }; 20 | 21 | struct Node *root = NULL; 22 | 23 | bool hasPath(struct Node *root, int sum) { 24 | if(root == NULL) return false; 25 | 26 | if(root->data == sum && root->left == NULL && root->right == NULL) { 27 | return true; 28 | } 29 | 30 | return hasPath(root->left, sum - root->data) || hasPath(root->right, sum - root->data); 31 | 32 | } 33 | 34 | int main(int argc, char const *argv[]) { 35 | root = new Node(12); 36 | root->left = new Node(7); 37 | root->right = new Node(1); 38 | root->left->left = new Node(9); 39 | root->right->left = new Node(10); 40 | root->right->right = new Node(5); 41 | root->left->left->left = new Node(3); 42 | bool ans = hasPath(root, 23); 43 | if(ans) 44 | cout << "true"; 45 | else 46 | cout << "false"; 47 | cout << endl; 48 | } 49 | -------------------------------------------------------------------------------- /C++/DFS/CP01_BinaryTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | 10 | vector bfs(int n, int source, map> tree) { 11 | vector distance(n + 1, 0); 12 | queue q; 13 | q.push(source); 14 | while(!q.empty()) { 15 | int current = q.front(); 16 | q.pop(); 17 | for(auto child : tree[current]) { 18 | distance[child] = distance[current] + 1; 19 | q.push(child); 20 | } 21 | } 22 | return distance; 23 | } 24 | 25 | int main(int argc, char const *argv[]) { 26 | 27 | int t; 28 | cin >> t; 29 | 30 | while(t--) { 31 | int n; 32 | cin >> n; 33 | map> tree; 34 | for(int i = 0; i < (n - 1); i++) { 35 | int a, b; 36 | cin >> a >> b; 37 | tree[a].push_back(b); 38 | } 39 | vector distance = bfs(n, 1, tree); 40 | 41 | for(int i = 1; i <= n; i++) { 42 | cout << distance[i] << " "; 43 | } 44 | cout << endl; 45 | } 46 | return 0; 47 | } -------------------------------------------------------------------------------- /C++/DFS/LowestCommonAncestorBT.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 5 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | struct Node { 13 | int data; 14 | struct Node *left, *right; 15 | Node(int data) { 16 | this->data = data; 17 | left = right = NULL; 18 | } 19 | }; 20 | 21 | struct Node *root = NULL; 22 | 23 | struct Node* lowestCommonAncestor(struct Node *root, struct Node *p, struct Node *q) { 24 | 25 | if(root == NULL) 26 | return NULL; 27 | 28 | if(root->data == p->data || root->data == q->data) 29 | return root; 30 | 31 | struct Node *left = lowestCommonAncestor(root->left, p, q); 32 | struct Node *right = lowestCommonAncestor(root->right, p, q); 33 | 34 | if(left != NULL && right != NULL) 35 | return root; 36 | 37 | return left != NULL ? left : right; 38 | 39 | } 40 | 41 | int main(int argc, char const *argv[]) { 42 | root = new Node(3); 43 | root->left = new Node(5); 44 | root->right = new Node(1); 45 | root->left->left = new Node(6); 46 | root->left->right = new Node(2); 47 | root->right->left = new Node(0); 48 | root->right->right = new Node(8); 49 | root->left->right->left = new Node(7); 50 | root->left->right->right = new Node(4); 51 | 52 | struct Node *p = root->left; 53 | struct Node *q = root->left->right->right; 54 | 55 | struct Node *lca = lowestCommonAncestor(root, p, q); 56 | cout << lca->data << endl; 57 | 58 | } 59 | -------------------------------------------------------------------------------- /C++/DFS/MergeTwoTrees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 3 6 3 1 8 10 5 7 | * 8 | */ 9 | 10 | #include 11 | using namespace std; 12 | 13 | struct Node { 14 | int data; 15 | struct Node *left, *right; 16 | Node(int data) { 17 | this->data = data; 18 | left = right = NULL; 19 | } 20 | }; 21 | 22 | struct Node *root1 = NULL; 23 | struct Node *root2 = NULL; 24 | 25 | void traverse(struct Node *root) { 26 | if(root == NULL) { 27 | return; 28 | } 29 | cout << root->data << " "; 30 | traverse(root->left); 31 | traverse(root->right); 32 | } 33 | 34 | struct Node* merge(struct Node *root1, struct Node *root2) { 35 | if(root1 == NULL) return root2; 36 | if(root2 == NULL) return root1; 37 | 38 | root1->data += root2->data; 39 | root1->left = merge(root1->left, root2->left); 40 | root1->right = merge(root1->right, root2->right); 41 | 42 | return root1; 43 | } 44 | 45 | int main(int argc, char const *argv[]) { 46 | root1 = new Node(1); 47 | root1->left = new Node(2); 48 | root1->right = new Node(3); 49 | root1->right->left = new Node(4); 50 | root1->right->right = new Node(5); 51 | 52 | 53 | root2 = new Node(2); 54 | root2->left = new Node(4); 55 | root2->right = new Node(5); 56 | root2->left->left = new Node(3); 57 | root2->left->right = new Node(1); 58 | root2->right->left = new Node(6); 59 | 60 | struct Node *root = merge(root1, root2); 61 | traverse(root); 62 | 63 | } 64 | -------------------------------------------------------------------------------- /C++/DFS/PathWithGivenSequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * true 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | struct Node { 13 | int data; 14 | struct Node *left, *right; 15 | Node(int data) { 16 | this->data = data; 17 | left = right = NULL; 18 | } 19 | }; 20 | 21 | struct Node *root = NULL; 22 | 23 | bool findSequence(struct Node *root, vector sequence, int index) { 24 | if(root == NULL) return false; 25 | 26 | if(index >= sequence.size() || root->data != sequence[index]) { 27 | return false; 28 | } 29 | 30 | if(root->left == NULL && root->right == NULL && index == sequence.size() - 1) { 31 | return true; 32 | } 33 | 34 | return findSequence(root->left, sequence, index + 1) || findSequence(root->right, sequence, index + 1); 35 | 36 | } 37 | 38 | bool hasPath(struct Node *root, vector sequence) { 39 | if(root == NULL) return sequence.size() == 0; 40 | 41 | return findSequence(root, sequence, 0); 42 | } 43 | 44 | int main(int argc, char const *argv[]) { 45 | root = new Node(3); 46 | root->left = new Node(7); 47 | root->right = new Node(1); 48 | root->left->left = new Node(9); 49 | root->right->left = new Node(2); 50 | root->right->right = new Node(5); 51 | bool ans = hasPath(root, vector{3, 1, 2}); 52 | if(ans) 53 | cout << "true"; 54 | else 55 | cout << "false"; 56 | cout << endl; 57 | } 58 | -------------------------------------------------------------------------------- /C++/DFS/PathWithMaximumSum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 42 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | struct Node { 13 | int data; 14 | struct Node *left, *right; 15 | Node(int data) { 16 | this->data = data; 17 | left = right = NULL; 18 | } 19 | }; 20 | 21 | struct Node *root = NULL; 22 | 23 | int maxSum = numeric_limits::min(); 24 | 25 | int findMaxSum(struct Node *root) { 26 | if(root == NULL) return 0; 27 | 28 | int leftSum = findMaxSum(root->left); 29 | int rightSum = findMaxSum(root->right); 30 | 31 | leftSum = max(leftSum, 0); 32 | rightSum = max(rightSum, 0); 33 | 34 | int currentSum = leftSum + rightSum + root->data; 35 | 36 | maxSum = max(currentSum, maxSum); 37 | return max(leftSum, rightSum) + root->data; 38 | 39 | } 40 | 41 | int findMaximumPathSum(struct Node *root) { 42 | findMaxSum(root); 43 | return maxSum; 44 | } 45 | 46 | int main(int argc, char const *argv[]) { 47 | root = new Node(10); 48 | root->left = new Node(2); 49 | root->right = new Node(10); 50 | root->left->left = new Node(20); 51 | root->left->right = new Node(1); 52 | root->right->left = new Node(-25); 53 | root->right->left->left = new Node(3); 54 | root->right->left->right = new Node(4); 55 | int ans = findMaximumPathSum(root); 56 | cout << ans << endl; 57 | } 58 | -------------------------------------------------------------------------------- /C++/DFS/Subordinates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector tree[200001]; 5 | 6 | void dfs(int curr, int prev, int count[]) { 7 | count[curr] = 1; 8 | for(auto nbr : tree[curr]) { 9 | dfs(nbr, curr, count); 10 | count[curr] += count[nbr]; 11 | } 12 | } 13 | 14 | 15 | int main(int argc, char const *argv[]) { 16 | int n; 17 | cin >> n; 18 | int emp[n - 1]; 19 | for(int i = 0; i < n - 1; i++) { 20 | cin >> emp[i]; 21 | tree[emp[i]].push_back(i + 2); 22 | } 23 | int count[n + 1]; 24 | dfs(1, 0, count); 25 | for(int i = 1; i <= n; i++) { 26 | cout << count[i] - 1 << " "; 27 | } 28 | cout << endl; 29 | return 0; 30 | } -------------------------------------------------------------------------------- /C++/DFS/SumOfPathNumbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 1008 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | struct Node { 13 | int data; 14 | struct Node *left, *right; 15 | Node(int data) { 16 | this->data = data; 17 | left = right = NULL; 18 | } 19 | }; 20 | 21 | struct Node *root = NULL; 22 | 23 | int findPathSum(struct Node *root, int pathSum) { 24 | if(root == NULL) return 0; 25 | 26 | pathSum = 10 * pathSum + root->data; 27 | 28 | if(root->left == NULL && root->right == NULL) { 29 | return pathSum; 30 | } 31 | 32 | return findPathSum(root->left, pathSum) + findPathSum(root->right, pathSum); 33 | } 34 | 35 | int findSumPathNumbers(struct Node *root) { 36 | return findPathSum(root, 0); 37 | } 38 | 39 | int main(int argc, char const *argv[]) { 40 | root = new Node(3); 41 | root->left = new Node(7); 42 | root->right = new Node(1); 43 | root->left->left = new Node(9); 44 | root->right->left = new Node(4); 45 | root->right->right = new Node(5); 46 | int ans = findSumPathNumbers(root); 47 | cout << ans << endl; 48 | } 49 | -------------------------------------------------------------------------------- /C++/DFS/SymmetricTree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * True 7 | * 8 | */ 9 | 10 | #include 11 | using namespace std; 12 | 13 | struct Node { 14 | int data; 15 | struct Node *left, *right; 16 | Node(int data) { 17 | this->data = data; 18 | left = right = NULL; 19 | } 20 | }; 21 | 22 | struct Node *root = NULL; 23 | 24 | bool findSymmetric(struct Node *root1, struct Node *root2) { 25 | if(root1 == NULL && root2 == NULL) 26 | return true; 27 | if(root1 == NULL || root2 ==NULL) 28 | return false; 29 | return (root1->data == root2->data) && 30 | findSymmetric(root1->left, root2->right) && 31 | findSymmetric(root1->right, root2->left); 32 | } 33 | 34 | bool isSymmetric(struct Node *root) { 35 | return findSymmetric(root, root); 36 | } 37 | 38 | int main(int argc, char const *argv[]) { 39 | root = new Node(1); 40 | root->left = new Node(2); 41 | root->right = new Node(2); 42 | root->left->left = new Node(3); 43 | root->left->right = new Node(4); 44 | root->right->left = new Node(4); 45 | root->right->right = new Node(3); 46 | 47 | bool ans = isSymmetric(root); 48 | if(ans) 49 | cout << "True" << endl; 50 | else 51 | cout << "False" << endl; 52 | 53 | } 54 | -------------------------------------------------------------------------------- /C++/DFS/TreeDiameter.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 8 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | struct Node { 13 | int data; 14 | struct Node *left, *right; 15 | Node(int data) { 16 | this->data = data; 17 | left = right = NULL; 18 | } 19 | }; 20 | 21 | struct Node *root = NULL; 22 | 23 | int diameter = 0; 24 | 25 | int findHeight(struct Node *root) { 26 | if(root == NULL) return 0; 27 | 28 | int leftHeight = findHeight(root->left); 29 | int rightHeight = findHeight(root->right); 30 | 31 | int currentDiameter = leftHeight + rightHeight + 1; 32 | 33 | diameter = max(currentDiameter, diameter); 34 | return max(leftHeight, rightHeight) + 1; 35 | 36 | } 37 | 38 | int findDiameter(struct Node *root) { 39 | findHeight(root); 40 | return diameter; 41 | } 42 | 43 | int main(int argc, char const *argv[]) { 44 | root = new Node(1); 45 | root->left = new Node(2); 46 | root->right = new Node(3); 47 | root->right->left = new Node(4); 48 | root->right->right = new Node(5); 49 | root->right->left->left = new Node(6); 50 | root->right->right->right = new Node(7); 51 | root->right->right->right->left = new Node(12); 52 | root->right->right->right->right = new Node(13); 53 | root->right->left->left->left = new Node(8); 54 | root->right->left->left->right = new Node(10); 55 | root->right->left->left->right->left = new Node(11); 56 | int ans = findDiameter(root); 57 | cout << ans << endl; 58 | } 59 | -------------------------------------------------------------------------------- /C++/Graph/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/C++/Graph/.DS_Store -------------------------------------------------------------------------------- /C++/Graph/BreadthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Output: 7 | * 2 0 1 3 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class Graph { 15 | int vertices; 16 | vector *adjacencyList; 17 | 18 | public: 19 | Graph(int v) { 20 | vertices = v; 21 | adjacencyList = new vector[vertices]; 22 | } 23 | 24 | void addEdge(int source, int destination) { 25 | adjacencyList[source].push_back(destination); 26 | adjacencyList[destination].push_back(source); // for directed graph comment this line 27 | } 28 | 29 | vector breadthFirstSearch(int source) { 30 | vector bfs; 31 | queue q; 32 | bool *visited = new bool[vertices]{false}; 33 | q.push(source); 34 | visited[source] = true; 35 | while(!q.empty()) { 36 | int curr = q.front(); 37 | q.pop(); 38 | bfs.push_back(curr); 39 | for(auto nbr : adjacencyList[curr]) { 40 | if(visited[nbr] == false) { 41 | q.push(nbr); 42 | visited[nbr] = true; 43 | } 44 | } 45 | } 46 | return bfs; 47 | } 48 | }; 49 | 50 | int main() { 51 | Graph g(4); 52 | g.addEdge(0, 1); 53 | g.addEdge(0, 2); 54 | g.addEdge(1, 2); 55 | g.addEdge(2, 3); 56 | vector ans = g.breadthFirstSearch(2); 57 | for(auto ele : ans) { 58 | cout << ele << " "; 59 | } 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /C++/Graph/DepthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Output: 7 | * 0 1 2 3 4 5 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class Graph { 15 | int vertices; 16 | vector *adjacencyList; 17 | 18 | public: 19 | Graph(int v) { 20 | vertices = v; 21 | adjacencyList = new vector[vertices]; 22 | } 23 | 24 | void addEdge(int source, int destination) { 25 | adjacencyList[source].push_back(destination); 26 | adjacencyList[destination].push_back(source); // for directed graph comment this line 27 | } 28 | 29 | void dfsUtil(int node, bool *visited, vector &dfs) { 30 | dfs.push_back(node); 31 | visited[node] = true; 32 | for(auto child : adjacencyList[node]) { 33 | if(!visited[child]) { 34 | visited[child] = true; 35 | dfsUtil(child, visited, dfs); 36 | } 37 | } 38 | } 39 | 40 | vector depthFirstSearch(int source) { 41 | vector dfs; 42 | bool *visited = new bool[vertices]{false}; 43 | dfsUtil(source, visited, dfs); 44 | return dfs; 45 | } 46 | }; 47 | 48 | int main() { 49 | Graph g(6); 50 | g.addEdge(0, 1); 51 | g.addEdge(1, 2); 52 | g.addEdge(2, 3); 53 | g.addEdge(2, 4); 54 | g.addEdge(4, 5); 55 | vector ans = g.depthFirstSearch(0); 56 | for(auto ele : ans) { 57 | cout << ele << " "; 58 | } 59 | return 0; 60 | } 61 | -------------------------------------------------------------------------------- /C++/Graph/Graph-Representation-Adjacency-List-2.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Output: 7 | * Adjacency List of Undirected Graph 8 | * |Delhi| => Mumbai Bangalore 9 | * |Mumbai| => Delhi Hyderabad Bangalore 10 | * |Bangalore| => Delhi Mumbai 11 | * |Hyderabad| => Mumbai 12 | * 13 | */ 14 | 15 | #include 16 | using namespace std; 17 | 18 | class Graph { 19 | vector cities; 20 | unordered_map> adjacencyList; 21 | 22 | public: 23 | Graph(vector c) { 24 | cities = c; 25 | for(auto city : cities) { 26 | vector v; 27 | adjacencyList[city] = v; 28 | } 29 | } 30 | 31 | void addEdge(string source, string destination) { 32 | adjacencyList[source].push_back(destination); 33 | adjacencyList[destination].push_back(source); // for directed graph comment this line 34 | } 35 | 36 | void printGraph() { 37 | cout << "Adjacency List of Undirected Graph" << endl; 38 | for (auto city : cities) { 39 | cout << "|" << city << "| => "; 40 | for(auto nbrCity : adjacencyList[city]) { 41 | cout << nbrCity << " "; 42 | } 43 | cout << endl; 44 | } 45 | } 46 | }; 47 | 48 | int main() { 49 | vector cities = {"Delhi", "Mumbai", "Bangalore", "Hyderabad"}; 50 | Graph g(cities); 51 | g.addEdge("Delhi", "Mumbai"); 52 | g.addEdge("Delhi", "Bangalore"); 53 | g.addEdge("Mumbai", "Hyderabad"); 54 | g.addEdge("Mumbai", "Bangalore"); 55 | g.printGraph(); 56 | return 0; 57 | 58 | } -------------------------------------------------------------------------------- /C++/Graph/ShortestReachHackerRank.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Problem Link: https://www.hackerrank.com/challenges/bfsshortreach/problem 7 | * Note: I have completed the function only. 8 | * 9 | */ 10 | 11 | 12 | 13 | vector bfs(int n, int m, vector> edges, int s) { 14 | vector distance(n + 1, -1); 15 | queue q; 16 | bool *visited = new bool[n + 1]{false}; 17 | q.push(s); 18 | visited[s] = true; 19 | distance[s] = 0; 20 | 21 | // creating adjacency list from the given set of edges. 22 | vector *adjacencyList = new vector[n + 1]; 23 | for(auto edge : edges) { 24 | adjacencyList[edge[0]].push_back(edge[1]); 25 | adjacencyList[edge[1]].push_back(edge[0]); 26 | } 27 | 28 | while(!q.empty()) { 29 | int curr = q.front(); 30 | q.pop(); 31 | for(auto nbr : adjacencyList[curr]) { 32 | if(visited[nbr] == false) { 33 | q.push(nbr); 34 | visited[nbr] = true; 35 | distance[nbr] = distance[curr] + 6; 36 | } 37 | } 38 | } 39 | vector ans; 40 | for(int i = 1; i <= n; i++) { 41 | if(distance[i] != 0) { 42 | ans.push_back(distance[i]); 43 | } 44 | } 45 | return ans; 46 | } 47 | -------------------------------------------------------------------------------- /C++/Heap/KClosestPointToOrigin.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | class Point { 14 | public: 15 | int x; 16 | int y; 17 | int d; 18 | Point(int x, int y, int d) { 19 | this->x = x; 20 | this->y = y; 21 | this->d = d; 22 | } 23 | }; 24 | 25 | struct comparator { 26 | bool operator() (Point &a, Point &b) { 27 | return (b.d > a.d); 28 | } 29 | }; 30 | 31 | class KClosestPointToOrigin { 32 | public: 33 | 34 | vector> kClosest(vector>& points, int k) { 35 | priority_queue, comparator> maxHeap; 36 | 37 | for(vector point : points) { 38 | int x = point[0]; 39 | int y = point[1]; 40 | int dist = (x * x) + (y * y); 41 | maxHeap.push(Point(x, y, distance);); 42 | if(maxHeap.size() > k) { 43 | maxHeap.pop(); 44 | } 45 | } 46 | 47 | vector> ans(k,{0, 0}); 48 | int i = 0; 49 | while(!maxHeap.empty()) { 50 | Point p = maxHeap.top(); 51 | maxHeap.pop(); 52 | ans[i][0] = p.x; 53 | ans[i][1] = p.y; 54 | i += 1; 55 | } 56 | return ans; 57 | 58 | } 59 | }; -------------------------------------------------------------------------------- /C++/Heap/KthLargestElement.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class KthLargestElement { 15 | public: 16 | 17 | static int findKthLargestNumber(const vector &nums, int k) { 18 | priority_queue, greater<>> minHeap; 19 | 20 | for(int i = 0; i < k; i++) { 21 | minHeap.push(nums[i]); 22 | } 23 | 24 | for(int i = k; i < nums.size(); i++) { 25 | if(nums[i] > minHeap.top()) { 26 | minHeap.pop(); 27 | minHeap.push(nums[i]); 28 | } 29 | } 30 | return minHeap.top(); 31 | } 32 | }; 33 | 34 | int main(int argc, char const *argv[]) 35 | { 36 | int result = KthLargestElement::findKthLargestNumber(vector{3, 1, 5, 12, 2, 11}, 3); 37 | cout << result; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /C++/Heap/KthSmallestElement.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class KthSmallestElement { 15 | public: 16 | 17 | static int findKthSmallestNumber(const vector &nums, int k) { 18 | priority_queue> maxHeap; 19 | 20 | for(int i = 0; i < k; i++) { 21 | maxHeap.push(nums[i]); 22 | } 23 | 24 | for(int i = k; i < nums.size(); i++) { 25 | if(nums[i] < maxHeap.top()) { 26 | maxHeap.pop(); 27 | maxHeap.push(nums[i]); 28 | } 29 | } 30 | return maxHeap.top(); 31 | } 32 | }; 33 | 34 | int main(int argc, char const *argv[]) 35 | { 36 | int result = KthSmallestElement::findKthSmallestNumber(vector{3, 1, 5, 12, 2, 11}, 3); 37 | cout << result; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /C++/Heap/Largest_K_Elements.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class Largest_K_Elements { 15 | public: 16 | 17 | static vector findKLargestNumbers(const vector &nums, int k) { 18 | priority_queue, greater<>> minHeap; 19 | 20 | for(int i = 0; i < k; i++) { 21 | minHeap.push(nums[i]); 22 | } 23 | 24 | for(int i = k; i < nums.size(); i++) { 25 | if(nums[i] > minHeap.top()) { 26 | minHeap.pop(); 27 | minHeap.push(nums[i]); 28 | } 29 | } 30 | vector answer(k); 31 | for (int i = 0; i < k; i++) { 32 | answer[i] = minHeap.top(); 33 | minHeap.pop(); 34 | } 35 | return answer; 36 | } 37 | }; 38 | 39 | int main(int argc, char const *argv[]) 40 | { 41 | vector result = Largest_K_Elements::findKLargestNumbers(vector{3, 1, 5, 12, 2, 11}, 3); 42 | for(auto num : result) { 43 | cout << num << " "; 44 | } 45 | cout << endl; 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /C++/Heap/ReorganizeString.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class Solution { 15 | public: 16 | 17 | struct valueCompare { 18 | char operator()(pair &x, pair &y) { 19 | return y.second > x.second; 20 | } 21 | }; 22 | 23 | string reorganizeString(string s) { 24 | 25 | unordered_map hash_map; 26 | for(char ch : s) { 27 | hash_map[ch]++; 28 | } 29 | priority_queue, vector>, valueCompare> max_heap; 30 | for(auto entry : hash_map) { 31 | max_heap.push(entry); 32 | } 33 | pair prev(-1, -1); 34 | string res = ""; 35 | while(!max_heap.empty()) { 36 | pair entry = max_heap.top(); 37 | max_heap.pop(); 38 | res += entry.first; 39 | if(prev.second > 0) { 40 | max_heap.push(prev); 41 | } 42 | prev = entry; 43 | prev.second--; 44 | 45 | } 46 | 47 | if(res.length() == s.length()) { 48 | return res; 49 | } 50 | else { 51 | return ""; 52 | } 53 | } 54 | }; -------------------------------------------------------------------------------- /C++/Heap/Smallest_K_Elements.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class Smallest_K_Elements { 15 | public: 16 | 17 | static vector findKSmallestNumbers(const vector &nums, int k) { 18 | priority_queue> maxHeap; 19 | 20 | for(int i = 0; i < k; i++) { 21 | maxHeap.push(nums[i]); 22 | } 23 | 24 | for(int i = k; i < nums.size(); i++) { 25 | if(nums[i] < maxHeap.top()) { 26 | maxHeap.pop(); 27 | maxHeap.push(nums[i]); 28 | } 29 | } 30 | vector answer(k); 31 | for (int i = 0; i < k; i++) { 32 | answer[i] = maxHeap.top(); 33 | maxHeap.pop(); 34 | } 35 | return answer; 36 | } 37 | }; 38 | 39 | int main(int argc, char const *argv[]) { 40 | vector result = Smallest_K_Elements::findKSmallestNumbers(vector{3, 1, 5, 12, 2, 11}, 3); 41 | for(auto num : result) { 42 | cout << num << " "; 43 | } 44 | cout << endl; 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /C++/Heap/SortCharactersByFrequency.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class SortCharactersByFrequency { 15 | public: 16 | 17 | struct comparator { 18 | bool operator() (pair &x, pair &y) { 19 | return y.second > x.second; 20 | } 21 | }; 22 | 23 | static string sortCharactersByFrequency(const string s) { 24 | 25 | unordered_map frequencyMap; 26 | for(char c : s) { 27 | frequencyMap[c]++; 28 | } 29 | 30 | priority_queue, vector>, comparator> maxHeap; 31 | 32 | for(auto entry : frequencyMap) { 33 | maxHeap.push(entry); 34 | } 35 | 36 | string sortedString = ""; 37 | while(!maxHeap.empty()) { 38 | auto entry = maxHeap.top(); 39 | maxHeap.pop(); 40 | for(int i = 0; i < entry.second; i++) { 41 | sortedString += entry.first; 42 | } 43 | } 44 | return sortedString; 45 | } 46 | }; 47 | 48 | int main(int argc, char const *argv[]) { 49 | string result = SortCharactersByFrequency::sortCharactersByFrequency("tree"); 50 | cout << result; 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /C++/Heap/TopKFrequentElements.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | class Solution { 15 | public: 16 | 17 | struct valueCompare { 18 | char operator()(pair &x, pair &y) { 19 | return y.second < x.second; 20 | } 21 | }; 22 | 23 | string topKFrequentElements(vector v, int k) { 24 | 25 | unordered_map hash_map; 26 | for(int a : s) { 27 | hash_map[a]++; 28 | } 29 | priority_queue, vector>, valueCompare> min_heap; 30 | 31 | for(auto entry : hash_map) { 32 | min_heap.push(entry); 33 | if(min_heap.size() == k + 1) { 34 | min_heap.pop(); 35 | } 36 | } 37 | } 38 | }; -------------------------------------------------------------------------------- /C++/LinkedList/LoopDetection.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash Verma 4 | 5 | Detecting a loop in a linked list. 6 | 7 | Output: 8 | true 9 | 10 | */ 11 | 12 | 13 | #include 14 | using namespace std; 15 | 16 | /* creating a node structure in C/C++ */ 17 | struct Node { 18 | int data; 19 | struct Node *next; 20 | }; 21 | 22 | /* defining head as null as there is no node in the list initially. */ 23 | struct Node* head = NULL; 24 | 25 | void push(int data) { 26 | Node *temp; 27 | temp = head; 28 | 29 | /* creating a node and assigning data to it and make its next as null */ 30 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 31 | new_node->data = data; 32 | new_node->next = NULL; 33 | 34 | /* check if it's empty make new_node as head */ 35 | if(head == NULL) { 36 | head = new_node; 37 | } 38 | /* otherwise move upto the last and then connect last node with the new_node */ 39 | else { 40 | while(temp->next != NULL) { 41 | temp = temp->next; 42 | } 43 | temp->next = new_node; 44 | } 45 | } 46 | 47 | /* finding loop in a linked list. */ 48 | bool isLoopFound() { 49 | Node *slow, *fast; 50 | slow = fast = head; 51 | 52 | if(head == NULL) { 53 | cout << "The list doesn't exist." << endl; 54 | return false; 55 | } 56 | 57 | while(fast != NULL && fast->next != NULL) { 58 | slow = slow->next; 59 | fast = fast->next->next; 60 | if(slow == fast) { 61 | return true; 62 | } 63 | } 64 | 65 | return false; 66 | } 67 | 68 | int main() { 69 | 70 | push(2); 71 | push(3); 72 | push(4); 73 | push(5); 74 | push(6); 75 | head->next->next->next->next->next = head->next->next; 76 | bool loopFound = isLoopFound(); 77 | cout << loopFound << endl; 78 | return 0; 79 | 80 | } -------------------------------------------------------------------------------- /C++/MergeIntervals/InsertInterval.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Innoskrit { 5 | public: 6 | static vector> insert(vector>& intervals, vector& newInterval) { 7 | int i = 0; 8 | vector> ans; 9 | 10 | while(i < intervals.size() && intervals[i][1] < newInterval[0]) { 11 | ans.push_back(intervals[i]); 12 | i += 1; 13 | } 14 | 15 | while(i < intervals.size() && intervals[i][0] <= newInterval[1]) { 16 | newInterval[0] = min(newInterval[0], intervals[i][0]); 17 | newInterval[1] = max(newInterval[1], intervals[i][1]); 18 | i += 1; 19 | } 20 | ans.push_back(newInterval); 21 | 22 | while(i < intervals.size()) { 23 | ans.push_back(intervals[i]); 24 | i += 1; 25 | } 26 | 27 | return ans; 28 | } 29 | }; 30 | 31 | int main() { 32 | vector> intervals = {{1, 3}, {5, 7}, {8, 12}}; 33 | vector newInterval = {4, 6}; 34 | for (auto interval : Innoskrit::insert(intervals, newInterval)) { 35 | cout << "[" << interval[0] << "," << interval[1] << "] "; 36 | } 37 | cout << endl; 38 | } -------------------------------------------------------------------------------- /C++/MergeIntervals/IntervalsIntersection.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Innoskrit { 5 | public: 6 | static vector> intervalIntersection(vector>& arr1, vector>& arr2) { 7 | int i = 0, j = 0; 8 | vector> ans; 9 | 10 | while(i < arr1.size() && j < arr2.size()) { 11 | vector intersection; 12 | intersection.push_back(max(arr1[i][0], arr2[j][0])); 13 | intersection.push_back(min(arr1[i][1], arr2[j][1])); 14 | 15 | if(intersection[0] <= intersection[1]) { 16 | ans.push_back(intersection); 17 | } 18 | 19 | if(arr1[i][1] < arr2[j][1]) { 20 | i += 1; 21 | } else { 22 | j += 1; 23 | } 24 | } 25 | return ans; 26 | } 27 | }; 28 | 29 | int main() { 30 | vector> arr1 = {{1, 3}, {5, 6}, {7, 9}}; 31 | vector> arr2 = {{2, 3}, {5, 7}}; 32 | for (auto interval : Innoskrit::intervalIntersection(arr1, arr2)) { 33 | cout << "[" << interval[0] << ", " << interval[1] << "] "; 34 | } 35 | cout << endl; 36 | } -------------------------------------------------------------------------------- /C++/Recursion/Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int fibonacci(int n) { 5 | if(n == 1 || n == 2) { 6 | return 1; 7 | } 8 | return fibonacci(n - 1) + fibonacci(n - 2); 9 | } 10 | 11 | int main() { 12 | int n = 10; 13 | cout << fibonacci(n); 14 | return 0; 15 | } -------------------------------------------------------------------------------- /C++/Recursion/Handshake.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int handshake(int n) { 5 | if(n == 1) 6 | return 0; 7 | return (n - 1) + handshake(n - 1); 8 | } 9 | 10 | int main() { 11 | int n = 10; 12 | cout << handshake(n); 13 | return 0; 14 | } -------------------------------------------------------------------------------- /C++/Stack/NGEL.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: Given an array, find an array of the Next Greater Elements (NGE) for every element. 6 | The Next Greater Element for an element x is the first greater element 7 | on the left side of x in array. Elements for which no greater element exist, 8 | consider next greater element as -1. 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | vector nextGreaterElementToLeft(int arr[], int n) { 15 | stack s; 16 | vector v; 17 | 18 | for(int i = 0; i < n; i++) { 19 | while(!s.empty() && s.top() <= arr[i]) { 20 | s.pop(); 21 | } 22 | if(s.empty()) { 23 | v.push_back(-1); 24 | } 25 | else { 26 | v.push_back(s.top()); 27 | } 28 | s.push(arr[i]); 29 | } 30 | return v; 31 | } 32 | 33 | int main(int argc, char const *argv[]) { 34 | 35 | int arr[] = {4, 5, 2, 25}; 36 | int n = sizeof(arr) / sizeof(arr[0]); 37 | vector ans = nextGreaterElementToLeft(arr, n); 38 | for (int a: ans) { 39 | cout << a << " "; 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /C++/Stack/NGER.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: Given an array, find an array of the Next Greater Elements (NGE) for every element. 6 | The Next Greater Element for an element x is the first greater element 7 | on the right side of x in array. Elements for which no greater element exist, 8 | consider next greater element as -1. 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | vector nextGreaterElementToRight(int arr[], int n) { 15 | stack s; 16 | vector v; 17 | 18 | for(int i = n - 1; i >= 0; i--) { 19 | while(!s.empty() && s.top() <= arr[i]) { 20 | s.pop(); 21 | } 22 | if(s.empty()) { 23 | v.push_back(-1); 24 | } 25 | else { 26 | v.push_back(s.top()); 27 | } 28 | s.push(arr[i]); 29 | } 30 | reverse(v.begin(), v.end()); 31 | return v; 32 | } 33 | 34 | int main(int argc, char const *argv[]) { 35 | 36 | int arr[] = {7, 8, 1, 4}; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | vector ans = nextGreaterElementToRight(arr, n); 39 | for (int a: ans) { 40 | cout << a << " "; 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /C++/Stack/NSEL.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: Given an array, find an array of the Next Smaller Elements (NSE) for every element. 6 | The Next Smaller Element for an element x is the first smaller element 7 | on the left side of x in array. Elements for which no smaller element exist, 8 | consider next smaller element as -1. 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | vector nextSmallerElementToLeft(int arr[], int n) { 15 | stack s; 16 | vector v; 17 | 18 | for(int i = 0; i < n; i++) { 19 | while(!s.empty() && s.top() >= arr[i]) { 20 | s.pop(); 21 | } 22 | if(s.empty()) { 23 | v.push_back(-1); 24 | } 25 | else { 26 | v.push_back(s.top()); 27 | } 28 | s.push(arr[i]); 29 | } 30 | return v; 31 | } 32 | 33 | int main(int argc, char const *argv[]) { 34 | 35 | int arr[] = {7, 8, 1, 4}; 36 | int n = sizeof(arr) / sizeof(arr[0]); 37 | vector ans = nextSmallerElementToLeft(arr, n); 38 | for (int a: ans) { 39 | cout << a << " "; 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /C++/Stack/NSER.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: Given an array, find an array of the Next Smaller Elements (NSE) for every element. 6 | The Next Smaller Element for an element x is the first smaller element 7 | on the right side of x in array. Elements for which no smaller element exist, 8 | consider next smaller element as -1. 9 | */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | vector nextSmallerElementToRight(int arr[], int n) { 15 | stack s; 16 | vector v; 17 | 18 | for(int i = n - 1; i >= 0; i--) { 19 | while(!s.empty() && s.top() >= arr[i]) { 20 | s.pop(); 21 | } 22 | if(s.empty()) { 23 | v.push_back(-1); 24 | } 25 | else { 26 | v.push_back(s.top()); 27 | } 28 | s.push(arr[i]); 29 | } 30 | reverse(v.begin(), v.end()); 31 | return v; 32 | } 33 | 34 | int main(int argc, char const *argv[]) { 35 | 36 | int arr[] = {7, 8, 1, 4}; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | vector ans = nextSmallerElementToRight(arr, n); 39 | for (int a: ans) { 40 | cout << a << " "; 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /C++/Stack/StockSpan.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: 6 | The stock span problem is a financial problem where we have a series of 7 | n daily price quotes for a stock and we need to calculate span of stock’s 8 | price for all n days. 9 | The span Si of the stock’s price on a given day i is defined as the maximum 10 | number of consecutive days just before the given day, for which the price 11 | of the stock on the current day is less than or equal to its price on the 12 | given day. 13 | */ 14 | 15 | #include 16 | using namespace std; 17 | 18 | vector getSpanArray(vector arr) { 19 | 20 | vector ans; 21 | 22 | /* Creating Stack to put span & price */ 23 | stack prices; 24 | stack span; 25 | prices.push(arr[0]); 26 | span.push(1); 27 | 28 | ans.push_back(1); 29 | 30 | for(int i = 1; i < arr.size(); i++) { 31 | int count = 1; 32 | while(!prices.empty() && prices.top() < arr[i]) { 33 | count += span.top(); 34 | prices.pop(); 35 | span.pop(); 36 | } 37 | span.push(count); 38 | prices.push(arr[i]); 39 | ans.push_back(count); 40 | } 41 | return ans; 42 | } 43 | 44 | int main(int argc, char const *argv[]) { 45 | 46 | vector arr = {10, 4, 5, 90, 120, 80}; 47 | vector ans = getSpanArray(arr); 48 | for(int i: ans) { 49 | cout << i << " "; 50 | } 51 | return 0; 52 | } -------------------------------------------------------------------------------- /C++/Stack/StockSpan2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: The stock span problem is a financial problem where we have a 6 | series of n daily price quotes for a stock and we need to calculate span 7 | of stock’s price for all n days. 8 | The span Si of the stock’s price on a given day i is defined as the 9 | maximum number of consecutive days just before the given day, for which 10 | the price of the stock on the current day is less than or equal to its 11 | price on the given day. 12 | 13 | Output: 1 1 1 2 1 4 6 14 | */ 15 | 16 | #include 17 | using namespace std; 18 | 19 | vector stockSpan(int arr[], int n) { 20 | stack> s; 21 | vector v; 22 | vector span; 23 | 24 | for(int i = 0; i < n; i++) { 25 | while(!s.empty() && s.top().first <= arr[i]) { 26 | s.pop(); 27 | } 28 | if(s.empty()) { 29 | v.push_back(-1); 30 | } 31 | else { 32 | v.push_back(s.top().second); 33 | } 34 | s.push({arr[i], i}); 35 | } 36 | for(int i = 0; i < n; i++) { 37 | span.push_back(i - v[i]); 38 | } 39 | return span; 40 | } 41 | 42 | int main(int argc, char const *argv[]) { 43 | 44 | int arr[] = {100, 80, 60, 70, 60, 75, 85}; 45 | int n = sizeof(arr) / sizeof(arr[0]); 46 | vector ans = stockSpan(arr, n); 47 | for (int a: ans) { 48 | cout << a << " "; 49 | } 50 | 51 | } -------------------------------------------------------------------------------- /C++/TopologicalSort/TopologicalSort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 5 6 3 4 0 2 1 7 | */ 8 | 9 | #include 10 | using namespace std; 11 | 12 | vector topologicalSort(vector> edges, int vertices) { 13 | vector sortedOrder; 14 | if(vertices <= 0) { 15 | return sortedOrder; 16 | } 17 | 18 | map inDegree; 19 | map> graph; 20 | 21 | // intializing the graph 22 | for(int i = 0; i < vertices; i++) { 23 | inDegree[i] = 0; 24 | vector v; 25 | graph[i] = v; 26 | } 27 | 28 | // building the graph 29 | for(int i = 0; i < edges.size(); i++) { 30 | int parent = edges[i][0]; 31 | int child = edges[i][1]; 32 | graph[parent].push_back(child); 33 | inDegree[child] += 1; 34 | } 35 | 36 | // processing all valid starting nodes 37 | queue q; 38 | for(auto entry : inDegree) { 39 | if(entry.second == 0) { 40 | q.push(entry.first); 41 | } 42 | } 43 | 44 | while(!q.empty()) { 45 | int vertex = q.front(); 46 | q.pop(); 47 | sortedOrder.push_back(vertex); 48 | vector children = graph[vertex]; 49 | for(auto child : children) { 50 | inDegree[child] -= 1; 51 | if(inDegree[child] == 0) { 52 | q.push(child); 53 | } 54 | } 55 | } 56 | 57 | if(sortedOrder.size() != vertices) { 58 | vector v; 59 | return v; 60 | } 61 | 62 | return sortedOrder; 63 | 64 | } 65 | 66 | int main(int argc, char const *argv[]) { 67 | vector> edges {{6, 4}, {6, 2}, {5, 3}, {5, 4}, {3, 0}, {3, 1}, {3, 2}, {4, 1}}; 68 | vector ans = topologicalSort(edges, 7); 69 | for(auto a : ans) { 70 | cout << a << " "; 71 | } 72 | return 0; 73 | } -------------------------------------------------------------------------------- /C++/TreeConstructions/TreeFromInorderPostorder.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | */ 7 | 8 | struct TreeNode { 9 | int val; 10 | TreeNode *left; 11 | TreeNode *right; 12 | TreeNode() : val(0), left(nullptr), right(nullptr) {} 13 | TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 14 | TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 15 | }; 16 | 17 | 18 | class Solution { 19 | 20 | /* LeetCode Code 21 | Line 24 - 46 22 | */ 23 | 24 | public: 25 | int postIndex; 26 | map inorder_map; 27 | 28 | TreeNode* solve(vector& postorder, int start, int end){ 29 | if(start > end) 30 | return NULL; 31 | int rootValue = postorder[postIndex]; 32 | int index = inorder_map[rootValue]; 33 | postIndex--; 34 | TreeNode* root = new TreeNode(rootValue); 35 | root->right = solve(postorder, index + 1, end); 36 | root->left = solve(postorder, start, index - 1); 37 | return root; 38 | } 39 | 40 | TreeNode* buildTree(vector& inorder, vector& postorder) { 41 | postIndex = postorder.size()-1; 42 | for(int i = 0; i < inorder.size(); i++) 43 | inorder_map[inorder[i]] = i; 44 | return solve(postorder, 0, postorder.size() - 1); 45 | } 46 | }; 47 | 48 | int main(int argc, char const *argv[]) 49 | { 50 | vector inorder = {}; 51 | vector postorder = {}; 52 | TreeNode* root = buildTree(inorder, postorder); 53 | /** 54 | * We can write the code for BFS traversal to check the formed tree. 55 | * 56 | */ 57 | } -------------------------------------------------------------------------------- /Java/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Java/.DS_Store -------------------------------------------------------------------------------- /Java/BFS/LevelOrderSuccessor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 6 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class LevelOrderSuccessor { 23 | 24 | static Node root; 25 | LevelOrderSuccessor() { 26 | root = null; 27 | } 28 | 29 | public static Node levelOrderSuccessor(Node root, int key) { 30 | if(root == null) return null; 31 | Queue queue = new LinkedList<>(); 32 | queue.offer(root); 33 | while(!queue.isEmpty()) { 34 | Node current = queue.poll(); 35 | if(current.left != null) 36 | queue.offer(current.left); 37 | if(current.right != null) 38 | queue.offer(current.right); 39 | 40 | if(current.data == key) { 41 | break; 42 | } 43 | } 44 | return queue.poll(); 45 | } 46 | 47 | public static void main (String[] args) { 48 | root = new Node(1); 49 | root.left = new Node(2); 50 | root.right = new Node(3); 51 | root.left.left = new Node(4); 52 | root.right.left = new Node(6); 53 | root.right.right = new Node(7); 54 | root.right.right.left = new Node(8); 55 | Node ans = levelOrderSuccessor(root, 4); 56 | System.out.println(ans.data); 57 | } 58 | } -------------------------------------------------------------------------------- /Java/BFS/MinimumDepth.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 3 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class MinimumTreeDepth { 23 | 24 | static Node root; 25 | MinimumTreeDepth() { 26 | root = null; 27 | } 28 | 29 | public static int findMinimumDepth(Node root) { 30 | int minimumDepth = 0; 31 | if(root == null) return minimumDepth; 32 | Queue queue = new LinkedList<>(); 33 | queue.offer(root); 34 | while(!queue.isEmpty()) { 35 | minimumDepth++; 36 | int levelSize = queue.size(); 37 | for(int i = 0; i < levelSize; i++) { 38 | Node current = queue.poll(); 39 | 40 | if(current.left == null && current.right == null) { 41 | return minimumDepth; 42 | } 43 | 44 | if(current.left != null) 45 | queue.offer(current.left); 46 | if(current.right != null) 47 | queue.offer(current.right); 48 | } 49 | } 50 | return minimumDepth; 51 | } 52 | 53 | public static void main (String[] args) { 54 | root = new Node(1); 55 | root.left = new Node(2); 56 | root.right = new Node(3); 57 | root.left.left = new Node(4); 58 | root.right.left = new Node(6); 59 | root.right.right = new Node(7); 60 | root.right.right.left = new Node(8); 61 | int ans = findMinimumDepth(root); 62 | System.out.println(ans); 63 | } 64 | } -------------------------------------------------------------------------------- /Java/BFS/RightView.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 12 1 5 3 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class RightView { 23 | 24 | static Node root; 25 | RightView() { 26 | root = null; 27 | } 28 | 29 | public static List rightView(Node root) { 30 | List result = new ArrayList<>(); 31 | if(root == null) return result; 32 | Queue queue = new LinkedList<>(); 33 | queue.offer(root); 34 | while(!queue.isEmpty()) { 35 | int levelSize = queue.size(); 36 | for(int i = 0; i < levelSize; i++) { 37 | Node current = queue.poll(); 38 | 39 | if(i == levelSize - 1) { 40 | result.add(current.data); 41 | } 42 | 43 | if(current.left != null) 44 | queue.offer(current.left); 45 | if(current.right != null) 46 | queue.offer(current.right); 47 | } 48 | } 49 | return result; 50 | } 51 | 52 | public static void main (String[] args) { 53 | root = new Node(12); 54 | root.left = new Node(7); 55 | root.right = new Node(1); 56 | root.left.left = new Node(9); 57 | root.right.left = new Node(10); 58 | root.right.right = new Node(5); 59 | root.left.left.left = new Node(3); 60 | List ans = rightView(root); 61 | for(int node : ans) { 62 | System.out.print(node + " "); 63 | } 64 | System.out.println(); 65 | } 66 | } -------------------------------------------------------------------------------- /Java/BinaryTree/ConstructingBinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * @author 4 | * Aakash Verma 5 | * 6 | */ 7 | 8 | 9 | /* 10 | Creating a structure for the node. 11 | Initializing the node's data upon calling its constructor. 12 | */ 13 | class Node { 14 | int data; 15 | Node left, right; 16 | 17 | public Node(int key) { 18 | data = key; 19 | left = right = null; 20 | } 21 | } 22 | 23 | 24 | class BinaryTree { 25 | 26 | /* Creating a root node for the Tree */ 27 | static Node root; 28 | 29 | /* 30 | Assigning root as null initially. So as soon as the object will be created 31 | of this BinaryTreeTraversal class, root will be set as null. 32 | */ 33 | BinaryTree() { 34 | root = null; 35 | } 36 | 37 | /* main method */ 38 | public static void main (String[] args) { 39 | BinaryTree tree = new BinaryTree(); 40 | tree.root = new Node(1); 41 | tree.root.left = new Node(2); 42 | tree.root.right = new Node(3); 43 | tree.root.left.left = new Node(4); 44 | tree.root.left.right = new Node(5); 45 | tree.root.right.left = new Node(6); 46 | tree.root.right.right = new Node(7); 47 | } -------------------------------------------------------------------------------- /Java/BinaryTree/InorderTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author 3 | * aakash.verma 4 | * 5 | */ 6 | 7 | import java.util.*; 8 | 9 | class InorderTraversal { 10 | public List inorderTraversal(TreeNode root) { 11 | List inorder = new ArrayList<>(); 12 | Stack stack = new Stack<>(); 13 | if(root == null) { 14 | return inorder; 15 | } 16 | 17 | TreeNode curr = root; 18 | while(curr != null || stack.size() != 0) { 19 | while(curr != null) { 20 | stack.push(curr); 21 | curr = curr.left; 22 | } 23 | curr = stack.pop(); 24 | inorder.add(curr.val); 25 | curr = curr.right; 26 | } 27 | return inorder; 28 | } 29 | 30 | public static void main(String[] args) { 31 | . 32 | . 33 | . 34 | } 35 | } -------------------------------------------------------------------------------- /Java/BinaryTree/PostorderTraversal.java: -------------------------------------------------------------------------------- 1 | /** 2 | * @author 3 | * aakash.verma 4 | * 5 | */ 6 | 7 | import java.util.*; 8 | 9 | class PostorderTraversal { 10 | 11 | public List postorderTraversal(TreeNode root) { 12 | List postorder = new ArrayList<>(); 13 | Stack stack1 = new Stack<>(); 14 | Stack stack2 = new Stack<>(); 15 | if(root == null) return postorder; 16 | stack1.push(root); 17 | while(stack1.size() != 0) { 18 | TreeNode current = stack1.pop(); 19 | stack2.push(current); 20 | if(current.left != null) stack1.push(current.left); 21 | if(current.right != null) stack1.push(current.right); 22 | } 23 | while(stack2.size() != 0) { 24 | postorder.add(stack2.pop().val); 25 | } 26 | return postorder; 27 | } 28 | 29 | public static void main(String[] args) { 30 | . 31 | . 32 | . 33 | } 34 | } -------------------------------------------------------------------------------- /Java/DFS/BinaryTreePathSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * true 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class BinaryTreePathSum { 23 | 24 | static Node root; 25 | BinaryTreePathSum() { 26 | root = null; 27 | } 28 | 29 | public static boolean hasPath(Node root, int sum) { 30 | if(root == null) return false; 31 | 32 | if(root.data == sum && root.left == null && root.right == null) 33 | return true; 34 | 35 | return hasPath(root.left, sum - root.data) || hasPath(root.right, sum - root.data); 36 | } 37 | 38 | public static void main (String[] args) { 39 | root = new Node(12); 40 | root.left = new Node(7); 41 | root.right = new Node(1); 42 | root.left.left = new Node(9); 43 | root.right.left = new Node(10); 44 | root.right.right = new Node(5); 45 | root.left.left.left = new Node(3); 46 | boolean ans = hasPath(root, 23); 47 | System.out.println(ans); 48 | } 49 | } -------------------------------------------------------------------------------- /Java/DFS/CP01_BinaryTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | */ 6 | 7 | import java.util.*; 8 | import java.lang.*; 9 | import java.io.*; 10 | 11 | class CP01_BinaryTree { 12 | 13 | public static int[] bfs(int n, int source, HashMap> tree) { 14 | Queue queue = new LinkedList<>(); 15 | queue.offer(source); 16 | int distance[] = new int[n + 1]; 17 | while(!queue.isEmpty()) { 18 | int current = queue.poll(); 19 | for(int neighbour : tree.get(current)) { 20 | queue.offer(neighbour); 21 | distance[neighbour] = distance[current] + 1; 22 | } 23 | } 24 | return distance; 25 | } 26 | 27 | public static void main(String[] args) throws Exception { 28 | BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 29 | int t = Integer.parseInt(reader.readLine()); 30 | while(t-- > 0) { 31 | int n = Integer.parseInt(reader.readLine()); 32 | HashMap> tree = new HashMap<>(); 33 | for(int i = 1; i <= n; i++) { 34 | tree.put(i, new ArrayList<>()); 35 | } 36 | for(int i = 0; i < n - 1; i++) { 37 | String[] st = reader.readLine().trim().split("\\s+"); 38 | int a = Integer.parseInt(st[0]); 39 | int b = Integer.parseInt(st[1]); 40 | tree.get(a).add(b); 41 | tree.put(a, tree.get(a)); 42 | } 43 | int distance[] = bfs(n, 1, tree); 44 | for(int i = 1; i <= n; i++) { 45 | System.out.print(distance[i] + " "); 46 | } 47 | System.out.println(); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /Java/DFS/LowestCommonAncestorBT.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 5 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class LowestCommonAncestor { 23 | 24 | static Node root; 25 | LowestCommonAncestor() { 26 | root = null; 27 | } 28 | 29 | public static Node lowestCommonAncestor(Node root, Node p, Node q) { 30 | 31 | if(root == null) 32 | return null; 33 | 34 | if(root.data == p.data || root.data == q.data) 35 | return root; 36 | 37 | Node left = lowestCommonAncestor(root.left, p, q); 38 | Node right = lowestCommonAncestor(root.right, p, q); 39 | 40 | if(left != null && right != null) 41 | return root; 42 | 43 | return left != null ? left : right; 44 | } 45 | 46 | public static void main (String[] args) { 47 | root = new Node(3); 48 | root.left = new Node(5); 49 | root.right = new Node(1); 50 | root.left.left = new Node(6); 51 | root.left.right = new Node(2); 52 | root.right.left = new Node(0); 53 | root.right.right = new Node(8); 54 | root.left.right.left = new Node(7); 55 | root.left.right.right = new Node(4); 56 | 57 | Node p = root.left; 58 | Node q = root.left.right.right; 59 | 60 | Node lca = lowestCommonAncestor(root, p, q); 61 | System.out.println(lca.data); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Java/DFS/MergeTwoTrees.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 3 6 3 1 8 10 5 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class MergeTwoTrees { 23 | 24 | static Node root1, root2; 25 | MergeTwoTrees() { 26 | root1 = null; 27 | root2 = null; 28 | } 29 | 30 | public static void traverse(Node root) { 31 | if(root == null) { 32 | return; 33 | } 34 | System.out.print(root.data + " "); 35 | traverse(root.left); 36 | traverse(root.right); 37 | } 38 | 39 | public static Node merge(Node root1, Node root2) { 40 | if(root1 == null) 41 | return root2; 42 | if(root2 == null) 43 | return root1; 44 | 45 | root1.data += root2.data; 46 | 47 | root1.left = merge(root1.left, root2.left); 48 | root1.right = merge(root1.right, root2.right); 49 | return root1; 50 | } 51 | 52 | public static void main (String[] args) { 53 | root1 = new Node(1); 54 | root1.left = new Node(2); 55 | root1.right = new Node(3); 56 | root1.right.left = new Node(4); 57 | root1.right.right = new Node(5); 58 | 59 | root2 = new Node(2); 60 | root2.left = new Node(4); 61 | root2.right = new Node(5); 62 | root2.left.left = new Node(3); 63 | root2.left.right = new Node(1); 64 | root2.right.left = new Node(6); 65 | 66 | Node root = merge(root1, root2); 67 | traverse(root); 68 | 69 | } 70 | } -------------------------------------------------------------------------------- /Java/DFS/PathWithGivenSequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * true 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class PathWithGivenSequence { 23 | 24 | static Node root; 25 | PathWithGivenSequence() { 26 | root = null; 27 | } 28 | 29 | private static boolean findSequence(Node root, int[] sequence, int index) { 30 | if(root == null) return false; 31 | 32 | if(index >= sequence.length || root.data != sequence[index]) { 33 | return false; 34 | } 35 | 36 | if(root.left == null && root.right == null && index == sequence.length - 1) { 37 | return true; 38 | } 39 | 40 | return findSequence(root.left, sequence, index + 1) || findSequence(root.right, sequence, index + 1); 41 | } 42 | 43 | public static boolean hasPath(Node root, int[] sequence) { 44 | if(root == null) return sequence.length == 0; 45 | 46 | return findSequence(root, sequence, 0); 47 | } 48 | 49 | public static void main (String[] args) { 50 | root = new Node(3); 51 | root.left = new Node(7); 52 | root.right = new Node(1); 53 | root.left.left = new Node(9); 54 | root.right.left = new Node(2); 55 | root.right.right = new Node(5); 56 | boolean ans = hasPath(root, new int[] {3, 1, 2}); 57 | System.out.println(ans); 58 | } 59 | } -------------------------------------------------------------------------------- /Java/DFS/PathWithMaximumSum.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 42 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class PathWithMaximumSum { 23 | 24 | static Node root; 25 | PathWithMaximumSum() { 26 | root = null; 27 | } 28 | 29 | private static int maxSum; 30 | 31 | private static int findMaxSum(Node root) { 32 | if(root == null) return 0; 33 | 34 | int leftSum = findMaxSum(root.left); 35 | int rightSum = findMaxSum(root.right); 36 | 37 | leftSum = Math.max(leftSum, 0); 38 | rightSum = Math.max(rightSum, 0); 39 | 40 | int currentSum = leftSum + rightSum + root.data; 41 | 42 | maxSum = Math.max(currentSum, maxSum); 43 | return Math.max(leftSum, rightSum) + root.data; 44 | } 45 | 46 | public static int findMaximumPathSum(Node root) { 47 | maxSum = Integer.MIN_VALUE; 48 | findMaxSum(root); 49 | return maxSum; 50 | } 51 | 52 | public static void main (String[] args) { 53 | root = new Node(10); 54 | root.left = new Node(2); 55 | root.right = new Node(10); 56 | root.left.left = new Node(20); 57 | root.left.right = new Node(1); 58 | root.right.left = new Node(-25); 59 | root.right.left.left = new Node(3); 60 | root.right.left.right = new Node(4); 61 | int ans = findMaximumPathSum(root); 62 | System.out.println(ans); 63 | } 64 | } -------------------------------------------------------------------------------- /Java/DFS/SumOfPathNumbers.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 1008 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class BinaryTreePathSum { 23 | 24 | static Node root; 25 | BinaryTreePathSum() { 26 | root = null; 27 | } 28 | 29 | private static int findPathSum(Node root, int pathSum) { 30 | if(root == null) return 0; 31 | 32 | pathSum = pathSum * 10 + root.data; 33 | 34 | if(root.left == null && root.right == null) { 35 | return pathSum; 36 | } 37 | 38 | return findPathSum(root.left, pathSum) + findPathSum(root.right, pathSum); 39 | } 40 | 41 | public static int findSumPathNumbers(Node root) { 42 | return findPathSum(root, 0); 43 | } 44 | 45 | public static void main (String[] args) { 46 | root = new Node(3); 47 | root.left = new Node(7); 48 | root.right = new Node(1); 49 | root.left.left = new Node(9); 50 | root.right.left = new Node(4); 51 | root.right.right = new Node(5); 52 | int ans = findSumPathNumbers(root); 53 | System.out.println(ans); 54 | } 55 | } -------------------------------------------------------------------------------- /Java/DFS/SymmetricTree.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * true 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class SymmetricTree { 23 | 24 | static Node root; 25 | SymmetricTree() { 26 | root = null; 27 | } 28 | 29 | public static boolean findSymmetric(Node root1, Node root2) { 30 | if(root1 == null && root2 == null) 31 | return true; 32 | 33 | if(root1 == null || root2 == null) 34 | return false; 35 | 36 | return (root1.data == root2.data) && 37 | findSymmetric(root1.left, root2.right) && 38 | findSymmetric(root1.right, root2.left); 39 | } 40 | 41 | public static boolean isSymmetric(Node root) { 42 | return findSymmetric(root, root); 43 | } 44 | 45 | public static void main (String[] args) { 46 | root = new Node(1); 47 | root.left = new Node(2); 48 | root.right = new Node(2); 49 | root.left.left = new Node(3); 50 | root.left.right = new Node(4); 51 | root.right.left = new Node(4); 52 | root.right.right = new Node(3); 53 | boolean ans = isSymmetric(root); 54 | System.out.println(ans); 55 | 56 | } 57 | } -------------------------------------------------------------------------------- /Java/DFS/TreeDiameter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 8 7 | * 8 | */ 9 | 10 | import java.util.*; 11 | 12 | class Node { 13 | int data; 14 | Node left, right; 15 | public Node(int key) { 16 | data = key; 17 | left = right = null; 18 | } 19 | } 20 | 21 | 22 | class TreeDiameter { 23 | 24 | static Node root; 25 | TreeDiameter() { 26 | root = null; 27 | } 28 | 29 | static int diameter = 0; 30 | 31 | private static int findHeight(Node root) { 32 | if(root == null) return 0; 33 | 34 | int leftHeight = findHeight(root.left); 35 | int rightHeight = findHeight(root.right); 36 | 37 | int currentDiameter = leftHeight + rightHeight + 1; 38 | 39 | diameter = Math.max(currentDiameter, diameter); 40 | return Math.max(leftHeight, rightHeight) + 1; 41 | } 42 | 43 | public static int findDiameter(Node root) { 44 | findHeight(root); 45 | return diameter; 46 | } 47 | 48 | public static void main (String[] args) { 49 | root = new Node(1); 50 | root.left = new Node(2); 51 | root.right = new Node(3); 52 | root.right.left = new Node(4); 53 | root.right.right = new Node(5); 54 | root.right.left.left = new Node(6); 55 | root.right.right.right = new Node(7); 56 | root.right.right.right.left = new Node(12); 57 | root.right.right.right.right = new Node(13); 58 | root.right.left.left.left = new Node(8); 59 | root.right.left.left.right = new Node(10); 60 | root.right.left.left.right.left = new Node(11); 61 | int ans = findDiameter(root); 62 | System.out.println(ans); 63 | } 64 | } -------------------------------------------------------------------------------- /Java/DisjointSetUnion/DSU.java: -------------------------------------------------------------------------------- 1 | package Java.DisjointSetUnion; 2 | 3 | class UnionFind { 4 | 5 | private int[] parent; 6 | 7 | public UnionFind(int size) { 8 | this.parent = new int[size]; 9 | for(int i = 0; i < size; i++) { 10 | this.parent[i] = i; 11 | } 12 | } 13 | 14 | public int find(int u) { 15 | if(u == this.parent[u]) return u; 16 | return find(parent[u]); 17 | } 18 | 19 | public void union(int u, int v) { 20 | int p1 = find(u); 21 | int p2 = find(v); 22 | if(p1 != p2) { 23 | parent[p2] = p1; 24 | } 25 | } 26 | 27 | public boolean connected(int u, int v) { 28 | return find(u) == find(v); 29 | } 30 | 31 | } 32 | 33 | public class DSU { 34 | // int[][] edges = new int[][]{{0, 1}, {0, 2}, {1, 2}, {1, 3}, {2, 3}, {3, 4}}; 35 | public static void main(String[] args) { 36 | UnionFind obj = new UnionFind(7); 37 | obj.union(0, 1); 38 | obj.union(0, 2); 39 | obj.union(1, 2); 40 | obj.union(1, 3); 41 | obj.union(2, 3); 42 | obj.union(3, 4); 43 | obj.union(5, 6); 44 | System.out.println(obj.connected(1, 3)); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Java/DisjointSetUnion/DSU2.java: -------------------------------------------------------------------------------- 1 | package Java.DisjointSetUnion; 2 | 3 | class UnionFind { 4 | 5 | private int[] parent; 6 | 7 | public UnionFind(int size) { 8 | this.parent = new int[size]; 9 | for(int i = 0; i < size; i++) { 10 | this.parent[i] = i; 11 | } 12 | } 13 | 14 | // O(1) 15 | public int find(int u) { 16 | return parent[u]; 17 | } 18 | 19 | // O(N) 20 | public void union(int u, int v) { 21 | int p1 = find(u); 22 | int p2 = find(v); 23 | if(p1 != p2) { 24 | parent[p2] = p1; 25 | for(int i = 0; i < parent.length; i++) { 26 | if(parent[i] == p2) { 27 | parent[i] = p1; 28 | } 29 | } 30 | } 31 | } 32 | 33 | public boolean connected(int u, int v) { 34 | return find(u) == find(v); 35 | } 36 | 37 | } 38 | 39 | public class DSU2 { 40 | // int[][] edges = new int[][]{{0, 1}, {0, 2}, {1, 2}, {1, 3}, {2, 3}, {3, 4}}; 41 | public static void main(String[] args) { 42 | UnionFind obj = new UnionFind(7); 43 | obj.union(0, 1); 44 | obj.union(0, 2); 45 | obj.union(1, 2); 46 | obj.union(1, 3); 47 | obj.union(2, 3); 48 | obj.union(3, 4); 49 | obj.union(5, 6); 50 | System.out.println(obj.connected(2, 4)); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Java/DisjointSetUnion/DSU_PathCompression.java: -------------------------------------------------------------------------------- 1 | package Java.DisjointSetUnion; 2 | 3 | class UnionFind { 4 | 5 | private int[] parent; 6 | private int[] rank; 7 | 8 | public UnionFind(int size) { 9 | this.parent = new int[size]; 10 | this.rank = new int[size]; 11 | for(int i = 0; i < size; i++) { 12 | this.parent[i] = i; 13 | this.rank[i] = 1; 14 | } 15 | } 16 | 17 | public int find(int u) { 18 | if(u == this.parent[u]) return u; 19 | return parent[u] = find(parent[u]); 20 | } 21 | 22 | public void union(int u, int v) { 23 | int p1 = find(u); 24 | int p2 = find(v); 25 | if(p1 != p2) { 26 | if(rank[p1] > rank[p2]) { 27 | parent[p2] = p1; 28 | } else if(rank[p1] < rank[p2]) { 29 | parent[p1] = p2; 30 | } else { 31 | parent[p2] = p1; 32 | rank[p1] += 1; 33 | } 34 | } 35 | } 36 | 37 | public boolean connected(int u, int v) { 38 | return find(u) == find(v); 39 | } 40 | 41 | } 42 | 43 | public class DSU_PathCompression { 44 | // int[][] edges = new int[][]{{0, 1}, {0, 2}, {1, 2}, {1, 3}, {2, 3}, {3, 4}}; 45 | public static void main(String[] args) { 46 | UnionFind obj = new UnionFind(7); 47 | obj.union(0, 1); 48 | obj.union(0, 2); 49 | obj.union(1, 2); 50 | obj.union(1, 3); 51 | obj.union(2, 3); 52 | obj.union(3, 4); 53 | obj.union(5, 6); 54 | System.out.println(obj.connected(1, 3)); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Java/DisjointSetUnion/DSU_Rank.java: -------------------------------------------------------------------------------- 1 | package Java.DisjointSetUnion; 2 | 3 | class UnionFind { 4 | 5 | private int[] parent; 6 | private int[] rank; 7 | 8 | public UnionFind(int size) { 9 | this.parent = new int[size]; 10 | this.rank = new int[size]; 11 | for(int i = 0; i < size; i++) { 12 | this.parent[i] = i; 13 | this.rank[i] = 1; 14 | } 15 | } 16 | 17 | public int find(int u) { 18 | if(u == this.parent[u]) return u; 19 | return find(parent[u]); 20 | } 21 | 22 | public void union(int u, int v) { 23 | int p1 = find(u); 24 | int p2 = find(v); 25 | if(p1 != p2) { 26 | if(rank[p1] > rank[p2]) { 27 | parent[p2] = p1; 28 | } else if(rank[p1] < rank[p2]) { 29 | parent[p1] = p2; 30 | } else { 31 | parent[p2] = p1; 32 | rank[p1] += 1; 33 | } 34 | } 35 | } 36 | 37 | public boolean connected(int u, int v) { 38 | return find(u) == find(v); 39 | } 40 | 41 | } 42 | 43 | public class DSU_Rank { 44 | // int[][] edges = new int[][]{{0, 1}, {0, 2}, {1, 2}, {1, 3}, {2, 3}, {3, 4}}; 45 | public static void main(String[] args) { 46 | UnionFind obj = new UnionFind(7); 47 | obj.union(0, 1); 48 | obj.union(0, 2); 49 | obj.union(1, 2); 50 | obj.union(1, 3); 51 | obj.union(2, 3); 52 | obj.union(3, 4); 53 | obj.union(5, 6); 54 | System.out.println(obj.connected(1, 3)); 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Java/DynamicProgramming/CountSubset.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class Innoskrit { 4 | 5 | public static int countSubset(int arr[], int target) { 6 | int dp[][] = new int[arr.length + 1][target + 1]; 7 | 8 | for(int col = 0; col < dp[0].length; col++) { 9 | dp[0][col] = 0; 10 | } 11 | 12 | for(int row = 0; row < dp.length; row++) { 13 | dp[row][0] = 1; 14 | } 15 | 16 | for(int i = 1; i < dp.length; i++) { 17 | for(int j = 1; j < dp[0].length; j++) { 18 | if(arr[i - 1] > j) { 19 | dp[i][j] = dp[i - 1][j]; 20 | } else { 21 | dp[i][j] = dp[i - 1][j] + dp[i - 1][j - arr[i - 1]]; 22 | } 23 | } 24 | } 25 | return dp[arr.length][target]; 26 | } 27 | public static void main(String[] args) { 28 | int arr[] = new int[]{1, 4, 6, 3, 9, 2}; 29 | int target = 12; 30 | System.out.println(Innoskrit.countSubset(arr, target)); 31 | } 32 | } -------------------------------------------------------------------------------- /Java/DynamicProgramming/KnapsackMemoized.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class MemoizedKnapsack { 4 | 5 | public static int knapsack(int W, int wt[], int val[], int n, int dp[][]) { 6 | 7 | if(n == 0 || W == 0) { 8 | return 0; 9 | } 10 | if(dp[n][W] != -1) { 11 | return dp[n][W]; 12 | } 13 | if(wt[n - 1] > W) { 14 | return dp[n][W] = knapsack(W, wt, val, n - 1, dp); 15 | } 16 | return dp[n][W] = Math.max(val[n - 1] + knapsack(W - wt[n - 1], wt, val, n - 1, dp), knapsack(W, wt, val, n -1, dp)); 17 | } 18 | public static void main (String[] args) { 19 | int n = 4; 20 | int wt[] = {1, 3, 1, 2}; 21 | int val[] = {10, 5, 30, 20}; 22 | int W = 2; 23 | int dp[][] = new int[n + 1][W + 1]; 24 | for(int i = 0; i <= n; i++) { 25 | for(int j = 0; j <= W; j++) { 26 | dp[i][j] = -1; 27 | } 28 | } 29 | int profit = knapsack(W, wt, val, n, dp); 30 | System.out.println(profit); 31 | } 32 | } -------------------------------------------------------------------------------- /Java/DynamicProgramming/KnapsackTabulation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class KnapsackTabulation { 4 | 5 | public static int knapsack(int W, int wt[], int val[], int n) { 6 | int dp[][] = new int[n + 1][W + 1]; 7 | for(int i = 0; i <= n; i++) { 8 | for(int j = 0; j <= W; j++) { 9 | if(i == 0 || j == 0) { 10 | dp[i][j] = 0; 11 | } 12 | else if(wt[i - 1] > j) { 13 | dp[i][j] = dp[i - 1][j]; 14 | } 15 | else { 16 | dp[i][j] = Math.max(dp[i - 1][j], val[i - 1] + dp[i - 1][j - wt[i - 1]]); 17 | } 18 | } 19 | } 20 | return dp[n][W]; 21 | 22 | } 23 | public static void main (String[] args) { 24 | int n = 4; 25 | int wt[] = {1, 3, 1, 2}; 26 | int val[] = {10, 5, 30, 20}; 27 | int W = 2; 28 | int profit = knapsack(W, wt, val, n); 29 | System.out.println(profit); 30 | } 31 | } -------------------------------------------------------------------------------- /Java/DynamicProgramming/LongestCommonSubsequence.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 4 7 | * 8 | */ 9 | 10 | 11 | class LongestCommonSubsequence { 12 | 13 | public static int longestCommonSubsequence(String a, String b, int m, int n) { 14 | int dp[][] = new int[m + 1][n + 1]; 15 | for(int i = 0; i <= m; i++) { 16 | for(int j = 0; j <= n; j++) { 17 | if(i == 0 || j == 0) { 18 | dp[i][j] = 0; 19 | } 20 | else if(a.charAt(i - 1) == b.charAt(j - 1)) { 21 | dp[i][j] = 1 + dp[i - 1][j - 1]; 22 | } 23 | else { 24 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 25 | } 26 | } 27 | } 28 | return dp[m][n]; 29 | } 30 | public static void main(String[] args) { 31 | String a = "AGGTAB"; 32 | String b = "GXTXAYB"; 33 | int lcs = longestCommonSubsequence(a, b, a.length(), b.length()); 34 | System.out.println(lcs); 35 | } 36 | } -------------------------------------------------------------------------------- /Java/DynamicProgramming/LongestCommonSubstring.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 3 7 | * 8 | */ 9 | 10 | 11 | class LongestCommonSubstring { 12 | 13 | public static int longestCommonSubstring(String a, String b, int m, int n) { 14 | int dp[][] = new int[m + 1][n + 1]; 15 | for(int i = 0; i <= m; i++) { 16 | for(int j = 0; j <= n; j++) { 17 | if(i == 0 || j == 0) { 18 | dp[i][j] = 0; 19 | } 20 | else if(a.charAt(i - 1) == b.charAt(j - 1)) { 21 | dp[i][j] = 1 + dp[i - 1][j - 1]; 22 | } 23 | else { 24 | dp[i][j] = 0; 25 | } 26 | } 27 | } 28 | return dp[m][n]; 29 | } 30 | public static void main(String[] args) { 31 | String a = "AGGTAB"; 32 | String b = "GXTAB"; 33 | int lcs = longestCommonSubstring(a, b, a.length(), b.length()); 34 | System.out.println(lcs); 35 | } 36 | } -------------------------------------------------------------------------------- /Java/DynamicProgramming/SubsetSumTabulation.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class SubsetSum { 4 | 5 | public static boolean subsetSum(int sum, int arr[], int n) { 6 | boolean dp[][] = new boolean[n + 1][sum + 1]; 7 | for(int i = 0; i <= sum; i++) { 8 | dp[0][i] = false; 9 | } 10 | for(int i = 0; i <= n; i++) { 11 | dp[i][0] = true; 12 | } 13 | 14 | for(int i = 1; i <= n; i++) { 15 | for(int j = 1; j <= sum; j++) { 16 | if(arr[i - 1] > j) { 17 | dp[i][j] = dp[i - 1][j]; 18 | } 19 | else { 20 | dp[i][j] = dp[i - 1][j] || dp[i - 1][j - arr[i - 1]]; 21 | } 22 | } 23 | } 24 | return dp[n][sum]; 25 | 26 | } 27 | public static void main (String[] args) { 28 | int n = 5; 29 | int arr[] = {6, 19, 4, 10, 1}; 30 | int sum = 11; 31 | boolean ans = subsetSum(sum, arr, n); 32 | System.out.println(ans); 33 | } 34 | } -------------------------------------------------------------------------------- /Java/Graph/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Java/Graph/.DS_Store -------------------------------------------------------------------------------- /Java/Graph/BreadthFirstSearch.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Output: 7 | * 2 0 1 3 8 | * 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class Graph { 14 | 15 | int vertices; 16 | LinkedList adjacencyList[]; 17 | 18 | @SuppressWarnings("unchecked") 19 | public Graph(int vertices) { 20 | this.vertices = vertices; 21 | adjacencyList = new LinkedList[vertices]; 22 | 23 | for (int i = 0; i < vertices; i++) { 24 | adjacencyList[i] = new LinkedList<>(); 25 | } 26 | } 27 | 28 | public void addEdge(int source, int destination) { 29 | this.adjacencyList[source].add(destination); 30 | this.adjacencyList[destination].add(source); // for directed graph comment this line 31 | } 32 | 33 | public List breadthFirstSearch(int source) { 34 | List bfs = new ArrayList<>(); 35 | Queue q = new LinkedList<>(); 36 | boolean[] visited = new boolean[vertices]; 37 | q.offer(source); 38 | visited[source] = true; 39 | while(!q.isEmpty()) { 40 | int curr = q.poll(); 41 | bfs.add(curr); 42 | for(int nbr : adjacencyList[curr]) { 43 | if(visited[nbr] == false) { 44 | q.offer(nbr); 45 | visited[nbr] = true; 46 | } 47 | } 48 | } 49 | return bfs; 50 | } 51 | 52 | public static void main( String args[] ) { 53 | Graph g = new Graph(4); 54 | g.addEdge(0, 1); 55 | g.addEdge(0, 2); 56 | g.addEdge(1, 2); 57 | g.addEdge(2, 3); 58 | List ans = g.breadthFirstSearch(2); 59 | for(int ele : ans) { 60 | System.out.print(ele + " "); 61 | } 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /Java/Graph/DepthFirstSearch.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Output: 7 | * 0 1 2 3 4 5 8 | * 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class Graph { 14 | 15 | int vertices; 16 | LinkedList adjacencyList[]; 17 | 18 | @SuppressWarnings("unchecked") 19 | public Graph(int vertices) { 20 | this.vertices = vertices; 21 | adjacencyList = new LinkedList[vertices]; 22 | 23 | for (int i = 0; i < vertices; i++) { 24 | adjacencyList[i] = new LinkedList<>(); 25 | } 26 | } 27 | 28 | public void addEdge(int source, int destination) { 29 | this.adjacencyList[source].add(destination); 30 | this.adjacencyList[destination].add(source); // for directed graph comment this line 31 | } 32 | 33 | public void dfsUtil(int node, boolean[] visited, List dfs) { 34 | dfs.add(node); 35 | visited[node] = true; 36 | for(int child : adjacencyList[node]) { 37 | if(!visited[child]) { 38 | dfsUtil(child, visited, dfs); 39 | visited[child] = true; 40 | } 41 | } 42 | } 43 | 44 | public List depthFirstSearch(int source) { 45 | List dfs = new ArrayList<>(); 46 | boolean[] visited = new boolean[vertices]; 47 | dfsUtil(source, visited, dfs); 48 | return dfs; 49 | } 50 | 51 | public static void main( String args[] ) { 52 | Graph g = new Graph(6); 53 | g.addEdge(0, 1); 54 | g.addEdge(1, 2); 55 | g.addEdge(2, 3); 56 | g.addEdge(2, 4); 57 | g.addEdge(4, 5); 58 | List ans = g.depthFirstSearch(0); 59 | for(int ele : ans) { 60 | System.out.print(ele + " "); 61 | } 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /Java/Graph/DijkstrasAlgorithm.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Java/Graph/DijkstrasAlgorithm.class -------------------------------------------------------------------------------- /Java/Graph/Graph-Representation-Adjacency-List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Output: 7 | * Adjacency List of Undirected Graph 8 | * |0| => 1 2 9 | * |1| => 0 3 10 | * |2| => 0 3 11 | * |3| => 1 2 12 | * 13 | */ 14 | 15 | import java.util.*; 16 | 17 | class Graph { 18 | 19 | int vertices; 20 | LinkedList adjacencyList[]; 21 | 22 | @SuppressWarnings("unchecked") 23 | public Graph(int vertices) { 24 | this.vertices = vertices; 25 | adjacencyList = new LinkedList[vertices]; 26 | 27 | for (int i = 0; i < vertices; i++) { 28 | adjacencyList[i] = new LinkedList<>(); 29 | } 30 | } 31 | 32 | public void addEdge(int source, int destination) { 33 | this.adjacencyList[source].add(destination); 34 | this.adjacencyList[destination].add(source); // for directed graph comment this line 35 | } 36 | 37 | public void printGraph() { 38 | System.out.println("Adjacency List of Undirected Graph"); 39 | for (int i = 0; i < vertices; i++) { 40 | System.out.print("|" + i + "| => "); 41 | for(int nbr : adjacencyList[i]) { 42 | System.out.print(nbr + " "); 43 | } 44 | System.out.println(); 45 | } 46 | } 47 | 48 | public static void main( String args[] ) { 49 | Graph g = new Graph(4); 50 | g.addEdge(0, 1); 51 | g.addEdge(0, 2); 52 | g.addEdge(1, 3); 53 | g.addEdge(2, 3); 54 | 55 | g.printGraph(); 56 | } 57 | 58 | } -------------------------------------------------------------------------------- /Java/Graph/Pair.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Java/Graph/Pair.class -------------------------------------------------------------------------------- /Java/Graph/PrimsAlgorithm.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Java/Graph/PrimsAlgorithm.class -------------------------------------------------------------------------------- /Java/Graph/ShortestReachHackerRank.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Problem Link: https://www.hackerrank.com/challenges/bfsshortreach/problem 7 | * Note: I have completed the function only. 8 | * 9 | */ 10 | 11 | public static List bfs(int n, int m, List> edges, int s) { 12 | List distance = new ArrayList<>(n + 1); 13 | Queue q = new LinkedList<>(); 14 | boolean visited[] = new boolean[n + 1]; 15 | q.offer(s); 16 | visited[s] = true; 17 | distance[] 18 | distance.set(s, 0); 19 | 20 | @SuppressWarnings("unchecked") 21 | LinkedList adjacencyList[] = new LinkedList[n + 1]; 22 | for(List edge : edges) { 23 | adjacencyList[edge.get(0)].add(edge.get(1)); 24 | adjacencyList[edge.get(1)].add(edge.get(0)); 25 | } 26 | 27 | while(!q.isEmpty()) { 28 | int curr = q.poll(); 29 | for(int nbr : adjacencyList[curr]) { 30 | if(visited[nbr] == false) { 31 | q.offer(nbr); 32 | visited[nbr] = true; 33 | distance.set(nbr, distance.get(curr) + 6); 34 | } 35 | } 36 | } 37 | return distance; 38 | } 39 | -------------------------------------------------------------------------------- /Java/Heap/KClosestPointToOrigin.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Point { 4 | int x; 5 | int y; 6 | int d; 7 | public Point(int x, int y, int d) { 8 | this.x = x; 9 | this.y = y; 10 | this.d = d; 11 | } 12 | } 13 | 14 | class KClosestPointToOrigin { 15 | public int[][] kClosest(int[][] points, int k) { 16 | PriorityQueue maxHeap = new PriorityQueue<>((p1, p2) -> p2.d - p1.d); 17 | for(int point[] : points) { 18 | int x = point[0]; 19 | int y = point[1]; 20 | int dist = (x * x) + (y * y); 21 | Point p = new Point(x, y, dist); 22 | maxHeap.offer(point); 23 | if(maxHeap.size() > k) { 24 | maxHeap.poll(); 25 | } 26 | } 27 | 28 | int ans[][] = new int[k][2]; 29 | int i = 0; 30 | while(!maxHeap.isEmpty()) { 31 | Point p = maxHeap.poll(); 32 | ans[i][0] = p.x; 33 | ans[i][1] = p.y; 34 | i += 1; 35 | } 36 | return ans; 37 | } 38 | } -------------------------------------------------------------------------------- /Java/Heap/KthLargestElement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class KthLargestElement { 14 | 15 | public static int findKthLargestNumber(int[] nums, int k) { 16 | PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a - b); 17 | for(int i = 0; i < k; i++) { 18 | minHeap.add(nums[i]); 19 | } 20 | 21 | for(int i = k; i < nums.length; i++) { 22 | if(nums[i] > minHeap.peek()) { 23 | minHeap.poll(); 24 | minHeap.add(nums[i]); 25 | } 26 | } 27 | return minHeap.peek(); 28 | } 29 | 30 | public static void main(String[] args) { 31 | int result = KthLargestElement.findKthLargestNumber(new int[] {3, 1, 5, 12, 2, 11}, 3); 32 | System.out.println(result); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /Java/Heap/KthSmallestElement.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class KthSmallestElement { 14 | 15 | public static int findKthSmallestNumber(int[] nums, int k) { 16 | PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b - a); 17 | for(int i = 0; i < k; i++) { 18 | maxHeap.add(nums[i]); 19 | } 20 | 21 | for(int i = k; i < nums.length; i++) { 22 | if(nums[i] < maxHeap.peek()) { 23 | maxHeap.poll(); 24 | maxHeap.add(nums[i]); 25 | } 26 | } 27 | return maxHeap.peek(); 28 | } 29 | 30 | public static void main(String[] args) { 31 | int result = KthSmallestElement.findKthSmallestNumber(new int[] {3, 1, 5, 12, 2, 11}, 3); 32 | System.out.println(result); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /Java/Heap/Largest_K_Elements.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class Largest_K_Elements { 14 | 15 | public static List findKLargestNumbers(int[] nums, int k) { 16 | PriorityQueue minHeap = new PriorityQueue<>((a, b) -> a - b); 17 | for(int i = 0; i < k; i++) { 18 | minHeap.add(nums[i]); 19 | } 20 | 21 | for(int i = k; i < nums.length; i++) { 22 | if(nums[i] > minHeap.peek()) { 23 | minHeap.poll(); 24 | minHeap.add(nums[i]); 25 | } 26 | } 27 | return new ArrayList<>(minHeap); 28 | } 29 | 30 | public static void main(String[] args) { 31 | List result = Largest_K_Elements.findKLargestNumbers(new int[] {3, 1, 5, 12, 2, 11}, 3); 32 | System.out.println(result); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /Java/Heap/ReorganizeString.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | 12 | import java.util.*; 13 | 14 | class Solution { 15 | public String reorganizeString(String string) { 16 | 17 | Map map = new HashMap<>(); 18 | for(char ch : string.toCharArray()) { 19 | map.put(ch, map.getOrDefault(ch, 0) + 1); 20 | } 21 | 22 | PriorityQueue> maxHeap = new PriorityQueue<>((e1, e2) -> e2.getValue() - e1.getValue()); 23 | 24 | maxHeap.addAll(map.entrySet()); 25 | 26 | Map.Entry first = null; 27 | StringBuilder ans = new StringBuilder(""); 28 | while(!maxHeap.isEmpty()) { 29 | Map.Entry second = maxHeap.poll(); 30 | if(first != null && first.getValue() > 0) { 31 | maxHeap.offer(first); 32 | } 33 | ans.append(second.getKey()); 34 | second.setValue(second.getValue() - 1); 35 | first = second; 36 | } 37 | 38 | if(ans.length() == string.length()) { 39 | return ans.toString(); 40 | } 41 | else { 42 | return ""; 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /Java/Heap/Smallest_K_Elements.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class Smallest_K_Elements { 14 | 15 | public static List findKSmallestNumbers(int[] nums, int k) { 16 | PriorityQueue maxHeap = new PriorityQueue<>((a, b) -> b - a); 17 | for(int i = 0; i < k; i++) { 18 | maxHeap.add(nums[i]); 19 | } 20 | 21 | for(int i = k; i < nums.length; i++) { 22 | if(nums[i] < maxHeap.peek()) { 23 | maxHeap.poll(); 24 | maxHeap.add(nums[i]); 25 | } 26 | } 27 | return new ArrayList<>(maxHeap); 28 | } 29 | 30 | public static void main(String[] args) { 31 | List result = Smallest_K_Elements.findKSmallestNumbers(new int[] {3, 1, 5, 12, 2, 11}, 3); 32 | System.out.println(result); 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /Java/Heap/SortCharactersByFrequency.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | * Instagram: https://www.instagram.com/aakashverma1102/ 7 | * LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | * 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class SortCharactersByFrequency { 14 | 15 | public static String sortCharactersByFrequency(String s) { 16 | HashMap frequencyMap = new HashMap<>(); 17 | for(char ch : s.toCharArray()) { 18 | frequencyMap.put(ch, frequencyMap.getOrDefault(ch, 0) + 1); 19 | } 20 | 21 | PriorityQueue> maxHeap = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue()); 22 | for(Map.Entry entry : frequencyMap.entrySet()) { 23 | maxHeap.offer(entry); 24 | } 25 | StringBuilder sortedString = new StringBuilder(); 26 | while(!maxHeap.isEmpty()) { 27 | Map.Entry entry = maxHeap.poll(); 28 | for(int i = 0; i < entry.getValue(); i++) { 29 | sortedString.append(entry.getKey()); 30 | } 31 | } 32 | return sortedString.toString(); 33 | } 34 | 35 | public static void main(String[] args) { 36 | String result = SortCharactersByFrequency.sortCharactersByFrequency("tree"); 37 | System.out.println(result); 38 | } 39 | 40 | } -------------------------------------------------------------------------------- /Java/MergeIntervals/InsertInterval.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Innoskrit { 4 | public static int[][] insert(int[][] intervals, int[] newInterval) { 5 | 6 | int i = 0; 7 | List ans = new ArrayList<>(); 8 | while(i < intervals.length && intervals[i][1] < newInterval[0]) { 9 | ans.add(intervals[i]); 10 | i += 1; 11 | } 12 | 13 | while(i < intervals.length && intervals[i][0] <= newInterval[1]) { 14 | newInterval[0] = Math.min(newInterval[0], intervals[i][0]); 15 | newInterval[1] = Math.max(newInterval[1], intervals[i][1]); 16 | i += 1; 17 | } 18 | ans.add(newInterval); 19 | 20 | while(i < intervals.length) { 21 | ans.add(intervals[i]); 22 | i += 1; 23 | } 24 | 25 | return ans.toArray(new int[ans.size()][2]); 26 | } 27 | 28 | public static void main(String[] args) { 29 | int intervals[][] = new int[][]{{1, 3}, {5, 7}, {8, 12}}; 30 | int newInterval[] = new int[]{4, 6}; 31 | for (int[] interval : Innoskrit.insert(intervals, newInterval)) 32 | System.out.print("[" + interval[0] + "," + interval[1] + "] "); 33 | System.out.println(); 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /Java/MergeIntervals/IntervalsIntersection.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Innoskrit { 4 | public int[][] intervalIntersection(int[][] arr1, int[][] arr2) { 5 | List ans = new ArrayList<>(); 6 | 7 | int i = 0, j = 0; 8 | 9 | while(i < arr1.length && j < arr2.length) { 10 | int intersection[] = new int[2]; 11 | intersection[0] = Math.max(arr1[i][0], arr2[j][0]); 12 | intersection[1] = Math.min(arr1[i][1], arr2[j][1]); 13 | 14 | if(intersection[0] <= intersection[1]) { 15 | ans.add(intersection); 16 | } 17 | 18 | if(arr1[i][1] < arr2[j][1]) { 19 | i += 1; 20 | } else { 21 | j += 1; 22 | } 23 | } 24 | return ans.toArray(new int[ans.size()][2]); 25 | } 26 | 27 | public static void main(String[] args) { 28 | int arr1[][] = new int[][]{{1, 3}, {5, 6}, {7, 9}}; 29 | int arr2[][] = new int[][]{{2, 3}, {5, 7}}; 30 | for (int[] interval : Innoskrit.intervalIntersection(arr1, arr2)) 31 | System.out.print("[" + interval[0] + "," + interval[1] + "] "); 32 | System.out.println(); 33 | } 34 | } -------------------------------------------------------------------------------- /Java/Recursion/CountSubset.java: -------------------------------------------------------------------------------- 1 | class CountSubset { 2 | 3 | public static int solve(int arr[], int target, int n) { 4 | if(target == 0) return 1; 5 | if(n == 0) return 0; 6 | 7 | if(arr[n - 1] > target) { 8 | return solve(arr, target, n - 1); 9 | } 10 | 11 | return solve(arr, target - arr[n - 1], n - 1) + solve(arr, target, n - 1); 12 | 13 | } 14 | 15 | public static int countSubset(int arr[], int target) { 16 | return solve(arr, target, arr.length); 17 | } 18 | public static void main(String[] args) { 19 | int arr[] = new int[]{1, 4, 6, 3, 9, 2}; 20 | int target = 12; 21 | System.out.println(CountSubset.countSubset(arr, target)); 22 | } 23 | } -------------------------------------------------------------------------------- /Java/Recursion/Fibonacci.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Java/Recursion/Fibonacci.class -------------------------------------------------------------------------------- /Java/Recursion/Fibonacci.java: -------------------------------------------------------------------------------- 1 | class Fibonacci { 2 | 3 | static int fibonacci(int n) { 4 | if(n == 1 || n == 2) { 5 | return 1; 6 | } 7 | return fibonacci(n - 1) + fibonacci(n - 2); 8 | } 9 | 10 | public static void main(String[] args) { 11 | int n = 10; 12 | System.out.println(fibonacci(n)); 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /Java/Recursion/Handshake.java: -------------------------------------------------------------------------------- 1 | class Handshake { 2 | 3 | static int handshake(int n) { 4 | if(n == 1) 5 | return 0; 6 | return (n - 1) + handshake(n - 1); 7 | } 8 | 9 | public static void main(String[] args) { 10 | int n = 10; 11 | System.out.println(handshake(n)); 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /Java/Recursion/Knapsack.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class Knapsack { 4 | 5 | public static int knapsack(int W, int wt[], int val[], int n) { 6 | if(n == 0 || W == 0) { 7 | return 0; 8 | } 9 | if(wt[n - 1] > W) { 10 | return knapsack(W, wt, val, n - 1); 11 | } 12 | return Math.max(val[n - 1] + knapsack(W - wt[n - 1], wt, val, n - 1), knapsack(W, wt, val, n -1)); 13 | } 14 | public static void main (String[] args) { 15 | int n = 4; 16 | int wt[] = {1, 3, 1, 2}; 17 | int val[] = {10, 5, 30, 20}; 18 | int W = 2; 19 | int profit = knapsack(W, wt, val, n); 20 | System.out.println(profit); 21 | } 22 | } -------------------------------------------------------------------------------- /Java/Recursion/SubsetSum.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class SubsetSum { 4 | 5 | public static boolean subsetSum(int sum, int arr[], int n) { 6 | if(sum == 0) { 7 | return true; 8 | } 9 | if(n == 0) { 10 | return false; 11 | } 12 | if(arr[n - 1] > sum) { 13 | return subsetSum(sum, arr, n - 1); 14 | } 15 | return subsetSum(sum - arr[n - 1], arr, n - 1) || subsetSum(sum, arr, n - 1); 16 | } 17 | public static void main (String[] args) { 18 | int n = 5; 19 | int arr[] = {6, 19, 4, 10, 1}; 20 | int sum = 11; 21 | boolean ans = subsetSum(sum, arr, n); 22 | System.out.println(ans); 23 | } 24 | } -------------------------------------------------------------------------------- /Java/SlidingWindow/MaxSubarraySum.java: -------------------------------------------------------------------------------- 1 | package abes.slidingwindow; 2 | 3 | public class MaxSubarraySum { 4 | 5 | public static int maxSubarraySum(int arr[], int k) { 6 | int windowStart = 0; 7 | int windowSum = 0; 8 | int maxSum = Integer.MIN_VALUE; 9 | for(int windowEnd = 0; windowEnd < arr.length; windowEnd++) { 10 | windowSum += arr[windowEnd]; 11 | if(windowEnd >= k - 1) { 12 | maxSum = Math.max(maxSum, windowSum); 13 | windowSum -= arr[windowStart]; 14 | windowStart += 1; 15 | } 16 | } 17 | return maxSum; 18 | } 19 | 20 | public static void main(String[] args) { 21 | int arr[] = new int[]{1, 2, 3, 4, 5, 6}; 22 | int k = 3; 23 | 24 | int maxSum = MaxSubarraySum.maxSubarraySum(arr, k); 25 | System.out.println(maxSum); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/SlidingWindow/MinimumLengthSubarrayWithGivenSum.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Java/SlidingWindow/MinimumLengthSubarrayWithGivenSum.java -------------------------------------------------------------------------------- /Java/SlidingWindow/SubarrayAverage.java: -------------------------------------------------------------------------------- 1 | package abes.slidingwindow; 2 | 3 | public class AverageSubarray { 4 | 5 | public static double[] averageSubarray(int arr[], int k) { 6 | double ans[] = new double[arr.length - k + 1]; 7 | int windowStart = 0; 8 | int windowSum = 0; 9 | for(int windowEnd = 0; windowEnd < arr.length; windowEnd++) { 10 | windowSum += arr[windowEnd]; 11 | if(windowEnd >= k - 1) { 12 | ans[windowStart] = (double) windowSum/k; 13 | windowSum -= arr[windowStart]; 14 | windowStart += 1; 15 | } 16 | } 17 | return ans; 18 | } 19 | 20 | public static int maxSubarraySum(int arr[], int k) { 21 | int windowStart = 0; 22 | int windowSum = 0; 23 | int maxSum = Integer.MIN_VALUE; 24 | for(int windowEnd = 0; windowEnd < arr.length; windowEnd++) { 25 | windowSum += arr[windowEnd]; 26 | if(windowEnd >= k - 1) { 27 | maxSum = Math.max(maxSum, windowSum); 28 | windowSum -= arr[windowStart]; 29 | windowStart += 1; 30 | } 31 | } 32 | return maxSum; 33 | } 34 | 35 | public static void main(String[] args) { 36 | int arr[] = new int[]{1, 2, 3, 4, 5, 6}; 37 | int k = 3; 38 | double ans[] = AverageSubarray.averageSubarray(arr, k); 39 | for(double a : ans) { 40 | System.out.print(a + " "); 41 | } 42 | System.out.println(); 43 | int maxSum = AverageSubarray.maxSubarraySum(arr, k); 44 | System.out.println(maxSum); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Java/Sorting/InversionCount.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 10 7 | * 8 | */ 9 | 10 | class InversionCount { 11 | 12 | static int inversion_count = 0; 13 | public static void merge(int arr[], int low, int mid, int high) { 14 | int temp[] = new int[high - low + 1]; 15 | int i = low; 16 | int j = mid + 1; 17 | int k = 0; 18 | while(i <= mid && j <= high) { 19 | if(arr[i] <= arr[j]) { 20 | temp[k] = arr[i]; 21 | i += 1; 22 | } 23 | else { 24 | temp[k] = arr[j]; 25 | j += 1; 26 | inversion_count += (mid - i + 1); 27 | } 28 | k += 1; 29 | } 30 | while(i <= mid) { 31 | temp[k] = arr[i]; 32 | i += 1; 33 | k += 1; 34 | } 35 | while(j <= high) { 36 | temp[k] = arr[j]; 37 | j += 1; 38 | k += 1; 39 | } 40 | for(int p = low; p <= high; p++) { 41 | arr[p] = temp[p - low]; 42 | } 43 | } 44 | 45 | public static void mergeSort(int arr[], int low, int high) { 46 | if(low < high) { 47 | int mid = low + (high - low)/2; 48 | mergeSort(arr, low, mid); 49 | mergeSort(arr, mid + 1, high); 50 | merge(arr, low, mid, high); 51 | } 52 | } 53 | public static void main (String[] args) { 54 | int arr[] = {5, 4, 3, 2, 1}; 55 | int n = 5; 56 | mergeSort(arr, 0, n - 1); 57 | System.out.println(inversion_count); 58 | } 59 | } -------------------------------------------------------------------------------- /Java/Sorting/MergeSort.java: -------------------------------------------------------------------------------- 1 | /* 2 | * @author 3 | * Aakash Verma 4 | * 5 | * Output: 6 | * 5 10 11 20 26 34 50 89 7 | * 8 | */ 9 | 10 | class MergeSort { 11 | 12 | public static void merge(int arr[], int low, int mid, int high) { 13 | int temp[] = new int[high - low + 1]; 14 | int i = low; 15 | int j = mid + 1; 16 | int k = 0; 17 | while(i <= mid && j <= high) { 18 | if(arr[i] <= arr[j]) { 19 | temp[k] = arr[i]; 20 | i += 1; 21 | } 22 | else { 23 | temp[k] = arr[j]; 24 | j += 1; 25 | } 26 | k += 1; 27 | } 28 | while(i <= mid) { 29 | temp[k] = arr[i]; 30 | i += 1; 31 | k += 1; 32 | } 33 | while(j <= high) { 34 | temp[k] = arr[j]; 35 | j += 1; 36 | k += 1; 37 | } 38 | for(int p = low; p <= high; p++) { 39 | arr[p] = temp[p - low]; 40 | } 41 | } 42 | 43 | public static void mergeSort(int arr[], int low, int high) { 44 | if(low < high) { 45 | int mid = low + (high - low)/2; 46 | mergeSort(arr, low, mid); 47 | mergeSort(arr, mid + 1, high); 48 | merge(arr, low, mid, high); 49 | } 50 | } 51 | public static void main (String[] args) { 52 | int arr[] = {10, 20, 5, 50, 34, 26, 89, 11}; 53 | int n = arr.length; 54 | mergeSort(arr, 0, n - 1); 55 | for(int i = 0; i < arr.length; i++) { 56 | System.out.print(arr[i] + " "); 57 | } 58 | } 59 | } -------------------------------------------------------------------------------- /Java/Stack/NGEL.java: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: Given an array, print the Next Greater Element (NGE) for every element. 6 | The Next Greater Element for an element x is the first greater element 7 | on the left side of x in array. Elements for which no greater element exist, 8 | consider next greater element as -1. 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class NGEL { 14 | 15 | public static ArrayList nextGreaterElementToLeft(int arr[], int n) { 16 | ArrayList v = new ArrayList<>(); 17 | Stack s = new Stack<>(); 18 | 19 | for(int i = 0; i < n; i++) { 20 | while(!s.empty() && s.peek() < arr[i]) { 21 | s.pop(); 22 | } 23 | if(s.empty()) { 24 | v.add(-1); 25 | } 26 | else { 27 | v.add(s.peek()); 28 | } 29 | s.push(arr[i]); 30 | } 31 | return v; 32 | } 33 | 34 | public static void main(String[] args) { 35 | 36 | int arr[] = {7, 8, 1, 4}; 37 | ArrayList ans = nextGreaterElementToLeft(arr, arr.length); 38 | System.out.println(ans.toString()); 39 | 40 | } 41 | } -------------------------------------------------------------------------------- /Java/Stack/NGER.java: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: Given an array, find an array of Greater Elements (NGE) for every element. 6 | The Next Greater Element for an element x is the first greater element 7 | on the right side of x in array. Elements for which no greater element exist, 8 | consider next greater element as -1. 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class NGER { 14 | 15 | public static ArrayList nextGreaterElementToRight(int arr[], int n) { 16 | ArrayList v = new ArrayList<>(); 17 | Stack s = new Stack<>(); 18 | 19 | for(int i = n - 1; i >= 0; i--) { 20 | while(!s.empty() && s.peek() <= arr[i]) { 21 | s.pop(); 22 | } 23 | if(s.empty()) { 24 | v.add(-1); 25 | } 26 | else { 27 | v.add(s.peek()); 28 | } 29 | s.push(arr[i]); 30 | } 31 | Collections.reverse(v); 32 | return v; 33 | } 34 | 35 | public static void main(String[] args) { 36 | 37 | int arr[] = {7, 8, 1, 4}; 38 | ArrayList ans = nextGreaterElementToRight(arr, arr.length); 39 | System.out.println(ans.toString()); 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /Java/Stack/NSEL.java: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: Given an array, print the Next Smaller Element (NSE) for every element. 6 | The Next Smaller Element for an element x is the first smaller element 7 | on the left side of x in array. Elements for which no smaller element exist, 8 | consider next smaller element as -1. 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class NSEL { 14 | 15 | public static ArrayList nextSmallerElementToLeft(int arr[], int n) { 16 | ArrayList v = new ArrayList<>(); 17 | Stack s = new Stack<>(); 18 | 19 | for(int i = 0; i < n; i++) { 20 | while(!s.empty() && s.peek() >= arr[i]) { 21 | s.pop(); 22 | } 23 | if(s.empty()) { 24 | v.add(-1); 25 | } 26 | else { 27 | v.add(s.peek()); 28 | } 29 | s.push(arr[i]); 30 | } 31 | return v; 32 | } 33 | 34 | public static void main(String[] args) { 35 | 36 | int arr[] = {7, 8, 1, 4}; 37 | ArrayList ans = nextSmallerElementToLeft(arr, arr.length); 38 | System.out.println(ans.toString()); 39 | 40 | } 41 | } -------------------------------------------------------------------------------- /Java/Stack/NSER.java: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: Given an array, print the Next Smaller Element (NSE) for every element. 6 | The Next Smaller Element for an element x is the first smaller element 7 | on the right side of x in array. Elements for which no smaller element exist, 8 | consider next smaller element as -1. 9 | */ 10 | 11 | import java.util.*; 12 | 13 | class NSER { 14 | 15 | public static ArrayList nextSmallerElementToRight(int arr[], int n) { 16 | ArrayList v = new ArrayList<>(); 17 | Stack s = new Stack<>(); 18 | 19 | for(int i = n - 1; i >= 0; i--) { 20 | while(!s.empty() && s.peek() >= arr[i]) { 21 | s.pop(); 22 | } 23 | if(s.empty()) { 24 | v.add(-1); 25 | } 26 | else { 27 | v.add(s.peek()); 28 | } 29 | s.push(arr[i]); 30 | } 31 | Collections.reverse(v); 32 | return v; 33 | } 34 | 35 | public static void main(String[] args) { 36 | 37 | int arr[] = {7, 8, 1, 4}; 38 | ArrayList ans = nextSmallerElementToRight(arr, arr.length); 39 | System.out.println(ans.toString()); 40 | 41 | } 42 | } -------------------------------------------------------------------------------- /Java/Stack/StockSpan.java: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: 6 | The stock span problem is a financial problem where we have a series of 7 | n daily price quotes for a stock and we need to calculate span of stock’s 8 | price for all n days. 9 | The span Si of the stock’s price on a given day i is defined as the maximum 10 | number of consecutive days just before the given day, for which the price 11 | of the stock on the current day is less than or equal to its price on the 12 | given day. 13 | */ 14 | 15 | import java.util.*; 16 | 17 | class StockSpan { 18 | 19 | public static ArrayList getSpanArray(int arr[]) { 20 | 21 | ArrayList ans = new ArrayList<>(); 22 | 23 | /* Creating Stack to put span & price */ 24 | Stack prices = new Stack<>(); 25 | Stack span = new Stack<>(); 26 | prices.push(arr[0]); 27 | span.push(1); 28 | ans.add(1); 29 | 30 | for(int i = 1; i < arr.length; i++) { 31 | int count = 1; 32 | while(!prices.empty() && prices.peek() < arr[i]) { 33 | count += span.peek(); 34 | prices.pop(); 35 | span.pop(); 36 | } 37 | span.push(count); 38 | prices.push(arr[i]); 39 | ans.add(count); 40 | } 41 | return ans; 42 | } 43 | 44 | public static void main(String[] args) { 45 | int arr[] = {10, 4, 5, 90, 120, 80}; 46 | ArrayList ans = getSpanArray(arr); 47 | System.out.println(ans.toString()); 48 | } 49 | } -------------------------------------------------------------------------------- /Java/Stack/StockSpan2.java: -------------------------------------------------------------------------------- 1 | /* 2 | @author 3 | Aakash.Verma 4 | 5 | Problem: The stock span problem is a financial problem where we have a 6 | series of n daily price quotes for a stock and we need to calculate span 7 | of stock’s price for all n days. 8 | The span Si of the stock’s price on a given day i is defined as the 9 | maximum number of consecutive days just before the given day, for which 10 | the price of the stock on the current day is less than or equal to its 11 | price on the given day. 12 | 13 | Output: [1, 1, 1, 2, 1, 4, 6] 14 | */ 15 | 16 | import java.util.*; 17 | 18 | class StockSpan { 19 | 20 | public static ArrayList stockSpan(int arr[], int n) { 21 | ArrayList v = new ArrayList<>(); 22 | ArrayList span = new ArrayList<>(); 23 | Stack> s = new Stack<>(); 24 | 25 | for(int i = 0; i < n; i++) { 26 | while(!s.empty() && s.peek().get(0) <= arr[i]) { 27 | s.pop(); 28 | } 29 | if(s.empty()) { 30 | v.add(-1); 31 | } 32 | else { 33 | v.add(s.peek().get(1)); 34 | } 35 | 36 | ArrayList tempList = new ArrayList<>(); 37 | tempList.add(arr[i]); 38 | tempList.add(i); 39 | s.push(tempList); 40 | } 41 | for(int i = 0; i < n; i++) { 42 | span.add(i - v.get(i)); 43 | } 44 | return span; 45 | } 46 | 47 | public static void main(String[] args) { 48 | 49 | int arr[] = {100, 80, 60, 70, 60, 75, 85}; 50 | ArrayList ans = stockSpan(arr, arr.length); 51 | System.out.println(ans.toString()); 52 | 53 | } 54 | } -------------------------------------------------------------------------------- /Java/TopologicalSort/AlienDictionary.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Java/TopologicalSort/AlienDictionary.class -------------------------------------------------------------------------------- /Java/TreeConstructions/TreeFromInorderPostorder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author 4 | * aakash.verma 5 | * 6 | */ 7 | 8 | class TreeNode { 9 | int val; 10 | TreeNode left; 11 | TreeNode right; 12 | TreeNode(int val, TreeNode left, TreeNode right) { 13 | this.val = val; 14 | this.left = left; 15 | this.right = right; 16 | } 17 | } 18 | 19 | class Solution { 20 | 21 | /* LeetCode Code 22 | Line 25 - 44 23 | */ 24 | 25 | int postIndex; 26 | HashMap inorderMap = new HashMap<>(); 27 | 28 | private TreeNode solve(int[] postorder, int left, int right) { 29 | if(left > right) return null; 30 | int rootValue = postorder[postIndex--]; 31 | int index = inorderMap.get(rootValue); 32 | TreeNode root = new TreeNode(rootValue); 33 | root.right = solve(postorder, index + 1, right); 34 | root.left = solve(postorder, left, index - 1); 35 | return root; 36 | } 37 | 38 | public TreeNode buildTree(int[] inorder, int[] postorder) { 39 | for(int i = 0; i < inorder.length; i++) { 40 | inorderMap.put(inorder[i], i); 41 | } 42 | postIndex = postorder.length - 1; 43 | return solve(postorder, 0, postorder.length - 1); 44 | } 45 | 46 | 47 | 48 | public static void main(String[] args) { 49 | int inorder[] = new int[]{}; 50 | int postorder[] = new int[]{}; 51 | TreeNode root = Solution.buildTree(inorder, postorder); 52 | /** 53 | * We can write the code for BFS traversal to check the formed tree. 54 | */ 55 | } 56 | } -------------------------------------------------------------------------------- /JavaScript/code.js: -------------------------------------------------------------------------------- 1 | // author : Armaan Soni 2 | // feature add while loop 3 | 4 | let text = ""; 5 | let i = 0; 6 | while (i < 10) { 7 | text += "
The number is " + i; 8 | i++; 9 | } 10 | document.getElementById("demo").innerHTML = text; 11 | -------------------------------------------------------------------------------- /Python/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Python/.DS_Store -------------------------------------------------------------------------------- /Python/BFS/LevelOrderSuccessor.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # 6 6 | 7 | from collections import * 8 | 9 | class Node: 10 | def __init__(self, data): 11 | self.data = data 12 | self.right = self.left = None 13 | 14 | class LevelOrderSuccessor: 15 | 16 | def __init__(self): 17 | self.root = None 18 | 19 | def levelOrderSuccessor(self, root, key): 20 | if root is None: 21 | return None 22 | queue = deque([]) 23 | queue.append(self.root) 24 | while len(queue) != 0: 25 | current = queue.popleft() 26 | 27 | if current.left is not None: 28 | queue.append(current.left) 29 | if current.right is not None: 30 | queue.append(current.right) 31 | 32 | if current.data == key: 33 | break 34 | 35 | return queue.popleft() 36 | 37 | if __name__ == '__main__': 38 | tree = LevelOrderSuccessor() 39 | tree.root = Node(1) 40 | tree.root.left = Node(2) 41 | tree.root.right = Node(3) 42 | tree.root.left.left = Node(4) 43 | tree.root.right.left = Node(6) 44 | tree.root.right.right = Node(7) 45 | tree.root.right.right.left = Node(7) 46 | ans = tree.levelOrderSuccessor(tree.root, 4) 47 | print(ans.data) 48 | 49 | 50 | -------------------------------------------------------------------------------- /Python/BFS/LevelOrderTraversal.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # [1] 6 | # [2, 3] 7 | # [4, 5, 6, 7] 8 | 9 | from collections import * 10 | 11 | class Node: 12 | def __init__(self, data): 13 | self.data = data 14 | self.right = self.left = None 15 | 16 | class LevelOrderTraversal: 17 | 18 | def __init__(self): 19 | self.root = None 20 | 21 | def traverse(self, root): 22 | bfs = [] 23 | if root is None: 24 | return bfs 25 | queue = deque([]) 26 | queue.append(self.root) 27 | while len(queue) != 0: 28 | level_size = len(queue) 29 | current_level = [] 30 | for i in range(level_size): 31 | current = queue.popleft() 32 | current_level.append(current.data) 33 | if current.left is not None: 34 | queue.append(current.left) 35 | if current.right is not None: 36 | queue.append(current.right) 37 | bfs.append(current_level) 38 | return bfs 39 | 40 | if __name__ == '__main__': 41 | tree = LevelOrderTraversal() 42 | tree.root = Node(1) 43 | tree.root.left = Node(2) 44 | tree.root.right = Node(3) 45 | tree.root.left.left = Node(4) 46 | tree.root.left.right = Node(5) 47 | tree.root.right.left = Node(6) 48 | tree.root.right.right = Node(7) 49 | ans = tree.traverse(tree.root) 50 | for level in ans: 51 | print(level) 52 | 53 | 54 | -------------------------------------------------------------------------------- /Python/BFS/MinimumDepth.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # 3 6 | 7 | from collections import * 8 | 9 | class Node: 10 | def __init__(self, data): 11 | self.data = data 12 | self.right = self.left = None 13 | 14 | class MinimumTreeDepth: 15 | 16 | def __init__(self): 17 | self.root = None 18 | 19 | def traverse(self, root): 20 | minimum_depth = 0 21 | if root is None: 22 | return minimum_depth 23 | queue = deque([]) 24 | queue.append(self.root) 25 | while len(queue) != 0: 26 | minimum_depth += 1 27 | level_size = len(queue) 28 | for i in range(level_size): 29 | current = queue.popleft() 30 | 31 | if current.left is None and current.right is None: 32 | return minimum_depth 33 | 34 | if current.left is not None: 35 | queue.append(current.left) 36 | if current.right is not None: 37 | queue.append(current.right) 38 | return minimum_depth 39 | 40 | if __name__ == '__main__': 41 | tree = MinimumTreeDepth() 42 | tree.root = Node(1) 43 | tree.root.left = Node(2) 44 | tree.root.right = Node(3) 45 | tree.root.left.left = Node(4) 46 | tree.root.right.left = Node(6) 47 | tree.root.right.right = Node(7) 48 | tree.root.right.right.left = Node(7) 49 | ans = tree.traverse(tree.root) 50 | print(ans) 51 | 52 | 53 | -------------------------------------------------------------------------------- /Python/BFS/RightView.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # 12 1 5 3 6 | 7 | from collections import * 8 | 9 | class Node: 10 | def __init__(self, data): 11 | self.data = data 12 | self.right = self.left = None 13 | 14 | class RightView: 15 | 16 | def __init__(self): 17 | self.root = None 18 | 19 | def rightView(self, root): 20 | result = [] 21 | if root is None: 22 | return result 23 | queue = deque([]) 24 | queue.append(self.root) 25 | while len(queue) != 0: 26 | level_size = len(queue) 27 | for i in range(level_size): 28 | current = queue.popleft() 29 | 30 | if (i == level_size - 1): 31 | result.append(current.data) 32 | 33 | if current.left is not None: 34 | queue.append(current.left) 35 | if current.right is not None: 36 | queue.append(current.right) 37 | return result 38 | 39 | if __name__ == '__main__': 40 | tree = RightView() 41 | tree.root = Node(12); 42 | tree.root.left = Node(7); 43 | tree.root.right = Node(1); 44 | tree.root.left.left = Node(9); 45 | tree.root.right.left = Node(10); 46 | tree.root.right.right = Node(5); 47 | tree.root.left.left.left = Node(3); 48 | ans = tree.rightView(tree.root) 49 | for node in ans: 50 | print(node, end = " ") 51 | print() 52 | 53 | 54 | -------------------------------------------------------------------------------- /Python/BFS/ZigZagTraversal.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # [1] 6 | # [3, 2] 7 | # [4, 5, 6, 7] 8 | 9 | from collections import * 10 | 11 | class Node: 12 | def __init__(self, data): 13 | self.data = data 14 | self.right = self.left = None 15 | 16 | class ZigZagTraversal: 17 | 18 | def __init__(self): 19 | self.root = None 20 | 21 | def traverse(self, root): 22 | bfs = [] 23 | left_to_right = True 24 | if root is None: 25 | return bfs 26 | queue = deque([]) 27 | queue.append(self.root) 28 | while len(queue) != 0: 29 | level_size = len(queue) 30 | current_level = deque() 31 | for i in range(level_size): 32 | current = queue.popleft() 33 | 34 | if left_to_right: 35 | current_level.append(current.data) 36 | else: 37 | current_level.appendleft(current.data) 38 | 39 | if current.left is not None: 40 | queue.append(current.left) 41 | if current.right is not None: 42 | queue.append(current.right) 43 | bfs.append(current_level) 44 | left_to_right = not left_to_right 45 | return bfs 46 | 47 | if __name__ == '__main__': 48 | tree = ZigZagTraversal() 49 | tree.root = Node(1) 50 | tree.root.left = Node(2) 51 | tree.root.right = Node(3) 52 | tree.root.left.left = Node(4) 53 | tree.root.left.right = Node(5) 54 | tree.root.right.left = Node(6) 55 | tree.root.right.right = Node(7) 56 | ans = tree.traverse(tree.root) 57 | for level in ans: 58 | print(list(level)) -------------------------------------------------------------------------------- /Python/BinarySearch/Cabs.py: -------------------------------------------------------------------------------- 1 | def findTrips(cabsTime, midTime): 2 | totalTrips = 0 3 | for cab in cabsTime: 4 | totalTrips += (midTime//cab) 5 | return totalTrips 6 | 7 | def binarySearch(cabsTime, low, high, trips): 8 | while low != high: 9 | midTime = (low + high)//2 10 | totalTrips = findTrips(cabsTime, midTime) 11 | if totalTrips > trips: 12 | high = midTime 13 | else: 14 | low = midTime + 1 15 | return low 16 | 17 | def findMinTime(cabsTime, trips): 18 | low = 1 19 | high = min(cabsTime) * trips 20 | return binarySearch(cabsTime, low, high, trips) 21 | 22 | if __name__ == "__main__": 23 | cabsTime = [5, 1, 3, 7] 24 | trips = 10 25 | print(findMinTime(cabsTime, trips)) -------------------------------------------------------------------------------- /Python/BinaryTree/BinarySearchTree_Search.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | 6 | 7 | # Creating a structure for the node. 8 | # Initializing the node's data upon calling its constructor. 9 | 10 | class Node: 11 | def __init__(self, data): 12 | self.data = data 13 | self.right = self.left = None 14 | 15 | 16 | # Defining class for the Binary Tree 17 | class BST_Search: 18 | 19 | # Assigning root as null initially. So as soon as the object will be created 20 | # of this BinaryTreeTraversal class, root will be set as null. 21 | def __init__(self): 22 | self.root = None 23 | 24 | def bst_search(self, root, key): 25 | 26 | if root is None or root.data == key: 27 | return root 28 | 29 | elif root.data < key: 30 | return self.bst_search(root.right, key) 31 | 32 | else: 33 | return self.bst_search(root.left, key) 34 | 35 | 36 | 37 | #main method 38 | if __name__ == '__main__': 39 | tree = BST_Search() 40 | tree.root = Node(20) 41 | tree.root.left = Node(15) 42 | tree.root.right = Node(25) 43 | tree.root.left.left = Node(14) 44 | tree.root.left.right = Node(17) 45 | tree.root.right.left = Node(22) 46 | tree.root.right.right = Node(30) 47 | tree.root.right.left.right = Node(24) 48 | 49 | ans = tree.bst_search(tree.root, 24) 50 | if ans is None: 51 | print(False) 52 | else: 53 | print(True) 54 | 55 | -------------------------------------------------------------------------------- /Python/BinaryTree/ConstructingBinaryTree.py: -------------------------------------------------------------------------------- 1 | 2 | # @author 3 | # Aakash Verma 4 | 5 | # Creating a structure for the node. 6 | # Initializing the node's data upon calling its constructor. 7 | class Node: 8 | def __init__(self, data): 9 | self.data = data 10 | self.right = self.left = None 11 | 12 | 13 | # Defining class for the Binary Tree 14 | class BinaryTree: 15 | 16 | # Assigning root as null initially. So as soon as the object will be created 17 | # of this BinaryTreeTraversal class, root will be set as null. 18 | def __init__(self): 19 | self.root = None 20 | 21 | # main method 22 | if __name__ == '__main__': 23 | tree = BinaryTree() 24 | tree.root = Node(1) 25 | tree.root.left = Node(2) 26 | tree.root.right = Node(3) 27 | tree.root.left.left = Node(4) 28 | tree.root.left.right = Node(5) 29 | tree.root.right.left = Node(6) 30 | tree.root.right.right = Node(7) -------------------------------------------------------------------------------- /Python/BinaryTree/InorderTraversal.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # aakash.verma 4 | # 5 | 6 | class InorderTraversal: 7 | def inorderTraversal(self, root: TreeNode) -> List[int]: 8 | inorder = [] 9 | stack = [] 10 | if root is None: 11 | return inorder 12 | curr = root 13 | while curr is not None or len(stack) != 0: 14 | while curr is not None: 15 | stack.append(curr) 16 | curr = curr.left 17 | curr = stack.pop() 18 | inorder.append(curr.val) 19 | curr = curr.right 20 | return inorder 21 | 22 | if __name__ == '__main__': 23 | . 24 | . 25 | . -------------------------------------------------------------------------------- /Python/BinaryTree/NumberOfFullNodes.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # Pre Order Traversal is: 1 2 4 5 3 6 7 6 | # Number Of Full Nodes: 3 7 | 8 | 9 | # Creating a structure for the node. 10 | # Initializing the node's data upon calling its constructor. 11 | 12 | class Node: 13 | def __init__(self, data): 14 | self.data = data 15 | self.right = self.left = None 16 | 17 | 18 | # Defining class for the Binary Tree 19 | class NumberOfFullNodes: 20 | 21 | # Assigning root as null initially. So as soon as the object will be created 22 | # of this NumberOfFullNodes class, root will be set as null. 23 | def __init__(self): 24 | self.root = None 25 | 26 | # Pre Order Traversal 27 | def preOrder(self, root): 28 | if root is None: 29 | return 30 | print(root.data, end = " ") 31 | self.preOrder(root.left) 32 | self.preOrder(root.right) 33 | 34 | def numFullNodes(self, root): 35 | if root is None: 36 | return 0 37 | if root.left is None and root.right is None: 38 | return 0; 39 | return self.numFullNodes(root.left) + self.numFullNodes(root.right) + (1 if root.left is not None and root.right is not None else 0); 40 | 41 | # main method 42 | if __name__ == '__main__': 43 | tree = NumberOfFullNodes() 44 | tree.root = Node(1) 45 | tree.root.left = Node(2) 46 | tree.root.right = Node(3) 47 | tree.root.left.left = Node(4) 48 | tree.root.left.right = Node(5) 49 | tree.root.right.left = Node(6) 50 | tree.root.right.right = Node(7) 51 | print("Pre Order Traversal is:", end = " ") 52 | tree.preOrder(tree.root) 53 | print() 54 | print("Number Of non-Leaf Nodes:", end = " ") 55 | print(tree.numFullNodes(tree.root)) 56 | 57 | -------------------------------------------------------------------------------- /Python/BinaryTree/NumberOfLeafNodes.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # Pre Order Traversal is: 1 2 4 5 3 6 7 6 | # Number Of non-Leaf Nodes: 3 7 | 8 | 9 | # Creating a structure for the node. 10 | # Initializing the node's data upon calling its constructor. 11 | 12 | class Node: 13 | def __init__(self, data): 14 | self.data = data 15 | self.right = self.left = None 16 | 17 | 18 | # Defining class for the Binary Tree 19 | class NumberOfLeafNodes: 20 | 21 | # Assigning root as null initially. So as soon as the object will be created 22 | # of this NumberOfLeafNodes class, root will be set as null. 23 | def __init__(self): 24 | self.root = None 25 | 26 | # Pre Order Traversal 27 | def preOrder(self, root): 28 | if root is None: 29 | return 30 | print(root.data, end = " ") 31 | self.preOrder(root.left) 32 | self.preOrder(root.right) 33 | 34 | def numLeafNodes(self, root): 35 | if root is None: 36 | return 0 37 | if root.left is None and root.right is None: 38 | return 1; 39 | return self.numLeafNodes(root.left) + self.numLeafNodes(root.right) 40 | 41 | # main method 42 | if __name__ == '__main__': 43 | tree = NumberOfLeafNodes() 44 | tree.root = Node(1) 45 | tree.root.left = Node(2) 46 | tree.root.right = Node(3) 47 | tree.root.left.left = Node(4) 48 | tree.root.left.right = Node(5) 49 | tree.root.right.left = Node(6) 50 | tree.root.right.right = Node(7) 51 | print("Pre Order Traversal is:", end = " ") 52 | tree.preOrder(tree.root) 53 | print() 54 | print("Number Of Leaf Nodes:", end = " ") 55 | print(tree.numLeafNodes(tree.root)) 56 | 57 | -------------------------------------------------------------------------------- /Python/BinaryTree/NumberOfNodesInBinaryTree.py: -------------------------------------------------------------------------------- 1 | 2 | # @author 3 | # Aakash Verma 4 | 5 | # Output: 6 | # Pre Order Traversal is: 1 2 4 5 3 6 7 7 | # Number Of Nodes: 7 8 | 9 | 10 | # Creating a structure for the node. 11 | # Initializing the node's data upon calling its constructor. 12 | 13 | class Node: 14 | def __init__(self, data): 15 | self.data = data 16 | self.right = self.left = None 17 | 18 | 19 | # Defining class for the Binary Tree 20 | class NumberOfNodesInBinaryTree: 21 | 22 | # Assigning root as null initially. So as soon as the object will be created 23 | # of this NumberOfNodesInBinaryTree class, root will be set as null. 24 | def __init__(self): 25 | self.root = None 26 | 27 | # Pre Order Traversal 28 | def preOrder(self, root): 29 | if root is None: 30 | return 31 | print(root.data, end = " ") 32 | self.preOrder(root.left) 33 | self.preOrder(root.right) 34 | 35 | def numNodes(self, root): 36 | if root is None: 37 | return 0 38 | return 1 + self.numNodes(root.left) + self.numNodes(root.right); 39 | 40 | #main method 41 | if __name__ == '__main__': 42 | tree = NumberOfNodesInBinaryTree() 43 | tree.root = Node(1) 44 | tree.root.left = Node(2) 45 | tree.root.right = Node(3) 46 | tree.root.left.left = Node(4) 47 | tree.root.left.right = Node(5) 48 | tree.root.right.left = Node(6) 49 | tree.root.right.right = Node(7) 50 | print("Pre Order Traversal is:", end = " ") 51 | tree.preOrder(tree.root) 52 | print() 53 | print("Number Of Nodes:", end = " ") 54 | print(tree.numNodes(tree.root)) 55 | 56 | -------------------------------------------------------------------------------- /Python/BinaryTree/NumberOfNonLeafNodes.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # Pre Order Traversal is: 1 2 4 5 3 6 7 6 | # Number Of non-Leaf Nodes: 3 7 | 8 | 9 | # Creating a structure for the node. 10 | # Initializing the node's data upon calling its constructor. 11 | 12 | class Node: 13 | def __init__(self, data): 14 | self.data = data 15 | self.right = self.left = None 16 | 17 | 18 | # Defining class for the Binary Tree 19 | class NumberOfNonLeafNodes: 20 | 21 | # Assigning root as null initially. So as soon as the object will be created 22 | # of this NumberOfNonLeafNodes class, root will be set as null. 23 | def __init__(self): 24 | self.root = None 25 | 26 | # Pre Order Traversal 27 | def preOrder(self, root): 28 | if root is None: 29 | return 30 | print(root.data, end = " ") 31 | self.preOrder(root.left) 32 | self.preOrder(root.right) 33 | 34 | def numNonLeafNodes(self, root): 35 | if root is None: 36 | return 0 37 | if root.left is None and root.right is None: 38 | return 0; 39 | return 1 + self.numNonLeafNodes(root.left) + self.numNonLeafNodes(root.right) 40 | 41 | # main method 42 | if __name__ == '__main__': 43 | tree = NumberOfNonLeafNodes() 44 | tree.root = Node(1) 45 | tree.root.left = Node(2) 46 | tree.root.right = Node(3) 47 | tree.root.left.left = Node(4) 48 | tree.root.left.right = Node(5) 49 | tree.root.right.left = Node(6) 50 | tree.root.right.right = Node(7) 51 | print("Pre Order Traversal is:", end = " ") 52 | tree.preOrder(tree.root) 53 | print() 54 | print("Number Of non-Leaf Nodes:", end = " ") 55 | print(tree.numNonLeafNodes(tree.root)) 56 | 57 | -------------------------------------------------------------------------------- /Python/BinaryTree/PostorderTraversal.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # aakash.verma 4 | # 5 | 6 | class Solution: 7 | def postorderTraversal(self, root: TreeNode) -> List[int]: 8 | postorder = [] 9 | stack1 = [] 10 | stack2 = [] 11 | if root is None: 12 | return postorder 13 | stack1.append(root) 14 | while len(stack1) != 0: 15 | current = stack1.pop() 16 | stack2.append(current) 17 | if current.left is not None: 18 | stack1.append(current.left) 19 | if current.right is not None: 20 | stack1.append(current.right) 21 | 22 | while len(stack2) != 0: 23 | postorder.append(stack2.pop().val) 24 | 25 | return postorder 26 | 27 | if __name__ == '__main__': 28 | . 29 | . 30 | . -------------------------------------------------------------------------------- /Python/DFS/BinaryTreePathSum.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # true 6 | 7 | from collections import * 8 | 9 | class Node: 10 | def __init__(self, data): 11 | self.data = data 12 | self.right = self.left = None 13 | 14 | class BinaryTreePathSum: 15 | 16 | def __init__(self): 17 | self.root = None 18 | 19 | def hasPath(self, root, sum): 20 | if(root is None): return False 21 | 22 | if(root.data == sum and root.left is None and root.right is None): 23 | return True 24 | 25 | return self.hasPath(root.left, sum - root.data) or self.hasPath(root.right, sum - root.data) 26 | 27 | if __name__ == '__main__': 28 | tree = BinaryTreePathSum() 29 | tree.root = Node(12) 30 | tree.root.left = Node(7) 31 | tree.root.right = Node(1) 32 | tree.root.left.left = Node(9) 33 | tree.root.right.left = Node(10) 34 | tree.root.right.right = Node(5) 35 | tree.root.left.left.left = Node(3) 36 | ans = tree.hasPath(tree.root, 23) 37 | print(ans) 38 | 39 | 40 | -------------------------------------------------------------------------------- /Python/DFS/CP01_BinaryTree.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | from collections import deque 5 | 6 | def bfs(n, source, tree): 7 | 8 | queue = deque([]) 9 | queue.append(source) 10 | distance = [0] * (n + 1) 11 | 12 | while queue: 13 | current = queue.popleft() 14 | for node in tree[current]: 15 | queue.append(node) 16 | distance[node] = distance[current] + 1 17 | 18 | return distance 19 | 20 | if __name__ == '__main__': 21 | 22 | t = int(input()) 23 | for i in range(t): 24 | n = int(input()) 25 | 26 | tree = dict() 27 | 28 | for i in range(1, n + 1): 29 | tree[i] = [] 30 | 31 | for i in range(n - 1): 32 | a, b = tuple(map(int, input().split())) 33 | tree[a].append(b) 34 | 35 | distance = bfs(n, 1, tree) 36 | 37 | for i in range(1, n + 1): 38 | print(distance[i], end = " ") 39 | print() 40 | 41 | -------------------------------------------------------------------------------- /Python/DFS/CountPathsForASum.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # true 6 | 7 | from collections import * 8 | from itertools import count 9 | 10 | class Node: 11 | def __init__(self, data): 12 | self.data = data 13 | self.right = self.left = None 14 | 15 | class CountPathsForASum: 16 | 17 | def __init__(self): 18 | self.root = None 19 | 20 | def countAllPaths(self, root, target, current_path): 21 | if root is None: 22 | return 0 23 | 24 | current_path.append(root.data) 25 | path_sum = 0 26 | path_count = 0 27 | 28 | for i in range(len(current_path) - 1, -1, -1): 29 | path_sum += current_path[i] 30 | if path_sum == target: 31 | path_count += 1 32 | 33 | left_count = self.countAllPaths(root.left, target, current_path) 34 | right_count = self.countAllPaths(root.right, target, current_path) 35 | path_count += (left_count + right_count) 36 | 37 | del current_path[-1] 38 | 39 | return path_count 40 | 41 | 42 | def countPaths(self, root, target): 43 | current_path = [] 44 | return self.countAllPaths(root, target, current_path) 45 | 46 | if __name__ == '__main__': 47 | tree = CountPathsForASum() 48 | tree.root = Node(1) 49 | tree.root.left = Node(7) 50 | tree.root.right = Node(9) 51 | tree.root.left.left = Node(6) 52 | tree.root.left.right = Node(5) 53 | tree.root.right.left = Node(2) 54 | tree.root.right.right = Node(3) 55 | ans = tree.countPaths(tree.root, 12) 56 | print(ans) 57 | 58 | 59 | -------------------------------------------------------------------------------- /Python/DFS/LowestCommonAncestorBT.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # 5 6 | 7 | from collections import * 8 | 9 | class Node: 10 | def __init__(self, data): 11 | self.data = data 12 | self.right = self.left = None 13 | 14 | class LowestCommonAncestor: 15 | 16 | def __init__(self): 17 | self.root = None 18 | 19 | def lowestCommonAncestor(self, root, p, q): 20 | 21 | if(root is None): 22 | return None 23 | 24 | if root.data == p.data or root.data == q.data: 25 | return root 26 | 27 | left = self.lowestCommonAncestor(root.left, p, q) 28 | right = self.lowestCommonAncestor(root.right, p, q) 29 | 30 | if left is not None and right is not None: 31 | return root 32 | 33 | return left if left is not None else right 34 | 35 | if __name__ == '__main__': 36 | tree = LowestCommonAncestor() 37 | tree.root = Node(3) 38 | tree.root.left = Node(5) 39 | tree.root.right = Node(1) 40 | tree.root.left.left = Node(6) 41 | tree.root.left.right = Node(2) 42 | tree.root.right.left = Node(0) 43 | tree.root.right.right = Node(8) 44 | tree.root.left.right.left = Node(7) 45 | tree.root.left.right.right = Node(4) 46 | 47 | p = tree.root.left 48 | q = tree.root.left.right.right 49 | 50 | lca = tree.lowestCommonAncestor(tree.root, p, q) 51 | print(lca.data) 52 | 53 | -------------------------------------------------------------------------------- /Python/DFS/MergeTwoTrees.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # 3 6 3 1 8 10 5 6 | 7 | 8 | from collections import deque 9 | 10 | class Node: 11 | def __init__(self, data): 12 | self.data = data 13 | self.right = self.left = None 14 | 15 | class MergeTwoTrees: 16 | 17 | def __init__(self): 18 | self.root1 = None 19 | self.root2 = None 20 | 21 | def traverse(self, root): 22 | if(root is None): 23 | return 24 | print(root.data, end = " ") 25 | self.traverse(root.left) 26 | self.traverse(root.right) 27 | 28 | def merge(self, root1, root2): 29 | if root1 is None: 30 | return root2 31 | if root2 is None: 32 | return root1 33 | 34 | root1.data += root2.data 35 | 36 | root1.left = self.merge(root1.left, root2.left) 37 | root1.right = self.merge(root1.right, root2.right) 38 | 39 | return root1 40 | 41 | 42 | if __name__ == '__main__': 43 | tree = MergeTwoTrees() 44 | tree.root1 = Node(1) 45 | tree.root1.left = Node(2) 46 | tree.root1.right = Node(3) 47 | tree.root1.right.left = Node(4) 48 | tree.root1.right.right = Node(5) 49 | 50 | tree.root2 = Node(2) 51 | tree.root2.left = Node(4) 52 | tree.root2.right = Node(5) 53 | tree.root2.left.left = Node(3) 54 | tree.root2.left.right = Node(1) 55 | tree.root2.right.left = Node(6) 56 | 57 | root = tree.merge(tree.root1, tree.root2) 58 | tree.traverse(root) 59 | 60 | 61 | -------------------------------------------------------------------------------- /Python/DFS/PathWithGivenSequence.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # true 6 | 7 | from collections import * 8 | 9 | class Node: 10 | def __init__(self, data): 11 | self.data = data 12 | self.right = self.left = None 13 | 14 | class PathWithGivenSequence: 15 | 16 | def __init__(self): 17 | self.root = None 18 | 19 | def findSequence(self, root, sequence, index): 20 | if root is None: return False 21 | 22 | if index >= len(sequence) or root.data != sequence[index]: 23 | return False 24 | 25 | if(root.left is None and root.right is None and index == len(sequence) - 1): 26 | return True 27 | 28 | return self.findSequence(root.left, sequence, index + 1) or self.findSequence(root.right, sequence, index + 1) 29 | 30 | def hasPath(self, root, sequence): 31 | if root is None: return len(sequence) == 0 32 | 33 | return self.findSequence(root, sequence, 0) 34 | 35 | 36 | 37 | if __name__ == '__main__': 38 | tree = PathWithGivenSequence() 39 | tree.root = Node(3) 40 | tree.root.left = Node(7) 41 | tree.root.right = Node(1) 42 | tree.root.left.left = Node(9) 43 | tree.root.right.left = Node(2) 44 | tree.root.right.right = Node(5) 45 | ans = tree.hasPath(tree.root, [3, 1, 2]) 46 | print(ans) 47 | 48 | 49 | -------------------------------------------------------------------------------- /Python/DFS/PathWithMaximumSum.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # 42 6 | 7 | from collections import * 8 | import math 9 | 10 | class Node: 11 | def __init__(self, data): 12 | self.data = data 13 | self.right = self.left = None 14 | 15 | class PathWithMaximumSum: 16 | 17 | def __init__(self): 18 | self.root = None 19 | 20 | def findMaxSum(self, root): 21 | if root is None: return 0 22 | 23 | leftSum = self.findMaxSum(root.left) 24 | rightSum = self.findMaxSum(root.right) 25 | 26 | leftSum = max(leftSum, 0) 27 | rightSum = max(rightSum, 0) 28 | 29 | currentSum = leftSum + rightSum + root.data 30 | 31 | self.maxSum = max(currentSum, self.maxSum) 32 | 33 | return max(leftSum, rightSum) + root.data 34 | 35 | def findMaximumPathSum(self, root): 36 | self.maxSum = -math.inf 37 | self.findMaxSum(root) 38 | return self.maxSum 39 | 40 | 41 | if __name__ == '__main__': 42 | tree = PathWithMaximumSum() 43 | tree.root = Node(10) 44 | tree.root.left = Node(2) 45 | tree.root.right = Node(10) 46 | tree.root.left.left = Node(20) 47 | tree.root.left.right = Node(1) 48 | tree.root.right.left = Node(-25) 49 | tree.root.right.left.left = Node(3) 50 | tree.root.right.left.right = Node(4) 51 | ans = tree.findMaximumPathSum(tree.root) 52 | print(ans) 53 | 54 | 55 | -------------------------------------------------------------------------------- /Python/DFS/Subordinates.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.setrecursionlimit(10**6) 3 | 4 | def dfs(curr, prev, count, tree): 5 | count[curr] = 1 6 | for nbr in tree[curr]: 7 | dfs(nbr, curr, count, tree) 8 | count[curr] += count[nbr] 9 | 10 | if __name__ == '__main__': 11 | n = int(input()) 12 | tree = dict() 13 | for i in range(1, n + 1): 14 | tree[i] = [] 15 | emp = list(map(int, input().split())) 16 | for i in range(n - 1): 17 | tree[emp[i]].append(i + 2) 18 | count = [0] * (n + 1) 19 | dfs(1, 0, count, tree) 20 | for i in range(1, n + 1): 21 | print(count[i] - 1, end = " ") 22 | print() -------------------------------------------------------------------------------- /Python/DFS/SumOfPathNumbers.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # 1008 6 | 7 | from collections import * 8 | 9 | class Node: 10 | def __init__(self, data): 11 | self.data = data 12 | self.right = self.left = None 13 | 14 | class BinaryTreePathSum: 15 | 16 | def __init__(self): 17 | self.root = None 18 | 19 | def findPathSum(self, root, pathSum): 20 | if root is None: 21 | return 0 22 | 23 | pathSum = 10 * pathSum + root.data 24 | 25 | if root.left is None and root.right is None: 26 | return pathSum 27 | 28 | return self.findPathSum(root.left, pathSum) + self.findPathSum(root.right, pathSum) 29 | 30 | def findSumPathNumbers(self, root): 31 | return self.findPathSum(root, 0) 32 | 33 | if __name__ == '__main__': 34 | tree = BinaryTreePathSum() 35 | tree.root = Node(3) 36 | tree.root.left = Node(7) 37 | tree.root.right = Node(1) 38 | tree.root.left.left = Node(9) 39 | tree.root.right.left = Node(4) 40 | tree.root.right.right = Node(5) 41 | ans = tree.findSumPathNumbers(tree.root) 42 | print(ans) 43 | 44 | 45 | -------------------------------------------------------------------------------- /Python/DFS/SymmetricTree.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # True 6 | 7 | 8 | from collections import deque 9 | 10 | class Node: 11 | def __init__(self, data): 12 | self.data = data 13 | self.right = self.left = None 14 | 15 | class SymmetricTree: 16 | 17 | def __init__(self): 18 | self.root = None 19 | 20 | def findSymmetric(self, root1, root2): 21 | if root1 is None and root2 is None: 22 | return True 23 | if root1 is None or root2 is None: 24 | return False 25 | return (root1.data == root2.data) and self.findSymmetric(root1.left, root2.right) and self.findSymmetric(root1.right, root2.left) 26 | 27 | def isSymmetric(self, root): 28 | 29 | return self.findSymmetric(root, root) 30 | 31 | 32 | if __name__ == '__main__': 33 | tree = SymmetricTree() 34 | tree.root = Node(1) 35 | tree.root.left = Node(2) 36 | tree.root.right = Node(2) 37 | tree.root.left.left = Node(3) 38 | tree.root.left.right = Node(4) 39 | tree.root.right.left = Node(4) 40 | tree.root.right.right = Node(3) 41 | ans = tree.isSymmetric(tree.root) 42 | print(ans) 43 | 44 | 45 | -------------------------------------------------------------------------------- /Python/DFS/TreeDiameter.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # 8 6 | 7 | from collections import * 8 | 9 | class Node: 10 | def __init__(self, data): 11 | self.data = data 12 | self.right = self.left = None 13 | 14 | class TreeDiameter: 15 | 16 | diameter = 0 17 | 18 | def __init__(self): 19 | self.root = None 20 | 21 | def findHeight(self, root): 22 | if root is None: return 0 23 | 24 | leftHeight = self.findHeight(root.left) 25 | rightHeight = self.findHeight(root.right) 26 | 27 | currentDiameter = leftHeight + rightHeight + 1 28 | 29 | self.diameter = max(currentDiameter, self.diameter) 30 | 31 | return max(leftHeight, rightHeight) + 1 32 | 33 | def findDiameter(self, root): 34 | self.findHeight(root) 35 | return self.diameter 36 | 37 | 38 | if __name__ == '__main__': 39 | tree = TreeDiameter() 40 | tree.root = Node(1) 41 | tree.root.left = Node(2) 42 | tree.root.right = Node(3) 43 | tree.root.right.left = Node(4) 44 | tree.root.right.right = Node(5) 45 | tree.root.right.left.left = Node(6) 46 | tree.root.right.right.right = Node(7) 47 | tree.root.right.right.right.left = Node(12) 48 | tree.root.right.right.right.right = Node(13) 49 | tree.root.right.left.left.left = Node(8) 50 | tree.root.right.left.left.right = Node(10) 51 | tree.root.right.left.left.right.left = Node(11) 52 | ans = tree.findDiameter(tree.root) 53 | print(ans) 54 | 55 | 56 | -------------------------------------------------------------------------------- /Python/Graph/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Python/Graph/.DS_Store -------------------------------------------------------------------------------- /Python/Graph/BreadthFirstSearch.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # aakash.verma 4 | # 5 | # Output: 6 | # 2 0 1 3 7 | # 8 | 9 | from collections import deque 10 | 11 | class Graph: 12 | 13 | def __init__(self, vertices): 14 | self.vertices = vertices 15 | self.adjacency_list = [[] for i in range(self.vertices)] 16 | 17 | def add_edge(self, source, destination): 18 | self.adjacency_list[source].append(destination) 19 | self.adjacency_list[destination].append(source) # for directed graph comment this line 20 | 21 | def breadth_first_search(self, source): 22 | bfs = [] 23 | queue = deque([]) 24 | visited = [False] * self.vertices 25 | queue.append(source) 26 | visited[source] = True 27 | 28 | while len(queue) != 0: 29 | curr = queue.popleft() 30 | bfs.append(curr) 31 | for nbr in self.adjacency_list[curr]: 32 | if visited[nbr] is not True: 33 | queue.append(nbr) 34 | visited[nbr] = True 35 | return bfs 36 | 37 | if __name__ == '__main__': 38 | 39 | g = Graph(4); 40 | g.add_edge(0, 1) 41 | g.add_edge(0, 2) 42 | g.add_edge(1, 2) 43 | g.add_edge(2, 3) 44 | ans = g.breadth_first_search(2) 45 | for ele in ans: 46 | print(ele, end = " ") 47 | -------------------------------------------------------------------------------- /Python/Graph/ConnectedCell_Hackerrank.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # www.aboutaakash.in 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | # Problem Link: https://www.hackerrank.com/challenges/connected-cell-in-a-grid/problem 10 | # Only functions are written in this code 11 | 12 | def getMaxRegion(matrix, row, col): 13 | if (row < 0 or row >= len(matrix) or col < 0 or col >= len(matrix[0])): 14 | return 0 15 | if matrix[row][col] == 0: 16 | return 0 17 | matrix[row][col] = 0 # this is because, we don't want to infinite recursive calls. 18 | size = 1 # because we have visited one 1 and that's why we are in this function 19 | for r in range(row - 1, row + 2): # because we have to from row - 1 to row + 1 20 | for c in range(col - 1, col + 2): 21 | if (r != row or c != col): 22 | size += getMaxRegion(matrix, r, c) 23 | 24 | return size 25 | 26 | # Complete the connectedCell function below. 27 | def connectedCell(matrix): 28 | maxRegion = 0 29 | row = len(matrix) 30 | col = len(matrix[0]) 31 | for i in range(row): 32 | for j in range(col): 33 | if (matrix[i][j] == 1): 34 | size = getMaxRegion(matrix, i, j) 35 | maxRegion = max(size, maxRegion) 36 | return maxRegion 37 | 38 | 39 | # main method 40 | # ... 41 | # ... 42 | # ... -------------------------------------------------------------------------------- /Python/Graph/DFS.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # www.aboutaakash.in 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | from collections import deque 10 | 11 | def gridToAdjacencyList(edges): 12 | d = dict() 13 | 14 | # initializing the graph (converting edges into an adjacency list) 15 | for i in range(1, vertices + 1): 16 | d[i] = list() 17 | for edge in edges: 18 | d[edge[0]].append(edge[1]) 19 | d[edge[1]].append(edge[0]) 20 | return d 21 | 22 | def dfs_util(s, graph, visited, dfs_ans): 23 | 24 | visited[s] = True 25 | dfs_ans.append(s) 26 | 27 | for neighbour in graph[s]: 28 | if visited[neighbour] is not True: 29 | dfs_util(neighbour, graph, visited, dfs_ans) 30 | 31 | def dfs(s, edges, vertices): 32 | 33 | # getting converted edges into an adjacency list 34 | graph = gridToAdjacencyList(edges) 35 | visited = [False] * (vertices + 1) 36 | dfs_ans = [] 37 | 38 | dfs_util(s, graph, visited, dfs_ans) 39 | return dfs_ans 40 | 41 | 42 | 43 | if __name__ == '__main__': 44 | 45 | edges = [[1, 2], [1, 3], [2, 4], [2, 5], [3, 5], [4, 5], [4, 6], [5, 6]] 46 | vertices = 6 47 | ans = dfs(1, edges, vertices) 48 | print(ans) 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /Python/Graph/DSU.py: -------------------------------------------------------------------------------- 1 | class DSU: 2 | 3 | dsu_array = [] 4 | 5 | def __init__(self, n): 6 | DSU.dsu_array = [-1] * n 7 | self.n = n 8 | 9 | def find(self, v): 10 | if self.dsu_array[v] != -1: 11 | return self.find(DSU.dsu_array[v]) 12 | return v 13 | 14 | def union(self, v1, v2): 15 | DSU.dsu_array[v2] = v1 16 | 17 | def is_cycle(self, edges, n): 18 | for edge in edges: 19 | p1 = self.find(edge[0]) 20 | p2 = self.find(edge[1]) 21 | if p1 == p2: 22 | return True 23 | self.union(edge[0], edge[1]) 24 | return False 25 | 26 | if __name__ == "__main__": 27 | edges = [[0, 1], [0, 2], [1, 3], [2, 4], [4, 5], [3, 5]] 28 | dsu = DSU(6) 29 | print(dsu.is_cycle(edges, 6)) -------------------------------------------------------------------------------- /Python/Graph/DSUOptimized.py: -------------------------------------------------------------------------------- 1 | class DSU: 2 | dsu_array = [] 3 | def __init__(self, n): 4 | DSU.dsu_array = [[-1, 0]] * n 5 | self.n = n 6 | def find(self, v): 7 | print(DSU.dsu_array) 8 | if DSU.dsu_array[v][0] != -1: 9 | DSU.dsu_array[v][0] = self.find(DSU.dsu_array[v][0]) 10 | return v 11 | def union(self, p1, p2): 12 | if DSU.dsu_array[p1][1] > DSU.dsu_array[p2][1]: 13 | DSU.dsu_array[p2][0] = p1 14 | elif DSU.dsu_array[p2][1] < DSU.dsu_array[p1][1]: 15 | DSU.dsu_array[p1][0] = p2 16 | else: 17 | DSU.dsu_array[p2][0] = p1 18 | DSU.dsu_array[p1][1] += 1 19 | def is_cycle(self, edges, n): 20 | for edge in edges: 21 | p1 = self.find(edge[0]) 22 | p2 = self.find(edge[1]) 23 | if p1 == p2: 24 | return True 25 | self.union(p1, p2) 26 | return False 27 | if __name__ == "__main__": 28 | edges = [[0, 1], [0, 2]] 29 | dsu = DSU(3) 30 | print(dsu.is_cycle(edges, 3)) -------------------------------------------------------------------------------- /Python/Graph/DepthFirstSearch.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # aakash.verma 4 | # 5 | # Output: 6 | # 0 1 2 3 4 5 7 | # 8 | 9 | from collections import deque 10 | 11 | class Graph: 12 | 13 | def __init__(self, vertices): 14 | self.vertices = vertices 15 | self.adjacency_list = [[] for i in range(self.vertices)] 16 | 17 | def add_edge(self, source, destination): 18 | self.adjacency_list[source].append(destination) 19 | self.adjacency_list[destination].append(source) # for directed graph comment this line 20 | 21 | def dfs_util(self, node, visited, dfs): 22 | dfs.append(node) 23 | visited[node] = True 24 | for child in self.adjacency_list[node]: 25 | if visited[child] is not True: 26 | self.dfs_util(child, visited, dfs) 27 | 28 | def depth_first_search(self, source): 29 | dfs = [] 30 | visited = [False] * self.vertices 31 | self.dfs_util(source, visited, dfs) 32 | return dfs 33 | 34 | if __name__ == '__main__': 35 | 36 | g = Graph(6); 37 | g.add_edge(0, 1) 38 | g.add_edge(1, 2) 39 | g.add_edge(2, 3) 40 | g.add_edge(2, 4) 41 | g.add_edge(4, 5) 42 | ans = g.depth_first_search(0) 43 | for ele in ans: 44 | print(ele, end = " ") 45 | -------------------------------------------------------------------------------- /Python/Graph/Graph-Representation-Adjacency-List-2.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # aakash.verma 4 | # 5 | # Output: 6 | # Adjacency List of Undirected Graph 7 | # |Delhi| => Mumbai Bangalore 8 | # |Mumbai| => Delhi Hyderabad Bangalore 9 | # |Bangalore| => Delhi Mumbai 10 | # |Hyderabad| => Mumbai 11 | # 12 | # 13 | 14 | class Graph: 15 | 16 | def __init__(self, cities): 17 | self.cities = cities 18 | self.adjacency_list = dict() 19 | for city in self.cities: 20 | self.adjacency_list[city] = list() 21 | 22 | def add_edge(self, source, destination): 23 | self.adjacency_list[source].append(destination) 24 | self.adjacency_list[destination].append(source) # for directed graph comment this line 25 | 26 | def print_graph(self): 27 | print("Adjacency List of Undirected Graph") 28 | for city in self.cities: 29 | print("|", city, "| => ", end = " ") 30 | for nbr_city in self.adjacency_list[city]: 31 | print(nbr_city, end = " ") 32 | print() 33 | 34 | 35 | if __name__ == '__main__': 36 | 37 | cities = ["Delhi", "Mumbai", "Bangalore", "Hyderabad"] 38 | g = Graph(cities); 39 | g.add_edge("Delhi", "Mumbai") 40 | g.add_edge("Delhi", "Bangalore") 41 | g.add_edge("Mumbai", "Hyderabad") 42 | g.add_edge("Mumbai", "Bangalore") 43 | g.print_graph() 44 | 45 | 46 | -------------------------------------------------------------------------------- /Python/Graph/Graph-Representation-Adjacency-List.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # aakash.verma 4 | # 5 | # Output: 6 | # Adjacency List of Undirected Graph 7 | # |0| => 1 2 8 | # |1| => 0 3 9 | # |2| => 0 3 10 | # |3| => 1 2 11 | # 12 | # 13 | 14 | class Graph: 15 | 16 | def __init__(self, vertices): 17 | self.vertices = vertices 18 | self.adjacency_list = [[] for i in range(self.vertices)] 19 | 20 | def add_edge(self, source, destination): 21 | self.adjacency_list[source].append(destination) 22 | self.adjacency_list[destination].append(source) # for directed graph comment this line 23 | 24 | def print_graph(self): 25 | print("Adjacency List of Undirected Graph") 26 | for i in range(self.vertices): 27 | print("|", i, "| => ", end = " ") 28 | for nbr in self.adjacency_list[i]: 29 | print(nbr, end = " ") 30 | print() 31 | 32 | 33 | if __name__ == '__main__': 34 | 35 | g = Graph(4); 36 | g.add_edge(0, 1) 37 | g.add_edge(0, 2) 38 | g.add_edge(1, 3) 39 | g.add_edge(2, 3) 40 | g.print_graph() 41 | 42 | 43 | -------------------------------------------------------------------------------- /Python/Graph/GraphAdjacencyList.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | 3 | vertices = 0 4 | graph = {} 5 | 6 | def __init__(self, vertices): 7 | self.vertices = vertices 8 | for i in range(1, vertices + 1): 9 | self.graph[i] = [] 10 | print(self.graph) 11 | 12 | def add_edge(self, edges): 13 | for edge in edges: 14 | self.graph[edge[0]].append(edge[1]) 15 | self.graph[edge[1]].append(edge[0]) 16 | 17 | print(self.graph) 18 | 19 | def print_graph(self): 20 | 21 | for key in self.graph: 22 | print(key, "is connected to ", self.graph[key]) 23 | 24 | if __name__ == '__main__': 25 | 26 | vertices = 4 27 | edges = [[1, 2], [1, 3], [1, 4], [2, 3]] 28 | 29 | graph = Graph(vertices) 30 | graph.add_edge(edges) 31 | graph.print_graph() 32 | 33 | -------------------------------------------------------------------------------- /Python/Graph/JourneyToTheMoon.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # www.aboutaakash.in 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | # Problem Link: https://www.hackerrank.com/challenges/journey-to-the-moon/problem 10 | # Only functions are written in this code 11 | 12 | def dfs(node, visited, graph): 13 | count = 1 14 | visited[node] = True 15 | for neighbour in graph[node]: 16 | if visited[neighbour] is not True: 17 | count += dfs(neighbour, visited, graph) 18 | 19 | return count 20 | 21 | def gridToAdjacencyList(cities, n): 22 | graph = dict() 23 | for i in range(n): 24 | graph[i] = list() 25 | for city in cities: 26 | graph[city[0]].append(city[1]) 27 | graph[city[1]].append(city[0]) 28 | 29 | def journeyToMoon(n, astronauts): 30 | 31 | graph = gridToAdjacencyList(astronaut, n) 32 | 33 | visited = [False] * (n) 34 | components = [] 35 | 36 | for v in range(n): 37 | if len(graph[v]) > 0 and visited[v] is not True: 38 | components.append(dfs(v, visited, graph)) 39 | elif (len(graph[v]) == 0): 40 | components.append(1) 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | length = len(components) 50 | prefix_array = [0] * length 51 | prefix_array[-1] = components[-1] 52 | for i in range(length - 2, -1, -1): 53 | prefix_array[i] = prefix_array[i + 1] + components[i] 54 | 55 | ans = 0 56 | for i in range(length - 1): 57 | ans = ans + components[i] * prefix_array[i + 1] 58 | return ans -------------------------------------------------------------------------------- /Python/Graph/Roads_And_Libraries.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # www.aboutaakash.in 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | # Problem Link: https://www.hackerrank.com/challenges/torque-and-development/problem 10 | # Only functions are written in this code 11 | 12 | def dfs(node, visited, graph): 13 | count = 1 14 | visited[node] = True 15 | for neighbour in graph[node]: 16 | if visited[neighbour] is not True: 17 | count += dfs(neighbour, visited, graph) 18 | 19 | return count 20 | 21 | def gridToAdjacencyList(cities, n): 22 | graph = dict() 23 | for i in range(n): 24 | graph[i] = list() 25 | for city in cities: 26 | graph[city[0]].append(city[1]) 27 | graph[city[1]].append(city[0]) 28 | 29 | 30 | def roadsAndLibraries(n, c_lib, c_road, cities): 31 | graph = gridToAdjacencyList(cities, n) 32 | 33 | visited = [False] * (n + 1) 34 | components = [] 35 | 36 | for v in range(1, n + 1): 37 | if len(graph[v]) > 0 and visited[v] is not True: 38 | components.append(dfs(v, visited, graph)) 39 | elif (len(graph[v]) == 0): 40 | components.append(1) 41 | 42 | ans = 0 43 | for i in range(len(components)): 44 | ans += min((components[i]-1) * c_road + c_lib, components[i] * c_lib) 45 | return ans 46 | -------------------------------------------------------------------------------- /Python/Graph/ShortestReachHackerRank.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # @author 4 | # aakash.verma 5 | # 6 | # Problem Link: https://www.hackerrank.com/challenges/bfsshortreach/problem 7 | # Note: I have completed the function only. 8 | # 9 | 10 | def bfs(n, m, edges, s): 11 | distance = [-1] * (n + 1) 12 | q = deque([]) 13 | visited = [False] * (n + 1) 14 | q.append(s) 15 | visited[s] = True 16 | distance[s] = 0 17 | 18 | # creating adjacency list from the given set of edges. 19 | adjacency_list = [[] for i in range(n + 1)] 20 | for edge in edges: 21 | adjacency_list[edge[0]].append(edge[1]) 22 | adjacency_list[edge[1]].append(edge[0]) 23 | 24 | while len(q) != 0: 25 | curr = q.popleft() 26 | for nbr in adjacency_list[curr]: 27 | if visited[nbr] is not True: 28 | q.append(nbr) 29 | visited[nbr] = True 30 | distance[nbr] = distance[curr] + 6 31 | 32 | distance.remove(0) 33 | return distance[1:] -------------------------------------------------------------------------------- /Python/Heap/KClosestPointToOrigin.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # Aakash Verma 4 | # 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | from heapq import heappop 10 | 11 | class Solution: 12 | def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: 13 | max_heap = [] 14 | for i in range(k): 15 | x = points[i][0] 16 | y = points[i][1] 17 | dis = x*x + y*y 18 | heappush(max_heap, (-dis, x, y)) 19 | 20 | for i in range(k, len(points)): 21 | x = points[i][0] 22 | y = points[i][1] 23 | dis = x*x + y*y 24 | if dis < -max_heap[0][0]: 25 | heappop(max_heap) 26 | heappush(max_heap, (-dis, x, y)) 27 | 28 | ans = [] 29 | while len(max_heap) != 0: 30 | temp, x, y = heappop(max_heap) 31 | ans.append([x, y]) 32 | return ans -------------------------------------------------------------------------------- /Python/Heap/KthLargestElement.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # Aakash Verma 4 | # 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | from heapq import * 10 | 11 | def findKLargestNumbers(nums, k): 12 | min_heap = [] 13 | 14 | for i in range(k): 15 | heappush(min_heap, nums[i]) 16 | 17 | for i in range(k, len(nums)): 18 | if nums[i] > min_heap[0]: 19 | heappop(min_heap) 20 | heappush(min_heap, nums[i]) 21 | 22 | return min_heap[0] 23 | 24 | if __name__ == '__main__': 25 | 26 | print(findKLargestNumbers([3, 1, 5, 12, 2, 11], 3)) 27 | -------------------------------------------------------------------------------- /Python/Heap/KthSmallestElement.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # Aakash Verma 4 | # 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | from heapq import * 10 | 11 | def findKthSmallestNumber(nums, k): 12 | max_heap = [] 13 | 14 | for i in range(k): 15 | heappush(max_heap, -nums[i]) 16 | 17 | for i in range(k, len(nums)): 18 | if -nums[i] > max_heap[0]: 19 | heappop(max_heap) 20 | heappush(max_heap, -nums[i]) 21 | 22 | return -max_heap[0] 23 | 24 | if __name__ == '__main__': 25 | 26 | print(findKthSmallestNumber([3, 1, 5, 12, 2, 11], 3)) 27 | -------------------------------------------------------------------------------- /Python/Heap/Largest_K_Elements.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # Aakash Verma 4 | # 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | from heapq import * 10 | 11 | def findKLargestNumbers(nums, k): 12 | min_heap = [] 13 | 14 | for i in range(k): 15 | heappush(min_heap, nums[i]) 16 | 17 | for i in range(k, len(nums)): 18 | if nums[i] > min_heap[0]: 19 | heappop(min_heap) 20 | heappush(min_heap, nums[i]) 21 | 22 | return list(min_heap) 23 | 24 | if __name__ == '__main__': 25 | 26 | print(findKLargestNumbers([3, 1, 5, 12, 2, 11], 3)) 27 | -------------------------------------------------------------------------------- /Python/Heap/RearrangeString.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # www.aboutaakash.in 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | # Youtube: https://www.youtube.com/channel/UC7A5AUQ7sZTJ7A1r8J9hw9A 9 | 10 | # Problem Statement: Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same. 11 | # If possible, output any possible result. If not possible, return the empty string. 12 | # Problem Link: https://leetcode.com/problems/reorganize-string/ 13 | 14 | 15 | from heapq import * 16 | 17 | def rearrange_string(string): 18 | 19 | hash_map = dict() 20 | for char in string: 21 | hash_map[char] = hash_map.get(char, 0) + 1 22 | 23 | max_heap = [] 24 | 25 | for char, freq in hash_map.items(): 26 | heappush(max_heap, (-freq, char)) 27 | 28 | prev_characecter, prev_frequency = None, 0 29 | 30 | resultString = [] 31 | 32 | while max_heap: 33 | freq, char = heappop(max_heap) 34 | 35 | if prev_characecter and -prev_frequency > 0: 36 | heappush(max_heap, (prev_frequency, prev_characecter)) 37 | 38 | resultString.append(char) 39 | prev_characecter = char 40 | prev_frequency = freq + 1 41 | 42 | return ''.join(resultString) 43 | if(len(resultString) == len(string)): 44 | return resultString 45 | else: 46 | return "" 47 | 48 | if __name__ == '__main__': 49 | string1 = "Programming" 50 | ans1 = rearrange_string(string1) 51 | print(ans1) 52 | 53 | -------------------------------------------------------------------------------- /Python/Heap/RearrangeStringKDistanceApart.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # www.aboutaakash.in 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | # Youtube: https://www.youtube.com/channel/UC7A5AUQ7sZTJ7A1r8J9hw9A 9 | 10 | # Problem Statement: Given a string and a number ‘K’, find if the string can be rearranged such that the same characters 11 | # are at least ‘K’ distance apart from each other. 12 | # Problem Link: https://leetcode.com/problems/rearrange-string-k-distance-apart/ 13 | 14 | 15 | from heapq import * 16 | from collections import deque 17 | 18 | def rearrange_string_k_distnace_apart(string, k): 19 | 20 | if k <= 1: 21 | return string 22 | 23 | hash_map = dict() 24 | for char in string: 25 | hash_map[char] = hash_map.get(char, 0) + 1 26 | 27 | max_heap = [] 28 | 29 | for char, freq in hash_map.items(): 30 | heappush(max_heap, (-freq, char)) 31 | 32 | queue = deque([]) 33 | resultString = [] 34 | 35 | while max_heap: 36 | freq, char = heappop(max_heap) 37 | resultString.append(char) 38 | queue.append((char, freq + 1)) 39 | 40 | if len(queue) == k: 41 | character, frequency = queue.popleft() 42 | if -frequency > 0: 43 | heappush(max_heap, (frequency, character)) 44 | 45 | 46 | resultString = ''.join(resultString) 47 | if(len(resultString) == len(string)): 48 | return resultString 49 | else: 50 | return "" 51 | 52 | if __name__ == '__main__': 53 | string1 = "aaadbbcc" 54 | ans1 = rearrange_string_k_distnace_apart(string1, 2) 55 | print(ans1) 56 | 57 | -------------------------------------------------------------------------------- /Python/Heap/ReorganizeString.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # Aakash Verma 4 | # 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | from heapq import * 10 | 11 | class Solution: 12 | def reorganizeString(self, s: str) -> str: 13 | hash_map = {} 14 | 15 | for ch in s: 16 | hash_map[ch] = hash_map.get(ch, 0) + 1 17 | 18 | max_heap = [] 19 | 20 | for char, freq in hash_map.items(): 21 | heappush(max_heap, (-freq, char)) 22 | 23 | prev_char = None 24 | prev_freq = None 25 | 26 | res = [] 27 | 28 | while max_heap: 29 | curr_freq, curr_char = heappop(max_heap) 30 | curr_freq = -(curr_freq) 31 | res.append(curr_char) 32 | 33 | if prev_char is not None and prev_freq > 0: 34 | heappush(max_heap, (-prev_freq, prev_char)) 35 | 36 | prev_char = curr_char 37 | prev_freq = curr_freq - 1 38 | 39 | if len(res) == len(s): 40 | return ''.join(res) 41 | else: 42 | return "" 43 | 44 | 45 | -------------------------------------------------------------------------------- /Python/Heap/Smallest_K_Elements.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # Aakash Verma 4 | # 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | from heapq import * 10 | 11 | def findKSmallestNumbers(nums, k): 12 | max_heap = [] 13 | 14 | for i in range(k): 15 | heappush(max_heap, -nums[i]) 16 | 17 | for i in range(k, len(nums)): 18 | if -nums[i] > max_heap[0]: 19 | heappop(max_heap) 20 | heappush(max_heap, -nums[i]) 21 | 22 | ans = [-i for i in max_heap] 23 | return ans 24 | 25 | if __name__ == '__main__': 26 | 27 | print(findKSmallestNumbers([3, 1, 5, 12, 2, 11], 3)) 28 | -------------------------------------------------------------------------------- /Python/Heap/SortCharactersByFrequency.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # Aakash Verma 4 | # 5 | # www.innoskrit.in 6 | # Instagram: https://www.instagram.com/aakashverma1102/ 7 | # LinkedIn: https://www.linkedin.com/in/aakashverma1124/ 8 | 9 | from heapq import * 10 | 11 | def sort_characters_by_frequency(string): 12 | frequency_map = dict() 13 | 14 | for char in string: 15 | frequency_map[char] = frequency_map.get(char, 0) + 1 16 | 17 | max_heap = [] 18 | 19 | for char, frequency in frequency_map.items(): 20 | heappush(max_heap, (-frequency, char)) 21 | 22 | sorted_string = [] 23 | 24 | while max_heap: 25 | frequency, char = heappop(max_heap) 26 | for i in range(-frequency): 27 | sorted_string.append(char) 28 | 29 | return ''.join(sorted_string) 30 | 31 | if __name__ == '__main__': 32 | 33 | string = "tree" 34 | result = sort_characters_by_frequency(string) 35 | print(result) 36 | 37 | -------------------------------------------------------------------------------- /Python/Heap/TopKFrequentElements.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aakashverma1124/Data-Structures-and-Algorithms-for-Interviews/8846ca1447ccb703a8323066cffba5a02e7e140c/Python/Heap/TopKFrequentElements.py -------------------------------------------------------------------------------- /Python/LinkedList/LoopDetection.py: -------------------------------------------------------------------------------- 1 | # 2 | # 3 | # 4 | # @author 5 | # Aakash Verma 6 | # 7 | # Middle Of a Linked List 8 | # 9 | # Output: 10 | # true 11 | # 12 | 13 | 14 | # Below is the structute of a node which is used to create a new node every time. 15 | class Node: 16 | 17 | def __init__(self, data): 18 | self.data = data 19 | self.next = None # None is nothing but null 20 | 21 | # Creating a class for implementing the code for Loop Detection in a LinkedList 22 | class LinkedList: 23 | 24 | # Whenever I'll create the object of a LinkedList class head will be pointing to null initially 25 | def __init__(self): 26 | self.head = None 27 | 28 | 29 | # Inserting at the end of a Linked List (append function) 30 | def append(self, key): 31 | 32 | h = self.head 33 | 34 | if h is None: 35 | new_node = Node(key) 36 | self.head = new_node 37 | else: 38 | while h.next != None: 39 | h = h.next 40 | new_node = Node(key) 41 | h.next = new_node 42 | 43 | # middle of a linked list 44 | def isLoopFound(self): 45 | fast = self.head 46 | slow = self.head 47 | 48 | if self.head is None: 49 | print("The list doesn't exist.") 50 | return False 51 | 52 | 53 | while fast is not None and fast.next is not None: 54 | slow = slow.next 55 | fast = fast.next.next 56 | if slow == fast: 57 | return True 58 | 59 | return False 60 | 61 | 62 | # Code execution starts here 63 | if __name__=='__main__': 64 | 65 | myList = LinkedList() 66 | myList.append(3) 67 | myList.append(4) 68 | myList.append(5) 69 | myList.append(6) 70 | myList.append(7) 71 | myList.head.next.next.next.next.next = myList.head.next.next 72 | loopFound = myList.isLoopFound() 73 | print(loopFound) 74 | 75 | 76 | -------------------------------------------------------------------------------- /Python/MergeIntervals/InsertInterval.py: -------------------------------------------------------------------------------- 1 | class Innoskrit: 2 | def insert(self, intervals, newInterval): 3 | 4 | i = 0 5 | ans = [] 6 | 7 | while i < len(intervals) and intervals[i][1] < newInterval[0]: 8 | ans.append(intervals[i]) 9 | i += 1 10 | 11 | while i < len(intervals) and intervals[i][0] <= newInterval[1]: 12 | newInterval[0] = min(newInterval[0], intervals[i][0]) 13 | newInterval[1] = max(newInterval[1], intervals[i][1]) 14 | i += 1 15 | ans.append(newInterval) 16 | 17 | while i < len(intervals): 18 | ans.append(intervals[i]) 19 | i += 1 20 | 21 | return ans 22 | 23 | if __name__ == "__main__": 24 | intervals = [[1, 3], [5, 7], [8, 12]] 25 | newInterval = [4, 6] 26 | for interval in Innoskrit().insert(intervals, newInterval): 27 | print(interval, end = " ") 28 | print() 29 | -------------------------------------------------------------------------------- /Python/MergeIntervals/IntervalsIntersection.py: -------------------------------------------------------------------------------- 1 | class Innoskrit: 2 | def intervalIntersection(self, arr1, arr2): 3 | 4 | i, j = 0, 0 5 | ans = [] 6 | 7 | while i < len(arr1) and j < len(arr2): 8 | 9 | intersection = [] 10 | intersection.append(max(arr1[i][0], arr2[j][0])) 11 | intersection.append(min(arr1[i][1], arr2[j][1])) 12 | 13 | if(intersection[0] <= intersection[1]): 14 | ans.append(intersection) 15 | 16 | if(arr1[i][1] < arr2[j][1]): 17 | i += 1 18 | else: 19 | j += 1 20 | 21 | return ans 22 | 23 | if __name__ == "__main__": 24 | arr1 = [[1, 3], [5, 6], [7, 9]] 25 | arr2 = [[2, 3], [5, 7]] 26 | for interval in Innoskrit().intervalIntersection(arr1, arr2): 27 | print(interval, end = " ") 28 | print() -------------------------------------------------------------------------------- /Python/Recursion/Fiboanacci.py: -------------------------------------------------------------------------------- 1 | def fibonacci(n): 2 | if (n == 1 or n == 2): 3 | return 1 4 | return fibonacci(n - 1) + fibonacci(n - 2) 5 | 6 | if __name__ == '__main__': 7 | n = 10 8 | print(fibonacci(n)) -------------------------------------------------------------------------------- /Python/Recursion/Handshake.py: -------------------------------------------------------------------------------- 1 | def handshake(n): 2 | if (n == 1): 3 | return 0 4 | return (n - 1) + handshake(n - 1) 5 | 6 | if __name__ == '__main__': 7 | n = 10 8 | print(handshake(n)) -------------------------------------------------------------------------------- /Python/Recursion/LCS.py: -------------------------------------------------------------------------------- 1 | def solve(s1, s2, m, n, dp): 2 | 3 | if m == 0 or n == 0: 4 | dp[m][n] = 0 5 | return dp[m][n] 6 | 7 | if dp[m][n] != -1: 8 | return dp[m][n] 9 | 10 | if s1[m - 1] == s2[n - 1]: 11 | dp[m][n] = 1 + solve(s1, s2, m - 1, n - 1, dp) 12 | return dp[m][n] 13 | 14 | dp[m][n] = max(solve(s1, s2, m, n - 1, dp), solve(s1, s2, m - 1, n, dp)) 15 | return dp[m][n] 16 | 17 | def lcs(s1, s2): 18 | dp = [[-1 for j in range(len(s2) + 1)] for i in range(len(s1) + 1)] 19 | return solve(s1, s2, len(s1), len(s2), dp) 20 | 21 | if __name__ == "__main__": 22 | s1 = "abc" 23 | s2 = "bca" 24 | print(lcs(s1, s2)) -------------------------------------------------------------------------------- /Python/Stack/MaximumAreaHistogram.py: -------------------------------------------------------------------------------- 1 | 2 | # @author 3 | # Aakash.Verma 4 | 5 | # Problem: Find the largest rectangular area possible in a given histogram where the largest 6 | # rectangle can be made of a number of contiguous bars. For simplicity, assume that 7 | # all bars have same width and the width is 1 unit. 8 | 9 | # For example, consider the following histogram with 7 bars of heights {6, 2, 5, 4, 5, 1, 6}. 10 | # The largest possible rectangle possible is 12. 11 | 12 | 13 | def nsel(arr, n): 14 | 15 | nselIndex = [] 16 | s = [] 17 | 18 | for i in range(0, n): 19 | while(len(s) != 0 and s[-1][0] <= arr[i]): 20 | s.pop() 21 | 22 | if len(s) == 0 : 23 | nselIndex.append(-1) 24 | else: 25 | nselIndex.append(s[-1][1]) 26 | 27 | s.append([arr[i], i]) 28 | print(nselIndex) 29 | return nselIndex 30 | 31 | 32 | def nser(arr, n): 33 | 34 | nserIndex = [] 35 | s = [] 36 | 37 | for i in range(n - 1, -1, -1): 38 | while(len(s) != 0 and s[-1][0] <= arr[i]): 39 | s.pop() 40 | 41 | if len(s) == 0 : 42 | nserIndex.append(n) 43 | else: 44 | nserIndex.append(s[-1][1]) 45 | 46 | s.append([arr[i], i]) 47 | 48 | nserIndex.reverse() 49 | print(nserIndex) 50 | return nserIndex 51 | 52 | def maxAreaHistogram(arr, n): 53 | 54 | nselIndexArray = nsel(arr, n) 55 | nserIndexArray = nser(arr, n) 56 | ans = [] 57 | maxArea = 0 58 | for i in range(n): 59 | ans.append((nserIndexArray[i] - nselIndexArray[i] - 1) * arr[i]) 60 | if(maxArea < ans[i]): 61 | maxArea = ans[i] 62 | 63 | return maxArea 64 | 65 | if __name__ == '__main__': 66 | arr = [6, 2, 5, 4, 5, 1, 6] 67 | ans = maxAreaHistogram(arr, len(arr)) 68 | print(ans) -------------------------------------------------------------------------------- /Python/Stack/NGEL.py: -------------------------------------------------------------------------------- 1 | 2 | # @author 3 | # Aakash.Verma 4 | 5 | # Problem: Given an array, print the Next Greater Element (NGE) for every element. 6 | # The Next Greater Element for an element x is the first greater element 7 | # on the left side of x in array. Elements for which no greater element exist, 8 | # consider next greater element as -1. 9 | 10 | 11 | def nextGreaterElementToLeft(arr, n): 12 | s = [] 13 | v = [] 14 | 15 | for i in range(0, n): 16 | while(len(s) != 0 and s[-1] <= arr[i]): 17 | s.pop() 18 | 19 | if len(s) == 0 : 20 | v.append(-1) 21 | 22 | else: 23 | v.append(s[-1]) 24 | 25 | s.append(arr[i]) 26 | 27 | return v 28 | 29 | if __name__ == '__main__': 30 | 31 | arr = [7, 8, 1, 4] 32 | ans = nextGreaterElementToLeft(arr, len(arr)) 33 | print(ans) 34 | -------------------------------------------------------------------------------- /Python/Stack/NGER.py: -------------------------------------------------------------------------------- 1 | 2 | # @author 3 | # Aakash.Verma 4 | 5 | # Problem: Given an array, find an array of Next Greater Elements (NGE) for every element. 6 | # The Next Greater Element for an element x is the first greater element 7 | # on the right side of x in array. Elements for which no greater element exist, 8 | # consider next greater element as -1. 9 | 10 | 11 | def nextGreaterElementToRight(arr, n): 12 | s = [] 13 | v = [] 14 | 15 | for i in range(n-1, -1, -1): 16 | while(len(s) != 0 and s[-1] <= arr[i]): 17 | s.pop() 18 | 19 | if len(s) == 0 : 20 | v.append(-1) 21 | 22 | else: 23 | v.append(s[-1]) 24 | s.append(arr[i]) 25 | 26 | v.reverse() 27 | return v 28 | 29 | if __name__ == '__main__': 30 | 31 | arr = [7, 8, 1, 4] 32 | ans = nextGreaterElementToRight(arr, len(arr)) 33 | print(ans) 34 | -------------------------------------------------------------------------------- /Python/Stack/NSEL.py: -------------------------------------------------------------------------------- 1 | 2 | # @author 3 | # Aakash.Verma 4 | 5 | # Problem: Given an array, print the Next Smaller Element (NSE) for every element. 6 | # The Next Smaller Element for an element x is the first smaller element 7 | # on the left side of x in array. Elements for which no smaller element exist, 8 | # consider next smaller element as -1. 9 | 10 | 11 | def nextSmallerElementToLeft(arr, n): 12 | s = [] 13 | v = [] 14 | 15 | for i in range(0, n): 16 | while(len(s) != 0 and s[-1] >= arr[i]): 17 | s.pop() 18 | 19 | if len(s) == 0 : 20 | v.append(-1) 21 | 22 | else: 23 | v.append(s[-1]) 24 | 25 | s.append(arr[i]) 26 | 27 | return v 28 | 29 | if __name__ == '__main__': 30 | 31 | arr = [7, 8, 1, 4] 32 | ans = nextSmallerElementToLeft(arr, len(arr)) 33 | print(ans) 34 | -------------------------------------------------------------------------------- /Python/Stack/NSER.py: -------------------------------------------------------------------------------- 1 | 2 | # @author 3 | # Aakash.Verma 4 | 5 | # Problem: Given an array, print the Next Smaller Element (NSE) for every element. 6 | # The Next Smaller Element for an element x is the first smaller element 7 | # on the right side of x in array. Elements for which no smaller element exist, 8 | # consider next smaller element as -1. 9 | 10 | 11 | def nextSmallerElementToRight(arr, n): 12 | s = [] 13 | v = [] 14 | 15 | for i in range(n - 1, -1, -1): 16 | while(len(s) != 0 and s[-1] >= arr[i]): 17 | s.pop() 18 | 19 | if len(s) == 0 : 20 | v.append(-1) 21 | 22 | else: 23 | v.append(s[-1]) 24 | 25 | s.append(arr[i]) 26 | v.reverse() 27 | return v 28 | 29 | if __name__ == '__main__': 30 | 31 | arr = [7, 8, 1, 4] 32 | ans = nextSmallerElementToRight(arr, len(arr)) 33 | print(ans) 34 | -------------------------------------------------------------------------------- /Python/Stack/StockSpan.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash.Verma 3 | 4 | # Problem: 5 | # The stock span problem is a financial problem where we have a series of 6 | # n daily price quotes for a stock and we need to calculate span of stock’s 7 | # price for all n days. 8 | # The span Si of the stock’s price on a given day i is defined as the maximum 9 | # number of consecutive days just before the given day, for which the price 10 | # of the stock on the current day is less than or equal to its price on the 11 | # given day. 12 | 13 | def getSpanArray(arr): 14 | 15 | ans = [] 16 | 17 | # Creating Stack to put span & price 18 | prices = [] 19 | span = [] 20 | prices.append(arr[0]) 21 | span.append(1) 22 | ans.append(1) 23 | 24 | for i in range(1, len(arr)): 25 | count = 1 26 | while(len(prices) != 0 and prices[-1] < arr[i]): 27 | count += span[-1] 28 | prices.pop() 29 | span.pop() 30 | 31 | span.append(count) 32 | prices.append(arr[i]) 33 | ans.append(count) 34 | return ans 35 | 36 | if __name__ == '__main__': 37 | arr = [10, 4, 5, 90, 120, 80] 38 | ans = getSpanArray(arr) 39 | print(ans) -------------------------------------------------------------------------------- /Python/Stack/StockSpan2.py: -------------------------------------------------------------------------------- 1 | 2 | # @author 3 | # Aakash.Verma 4 | # Problem: The stock span problem is a financial problem where we have a 5 | # series of n daily price quotes for a stock and we need to calculate span 6 | # of stock’s price for all n days. 7 | # The span Si of the stock’s price on a given day i is defined as the 8 | # maximum number of consecutive days just before the given day, for which 9 | # the price of the stock on the current day is less than or equal to its 10 | # price on the given day. 11 | 12 | # Output: [1, 1, 1, 2, 1, 4, 6] 13 | 14 | 15 | def stockSpan(arr, n): 16 | s = [] 17 | v = [] 18 | span = [] 19 | 20 | for i in range(0, n): 21 | while(len(s) != 0 and s[-1][0] <= arr[i]): 22 | s.pop() 23 | 24 | if len(s) == 0 : 25 | v.append(-1) 26 | 27 | else: 28 | v.append(s[-1][1]) 29 | 30 | s.append([arr[i], i]) 31 | 32 | for i in range(n): 33 | span.append(i - v[i]) 34 | return span 35 | 36 | if __name__ == '__main__': 37 | 38 | arr = [100, 80, 60, 70, 60, 75, 85] 39 | ans = stockSpan(arr, len(arr)) 40 | print(ans) 41 | -------------------------------------------------------------------------------- /Python/TopologicalSort/AlienDictionary.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def alienOrder(words): 4 | if len(words) == 0: 5 | return "" 6 | 7 | in_degree = {} 8 | graph = {} 9 | 10 | for word in words: 11 | for char in word: 12 | in_degree[char] = 0 13 | graph[char] = [] 14 | 15 | for i in range(len(words) - 1): 16 | w1, w2 = words[i], words[i + 1] 17 | if len(w2) < len(w1) and w1.startswith(w2): 18 | return "" 19 | for j in range(min(len(w1), len(w2))): 20 | parent, child = w1[j], w2[j] 21 | if parent != child: 22 | graph[parent].append(child) 23 | in_degree[child] += 1 24 | break 25 | 26 | queue = deque() 27 | for key in in_degree: 28 | if in_degree[key] == 0: 29 | queue.append(key) 30 | 31 | sorted_order = [] 32 | while queue: 33 | vertex = queue.popleft() 34 | sorted_order.append(vertex) 35 | for child in graph[vertex]: 36 | in_degree[child] -= 1 37 | if in_degree[child] == 0: 38 | queue.append(child) 39 | 40 | if len(sorted_order) != len(in_degree): 41 | return "" 42 | 43 | return ''.join(sorted_order) 44 | 45 | 46 | if __name__ == '__main__': 47 | words = ["ywx", "wz", "xww", "xz", "zyy", "zwz"] 48 | ans = findOrder(words) 49 | print(ans) -------------------------------------------------------------------------------- /Python/TopologicalSort/TopologicalSort.py: -------------------------------------------------------------------------------- 1 | # @author 2 | # Aakash Verma 3 | 4 | # Output: 5 | # 5 6 3 4 0 2 1 6 | 7 | from collections import deque 8 | 9 | def topologicalSort(edges, vertices): 10 | sorted_order = [] 11 | if(vertices <= 0): 12 | return sorted_order 13 | 14 | in_degree = dict() 15 | graph = dict() 16 | 17 | # intializing the graph 18 | for i in range(vertices): 19 | in_degree[i] = 0 20 | graph[i] = [] 21 | 22 | # building the graph 23 | for i in range(len(edges)): 24 | parent = edges[i][0] 25 | child = edges[i][1] 26 | in_degree[child] += 1 27 | graph[parent].append(child) 28 | 29 | # processing all valid starting nodes 30 | queue = deque() 31 | for key in in_degree: 32 | if in_degree[key] == 0: 33 | queue.append(key) 34 | 35 | while queue: 36 | vertex = queue.popleft() 37 | sorted_order.append(vertex) 38 | children = graph[vertex] 39 | for child in children: 40 | in_degree[child] -= 1 41 | if in_degree[child] == 0: 42 | queue.append(child) 43 | 44 | if len(sorted_order) != vertices: 45 | return [] 46 | 47 | return sorted_order 48 | 49 | 50 | 51 | if __name__ == '__main__': 52 | 53 | edges = [[6, 4], [6, 2], [5, 3], [5, 4], [3, 0], [3, 1], [3, 2], [4, 1]] 54 | ans = topologicalSort(edges, 7) 55 | print(ans) -------------------------------------------------------------------------------- /Python/TreeConstructions/TreeFromInorderPostorder.py: -------------------------------------------------------------------------------- 1 | # 2 | # @author 3 | # aakash.verma 4 | # 5 | 6 | 7 | class TreeNode: 8 | def __init__(self, val=0, left=None, right=None): 9 | self.val = val 10 | self.left = left 11 | self.right = right 12 | 13 | class Solution: 14 | 15 | # LeetCode Code 16 | # Line 18 - 31 17 | 18 | inorder_map = {} 19 | def solve(postorder, left, right): 20 | if left > right: 21 | return None 22 | rootValue = postorder.pop() 23 | index = Solution.inorder_map[rootValue] 24 | root = TreeNode(rootValue) 25 | root.right = Solution.solve(postorder, index + 1, right) 26 | root.left = Solution.solve(postorder, left, index - 1) 27 | return root 28 | 29 | def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: 30 | Solution.inorder_map = {val:index for index, val in enumerate(inorder)} 31 | return Solution.solve(postorder, 0, len(inorder) - 1) 32 | 33 | if __name__ == '__main__': 34 | 35 | inorder = [9,3,15,20,7] 36 | postorder = [9,15,7,20,3] 37 | root = buildTree(inorder, postorder) 38 | # We can write the code for BFS traversal to check the formed tree. -------------------------------------------------------------------------------- /go/LinkedList/linkedlist_deletion/delete_linked_list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | type Node struct { 9 | Data int 10 | Next *Node 11 | } 12 | 13 | func NewNode(data int) *Node { // create New Node 14 | return &Node{ 15 | Data: data, 16 | Next: nil, 17 | } 18 | } 19 | 20 | type LinkedListDeletion struct { 21 | head *Node 22 | } 23 | 24 | func (list *LinkedListDeletion) Print() { 25 | current := list.head 26 | for current != nil { 27 | fmt.Printf("%d ", current.Data) 28 | current = current.Next 29 | } 30 | fmt.Println() 31 | } 32 | 33 | func (list *LinkedListDeletion) DeleteFromStart() { 34 | if list.head == nil { 35 | log.Printf("Can't delete from Empty List") 36 | return 37 | } 38 | list.head = list.head.Next 39 | } 40 | 41 | func (list *LinkedListDeletion) DeleteAfterNode(nodeAfter int) { 42 | current := list.head 43 | prev := &Node{} 44 | for current != nil { 45 | if current.Data == nodeAfter { // If nodeAfterExist 46 | break 47 | } 48 | prev = current 49 | current = current.Next 50 | } 51 | if current == nil { 52 | log.Println("DeleteAfterNode operation can't perform as nodeAfter does not exist") 53 | return 54 | } 55 | prev.Next = current.Next 56 | } 57 | 58 | func (list *LinkedListDeletion) DeleteFromEnd() { 59 | current := list.head 60 | prev := &Node{} 61 | for current != nil && current.Next != nil { // traverse till last node 62 | prev = current 63 | current = current.Next 64 | } 65 | prev.Next = nil 66 | } 67 | -------------------------------------------------------------------------------- /go/LinkedList/linkedlist_deletion/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Data-Structures-and-Algorithms-for-Interviews/go/LinkedList/linkedlist_deletion 2 | 3 | go 1.20 4 | -------------------------------------------------------------------------------- /go/LinkedList/linkedlist_deletion/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /* 6 | * 7 | * @author 8 | * Md Hasnain 9 | * 10 | * Deletion from Linked List 11 | * 12 | * Output: 13 | * 14 | * Initial list is: 1 2 3 4 5 15 | * After Deleting at the Beginning, list is: 2 3 4 5 16 | * After Deleting at the End, list is: 2 3 4 17 | * After Inserting after given node, list is: 2 4 18 | * 19 | * 20 | * 21 | */ 22 | 23 | func main() { 24 | list := LinkedListDeletion{} 25 | 26 | list.head = NewNode(1) 27 | current := list.head 28 | for i := 2; i <= 5; i++ { 29 | // if current == nil { 30 | // current = NewNode(i) 31 | // } else { 32 | current.Next = NewNode(i) 33 | // } 34 | current = current.Next 35 | } 36 | 37 | fmt.Print("Initial List: ") 38 | list.Print() 39 | list.DeleteFromStart() 40 | fmt.Print("List after deleting at beginning: ") 41 | list.Print() 42 | list.DeleteFromEnd() 43 | fmt.Print("List after deleting at end: ") 44 | list.Print() 45 | list.DeleteAfterNode(3) 46 | fmt.Print("List after deleting given node: ") 47 | list.Print() 48 | } 49 | -------------------------------------------------------------------------------- /go/LinkedList/linkedlist_insertion/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Data-Structures-and-Algorithms-for-Interviews/go/LinkedList/linkedlist_insertion 2 | 3 | go 1.20 4 | -------------------------------------------------------------------------------- /go/LinkedList/linkedlist_insertion/insert_linked_list.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | ) 7 | 8 | type Node struct { 9 | Data int 10 | Next *Node 11 | } 12 | 13 | func NewNode(data int) *Node { // create New Node 14 | return &Node{ 15 | Data: data, 16 | Next: nil, 17 | } 18 | } 19 | 20 | type LinkedListInsertion struct { 21 | head *Node 22 | } 23 | 24 | func (list *LinkedListInsertion) Print() { 25 | current := list.head 26 | for current != nil { 27 | fmt.Printf("%d ", current.Data) 28 | current = current.Next 29 | } 30 | fmt.Println() 31 | } 32 | 33 | func (list *LinkedListInsertion) InsertAtBeggining(key int) { 34 | newNode := NewNode(key) 35 | newNode.Next = list.head 36 | list.head = newNode 37 | } 38 | 39 | func (list *LinkedListInsertion) InsertAfterNode(key, nodeAfter int) { 40 | current := list.head 41 | for current != nil { 42 | if current.Data == nodeAfter { // If nodeAfterExist 43 | break 44 | } 45 | current = current.Next 46 | } 47 | if current == nil { 48 | log.Println("InsertAfterNode operation can't perform as nodeAfter does not exist") 49 | return 50 | } 51 | temp := current.Next 52 | newNode := NewNode(key) 53 | current.Next = newNode 54 | newNode.Next = temp 55 | } 56 | 57 | func (list *LinkedListInsertion) InsertAtEnd(key int) { 58 | current := list.head 59 | for current != nil && current.Next != nil { // traverse till last node 60 | current = current.Next 61 | } 62 | 63 | newNode := NewNode(key) 64 | current.Next = newNode 65 | } 66 | -------------------------------------------------------------------------------- /go/LinkedList/linkedlist_insertion/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /* 6 | * 7 | * @author 8 | * Md Hasnain 9 | * 10 | * Insertion in Linked List 11 | * 12 | * Output: 13 | * 14 | * Initial list is: 1 2 3 15 | * After Inserting at the Beginning, list is: 4 1 2 3 16 | * After Inserting at the End, list is: 4 1 2 3 5 17 | * After Inserting after given node, list is: 4 1 2 3 7 5 18 | * 19 | * 20 | * 21 | */ 22 | 23 | func main() { 24 | list := LinkedListInsertion{} 25 | 26 | list.head = NewNode(1) 27 | list.head.Next = NewNode(2) 28 | list.head.Next.Next = NewNode(3) 29 | fmt.Print("Initial List: ") 30 | list.Print() 31 | list.InsertAtBeggining(4) 32 | fmt.Print("List after inserting at beginning: ") 33 | list.Print() 34 | list.InsertAtEnd(5) 35 | fmt.Print("List after inserting at end: ") 36 | list.Print() 37 | list.InsertAfterNode(7, 3) 38 | fmt.Print("List after inserting at after given node: ") 39 | list.Print() 40 | } 41 | -------------------------------------------------------------------------------- /javascript/HelloWorld.js: -------------------------------------------------------------------------------- 1 | console.log("Hello World!") --------------------------------------------------------------------------------