├── .vscode └── settings.json ├── CONTRIBUTING.md ├── Dijkstra-Algorithm.cpp ├── InfixToPostfix.c ├── LICENSE ├── README.md └── codes ├── cpp ├── 3sumclosest.cpp ├── AddTwoNumbers.cpp ├── AddTwoNumbers2.cpp ├── BinaryTreeRightSideViewProg.cpp ├── Construct Binary Search Tree from Preorder Traversal ├── CopyListWithRandomPointer.cpp ├── Design-Hashmap.cpp ├── Generate Parentheses ├── Implementing-Dijkstra-Algorithm.cpp ├── LinkedListCycle2.cpp ├── LongestSubstringWithoutRepeatingCharacters.cpp ├── Max Path Sum.cpp ├── OddEvenList.cpp ├── RemoveNthNodeFromEndOfList.cpp ├── ReverseInteger.cpp ├── SearchRotatedSortedArray.cpp ├── Serialize and Deserialize BST ├── Set-Matrix-Zero.cpp ├── SortColors.cpp ├── SpiralMatrix.cpp ├── TrappingRainWater.cpp ├── combination_sum_iii.cpp ├── generate_paranthesis.cpp ├── generate_subsets.cpp ├── generate_subsets_bit_masking.cpp ├── longestPalindromicSubsequence.cpp ├── minimumswapstomakesequencesincreasing.cpp ├── nextPermutation.cpp ├── next_greater_element3.cpp ├── partitionEqualSubsetSum.cpp ├── shortestCommonSupersequence.cpp ├── sum_of_subarray_minimums.cpp ├── targetSum.cpp ├── trapping_rainwater.cpp └── word_break.cpp ├── java ├── 3sumclosest.java ├── FirstUniqueCharacterinaString.java ├── GenerateParentheses.java ├── GroupAnagramsProg.java ├── HouseRobberII.java ├── KthBitNthBinaryString.java ├── LongestCommonSubstring.java ├── LongestValidParentheses.java ├── RegularExpressionMatching.java ├── RotateImage.java ├── Stringtointeger.java ├── SubstringWithConcatenationOfAllWords.java ├── containerwithmostwater.java ├── integertoroman.java ├── kadanesalgo.java ├── maximum-length-of-a-concatenated-string-with-unique-characters.java ├── minimumswapstomakesequencesincreasing.java ├── setmatrixzeros.java ├── timebasedkeyvaluestore.java └── zigzagconversion.java └── python ├── Alien_Dic.py ├── DijkstraAlgo.py ├── InterleavingStringsProg.py ├── KadaneAlgo.py ├── Palind_Part.py ├── Sum_of_k_smallest_elements_in_BST.py ├── designLinkedList.py ├── flattenbinarytree.py ├── largest_rectangular_sub_matrix_sum_divisbl_by_k ├── timebasedkeyvaluestore.py └── wigglesubsequence.py /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "githubPullRequests.ignoredPullRequestBranches": [ 3 | "main" 4 | ] 5 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # 🎃 HacktoberFest is here 🎃 2 | 3 | Use this project to make your first contribution to an open source project on GitHub. Practice making your first pull request to a public repository before doing the real thing! 4 | 5 | Celebrate [Hacktoberfest](https://hacktoberfest.digitalocean.com/) by getting involved in the open source community by completing some simple tasks in this project. 6 | 7 | 8 | [https://github.com/GDSC-TMSL/ProjectAlgorithms/](https://github.com/GDSC-TMSL/ProjectAlgorithms/) 9 | 10 |
11 | 12 | ## What is Hacktoberfest? 13 | A month-long celebration from October 1st - 31st sponsored by [Digital Ocean](https://hacktoberfest.digitalocean.com/) and [GitHub](https://github.com/blog/2433-celebrate-open-source-this-october-with-hacktoberfest) to get people involved in [Open Source](https://github.com/open-source). Create your very first pull request to any public repository on GitHub and contribute to the open source developer community. 14 | 15 | [https://hacktoberfest.digitalocean.com/](https://hacktoberfest.digitalocean.com/) 16 | 17 |
18 | 19 | # What is this project? 20 | ## Project Algorithms 21 | A place where you can find solutions to the most asked interview questions. 22 | 23 | You can contribute by adding new questions and their solutions to the repository. 24 | 25 |
26 | 27 | # Contribution in short 28 | 29 | 1. Check if the question your adding already exists. 30 | 2. If not, then go to issues and see if someone has added an issue raising the same issue. 31 | 3. If you see that no such issue exists then make a new issue. Make sure to mention which questions your adding and the links to ***Your*** solutions. 32 | 4. After having the new issue has been assigned to you, start working on the same. Make sure to follow the rules after this section. ***Maintain the structure of the repository. If the structure is not maintained then the PR might not be accepted***. 33 | 5. Send a PR. Do mention which Issue you solved by referencing it with a # and then typing the name of your issue. 34 | 6. Make the steps below to get more details and a walkthrough of the PR process. 35 | 36 |
37 | 38 | # How to contribute to this project 39 | Here are 3 quick and painless steps to contribute to this project: 40 | 41 | * Make a new issue under (check if the same issue is open before checking that). 42 | * Wait for you to be assingned the issue. 43 | * Once assingned, you can make the changes you need and send a PR this way. After reviewing of the code, we will merge it. 44 | 45 |
46 | 47 | # Getting started 48 | * Fork this repository (Click the Fork button in the top right of this page, click your Profile Image) 49 | * Clone your fork down to your local machine 50 | 51 | ```markdown 52 | git clone https://github.com/your-username/ProjectAlgorithms.git 53 | ``` 54 | 55 | * Create a branch 56 | 57 | ```markdown 58 | git checkout -b branch-name 59 | ``` 60 | 61 | * Make your changes (choose from any task below) 62 | * Commit and push 63 | 64 | ```markdown 65 | git add . 66 | git commit -m 'Commit message' 67 | git push origin branch-name 68 | ``` 69 | 70 | * Create a new pull request from your forked repository (Click the `New Pull Request` button located at the top of your repo) 71 | * Wait for your PR review and merge approval! 72 | * __Star this repository__ if you had fun! 73 | 74 |
75 | 76 | # Some things to keep in mind. 77 | ### 1. Add some feature/ Improve existing feature. 78 | Usually when you feel the project is missing something, you want to add some feature. 79 | 80 | ```markdown 81 | #### How to make a good issue. 82 | - Identify the problem. 83 | - See if a same issue has already been created. 84 | - Issue Name: Make a apt but compact name. 85 | - Issue Desription: Why did you make this issue? What was the repo missing. 86 | - Finally: How did you fix the issue. 87 | ``` 88 | 89 | ### 2. Branch Names 90 | When making a branch with git checkout -b "new-branch", keep these things in mind. 91 | 92 | ```markdown 93 | # Branch Name 94 | Name the branch something short but apt. It cannot have spaces. 95 | ``` 96 | 97 | ### 3. Get Coding 98 | Let your inner code show its colours. Do keep these in mind. 99 | 100 | ```markdown 101 | # Commit messages 102 | The commit messages must be a small description of what you are trying to fix, add or remove. Its usually around 5-15 words. 103 | ``` 104 | 105 |
106 | 107 | ## Shoutout to our awesome contributors 108 | 109 | 110 | 111 | 112 | 113 | 114 |
115 | -------------------------------------------------------------------------------- /Dijkstra-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | Question Implementing Dijkstra Algorithm 2 | Given a weighted, undirected and connected graph of V vertices and an adjacency list adj where adj[i] is a list of lists containing two integers where the first integer of each list j denotes there is edge between i and j , second integers corresponds to the weight of that edge . You are given the source vertex S and You to Find the shortest distance of all the vertex's from the source vertex S. You have to return a list of integers denoting shortest distance between each node and Source vertex S. 3 | 4 | 5 | 6 | Note: The Graph doesn't contain any negative weight cycle. 7 | Question Link - https://practice.geeksforgeeks.org/problems/implementing-dijkstra-set-1-adjacency-matrix/1 8 | Youtube Link - https://youtu.be/SQ-pXKsBBz8 9 | 10 | //{ Driver Code Starts 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | // } Driver Code Ends 17 | 18 | class Solution 19 | 20 | { 21 | 22 | public: 23 | 24 | //Function to find the shortest distance of all the vertices 25 | 26 | //from the source vertex S. 27 | 28 | vector dijkstra(int V, vector> adj[], int S) 29 | 30 | { 31 | 32 | // Code here 33 | 34 | priority_queue, vector>, greater>> pq; 35 | 36 | 37 | 38 | vector dist(V); 39 | 40 | for (int i=0; i> t; 99 | 100 | while (t--) { 101 | 102 | int V, E; 103 | 104 | cin >> V >> E; 105 | 106 | vector> adj[V]; 107 | 108 | int i=0; 109 | 110 | while (i++> u >> v >> w; 115 | 116 | vector t1,t2; 117 | 118 | t1.push_back(v); 119 | 120 | t1.push_back(w); 121 | 122 | adj[u].push_back(t1); 123 | 124 | t2.push_back(u); 125 | 126 | t2.push_back(w); 127 | 128 | adj[v].push_back(t2); 129 | 130 | } 131 | 132 | int S; 133 | 134 | cin>>S; 135 | 136 | 137 | 138 | Solution obj; 139 | 140 | vector res = obj.dijkstra(V, adj, S); 141 | 142 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | typedef struct { 6 | int size; 7 | int top; 8 | char *arr; 9 | }stack; 10 | 11 | int isEmpty(stack *s){ 12 | 13 | if(s->top == -1) 14 | return 1; 15 | 16 | return 0; 17 | } 18 | 19 | int isFull(stack *s) { 20 | 21 | if(s->top == s->size - 1) 22 | return 1; 23 | 24 | return 0; 25 | } 26 | 27 | void push(stack *s, char d) { 28 | 29 | if(isFull(s)){ 30 | printf("Stack Overflow!\n"); 31 | return; 32 | } 33 | 34 | s->top++; 35 | s->arr[s->top] = d; 36 | } 37 | 38 | char pop(stack *s) { 39 | 40 | if(isEmpty(s)){ 41 | printf("Stack Underflow! Cannot pop more\n"); 42 | return -1; 43 | } 44 | 45 | char val = s->arr[s->top]; 46 | s->top--; 47 | return val; 48 | } 49 | 50 | char peek(stack *s) { 51 | return s->arr[s->top]; 52 | } 53 | 54 | int precedence(char ch) { 55 | 56 | if(ch == '*' || ch == '/') 57 | return 3; 58 | else if(ch == '+' || ch == '-') 59 | return 2; 60 | else 61 | return 0; 62 | } 63 | 64 | int isOperator(char ch) { 65 | 66 | if(ch == '+' || ch == '-' || ch == '*' || ch == '/') 67 | return 1; 68 | 69 | return 0; 70 | } 71 | 72 | char* infixToPostfix(char* infix) { 73 | 74 | stack *s = (stack *)malloc(sizeof(stack)); 75 | s->size = 100; 76 | s->top = -1; 77 | s->arr = (char *)malloc(s->size * sizeof(char)); 78 | 79 | char* postfix = (char *)malloc((strlen(infix)+1) * sizeof(char)); 80 | 81 | int i = 0;// Track infix traversal 82 | int j = 0;// Track Postfix addition 83 | 84 | while(infix[i] != '\0') { 85 | if(!isOperator(infix[i])){ 86 | postfix[j] = infix[i]; 87 | j++; 88 | i++; 89 | } 90 | else{ 91 | if(precedence(infix[i])>precedence(peek(s))){ 92 | push(s, infix[i]); 93 | i++; 94 | } 95 | else{ 96 | postfix[j] = pop(s); 97 | j++; 98 | } 99 | } 100 | } 101 | 102 | while(!isEmpty(s)){ 103 | 104 | postfix[j] = pop(s); 105 | j++; 106 | } 107 | 108 | postfix[j] = '\0'; 109 | return postfix; 110 | } 111 | 112 | int main() { 113 | 114 | char* infix = "x-y/z-k*d"; 115 | 116 | printf("Postfix: %s\n", infixToPostfix(infix)); 117 | 118 | // push(s, 10); 119 | // push(s, 20); 120 | // push(s, 30); 121 | // push(s, 40); 122 | // push(s, 50); 123 | // push(s, 60);// Stack overflow occurs here 124 | 125 | // printf("Popped %d\n", pop(s)); 126 | // printf("Popped %d\n", pop(s)); 127 | // printf("Popped %d\n", pop(s)); 128 | // printf("Popped %d\n", pop(s)); 129 | // printf("Popped %d\n", pop(s)); 130 | // printf("Popped %d\n", pop(s));// Stack underflow occurs here 131 | 132 | 133 | 134 | return 0; 135 | } 136 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Google Developer Student Club - Techno Main Salt Lake 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | 6 | 7 | 8 |

Project Algorithms - A Problem Solver's Paradise 9 |

10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 |

