├── .gitignore ├── 2 Keys Keyboard ├── README.md ├── solution.cpp └── solution.txt ├── 3 Sum ├── README.md ├── images │ ├── ap2-step1.png │ ├── ap2-step2.png │ └── ap2-step3.png └── solution.cpp ├── BST Checker ├── README.md ├── solution.cpp └── solution2.cpp ├── CS Fundamentals ├── DBMS.txt └── OOPs.txt ├── Count Numbers Less Than K ├── README.md ├── solution.cpp └── solution.txt ├── Deterministic Finite Automaton ├── README.md ├── solution.cpp └── solution.md ├── Diameter of Generic Tree ├── README.md └── solution.cpp ├── Find K Closest Elements ├── README.md └── solution.cpp ├── Game of Life ├── README.md └── solution.cpp ├── Gas Station ├── README.md ├── solution.cpp └── solution.txt ├── Get Set Queries ├── README.md ├── solution.cpp └── solution.txt ├── Island Count ├── README.md ├── example.png └── solution.cpp ├── LICENSE ├── Linked List ├── Cycle Detection │ ├── README.md │ └── solution.cpp ├── Delete Node │ ├── README.md │ ├── solution.cpp │ └── solution.txt ├── Remove Zero Sum Consecutive Nodes │ ├── README.md │ ├── solution.cpp │ └── solution.txt └── Shift Linked List │ ├── README.md │ ├── scratchpad.txt │ └── solution.cpp ├── Majority Element ├── README.md ├── solution.cpp └── solution.txt ├── Maximum Selling Gap ├── README.md ├── solution.cpp └── solution.md ├── Minimize The Absolute Difference ├── README.md ├── solution.cpp └── solution.txt ├── Minimum Falling Path Sum ├── README.md ├── solution.cpp └── solution.txt ├── Populating Next Right Pointers ├── README.md └── solution.cpp ├── README.md ├── Remove K Digits ├── README.md ├── solution.cpp └── solution.txt ├── Set Matrix Zeroes ├── README.md ├── solution.txt ├── solution_constant_space.cpp └── solution_linear_space.cpp ├── Target Sum └── solution.cpp ├── Unique Paths III ├── README.md └── solution.cpp ├── Very Hard Queries ├── README.md ├── image_1.png ├── solution.cpp └── solution.md ├── Ways To Form Max Heap ├── README.md ├── solution.cpp └── solution.txt └── Word Break ├── README.md ├── solution.cpp └── solution.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | -------------------------------------------------------------------------------- /2 Keys Keyboard/README.md: -------------------------------------------------------------------------------- 1 | # Two Keys Keyboard 2 | [Try the problem](http://leetcode.com/problems/2-keys-keyboard/) 3 | 4 | Initially on a notepad only one character 'A' is present. 5 | You can perform two operations on this notepad for each step: 6 | 7 | 1. `Copy All`: You can copy all the characters present on the notepad (partial copy is not allowed). 8 | 2. `Paste`: You can paste the characters which are copied **last time**. 9 | 10 | Given a number `n`. 11 | 12 | You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. 13 | Output the minimum number of steps to get n 'A'. 14 | 15 | ### Example 1 16 | 17 | ``` 18 | Input: 3 19 | Output: 3 20 | Explanation: 21 | Intitally, we have one character 'A'. 22 | In step 1, we use Copy All operation. 23 | In step 2, we use Paste operation to get 'AA'. 24 | In step 3, we use Paste operation to get 'AAA'. 25 | ``` -------------------------------------------------------------------------------- /2 Keys Keyboard/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Solution { 5 | private: 6 | int steps[1010][1010]; 7 | public: 8 | int solve(int cur_len, int copy_len, int N) { 9 | if (cur_len == N) { 10 | return 0; 11 | } 12 | if (cur_len > N) { 13 | return -1; 14 | } 15 | if (steps[cur_len][copy_len] != -1) { 16 | return steps[cur_len][copy_len]; 17 | } 18 | int res = INT_MAX; 19 | // copy if copy_len != cur_len 20 | if (copy_len != cur_len) { 21 | int next = solve(cur_len, cur_len, N); 22 | if (next != -1) { 23 | res = 1 + next; 24 | } 25 | } 26 | // paste if copy_len > 0 27 | if (copy_len > 0) { 28 | int next = solve(cur_len + copy_len, copy_len, N); 29 | if (next != -1) { 30 | res = min(res, 1 + next); 31 | } 32 | } 33 | if (res == INT_MAX) { 34 | res = -1; 35 | } 36 | return steps[cur_len][copy_len] = res; 37 | } 38 | int minSteps(int n) { 39 | if (n == 1) { 40 | return 0; 41 | } 42 | memset(steps, -1, sizeof(steps)); 43 | return solve(1, 0, n); 44 | } 45 | }; 46 | 47 | int main () { 48 | Solution solver; 49 | cout << solver.minSteps(10) << endl; 50 | return 0; 51 | } -------------------------------------------------------------------------------- /2 Keys Keyboard/solution.txt: -------------------------------------------------------------------------------- 1 | Think it in terms of having 2 options at each step 2 | either to choose the copy option (not required in case current length is same as copied length) 3 | or to choose the paste option. 4 | 5 | So, we can use recursion and memoization (caching the results for (cur_len, copy_len) pair). -------------------------------------------------------------------------------- /3 Sum/README.md: -------------------------------------------------------------------------------- 1 | # 3Sum 2 | 3 | ## Problem Statement 4 | Given an array of **nums** of **n** integers, are there elements *a*, *b*, *c* in **nums** such that *a + b + c = 0*? Find all unique triplets in the array which gives the sum of zero. 5 | 6 | ### Note 7 | The solution set must not contain duplicate triplets. 8 | 9 | ### Example 10 | Given array `nums = [-1, 0, 1, 2, -1, -4]`, 11 | 12 | A solution set is: 13 | 14 | `[ 15 | [-1, 0, 1], 16 | [-1, -1, 2] 17 | ]` 18 | 19 | ## Solution Approach 1 - Brute Force (Time Limit Exceeded) 20 | Consider all possible triplets using 3 nested loops, and if the sum of the triplet equals 0, add it to a set of vector (after sorting those 3 numbers). This will make sure that the final result doesn't contain any duplicate triplets. 21 | 22 | ### Time Complexity 23 | This solution takes a time complexity of `O(N^3 log N)` since insertion in the set will take `O(log N)` time. 24 | 25 | ## Solution Approach 2 - Two Pointers 26 | ### Intuition 27 | Let's say we fixed one of the numbers in the triplets as `x` and other numbers be `y` and `z`. 28 | Thus, 29 | `y + z = -x`. 30 | 31 | If we had sorted the elements in the given array, we can easily find a pair with given sum value using a `two-pointer` approach. 32 | 33 | We maintain one `start` pointer at the beginning of the array, and an `end` pointer at the end of the array. 34 | 35 | Considering the sum of values at these 2 positions: 36 | 37 | - Less than the `target`: Shift the `start` pointer to right. 38 | - Greater than the `target`: Shift the `end` pointer to the left. 39 | - Equals the `target`: Congrats! You've found the pair. 40 | 41 | Let us understand the 2-pointer approach to find pair with given sum. Consider the given array (sorted) as 42 | 43 | `A = [-10, -5, -2, 12, 13]` 44 | 45 | and you need to find a pair with sum = -12. 46 | 47 | ![Step 1](images/ap2-step1.png) 48 | 49 | Initially, sum = 3 which is more than -12, thus shifting the end pointer to left. 50 | 51 | ![Step 2](images/ap2-step2.png) 52 | 53 | Again, shifting the end pointer to the left. 54 | 55 | ![Step 3](images/ap2-step3.png) 56 | 57 | Finally, you get a pair with sum = target. 58 | 59 | We still need to make sure that we do not get duplicate triplets, and we do not miss one! 60 | 61 | ## Algorithm 62 | Let's take an example to develop the algorithm. 63 | 64 | `A = [-2, -2, -1, -1, 0, 1, 1, 2, 2]` 65 | 66 | Let's say we were to consider first -2 as fixed. Now, we need to find pairs with sum = 2 in the remaining array.
67 | i.e. pairs with **target = 2** in `A' = [-2, -1, -1, 0, 1, 1, 2, 2]` 68 | 69 | To find multiple pairs, we can do the following modification: 70 |
71 | Whenever pair sum = target, shift both start and end pointers to right and left respectively. 72 | So, we will get `(0, 2)` and `(1, 1)` as the required pairs and hence `(-2, 0, 2)` and `(-2, 1, 1)` as the corresponding triplets. 73 | 74 | Now, considering the next `-2` in the array, can we simply ignore the left part of the array? 75 |
76 | Exactly, because we already found all possible pairs taking elements in the left part as fixed. 77 |
78 | So, for the second `-2` in the array, the array to look is just to the right of it, i.e. `A' = [-1, -1, 0, 1, 1, 2, 2]`. 79 | 80 | But, now how do we ensure that no duplicate triplets are present in the result? 81 |
82 | If we use an additional set to store the results, it will be require additional space, as well as insertion would take `O(log N)`. Can we do it more **efficiently**? 83 | 84 | Let's consider another example:
85 | `B = [-2, -2, -2, 1, 1, 4, 4]` 86 | 87 | - So, let's start with the `-2` at index `0`. 88 | - Let's find all pairs with sum `2`. 89 | - They come out to be `(-2, 4), (-2, 4), (1, 1)`. 90 | - At each step, we shift both the `start` and `end` pointers since sum exactly matches target. 91 | 92 | Could we have avoided the duplicate `(-2, 4)` getting in our way? YES.
93 | See that we can simply move the `start` pointer while it matches its old value (-2) and similarly shift the `end` pointer till it matches its old value (4). 94 | 95 | - Now, let's come to the `-2` at index `1`. 96 | - As per our approach, we will see to its right to get pairs with sum `2`. 97 | - But, we have already considered all possible pairs with `sum = 2` for the previous `-2`. 98 | - So, we can simply ignore this element for further processing to avoid duplicates. 99 | 100 | From this example, we have found out a way to avoid duplicates. 101 | 102 | - We can simply move our first element of triplet to the right till it matches the previous number. 103 | - While finding the pair with sum equal to negation of fixed element, we can shift the start/end pointers till they refer to the same values (old start/end). 104 | 105 | ### Time Complexity 106 | - First of all, array is sorted incurring `O(n log n)`. 107 | - We are then fixing the first element of the triplet in the outer loop running over all the elements. 108 | - In the inner loop, we find a pair with sum equals negation of number fixed in outer loop, using two-pointer approach and avoiding duplicates smartly. 109 | 110 | Thus, overall time complexity = `O(nlogn + n*n)` = `O(n^2)` 111 | 112 | ### Implementation 113 | 114 | #### C++ Code 115 | ```c++ 116 | class Solution { 117 | public: 118 | vector> threeSum(vector& nums) { 119 | vector> res; 120 | 121 | // size of the array nums 122 | int total = nums.size(); 123 | 124 | // sort the numbers 125 | sort(nums.begin(), nums.end()); 126 | 127 | // fix the first number of the triplet 128 | for (int firstNumIdx = 0; firstNumIdx < total; ++firstNumIdx) { 129 | int firstNum = nums[firstNumIdx]; 130 | // find pairs with sum = -firstNum in the right 131 | int start = firstNumIdx + 1; 132 | int end = total - 1; 133 | while (start < end) { 134 | // consider the current pair sum 135 | int current = nums[start] + nums[end]; 136 | if (current < -firstNum) { 137 | // shift the start pointer to the right 138 | ++start; 139 | } else if (current > -firstNum) { 140 | // shift the end pointer to the left 141 | --end; 142 | } else { 143 | // add to the result 144 | res.push_back({firstNum, nums[start], nums[end]}); 145 | int oldStart = start; 146 | int oldEnd = end; 147 | // shift the start till it matches the old value 148 | while (start < end && nums[start] == nums[oldStart]) { 149 | ++start; 150 | } 151 | // shift the end till it matches the old value 152 | while (end > start && nums[end] == nums[oldEnd]) { 153 | --end; 154 | } 155 | // the above two while loops ensure that both start/end 156 | // get shifted atleast once 157 | } 158 | // avoid duplicates 159 | while (firstNumIdx + 1 < total 160 | && nums[firstNumIdx + 1] == nums[firstNumIdx]) { 161 | ++firstNumIdx; 162 | } 163 | } 164 | } 165 | 166 | return res; 167 | } 168 | }; 169 | ``` -------------------------------------------------------------------------------- /3 Sum/images/ap2-step1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahilbansal17/Coding-Interview-Problems/7f30d64c5aba2c3aef92b0efb76ffbec92c61dd3/3 Sum/images/ap2-step1.png -------------------------------------------------------------------------------- /3 Sum/images/ap2-step2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahilbansal17/Coding-Interview-Problems/7f30d64c5aba2c3aef92b0efb76ffbec92c61dd3/3 Sum/images/ap2-step2.png -------------------------------------------------------------------------------- /3 Sum/images/ap2-step3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahilbansal17/Coding-Interview-Problems/7f30d64c5aba2c3aef92b0efb76ffbec92c61dd3/3 Sum/images/ap2-step3.png -------------------------------------------------------------------------------- /3 Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> threeSum(vector& nums) { 4 | vector> res; 5 | 6 | // size of the array nums 7 | int total = nums.size(); 8 | 9 | // sort the numbers 10 | sort(nums.begin(), nums.end()); 11 | 12 | // fix the first number of the triplet 13 | for (int firstNumIdx = 0; firstNumIdx < total; ++firstNumIdx) { 14 | int firstNum = nums[firstNumIdx]; 15 | // find pairs with sum = -firstNum in the right 16 | int start = firstNumIdx + 1; 17 | int end = total - 1; 18 | while (start < end) { 19 | // consider the current pair sum 20 | int current = nums[start] + nums[end]; 21 | if (current < -firstNum) { 22 | // shift the start pointer to the right 23 | ++start; 24 | } else if (current > -firstNum) { 25 | // shift the end pointer to the left 26 | --end; 27 | } else { 28 | // add to the result 29 | res.push_back({firstNum, nums[start], nums[end]}); 30 | int oldStart = start; 31 | int oldEnd = end; 32 | // shift the start till it matches the old value 33 | while (start < end && nums[start] == nums[oldStart]) { 34 | ++start; 35 | } 36 | // shift the end till it matches the old value 37 | while (end > start && nums[end] == nums[oldEnd]) { 38 | --end; 39 | } 40 | // the above two while loops ensure that both start/end 41 | // get shifted atleast once 42 | } 43 | // avoid duplicates 44 | while (firstNumIdx + 1 < total 45 | && nums[firstNumIdx + 1] == nums[firstNumIdx]) { 46 | ++firstNumIdx; 47 | } 48 | } 49 | } 50 | 51 | return res; 52 | } 53 | }; -------------------------------------------------------------------------------- /BST Checker/README.md: -------------------------------------------------------------------------------- 1 | # Binary Search Tree Checker 2 | [Try the problem](https://leetcode.com/problems/validate-binary-search-tree/) 3 | 4 | Given a binary tree, determine if it is a valid binary search tree (BST). 5 | 6 | Assume a BST is defined as follows: 7 | - The left subtree of a node contains only nodes with keys less than the node's key. 8 | - The right subtree of a node contains only nodes with keys greater than the node's key. 9 | - Both the left and right subtrees must also be binary search trees. 10 | 11 | ### Example 1 12 | 13 | ``` 14 | 2 15 | / \ 16 | 1 3 17 | 18 | Input: [2,1,3] 19 | Output: true 20 | ``` 21 | 22 | ### Example 2 23 | 24 | ``` 25 | 5 26 | / \ 27 | 1 4 28 | / \ 29 | 3 6 30 | 31 | Input: [5,1,4,null,null,3,6] 32 | Output: false 33 | Explanation: The root node's value is 5 but its right child's value is 4. 34 | ``` -------------------------------------------------------------------------------- /BST Checker/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | */ 7 | struct TreeNode { 8 | int val; 9 | TreeNode *left; 10 | TreeNode *right; 11 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 12 | }; 13 | 14 | TreeNode* insertLeft(TreeNode* root, int value) { 15 | root->left = new TreeNode(value); 16 | return root->left; 17 | } 18 | 19 | TreeNode* insertRight(TreeNode* root, int value) { 20 | root->right = new TreeNode(value); 21 | return root->right; 22 | } 23 | 24 | class Solution { 25 | public: 26 | bool isValid(TreeNode* root, int minVal, int maxVal, bool noMin, bool noMax) { 27 | if (root == NULL) { 28 | return true; 29 | } 30 | if (!noMin && root->val <= minVal) { 31 | return false; 32 | } 33 | if (!noMax && root->val >= maxVal) { 34 | return false; 35 | } 36 | bool rightValid = false; 37 | bool leftValid = false; 38 | rightValid = isValid(root->right, root->val, maxVal, false, noMax); 39 | leftValid = isValid(root->left, minVal, root->val, noMin, false); 40 | return rightValid && leftValid; 41 | } 42 | bool isValidBST(TreeNode* root) { 43 | return isValid(root, 0, 0, true, true); 44 | } 45 | }; 46 | 47 | int main() { 48 | auto root1 = new TreeNode(50); 49 | Solution solver; 50 | cout << solver.isValidBST(root1) << endl; // true 51 | 52 | auto root2 = new TreeNode(50); 53 | insertLeft(root2, 30); 54 | insertLeft(root2->left, 10); 55 | insertRight(root2, 70); 56 | insertRight(root2->right, 80); 57 | insertRight(root2->left, 40); 58 | insertLeft(root2->right, 60); 59 | cout << solver.isValidBST(root2) << endl; // true 60 | 61 | auto root3 = new TreeNode(50); 62 | insertLeft(root3, 30); 63 | insertLeft(root3->left, 20); 64 | insertRight(root3, 80); 65 | insertRight(root3->right, 90); 66 | insertRight(root3->left, 60); 67 | insertLeft(root3->right, 70); 68 | cout << solver.isValidBST(root3) << endl; // false 69 | } -------------------------------------------------------------------------------- /BST Checker/solution2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /** 5 | * Definition for a binary tree node. 6 | */ 7 | struct TreeNode { 8 | int val; 9 | TreeNode *left; 10 | TreeNode *right; 11 | TreeNode(int x) : val(x), left(NULL), right(NULL) {} 12 | }; 13 | 14 | TreeNode* insertLeft(TreeNode* root, int value) { 15 | root->left = new TreeNode(value); 16 | return root->left; 17 | } 18 | 19 | TreeNode* insertRight(TreeNode* root, int value) { 20 | root->right = new TreeNode(value); 21 | return root->right; 22 | } 23 | 24 | class Solution { 25 | public: 26 | pair solve(TreeNode* node, bool& res) { 27 | int val = node->val; 28 | pair p[2]; 29 | // handle corner cases 30 | 31 | int *minRight = NULL; 32 | int *maxLeft = NULL; 33 | if (node->left) { 34 | p[0] = solve(node->left, res); 35 | maxLeft = new int; 36 | *maxLeft = p[0].second; 37 | } 38 | if (node->right) { 39 | p[1] = solve(node->right, res); 40 | minRight = new int; 41 | *minRight = p[1].first; 42 | } 43 | if (maxLeft && val <= *maxLeft) { 44 | res = false; 45 | } 46 | if (minRight && val >= *minRight) { 47 | res = false; 48 | } 49 | 50 | pair returnPair; 51 | int overallMin = node->val, overallMax = node->val; 52 | if (maxLeft) { 53 | overallMax = max(overallMax, *maxLeft); 54 | overallMin = min(overallMin, p[0].first); 55 | } 56 | if (minRight) { 57 | overallMax = max(overallMax, p[1].second); 58 | overallMin = min(overallMin, *minRight); 59 | } 60 | returnPair.first = overallMin; 61 | returnPair.second = overallMax; 62 | // cout << overallMin << " " << overallMax << endl; 63 | return returnPair; 64 | } 65 | bool isValidBST(TreeNode* root) { 66 | bool res = true; 67 | // handle corner cases 68 | if (!root) { 69 | return res; 70 | } 71 | pair vals = solve(root, res); 72 | return res; 73 | } 74 | }; 75 | 76 | int main() { 77 | auto root1 = new TreeNode(50); 78 | Solution solver; 79 | cout << solver.isValidBST(root1) << endl; // true 80 | 81 | auto root2 = new TreeNode(50); 82 | insertLeft(root2, 30); 83 | insertLeft(root2->left, 10); 84 | insertRight(root2, 70); 85 | insertRight(root2->right, 80); 86 | insertRight(root2->left, 40); 87 | insertLeft(root2->right, 60); 88 | cout << solver.isValidBST(root2) << endl; // true 89 | 90 | auto root3 = new TreeNode(50); 91 | insertLeft(root3, 30); 92 | insertLeft(root3->left, 20); 93 | insertRight(root3, 80); 94 | insertRight(root3->right, 90); 95 | insertRight(root3->left, 60); 96 | insertLeft(root3->right, 70); 97 | cout << solver.isValidBST(root3) << endl; // false 98 | } -------------------------------------------------------------------------------- /CS Fundamentals/DBMS.txt: -------------------------------------------------------------------------------- 1 | 1. Entity Relationship Model 2 | 2. Relational Model 3 | 3. Normalization 4 | i. 1 NF 5 | ii. 2 NF 6 | iii. 3 NF 7 | iv. BCNF 8 | 4. Transacations and ACID properties 9 | i. Atomicity 10 | ii. Consistency 11 | iii. Isolation 12 | iv. Durability -------------------------------------------------------------------------------- /CS Fundamentals/OOPs.txt: -------------------------------------------------------------------------------- 1 | 1. Object Oriented Programming 2 | i. Encapuslation 3 | ii. Data Abstraction 4 | -> Access modifiers 5 | a. Private 6 | b. Protected 7 | c. Public 8 | -> Friend functions 9 | iii. Polymorphism 10 | -> Static 11 | a. Operator Overloading 12 | b. Function Overloading 13 | -> Dynamic/Runtime 14 | a. Virtual Functions 15 | -> vtable 16 | -> vptr 17 | iv. Inheritance 18 | -> Modes 19 | a. Public 20 | b. Protected 21 | c. Private 22 | -> Types 23 | a. Single 24 | b. Multiple 25 | c. Multilevel 26 | d. Hierarchical 27 | e. Hybrid -------------------------------------------------------------------------------- /Count Numbers Less Than K/README.md: -------------------------------------------------------------------------------- 1 | # Numbers of length N and value less than K 2 | [Try the problem](https://www.interviewbit.com/problems/numbers-of-length-n-and-value-less-than-k/) 3 | 4 | Given a set of digits (A) in sorted order, find how many numbers of length B are possible whose value is less than number C. 5 | 6 | ### Example 1 7 | 8 | ``` 9 | Input: 10 | 0 1 5 11 | 1 12 | 2 13 | 14 | Output: 15 | 2 (0 and 1 are possible) 16 | ``` 17 | 18 | ### Example 2 19 | 20 | ``` 21 | Input: 22 | 0 1 2 5 23 | 2 24 | 21 25 | 26 | Output: 27 | 5 (10, 11, 12, 15, 20 are possible) 28 | ``` -------------------------------------------------------------------------------- /Count Numbers Less Than K/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | int countDigits(int X) { 7 | int cnt = 0; 8 | while (X) { 9 | X /= 10; 10 | ++cnt; 11 | } 12 | return cnt; 13 | } 14 | 15 | class Solution { 16 | public: 17 | int solve(vector &A, int B, int C); 18 | }; 19 | 20 | /* 21 | * vector& A: contains the digits which can be used 22 | * int B: the length of which the numbers are to be formed 23 | * int C: the numbers formed should have value < C 24 | */ 25 | int Solution::solve(vector &A, int B, int C) { 26 | // not assuming that length of C is same as B 27 | int total = countDigits(C); 28 | 29 | if (total < B) { 30 | return 0; 31 | } 32 | 33 | int result = 0; // we can form all numbers with length B, not starting from 0 34 | bool zeroPresent = false; 35 | int n = A.size(); 36 | 37 | vector cnt(11, 0); 38 | vector origCnt(11, 0); 39 | for (int i = 0; i < n; ++i) { 40 | ++cnt[A[i]]; 41 | ++origCnt[A[i]]; 42 | if (A[i] == 0) { 43 | zeroPresent = true; 44 | } 45 | } 46 | if (!zeroPresent) { 47 | result = pow(n, B); 48 | } else { 49 | result = (n - 1) * pow(n, B - 1); 50 | } 51 | 52 | int origC = C; 53 | if (total == B) { 54 | // need to subtract those cases where number formed is >= C 55 | // find suffix of cnt to represent count of digits in set >= given digit 56 | for (int i = 8; i >= 0; --i) { 57 | cnt[i] = cnt[i] + cnt[i + 1]; 58 | } 59 | 60 | vector digits; 61 | while (C) { 62 | digits.push_back(C % 10); 63 | C /= 10; 64 | } 65 | reverse(digits.begin(), digits.end()); 66 | 67 | int toSubtract = 0; 68 | // loop for every digit in C 69 | bool presentC = true; 70 | for (int i = 0; i < B; ++i) { 71 | int cur = digits[i]; 72 | toSubtract += cnt[cur + 1]*pow(n, B - i - 1); 73 | if (origCnt[cur] == 0) { 74 | presentC = false; 75 | break; 76 | } 77 | } 78 | if (presentC) { 79 | toSubtract += 1; 80 | } 81 | result -= toSubtract; 82 | } 83 | if (B == 1 && origC > 0 && zeroPresent) { 84 | ++result; 85 | } 86 | return result; 87 | } 88 | 89 | int main () { 90 | Solution solver; 91 | vector digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 92 | int length = 3; 93 | int maxValue = 1000; 94 | cout << solver.solve(digits, length, maxValue) << endl; 95 | return 0; 96 | } -------------------------------------------------------------------------------- /Count Numbers Less Than K/solution.txt: -------------------------------------------------------------------------------- 1 | To be updated! -------------------------------------------------------------------------------- /Deterministic Finite Automaton/README.md: -------------------------------------------------------------------------------- 1 | # Deterministic Finite Automaton 2 | [Try the problem](https://www.interviewbit.com/problems/deterministic-finite-automaton/) 3 | 4 | Deterministic finite automaton(DFA) is a finite state machine that accepts/rejects finite strings of symbols and only produces a unique computation (or run) of the automation for each input string. 5 | 6 | - DFAs can be represented using state diagrams. For example, in the automaton shown below, there are three states: S0, S1, and S2 (denoted graphically by circles). 7 | - The automaton takes a finite sequence of 0s and 1s as input. 8 | - For each state, there is a transition arrow leading out to a next state for both 0 and 1. 9 | - Upon reading a symbol, a DFA jumps deterministically from a state to another by following the transition arrow. 10 | - For example, if the automaton is currently in state S0 and current input symbol is 1 then it deterministically jumps to state S1. 11 | - A DFA has a start state (denoted graphically by an arrow coming in from nowhere) where computations begin, and a set of accept states (denoted graphically by a double circle) which help define when a computation is successful. 12 | 13 | ![multiples_of_3](https://upload.wikimedia.org/wikipedia/commons/9/94/DFA_example_multiplies_of_3.svg) 14 | 15 | These are some strings above DFA accepts, 16 | 17 | ``` 18 | 0 19 | 00 20 | 000 21 | 11 22 | 110 23 | 1001 24 | ``` 25 | 26 | You are given a DFA in input and an integer N. You have to tell how many distinct strings of length N the given DFA accepts. Return answer modulo 109+7. 27 | 28 | ### Notes 29 | 30 | 1. Assume each state has two outgoing edges(one for 0 and one for 1). Both outgoing edges won’t go to the same state. 31 | 2. There could be multiple accept states, but only one start state. 32 | 3. A start state could also be an accept state. 33 | 34 | ### Input Format 35 | 36 | 1. States are numbered from 0 to K-1, where K is total number of states in DFA. 37 | 2. You are given three arrays zeroEdges, oneEdges, accepting and two integers start and N. 38 | 3. Array `zeroEdges` denotes a 0 edge from state numbered i to state A[i], for all 0 ≤ i ≤ K-1 39 | 4. Array `oneEdges` denotes a 1 edge from state numbered i to state B[i], for all 0 ≤ i ≤ K-1 40 | 5. Array `accepting` contains indices of all accept states. 41 | 6. Integer `start` denotes the start state. 42 | 7. Integer `N` denotes you have to count how many distinct strings of length N the given DFA accepts. 43 | 44 | ### Example 45 | 46 | ``` 47 | For the DFA shown in image, input is 48 | zeroEdges = [0, 2, 1] 49 | oneEdges = [1, 0, 2] 50 | accepting = [0] 51 | start = 0 52 | 53 | Input 1 54 | ------- 55 | N = 2 56 | Strings '00' and '11' are only strings on length 2 which are accepted. So, answer is 2. 57 | 58 | Input 2 59 | ------- 60 | N = 1 61 | String '0' is the only string. Answer is 1. 62 | ``` -------------------------------------------------------------------------------- /Deterministic Finite Automaton/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | const ll MOD = 1e9 + 7; 6 | /* 7 | ll cache[60][4010]; 8 | 9 | ll solve(int start, int N, vector& zero, vector& one, vector& accepting) { 10 | if (N == 0) { 11 | if (accepting[start]) { 12 | return 1; 13 | } 14 | return 0; 15 | } 16 | if (cache[start][N] != -1) { 17 | return cache[start][N]; 18 | } 19 | ll res = 0; 20 | res += solve(zero[start], N - 1, zero, one, accepting); 21 | res %= MOD; 22 | res += solve(one[start], N - 1, zero, one, accepting); 23 | return cache[start][N] = res; 24 | } 25 | */ 26 | int automata(vector &zeroEdge, vector &oneEdge, vector &accepting, int start, int N) { 27 | // memset(cache, -1, sizeof(cache)); 28 | 29 | int states = zeroEdge.size(); 30 | vector acceptingState(states, 0); 31 | for (auto acc: accepting) { 32 | acceptingState[acc] = 1; 33 | } 34 | // return (int)solve(start, N, zeroEdge, oneEdge, acceptingState); 35 | 36 | /** 37 | * Time: O(N*K) where N = length, K = no of states 38 | * Space: O(K) 39 | * Iterative Dynamic Programming 40 | */ 41 | vector acceptingBefore(states, 0); // for length (i - 1) 42 | vector acceptingCurrent(states, 0); // for length (i) 43 | for (int i = 0; i < states; ++i) { 44 | if (acceptingState[i]) { 45 | acceptingCurrent[i] = 1; // for length 0, it is accepting 46 | } 47 | } 48 | 49 | for (int len = 1; len <= N; ++len) { 50 | acceptingBefore = acceptingCurrent; 51 | for (int state = 0; state < states; ++state) { 52 | acceptingCurrent[state] = (acceptingBefore[zeroEdge[state]] + acceptingBefore[oneEdge[state]]) % MOD; 53 | } 54 | } 55 | 56 | // only consider strings accepted with start state and having length N 57 | return (int)acceptingCurrent[start]; 58 | } 59 | 60 | int main () { 61 | vector zeroEdges = {0, 2, 1}; 62 | vector oneEdges = {1, 0, 2}; 63 | vector accepting = {0}; 64 | int start = 0; 65 | int length = 2; 66 | cout << automata(zeroEdges, oneEdges, accepting, start, length) << endl; 67 | return 0; 68 | } -------------------------------------------------------------------------------- /Deterministic Finite Automaton/solution.md: -------------------------------------------------------------------------------- 1 | # Solution 2 | 3 |
4 | 5 | Hint 1 6 | 7 | Being at the start state, you have two options, either to take a zeroEdge from here, or to take a oneEdge from here. 8 | 9 | Now, your problem reduces to finding accepting string count for length (N - 1) being at this new state. 10 | So, try to think in terms of recursion. 11 | Make sure you end up writing base cases clearly. 12 |
13 | 14 |
15 | 16 | Hint 2 17 | 18 | Think about of base case, when the length passed is zero. Then you have two cases to consider, either the current state is accepting or non-accepting! 19 | 20 | Now, try to take some examples and you can observe that there will be overlapping subproblems. Thus, you can use dynamic programming over here. 21 | First of all, try to implement the memoized version of the solution, and analyze its time and space complexity. 22 | 23 |
24 | 25 |
26 | 27 | Hint 3 28 | 29 | You will notice that the recursion with memoization takes O(N*K) time where K is the no. of states, as well as `O(N*K)` memory. Thus, the solution is memory intensive. 30 | 31 | Try to take an example, and see how the values are getting filled in the memo or cache or table. You can come up with an iterative solution that will take up linear space! 32 |
-------------------------------------------------------------------------------- /Diameter of Generic Tree/README.md: -------------------------------------------------------------------------------- 1 | # Largest Distance between nodes of a Tree 2 | [Try the problem](https://www.interviewbit.com/problems/largest-distance-between-nodes-of-a-tree/) 3 | 4 | Given an arbitrary unweighted rooted tree which consists of `N (2 <= N <= 40000)` nodes. 5 | 6 | The goal of the problem is to find largest distance between two nodes in a tree. 7 | 8 | Distance between two nodes is a number of edges on a path between the nodes (there will be a unique path between any pair of nodes since it is a tree). 9 | 10 | The nodes will be numbered `0` through `N - 1`. 11 | 12 | The tree is given as an array `P`, there is an edge between nodes `P[i]` and `i` (0 <= i < N). 13 | 14 | Exactly one of the i’s will have P[i] equal to -1, it will be **root node**. 15 | 16 | ### Example 17 | 18 | ``` 19 | Input: 20 | P = [-1, 0, 0, 0, 3] 21 | ``` 22 | 23 | Tree looks like this: 24 | ``` 25 | 0 26 | / | \ 27 | 3 1 2 28 | / 29 | 4 30 | ``` 31 | 32 | ``` 33 | Output: 3 (one of the longest path is 4 -> 3 -> 0 -> 2). 34 | ``` -------------------------------------------------------------------------------- /Diameter of Generic Tree/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | pair rec_solve(int root, vector adj[], vector& vis) { 5 | vis[root] = 1; 6 | 7 | int ht = 0; 8 | int dia = 0; 9 | int ht_best = -1; 10 | int ht_second_best = -1; 11 | for (auto next: adj[root]) { 12 | if (!vis[next]) { 13 | auto dia_height = rec_solve(next, adj, vis); 14 | int dia_next = dia_height.first; 15 | int ht_next = dia_height.second; 16 | ht = max(ht, ht_next); 17 | if (ht_next > ht_best) { 18 | ht_second_best = ht_best; 19 | ht_best = ht_next; 20 | } else if (ht_next > ht_second_best) { 21 | ht_second_best = ht_next; 22 | } 23 | dia = max(dia, dia_next); 24 | int dia2 = 0; 25 | if (ht_best != -1) { 26 | dia2 = ht_best; 27 | } 28 | if (ht_second_best != -1) { 29 | dia2 += ht_second_best; 30 | } 31 | dia = max(dia, dia2); 32 | } 33 | } 34 | 35 | return {dia, 1 + ht}; 36 | } 37 | 38 | int diameter(vector &A) { 39 | int n = A.size(); 40 | int root = 0; 41 | vector adj[n]; 42 | for (int i = 0; i < n; ++i) { 43 | if (A[i] == -1) { 44 | root = i; 45 | } else { 46 | adj[i].push_back(A[i]); 47 | adj[A[i]].push_back(i); 48 | } 49 | } 50 | vectorvis(n, 0); 51 | pair res = rec_solve(root, adj, vis); // {diameter, height} 52 | return res.first; 53 | } 54 | 55 | int main () { 56 | 57 | vector P = {-1, 0, 0, 0, 3}; 58 | cout << diameter(P) << endl; // 3 59 | } -------------------------------------------------------------------------------- /Find K Closest Elements/README.md: -------------------------------------------------------------------------------- 1 | # Find K Closest Elements 2 | [Try the problem](https://leetcode.com/problems/find-k-closest-elements/) 3 | 4 | Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred. -------------------------------------------------------------------------------- /Find K Closest Elements/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | vector findClosestElements(vector& arr, int k, int x) { 9 | int n = arr.size(); 10 | int idx = lower_bound(arr.begin(), arr.end(), x) - arr.begin(); 11 | int left = idx - 1; 12 | int right = idx; 13 | vector res; 14 | while (res.size() < k) { 15 | int diff_left = INT_MAX; 16 | int diff_right = INT_MAX; 17 | if (left >= 0) { 18 | diff_left = abs(arr[left] - x); 19 | } 20 | if (right < n) { 21 | diff_right = abs(arr[right] - x); 22 | } 23 | if (diff_left <= diff_right) { 24 | res.push_back(arr[left]); 25 | --left; 26 | } else { 27 | res.push_back(arr[right]); 28 | ++right; 29 | } 30 | } 31 | sort(res.begin(), res.end()); 32 | return res; 33 | } 34 | }; 35 | 36 | int main() { 37 | Solution solver; 38 | vector inp({2, 6, 8, 13, 14, 15}); 39 | int k = 3; 40 | int x = 10; 41 | 42 | vector res = solver.findClosestElements(inp, k, x); // [6, 8, 13] 43 | for (auto elem: res) { 44 | cout << elem << " "; 45 | } 46 | cout << endl; 47 | } -------------------------------------------------------------------------------- /Game of Life/README.md: -------------------------------------------------------------------------------- 1 | # Game of Life 2 | [Try the problem](https://leetcode.com/problems/game-of-life/) 3 | 4 | According to the [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." 5 | 6 | Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): 7 | 8 | 1. Any live cell with fewer than two live neighbors dies, as if caused by under-population. 9 | 2. Any live cell with two or three live neighbors lives on to the next generation. 10 | 3. Any live cell with more than three live neighbors dies, as if by over-population.. 11 | 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. 12 | 13 | Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. 14 | 15 | ### Example 16 | 17 | ``` 18 | Input: 19 | [ 20 | [0,1,0], 21 | [0,0,1], 22 | [1,1,1], 23 | [0,0,0] 24 | ] 25 | ``` 26 | 27 | ``` 28 | Output: 29 | [ 30 | [0,0,0], 31 | [1,0,1], 32 | [0,1,1], 33 | [0,1,0] 34 | ] 35 | ``` 36 | 37 | ### Follow-up 38 | 1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells. 39 | 2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems? -------------------------------------------------------------------------------- /Game of Life/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | private: 7 | int dx[8] = {-1, -1, -1, 0, 0, +1, +1, +1}; 8 | int dy[8] = {-1, 0, +1, -1, +1, -1, 0, +1}; 9 | bool isSafe(int x, int y, int N, int M) { 10 | if (x < 0 || y < 0) { 11 | return false; 12 | } 13 | if (x >= N || y >= M) { 14 | return false; 15 | } 16 | return true; 17 | } 18 | public: 19 | void gameOfLife(vector>& board) { 20 | int N = board.size(); 21 | int M = board[0].size(); 22 | for (int row = 0; row < N; ++row) { 23 | for (int col = 0; col < M; ++col) { 24 | // count no. of live neighbors 25 | int neighbors = 0; 26 | for (int k = 0; k < 8; ++k) { 27 | int x = row + dx[k]; 28 | int y = col + dy[k]; 29 | if (isSafe(x, y, N, M) && board[x][y] >= 1) { 30 | ++neighbors; 31 | } 32 | } 33 | if (board[row][col] == 1) { 34 | // update the cell with neighbors count 35 | if (neighbors != 0) { 36 | board[row][col] = neighbors; 37 | } 38 | } else { 39 | // update the cell with -neighbors count 40 | board[row][col] = -neighbors; 41 | } 42 | } 43 | } 44 | 45 | for (int row = 0; row < N; ++row) { 46 | for (int col = 0; col < M; ++col) { 47 | int neighbors = board[row][col]; 48 | if (neighbors > 0) { 49 | if (neighbors < 2) { // live cell with < 2 live neighbors dies 50 | board[row][col] = 0; 51 | } else if (neighbors <= 3) { // with 2-3 lives 52 | board[row][col] = 1; 53 | } else { // dies due to over-population 54 | board[row][col] = 0; 55 | } 56 | } else { 57 | if (neighbors == -3) { // dead cell with 3 live neighbors 58 | board[row][col] = 1; 59 | } else { 60 | board[row][col] = 0; 61 | } 62 | } 63 | } 64 | } 65 | } 66 | }; 67 | 68 | int main () { 69 | vector> board = {{0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0}}; 70 | 71 | Solution solver; 72 | solver.gameOfLife(board); 73 | 74 | for (auto row: board) { 75 | for (auto elem: row) { 76 | cout << elem << " "; 77 | } 78 | cout << endl; 79 | } 80 | return 0; 81 | } -------------------------------------------------------------------------------- /Gas Station/README.md: -------------------------------------------------------------------------------- 1 | # Gas Station 2 | [Try the problem](https://leetcode.com/problems/gas-station/) 3 | 4 | There are `N` gas stations along a circular route, where the amount of gas at station `i` is `gas[i]`. 5 | 6 | You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. 7 | 8 | Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return `-1`. 9 | 10 | ### Example: 11 | ``` 12 | Input: 13 | gas = [1, 2, 3, 4, 5] 14 | cost = [3, 4, 5, 1, 2] 15 | 16 | Output: 3 17 | 18 | Explanation: 19 | Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 20 | Travel to station 4. Your tank = 4 - 1 + 5 = 8 21 | Travel to station 0. Your tank = 8 - 2 + 1 = 7 22 | Travel to station 1. Your tank = 7 - 3 + 2 = 6 23 | Travel to station 2. Your tank = 6 - 4 + 3 = 5 24 | Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. 25 | Therefore, return 3 as the starting index. 26 | ``` -------------------------------------------------------------------------------- /Gas Station/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | class Solution { 7 | public: 8 | int canCompleteCircuit(vector& gas, vector& cost) { 9 | int n = gas.size(); 10 | vector diff(n); 11 | for (int i = 0; i < n; ++i) { 12 | diff[i] = gas[i] - cost[i]; 13 | } 14 | 15 | int res = -1; 16 | int curPos = 0; 17 | int curSum = 0; 18 | int i = 0; 19 | 20 | bool traversed = false; 21 | while (!traversed) { 22 | curPos = i; 23 | bool cnt = true; 24 | bool possible = true; 25 | // while either the first element starting from curPos 26 | // or not come back to it as end position 27 | while (cnt || curPos != i) { 28 | // first position 29 | if (cnt) { 30 | cnt = !cnt; // set cnt to false 31 | curSum = diff[curPos]; 32 | } else { 33 | curSum += diff[curPos]; 34 | } 35 | // if reach negative fuel, break 36 | if (curSum < 0) { 37 | curSum = 0; 38 | possible = false; 39 | break; 40 | } 41 | curPos = (curPos + 1) % n; 42 | // hit 0 atleast once, set traversed to true 43 | if (curPos == 0) { 44 | traversed = true; 45 | } 46 | } 47 | if (possible) { 48 | res = i; 49 | break; 50 | } else { 51 | // start from nextPosition in next iteration 52 | i = (curPos + 1) % n; 53 | // if hit 0, set traversed to true 54 | if (i == 0) { 55 | traversed = true; 56 | } 57 | } 58 | } 59 | return res; 60 | } 61 | }; 62 | 63 | int main () { 64 | Solution solver; 65 | vector gas = {5, 3, 2, 4, 2}; 66 | vector cost = {2, 6, 4, 1, 3}; 67 | 68 | cout << solver.canCompleteCircuit(gas, cost) << endl; // 3 69 | 70 | gas = {5, 3, 2, 4, 1}; 71 | cout << solver.canCompleteCircuit(gas, cost) << endl; // -1 72 | 73 | return 0; 74 | } -------------------------------------------------------------------------------- /Gas Station/solution.txt: -------------------------------------------------------------------------------- 1 | The O(N^2) solution is quite obvious. 2 | You can start from each position and try to see if you reach back 3 | or if at any position, the current fuel falls less than 0. 4 | 5 | Now, the thing is do we really need to check for each of the positions. 6 | 7 | Let's say at position x, gas[x] >= cost[x]. 8 | So, the amount saved here = gas[x]-cost[x]. 9 | This gets added when we go to the next station. 10 | So, to go from (x+1) to (x+2), we must have cost[x + 1] fuel. 11 | Fuel we have actually is 'gas[x]-cost[x] + gas[x+1]' 12 | Thus, the condition is 13 | 14 | gas[x] - cost[x] + gas[x+1] >= cost[x+1] 15 | 16 | Rearranging the terms, it becomes 17 | gas[x] + gas[x+1] >= cost[x] + cost[x+1] 18 | 19 | Again, similarly, we will realize that, to go from (x+2) to (x+3): 20 | gas[x] + gas[x+1] + gas[x+2] >= cost[x] + cost[x+1] + cost[x+2] 21 | 22 | So, if at any point 'i', the sum of gas[x] from starting postion(x=start) to current position(x=i) 23 | drops below sum of cost[x] from starting to that position, we cannot proceed further. 24 | 25 | Now, does that also mean, we need not check for positions in between start and i? 26 | YES, because, 27 | 28 | gas[start] + gas[start+1] + ... + gas[i] < cost[start] + cost[start+1] + ... + cost[i] 29 | => gas[start+1] + ... + gas[i] < cost[start+1] + ... + cost[i] + (cost[start] - gas[start]) 30 | 31 | And, since we started at the 'start' position, thus: 32 | gas[start] >= cost[start] 33 | => cost[start] - gas[start] <= 0 34 | 35 | Thus, removing this quantity in RHS, doesn't change the inequality, leading to: 36 | gas[start+1] + ... + gas[i] < cost[start + 1] + ... cost[i] 37 | 38 | Similarly, we can show it for all positions from (start+1) till 'i'. 39 | 40 | Hence, we only need to check for some positions in the array. 41 | But, is it now O(N)? 42 | 43 | So, if you came from index 0 to index (n - 2), now, you need not see any position in between, 44 | so, when at index (n - 1), if you find it, then that's it, otherwise it's not possible, 45 | since any ways, you will be reusing some index from 0 onwards as start. 46 | 47 | Similarly, even if you go from small jumps from index 0 to say index 2, then to 4, etc. 48 | So, you are only doing O(N) computation, and at the end if you have traversed through index 0 49 | having some index as start, then you can stop after that iteration itself. 50 | 51 | Hence, it is O(N), do thing about it and try to convince yourself or maybe find a counter-example!! -------------------------------------------------------------------------------- /Get Set Queries/README.md: -------------------------------------------------------------------------------- 1 | # Answer a Query 2 | 3 | ## Problem 4 | Imagine a length-N array of booleans, initially all false. Over time, some values are set to true, and at various points in time you would like to find the location of the nearest true to the right of given indices. 5 | You will receive Q queries, each of which has a type and a value. SET queries have type = 1 and GET queries have type = 2. 6 | When you receive a SET query, the value of the query denotes an index in the array that is set to true. Note that these indices start at 1. When you receive a GET query, you must return the smallest index that contains a true value that is greater than or equal to the given index, or -1 if no such index exists. 7 | 8 | ## Signature 9 | int[] answerQueries(ArrayList queries, int N) 10 | 11 | ## Input 12 | A list of Q queries, formatted as [type, index] where type is either 1 or 2, and index is <= N 13 | 1 <= N <= 1,000,000,000 14 | 1 <= Q <= 500,000 15 | 16 | ## Output 17 | Return an array containing the results of all GET queries. The result of queries[i] is the smallest index that contains a true value that is greater than or equal to i, or -1 if no index satisfies those conditions. 18 | 19 | ## Example 20 | N = 5 21 | Q = 5 22 | queries = `[[2, 3], [1, 2], [2, 1], [2, 3], [2, 2]]` 23 | output = `[-1, 2, -1, 2]` 24 | The initial state of the array is `[false, false, false, false, false]`. 25 | The first query is GET 3, but no values in the array are true, so the answer is -1. 26 | The second query is SET 2, so the value at index 2 is set to true. 27 | The new state of the array is `[false, true, false, false, false]`. 28 | The third query is GET 1, and the index of the true value nearest to 1 (to the right) is 2. 29 | The fourth query is GET 3, but no values to the right of index 3 are true. 30 | The fifth query is GET 2, and the value at index 2 is true. -------------------------------------------------------------------------------- /Get Set Queries/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int findUpperBound(set& numbers, int index) { 6 | set::iterator it = lower_bound(numbers.begin(), numbers.end(), index); 7 | if (it == numbers.end()) { 8 | return -1; 9 | } 10 | return *it; 11 | } 12 | 13 | int customLowerBound(set& numbers, int target) { 14 | set:: iterator left = numbers.begin(); 15 | set:: iterator right = numbers.end(); 16 | 17 | while (left != right) { 18 | set::iterator mid = left; 19 | advance(mid, distance(left, right) / 2); 20 | 21 | if (*mid < target) { 22 | left = ++mid; 23 | } else { 24 | right = mid; 25 | } 26 | } 27 | 28 | if (left == numbers.end()) { 29 | return -1; 30 | } 31 | 32 | return *left; 33 | } 34 | 35 | vector answerQueries(vector> queries, int N) { 36 | 37 | set visited; 38 | int q = queries.size(); 39 | 40 | vector res; 41 | for (int i = 0; i < q; ++i) { 42 | int type = queries[i][0]; 43 | int index = queries[i][1]; 44 | 45 | if (type == 2) { 46 | // get - search for upper bound of this index <= N in the visited 47 | // int upperIndex = findUpperBound(visited, index); 48 | int upperIndex = customLowerBound(visited, index); 49 | res.push_back(upperIndex); 50 | } else { 51 | // set 52 | visited.insert(index); 53 | } 54 | } 55 | 56 | return res; 57 | } 58 | 59 | int main () { 60 | vector> queries = {{2, 3}, {1, 2}, {2, 1}, {2, 3}, {2, 2}}; 61 | 62 | vector res = answerQueries(queries, 5); 63 | 64 | for (int i = 0; i < res.size(); ++i) { 65 | cout << res[i] << " "; 66 | } 67 | cout << endl; 68 | } -------------------------------------------------------------------------------- /Get Set Queries/solution.txt: -------------------------------------------------------------------------------- 1 | The brute force approach is: 2 | 1. Use a boolean array of size N to represent the state 3 | 2. For SET queries (type 1): 4 | - Set array[index] = true 5 | 3. For GET queries (type 2): 6 | - Iterate from the given index to N 7 | - Return the first index where array[i] is true 8 | - If no true found, return -1 9 | 10 | Time Complexity: 11 | - SET: O(1) 12 | - GET: O(N) in worst case 13 | - Overall: O(Q*N) where Q is number of queries 14 | Space Complexity: O(N) for the boolean array 15 | 16 | The optimized approach is: 17 | 1. Use a Set data structure to store only the indices that are set to true 18 | 2. For SET queries (type 1): 19 | - Insert the index into the set 20 | 3. For GET queries (type 2): 21 | - Use binary search (lower_bound) to find the smallest number in the set that is >= index 22 | - If no such number exists, return -1 23 | 24 | Key Insights: 25 | - Instead of maintaining the entire boolean array, we only track "true" positions 26 | - Binary search allows us to efficiently find the next true value 27 | - Set automatically maintains sorted order of elements 28 | 29 | Time Complexity: 30 | - SET: O(log K) where K is current size of set 31 | - GET: O(log K) using binary search 32 | - Overall: O(Q * log K) where K ≤ Q 33 | Space Complexity: O(K) where K is number of SET operations 34 | 35 | Implementation Details: 36 | 1. We can use C++'s set container which: 37 | - Maintains sorted order 38 | - Provides efficient insertion O(log n) 39 | - Has built-in lower_bound function 40 | 2. Custom binary search implementation also works and might be good to show in interviews 41 | 3. Edge cases to handle: 42 | - Empty set 43 | - No valid answer (return -1) 44 | - Index at boundaries 45 | 46 | Interview Tips: 47 | 1. Start with brute force to show problem understanding 48 | 2. Identify inefficiency (linear scan in GET queries) 49 | 3. Propose optimization using binary search 50 | 4. Discuss trade-offs (space vs time) 51 | 5. Mention alternative data structures (e.g., TreeSet in Java) -------------------------------------------------------------------------------- /Island Count/README.md: -------------------------------------------------------------------------------- 1 | # Count the number of islands 2 | [Try the problem](https://leetcode.com/problems/number-of-islands/) 3 | 4 | Given a 2D array `binaryMatrix` of 0s and 1s, implement a function `getNumberOfIslands` that returns the number of islands of 1s in `binaryMatrix`. 5 | 6 | An island is defined as a group of adjacent values that are all 1s. A cell in `binaryMatrix` is considered adjacent to another cell if they are next to each either on the same row or column. Note that two values of 1 are **not** part of the same island if they’re sharing only a mutual “corner” (i.e. they are diagonally neighbors). 7 | 8 | Explain and code the most efficient solution possible and analyze its time and space complexities. 9 | 10 | ### Example: 11 | ``` 12 | input: binaryMatrix = [ [0, 1, 0, 1, 0], 13 | [0, 0, 1, 1, 1], 14 | [1, 0, 0, 1, 0], 15 | [0, 1, 1, 0, 0], 16 | [1, 0, 1, 0, 1] ] 17 | 18 | output: 6 # since this is the number of islands in binaryMatrix. 19 | # See all 6 islands color-coded below. 20 | ``` 21 | 22 | ![exampleImage](example.png) -------------------------------------------------------------------------------- /Island Count/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahilbansal17/Coding-Interview-Problems/7f30d64c5aba2c3aef92b0efb76ffbec92c61dd3/Island Count/example.png -------------------------------------------------------------------------------- /Island Count/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int dRow[4] = {-1, 0, 0, +1}; 9 | int dCol[4] = {0, +1, -1, 0}; 10 | 11 | /* 12 | C2 13 | C1 C3 C4 14 | C5 15 | */ 16 | 17 | bool isSafe(int row, int col, int R, int C) { 18 | if (row < 0 || row >= R || col < 0 || col >= C) { 19 | return false; 20 | } 21 | return true; 22 | } 23 | 24 | void bfs(int cr, int cc, const vector>& binaryMatrix, 25 | vector> &visited) { 26 | queue> q; 27 | q.push({cr, cc}); 28 | int R = binaryMatrix.size(); 29 | int C = binaryMatrix[0].size(); 30 | while (!q.empty()) { 31 | // pop from the queue to get front cell 32 | int curRow = q.front().first; 33 | int curCol = q.front().second; 34 | visited[curRow][curCol] = true; 35 | q.pop(); 36 | 37 | for (int k = 0; k < 4; ++k) { 38 | int nextRow = curRow + dRow[k]; 39 | int nextCol = curCol + dCol[k]; 40 | if (isSafe(nextRow, nextCol, R, C)) { 41 | bool shouldVisit = !visited[nextRow][nextCol] && 42 | (binaryMatrix[nextRow][nextCol] == 1); 43 | if (shouldVisit) { 44 | q.push({nextRow, nextCol}); 45 | } 46 | } 47 | } 48 | } 49 | } 50 | 51 | int getNumberOfIslands( const vector>& binaryMatrix ) 52 | { 53 | int countOfIslands = 0; 54 | 55 | int rows = binaryMatrix.size(); 56 | int cols = binaryMatrix[0].size(); 57 | vector> visited(rows, vector(cols, false)); 58 | 59 | for (int curRow = 0; curRow < rows; ++curRow) { 60 | for (int curCol = 0; curCol < cols; ++curCol) { 61 | // check if not visited and equal to 1 62 | bool shouldVisit = !visited[curRow][curCol] && (binaryMatrix[curRow][curCol] == 1); 63 | if (shouldVisit) { 64 | bfs(curRow, curCol, binaryMatrix, visited); 65 | ++countOfIslands; 66 | } 67 | } 68 | } 69 | return countOfIslands; 70 | } 71 | 72 | int main() { 73 | 74 | vector> matrix = {{1, 1, 1, 1, 0}}; 75 | 76 | cout << getNumberOfIslands(matrix) << endl; 77 | return 0; 78 | 79 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Linked List/Cycle Detection/README.md: -------------------------------------------------------------------------------- 1 | # Linked List Cycle 2 | [Try the problem](https://leetcode.com/problems/linked-list-cycle/) 3 | 4 | Given a linked list, determine if it has a cycle in it. 5 | 6 | To represent a cycle in the given linked list, we use an integer `pos` which represents the position (0-indexed) in the linked list where tail connects to. If `pos` is `-1`, then there is no cycle in the linked list. 7 | 8 | ### Example 9 | 10 | ``` 11 | Input: head = [3,2,0,-4], pos = 1 12 | Output: true 13 | Explanation: There is a cycle in the linked list, where tail connects to the second node. 14 | ``` 15 | ![linked_list_1](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png) -------------------------------------------------------------------------------- /Linked List/Cycle Detection/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct ListNode { 6 | int val; 7 | ListNode* next; 8 | ListNode(int x): val(x), next(NULL) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | bool hasCycle(ListNode *head) { 14 | unordered_set seen; 15 | bool done = false; 16 | while (head) { 17 | if (seen.find(head) != seen.end()) { 18 | return true; 19 | } 20 | seen.insert(head); 21 | head = head->next; 22 | } 23 | return false; 24 | } 25 | void printList(ListNode* head) { 26 | while (head) { 27 | cout << head->val << " "; 28 | head = head->next; 29 | } 30 | cout << endl; 31 | } 32 | }; 33 | 34 | int main () { 35 | ListNode* head = new ListNode(3); 36 | head->next = new ListNode(2); 37 | head->next->next = new ListNode(0); 38 | head->next->next->next = new ListNode(-4); 39 | head->next->next->next->next = head->next; 40 | 41 | Solution solver; 42 | if (solver.hasCycle(head->next)) { 43 | cout << "The list has cycle." << endl; 44 | } else { 45 | cout << "The list does not have a cycle!" << endl; 46 | } 47 | } -------------------------------------------------------------------------------- /Linked List/Delete Node/README.md: -------------------------------------------------------------------------------- 1 | # Delete Node in a linked list 2 | [Try the problem](https://leetcode.com/problems/delete-node-in-a-linked-list/) 3 | 4 | Delete a node from a singly-linked list, given only a variable pointing to that node. 5 | 6 | ### Example 1 7 | 8 | ``` 9 | Input: head = [4,5,1,9], node = 5 10 | Output: [4,1,9] 11 | Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. 12 | ``` 13 | 14 | ### Example 2 15 | 16 | ``` 17 | Input: head = [4,5,1,9], node = 1 18 | Output: [4,5,9] 19 | Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. 20 | ``` -------------------------------------------------------------------------------- /Linked List/Delete Node/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct ListNode { 5 | int val; 6 | ListNode* next; 7 | ListNode(int x): val(x), next(NULL) {} 8 | }; 9 | 10 | class Solution { 11 | public: 12 | void deleteNode(ListNode* node) { 13 | ListNode* nextNode = node->next; 14 | node->val = nextNode->val; 15 | node->next = nextNode->next; 16 | delete(nextNode); 17 | } 18 | void printList(ListNode* head) { 19 | while (head) { 20 | cout << head->val << " "; 21 | head = head->next; 22 | } 23 | cout << endl; 24 | } 25 | }; 26 | 27 | int main () { 28 | ListNode* head = new ListNode(5); 29 | head->next = new ListNode(4); 30 | head->next->next = new ListNode(6); 31 | Solution solver; 32 | solver.deleteNode(head->next); 33 | solver.printList(head); // 5 6 34 | } -------------------------------------------------------------------------------- /Linked List/Delete Node/solution.txt: -------------------------------------------------------------------------------- 1 | This question is a little tricky one. 2 | 3 | You might get the idea at first glance and might not. 4 | You need to delete a particular node in a linked list not knowing the head of the list. 5 | You only know the pointer to that node which is to be deleted. 6 | 7 | I am referring the current node as the node to be deleted in the further discussion. 8 | 9 | So, there is no way to access its previous node and thus, the normal delete cannot be performed, 10 | where you could have just shifted the next node of the previous node to the current node's next node. 11 | 12 | The solution is little tricky. 13 | You copy the value of the next node in the current node, and delete the current node's next node. 14 | So, in a way you get the resulting list as what you might have expected. 15 | 16 | But, be careful. In this process, 17 | You cannot delete a node if it is the last node of the linked list. 18 | Because, in this case, the previous node will still point to some node which should now be NULL. 19 | 20 | Also, there are some side-effects possible, 21 | if some other node in our code points to the input node, that will now effectively 22 | have it's next node's value. 23 | 24 | And, if there are pointers to the input node's original next node, those pointers now 25 | point to a "dangling" node. -------------------------------------------------------------------------------- /Linked List/Remove Zero Sum Consecutive Nodes/README.md: -------------------------------------------------------------------------------- 1 | # Remove Zero Sum Consecutive Nodes from Linked List 2 | [Try the problem](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/) 3 | 4 | Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. 5 | 6 | After doing so, return the head of the final linked list. You may return any such answer. 7 | 8 | ### Example 1 9 | 10 | ``` 11 | Input: head = [1,2,-3,3,1] 12 | Output: [3,1] 13 | Note: The answer [1,2,1] would also be accepted. 14 | ``` 15 | 16 | ### Example 2 17 | 18 | ``` 19 | Input: head = [1,2,3,-3,4] 20 | Output: [1,2,4] 21 | ``` 22 | 23 | ### Example 3 24 | 25 | ``` 26 | Input: head = [1,2,3,-3,-2] 27 | Output: [1] 28 | ``` -------------------------------------------------------------------------------- /Linked List/Remove Zero Sum Consecutive Nodes/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct ListNode { 6 | int val; 7 | ListNode* next; 8 | ListNode(int x): val(x), next(NULL) {} 9 | }; 10 | 11 | class Solution { 12 | public: 13 | ListNode* removeZeroSumSublists(ListNode* head) { 14 | int curSum = 0; 15 | ListNode* cur = head; 16 | unordered_map seen_sum; 17 | seen_sum[0] = cur; 18 | 19 | while (cur) { 20 | curSum += cur->val; 21 | ListNode* seen_node = NULL; 22 | if (seen_sum.find(curSum) != seen_sum.end()) { 23 | seen_node = seen_sum[curSum]; 24 | } 25 | if (seen_node) { 26 | ListNode* temp; 27 | if (curSum == 0) { 28 | temp = seen_node; 29 | } 30 | else { 31 | temp = seen_node->next; 32 | } 33 | int temp_sum = curSum; 34 | // remove the extra keys from the seen_sum 35 | while (temp != cur) { 36 | temp_sum += temp->val; 37 | seen_sum.erase(temp_sum); 38 | temp = temp->next; 39 | } 40 | } 41 | if (curSum == 0) { 42 | // delete all nodes from first node to cur node 43 | seen_sum[0] = cur->next; 44 | } else if (seen_node) { 45 | // update the next pointer to delete the intermediate nodes 46 | seen_node->next = cur->next; 47 | } else { 48 | seen_sum[curSum] = cur; 49 | } 50 | cur = cur->next; 51 | } 52 | return seen_sum[0]; 53 | } 54 | void printList(ListNode* head) { 55 | while (head) { 56 | cout << head->val << " "; 57 | head = head->next; 58 | } 59 | cout << endl; 60 | } 61 | }; 62 | 63 | int main () { 64 | ListNode* head = new ListNode(1); 65 | ListNode* cur = head; 66 | head->next = new ListNode(2); 67 | cur = cur->next; 68 | cur->next = new ListNode(3); 69 | cur = cur->next; 70 | cur->next = new ListNode(-3); 71 | cur = cur->next; 72 | cur->next = new ListNode(-2); 73 | 74 | Solution solver; 75 | solver.removeZeroSumSublists(head); 76 | solver.printList(head); // 1 77 | } -------------------------------------------------------------------------------- /Linked List/Remove Zero Sum Consecutive Nodes/solution.txt: -------------------------------------------------------------------------------- 1 | To be updated! -------------------------------------------------------------------------------- /Linked List/Shift Linked List/README.md: -------------------------------------------------------------------------------- 1 | # Shift Linked List 2 | [Try the problem](https://www.algoexpert.io/questions/Shift%20Linked%20List) 3 | 4 | Write a function that takes in the head of a Singly Linked List and an integer `k`, shifts the list in place by `k` positions, and returns its new head. 5 | 6 | 7 | Shifting a Linked List means moving its nodes forward or backward and wrapping them around the list where appropriate. For example, shifting a Linked List forward by one position would make its tail become the new head of the linked list. 8 | 9 | 10 | Whether nodes are moved forward or backward is determined by whether `k` is positive or negative. 11 | 12 | Each `LinkedList` node has an integer `value` as well as a `next` node pointing to the next node in the list or to `None` / `null` if it's the tail of the list. 13 | 14 | 15 | ### Example 16 | 17 | #### Sample Input 18 | - head = 0 -> 1 -> 2 -> 3 -> 4 -> 5 19 | - k = 2 20 | 21 | #### Sample Output 22 | 23 | - 4 -> 5 -> 0 -> 1 -> 2 -> 3 -------------------------------------------------------------------------------- /Linked List/Shift Linked List/scratchpad.txt: -------------------------------------------------------------------------------- 1 | Shift a linked list by K positions 2 | K > 0 => shift forward 3 | K < 0 => shift backward 4 | 5 | 1 -> 2 -> 3 6 | shift by K = 1 7 | => 3 -> 1 -> 2 8 | 9 | 1. Break at the partition point i.e. new head 10 | 2. Connect the tail with original head 11 | 3. Replace the head with new head 12 | 13 | n = 5 14 | 15 | i = 0 -> n - k = 5 - 2 = 3 16 | 17 | 0 1 2 18 | 19 | 1 -> 2 -> 3 -> 4 -> 5 20 | k = 2 21 | 22 | 4 -> 5 -> 1 -> 2 -> 3 23 | 24 | /// 25 | 26 | Example Input 27 | 28 | p nh p nh 29 | 0 -> 1 -> 2 -> 3 -> 4 -> 5 30 | 31 | k = 2 32 | 33 | n = 6 -------------------------------------------------------------------------------- /Linked List/Shift Linked List/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class LinkedList { 5 | public: 6 | int value; 7 | LinkedList *next; 8 | 9 | LinkedList(int value) { 10 | this->value = value; 11 | next = nullptr; 12 | } 13 | }; 14 | 15 | LinkedList *shiftLinkedList(LinkedList *head, int k) { 16 | int n = 0; 17 | LinkedList *temp = head; 18 | LinkedList *tail = NULL; 19 | while (temp) { 20 | tail = temp; 21 | temp = temp->next; 22 | ++n; 23 | } 24 | if (n <= 1) { 25 | return head; 26 | } 27 | k = k % n; 28 | if (k < 0) { 29 | k += n; 30 | } 31 | if (k == 0) { 32 | return head; 33 | } 34 | LinkedList *new_head = head; 35 | LinkedList *prev = NULL; 36 | for (int i = 0; i < n - k; ++i) { 37 | prev = new_head; 38 | new_head = new_head->next; 39 | } 40 | prev->next = NULL; 41 | tail->next = head; 42 | 43 | return new_head; 44 | } 45 | 46 | vector linkedListToArray(LinkedList *head) { 47 | vector array{}; 48 | auto current = head; 49 | while (current != nullptr) { 50 | array.push_back(current->value); 51 | current = current->next; 52 | } 53 | return array; 54 | } 55 | 56 | int main() { 57 | auto head = new LinkedList(0); 58 | head->next = new LinkedList(1); 59 | head->next->next = new LinkedList(2); 60 | head->next->next->next = new LinkedList(3); 61 | head->next->next->next->next = new LinkedList(4); 62 | head->next->next->next->next->next = new LinkedList(5); 63 | auto result = shiftLinkedList(head, 2); 64 | auto array = linkedListToArray(result); 65 | 66 | for (auto e : array) { 67 | cout << e << " "; 68 | } 69 | cout << endl; 70 | 71 | vector expected{4, 5, 0, 1, 2, 3}; 72 | assert(expected == array); 73 | 74 | return 0; 75 | } -------------------------------------------------------------------------------- /Majority Element/README.md: -------------------------------------------------------------------------------- 1 | # Majority Element 2 | [Try the problem](https://leetcode.com/problems/majority-element/) 3 | 4 | Given an array of size `n`, find the majority element. The majority element is the element that appears more than `⌊ n/2 ⌋` times. 5 | 6 | You may assume that the array is non-empty and the majority element always exist in the array. 7 | 8 | ### Example 1 9 | 10 | ``` 11 | Input: [3, 2, 3] 12 | Output: 3 13 | ``` 14 | 15 | ### Example 2 16 | 17 | ``` 18 | Input: [2,2,1,1,1,2,2] 19 | Output: 2 20 | ``` 21 | 22 | -------------------------------------------------------------------------------- /Majority Element/solution.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Program to find the majority element in an array 3 | * using Boyer Moore's voting algorithm: O(N) time and O(1) space 4 | */ 5 | 6 | #include 7 | using namespace std; 8 | 9 | class Solution { 10 | public: 11 | int majorityElement(vector& nums) { 12 | int majorityIdx = 0; 13 | int n = nums.size(); 14 | int curCount = 1; 15 | for (int i = 1; i < n; ++i) { 16 | if (nums[i] != nums[majorityIdx]) { 17 | // decreases the effective count 18 | --curCount; 19 | } else { 20 | ++curCount; 21 | } 22 | if (curCount == 0) { 23 | // count of nums[majorityIdx] equals those not equal to it 24 | majorityIdx = i + 1; 25 | } 26 | } 27 | return nums[majorityIdx]; 28 | } 29 | }; 30 | 31 | /* 32 | // Using O(N) space 33 | 34 | void solve() { 35 | int n; 36 | cin >> n; 37 | vector a(n); 38 | for (int i = 0; i < n; ++i) { 39 | cin >> a[i]; 40 | } 41 | unordered_map count; 42 | int res = -1; 43 | for (auto x: a) { 44 | ++count[x]; 45 | if (count[x] > n/2) { 46 | res = x; 47 | } 48 | } 49 | cout << res << endl; 50 | } 51 | */ 52 | 53 | int main () { 54 | Solution solver; 55 | vector inp = {1, 1, 1, 1, 2, 2}; 56 | cout << solver.majorityElement(inp) << endl; 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Majority Element/solution.txt: -------------------------------------------------------------------------------- 1 | Will be updated! -------------------------------------------------------------------------------- /Maximum Selling Gap/README.md: -------------------------------------------------------------------------------- 1 | # Max Selling Gap 2 | [Try the problem](https://www.interviewbit.com/problems/max-distance/) 3 | 4 | Given an array `A` of integers, find the maximum of `j - i` subjected to the constraint of `A[i] <= A[j]`. 5 | 6 | If there is no solution possible, return `-1`. 7 | 8 | ### Example 1 9 | 10 | ``` 11 | Input: [3,5,4,2] 12 | Output: 2 13 | Explanation: For the pair (3, 4). 14 | ``` 15 | 16 | ### Example 2 17 | ``` 18 | Input: [5,7,1,9,6,3,2] 19 | Output: 4 20 | Explanation: For the pair (1, 2). There could be other answers but they'll have the same maximum gap. 21 | ``` -------------------------------------------------------------------------------- /Maximum Selling Gap/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int maxSellingGap(const vector& price) { 6 | 7 | int num = price.size(); 8 | 9 | vector suffix_max(num); 10 | suffix_max[num - 1] = price[num - 1]; 11 | for (int idx = num - 2; idx >= 0; --idx) { 12 | suffix_max[idx] = max(price[idx], suffix_max[idx + 1]); 13 | } 14 | 15 | int left = 0; 16 | int right = 0; 17 | 18 | int maxGap = 0; 19 | int minPrefix = price[0]; 20 | while (left < num && right < num) { 21 | int elem = price[left]; 22 | // 5 7 1 9 6 3 2 23 | // 5 5 1 1 1 1 1 (minPrefix) 24 | // 9 9 9 9 6 3 2 (suffix_max) 25 | // ^ 26 | 27 | minPrefix = min(minPrefix, elem); 28 | if (minPrefix <= suffix_max[right]) { 29 | maxGap = max(maxGap, right - left); 30 | ++right; 31 | } else { 32 | ++left; 33 | } 34 | } 35 | 36 | return maxGap; 37 | } 38 | 39 | int main () { 40 | vector price = {5,7,1,9,6,3,2}; 41 | cout << maxSellingGap(price) << endl; 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Maximum Selling Gap/solution.md: -------------------------------------------------------------------------------- 1 | # Solution 2 | 3 |
4 | 5 | Hint 1 6 | 7 | The brute force O(N^2) solution is obvious. Try to think if you can use sorting (you might have to also store the index information) to optimize it to O(N log N). 8 |
9 | 10 |
11 | 12 | Hint 2 13 | 14 | Think if you can further reduce the complexity of your algorithm to O(N). You might need extra space. 15 | Given a index i, we basically want to find the maximum index j, such that A[i] <= A[j]. 16 | So, does storing the suffixMax (i.e. maximum starting from a given index till the end) help? 17 | 18 | At an index, if the suffixMax at next index is greater than it, definitely we can get a possible value from here. How to get the maximum one? 19 |
20 | 21 |
22 | 23 | Hint 3 24 | 25 | Now, also think if storing or calculating (while iterating) the prefixMin can help in some way! 26 |
-------------------------------------------------------------------------------- /Minimize The Absolute Difference/README.md: -------------------------------------------------------------------------------- 1 | # Minimize The Absolute Difference 2 | [Try the problem](https://www.interviewbit.com/problems/minimize-the-absolute-difference/) 3 | 4 | Given three sorted arrays A, B and C of not necessarily same sizes. 5 | 6 | Calculate the **minimum absolute difference* between the maximum and minimum number from the triplet (a, b, c) such that a, b, c belong to the arrays A, B and C respectively, i.e. 7 | minimize |max(a, b, c) - min(a, b, c)| for all possible triplets. 8 | 9 | ### Example 10 | 11 | ``` 12 | Input: 13 | A : [ 1, 4, 5, 8, 10 ] 14 | B : [ 6, 9, 15 ] 15 | C : [ 2, 3, 6, 6 ] 16 | 17 | Output: 18 | 1 19 | 20 | We get the minimum difference for a=5, b=6, c=6 as | max(a,b,c) - min(a,b,c) | = |6-5| = 1. 21 | ``` -------------------------------------------------------------------------------- /Minimize The Absolute Difference/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | int solve(vector &A, vector &B, vector &C); 8 | }; 9 | 10 | int Solution::solve(vector &A, vector &B, vector &C) { 11 | int n1 = A.size(); 12 | int n2 = B.size(); 13 | int n3 = C.size(); 14 | int i = 0, j = 0, k = 0; 15 | int res = INT_MAX; 16 | while (i < n1 && j < n2 && k < n3) { 17 | int mini = A[i], maxi = A[i]; 18 | if (B[j] < mini) { 19 | mini = B[j]; 20 | } 21 | if (B[j] > maxi) { 22 | maxi = B[j]; 23 | } 24 | if (C[k] < mini) { 25 | mini = C[k]; 26 | } 27 | if (C[k] > maxi) { 28 | maxi = C[k]; 29 | } 30 | res = min(res, maxi - mini); 31 | if (A[i] == mini) { 32 | ++i; 33 | } else if (B[j] == mini) { 34 | ++j; 35 | } else { 36 | ++k; 37 | } 38 | } 39 | return res; 40 | } 41 | 42 | int main() { 43 | vector A = {1, 2, 3, 4, 5}; 44 | vector B = {6, 7, 8, 9, 10}; 45 | vector C = {11, 12, 13, 14, 15}; 46 | Solution solver; 47 | cout << solver.solve(A, B, C) << endl; // 6 because (5, 6, 11) is the triplet 48 | } -------------------------------------------------------------------------------- /Minimize The Absolute Difference/solution.txt: -------------------------------------------------------------------------------- 1 | The brute force solution obviously is quite costly, i.e. O(N^3). 2 | 3 | Since the arrays are already sorted, thus there has to be a better algorithm. 4 | 5 | We start with the first element of each of the arrays as the first possible triplet. 6 | Now, we need to get to the triplet that minimizes the difference between maximum and minimum element in it. 7 | 8 | So, one way is to increase the minimum element in the triplet. So, move to the next element of the array 9 | whose current element is the minimum of the triplet, i.e. 10 | we have 3 pointers each pointing to the current element of the arrays, initially to 0th index of each. 11 | 12 | Now, we move the pointer to the right of the array having minimum element in the current triplet. 13 | We keep recalculating the required value for the current triplet and update if better than the minimum value. 14 | 15 | So, we keep doing so, until one of the array is exhausted, i.e. any of the 3 pointers has moved to the end of its array. 16 | 17 | This greedy solution will work intuitely but giving a proof could be little tricky! -------------------------------------------------------------------------------- /Minimum Falling Path Sum/README.md: -------------------------------------------------------------------------------- 1 | # Minimum Falling Path Sum 2 | [Try the problem](https://leetcode.com/problems/minimum-falling-path-sum/) 3 | 4 | Given a matrix of integers, we want to find the **minimum** sum of *falling path* through it. 5 | 6 | A falling path starts at any element in the first row, and chooses one element from each row. 7 |
8 | The next row's choice must be in a column that is different from the previous row's column by atmost one. 9 | 10 | ### Example 11 | 12 | ``` 13 | Input: [[1,2,3],[4,5,6],[7,8,9]] 14 | Output: 12 15 | Explanation: 16 | The possible falling paths are: 17 | ``` 18 | 19 | - `[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]` 20 | - `[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]` 21 | - `[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]` 22 | 23 | The falling path with the smallest sum is `[1,4,7]`, so the answer is `12`. -------------------------------------------------------------------------------- /Minimum Falling Path Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | class Solution { 6 | public: 7 | int minFallingPathSum(vector > &A) { 8 | int rows = A.size(); // 3 9 | int cols = A[0].size(); // 3 10 | vector > minSum(rows, vector (cols, 0)); // 3*3 with all 0's 11 | // set for first row 12 | for (int curCol = 0; curCol = 0 && prevCol < cols) { 23 | curMinSum = min(curMinSum, minSum[prevRow][prevCol]); 24 | } 25 | } 26 | // curMinSum is 1 for the cell valued 4, i.e. (1, 0) 27 | minSum[curRow][curCol] = A[curRow][curCol] + curMinSum; 28 | // minSum[1][0] = 4 + 1 = 5 29 | } 30 | } 31 | // minSum at the end = { {1, 2, 3}, {5, 6, 8}, {12, 13, 15} } 32 | // result is the minimum value in the last row 33 | int res = INT_MAX; 34 | for (int curCol = 0; curCol < cols; ++curCol) { 35 | res = min(res, minSum[rows - 1][curCol]); 36 | } 37 | return res; // 12 38 | } 39 | }; 40 | 41 | int main () { 42 | Solution solver; 43 | vector > A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; 44 | cout << solver.minFallingPathSum(A) << endl; 45 | } -------------------------------------------------------------------------------- /Minimum Falling Path Sum/solution.txt: -------------------------------------------------------------------------------- 1 | Initially, thinking of trying all possibilities as a naive and brute force solution to start with. 2 | 3 | Trying to realize its complexity, thinking it around O(N*3^(N-1)) as can start with any 4 | element in the first row and then for any element can go to around 3 other elements in the 5 | next row. 6 | 7 | Trying to think how to optimize this approach, the observation is once we are at a particular 8 | element in a row, the only think that matters now is the element in the next row, the path to 9 | reach that element doesn't really matter. 10 | 11 | So, its kind of an overlapping subproblem since we can reach that point from atmost 3 points above 12 | that element, but need to now solve the same problem. 13 | 14 | Also, another observation is that we are ultimately going to end at the last row, in some column. 15 | So, if we can consider minSum[i][j] denoting the minimum sum to reach the element (i, j) 16 | following the conditions given, then our answer is simply the minimum of all the values 17 | minSum[i][j] in the last row, i.e. i = Index of last row, j ranging from 0 to last column index. 18 | 19 | The recurrence is now kind of obvious. 20 | We can relate minSum[i][j] to minSum[i - 1][j - 1], minSum[i - 1][j] and minSum[i - 1][j + 1], 21 | handling the corner/boundary cases and implementing it in a space efficient way, since 22 | at any point of time we require no longer than 2 row values. 23 | 24 | -------------------------------------------------------------------------------- /Populating Next Right Pointers/README.md: -------------------------------------------------------------------------------- 1 | # Binary Search Tree Checker 2 | [Try the problem](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) 3 | 4 | You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: 5 | 6 | ``` 7 | struct Node { 8 | int val; 9 | Node *left; 10 | Node *right; 11 | Node *next; 12 | } 13 | ``` 14 | 15 | Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. 16 | Initially, all next pointers are set to NULL. 17 | 18 | ### Example 19 | ![Example 1](https://assets.leetcode.com/uploads/2019/02/14/116_sample.png) 20 | 21 | Input: root = [1,2,3,4,5,6,7] 22 | Output: [1,#,2,3,#,4,5,6,7,#] 23 | Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. -------------------------------------------------------------------------------- /Populating Next Right Pointers/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | class Node { 7 | public: 8 | int val; 9 | Node* left; 10 | Node* right; 11 | Node* next; 12 | 13 | Node() : val(0), left(NULL), right(NULL), next(NULL) {} 14 | 15 | Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} 16 | 17 | Node(int _val, Node* _left, Node* _right, Node* _next) 18 | : val(_val), left(_left), right(_right), next(_next) {} 19 | }; 20 | 21 | class Solution { 22 | public: 23 | Node* connect(Node* root) { 24 | if (!root) { 25 | return root; 26 | } 27 | queue > q; 28 | q.push({root, 0}); 29 | int prevLevel = 0; 30 | Node* prevNode = NULL; 31 | while (!q.empty()) { 32 | auto front = q.front(); 33 | auto node = front.first; 34 | auto level = front.second; 35 | q.pop(); 36 | if (prevLevel != level) { 37 | prevNode->next = NULL; 38 | prevLevel = level; 39 | prevNode = node; 40 | } else { 41 | if (prevNode) { 42 | prevNode->next = node; 43 | } 44 | prevNode = node; 45 | } 46 | if (node->left) { 47 | q.push({node->left, level + 1}); 48 | } 49 | if (node->right) { 50 | q.push({node->right, level + 1}); 51 | } 52 | } 53 | return root; 54 | } 55 | }; 56 | 57 | int main () { 58 | Node* root = new Node(1); 59 | root->left = new Node(2); 60 | root->right = new Node(3); 61 | root->left->left = new Node(4); 62 | root->left->right = new Node(5); 63 | root->right->left = new Node(6); 64 | root->right->right = new Node(7); 65 | 66 | Solution solver; 67 | root = solver.connect(root); 68 | 69 | Node* cur = root; 70 | while (cur) { 71 | Node* temp = cur; 72 | while (temp) { 73 | cout << temp->val << " " ; 74 | temp = temp->next; 75 | } 76 | cout << endl; 77 | cur = cur->left; 78 | } 79 | /* 80 | Output: 81 | 1 82 | 2 3 83 | 4 5 6 7 84 | */ 85 | 86 | return 0; 87 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Coding-Interview-Problems 2 | This repository contains the coding interview problems along with solutions. 3 | 4 | | Problem | Solution | Code | Category | Difficulty | 5 | |---------------|----------|------|----------|------------| 6 | | [Island Count](Island%20Count) | | [CPP](Island%20Count/solution.cpp) | Graph Traversal | Medium | 7 | | [Minimum Falling Path Sum](Minimum%20Falling%20Path%20Sum) | [text](Minimum%20Falling%20Path%20Sum/solution.txt) | [CPP](Minimum%20Falling%20Path%20Sum/solution.cpp) | Dynamic Programming | Medium | 8 | | [Word Break](Word%20Break) | [text](Word%20Break/solution.txt) | [CPP](Word%20Break/solution.cpp) | Dynamic Programming | Medium | 9 | | [Remove K Digits](Remove%20K%20Digits) | [text](Remove%20K%20Digits/solution.txt) | [CPP](Remove%20K%20Digits/solution.cpp) | Greedy, Stack | Medium | 10 | | [Binary Search Tree Checker](BST%20Checker) | To be updated | [CPP](BST%20Checker/solution.cpp) | Trees | Medium | 11 | | [Delete node in singly-linked list](Linked%20List/Delete%20Node/) | [text](Linked%20List/Delete%20Node/solution.txt) | [CPP](Linked%20List/Delete%20Node/solution.cpp) | Linked-List | Easy, Tricky | 12 | | [Minimize The Absolute Difference](Minimize%20The%20Absolute%20Difference/) | [text](Minimize%20The%20Absolute%20Difference/solution.txt) | [CPP](Minimize%20The%20Absolute%20Difference/solution.cpp) | Two Pointers | Easy | 13 | | [Majority Element](Majority%20Element/) | [text](Majority%20Element/solution.txt) | [CPP](Majority%20Element/solution.cpp) | Hashing, Trick | Easy, Tricky | 14 | | [Count Numbers Less Than K](Count%20Numbers%20Less%20Than%20K/) | [text](Count%20Numbers%20Less%20Than%20K/solution.txt) | [CPP](Count%20Numbers%20Less%20Than%20K/solution.cpp) | Mathematics | Easy-Medium | 15 | | [Remove Zero Sum Consecutive Nodes](Linked%20List/Remove%20Zero%20Sum%20Consecutive%20Nodes/) | [text](Linked%20List/Remove%20Zero%20Sum%20Consecutive%20Nodes/solution.txt) | [CPP](Linked%20List/Remove%20Zero%20Sum%20Consecutive%20Nodes/solution.cpp) | Linked Lists | Medium | 16 | | [Ways To Form Max Heap](Ways%20To%20Form%20Max%20Heap/) | [text](Ways%20To%20Form%20Max%20Heap/solution.txt) | [CPP](Ways%20To%20Form%20Max%20Heap/solution.cpp) | Heap, Mathematics | Medium-Hard | 17 | | [Find K Closest Elements](Find%20K%20Closest%20Elements/) | text | [CPP](Find%20K%20Closest%20Elements/solution.cpp) | MISC | Easy | 18 | | [Populating Next Right Pointers](Populating%20Next%20Right%20Pointers/) | text | [CPP](Populating%20Next%20Right%20Pointers/solution.cpp) | Trees | Medium | 19 | | [Gas Station](Gas%20Station/) | [text](Gas%20Station/solution.txt) | [CPP](Gas%20Station/solution.cpp) | Greedy Algorithm | Medium | 20 | | [Set Matrix Zeroes](Set%20Matrix%20Zeroes/) | [text](Set%20Matrix%20Zeroes/solution.txt) | [CPP](Set%20Matrix%20Zeroes/solution_constant_space.cpp) | Matrix Manipulation | Easy, Tricky | 21 | | [Diameter of Generic Tree](Diameter%20of%20Generic%20Tree) | text | [CPP](Diameter%20of%20Generic%20Tree/solution.cpp) | Trees, Graphs | Medium | 22 | | [2 Keys Keyboard](2%20Keys%20Keyboard) | [text](2%20Keys%20Keyboard/solution.txt) | [CPP](2%20Keys%20Keyboard/solution.cpp) | DP, Maths | Medium | 23 | | [Very Hard Queries](Very%20Hard%20Queries) | [Solution article](Very%20Hard%20Queries/solution.md) | [CPP](Very%20Hard%20Queries/solution.cpp) | Queries, Maths | Medium | 24 | | [Deterministic Finite Automaton](Deterministic%20Finite%20Automaton/) | [Solution article](Deterministic%20Finite%20Automaton/solution.md) | [CPP](Deterministic%20Finite%20Automaton/solution.cpp) | Recursion, Dynamic Programming | Medium | 25 | | [Maximum Selling Gap](Maximum%20Selling%20Gap) | [Solution article](Maximum%20Selling%20Gap/solution.md) | [CPP](Maximum%20Selling%20Gap/solution.cpp) | Arrays | Medium | 26 | | [Game of Life](Game%20of%20Life) | - | [CPP](Game%20of%20Life/solution.cpp) | Arrays | Medium | 27 | | [3 Sum](3%20Sum) | [Article](3%20Sum/README.md) | [CPP](3%20Sum/solution.cpp) | Two Pointers | Medium | 28 | | [Shift Linked List](Linked%20List/Shift%20Linked%20List) | [Scratchpad](Linked%20List/Shift%20Linked%20List/scratchpad.txt) | [CPP](Linked%20List/Shift%20Linked%20List/solution.cpp) | Linked List | Easy, Medium | 29 | | [Unique Paths III](Unique%20Paths%20III) | [Article](https://leetcode.com/problems/unique-paths-iii/solutions/2976056/backtracking-solution-in-c/) | [CPP](Unique%20Paths%20III/solution.cpp) | Backtracking | Medium | 30 | | [Get Set Queries](Get%20Set%20Queries) | - | [CPP](Get%20Set%20Queries/solution.cpp) | Ordered Sets | Medium | 31 | 32 | # CS Fundamentals 33 | 34 | 1. [DBMS Glossary](CS%20Fundamentals/DBMS.txt) 35 | 2. [Object Oriented Programming Glossary](CS%20Fundamentals/OOPs.txt) 36 | -------------------------------------------------------------------------------- /Remove K Digits/README.md: -------------------------------------------------------------------------------- 1 | # Remove K Digits 2 | [Try the problem](https://leetcode.com/problems/remove-k-digits/) 3 | 4 | Given a non-negative integer `num` represented as a string, remove *k* digits from the number so that the new number is the smallest possible. 5 | 6 | **Note**: 7 | - The given `num` does not contain any leading zero. 8 | 9 | ### Example 1 10 | 11 | ``` 12 | Input: num = "1432219", k = 3 13 | Output: "1219" 14 | Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest. 15 | ``` 16 | 17 | ### Example 2 18 | 19 | ``` 20 | Input: num = "10200", k = 1 21 | Output: "200" 22 | Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes. 23 | ``` 24 | 25 | ### Example 3 26 | 27 | ``` 28 | Input: num = "10", k = 2 29 | Output: "0" 30 | Explanation: Remove all the digits from the number and it is left with nothing which is 0. 31 | ``` -------------------------------------------------------------------------------- /Remove K Digits/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | class Solution { 6 | public: 7 | string removeKdigits(string num, int k) { 8 | int n = num.length(); 9 | stack st; 10 | for (int i = 0; i < n; ++i) { 11 | if (st.empty()) { 12 | st.push(num[i]); 13 | } else if (st.top() > num[i] && k > 0) { 14 | while (!st.empty() && st.top() > num[i] && k > 0) { 15 | st.pop(); 16 | --k; 17 | } 18 | st.push(num[i]); 19 | } else { 20 | st.push(num[i]); 21 | } 22 | } 23 | while (!st.empty() && k > 0) { 24 | st.pop(); 25 | --k; 26 | } 27 | string res; 28 | if (st.empty()) { 29 | res = '0'; 30 | } 31 | while (!st.empty()) { 32 | res += st.top(); 33 | st.pop(); 34 | } 35 | reverse(res.begin(), res.end()); 36 | // remove leading zeroes 37 | string finalRes; 38 | int firstIdx = 0; 39 | int finalLen = res.length(); 40 | while (firstIdx < finalLen && res[firstIdx] == '0') { 41 | ++firstIdx; 42 | } 43 | if (firstIdx == finalLen) { 44 | finalRes = '0'; 45 | } else { 46 | while (firstIdx < finalLen) { 47 | finalRes += res[firstIdx]; 48 | ++firstIdx; 49 | } 50 | } 51 | return finalRes; 52 | } 53 | }; 54 | 55 | int main() { 56 | Solution solver; 57 | 58 | cout << solver.removeKdigits("1234567890", 9) << endl; 59 | } -------------------------------------------------------------------------------- /Remove K Digits/solution.txt: -------------------------------------------------------------------------------- 1 | The problem is quite tricky and revolved around the idea of comparing the numbers, 2 | observing some kind of properties, leading to a greedy solution. -------------------------------------------------------------------------------- /Set Matrix Zeroes/README.md: -------------------------------------------------------------------------------- 1 | # Set Metrix Zeroes 2 | [Try the problem](https://leetcode.com/problems/set-matrix-zeroes/) 3 | 4 | Given a `m x n matrix`, if an element is **0**, set its entire row and column to **0**. Do it **in-place**. 5 | 6 | ### Example 1 7 | 8 | ``` 9 | Input: 10 | [ 11 | [1,1,1], 12 | [1,0,1], 13 | [1,1,1] 14 | ] 15 | Output: 16 | [ 17 | [1,0,1], 18 | [0,0,0], 19 | [1,0,1] 20 | ] 21 | ``` 22 | 23 | ### Example 2 24 | 25 | ``` 26 | Input: 27 | [ 28 | [0,1,2,0], 29 | [3,4,5,2], 30 | [1,3,1,5] 31 | ] 32 | Output: 33 | [ 34 | [0,0,0,0], 35 | [0,4,5,0], 36 | [0,3,1,0] 37 | ] 38 | ``` 39 | 40 | Follow up: 41 | - A straight forward solution using O(mn) space is probably a bad idea. 42 | - A simple improvement uses O(m + n) space, but still not the best solution. 43 | - Could you devise a constant space solution? 44 | 45 |
46 | 47 | Hint 1 48 | 49 | If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. 50 |
51 | 52 |
53 | 54 | Hint 2 55 | 56 | Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. 57 |
58 | 59 |
60 | 61 | Hint 3 62 | 63 | We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. 64 |
65 | 66 |
67 | 68 | Hint 4 69 | 70 | We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero. 71 |
-------------------------------------------------------------------------------- /Set Matrix Zeroes/solution.txt: -------------------------------------------------------------------------------- 1 | This video by Errichto will be helpful: 2 | https://www.youtube.com/watch?v=6_KMkeh5kEc -------------------------------------------------------------------------------- /Set Matrix Zeroes/solution_constant_space.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | void setZeroes(vector>& matrix) { 8 | int rows = matrix.size(); 9 | if (rows == 0) { 10 | return; 11 | } 12 | int cols = matrix[0].size(); 13 | 14 | // check if first row contains a zero 15 | bool first_zero = false; 16 | for (int i = 0; i < cols; ++i) { 17 | if (matrix[0][i] == 0) { 18 | first_zero = true; 19 | } 20 | } 21 | 22 | // put zeroes in first row if the column has zero 23 | for (int j = 0; j < cols; ++j) { 24 | for (int i = 0; i < rows; ++i) { 25 | if (matrix[i][j] == 0) { 26 | matrix[0][j] = 0; 27 | } 28 | } 29 | } 30 | 31 | // set zeroes in the matrix 32 | for (int i = 1; i < rows; ++i) { 33 | // check if row has zero 34 | bool row_zero = false; 35 | for (int j = 0; j < cols; ++j) { 36 | if (matrix[i][j] == 0) { 37 | row_zero = true; 38 | } 39 | } 40 | // if row has zero or the first row's particular element has zero 41 | for (int j = 0; j < cols; ++j) { 42 | if (matrix[0][j] == 0 || row_zero) { 43 | matrix[i][j] = 0; 44 | } 45 | } 46 | } 47 | // put zeroes in the first row only if first_zero is true 48 | if (first_zero) { 49 | for (int i = 0; i < cols; ++i) { 50 | matrix[0][i] = 0; 51 | } 52 | } 53 | 54 | } 55 | }; 56 | 57 | int main () { 58 | Solution solver; 59 | vector > matrix = {{0, 1, 2, 0}, 60 | {3, 4, 5, 2}, 61 | {1, 3, 1, 5}}; 62 | solver.setZeroes(matrix); 63 | 64 | for (auto row: matrix) { 65 | for (auto x: row) { 66 | cout << x << " "; 67 | } 68 | cout << endl; 69 | } 70 | return 0; 71 | } -------------------------------------------------------------------------------- /Set Matrix Zeroes/solution_linear_space.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | public: 7 | void setZeroes(vector>& matrix) { 8 | int rows = matrix.size(); 9 | if (rows == 0) { 10 | return; 11 | } 12 | int cols = matrix[0].size(); 13 | 14 | vector row_zero(rows, 0); 15 | vector col_zero(cols, 0); 16 | for (int i = 0; i < rows; ++i) { 17 | for (int j = 0; j < cols; ++j) { 18 | if (matrix[i][j] == 0) { 19 | row_zero[i] = 1; 20 | col_zero[j] = 1; 21 | } 22 | } 23 | } 24 | 25 | for (int i = 0; i < rows; ++i) { 26 | for (int j = 0; j < cols; ++j) { 27 | if (row_zero[i] || col_zero[j]) { 28 | matrix[i][j] = 0; 29 | } 30 | } 31 | } 32 | } 33 | }; 34 | 35 | int main () { 36 | Solution solver; 37 | vector > matrix = {{0, 1, 2, 0}, 38 | {3, 4, 5, 2}, 39 | {1, 3, 1, 5}}; 40 | solver.setZeroes(matrix); 41 | 42 | for (auto row: matrix) { 43 | for (auto x: row) { 44 | cout << x << " "; 45 | } 46 | cout << endl; 47 | } 48 | return 0; 49 | } -------------------------------------------------------------------------------- /Target Sum/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | private: 7 | int numWays[25][2010]; 8 | int solve(int idx, vector& nums, int target) { 9 | if (target > 1000) { 10 | return 0; 11 | } 12 | if (idx == nums.size()) { 13 | if (target == 0) { 14 | return 1; 15 | } 16 | return 0; 17 | } 18 | if (numWays[idx][1000 + target] != -1) { 19 | return numWays[idx][1000 + target]; 20 | } 21 | return numWays[idx][1000 + target] = solve(idx + 1, nums, target - nums[idx]) 22 | + solve(idx + 1, nums, target + nums[idx]); 23 | } 24 | public: 25 | int findTargetSumWays(vector& nums, int S) { 26 | memset(numWays, -1, sizeof(numWays)); 27 | return solve(0, nums, S); 28 | } 29 | }; 30 | 31 | int main () { 32 | 33 | Solution solver; 34 | int N, target; 35 | cin >> N >> target; 36 | vector nums(N); 37 | for (auto &i: nums) { 38 | cin >> i; 39 | } 40 | cout << solver.findTargetSumWays(nums, target) << endl; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Unique Paths III/README.md: -------------------------------------------------------------------------------- 1 | # Unique Paths III 2 | [Try the problem](https://leetcode.com/problems/unique-paths-iii/description/) 3 | 4 | ## Problem Statement 5 | You are given an m x n integer array grid where grid[i][j] could be: 6 | 7 | - 1 representing the starting square. There is exactly one starting square. 8 | - 2 representing the ending square. There is exactly one ending square. 9 | - 0 representing empty squares we can walk over. 10 | - -1 representing obstacles that we cannot walk over. 11 | 12 | Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once. 13 | 14 | ## Examples 15 | 16 | ### Example 1: 17 | 18 | Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,2,-1]] 19 | 20 | Output: 2 21 | 22 | Explanation: We have the following two paths: 23 | 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 24 | 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) 25 | 26 | ### Example 2: 27 | 28 | Input: grid = [[1,0,0,0],[0,0,0,0],[0,0,0,2]] 29 | 30 | Output: 4 31 | 32 | Explanation: We have the following four paths: 33 | 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 34 | 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 35 | 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 36 | 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) 37 | 38 | ### Example 3: 39 | 40 | Input: grid = [[0,1],[2,0]] 41 | 42 | Output: 0 43 | 44 | Explanation: There is no path that walks over every empty square exactly once. 45 | Note that the starting and ending square can be anywhere in the grid. 46 | 47 | 48 | ## Constraints 49 | 50 | - m == grid.length 51 | - n == grid[i].length 52 | - 1 <= m, n <= 20 53 | - 1 <= m * n <= 20 54 | - -1 <= grid[i][j] <= 2 55 | - There is exactly one starting cell and one ending cell. -------------------------------------------------------------------------------- /Unique Paths III/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Solution { 6 | private: 7 | int dx[4] = {-1, 0, 0, +1}; 8 | int dy[4] = {0, -1, +1, 0}; 9 | int res; 10 | 11 | bool allVisited(vector>& grid) { 12 | for (int r = 0; r < grid.size(); ++r) { 13 | for (int c = 0; c < grid[0].size(); ++c) { 14 | if (grid[r][c] == 0) { // unvisited cell 15 | return false; 16 | } 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | 23 | void backtrack(int sx, int sy, int ex, int ey, vector>& grid) { 24 | if (sx == ex && sy == ey) { 25 | // check if all cells are visited 26 | res += allVisited(grid) ? 1 : 0; 27 | } 28 | 29 | for (int k = 0; k < 4; ++k) { 30 | int nx = sx + dx[k]; 31 | int ny = sy + dy[k]; 32 | if (nx >= grid.size() || nx < 0 || ny >= grid[0].size() || ny < 0) { 33 | continue; // safety checking 34 | } 35 | if (grid[nx][ny] == 0 || 36 | grid[nx][ny] == 2) { // only 0 / 2 cell can be visited 37 | grid[nx][ny] = 3; // marking as visited 38 | backtrack(nx, ny, ex, ey, grid); 39 | grid[nx][ny] = 0; // marking as unvisited 40 | } 41 | } 42 | } 43 | 44 | public: 45 | Solution() { res = 0; } 46 | 47 | int uniquePathsIII(vector>& grid) { 48 | int sx = -1, sy = -1, ex = -1, ey = -1; 49 | for (int r = 0; r < grid.size(); ++r) { 50 | for (int c = 0; c < grid[0].size(); ++c) { 51 | if (grid[r][c] == 1) { 52 | sx = r, sy = c; 53 | } else if (grid[r][c] == 2) { 54 | ex = r, ey = c; 55 | } 56 | } 57 | } 58 | 59 | backtrack(sx, sy, ex, ey, grid); 60 | return res; 61 | } 62 | }; 63 | 64 | int main () { 65 | Solution solver; 66 | vector> grid = {{1,0,0,0},{0,0,0,0},{0,0,2,-1}}; 67 | cout << solver.uniquePathsIII(grid) << endl; 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Very Hard Queries/README.md: -------------------------------------------------------------------------------- 1 | # Very Hard Queries 2 | [Try the problem](https://www.interviewbit.com/problems/very-hard-queries/) 3 | 4 | You are given an array A having n integers. 5 | You have to perform some very hard queries on A. 6 | There are 2 types of queries: 7 | - 1 id X, change A[id] with X. 8 | - 2 L R, you have to find the minimum number of steps required to change all elements in [L, R] such that 9 | every element in [L, R] will have the odd number of divisors. In one step you can choose any element from A and can add or subtract 1 from it. 10 | 11 | Note that in the second type of query, the array does not change. 12 | 13 | ### Input Format 14 | 15 | ``` 16 | The 1st argument given is an integer array nums. 17 | The 2nd argument given is a 2D integer array queries, where queries[i] denotes ith query 18 | ``` 19 | 20 | ### Output Format 21 | 22 | ``` 23 | Return an Integer X % (1e9 + 7), the sum of answer for each query of type 2. 24 | ``` 25 | 26 | ### Example 27 | 28 | ``` 29 | Input: 30 | A = [1, 2, 3] 31 | B = [[2, 1, 1], [2, 1, 2], [1, 3, 1], [2, 1, 3]] 32 | Output: 33 | 2 34 | 35 | Explanation: 36 | query 1: we don't need any steps as 1 has an odd number of divisors, so the answer is 0. 37 | query 2: in 1 step we can change 2 to 1, so the answer is 1. 38 | query 3: change value of A[3] with 1, array after the 3rd query is A = [1, 2, 1] 39 | query 4: again in 1 step we can change 2 to 1, so answer is 1. 40 | 41 | So the sum of answers to all queries of type 2 is 2. 42 | ``` 43 | 44 |
45 | 46 | Hint 1 47 | 48 | What is so special about a number having odd number of divisors? Can you use it to find the minimum no. of steps to change a number to get to a number with odd no. of divisors? 49 |
50 | 51 |
52 | 53 | Hint 2 54 | 55 | Does the problem reduce to finding out the sum of values in a given range along with some update queries? 56 | Which data structure can you use here to optimize the brute force solution? 57 |
58 | 59 |
60 | 61 | Hint 3 62 | 63 | Read and learn about segment trees: https://cp-algorithms.com/data_structures/segment_tree.html 64 |
-------------------------------------------------------------------------------- /Very Hard Queries/image_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sahilbansal17/Coding-Interview-Problems/7f30d64c5aba2c3aef92b0efb76ffbec92c61dd3/Very Hard Queries/image_1.png -------------------------------------------------------------------------------- /Very Hard Queries/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | const ll MOD = 1e9 + 7; 6 | 7 | vector st; // segment tree 8 | void build(vector& arr, int v, int tl, int tr) { 9 | if (tl == tr) { 10 | st[v] = arr[tl]; 11 | } else { 12 | int tm = (tl + tr)/2; 13 | build(arr, 2*v, tl, tm); 14 | build(arr, 2*v + 1, tm + 1, tr); 15 | st[v] = st[2*v] + st[2*v + 1]; 16 | } 17 | } 18 | int sum(int v, int tl, int tr, int l, int r) { 19 | if (l > r) { 20 | return 0; 21 | } 22 | if (l == tl && r == tr) { 23 | return st[v]; 24 | } 25 | int tm = (tl + tr)/2; 26 | return sum(2*v, tl, tm, l, min(r, tm)) 27 | + sum(2*v + 1, tm + 1, tr, max(l, tm + 1), r); 28 | } 29 | void update(int v, int tl, int tr, int pos, int new_val) { 30 | if (tl == tr) { 31 | st[v] = new_val; 32 | } else { 33 | int tm = (tl + tr)/2; 34 | if (pos <= tm) { 35 | update(2*v, tl, tm, pos, new_val); 36 | } else { 37 | update(2*v + 1, tm + 1, tr, pos, new_val); 38 | } 39 | st[v] = st[2*v] + st[2*v + 1]; 40 | } 41 | } 42 | int countSteps(int n) { 43 | int root = sqrt(n); 44 | return min(abs(root*root - n), abs((root + 1)*(root + 1) - n)); 45 | } 46 | int solve(vector &nums, vector > &queries) { 47 | int n = nums.size(); 48 | st.assign(4*n, 0); 49 | vector steps(n); 50 | for (int i = 0; i < n; ++i) { 51 | steps[i] = countSteps(nums[i]); 52 | } 53 | build(steps, 1, 0, n - 1); 54 | 55 | ll ans = 0; 56 | for (auto query: queries) { 57 | int type = query[0]; 58 | if (type == 1) { 59 | int id = query[1]; 60 | int x = query[2]; 61 | // zero-based indexing 62 | --id; 63 | update(1, 0, n - 1, id, countSteps(x)); 64 | } else { 65 | int l = query[1]; 66 | int r = query[2]; 67 | // zero-based indexing 68 | --l; 69 | --r; 70 | int res = sum(1, 0, n - 1, l, r); 71 | ans += 1ll*res; 72 | ans %= MOD; 73 | } 74 | } 75 | return ans; 76 | } 77 | 78 | int main () { 79 | vector nums = {1, 2, 3}; 80 | vector> queries = {{2, 1, 1}, {2, 1, 2}, {1, 3, 1}, {2, 1, 3}}; 81 | cout << solve(nums, queries) << endl; 82 | return 0; 83 | } -------------------------------------------------------------------------------- /Very Hard Queries/solution.md: -------------------------------------------------------------------------------- 1 | # Solution 2 | 3 | First of all, which numbers have odd divisors? 4 | 5 | ![Odd Divisors](image_1.png) 6 | 7 | It turns out that only perfect square numbers have an odd count of divisors, like 1, 4, 9 ... 8 | 9 | Now, we need to change a number with minimum steps to turn it into a perfect square number. 10 | So, we can find distance of number from two of its nearest perfect square numbers. Think about it! 11 | 12 | Thus, second query reduces to finding the sum of minimum steps for all elements in [L, R]. 13 | 14 | We can store the steps required for each element in an array named `steps`. 15 | We just need to perform range sum query now. But, there are also update queries. 16 | So, the brute force solution with O(1) update and O(N) query is not optimal. 17 | 18 | We can use segment tree to perform O(log N) update and O(log N) Range Sum Query. -------------------------------------------------------------------------------- /Ways To Form Max Heap/README.md: -------------------------------------------------------------------------------- 1 | # Ways To Form Max Heap 2 | [Try the problem](https://www.interviewbit.com/problems/ways-to-form-max-heap/) 3 | 4 | Max Heap is a special kind of complete binary tree in which for every node, the value present in that node is greater than the value present in it’s children nodes. 5 | 6 | So now the problem statement for this question is: 7 | 8 | How many distinct Max Heaps can be made from `N` distinct integers? 9 | 10 | In short, you have to ensure the following properties for the max heap : 11 | 1. Heap has to be a complete binary tree ( A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. ) 12 | 2. Every node is greater than all its children. 13 | 14 | Let us take an example of 4 distinct integers. Without loss of generality let us take `1 2 3 4` as our 4 distinct integers. 15 | 16 | Following are the possible max heaps from these 4 numbers : 17 | 18 | ``` 19 | 4 20 | / \ 21 | 3 2 22 | / 23 | 1 24 | ``` 25 | ``` 26 | 4 27 | / \ 28 | 2 3 29 | / 30 | 1 31 | ``` 32 | ``` 33 | 4 34 | / \ 35 | 3 1 36 | / 37 | 2 38 | ``` 39 | 40 | As the final answer can be very large output your answer modulo `1000000007`. 41 | 42 | Assume that `N <= 100`. 43 | 44 | ### Examples 45 | 46 | ``` 47 | Input: 4 48 | Output: 3 49 | ``` 50 | 51 | ``` 52 | Input: 5 53 | Output: 8 54 | ``` -------------------------------------------------------------------------------- /Ways To Form Max Heap/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | const int MAX = 110; 6 | typedef long long ll; 7 | const ll MOD = 1000000007; 8 | ll ncr[MAX][MAX]; 9 | ll ways[MAX]; 10 | 11 | class Solution { 12 | private: 13 | int solveHelper(int n); 14 | public: 15 | int solve(int A); 16 | }; 17 | 18 | int Solution::solveHelper(int n) { 19 | if (n <= 2) { 20 | return 1; 21 | } 22 | if (n == 3) { 23 | return 2; 24 | } 25 | if (ways[n] != -1) { 26 | return ways[n]; 27 | } 28 | int k = ceil(1.0*(n - 1)/2); 29 | int hReq = log2(n); 30 | ll res = 0; 31 | for (int x = k; x < n - 1; ++x) { 32 | int hLeft = log2(x); 33 | int hRight = log2(n - x - 1); 34 | int lastLevelLeft = pow(2, hLeft + 1) - 1 - x; 35 | int lastLevelRight = pow(2, hRight + 1) - 1 - (n - x - 1); 36 | if (hLeft - hRight >= 2) { 37 | continue; 38 | } 39 | if (hLeft == hRight && lastLevelLeft > 0) { 40 | continue; 41 | } 42 | if (hLeft - hRight == 1 && lastLevelRight > 0) { 43 | continue; 44 | } 45 | if (hLeft + 1 > hReq) { 46 | continue; 47 | } 48 | res += ((ncr[n - 1][x] * solveHelper(x)) % MOD * solveHelper(n - x - 1)) % MOD; 49 | } 50 | return ways[n] = res; 51 | } 52 | 53 | int Solution::solve(int A) { 54 | for (int i = 1; i < MAX; ++i) { 55 | ncr[i][0] = 1; 56 | ncr[i][i] = 1; 57 | ncr[i][1] = i; 58 | } 59 | for (int i = 2; i < MAX; ++i) { 60 | for (int j = 2; j < MAX; ++j) { 61 | ncr[i][j] = ncr[i - 1][j - 1] + ncr[i - 1][j]; 62 | ncr[i][j] %= MOD; 63 | } 64 | } 65 | 66 | memset(ways, -1, sizeof(ways)); 67 | int res = solveHelper(A); 68 | return res; 69 | } 70 | 71 | int main () { 72 | Solution solver; 73 | cout << solver.solve(4) << endl; 74 | cout << solver.solve(5) << endl; 75 | cout << solver.solve(6) << endl; 76 | } 77 | -------------------------------------------------------------------------------- /Ways To Form Max Heap/solution.txt: -------------------------------------------------------------------------------- 1 | This problem requires recursion and heap properties. 2 | 3 | To find the no. of ways to form max heap with N distinct numbers, 4 | we first try to observe that the top of the heap should be the maximum element 5 | among the N distinct elements. 6 | 7 | Now, we try to recursively solve the problem by considering 'x' elements on its left, 8 | i.e. the left subtree having 'x' distinct elements, so the right subtree has 9 | 'N - x - 1' distinct elements. 10 | Clearly, these are two similar sub problems, since left subtree will also be a heap 11 | and so will be the right subtree. 12 | 13 | But, we can't simply iterative over all values of 'x' from 1 to 'N - 1'. 14 | First of all, the no. of elements in the left subtree cannot be more than the right one, 15 | since the heap is a complete binary tree, and all levels are filled fully, 16 | except the last one, which may not be fully filled, but filled from left to right. 17 | 18 | We need to make sure that the height of the left subtree and right subtree doesn't differ 19 | by more than 2. 20 | And, if they are the same height, then the last level of left should be completely filled, 21 | and last level of right can have some elements yet to be filled. 22 | If the height difference is one, then the last level of right must be completely filled, 23 | and last level of left, may have some elements left. 24 | 25 | So, we need to find the heights and carefully check these conditions. 26 | If conditions are satisfied we multiply the ways(Left) and ways(Right) and add to the result. 27 | Look at the code for more details! -------------------------------------------------------------------------------- /Word Break/README.md: -------------------------------------------------------------------------------- 1 | # Word Break 2 | [Try the problem](https://leetcode.com/problems/word-break/) 3 | 4 | Given a **non-empty** string s and a dictionary *wordDict* containing a list of **non-empty** words, determine if s can be segmented into a space-seperated sequence of one or more dictionary words. 5 | 6 | **Note:** 7 | - The same word in the dictionary may be resued multiple times in the segmentation. 8 | - You may assume the dictionary does not contain duplicate words. 9 | 10 | ### Example 1 11 | 12 | ``` 13 | Input: s = "leetcode", wordDict = ["leet", "code"] 14 | Output: true 15 | Explanation: Return true because "leetcode" can be segmented as "leet code". 16 | ``` 17 | 18 | ### Example 2 19 | 20 | ``` 21 | Input: s = "applepenapple", wordDict = ["apple", "pen"] 22 | Output: true 23 | Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". 24 | Note that you are allowed to reuse a dictionary word. 25 | ``` 26 | 27 | ## Example 3 28 | 29 | ``` 30 | Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] 31 | Output: false 32 | ``` -------------------------------------------------------------------------------- /Word Break/solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class Solution { 8 | public: 9 | bool wordBreak(string s, vector& wordDict) { 10 | int n = s.length(); 11 | // canBreak[i] denotes whether we can break the string starting from the i-th index 12 | bool canBreak[n]; 13 | memset(canBreak, false, sizeof(canBreak)); 14 | map isWord; 15 | for (auto word: wordDict) { 16 | isWord[word] = 1; 17 | } 18 | for (int i = n - 1; i >= 0; --i) { 19 | string cur = s.substr(i, 1); 20 | bool canBreakCur = false; 21 | for (int k = i + 1; k < n; ++k) { 22 | canBreakCur |= canBreak[k] && isWord[cur]; 23 | if (canBreakCur == true) { 24 | break; 25 | } 26 | cur += s[k]; 27 | } 28 | if (isWord[cur]) { 29 | canBreakCur = true; 30 | } 31 | canBreak[i] = canBreakCur; 32 | } 33 | return canBreak[0]; 34 | } 35 | }; 36 | 37 | int main() { 38 | Solution solver; 39 | vector wordDict = {"a", "bcd", "cd"}; 40 | cout << solver.wordBreak("abcd", wordDict) << endl; // 1 41 | cout << solver.wordBreak("acde", wordDict) << endl; // 0 42 | return 0; 43 | } -------------------------------------------------------------------------------- /Word Break/solution.txt: -------------------------------------------------------------------------------- 1 | The question is a perfect example of a problem where the interviewee can ask for 2 | clarification questions. 3 | 4 | For example, can the same word in the dictionary of words be used multiple times? 5 | If this were false, the solution could go in an entirely different direction. 6 | 7 | I tried to think of a brute force solution, and the idea that clicked was to figure 8 | out the smallest length string from the left that is a possible word in the dictionary, 9 | then I just have a smaller problem of checking whether a smaller string (left over) 10 | can be segmented into different dictionary words. 11 | 12 | Once we hit a deadpoint, that is the current string cannot be a dictionary word or segmented 13 | into one, we can return 0, and during backtracking we will try with a larger length 14 | string that is possible. 15 | 16 | Then, the realization comes that this problem can have overlapping subproblems. 17 | For e.g. the string 'catsandog' leads to a smaller subproblem 'andog' provided that 'cats' 18 | is a word in the dictionary. 19 | Now, 'andog' leads to the word 'dog' provided 'an' is in the dictionary. 20 | So, 'catsandog' can lead to the smaller subproblem 'dog' directly in one step provided 21 | 'catsan' is a word in the dictionary, during the backtracking step. 22 | 23 | So, now the think is how many states should be memoized? 24 | Clearly, the recursion here just contains the string, and just the starting index of the 25 | string seems to be sufficient. 26 | 27 | So, we can now even think of an iterative DP solution. 28 | 29 | Let us denote canBreak[i] as true if we can break the string starting from the i-th index 30 | using the words in the dictionary. 31 | 32 | So, the recursive step can be expressed as: 33 | canBreak[i] = (OR from k = i+1 to n): canBreak[i + k] AND isWord[i..(i+k)] 34 | 35 | The above expression with handling some boundary cases and verifying it mathematically, 36 | is just what we were trying to do recursively, when we get the smallest word matching, 37 | we moved to solving a new problem, now we can simply remember the solution to all smaller 38 | problems and use them whenever needed. 39 | 40 | The time complexity of the above solution can be verified to be O(N^2). 41 | And, we are using an extra space of O(N) to build this, so comes the space complexity as O(N). 42 | 43 | I was thinking whether we could further optimize the solution. 44 | But, for that we need to somehow think of getting rid of the loop on k in the above 45 | recursive expression, but wasn't able to think of any idea to do that! --------------------------------------------------------------------------------