18 | 19 | 20 | 21 | 22 | | Problem Name | Link | Approach | Code | 23 | | ------- | ------- | ---------- | -------- | 24 | | 3 Sum Closest | [LeetCode](https://leetcode.com/problems/3sum-closest/) | [Youtube](https://www.youtube.com/watch?v=qBr2hq4daWE) | [Java](./codes/java/3sumclosest.java)
[C++](./codes/cpp/3sumclosest.cpp) | 25 | | Time Based Key Value Store | [LeetCode](https://leetcode.com/problems/time-based-key-value-store/) | [Youtube](https://www.youtube.com/watch?v=fu2cD_6E8Hw)
[Medium](https://sakshi8699.medium.com/981-time-based-key-value-store-python-65bd81742818)| [Java](./codes/java/timebasedkeyvaluestore.java)
[Python](./codes/python/timebasedkeyvaluestore.py) | 26 | | Longest Common Substring | [GFG](https://www.geeksforgeeks.org/longest-common-substring-dp-29/) | [Youtube](https://www.youtube.com/watch?v=_wP9mWNPL5w&t=689s) | [Java](./codes/java/LongestCommonSubstring.java) 27 | | House Robber II | [LeetCode](https://leetcode.com/problems/house-robber-ii/) | [Youtube](https://www.youtube.com/watch?v=3WaxQMELSkw) | [Java](./codes/java/HouseRobberII.java) | 28 | | Design Hashmap | [LeetCode](https://leetcode.com/problems/design-hashmap/) | [Youtube](https://youtu.be/Xt4TuW31rtc?si=lEAxCq8KEhg45AA1) | [C++](./codes/cpp/Design-Hashmap.cpp) | 29 | | Minimum Swaps To Make Sequences Increasing | [LeetCode](https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/) | [Youtube](https://www.youtube.com/watch?v=IeT9Qz_vqHo) | [Java](./codes/java/minimumswapstomakesequencesincreasing.java)
[C++](./codes/cpp/minimumswapstomakesequencesincreasing.cpp) | 30 | | Find Kth Bit in Nth Binary String | [LeetCode](https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/) | [Youtube](https://www.youtube.com/watch?v=34QYE5HAFy4) | [Java](./codes/java/KthBitNthBinaryString.java) 31 | | Set Matrix Zeros | [LeetCode](https://leetcode.com/problems/set-matrix-zeroes/) | [Youtube](https://www.youtube.com/watch?v=M65xBewcqcI) | [Java](./codes/java/setmatrixzeros.java) | 32 | | Generate Parentheses | [LeetCode](https://leetcode.com/problems/generate-parentheses/) | [YouTube](https://www.youtube.com/watch?v=4KpSXSIPH2s&t=860s) | [C++](https://github.com/VetlaPavanKalyan/ProjectAlgorithms/blob/main/codes/cpp/generate_paranthesis.cpp)
[Java](codes/java/GenerateParentheses.java) 33 | | Generate Subsets | [LeetCode](https://leetcode.com/problems/subsets/) | [YouTube](https://www.youtube.com/watch?v=4KpSXSIPH2s&t=860s) | [C++](https://github.com/VetlaPavanKalyan/ProjectAlgorithms/blob/main/codes/cpp/generate_subsets.cpp) | 34 | | Generate Subsets using Bit-Masking | [LeetCode](https://leetcode.com/problems/subsets/) | [YouTube](https://www.youtube.com/watch?v=4KpSXSIPH2s&t=860s) | [C++](https://github.com/VetlaPavanKalyan/ProjectAlgorithms/blob/main/codes/cpp/generate_subsets_bit_masking.cpp) | 35 | | Serialize and Deserialize BST | [Leetcode](https://leetcode.com/problems/serialize-and-deserialize-bst/) | [YouTube](https://www.youtube.com/watch?v=-YbXySKJsX8&t=613s)|[C++](https://github.com/ShreemoyeeMukherjee/ProjectAlgorithms/blob/ShreemoyeeMukherjee-patch-2/Serialize%20and%20Deserialize%20BST) | 36 | | Construct Binary Search Tree from Preorder Traversal | [LeetCode](https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/) | [YouTube](https://www.youtube.com/watch?v=UmJT3j26t1I&t=692s) | [C++](https://github.com/ShreemoyeeMukherjee/ProjectAlgorithms/blob/ShreemoyeeMukherjee-patch-2/codes/cpp/Construct%20Binary%20Search%20Tree%20from%20Preorder%20Traversal) | 37 | | First Unique Character in a String | [LeetCode](https://leetcode.com/problems/first-unique-character-in-a-string/) | [YouTube](https://www.youtube.com/watch?v=St47WCbQa9M) | [Java](./codes/java/FirstUniqueCharacterinaString.java) | 38 | | Trapping Rain Water | [LeetCode](https://leetcode.com/problems/trapping-rain-water/description/) | [YouTube](https://www.youtube.com/watch?v=m18Hntz4go8) | [C++](./codes/cpp/TrappingRainWater.cpp) | 39 | | Interleaving Strings | [LeetCode](https://leetcode.com/problems/interleaving-string/) | [YouTube](https://www.youtube.com/watch?v=3Rw3p9LrgvE) | [Python](./codes/python/InterleavingStringsProg.py) | 40 | | Group Anagrams | [LeetCode](https://leetcode.com/problems/group-anagrams/) | [YouTube](https://www.youtube.com/watch?v=ptgykfAEax8) | [Java](./codes/java/GroupAnagramsProg.java) | 41 | | Binary Tree Right Side View | [LeetCode](https://leetcode.com/problems/binary-tree-right-side-view/) | [YouTube](https://www.youtube.com/watch?v=jCqIr_tBLKs&t=390s) | [C++](./codes/cpp/BinaryTreeRightSideViewProg.cpp) | 42 | | Kadane's Algorithm | [GFG](https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1?page=1&company[]=Google&curated[]=7&sortBy=submissions) | [YouTube](https://www.youtube.com/watch?v=w4W6yya1PIc) | [Python](./codes/python/KadaneAlgo.py) | [Java] (./codes/java/kadanesalgo.java) 43 | | Implementing Dijkstra Algorithm | [GFG](https://practice.geeksforgeeks.org/problems/implementing-dijkstra-set-1-adjacency-matrix/1) | [YouTube](https://www.youtube.com/watch?v=SQ-pXKsBBz8) | [Python](./codes/python/DijkstraAlgo.py) | 44 | | Container With Most Water | [LeetCode](https://leetcode.com/problems/container-with-most-water/) | [YouTube](https://www.youtube.com/watch?v=ZHQg07n_tbg) | [Java](./codes/java/containerwithmostwater.java) | 45 | | Zigzag Conversion | [LeetCode](https://leetcode.com/problems/zigzag-conversion/) | [YouTube](https://www.youtube.com/watch?v=pEku6cp_J80) | [Java](./codes/java/zigzagconversion.java) | 46 | | Integer to Roman | [LeetCode](https://leetcode.com/problems/integer-to-roman/) | [YouTube](https://www.youtube.com/watch?v=f_F9ItFyiEg) | [Java](./codes/java/integertoroman.java) | 47 | | Palindromic Partitioning | [GFG](https://practice.geeksforgeeks.org/problems/palindromic-patitioning4845/1?page=1&difficulty[]=2&company[]=Google&curated[]=4&sortBy=submissions) | [YouTube](https://www.youtube.com/watch?v=VOiNexeScLU) | [Python](./codes/python/Palind_Part.py) | 48 | | Alien Dictionary | [GFG](https://practice.geeksforgeeks.org/problems/alien-dictionary/1?page=1&difficulty[]=2&company[]=Google&sortBy=submissions) | [YouTube](https://www.youtube.com/watch?v=U3N_je7tWAs) | [Python](./codes/python/Alien_Dic.py) | 49 | | String To Integer | [GFG](https://www.geeksforgeeks.org/how-to-convert-a-string-to-an-int-in-java/) | [YouTube](https://www.youtube.com/watch?v=Pnaqn6GOyzU) | [Java](./codes/java/Stringtointeger.java) | 50 | | Maximum Length of a Concatenated String with Unique Characters | [LeetCode](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/) | [YouTube](https://www.youtube.com/watch?v=d4SPuvkaeoo) | [Java](./codes/java/maximum-length-of-a-concatenated-string-with-unique-characters.java) | 51 | | Sum of k smallest elements in BST| [GFG](https://www.geeksforgeeks.org/sum-k-smallest-elements-bst/) | [YouTube](https://www.youtube.com/watch?v=S02iWYlmyH4&t=3s) | [Python](./codes/python/Sum_of_k_smallest_elements_in_BST.py) | 52 | | Regular Expression Matching | [LeetCode](https://leetcode.com/problems/regular-expression-matching/) | [YouTube](https://www.youtube.com/watch?v=HAA8mgxlov8) | [Java](./codes/java/RegularExpressionMatching.java) | 53 | | Longest Valid Parentheses | [LeetCode](https://leetcode.com/problems/longest-valid-parentheses/) | [YouTube](https://www.youtube.com/watch?v=VdQuwtEd10M) | [Java](./codes/java/LongestValidParentheses.java) | 54 | | Rotate Image | [LeetCode](https://leetcode.com/problems/rotate-image/) | [YouTube](https://www.youtube.com/watch?v=Y72QeX0Efxw) | [Java](./codes/java/RotateImage.java) | 55 | | Substring with concatenation of all words | [LeetCode](https://leetcode.com/problems/substring-with-concatenation-of-all-words/) | [YouTube](https://www.youtube.com/watch?v=_MGzsJ0F8lE) | [Java](./codes/java/SubstringWithConcatenationOfAllWords.java) | 56 | |Largest rectangular sub-matrix having sum divisible by k| [GFG](https://www.geeksforgeeks.org/largest-rectangular-sub-matrix-sum-divisible-k/) | [YouTube](https://www.youtube.com/watch?v=_MGzsJ0F8lE) | [Python](./codes/python/largest_rectangular_sub_matrix_sum_divisbl_by_k) 57 | |Sum of Subarray Minimums |[LeetCode](https://leetcode.com/problems/sum-of-subarray-minimums/) |[Youtube](https://youtu.be/9-TXIVEXX2w?si=ktLhMFP8uMgkjXp5) |[C++](./codes/cpp/sum_of_subarray_minimums.cpp) 58 | |Trapping Rain Water |[LeetCode](https://leetcode.com/problems/trapping-rain-water/) |[Youtube](https://youtu.be/m18Hntz4go8?si=tIof7wcU0hnYjbyk) |[C++](./codes/cpp/trapping_rainwater.cpp) 59 | |Next Greater Element III |[LeetCode](https://leetcode.com/problems/next-greater-element-iii/) |[Youtube](https://youtu.be/fOeD3CW2c7c?si=n5lOpXS44P7R6q-y)|[C++](./codes/cpp/next_greater_element3.cpp) 60 | | Largest rectangular sub-matrix having sum divisible by k| [GFG](https://www.geeksforgeeks.org/largest-rectangular-sub-matrix-sum-divisible-k/) | [YouTube](https://www.youtube.com/watch?v=_MGzsJ0F8lE) | [Python](./codes/python/largest_rectangular_sub_matrix_sum_divisbl_by_k) 61 | | Word Break |[LeetCode](https://leetcode.com/problems/word-break/) |[Youtube](https://youtu.be/Sx9NNgInc3A?si=tzljO1p5FRdEaAPf) |[C++](./codes/cpp/word_break.cpp) 62 | | Combination Sum III |[LeetCode](https://leetcode.com/problems/combination-sum-iii/) |[Youtube](https://youtu.be/rP_K3WJnRR4?si=W1RUODPlWwOSvsnV) |[C++](./codes/cpp/combination_sum_iii.cpp) 63 | | Remove Nth Node From End of List |[LeetCode](https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/) |[Youtube](https://www.youtube.com/watch?v=Lhu3MsXZy-Q) |[C++](./codes/cpp/RemoveNthNodeFromEndOfList.cpp) | 64 | | Next Permutation |[LeetCode](https://leetcode.com/problems/next-permutation/description/) |[Youtube](https://www.youtube.com/watch?v=JDOXKqF60RQ) |[C++](./codes/cpp/nextPermutation.cpp) | 65 | | Spiral Matrix |[LeetCode](https://leetcode.com/problems/spiral-matrix/description/) |[Youtube](https://www.youtube.com/watch?v=3Zv-s9UUrFM) |[C++](./codes/cpp/SpiralMatrix.cpp) | 66 | | Sort Colors |[LeetCode](https://leetcode.com/problems/sort-colors/description/) |[Youtube](https://www.youtube.com/watch?v=oaVa-9wmpns) |[C++](./codes/cpp/SortColors.cpp)| 67 | | Odd Even Linked List |[LeetCode](https://leetcode.com/problems/odd-even-linked-list/) |[Youtube](https://www.youtube.com/watch?v=_VHInOZbp6A) |[C++](./codes/cpp/OddEvenList.cpp) 68 | | Add Two Numbers II |[LeetCode](https://leetcode.com/problems/add-two-numbers-ii/) |[Youtube](https://www.youtube.com/watch?v=B-uQN5wp6Jg) |[C++](./codes/cpp/AddTwoNumbers2.cpp) 69 | | Search in Rotated Sorted Array |[LeetCode](https://leetcode.com/problems/search-in-rotated-sorted-array/) |[Youtube](https://www.youtube.com/watch?v=iXLMMbdjeNM) |[C++](./codes/cpp/SearchRotatedSortedArray.cpp) 70 | | Linked List Cycle II |[LeetCode](https://leetcode.com/problems/linked-list-cycle-ii/) |[Youtube](https://www.youtube.com/watch?v=QfbOhn0WZ88) |[C++](./codes/cpp/LinkedListCycle2.cpp 71 | | Copy List with Random Pointer |[LeetCode](https://leetcode.com/problems/copy-list-with-random-pointer/) |[Youtube](https://www.youtube.com/watch?v=VNf6VynfpdM) |[C++](./codes/cpp/CopyListWithRandomPointer.cpp) 72 | | Remove Nth Node From End of List |[LeetCode](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) |[Youtube](https://www.youtube.com/watch?v=Lhu3MsXZy-Q) |[C++](./codes/cpp/RemoveNthNodeFromEndOfList.cpp) 73 | | Wiggle Subsequence | [LeetCode](https://leetcode.com/problems/wiggle-subsequence/description/) |[Youtube](https://www.youtube.com/watch?v=xtDu3jm5WsI)|[Python](./codes/python/wigglesubsequence.py) 74 | | Design Linked List | [LeetCode](https://leetcode.com/problems/design-linked-list/description/) |[Youtube](https://www.youtube.com/watch?v=Wf4QhpdVFQo)|[Python](./codes/python/designLinkedList.py) 75 | | Flatten Binary Tree to Linked List| [LeetCode](https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/) |[Youtube](https://www.youtube.com/watch?v=rKnD7rLT0lI)|[Python](./codes/python/flattenbinarytree.py) 76 | | Longest Palindromic Subsequence |[LeetCode](https://leetcode.com/problems/longest-palindromic-subsequence) |[Youtube](https://youtu.be/wuOOOATz_IA?si=uh1SZsPDClMGZHSL) |[C++](./codes/cpp/longestPalindromicSubsequence.cpp) 77 | | Shortest Common Supersequence |[LeetCode](https://leetcode.com/problems/shortest-common-supersequence) |[Youtube](https://youtu.be/823Grn4_dCQ?si=98CB83DN0gOwoa9k) |[C++](./codes/cpp/shortestCommonSupersequence.cpp) 78 | | Partition Equal Subset Sum |[LeetCode](https://leetcode.com/problems/partition-equal-subset-sum) |[Youtube](https://youtu.be/UmMh7xp07kY?si=A4-OUJ4J0MKgzHpu) |[C++](./codes/cpp/partitionEqualSubsetSum.cpp) 79 | | Target Sum |[LeetCode](https://leetcode.com/problems/target-sum) |[Youtube](https://youtu.be/Hw6Ygp3JBYw?si=q3EJhX8Dr9jEQ6nj) |[C++](./codes/cpp/targetSum.cpp) 80 | 81 | 82 |

83 | 84 |
85 | 86 |
87 | 88 | ## Some Free Online Tutorials 89 | 90 | - [C++ STL (Most Useful for Competitive Programming)](https://www.youtube.com/watch?v=R5BEcvTVZj0&list=PLauivoElc3gh3RCiQA82MDI-gJfXQQVnn) 91 | - [Arrays](https://www.youtube.com/watch?v=n60Dn0UsbEk) 92 | - [Searching and Sorting](https://www.youtube.com/playlist?list=PLDzeHZWIZsTp4pb_WBRahP1tnipLuX9qM) 93 | - [Hashing](https://www.youtube.com/playlist?list=PLqM7alHXFySGwXaessYMemAnITqlZdZVE) 94 | - [Strings](https://www.youtube.com/watch?v=Wdjr6uoZ0e0&t=16s) 95 | - [Recursion and Backtracking](https://www.youtube.com/playlist?list=PLgUwDviBIf0rGlzIn_7rsaR2FQ5e6ZOL9) 96 | - [Bit Manipulation](https://www.youtube.com/watch?v=5rtVTYAk9KQ) 97 | - [Linked List](https://www.youtube.com/watch?v=q8gdBn9RPeI&t=2470s) 98 | - [Stack and Queues](https://www.youtube.com/playlist?list=PLgUwDviBIf0oSO572kQ7KCSvCUh1AdILj) 99 | - [Dynamic Programming](https://www.youtube.com/playlist?list=PLgUwDviBIf0qUlt5H_kiKYaNSqJ81PMMY) 100 | - [Data Structures and Algorithms](https://www.youtube.com/playlist?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA) 101 | 102 | 103 | 104 | 105 |


106 | 107 | ## Some Reference Books PDFs 108 | 109 | - [Algorithms](http://dsp-book.narod.ru/Algorithms.pdf)-*Robert Sedgewick* 110 | - [Introduction to Algorithms](https://sd.blackball.lv/library/Introduction_to_Algorithms_Third_Edition_(2009).pdf)-*Thomas H. Cormen,Charles E. Leiserson,Ronald L. Rivest,Clifford Stein* 111 | - [Data Structures and Algorithm made easy](https://www.pdfdrive.com/download.pdf?id=158226594&h=d9a09e7e092770b490569037e38267ec&u=cache&ext=pdf)-*Narasimha Karumanchi* 112 | - [Data Structures and Algorithms in Java](https://cin.ufpe.br/~grm/downloads/Data_Structures_and_Algorithms_in_Java.pdf)-*Robert Lafore* 113 | - [Advanced Data Structures](https://doc.lagout.org/Others/Data%20Structures/Advanced%20Data%20Structures%20%5BBrass%202008-09-08%5D.pdf)-*Peter Brass* 114 | - [Grokking Algorithms](https://edu.anarcho-copy.org/Algorithm/grokking-algorithms-illustrated-programmers-curious.pdf)-*Aditya Y. Bhargava* 115 | - [Problem Solving with Algorithms and Data Structures](https://www.cs.auckland.ac.nz/compsci105s1c/resources/ProblemSolvingwithAlgorithmsandDataStructures.pdf)-*Brad Miller,David Ranum* 116 | 117 |

118 | 119 |


120 | 121 |

122 | 123 | 124 | 125 | 126 |

127 | 128 |
129 | -------------------------------------------------------------------------------- /codes/cpp/3sumclosest.cpp: -------------------------------------------------------------------------------- 1 | //3 Sum Closest 2 | //Question Link :- https://leetcode.com/problems/3sum-closest/ 3 | 4 | /* 5 | class Solution { 6 | public: 7 | int threeSumClosest(vector& nums, int target) { 8 | 9 | } 10 | }; 11 | */ 12 | 13 | class Solution { 14 | public: 15 | int threeSumClosest(vector& nums, int target) { 16 | sort(nums.begin(), nums.end()); 17 | int closestSum = nums[0] + nums[1] + nums[2]; 18 | 19 | for (int i = 0; i < nums.size(); ++i) { 20 | int j = i + 1; 21 | int k = nums.size() - 1; 22 | 23 | while (j < k) { 24 | int sum = nums[i] + nums[j] + nums[k]; 25 | 26 | if (abs(target - sum) < abs(target - closestSum)) { 27 | closestSum = sum; 28 | } 29 | 30 | if (sum < target) { 31 | ++j; 32 | } else if (sum > target) { 33 | --k; 34 | } else { 35 | return target; 36 | } 37 | } 38 | } 39 | 40 | return closestSum; 41 | } 42 | }; -------------------------------------------------------------------------------- /codes/cpp/AddTwoNumbers.cpp: -------------------------------------------------------------------------------- 1 | // You are given two non-empty linked lists representing two non-negative integers. 2 | // The digits are stored in reverse order, and each of their nodes contains 3 | // a single digit. Add the two numbers and return the sum as a linked list. 4 | 5 | #include 6 | using namespace std; 7 | 8 | 9 | ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 10 | ListNode *ans = new ListNode(); 11 | ListNode *temp = ans; 12 | int carry = 0; 13 | while(l1 || l2 || carry){ 14 | int sum = 0; 15 | if(l1){ 16 | sum += l1->val; 17 | l1 = l1->next; 18 | } 19 | 20 | if(l2){ 21 | sum += l2->val; 22 | l2 = l2->next; 23 | } 24 | 25 | sum += carry; 26 | carry = sum/10; 27 | ListNode *node = new ListNode(sum%10); 28 | temp->next = node; 29 | temp = temp->next; 30 | } 31 | return ans->next; 32 | } 33 | -------------------------------------------------------------------------------- /codes/cpp/AddTwoNumbers2.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | ListNode* reverseLL(ListNode *head) 5 | { 6 | ListNode *curr = head; 7 | ListNode *prev = NULL; 8 | ListNode *forward = NULL; 9 | 10 | while (curr) 11 | { 12 | forward = curr->next; 13 | curr->next = prev; 14 | prev = curr; 15 | curr = forward; 16 | } 17 | return prev; 18 | } 19 | ListNode* insert_tail(ListNode *head, int val) 20 | { 21 | ListNode *ptr = new ListNode(val); 22 | ListNode *temp = head; 23 | if (head == NULL) 24 | { 25 | head = ptr; 26 | return head; 27 | } 28 | while (temp->next) 29 | { 30 | temp = temp->next; 31 | } 32 | temp->next = ptr; 33 | return head; 34 | } 35 | ListNode* adding(ListNode *l1, ListNode *l2) 36 | { 37 | ListNode *ans = NULL; 38 | int carry = 0; 39 | int sum = l1->val + l2->val; 40 | while (l1 || l2 || carry) 41 | { 42 | int val1 = 0, val2 = 0; 43 | if (l1) 44 | val1 = l1->val; 45 | if (l2) 46 | val2 = l2->val; 47 | sum = val1 + val2 + carry; 48 | 49 | ans = insert_tail(ans, sum % 10); 50 | carry = sum / 10; 51 | 52 | if (l1) 53 | l1 = l1->next; 54 | if (l2) 55 | l2 = l2->next; 56 | } 57 | return ans; 58 | } 59 | ListNode* addTwoNumbers(ListNode *l1, ListNode *l2) 60 | { 61 | //step 1 62 | l1 = reverseLL(l1); 63 | l2 = reverseLL(l2); 64 | 65 | //step 2 66 | ListNode *ans = adding(l1, l2); 67 | 68 | //step 3 69 | ans = reverseLL(ans); 70 | return ans; 71 | } 72 | 73 | }; -------------------------------------------------------------------------------- /codes/cpp/BinaryTreeRightSideViewProg.cpp: -------------------------------------------------------------------------------- 1 | // BINARY TREE RIGHT SIDE VIEW (LEETCODE 199) SOLUTION 2 | // Question : https://leetcode.com/problems/binary-tree-right-side-view/ 3 | 4 | //-------------------------------------------------------------------------- 5 | 6 | /* 7 | * Definition for a binary tree node. 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 | class Solution { 18 | public: 19 | vector ans; 20 | 21 | vector rightSideView(TreeNode* root) { 22 | if(root==NULL)return ans; 23 | 24 | queueq; 25 | q.push(root); 26 | 27 | // Level order transversal 28 | while(!q.empty()){ 29 | int s=q.size(); 30 | int dat=0; 31 | 32 | while(s){ 33 | TreeNode*temp=q.front(); 34 | q.pop(); 35 | dat=temp->val; 36 | if(temp->left!=NULL)q.push(temp->left); 37 | if(temp->right!=NULL)q.push(temp->right); 38 | s--; 39 | } 40 | 41 | // Simply push ush the last value 42 | ans.push_back(dat); 43 | } 44 | return ans; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /codes/cpp/Construct Binary Search Tree from Preorder Traversal: -------------------------------------------------------------------------------- 1 | Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root. 2 | Input: preorder = [8,5,1,7,10,12] 3 | Output: [8,5,10,1,7,null,12] 4 | /** 5 | * Definition for a binary tree node. 6 | * struct TreeNode { 7 | * int val; 8 | * TreeNode *left; 9 | * TreeNode *right; 10 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 11 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 12 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 13 | * }; 14 | */ 15 | class Solution { 16 | public: 17 | TreeNode* bstFromPreorder(vector& preorder) { 18 | int i = 0; 19 | TreeNode* p = solve(preorder , i , INT_MAX); 20 | return(p); 21 | 22 | } 23 | TreeNode* solve(vector&preorder, int &i , int u) 24 | { 25 | if(i == preorder.size() || preorder[i] > u) 26 | { 27 | return(NULL); 28 | } 29 | TreeNode* m = new TreeNode(preorder[i++]); 30 | m->left = solve(preorder, i , m->val); 31 | m->right = solve(preorder, i , u); 32 | 33 | return(m); 34 | } 35 | }; 36 | -------------------------------------------------------------------------------- /codes/cpp/CopyListWithRandomPointer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | // Definition for a Node. 3 | class Node { 4 | public: 5 | int val; 6 | Node* next; 7 | Node* random; 8 | 9 | Node(int _val) { 10 | val = _val; 11 | next = NULL; 12 | random = NULL; 13 | } 14 | }; 15 | */ 16 | 17 | class Solution 18 | { 19 | public: 20 | Node* insert_tail(Node *head, int val) 21 | { 22 | Node *ptr = new Node(val); 23 | Node *temp = head; 24 | if (head == NULL) 25 | { 26 | head = ptr; 27 | return head; 28 | } 29 | while (temp->next) 30 | { 31 | temp = temp->next; 32 | } 33 | temp->next = ptr; 34 | return head; 35 | } 36 | Node* copyRandomList(Node *head) 37 | { 38 | //step 1: create clone linked list 39 | Node *clone = NULL; 40 | Node *temp = head; 41 | while (temp) 42 | { 43 | clone = insert_tail(clone, temp->val); 44 | temp = temp->next; 45 | } 46 | //step 2: create map 47 | temp = head; 48 | Node *temp1 = clone; 49 | unordered_map mapping; 50 | while (temp) 51 | { 52 | mapping[temp] = temp1; 53 | temp = temp->next; 54 | temp1 = temp1->next; 55 | } 56 | 57 | temp1 = clone; 58 | temp = head; 59 | while (temp) 60 | { 61 | temp1->random = mapping[temp->random]; 62 | temp = temp->next; 63 | temp1 = temp1->next; 64 | } 65 | 66 | return clone; 67 | } 68 | }; -------------------------------------------------------------------------------- /codes/cpp/Design-Hashmap.cpp: -------------------------------------------------------------------------------- 1 | class MyHashMap { 2 | public: 3 | vector vec; 4 | int sz; 5 | 6 | MyHashMap() { 7 | sz = 1e6+1; 8 | 9 | vec.resize(sz); 10 | 11 | fill(vec.begin(), vec.end(), -1); 12 | } 13 | 14 | void put(int key, int value) { 15 | vec[key] = value; 16 | } 17 | 18 | int get(int key) { 19 | return vec[key] ; 20 | } 21 | 22 | void remove(int key) { 23 | vec[key] =-1; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /codes/cpp/Generate Parentheses: -------------------------------------------------------------------------------- 1 | Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. 2 | Input: n = 3 3 | Output: ["((()))","(()())","(())()","()(())","()()()"] 4 | class Solution { 5 | public: 6 | 7 | void generate(string &s, int open, int close) 8 | { 9 | if(open == 0 && close == 0) 10 | { 11 | v.push_back(s); 12 | return; 13 | } 14 | if(open > 0) 15 | { 16 | s.push_back('('); 17 | generate(s, open - 1, close); 18 | s.pop_back(); 19 | } 20 | if(close > 0) 21 | { 22 | if(open < close) 23 | { 24 | s.push_back(')'); 25 | generate(s, open, close - 1); 26 | s.pop_back(); 27 | } 28 | } 29 | } 30 | 31 | vector v; 32 | 33 | vector generateParenthesis(int n) { 34 | string s; 35 | generate(s, n, n); 36 | return v; 37 | } 38 | 39 | }; 40 | -------------------------------------------------------------------------------- /codes/cpp/Implementing-Dijkstra-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | Question Implementing Dijkstra Algorithm 2 | Given a weighted, undirected and connected graph of V vertices and an adjacency list adj where adj[i] is a list of lists containing two integers where the first integer of each list j denotes there is edge between i and j , second integers corresponds to the weight of that edge . You are given the source vertex S and You to Find the shortest distance of all the vertex's from the source vertex S. You have to return a list of integers denoting shortest distance between each node and Source vertex S. 3 | 4 | Note: The Graph doesn't contain any negative weight cycle. 5 | Question Link - https://practice.geeksforgeeks.org/problems/implementing-dijkstra-set-1-adjacency-matrix/1 6 | Youtube Link - https://youtu.be/SQ-pXKsBBz8 7 | 8 | //{ Driver Code Starts 9 | 10 | #include 11 | 12 | using namespace std; 13 | 14 | // } Driver Code Ends 15 | 16 | class Solution 17 | 18 | { 19 | 20 | public: 21 | 22 | //Function to find the shortest distance of all the vertices 23 | 24 | //from the source vertex S. 25 | 26 | vector dijkstra(int V, vector> adj[], int S) 27 | 28 | { 29 | 30 | // Code here 31 | 32 | priority_queue, vector>, greater>> pq; 33 | 34 | 35 | 36 | vector dist(V); 37 | 38 | for (int i=0; i> t; 97 | 98 | while (t--) { 99 | 100 | int V, E; 101 | 102 | cin >> V >> E; 103 | 104 | vector> adj[V]; 105 | 106 | int i=0; 107 | 108 | while (i++> u >> v >> w; 113 | 114 | vector t1,t2; 115 | 116 | t1.push_back(v); 117 | 118 | t1.push_back(w); 119 | 120 | adj[u].push_back(t1); 121 | 122 | t2.push_back(u); 123 | 124 | t2.push_back(w); 125 | 126 | adj[v].push_back(t2); 127 | 128 | } 129 | 130 | int S; 131 | 132 | cin>>S; 133 | 134 | 135 | 136 | Solution obj; 137 | 138 | vector res = obj.dijkstra(V, adj, S); 139 | 140 | for(int i=0; inext == NULL) 21 | return NULL; 22 | fast = fast->next->next; 23 | slow = slow->next; 24 | if (fast == slow) 25 | return slow; 26 | } 27 | 28 | return NULL; 29 | } 30 | ListNode* detectCycle(ListNode *head) 31 | { 32 | 33 | ListNode *intersection = FloydCycle(head); 34 | 35 | if (intersection == NULL) 36 | return NULL; 37 | ListNode *slow = head; 38 | while (slow != intersection) 39 | { 40 | slow = slow->next; 41 | intersection = intersection->next; 42 | } 43 | return slow; 44 | } 45 | }; -------------------------------------------------------------------------------- /codes/cpp/LongestSubstringWithoutRepeatingCharacters.cpp: -------------------------------------------------------------------------------- 1 | // Given a string s, find the length of the longest substring without repeating characters. 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | int lengthOfLongestSubstring(string s) 10 | { 11 | unordered_set set; 12 | 13 | int i = 0, j = 0, n = s.size(), ans = 0; 14 | 15 | while( i 4 | using namespace std; 5 | 6 | // A binary tree node 7 | struct Node 8 | { 9 | int data; 10 | struct Node* left, *right; 11 | }; 12 | 13 | // Utility function to allocate memory for a new node 14 | struct Node* newNode(int data) 15 | { 16 | struct Node* node = new(struct Node); 17 | node->data = data; 18 | node->left = node->right = NULL; 19 | return (node); 20 | } 21 | 22 | // Utility function to find maximum of two integers 23 | int max(int a, int b) 24 | { return (a >= b)? a: b; } 25 | 26 | // A utility function to find the maximum sum between any 27 | // two leaves.This function calculates two values: 28 | // 1) Maximum path sum between two leaves which is stored 29 | // in res. 30 | // 2) The maximum root to leaf path sum which is returned. 31 | // If one side of root is empty, then it returns INT_MIN 32 | int maxPathSumUtil(struct Node *root, int &res) 33 | { 34 | // Base cases 35 | if (root==NULL) return 0; 36 | if (!root->left && !root->right) return root->data; 37 | 38 | // Find maximum sum in left and right subtree. Also 39 | // find maximum root to leaf sums in left and right 40 | // subtrees and store them in ls and rs 41 | int ls = maxPathSumUtil(root->left, res); 42 | int rs = maxPathSumUtil(root->right, res); 43 | 44 | 45 | // If both left and right children exist 46 | if (root->left && root->right) 47 | { 48 | // Update result if needed 49 | res = max(res, ls + rs + root->data); 50 | 51 | // Return maximum possible value for root being 52 | // on one side 53 | return max(ls, rs) + root->data; 54 | } 55 | 56 | // If any of the two children is empty, return 57 | // root sum for root being on one side 58 | return (!root->left)? rs + root->data: 59 | ls + root->data; 60 | } 61 | 62 | // The main function which returns sum of the maximum 63 | // sum path between two leaves. This function mainly 64 | // uses maxPathSumUtil() 65 | int maxPathSum(struct Node *root) 66 | { 67 | int res = INT_MIN; 68 | 69 | int val = maxPathSumUtil(root, res); 70 | 71 | //--- for test case --- 72 | // 7 73 | // / \ 74 | // Null -3 75 | // (case - 1) 76 | // value of res will be INT_MIN but the answer is 4 , which is returned by the 77 | // function maxPathSumUtil(). 78 | 79 | if(root->left && root->right) 80 | return res; 81 | return max(res, val); 82 | } 83 | 84 | // Driver Code 85 | int main() 86 | { 87 | struct Node *root = newNode(-15); 88 | root->left = newNode(5); 89 | root->right = newNode(6); 90 | root->left->left = newNode(-8); 91 | root->left->right = newNode(1); 92 | root->left->left->left = newNode(2); 93 | root->left->left->right = newNode(6); 94 | root->right->left = newNode(3); 95 | root->right->right = newNode(9); 96 | root->right->right->right= newNode(0); 97 | root->right->right->right->left= newNode(4); 98 | root->right->right->right->right= newNode(-1); 99 | root->right->right->right->right->left= newNode(10); 100 | cout << "Max pathSum of the given binary tree is " 101 | << maxPathSum(root); 102 | return 0; 103 | } 104 | -------------------------------------------------------------------------------- /codes/cpp/OddEvenList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | *Definition for singly-linked list. 3 | *struct ListNode { 4 | * int val; 5 | * ListNode * next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | *}; 10 | */ 11 | class Solution 12 | { 13 | public: 14 | ListNode* oddEvenList(ListNode *head) 15 | { 16 | if (head == NULL || head->next == NULL || head->next->next == NULL) return head; 17 | ListNode *odd = NULL; 18 | ListNode *o = NULL; 19 | ListNode *even = NULL; 20 | ListNode *e = NULL; 21 | 22 | int i = 1; 23 | while (head) 24 | { 25 | if (i % 2 == 0) 26 | { 27 | if (even == NULL) 28 | { 29 | even = head; 30 | e = head; 31 | } 32 | else 33 | { 34 | e->next = head; 35 | e = e->next; 36 | } 37 | } 38 | else 39 | { 40 | if (odd == NULL) 41 | { 42 | odd = head; 43 | o = head; 44 | } 45 | else 46 | { 47 | o->next = head; 48 | o = o->next; 49 | } 50 | } 51 | head = head->next; 52 | i++; 53 | } 54 | if (odd) 55 | o->next = even; 56 | if (even) 57 | e->next = NULL; 58 | if (odd == NULL) return even; 59 | return odd; 60 | } 61 | }; -------------------------------------------------------------------------------- /codes/cpp/RemoveNthNodeFromEndOfList.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * struct ListNode { 4 | * int val; 5 | * ListNode *next; 6 | * ListNode() : val(0), next(nullptr) {} 7 | * ListNode(int x) : val(x), next(nullptr) {} 8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 | * }; 10 | */ 11 | class Solution 12 | { 13 | public: 14 | ListNode* removeNthFromEnd(ListNode *head, int n) 15 | { 16 | ListNode *start = new ListNode(); 17 | start->next = head; 18 | ListNode *slow = start; 19 | ListNode *fast = start; 20 | 21 | for (int i = 1; i <= n; i++) 22 | { 23 | fast = fast->next; 24 | } 25 | 26 | while (fast->next) 27 | { 28 | fast = fast->next; 29 | slow = slow->next; 30 | } 31 | 32 | slow->next = slow->next->next; 33 | return start->next; 34 | } 35 | }; -------------------------------------------------------------------------------- /codes/cpp/ReverseInteger.cpp: -------------------------------------------------------------------------------- 1 | // Given a signed 32-bit integer x, return x with its digits reversed. 2 | // If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. 3 | 4 | #include 5 | using namespace std; 6 | 7 | int reverse(int x) { 8 | int ans = 0; 9 | while(x!=0){ 10 | int digit = x%10; 11 | if(ans>INT_MAX/10 || ans &nums) 5 | { 6 | int s = 0, l = nums.size() - 1; 7 | while (s < l) 8 | { 9 | int mid = s + (l - s) / 2; 10 | if (nums[mid] < nums[0]) 11 | l = mid; 12 | else 13 | s = mid + 1; 14 | } 15 | return l; 16 | } 17 | int binary_search(vector &nums, int s, int l, int target) 18 | { 19 | while (s <= l) 20 | { 21 | int mid = s + (l - s) / 2; 22 | if (nums[mid] == target) 23 | return mid; 24 | else if (nums[mid] < target) 25 | s = mid + 1; 26 | else 27 | l = mid - 1; 28 | } 29 | return -1; 30 | } 31 | int search(vector &nums, int target) 32 | { 33 | int pivot_index = pivot(nums); 34 | int ans = binary_search(nums, 0, pivot_index - 1, target); 35 | if (ans != -1) 36 | return ans; 37 | return binary_search(nums, pivot_index, nums.size() - 1, target); 38 | } 39 | }; -------------------------------------------------------------------------------- /codes/cpp/Serialize and Deserialize BST: -------------------------------------------------------------------------------- 1 | Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. 2 | 3 | Design an algorithm to serialize and deserialize a binary search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. 4 | 5 | The encoded string should be as compact as possible. 6 | 7 | Input: root = [2,1,3] 8 | Output: [2,1,3] 9 | /** 10 | * Definition for a binary tree node. 11 | * struct TreeNode { 12 | * int val; 13 | * TreeNode *left; 14 | * TreeNode *right; 15 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 16 | * }; 17 | */ 18 | class Codec { 19 | public: 20 | 21 | // Encodes a tree to a single string. 22 | string serialize(TreeNode* root) { 23 | if(root == NULL) 24 | { 25 | return(""); 26 | } 27 | string s = ""; 28 | queueq; 29 | q.push(root); 30 | while(q.size()>0) 31 | { 32 | TreeNode* m = q.front(); 33 | q.pop(); 34 | if(m == NULL) 35 | { 36 | s.append("#,"); 37 | } 38 | else 39 | { 40 | s.append(to_string(m->val)+","); 41 | } 42 | if(m!= NULL) 43 | { 44 | q.push(m->left); 45 | q.push(m->right); 46 | } 47 | } 48 | cout<q; 63 | getline(s,str,','); 64 | TreeNode* m = new TreeNode(stoi(str)); 65 | q.push(m); 66 | while(q.size()>0) 67 | { 68 | 69 | TreeNode* n =q.front(); 70 | q.pop(); 71 | getline(s,str,','); 72 | if(str == "#") 73 | { 74 | n->left = NULL; 75 | } 76 | else 77 | { 78 | TreeNode* n1 = new TreeNode(stoi(str)); 79 | n->left = n1; 80 | q.push(n1); 81 | } 82 | getline(s,str,','); 83 | if(str == "#") 84 | { 85 | n->right = NULL; 86 | 87 | } 88 | else 89 | { 90 | TreeNode* n2 = new TreeNode(stoi(str)); 91 | n->right = n2; 92 | q.push(n2); 93 | } 94 | } 95 | return(m); 96 | } 97 | }; 98 | 99 | 100 | // Codec* ser = new Codec(); 101 | // Codec* deser = new Codec(); 102 | // string tree = ser->serialize(root); 103 | // TreeNode* ans = deser->deserialize(tree); 104 | // return ans; 105 | -------------------------------------------------------------------------------- /codes/cpp/Set-Matrix-Zero.cpp: -------------------------------------------------------------------------------- 1 | Question Link:- https://leetcode.com/problems/set-matrix-zeroes/ 2 | Youtube Link:- https://www.youtube.com/watch?v=M65xBewcqcI 3 | class Solution { 4 | public: 5 | void makezero(vector>&matrix, int i, int j){ 6 | for(int z=0;z>& matrix) { 10 | vector> zeroindex; 11 | int n=matrix.size(), m=matrix[0].size(); 12 | for(int i=0;i& nums) { 4 | int low = 0, mid = 0, high = nums.size() - 1; 5 | while (mid <= high) { 6 | if (nums[mid] == 0) { 7 | swap(nums[low], nums[mid]); 8 | low++; 9 | mid++; 10 | } 11 | else if (nums[mid] == 1) { 12 | mid++; 13 | } 14 | else { 15 | swap(nums[mid], nums[high]); 16 | high--; 17 | } 18 | } 19 | } 20 | }; -------------------------------------------------------------------------------- /codes/cpp/SpiralMatrix.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector spiralOrder(vector>& matrix) { 4 | vector ans; 5 | int n = matrix.size(); 6 | int m = matrix[0].size(); 7 | int top = 0, left = 0, bottom = n-1, right = m-1; 8 | while (top <= bottom && left <= right) { 9 | for (int i = left; i <= right; i++) { 10 | ans.push_back(matrix[top][i]); 11 | } 12 | top++; 13 | for (int i = top; i <= bottom; i++) { 14 | ans.push_back(matrix[i][right]); 15 | } 16 | right--; 17 | if (top <= bottom) { 18 | for (int i = right; i >= left; i--) { 19 | ans.push_back(matrix[bottom][i]); 20 | } 21 | bottom--; 22 | } 23 | if (left <= right) { 24 | for (int i = bottom; i >= top; i--) { 25 | ans.push_back(matrix[i][left]); 26 | } 27 | left++; 28 | } 29 | } 30 | return ans; 31 | } 32 | }; -------------------------------------------------------------------------------- /codes/cpp/TrappingRainWater.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution { 3 | public: 4 | int trap(vector& height) { 5 | vector lmax(height.size(),0); 6 | vector rmax(height.size(),0); 7 | int i; 8 | lmax[0]=height[0]; 9 | for(i=1;i=0;i--) 15 | { 16 | rmax[i]=max(rmax[i+1],height[i]); 17 | } 18 | int res=0; 19 | for(i=0;i 2 | #include 3 | using namespace std; 4 | 5 | void findProperSubSet(int k,int n,vector>&ans,vector&partAns,int l){ 6 | if(k==0&&n<0) 7 | return; 8 | if(k==0&&n==0){ 9 | ans.push_back(partAns); 10 | return; 11 | } 12 | if(k==0&&n>0) 13 | return; 14 | for(int i=l;i<=9;i++){ 15 | partAns.push_back(i); 16 | findProperSubSet(k-1,n-i,ans,partAns,i+1); 17 | partAns.pop_back(); 18 | } 19 | 20 | } 21 | vector> combinationSum3(int k, int n) { 22 | vector>ans; 23 | vectorpartAns; 24 | findProperSubSet(k,n,ans,partAns,1); 25 | return ans; 26 | } 27 | int main() 28 | { 29 | int k,n; 30 | cin>>k; 31 | cin>>n; 32 | vector>ans=combinationSum3(k,n); 33 | for(int i=0;i 2 | using namespace std; 3 | 4 | vector v; 5 | 6 | void generate(string &s, int open, int close) 7 | { 8 | if(open == 0 && close == 0) 9 | { 10 | v.push_back(s); 11 | return; 12 | } 13 | 14 | if(open > 0) 15 | { 16 | s.push_back('('); 17 | // cout<<"open: "< 0) 24 | { 25 | if(open < close) 26 | { 27 | s.push_back(')'); 28 | // cout<<"close: "<>n; 43 | string s=""; 44 | generate(s, n, n); 45 | for(auto s : v) 46 | { 47 | cout< 2 | using namespace std; 3 | 4 | /* Time Complexity = O(2^N) */ 5 | 6 | vector> v; 7 | 8 | void generate(vector &subset, int i, vector &nums) 9 | { 10 | 11 | if(i == nums.size()) 12 | { 13 | v.push_back(subset); 14 | return; 15 | } 16 | 17 | // ith number consideration 18 | subset.push_back(nums[i]); 19 | generate(subset, i+1, nums); 20 | subset.pop_back(); 21 | 22 | // ith number NO consideration 23 | generate(subset, i+1, nums); 24 | 25 | } 26 | 27 | int main() { 28 | // your code goes here 29 | // make input and output faster 30 | ios_base::sync_with_stdio(false); 31 | cin.tie(NULL); 32 | cout.tie(NULL); 33 | int n; 34 | cin>>n; 35 | vector nums(n), subset; 36 | for(int i=0;i>nums[i]; 39 | } 40 | generate(subset, 0, nums); 41 | for(auto p : v) 42 | { 43 | for(auto q : p) 44 | { 45 | cout< 2 | using namespace std; 3 | 4 | /* Time Complexity = (N * 2^N) */ 5 | 6 | vector> subsets(vector& nums) { 7 | int n = nums.size(); 8 | int subset_ct = (1 << n); 9 | vector> subsets_sets; 10 | for(int mask=0; mask subset; 13 | for(int i=0; i> n; 29 | vector nums(n); 30 | for(int i=0; i> nums[i]; 33 | } 34 | 35 | auto all_subsets = subsets(nums); 36 | 37 | for(auto subset: all_subsets) 38 | { 39 | for(auto ele : subset) 40 | { 41 | cout << ele << " "; 42 | } 43 | cout << endl; 44 | } 45 | 46 | 47 | return 0; 48 | } 49 | 50 | -------------------------------------------------------------------------------- /codes/cpp/longestPalindromicSubsequence.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int LCS(string a,string b,int m,int n) 4 | { 5 | int dp[m+1][n+1]; 6 | for(int i=0;i& v1, vector& v2) { 4 | int n=v1.size(); 5 | int dp[n][2]; 6 | for(int i=0;iprev1 && v1[i]>prev2){ 15 | dp[i][1]=1+dp[i-1][1]; 16 | } 17 | //no swap at current position 18 | if(v1[i]>prev1 && v2[i]>prev2){ 19 | dp[i][0]=dp[i-1][1]; 20 | } 21 | } 22 | 23 | //prev position no swap 24 | prev1=v1[i-1]; 25 | prev2=v2[i-1]; 26 | if(dp[i-1][0]!=INT_MAX){ 27 | //swap at current position 28 | if(v2[i]>prev1 && v1[i]>prev2){ 29 | dp[i][1]=min(dp[i][1],1+dp[i-1][0]); 30 | } 31 | //no swap at current position 32 | if(v1[i]>prev1 && v2[i]>prev2){ 33 | dp[i][0]=min(dp[i][0],dp[i-1][0]); 34 | } 35 | } 36 | } 37 | return min(dp[n-1][0],dp[n-1][1]); 38 | } 39 | }; -------------------------------------------------------------------------------- /codes/cpp/nextPermutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector& nums) { 4 | int n = nums.size(); 5 | int ind = -1; 6 | for(int i = n-2; i>=0; i--) { 7 | if(nums[i] < nums[i+1]) { 8 | ind = i; 9 | break; 10 | } 11 | } 12 | if (ind == -1) { 13 | reverse(nums.begin(), nums.end()); 14 | } else { 15 | for (int i = n-1; i > ind; i--) { 16 | if (nums[i] > nums[ind]) { 17 | swap(nums[i], nums[ind]); 18 | break; 19 | } 20 | } 21 | int left = ind + 1; 22 | int right = n - 1; 23 | while (left < right) { 24 | swap(nums[left], nums[right]); 25 | left++; 26 | right--; 27 | } 28 | } 29 | 30 | } 31 | }; -------------------------------------------------------------------------------- /codes/cpp/next_greater_element3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | int nextGreaterElement(int n) { 7 | vectorvec; 8 | int temp = n; 9 | while(n>0){ 10 | int r = n%10; 11 | vec.push_back(r); 12 | n /= 10; 13 | } 14 | sort(vec.begin(),vec.end()); 15 | do{ 16 | int num=0; 17 | long j=0; 18 | int s = vec.size()-1; 19 | long i = pow(10,s); 20 | while(i>0) 21 | { 22 | num += i*vec[j++]; 23 | i /= 10; 24 | } 25 | if(num>temp) 26 | return num; 27 | 28 | } while(next_permutation(vec.begin(),vec.end())); 29 | return -1; 30 | } 31 | 32 | int main() 33 | { 34 | int n; 35 | cin>>n; 36 | cout< nums,int n,int sum) 4 | { 5 | bool dp[n+1][sum+1]; 6 | for(int i=0;i& nums) { 29 | int n=nums.size(); 30 | int sum=0; 31 | for(int i=0;i0 && j>0) 25 | { 26 | if(a[i-1]==b[j-1]) 27 | { 28 | s=a[i-1]+s; 29 | i--; 30 | j--; 31 | } 32 | else 33 | { 34 | if(dp[i-1][j]>dp[i][j-1]) 35 | { 36 | s=a[i-1]+s; 37 | i--; 38 | } 39 | else 40 | { 41 | s=b[j-1]+s; 42 | j--; 43 | } 44 | } 45 | } 46 | while(i>0) 47 | { 48 | s=a[i-1]+s; 49 | i--; 50 | } 51 | while(j>0) 52 | { 53 | s=b[j-1]+s; 54 | j--; 55 | } 56 | return s; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /codes/cpp/sum_of_subarray_minimums.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Solution { 4 | public: 5 | int sumSubarrayMins(vector& arr) { 6 | int n = arr.size(); 7 | int mod = 1e9 + 7; 8 | stack st; 9 | vector dp(n, 0); 10 | int sum = 0; 11 | for(int i =0 ;i < n ; i ++ ){ 12 | while(!st.empty() && arr[st.top()] > arr[i]){ 13 | st.pop(); 14 | } 15 | if(st.empty()){ 16 | dp[i] = (i+1)*arr[i]; 17 | }else{ 18 | dp[i] = dp[st.top()] + (i - st.top())*arr[i]; 19 | } 20 | sum = (sum + dp[i])%mod; 21 | st.push(i); 22 | } 23 | return sum; 24 | } 25 | }; 26 | int main(){ 27 | vector v = {3,1,2,4}; 28 | Solution ob; 29 | cout << (ob.sumSubarrayMins(v)); 30 | return 0; 31 | } -------------------------------------------------------------------------------- /codes/cpp/targetSum.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int subsetSumCount(vector nums,int sum) 4 | { 5 | int n=nums.size(); 6 | int dp[n+1][sum+1]; 7 | for(int i=0;i& nums, int target) { 30 | int s=0; 31 | for(int i=0;is) 34 | return 0; 35 | int sum = (target+s)/2; 36 | return subsetSumCount(nums,sum); 37 | } 38 | }; 39 | -------------------------------------------------------------------------------- /codes/cpp/trapping_rainwater.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of the approach 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | // Function to return the maximum 8 | // water that can be stored 9 | int trap(vector& height,int n) { 10 | int prefix[n],suffix[n]; 11 | prefix[0]=height[0]; 12 | for(int i=1;i=0;i--) 18 | { 19 | suffix[i]=max(suffix[i+1],height[i]); 20 | } 21 | int sum=0; 22 | for(int i=0;iheight; 32 | int n,ele; 33 | cout<<"Enter the size of array"<>n; 35 | for(int i=0;i>ele; 37 | height.push_back(ele); 38 | } 39 | 40 | cout << trap(height, n); 41 | 42 | return 0; 43 | } -------------------------------------------------------------------------------- /codes/cpp/word_break.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int dp[301]; 8 | int help(int i,string s ,set&wordDict){ 9 | if(i==s.size()) 10 | return 1; 11 | string temp; 12 | if(dp[i]!=-1) 13 | return dp[i]; 14 | for(int j=i;j& wordDict) { 28 | setst; 29 | memset(dp,-1,sizeof dp); 30 | for(int i=0;i>s; 40 | vectorworddict; 41 | int n; 42 | cin>>n;string word; 43 | for(int i=0;i>word; 45 | worddict.push_back(word); 46 | } 47 | cout< target){ 14 | b--; 15 | } 16 | else if(curr < target){ 17 | a++; 18 | } 19 | else{ 20 | return curr; 21 | } 22 | if(Math.abs(ans-target) > Math.abs(curr-target)){ 23 | ans = curr; 24 | } 25 | } 26 | } 27 | 28 | return ans; 29 | } 30 | } -------------------------------------------------------------------------------- /codes/java/FirstUniqueCharacterinaString.java: -------------------------------------------------------------------------------- 1 | // Name: Mohammad Mubaslat 2 | // Date: 19/10/2022 3 | 4 | // Given a string s, find the first non-repeating character in it and return its 5 | // index. If it does not exist, return -1. 6 | 7 | // Example 1: 8 | 9 | // Input: s = "leetcode" 10 | // Output: 0 11 | // Example 2: 12 | 13 | // Input: s = "loveleetcode" 14 | // Output: 2 15 | // Example 3: 16 | 17 | // Input: s = "aabb" 18 | // Output: -1 19 | 20 | // Constraints: 21 | 22 | // 1 <= s.length <= 105 23 | // s consists of only lowercase English letters. 24 | 25 | class Solution { 26 | public int firstUniqChar(String s) { 27 | Map myMap = new HashMap<>(); 28 | 29 | for (int i = 0; i < s.length(); i++) { 30 | if (myMap.containsKey(s.charAt(i))) 31 | myMap.put(s.charAt(i), myMap.get(s.charAt(i)) + 1); 32 | else 33 | myMap.put(s.charAt(i), 1); 34 | } 35 | 36 | for (int i = 0; i < s.length(); i++) 37 | if (myMap.get(s.charAt(i)) == 1) 38 | return i; 39 | 40 | return -1; 41 | 42 | } 43 | } -------------------------------------------------------------------------------- /codes/java/GenerateParentheses.java: -------------------------------------------------------------------------------- 1 | class Generate{ 2 | 3 | // function which generates all possible n pairs of 4 | // balanced parentheses. 5 | // open : count of the number of open parentheses used 6 | // in generating the current string s. close : count of 7 | // the number of closed parentheses used in generating 8 | // the current string s. s : currently generated string/ 9 | // ans : a vector of strings to store all the valid 10 | // parentheses. 11 | public static void 12 | generateParenthesis(int n, int open, int close, 13 | String s, ArrayList ans) 14 | { 15 | 16 | // if the count of both open and close parentheses 17 | // reaches n, it means we have generated a valid 18 | // parentheses. So, we add the currently generated 19 | // string s to the final ans and return. 20 | if (open == n && close == n) { 21 | ans.add(s); 22 | return; 23 | } 24 | 25 | // At any index i in the generation of the string s, 26 | // we can put an open parentheses only if its count 27 | // until that time is less than n. 28 | if (open < n) { 29 | generateParenthesis(n, open + 1, close, s + "{", 30 | ans); 31 | } 32 | 33 | // At any index i in the generation of the string s, 34 | // we can put a closed parentheses only if its count 35 | // until that time is less than the count of open 36 | // parentheses. 37 | if (close < open) { 38 | generateParenthesis(n, open, close + 1, s + "}", 39 | ans); 40 | } 41 | } 42 | 43 | public static void main(String[] args) 44 | { 45 | int n = 3; 46 | 47 | // vector ans is created to store all the possible 48 | // valid combinations of the parentheses. 49 | ArrayList ans = new ArrayList<>(); 50 | 51 | // initially we are passing the counts of open and 52 | // close as 0, and the string s as an empty string. 53 | generateParenthesis(n, 0, 0, "", ans); 54 | 55 | // Now, here we print out all the combinations. 56 | for (String s : ans) { 57 | System.out.println(s); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /codes/java/GroupAnagramsProg.java: -------------------------------------------------------------------------------- 1 | // GROUP ANAGRAMS (LEETCODE 49) SOLUTION 2 | // Question : https://leetcode.com/problems/group-anagrams/ 3 | 4 | //-------------------------------------------------------------------------- 5 | 6 | class Solution { 7 | public List> groupAnagrams(String[] strs) { 8 | if (strs.length == 0) 9 | return new ArrayList(); 10 | Map ans = new HashMap(); 11 | 12 | int[] count = new int[26]; 13 | for (String s : strs) { 14 | Arrays.fill(count, 0); 15 | for (char c : s.toCharArray()) 16 | count[c - 'a']++; 17 | 18 | StringBuilder sb = new StringBuilder(""); 19 | for (int i = 0; i < 26; i++) { 20 | sb.append('#'); 21 | sb.append(count[i]); 22 | } 23 | String key = sb.toString(); 24 | if (!ans.containsKey(key)) 25 | ans.put(key, new ArrayList()); 26 | 27 | ans.get(key).add(s); 28 | } 29 | return new ArrayList(ans.values()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /codes/java/HouseRobberII.java: -------------------------------------------------------------------------------- 1 | /* 2 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. 3 | 4 | Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. 5 | 6 | Input: nums = [2,3,2] 7 | Output: 3 8 | Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. 9 | */ 10 | 11 | public class HouseRobberII { 12 | public int rob(int[] nums) { 13 | if (nums.length == 0) 14 | return 0; 15 | if (nums.length < 2) 16 | return nums[0]; 17 | 18 | int[] startFromFirstHouse = new int[nums.length + 1]; 19 | int[] startFromSecondHouse = new int[nums.length + 1]; 20 | 21 | startFromFirstHouse[0] = 0; 22 | startFromFirstHouse[1] = nums[0]; 23 | startFromSecondHouse[0] = 0; 24 | startFromSecondHouse[1] = 0; 25 | 26 | for (int i = 2; i <= nums.length; i++) { 27 | startFromFirstHouse[i] = Math.max(startFromFirstHouse[i - 1], startFromFirstHouse[i - 2] + nums[i-1]); 28 | startFromSecondHouse[i] = Math.max(startFromSecondHouse[i - 1], startFromSecondHouse[i - 2] + nums[i-1]); 29 | } 30 | 31 | return Math.max(startFromFirstHouse[nums.length - 1], startFromSecondHouse[nums.length]); 32 | } 33 | } -------------------------------------------------------------------------------- /codes/java/KthBitNthBinaryString.java: -------------------------------------------------------------------------------- 1 | class KthBitNthBinaryString { 2 | public char findKthBit(int n, int k) { 3 | 4 | if(n==1){ // not n == 0 5 | return '0'; 6 | } 7 | 8 | int len = (1< len/2 + 1){ // if k is more, move to the 2nd half of the string 14 | 15 | if(findKthBit(n-1, len - k +1) == '0'){ // checking the original and then returning the inverted bit 16 | return '1'; 17 | } 18 | else{ 19 | return '0'; 20 | } 21 | } 22 | else if(k < len/2 + 1){ // if k is in the first half, no need to invert, just return the same bit 23 | return findKthBit(n-1, k); 24 | } 25 | 26 | return '1'; // dummy return for syntax 27 | } 28 | } -------------------------------------------------------------------------------- /codes/java/LongestCommonSubstring.java: -------------------------------------------------------------------------------- 1 | //import Java.util.*; 2 | import java.io.*; 3 | import java.util.Scanner; 4 | 5 | // create LCSExample1 class to find the Longest Common Subsequence 6 | class LCSExample1 { 7 | 8 | // create findLengthOfLCS() method that returns the longest common sequences 9 | public static String findLengthOfLCS(String str1, String str2, int p, int q) { 10 | 11 | // create a matrix which act as a table for LCS 12 | int[][] tableForLCS = new int[p + 1][q + 1]; 13 | 14 | // fill the table in the bottom up way 15 | for (int i = 0; i <= p; i++) { 16 | for (int j = 0; j <= q; j++) { 17 | if (i == 0 || j == 0) 18 | tableForLCS[i][j] = 0; // Fill each cell corresponding to first row and first column with 0 19 | else if (str1.charAt(i - 1) == str2.charAt(j - 1)) 20 | tableForLCS[i][j] = tableForLCS[i - 1][j - 1] + 1; // add 1 in the cell of the previous row and column and fill the current cell with it 21 | else 22 | tableForLCS[i][j] = Math.max(tableForLCS[i - 1][j], tableForLCS[i][j - 1]); //find the maximum value from the cell of the previous row and current column and the cell of the current row and previous column 23 | } 24 | } 25 | 26 | int index = tableForLCS[p][q]; 27 | int temp = index; 28 | 29 | char[] longestCommonSubsequence = new char[index + 1]; 30 | longestCommonSubsequence[index] = '\0'; 31 | 32 | int i = p, j = q; 33 | String lcs =""; 34 | while (i > 0 && j > 0) { 35 | if (str1.charAt(i - 1) == str2.charAt(j - 1)) { 36 | 37 | longestCommonSubsequence[index - 1] = str1.charAt(i - 1); 38 | i--; 39 | j--; 40 | index--; 41 | } 42 | else if (tableForLCS[i - 1][j] > tableForLCS[i][j - 1]) 43 | i--; 44 | else 45 | j--; 46 | } 47 | 48 | for (int k = 0; k <= temp; k++) 49 | lcs = lcs + longestCommonSubsequence[k]; 50 | 51 | return lcs; 52 | } 53 | public static void main(String[] args) { 54 | 55 | String str1, str2, LCS; 56 | 57 | Scanner sc= new Scanner(System.in); //System.in is a standard input stream. 58 | System.out.print("Enter first sequence: "); 59 | str1 = sc.nextLine(); //reads string. 60 | 61 | System.out.print("Enter second sequence: "); 62 | str2 = sc.nextLine(); //reads string. 63 | 64 | int p = str1.length(); 65 | int q = str2.length(); 66 | 67 | LCS = findLengthOfLCS(str1, str2, p, q); 68 | 69 | System.out.print("Sequence1: " + str1 + "\nSequence2: " + str2); 70 | System.out.println("\nLCS: "+LCS); 71 | 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /codes/java/LongestValidParentheses.java: -------------------------------------------------------------------------------- 1 | public class Solution { 2 | public boolean isValid(String s) { 3 | Stack stack = new Stack(); 4 | for (int i = 0; i < s.length(); i++) { 5 | if (s.charAt(i) == '(') { 6 | stack.push('('); 7 | } else if (!stack.empty() && stack.peek() == '(') { 8 | stack.pop(); 9 | } else { 10 | return false; 11 | } 12 | } 13 | return stack.empty(); 14 | } 15 | public int longestValidParentheses(String s) { 16 | int maxlen = 0; 17 | for (int i = 0; i < s.length(); i++) { 18 | for (int j = i + 2; j <= s.length(); j+=2) { 19 | if (isValid(s.substring(i, j))) { 20 | maxlen = Math.max(maxlen, j - i); 21 | } 22 | } 23 | } 24 | return maxlen; 25 | } 26 | } -------------------------------------------------------------------------------- /codes/java/RegularExpressionMatching.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public boolean isMatch(String text, String pattern) { 3 | boolean[][] dp = new boolean[text.length() + 1][pattern.length() + 1]; 4 | dp[text.length()][pattern.length()] = true; 5 | 6 | for (int i = text.length(); i >= 0; i--){ 7 | for (int j = pattern.length() - 1; j >= 0; j--){ 8 | boolean first_match = (i < text.length() && 9 | (pattern.charAt(j) == text.charAt(i) || 10 | pattern.charAt(j) == '.')); 11 | if (j + 1 < pattern.length() && pattern.charAt(j+1) == '*'){ 12 | dp[i][j] = dp[i][j+2] || first_match && dp[i+1][j]; 13 | } else { 14 | dp[i][j] = first_match && dp[i+1][j+1]; 15 | } 16 | } 17 | } 18 | return dp[0][0]; 19 | } 20 | } -------------------------------------------------------------------------------- /codes/java/RotateImage.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void rotate(int[][] matrix) { 3 | int n = matrix.length; 4 | for (int i = 0; i < (n + 1) / 2; i ++) { 5 | for (int j = 0; j < n / 2; j++) { 6 | int temp = matrix[n - 1 - j][i]; 7 | matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1]; 8 | matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 -i]; 9 | matrix[j][n - 1 - i] = matrix[i][j]; 10 | matrix[i][j] = temp; 11 | } 12 | } 13 | } 14 | } -------------------------------------------------------------------------------- /codes/java/Stringtointeger.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | public class Stringtointeger { 3 | // Function to convert String to integer 4 | public static int convert(String str) 5 | { 6 | int val = 0; 7 | System.out.println("String = " + str); 8 | 9 | // Convert the String 10 | try { 11 | val = Integer.parseInt(str); 12 | } 13 | catch (NumberFormatException e) { 14 | 15 | // This is thrown when the String 16 | // contains characters other than digits 17 | System.out.println("Invalid String"); 18 | } 19 | return val; 20 | } 21 | 22 | // Driver code 23 | public static void main(String[] args) 24 | { 25 | 26 | String str = "1234"; 27 | int val = convert(str); 28 | System.out.println("Integer value = " + val); 29 | System.out.println(); 30 | 31 | str = "123s"; 32 | val = convert(str); 33 | System.out.println("Integer value = " + val); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /codes/java/SubstringWithConcatenationOfAllWords.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | private HashMap wordCount = new HashMap(); 3 | private int wordLength; 4 | private int substringSize; 5 | private int k; 6 | 7 | private boolean check(int i, String s) { 8 | // Copy the original dictionary to use for this index 9 | HashMap remaining = new HashMap<>(wordCount); 10 | int wordsUsed = 0; 11 | 12 | // Each iteration will check for a match in words 13 | for (int j = i; j < i + substringSize; j += wordLength) { 14 | String sub = s.substring(j, j + wordLength); 15 | if (remaining.getOrDefault(sub, 0) != 0) { 16 | remaining.put(sub, remaining.get(sub) - 1); 17 | wordsUsed++; 18 | } else { 19 | break; 20 | } 21 | } 22 | 23 | return wordsUsed == k; 24 | } 25 | 26 | public List findSubstring(String s, String[] words) { 27 | int n = s.length(); 28 | k = words.length; 29 | wordLength = words[0].length(); 30 | substringSize = wordLength * k; 31 | 32 | for (String word : words) { 33 | wordCount.put(word, wordCount.getOrDefault(word, 0) + 1); 34 | } 35 | 36 | List answer = new ArrayList<>(); 37 | for (int i = 0; i < n - substringSize + 1; i++) { 38 | if (check(i, s)) { 39 | answer.add(i); 40 | } 41 | } 42 | 43 | return answer; 44 | } 45 | } -------------------------------------------------------------------------------- /codes/java/containerwithmostwater.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxArea(int[] height) { 3 | 4 | int area=0; 5 | int start=0; 6 | int end=height.length-1; 7 | int res=Math.min(height[start],height[end])*(end-start); 8 | while(startres) 17 | res=area; 18 | 19 | 20 | } 21 | return res; 22 | } 23 | } -------------------------------------------------------------------------------- /codes/java/integertoroman.java: -------------------------------------------------------------------------------- 1 | public class IntegerToRoman 2 | { 3 | public static void intToRoman(int num) 4 | { 5 | System.out.println("Integer: " + num); 6 | int[] values = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; 7 | String[] romanLetters = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 8 | StringBuilder roman = new StringBuilder(); 9 | for(int i=0;i= values[i]) 12 | { 13 | num = num - values[i]; 14 | roman.append(romanLetters[i]); 15 | } 16 | } 17 | System.out.println("Corresponding Roman Numerals is: " + roman.toString()); 18 | } 19 | public static void main(String args[]) 20 | { 21 | intToRoman(125); 22 | intToRoman(252); 23 | intToRoman(1000); 24 | intToRoman(1010); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /codes/java/kadanesalgo.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int maxSubArray(int[] arr) { 3 | int s=0;// intialzing sum with zero 4 | int max=Integer.MIN_VALUE;// intialzing max variable with minimum value 5 | for(int i=0;imax) // finding maximum sum 9 | max=s; //update max variable 10 | if(s<0) //if sum is -ve,means this subarray is useless 11 | s=0; //restart calculating sum 12 | } 13 | return max; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /codes/java/maximum-length-of-a-concatenated-string-with-unique-characters.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | int finalans = 0; 3 | public int maxLength(List arr) { 4 | // try brute force 5 | // get every match and calculate max 6 | // also check that the string that we are choosing, itself has unqiue chars or not 7 | combis(0, arr, new HashSet()); 8 | return finalans; 9 | } 10 | private void combis(int ind, List arr, HashSet curr){ 11 | if(ind == arr.size()){ 12 | finalans = Math.max(curr.size(), finalans); // stores the max answer 13 | return; 14 | } 15 | 16 | char[] currindarr = arr.get(ind).toCharArray(); // converting the current string to a char array 17 | 18 | boolean hasele = false; 19 | 20 | for(char c: currindarr){ // checks if the any character in the current string is int the hashset 21 | if(curr.contains(c)){ 22 | hasele = true; 23 | break; 24 | } 25 | } 26 | 27 | boolean reps = false; // to check for repitition in the string itself 28 | 29 | if(!hasele){ // if there is a element in the current hashmap, then i will not take it. 30 | for(char c: currindarr){ // adds the chars to the hashmap 31 | if(curr.contains(c)){ // checks if there is repition in the string itself 32 | reps = true; 33 | } 34 | curr.add(c); 35 | } 36 | 37 | if(!reps) combis(ind+1, arr, curr); // taking the string if there is no repitiion 38 | 39 | for(char c: currindarr){//removes the taken chars from the hashmap 40 | curr.remove(c); 41 | } 42 | } 43 | combis(ind+1, arr, curr); // not taking the current index and moving on 44 | } 45 | } -------------------------------------------------------------------------------- /codes/java/minimumswapstomakesequencesincreasing.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int minSwap(int[] nums1, int[] nums2) { 3 | int n = nums1.length; 4 | 5 | // initialize dp table 6 | int[][] memo = new int[2][n]; 7 | Arrays.fill(memo[0], -1); 8 | Arrays.fill(memo[1], -1); 9 | memo[0][0] = 0; 10 | memo[1][0] = 1; 11 | 12 | return Math.min(recurse(nums1, nums2, n - 1, 0, memo), 13 | recurse(nums1, nums2, n - 1, 1, memo)); 14 | } 15 | 16 | private int recurse(int[] nums1, int[] nums2, int i, int swap, int[][] memo) { 17 | //check dp table 18 | if (memo[swap][i] != -1) 19 | return memo[swap][i]; 20 | 21 | // initial value is set as max 22 | int res = Integer.MAX_VALUE; 23 | 24 | // if array is increasing without swapping 25 | if (nums1[i] > nums1[i - 1] && nums2[i] > nums2[i - 1]) 26 | res = recurse(nums1, nums2, i - 1, swap, memo); 27 | 28 | // if array is increasing with swapping 29 | if (nums1[i] > nums2[i - 1] && nums2[i] > nums1[i - 1]) 30 | res = Math.min(res, 31 | recurse(nums1, nums2, i - 1, 1 - swap, memo)); 32 | 33 | memo[swap][i] = swap == 0 ? res : res + 1; 34 | return memo[swap][i]; 35 | } 36 | } -------------------------------------------------------------------------------- /codes/java/setmatrixzeros.java: -------------------------------------------------------------------------------- 1 | public class setmatrixzeros { 2 | public static void setZeroes(int[][] matrix) { 3 | int[][] copy = new int[matrix.length][matrix[0].length]; 4 | int i, j; 5 | for (i = 0; i < copy.length; i++) { 6 | for (j = 0; j < copy[0].length; j++) { 7 | copy[i][j] = matrix[i][j]; 8 | } 9 | } 10 | for (i = 0; i < matrix.length; i++) { 11 | for (j = 0; j < matrix[i].length; j++) { 12 | if(copy[i][j]==0){ 13 | zerofi(matrix, i, j); 14 | } 15 | } 16 | } 17 | } 18 | public static void zerofi(int[][] arr, int row, int col){ 19 | int i; 20 | for (i = 0; i < arr.length; i++) { 21 | arr[i][col] = 0; 22 | } 23 | for (i = 0; i < arr[0].length; i++) { 24 | arr[row][i] = 0; 25 | } 26 | 27 | } 28 | public static void main(String[] args) { 29 | int[][] arr = {{0,1,2,0},{3,4,5,2},{1,3,1,5}}; 30 | // int[][] arr = {{1, 2, 3, 4}, {5, 0, 7, 8}, {9, 10, 11, 12}}; 31 | setZeroes(arr); 32 | for(int i =0; i> map; 4 | 5 | /** Initialize your data structure here. */ 6 | public TimeMap() { 7 | map = new HashMap<>(); 8 | } 9 | 10 | public void set(String key, String value, int timestamp) { 11 | if(!map.containsKey(key)) { 12 | map.put(key,new TreeMap<>()); 13 | } 14 | map.get(key).put(timestamp,value); 15 | } 16 | 17 | public String get(String key, int timestamp) { 18 | TreeMap treeMap = map.get(key); 19 | if(treeMap==null) { 20 | return ""; 21 | } 22 | Integer floor = treeMap.floorKey(timestamp); 23 | if(floor==null) { 24 | return ""; 25 | } 26 | return treeMap.get(floor); 27 | } 28 | } -------------------------------------------------------------------------------- /codes/java/zigzagconversion.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public String convert(String s, int numRows) { 3 | //Define StringBuilders 4 | StringBuilder[] sbs = new StringBuilder[numRows]; 5 | for(int i = 0; i < numRows; i++){ 6 | sbs[i] = new StringBuilder(); 7 | } 8 | 9 | //Define Variables 10 | char[] arr = s.toCharArray(); 11 | int n = arr.length; 12 | int index = 0; 13 | 14 | //Traverse zig zag 15 | while(index < n){ 16 | //Go down 17 | for(int j = 0; j < numRows && index < n; j++){ 18 | sbs[j].append(arr[index++]); 19 | } 20 | //Go Up before start 21 | for(int j = numRows - 2; j > 0 && index < n; j--){ 22 | sbs[j].append(arr[index++]); 23 | } 24 | } 25 | 26 | //Combine all stringbuilders into one 27 | StringBuilder res = sbs[0]; 28 | for(int i = 1; i < numRows; i++){ 29 | res.append(sbs[i].toString()); 30 | } 31 | return res.toString(); 32 | } 33 | } -------------------------------------------------------------------------------- /codes/python/Alien_Dic.py: -------------------------------------------------------------------------------- 1 | # Time: O(n) 2 | # Space: O(|V|+|E|) = O(26 + 26^2) = O(1) 3 | 4 | import collections 5 | 6 | 7 | # BFS solution. 8 | class Solution(object): 9 | def alienOrder(self, words): 10 | """ 11 | :type words: List[str] 12 | :rtype: str 13 | """ 14 | result, in_degree, out_degree = [], {}, {} 15 | zero_in_degree_queue = collections.deque() 16 | nodes = set() 17 | for word in words: 18 | for c in word: 19 | nodes.add(c) 20 | 21 | for i in xrange(1, len(words)): 22 | if (len(words[i-1]) > len(words[i]) and 23 | words[i-1][:len(words[i])] == words[i]): 24 | return "" 25 | self.findEdges(words[i - 1], words[i], in_degree, out_degree) 26 | 27 | for node in nodes: 28 | if node not in in_degree: 29 | zero_in_degree_queue.append(node) 30 | 31 | while zero_in_degree_queue: 32 | precedence = zero_in_degree_queue.popleft() 33 | result.append(precedence) 34 | 35 | if precedence in out_degree: 36 | for c in out_degree[precedence]: 37 | in_degree[c].discard(precedence) 38 | if not in_degree[c]: 39 | zero_in_degree_queue.append(c) 40 | 41 | del out_degree[precedence] 42 | 43 | if out_degree: 44 | return "" 45 | 46 | return "".join(result) 47 | 48 | # Construct the graph. 49 | def findEdges(self, word1, word2, in_degree, out_degree): 50 | str_len = min(len(word1), len(word2)) 51 | for i in xrange(str_len): 52 | if word1[i] != word2[i]: 53 | if word2[i] not in in_degree: 54 | in_degree[word2[i]] = set() 55 | if word1[i] not in out_degree: 56 | out_degree[word1[i]] = set() 57 | in_degree[word2[i]].add(word1[i]) 58 | out_degree[word1[i]].add(word2[i]) 59 | break 60 | 61 | 62 | # DFS solution. 63 | class Solution2(object): 64 | def alienOrder(self, words): 65 | """ 66 | :type words: List[str] 67 | :rtype: str 68 | """ 69 | # Find ancestors of each node by DFS. 70 | nodes, ancestors = set(), {} 71 | for i in xrange(len(words)): 72 | for c in words[i]: 73 | nodes.add(c) 74 | for node in nodes: 75 | ancestors[node] = [] 76 | for i in xrange(1, len(words)): 77 | if (len(words[i-1]) > len(words[i]) and 78 | words[i-1][:len(words[i])] == words[i]): 79 | return "" 80 | self.findEdges(words[i - 1], words[i], ancestors) 81 | 82 | # Output topological order by DFS. 83 | result = [] 84 | visited = {} 85 | for node in nodes: 86 | if self.topSortDFS(node, node, ancestors, visited, result): 87 | return "" 88 | 89 | return "".join(result) 90 | 91 | # Construct the graph. 92 | def findEdges(self, word1, word2, ancestors): 93 | min_len = min(len(word1), len(word2)) 94 | for i in xrange(min_len): 95 | if word1[i] != word2[i]: 96 | ancestors[word2[i]].append(word1[i]) 97 | break 98 | 99 | # Topological sort, return whether there is a cycle. 100 | def topSortDFS(self, root, node, ancestors, visited, result): 101 | if node not in visited: 102 | visited[node] = root 103 | for ancestor in ancestors[node]: 104 | if self.topSortDFS(root, ancestor, ancestors, visited, result): 105 | return True 106 | result.append(node) 107 | elif visited[node] == root: 108 | # Visited from the same root in the DFS path. 109 | # So it is cyclic. 110 | return True 111 | return False 112 | -------------------------------------------------------------------------------- /codes/python/DijkstraAlgo.py: -------------------------------------------------------------------------------- 1 | def dijkstra(current, nodes, distances): 2 | # These are all the nodes which have not been visited yet 3 | unvisited = {node: None for node in nodes} 4 | # It will store the shortest distance from one node to another 5 | visited = {} 6 | # It will store the predecessors of the nodes 7 | currentDistance = 0 8 | unvisited[current] = currentDistance 9 | # Running the loop while all the nodes have been visited 10 | while True: 11 | # iterating through all the unvisited node 12 | for neighbour, distance in distances[current].items(): 13 | # Iterating through the connected nodes of current_node (for 14 | # example, a is connected with b and c having values 10 and 3 15 | # respectively) and the weight of the edges 16 | if neighbour not in unvisited: continue 17 | newDistance = currentDistance + distance 18 | if unvisited[neighbour] is None or unvisited[neighbour] > newDistance: 19 | unvisited[neighbour] = newDistance 20 | # Till now the shortest distance between the source node and target node 21 | # has been found. Set the current node as the target node 22 | visited[current] = currentDistance 23 | del unvisited[current] 24 | if not unvisited: break 25 | candidates = [node for node in unvisited.items() if node[1]] 26 | print(sorted(candidates, key = lambda x: x[1])) 27 | current, currentDistance = sorted(candidates, key = lambda x: x[1])[0] 28 | return visited 29 | 30 | nodes = ('A', 'B', 'C', 'D', 'E') 31 | distances = { 32 | 'A': {'B': 5, 'C': 2}, 33 | 'B': {'C': 2, 'D': 3}, 34 | 'C': {'B': 3, 'D': 7}, 35 | 'D': {'E': 7}, 36 | 'E': {'D': 9}} 37 | current = 'A' 38 | 39 | print(dijkstra(current, nodes, distances)) 40 | -------------------------------------------------------------------------------- /codes/python/InterleavingStringsProg.py: -------------------------------------------------------------------------------- 1 | # INTERLEAVING STRINGS( LEETCODE 97) SOLUTION 2 | # Question : https://leetcode.com/problems/interleaving-string/ 3 | 4 | #-------------------------------------------------------------------------- 5 | 6 | class Solution: 7 | def isInterleave(self, s1: str, s2: str, s3: str) -> bool: 8 | m, n = len(s1), len(s2) 9 | if m + n != len(s3): 10 | return False 11 | dp = [[False] * (n + 1) for _ in range(m + 1)] 12 | dp[0][0] = True 13 | for i in range(1, m + 1): 14 | dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1] 15 | for j in range(1, n + 1): 16 | dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1] 17 | for i in range(1, m + 1): 18 | for j in range(1, n + 1): 19 | choose_s1, choose_s2 = False, False 20 | if s1[i - 1] == s3[i + j - 1]: 21 | choose_s1 = dp[i - 1][j] 22 | if s2[j - 1] == s3[i + j - 1]: 23 | choose_s2 = dp[i][j - 1] 24 | dp[i][j] = choose_s1 or choose_s2 25 | 26 | return dp[m][n] 27 | -------------------------------------------------------------------------------- /codes/python/KadaneAlgo.py: -------------------------------------------------------------------------------- 1 | import math 2 | class Solution: 3 | def maxSubArraySum(self,arr,N): 4 | ##Your code here 5 | max_ending=0 6 | max_so_far=-math.inf 7 | for i in range(N): 8 | max_ending+=arr[i] 9 | if max_so_far0): 22 | 23 | n=int(input()) 24 | 25 | arr=[int(x) for x in input().strip().split()] 26 | 27 | ob=Solution() 28 | 29 | print(ob.maxSubArraySum(arr,n)) 30 | 31 | T-=1 32 | 33 | 34 | if __name__ == "__main__": 35 | main() -------------------------------------------------------------------------------- /codes/python/Palind_Part.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def palindromicPartition(self, string): 4 | # code here 5 | a=string 6 | cut = [0 for i in range(len(a))] 7 | palindrome = [[False for i in range(len(a))] for j in range(len(a))] 8 | for i in range(len(a)): 9 | minCut = i 10 | for j in range(i + 1): 11 | if (a[i] == a[j] and (i - j < 2 or palindrome[j + 1][i - 1])): 12 | palindrome[j][i] = True 13 | minCut = min(minCut,0 if j == 0 else (cut[j - 1] + 1)) 14 | cut[i] = minCut; 15 | return cut[len(a) - 1] 16 | 17 | # Payel - AIML TMSL 18 | if __name__ == '__main__': 19 | t = int(input()) 20 | for _ in range (t): 21 | string = input() 22 | 23 | ob = Solution() 24 | print(ob.palindromicPartition(string)) 25 | -------------------------------------------------------------------------------- /codes/python/Sum_of_k_smallest_elements_in_BST.py: -------------------------------------------------------------------------------- 1 | # Python3 program to find Sum Of All 2 | # Elements smaller than or equal to 3 | # Kth Smallest Element In BST 4 | 5 | INT_MAX = 2147483647 6 | 7 | # Binary Tree Node 8 | """ utility that allocates a newNode 9 | with the given key """ 10 | 11 | 12 | class createNode: 13 | 14 | # Construct to create a newNode 15 | def __init__(self, key): 16 | self.data = key 17 | self.left = None 18 | self.right = None 19 | 20 | 21 | # A utility function to insert a new 22 | # Node with given key in BST and also 23 | # maintain lcount ,Sum 24 | def insert(root, key): 25 | # If the tree is empty, return a new Node 26 | if (root == None): 27 | return createNode(key) 28 | 29 | # Otherwise, recur down the tree 30 | if (root.data > key): 31 | root.left = insert(root.left, key) 32 | 33 | elif (root.data < key): 34 | root.right = insert(root.right, key) 35 | 36 | # return the (unchanged) Node pointer 37 | return root 38 | 39 | 40 | # function return sum of all element smaller 41 | # than and equal to Kth smallest element 42 | def ksmallestElementSumRec(root, k, count): 43 | # Base cases 44 | if (root == None): 45 | return 0 46 | if (count[0] > k[0]): 47 | return 0 48 | 49 | # Compute sum of elements in left subtree 50 | res = ksmallestElementSumRec(root.left, k, count) 51 | if (count[0] >= k[0]): 52 | return res 53 | 54 | # Add root's data 55 | res += root.data 56 | 57 | # Add current Node 58 | count[0] += 1 59 | if (count[0] >= k[0]): 60 | return res 61 | 62 | # If count is less than k, return 63 | # right subtree Nodes 64 | return res + ksmallestElementSumRec(root.right, 65 | k, count) 66 | 67 | 68 | # Wrapper over ksmallestElementSumRec() 69 | def ksmallestElementSum(root, k): 70 | count = [0] 71 | return ksmallestElementSumRec(root, k, count) 72 | 73 | 74 | # Driver Code 75 | if __name__ == '__main__': 76 | """ 20 77 | / \ 78 | 8 22 79 | / \ 80 | 4 12 81 | / \ 82 | 10 14 83 | """ 84 | root = None 85 | root = insert(root, 20) 86 | root = insert(root, 8) 87 | root = insert(root, 4) 88 | root = insert(root, 12) 89 | root = insert(root, 10) 90 | root = insert(root, 14) 91 | root = insert(root, 22) 92 | 93 | k = [3] 94 | print(ksmallestElementSum(root, k)) 95 | 96 | 97 | -------------------------------------------------------------------------------- /codes/python/designLinkedList.py: -------------------------------------------------------------------------------- 1 | class node: 2 | def __init__(self,data): 3 | self.data=data 4 | self.next=None 5 | 6 | class MyLinkedList: 7 | 8 | def __init__(self): 9 | self.head=None 10 | self.len=0 11 | 12 | def get(self, index: int) -> int: 13 | if index<0 or index>self.len: 14 | return -1 15 | count=0 16 | current=self.head 17 | while current!=None: 18 | if count==index: 19 | return current.data 20 | count+=1 21 | current=current.next 22 | return -1 23 | 24 | 25 | def addAtHead(self, val: int) -> None: 26 | nod=node(val) 27 | if self.head==None: 28 | self.head=nod 29 | self.len+=1 30 | else: 31 | nod.next= self.head 32 | self.head=nod 33 | self.len+=1 34 | 35 | def addAtTail(self, val: int) -> None: 36 | put=node(val) 37 | if self.head==None: 38 | self.head=put 39 | self.len+=1 40 | else: 41 | current=self.head 42 | while current.next!=None: 43 | current=current.next 44 | current.next=put 45 | self.len+=1 46 | 47 | def addAtIndex(self, index: int, val: int) -> None: 48 | if index < 0 or index > self.len: 49 | return 50 | if index == 0: 51 | self.addAtHead(val) 52 | else: 53 | new = node(val) 54 | current = self.head 55 | for i in range(index - 1): 56 | current = current.next 57 | new.next = current.next 58 | current.next = new 59 | self.len += 1 60 | 61 | 62 | def deleteAtIndex(self, index: int) -> None: 63 | if index < 0 or index >= self.len: 64 | return 65 | 66 | if index == 0: 67 | self.head = self.head.next 68 | else: 69 | current = self.head 70 | for i in range(index - 1): 71 | current = current.next 72 | current.next = current.next.next 73 | self.len -= 1 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | # Your MyLinkedList object will be instantiated and called as such: 83 | # obj = MyLinkedList() 84 | # param_1 = obj.get(index) 85 | # obj.addAtHead(val) 86 | # obj.addAtTail(val) 87 | # obj.addAtIndex(index,val) 88 | # obj.deleteAtIndex(index) -------------------------------------------------------------------------------- /codes/python/flattenbinarytree.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def flatten(self, root: Optional[TreeNode]) -> None: 9 | """ 10 | Do not return anything, modify root in-place instead. 11 | """ 12 | def preorder(current): 13 | if current==None: 14 | return None 15 | 16 | leftn=preorder(current.left) 17 | rightn=preorder(current.right) 18 | 19 | if current.left!=None: 20 | temp=current.right 21 | current.right=current.left 22 | current.left=None 23 | leftn.right=temp 24 | 25 | if rightn!=None: 26 | return rightn 27 | 28 | if leftn!=None: 29 | return leftn 30 | 31 | return current 32 | preorder(root) 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /codes/python/largest_rectangular_sub_matrix_sum_divisbl_by_k: -------------------------------------------------------------------------------- 1 | # Python implementation to find largest rectangular 2 | # sub-matrix having sum divisible by k 3 | 4 | start = 0 5 | finish = 0 6 | 7 | # function to find the longest subarray with sum divisible 8 | # by k. The function stores starting and ending indexes of 9 | # the subarray at addresses pointed by start and finish 10 | # pointers respectively. 11 | def longSubarrWthSumDivByK(arr, n, k): 12 | 13 | # unordered map 'um' implemented as 14 | # hash table 15 | 16 | global start,finish 17 | 18 | um = {} 19 | 20 | # 'mod_arr[i]' stores (sum[0..i] % k) 21 | mod_arr = [0 for i in range(n)] 22 | curr_sum,Max = 0,0 23 | 24 | # traverse arr[] and build up the 25 | # array 'mod_arr[]' 26 | for i in range(n): 27 | curr_sum += arr[i] 28 | 29 | # as the sum can be negative, taking modulo twice 30 | mod_arr[i] = ((curr_sum % k) + k) % k 31 | 32 | for i in range(n): 33 | 34 | # if true then sum(0..i) is divisible 35 | # by k 36 | if (mod_arr[i] == 0): 37 | 38 | # update variables 39 | max = i + 1 40 | start = 0 41 | finish = i 42 | 43 | # if value 'mod_arr[i]' not present in 'um' 44 | # then store it in 'um' with index of its 45 | # first occurrence 46 | elif (mod_arr[i] not in um): 47 | um[mod_arr[i]] = i 48 | 49 | else: 50 | # if true, then update variables 51 | if (Max < (i - um[mod_arr[i]])): 52 | Max = i - um[mod_arr[i]] 53 | start = um[mod_arr[i]] + 1 54 | finish = i 55 | 56 | # function to find largest rectangular sub-matrix 57 | # having sum divisible by k 58 | def findLargestSubmatrix(mat, n, k): 59 | # Variables to store the final output 60 | finalLeft, finalRight, finalTop, finalBottom = 0,0,0,0 61 | 62 | left, right, i, maxArea = 0,0,0,0 63 | temp = [0 for i in range(n)] 64 | 65 | # Set the left column 66 | for left in range(n): 67 | 68 | # Set the right column for the left column 69 | # set by outer loop 70 | for right in range(left,n): 71 | 72 | # Calculate sum between current left and 73 | # right for every row 'i' 74 | for i in range(n): 75 | temp[i] += mat[i][right] 76 | 77 | # The longSubarrWthSumDivByK() function sets 78 | # the values of 'start' and 'finish'. So 79 | # submatrix having sum divisible by 'k' between 80 | # (start, left) and (finish, right) which is 81 | # the largest submatrix with boundary columns 82 | # strictly as left and right. 83 | longSubarrWthSumDivByK(temp, n, k) 84 | 85 | # Calculate current area and compare it with 86 | # maximum area so far. If maxArea is less, then 87 | # update maxArea and other output values 88 | if (maxArea < ((right - left + 1) * (finish - start + 1))): 89 | finalLeft = left 90 | finalRight = right 91 | finalTop = start 92 | finalBottom = finish 93 | maxArea = (right - left + 1) * (finish - start + 1) 94 | 95 | # Print final values 96 | print(f"(Top, Left): ({finalTop}, {finalLeft})") 97 | print(f"(Bottom, Right): ({finalBottom}, {finalRight})") 98 | print(f"Area: {maxArea}") 99 | 100 | # Driver program to test above functions 101 | 102 | mat = [ [ 1, 2, -1, -4 ], 103 | [ -8, -3, 4, 2 ], 104 | [ 3, 8, 10, 1 ], 105 | [ -4, -1, 1, 7 ] ] 106 | 107 | n,k = 4,5 108 | findLargestSubmatrix(mat, n, k) 109 | 110 | 111 | -------------------------------------------------------------------------------- /codes/python/timebasedkeyvaluestore.py: -------------------------------------------------------------------------------- 1 | class TimeMap: 2 | def __init__(self): 3 | self.dict = defaultdict(list) 4 | 5 | def set(self, key: str, value: str, timestamp: int) -> None: 6 | self.dict[key].append((timestamp, value)) 7 | def get(self, key: str, timestamp: int) -> str: 8 | l, r = 0, len(self.dict[key])-1 9 | 10 | while l <= r: 11 | mid = (l+r)//2 12 | if values[mid][0] == timestamp: return values[mid][1] 13 | elif values[mid][0] < timestamp: 14 | l = mid+1 15 | else: 16 | r = mid-1 17 | 18 | return values[r][1] if r >= 0 else "" -------------------------------------------------------------------------------- /codes/python/wigglesubsequence.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def wiggleMaxLength(self, nums: List[int]) -> int: 3 | l=0 4 | cnt=0 5 | d=0 6 | what=0 7 | if len(nums)==1: 8 | return 1 9 | if nums[l+1]-nums[l]>0: 10 | d=1 11 | elif nums[l+1]-nums[l]<0: 12 | d=2 13 | else: 14 | d=0 15 | what=1 16 | cnt+=1 17 | l+=1 18 | while l0: 23 | d=1 24 | cnt+=1 25 | l+=1 26 | if what==1: 27 | return cnt 28 | else: 29 | return cnt+1 #i have no idea what just happened but it worked --------------------------------------------------------------------------------