└── DSA Essentials Solutions ├── 2d Arrays ├── PascalsTriangle.cpp ├── SubmatrixSum.cpp └── WavePrint.cpp ├── Arrays ├── K-rotate.cpp ├── LargestElement.cpp ├── LowerBound.cpp ├── MaximumSumSubarray.cpp └── SortedPairSum.cpp ├── Backtracking ├── N-QueenWays.cpp ├── RatAndMice.cpp ├── UniqueSubset.cpp ├── WordBreakProblem.cpp └── WordSearch.cpp ├── Basic Sorting Algorithms ├── Chopsticks.cpp ├── DefenseKingdom.cpp ├── OptimisedBubbleSort.cpp ├── SortingCartesianProducts.cpp └── SortingWithComparator.cpp ├── BinarySearchTree ├── DeleteInBST.cpp ├── IsBST.cpp └── MirrorABST.cpp ├── BinaryTree ├── ExpressionTree.cpp ├── K-thLevel.cpp ├── MinDepth.cpp ├── RemoveHalfNodes.cpp ├── SumOfNodes.cpp ├── SymmetricTree.cpp └── TargetPathSum.cpp ├── Bit Manipulation ├── EarthLevels.cpp ├── ModuloExponentiation.cpp ├── SubsetSumQueries.cpp └── Xoring.cpp ├── Divide and Conquer ├── 2DArrayMerge.cpp └── BinarySearchUsingRecursion.cpp ├── Dynamic Programming ├── CoinChange.cpp ├── MinimumPartitioning.cpp ├── OptimalGameStrategy.cpp └── Vacation.cpp ├── Graphs ├── AllPathsFromSourceToTarget.cpp ├── FindStarInGraph.cpp └── KeysAndRooms.cpp ├── Hashing ├── ArrayIntersection.cpp └── KSumSubarray.cpp ├── Heaps ├── MaximumProduct.cpp ├── ReduceArraySizeToHalf.cpp ├── RelativeRanks.cpp └── WeakestRows.cpp ├── Linked List ├── AlternateMerge.cpp ├── BubbleSortOnLinkedList.cpp ├── DeleteTail.cpp └── KthLastElement.cpp ├── Queues ├── FirstNonRepeatingLetter.cpp ├── InterleaveTwoHalvesOfQueue.cpp └── SortQueueWithConstantSpace.cpp ├── Recursion ├── 2DArrayMerge.cpp ├── AllOccurences.cpp ├── BinaryStrings.cpp ├── FriendsParty.cpp ├── PrintIncreasingNumbers.cpp └── TilingProblem.cpp ├── Stacks ├── DuplicateParenthesis.cpp ├── MaximumRectangularAreaInHistogram.cpp ├── NextGreaterElement.cpp ├── ReverseANumberUsingStack.cpp └── StockSpanProblem.cpp ├── Strings ├── ArePermutation.cpp ├── BinaryStringToNumber.cpp ├── CheckPalindrome.cpp ├── RemoveDuplicates.cpp ├── StringCompression.cpp └── VowelFind.cpp ├── Trie └── PrefixStrings.cpp └── Vectors ├── MakeZeroes.cpp ├── RotateImage.cpp ├── SortFruits.cpp └── SortingCabs.cpp /DSA Essentials Solutions/2d Arrays/PascalsTriangle.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n^3) 2 | 3 | //Hint: Use Binomial Coeffiecients 4 | 5 | 6 | #include 7 | using namespace std; 8 | 9 | int binomialCoeff(int n, int k); 10 | 11 | // Function to print first 12 | // n lines of Pascal's 13 | // Triangle 14 | vector> printPascal(int n) 15 | { 16 | // Iterate through every line and 17 | // print entries in it 18 | vector> res; 19 | for (int line = 0; line < n; line++) 20 | { 21 | // Every line has number of 22 | // integers equal to line 23 | // number 24 | vector v; 25 | for (int i = 0; i <= line; i++) 26 | {v.push_back(binomialCoeff(line, i));} 27 | 28 | res.push_back(v); 29 | } 30 | return res; 31 | } 32 | 33 | int binomialCoeff(int n, int k) 34 | { 35 | int res = 1; 36 | if (k > n - k) 37 | k = n - k; 38 | for (int i = 0; i < k; ++i) 39 | { 40 | res *= (n - i); 41 | res /= (i + 1); 42 | } 43 | 44 | return res; 45 | } 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/2d Arrays/SubmatrixSum.cpp: -------------------------------------------------------------------------------- 1 | //Hint: Pre Compute Cumilative Sums of every index i,j. 2 | 3 | //Expected Time Complexity: 4 | // Pre Computing : O(N^2) 5 | // Queries: O(1) 6 | 7 | #include 8 | using namespace std; 9 | 10 | int sum(vector> v, int sr, int sc, int er, int ec){ 11 | int m=v.size(); 12 | int n=v[0].size(); 13 | // // int aux[m][n]; 14 | int M=m; 15 | int N=n; 16 | vector> aux = v; 17 | vector> mat = v; 18 | int tli=sr, tlj=sc, rbi=er, rbj=ec; 19 | for (int i=0; i 0) 37 | res = res - aux[tli-1][rbj]; 38 | 39 | // Remove elements between (0, 0) and (rbi, tlj-1) 40 | if (tlj > 0) 41 | res = res - aux[rbi][tlj-1]; 42 | 43 | // Add aux[tli-1][tlj-1] as elements between (0, 0) 44 | // and (tli-1, tlj-1) are subtracted twice 45 | if (tli > 0 && tlj > 0) 46 | res = res + aux[tli-1][tlj-1]; 47 | 48 | return res; 49 | } 50 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/2d Arrays/WavePrint.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n^2) 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | vector WavePrint(int m, int n, vector> arr) 8 | { 9 | vector res; 10 | int i, j = n - 1, wave = 1; 11 | 12 | /* m - Ending row index 13 | n - Ending column index 14 | i, j - Iterator 15 | wave - for Direction 16 | wave = 1 - Wave direction down 17 | wave = 0 - Wave direction up */ 18 | while (j >= 0) { 19 | 20 | // Check whether to go in 21 | // upward or downward 22 | if (wave == 1) { 23 | 24 | // Print the element of the matrix 25 | // downward since the value of wave = 1 26 | for (i = 0; i < m; i++) 27 | res.push_back(arr[i][j]); 28 | wave = 0; 29 | j--; 30 | } 31 | else { 32 | 33 | // Print the elements of the 34 | // matrix upward since the value 35 | // of wave = 0 36 | for (i = m - 1; i >= 0; i--) 37 | res.push_back(arr[i][j]) ; 38 | wave = 1; 39 | j--; 40 | } 41 | } 42 | return res; 43 | } 44 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Arrays/K-rotate.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | vector kRotate(vector a, int k) 7 | { 8 | vector v; 9 | int n = a.size(); 10 | k = k % n; 11 | 12 | for(int i = 0; i < n; i++) 13 | { 14 | if(i < k) 15 | { 16 | v.push_back(a[n + i - k]); 17 | } 18 | else 19 | { 20 | v.push_back(a[i - k]); 21 | } 22 | } 23 | return v; 24 | } 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Arrays/LargestElement.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(N) 2 | 3 | #include 4 | using namespace std; 5 | 6 | int largestElement(vector A) { 7 | 8 | int largestEle = INT_MIN; 9 | 10 | for (auto element : A ) { 11 | largestEle = max(largestEle, element); 12 | } 13 | 14 | return largestEle; 15 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Arrays/LowerBound.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(logN) 2 | //Hint: Binary Search 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | 9 | int lowerBound(vector A, int Val) { 10 | 11 | int sz = A.size(); 12 | 13 | int l = 0, r = (sz-1); 14 | 15 | int answer = -1; 16 | 17 | while (l <= r) { 18 | int mid = (l + r) / 2; 19 | if (A[mid] > Val) { 20 | r = mid-1; 21 | } 22 | else { 23 | answer = A[mid]; 24 | l = mid+1; 25 | } 26 | } 27 | 28 | return answer; 29 | 30 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Arrays/MaximumSumSubarray.cpp: -------------------------------------------------------------------------------- 1 | //Time complexity: O(n) 2 | //Hint: Kadane's Algorithm 3 | 4 | #include 5 | using namespace std ; 6 | 7 | int maxSumSubarray(vector A) { 8 | int n = A.size(), max_sum = *min_element(A.begin(), A.end()), curr_sum = 0; 9 | 10 | for(int i = 0 ; i < n ; i++){ 11 | if(curr_sum + A[i] <= 0){ 12 | curr_sum = A[i]; 13 | }else{ 14 | curr_sum += A[i]; 15 | } 16 | 17 | max_sum = max(max_sum, curr_sum); 18 | } 19 | 20 | return max_sum; 21 | } 22 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Arrays/SortedPairSum.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(N) 2 | //Hint: Two Pointer Approach 3 | 4 | #include 5 | using namespace std; 6 | 7 | pair closestSum(vector arr, int x){ 8 | int res_l, res_r; 9 | int n = arr.size(); 10 | int l = 0, r = n-1, diff = INT_MAX; 11 | 12 | while (r > l) 13 | { 14 | if (abs(arr[l] + arr[r] - x) < diff) 15 | { 16 | res_l = l; 17 | res_r = r; 18 | diff = abs(arr[l] + arr[r] - x); 19 | } 20 | 21 | if (arr[l] + arr[r] > x) 22 | r--; 23 | else 24 | l++; 25 | } 26 | 27 | return {arr[res_l], arr[res_r]}; 28 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Backtracking/N-QueenWays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int cnt; 6 | 7 | int isSafe(int N, int mat[][20], int r, int c) 8 | { 9 | // return 0 if two queens share the same column 10 | for (int i = 0; i < r; i++) 11 | { 12 | if (mat[i][c] == 1) { 13 | return 0; 14 | } 15 | } 16 | 17 | // return 0 if two queens share the same `` diagonal 18 | for (int i = r, j = c; i >= 0 && j >= 0; i--, j--) 19 | { 20 | if (mat[i][j] == 1) { 21 | return 0; 22 | } 23 | } 24 | 25 | // return 0 if two queens share the same `/` diagonal 26 | for (int i = r, j = c; i >= 0 && j < N; i--, j++) 27 | { 28 | if (mat[i][j] == 1) { 29 | return 0; 30 | } 31 | } 32 | 33 | return 1; 34 | } 35 | 36 | void solve(int N,int mat[][20], int r) 37 | { 38 | // if `N` queens are placed successfully, print the solution 39 | if (r == N) 40 | { 41 | cnt++; 42 | return; 43 | } 44 | 45 | // place queen at every square in the current row `r` 46 | // and recur for each valid movement 47 | for (int i = 0; i < N; i++) 48 | { 49 | // if no two queens threaten each other 50 | if (isSafe(N, mat, r, i)) 51 | { 52 | // place queen on the current square 53 | mat[r][i] = 1; 54 | 55 | // recur for the next row 56 | solve(N,mat, r + 1); 57 | 58 | // backtrack and remove the queen from the current square 59 | mat[r][i] = 0; 60 | } 61 | } 62 | } 63 | 64 | 65 | int nQueen(int n){ 66 | cnt =0; 67 | int arr[20][20]={0}; 68 | 69 | solve(n,arr,0); 70 | return cnt; 71 | 72 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Backtracking/RatAndMice.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void ratchase(vector a,vector> &b,vector> &v,int i,int j,int n,int m){ 5 | if(i==n && j==m){ 6 | for(int k=0;k<=n;k++){ 7 | for(int l=0;l<=m;l++){ 8 | v[k][l] = b[k][l]; 9 | }cout<0 && a[i-1][j]!='X' && b[i-1][j]!=1){ 19 | b[i-1][j]=1; 20 | ratchase(a,b,v,i-1,j,n,m); 21 | b[i-1][j]=0; 22 | } 23 | if(j!=m && a[i][j+1]!='X' && b[i][j+1]!=1){ 24 | b[i][j+1]=1; 25 | ratchase(a,b,v,i,j+1,n,m); 26 | b[i][j+1]=0; 27 | } 28 | if(j>0 && a[i][j-1]!='X' && b[i][j-1]!=1){ 29 | b[i][j-1]=1; 30 | ratchase(a,b,v,i,j-1,n,m); 31 | b[i][j-1]=0; 32 | } 33 | return; 34 | } 35 | vector> ratAndMice(vector a) { 36 | int n = a.size(); 37 | int m = a[0].size(); 38 | vector> v(n, vector(m, 0)); 39 | vector> b(n, vector(m, 0)); 40 | b[0][0] = 1; 41 | 42 | ratchase(a,b,v,0,0,n-1,m-1); 43 | return v; 44 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Backtracking/UniqueSubset.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | set> s; 4 | void recur(vector &nums, vector ans, int i) 5 | { 6 | if(i == nums.size()){ 7 | sort(ans.begin(), ans.end()); 8 | s.insert(ans); 9 | return; 10 | } 11 | 12 | ans.push_back(nums[i]); 13 | recur(nums, ans, i+1); 14 | ans.pop_back(); 15 | recur(nums, ans, i+1); 16 | } 17 | vector> uniqueSubsets(vector nums){ 18 | s.clear(); 19 | vector ans; 20 | recur(nums, ans, 0); 21 | vector> v; 22 | for(auto x : s) 23 | v.push_back(x); 24 | return v; 25 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Backtracking/WordBreakProblem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int cnt = 0; 5 | vector v; 6 | void help(string s, int n, string res, vector &word) 7 | { 8 | for (int i = 1; i <= n; i++) 9 | { 10 | string ss = s.substr(0, i); 11 | int l = word.size(); 12 | bool flag = false; 13 | 14 | for (int j = 0; j < l; j++) 15 | if (word[j] == ss) 16 | flag = true; 17 | 18 | if (flag) 19 | { 20 | if (i == n) 21 | { 22 | res += ss; 23 | // v.push_back(res); 24 | cnt++; 25 | return; 26 | } 27 | help(s.substr(i, n - i), n - i, res + ss + " ", word); 28 | } 29 | } 30 | } 31 | 32 | int wordBreak(string s, vector &dictionary) 33 | { 34 | cnt = 0; 35 | // v.clear(); 36 | help(s, s.size(), "", dictionary); 37 | // for (auto x : v) cout << x << '\n'; 38 | return cnt; 39 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Backtracking/WordSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool chk; 4 | void recur(vector>& board, string &word, int i, int j, int k) 5 | { 6 | if(k == word.size()) 7 | { 8 | chk = true; 9 | return; 10 | } 11 | if(i < 0 || j < 0 || i == board.size() || j == board[0].size() || board[i][j] == '-1') 12 | return; 13 | 14 | if(board[i][j] == word[k]) 15 | { 16 | char c = board[i][j]; 17 | board[i][j] = '-1'; 18 | recur(board, word, i, j+1, k+1); 19 | recur(board, word, i+1, j, k+1); 20 | recur(board, word, i, j-1, k+1); 21 | recur(board, word, i-1, j, k+1); 22 | board[i][j] = c; 23 | } 24 | return; 25 | } 26 | bool wordSearch(vector> &board, string word) 27 | { 28 | chk = false; 29 | for(int i=0; i 5 | using namespace std; 6 | 7 | int pairSticks(vector length, int D) 8 | { 9 | // your code goes here 10 | sort(length.begin(), length.end()); 11 | int res = 0; 12 | 13 | for(int i=0; i 7 | using namespace std; 8 | using ll = long long; 9 | #define all(v) v.begin(), v.end() 10 | int defkin(int W, int H, vector> position) 11 | { 12 | // your code goes here 13 | vector> v = position; 14 | int w = W, h = H; 15 | vector x, y; 16 | x.push_back(0); y.push_back(0); 17 | 18 | ll maxx = INT_MIN, maxy = INT_MIN; 19 | 20 | for(int i=0; i 2 | using namespace std; 3 | 4 | vector optimizedBubbleSort(vector arr){ 5 | // your code goes here 6 | int i, j, n=arr.size(); 7 | bool swapped; 8 | for (i = 0; i < n-1; i++) 9 | { 10 | swapped = false; 11 | for (j = 0; j < n-i-1; j++) 12 | { 13 | if (arr[j] > arr[j+1]) 14 | { 15 | swap(arr[j], arr[j+1]); 16 | swapped = true; 17 | } 18 | } 19 | 20 | // IF no two elements were swapped by inner loop, then break 21 | if (swapped == false) 22 | break; 23 | } 24 | 25 | return arr; 26 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Basic Sorting Algorithms/SortingCartesianProducts.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity :O(N log N) 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | vector> sortCartesian(vector> v) 8 | { 9 | sort(v.begin(), v.end()); 10 | return v; 11 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Basic Sorting Algorithms/SortingWithComparator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | bool compare(int a, int b){ 4 | return a > b; 5 | } 6 | vector sortingWithComparator(vector v, bool flag){ 7 | // your code goes here 8 | if(flag) sort(v.begin(), v.end()); 9 | else sort(v.begin(), v.end(), compare); 10 | return v; 11 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinarySearchTree/DeleteInBST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class node{ 4 | public: 5 | int data; 6 | node*left; 7 | node*right; 8 | node(int d){ 9 | data=d; 10 | left=NULL; 11 | right=NULL; 12 | } 13 | }; 14 | 15 | 16 | node* deleteNode(node* root, int k){ 17 | // Base case 18 | if (root == NULL) 19 | return root; 20 | 21 | // Recursive calls for ancestors of 22 | // node to be deleted 23 | if (root->data > k) { 24 | root->left = deleteNode(root->left, k); 25 | return root; 26 | } 27 | else if (root->data < k) { 28 | root->right = deleteNode(root->right, k); 29 | return root; 30 | } 31 | 32 | // We reach here when root is the node 33 | // to be deleted. 34 | 35 | // If one of the children is empty 36 | if (root->left == NULL) { 37 | node* temp = root->right; 38 | delete root; 39 | return temp; 40 | } 41 | else if (root->right == NULL) { 42 | node* temp = root->left; 43 | delete root; 44 | return temp; 45 | } 46 | 47 | // If both children exist 48 | else { 49 | 50 | node* succParent = root; 51 | 52 | // Find successor 53 | node* succ = root->right; 54 | while (succ->left != NULL) { 55 | succParent = succ; 56 | succ = succ->left; 57 | } 58 | 59 | // Delete successor. Since successor 60 | // is always left child of its parent 61 | // we can safely make successor's right 62 | // right child as left of its parent. 63 | // If there is no succ, then assign 64 | // succ->right to succParent->right 65 | if (succParent != root) 66 | succParent->left = succ->right; 67 | else 68 | succParent->right = succ->right; 69 | 70 | // Copy Successor Data to root 71 | root->data = succ->data; 72 | 73 | // Delete Successor and return root 74 | delete succ; 75 | return root; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinarySearchTree/IsBST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int key; 8 | Node *left; 9 | Node *right; 10 | 11 | Node(int key){ 12 | this->key = key; 13 | left = right = NULL; 14 | } 15 | }; 16 | 17 | bool isBSTUtil(Node* node, int min, int max) 18 | { 19 | /* an empty tree is BST */ 20 | if (node==NULL) 21 | return true; 22 | 23 | /* false if this node violates 24 | the min/max constraint */ 25 | if (node->key < min || node->key > max) 26 | return false; 27 | 28 | /* otherwise check the subtrees recursively, 29 | tightening the min or max constraint */ 30 | return 31 | isBSTUtil(node->left, min, node->key) && 32 | isBSTUtil(node->right, node->key, max); 33 | } 34 | 35 | bool isBST(Node * root){ 36 | //complete this method 37 | return isBSTUtil(root, INT_MIN,INT_MAX); 38 | 39 | } 40 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinarySearchTree/MirrorABST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node 5 | { 6 | public: 7 | int key; 8 | Node *left; 9 | Node *right; 10 | 11 | Node(int key){ 12 | this->key = key; 13 | left = right = NULL; 14 | } 15 | }; 16 | 17 | void mirror(Node* node) 18 | { 19 | if (node == NULL) 20 | return; 21 | else 22 | { 23 | struct Node* temp; 24 | 25 | /* do the subtrees */ 26 | mirror(node->left); 27 | mirror(node->right); 28 | 29 | /* swap the pointers in this node */ 30 | temp = node->left; 31 | node->left = node->right; 32 | node->right = temp; 33 | } 34 | } 35 | 36 | Node* mirrorBST(Node * root){ 37 | //complete this method 38 | mirror(root); 39 | return root; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinaryTree/ExpressionTree.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | struct Node { 8 | string key; 9 | Node* left, *right; 10 | }; 11 | 12 | bool isOp(string data) 13 | { 14 | if(data == "+" or data == "-" or data == "*" or data == "/") 15 | return true; 16 | return false; 17 | } 18 | 19 | int evalTree(Node* root){ 20 | if(root == NULL) return 0; 21 | if(!isOp(root->key)) return stoi(root->key); 22 | 23 | if(root->key == "+") return evalTree(root->left)+evalTree(root->right); 24 | if(root->key == "-") return evalTree(root->left)-evalTree(root->right); 25 | if(root->key == "*") return evalTree(root->left)*evalTree(root->right); 26 | if(root->key == "/") return evalTree(root->left)/evalTree(root->right); 27 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinaryTree/K-thLevel.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | struct Node { 7 | int key; 8 | Node* left, *right; 9 | }; 10 | 11 | vector printKthLevel(Node* root, int k){ 12 | // your code goes here 13 | // Create Queue 14 | queue que; 15 | 16 | // Enqueue the root node 17 | que.push(root); 18 | 19 | // Create a set 20 | vector s; 21 | 22 | // Level to track 23 | // the current level 24 | int level = 0; 25 | int flag = 0; 26 | 27 | // Iterate the queue till its not empty 28 | while (!que.empty()) { 29 | 30 | // Calculate the number of nodes 31 | // in the current level 32 | int size = que.size(); 33 | 34 | // Process each node of the current 35 | // level and enqueue their left 36 | // and right child to the queue 37 | while (size--) { 38 | struct Node* ptr = que.front(); 39 | que.pop(); 40 | 41 | // If the current level matches the 42 | // required level then add into set 43 | if (level == k) { 44 | 45 | // Flag initialized to 1 46 | flag = 1; 47 | 48 | // Inserting node data in set 49 | s.push_back(ptr->key); 50 | } 51 | else { 52 | 53 | // Traverse to the left child 54 | if (ptr->left) 55 | que.push(ptr->left); 56 | 57 | // Traverse to the right child 58 | if (ptr->right) 59 | que.push(ptr->right); 60 | } 61 | } 62 | 63 | // Increment the variable level 64 | // by 1 for each level 65 | level++; 66 | 67 | // Break out from the loop 68 | // if the Kth Level is reached 69 | if (flag == 1) 70 | break; 71 | } 72 | return s; 73 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinaryTree/MinDepth.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node { 5 | int key; 6 | Node* left, *right; 7 | }; 8 | 9 | int minDepth(Node *root) { 10 | // Your code here 11 | int res = INT_MAX; 12 | queue> q; 13 | int d = 1; 14 | q.push({root, d}); 15 | while(!q.empty()) 16 | { 17 | Node* f = q.front().first; 18 | d = 1+q.front().second; 19 | if(f->left == NULL && f->right == NULL) 20 | res = min(res, q.front().second); 21 | q.pop(); 22 | if(f->left) q.push({f->left, d}); 23 | if(f->right) q.push({f->right, d}); 24 | } 25 | return res; 26 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinaryTree/RemoveHalfNodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node { 5 | int key; 6 | Node* left, *right; 7 | }; 8 | 9 | void inorder(Node* root, vector &v) 10 | { 11 | if(root == NULL) return; 12 | if(root->left) inorder(root->left, v); 13 | v.push_back(root->key); 14 | if(root->right) inorder(root->right, v); 15 | } 16 | 17 | Node *help(Node *root) 18 | { 19 | //add code here. 20 | if(root==NULL) return NULL; 21 | if(root->right) root->right = help(root->right); 22 | if(root->left) root->left = help(root->left); 23 | if( (root->left != NULL && root->right == NULL) or (root->left == NULL && root->right !=NULL) ) 24 | { 25 | if(root->left) root = root->left; 26 | else root = root->right; 27 | root = help(root); 28 | } 29 | return root; 30 | 31 | } 32 | 33 | vector removeHalfNodes(Node *root) 34 | { 35 | //add code here. 36 | root = help(root); 37 | vector v; 38 | inorder(root, v); 39 | return v; 40 | 41 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinaryTree/SumOfNodes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node { 5 | int key; 6 | Node* left, *right; 7 | }; 8 | 9 | int sumBT(Node* root) 10 | { 11 | // Code here 12 | int res = 0; 13 | queue q; 14 | q.push(root); 15 | while(!q.empty()) 16 | { 17 | Node* f = q.front(); 18 | q.pop(); 19 | if(f->left) q.push(f->left); 20 | if(f->right) q.push(f->right); 21 | res += f->key; 22 | } 23 | return res; 24 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinaryTree/SymmetricTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node { 5 | int key; 6 | Node* left, *right; 7 | }; 8 | bool isSymmetric(Node* root) { 9 | queue q1; 10 | queue q2; 11 | if(root == NULL || (root->right==NULL && root->left==NULL)) return true; 12 | if(root->right == NULL || root->left == NULL) return false; 13 | q1.push(root->left); 14 | q2.push(root->right); 15 | while(!q1.empty() && !q2.empty()) 16 | { 17 | Node* f1 = q1.front(); 18 | q1.pop(); 19 | Node* f2 = q2.front(); 20 | q2.pop(); 21 | if(q1.empty() && !q2.empty()) return false; 22 | if(!q1.empty() && q2.empty()) return false; 23 | if(f1->left==NULL && f2->right!=NULL) return false; 24 | if(f1->left!=NULL && f2->right==NULL) return false; 25 | if(f1->key != f2->key) return false; 26 | if(f1->left) q1.push(f1->left); 27 | if(f1->right) q1.push(f1->right); 28 | if(f2->right) q2.push(f2->right); 29 | if(f2->left) q2.push(f2->left); 30 | } 31 | if(q1.empty() && q2.empty()) return true; 32 | return false; 33 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/BinaryTree/TargetPathSum.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node { 5 | int val; 6 | Node* left, *right; 7 | }; 8 | 9 | vector> vv; 10 | void help(Node* root, int a, vector &v, int b) 11 | { 12 | if(root == NULL) return; 13 | if(root->left == NULL && root->right == NULL) 14 | { 15 | 16 | if(a == b+root->val) 17 | { 18 | v.push_back(root->val); 19 | vv.push_back(v); 20 | v.pop_back(); 21 | } 22 | return; 23 | } 24 | if(root->left) 25 | { 26 | v.push_back(root->val); 27 | help(root->left, a, v, b+root->val); 28 | v.pop_back(); 29 | } 30 | if(root->right) 31 | { 32 | v.push_back(root->val); 33 | help(root->right, a, v, b+root->val); 34 | v.pop_back(); 35 | } 36 | } 37 | vector> pathSum(Node* root, int targetSum) { 38 | vv.clear(); 39 | vector v; 40 | help(root, targetSum, v, 0); 41 | return vv; 42 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Bit Manipulation/EarthLevels.cpp: -------------------------------------------------------------------------------- 1 | // Expected Time Complexity : O(Log n) 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | long long convertDecimalToBinary(unsigned long long int n) 8 | { 9 | long long binaryNumber = 0; 10 | unsigned long long int remainder, i = 1, step = 1; 11 | 12 | while (n!=0) 13 | { 14 | remainder = n%2; 15 | n /= 2; 16 | binaryNumber += remainder*i; 17 | i *= 10; 18 | } 19 | return binaryNumber; 20 | } 21 | 22 | int earthLevel(int k) 23 | { 24 | //your code goes here 25 | unsigned long long int binaryNumber, sum = 0; 26 | binaryNumber = convertDecimalToBinary(k); 27 | 28 | while (binaryNumber != 0) 29 | { 30 | unsigned long long int t; 31 | t = binaryNumber%2; 32 | sum = sum + t; 33 | binaryNumber = binaryNumber/10; 34 | } 35 | 36 | return sum; 37 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Bit Manipulation/ModuloExponentiation.cpp: -------------------------------------------------------------------------------- 1 | // Expected Time Complexity : O(Log N) 2 | // Hint: if a is even, than x^a can be written as (x^(a/2))*(x^(a/2)) 3 | 4 | #include 5 | using namespace std; 6 | 7 | 8 | int power(int x, int y, int p) 9 | { 10 | int res = 1; // Initialize result 11 | 12 | x = x % p; // Update x if it is more than or 13 | // equal to p 14 | 15 | if (x == 0) return 0; // In case x is divisible by p; 16 | 17 | while (y > 0) 18 | { 19 | // If y is odd, multiply x with result 20 | if (y & 1) 21 | res = (res*x) % p; 22 | 23 | // y must be even now 24 | y = y>>1; // y = y/2 25 | x = (x*x) % p; 26 | } 27 | return res; 28 | } 29 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Bit Manipulation/SubsetSumQueries.cpp: -------------------------------------------------------------------------------- 1 | // Expected Time Complexity : O(1) for each query 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | vector subsetSum(vector v, vector q) 8 | { 9 | int n = q.size(); 10 | vector b(n); 11 | 12 | bitset<10000> bit; 13 | bit.reset(); 14 | bit[0] = 1; 15 | 16 | for (int i = 0; i < v.size(); ++i) 17 | bit |= (bit << v[i]); 18 | 19 | for(int i=0; i 5 | using namespace std; 6 | 7 | int xoring(vector v) 8 | { 9 | int res=0; 10 | for(auto x : v) res ^= x; 11 | return res; 12 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Divide and Conquer/2DArrayMerge.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | void merge_row(vector> &mat,int i, int cs, int cm, int ce){ 6 | vector sorted; 7 | int x=cs; 8 | int y=cm+1; 9 | //cout<> &mat,int j, int rs, int rm, int re){ 38 | vector sorted; 39 | int x=rs; 40 | int y=rm+1; 41 | while(x<=rm && y<=re){ 42 | if(mat[x][j]> &mat, int rs, int rm, int re,int cs, int cm, int ce){ 69 | 70 | 71 | 72 | //for sorting rows 73 | for(int i=rs; i<=re; i++){ 74 | merge_row(mat,i,cs,cm,ce); 75 | } 76 | 77 | //for sorting columns 78 | for(int j=cs; j<=ce; j++){ 79 | merge_col(mat,j,rs,rm,re); 80 | } 81 | return; 82 | 83 | } 84 | 85 | void merge_sort(int m, int n, vector> &mat, int rs, int re, int cs, int ce){ 86 | //cout<=re && cs>=ce){ 89 | return; 90 | } 91 | 92 | 93 | int rm=(rs+re)/2; 94 | int cm=(cs+ce)/2; 95 | 96 | // cout<> mergeSort(int m, int n, vector> v){ 112 | merge_sort(m,n,v,0,m-1,0,n-1); 113 | return v; 114 | } 115 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Divide and Conquer/BinarySearchUsingRecursion.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(logn) 2 | 3 | #include 4 | using namespace std; 5 | 6 | #include 7 | using namespace std; 8 | 9 | // A recursive binary search function. It returns 10 | // location of x in given array arr[l..r] is present, 11 | // otherwise -1 12 | int binary(vector arr, int l, int r, int x) 13 | { 14 | if (r >= l) { 15 | int mid = l + (r - l) / 2; 16 | 17 | // If the element is present at the middle 18 | // itself 19 | if (arr[mid] == x) 20 | return mid; 21 | 22 | // If element is smaller than mid, then 23 | // it can only be present in left subarray 24 | if (arr[mid] > x) 25 | return binary(arr, l, mid - 1, x); 26 | 27 | // Else the element can only be present 28 | // in right subarray 29 | return binary(arr, mid + 1, r, x); 30 | } 31 | 32 | // We reach here when element is not 33 | // present in array 34 | return -1; 35 | } 36 | 37 | int binarySearch(vector v, int x) 38 | { 39 | // your code goes here 40 | 41 | int n = v.size(); 42 | int result = binary(v, 0, n - 1, x); 43 | return result; 44 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Dynamic Programming/CoinChange.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | long long coinChange(int s, int n , vector a, long long dp[500][100]) 5 | { 6 | if (n < 0 || s < 0) return 0; 7 | if (s == 0) return 1; 8 | 9 | if (dp[s][n] != 0) return dp[s][n]; 10 | 11 | long long op1 = coinChange(s, n - 1, a, dp); 12 | long long op2 = coinChange(s - a[n], n, a, dp); 13 | 14 | return dp[s][n] = op1 + op2; 15 | } 16 | 17 | long long findCombinations(int n, vector coins) 18 | { 19 | long long dp[500][100] = {{0}}; 20 | return coinChange(n, coins.size()-1, coins, dp); 21 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Dynamic Programming/MinimumPartitioning.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findMin(vector arr) 5 | { 6 | int n = arr.size(); 7 | int sum = 0; 8 | for (int i = 0; i < n; i++) 9 | sum += arr[i]; 10 | 11 | // Create an array to store results of subproblems 12 | bool dp[n + 1][sum + 1]; 13 | 14 | // Initialize first column as true. 0 sum is possible 15 | // with all elements. 16 | for (int i = 0; i <= n; i++) 17 | dp[i][0] = true; 18 | 19 | // Initialize top row, except dp[0][0], as false. With 20 | // 0 elements, no other sum except 0 is possible 21 | for (int i = 1; i <= sum; i++) 22 | dp[0][i] = false; 23 | 24 | // Fill the partition table in bottom up manner 25 | for (int i = 1; i <= n; i++) { 26 | for (int j = 1; j <= sum; j++) { 27 | // If i'th element is excluded 28 | dp[i][j] = dp[i - 1][j]; 29 | 30 | // If i'th element is included 31 | if (arr[i - 1] <= j) 32 | dp[i][j] |= dp[i - 1][j - arr[i - 1]]; 33 | } 34 | } 35 | 36 | // Initialize difference of two sums. 37 | int diff = INT_MAX; 38 | 39 | // Find the largest j such that dp[n][j] 40 | // is true where j loops from sum/2 t0 0 41 | for (int j = sum / 2; j >= 0; j--) { 42 | // Find the 43 | if (dp[n][j] == true) { 44 | diff = sum - 2 * j; 45 | break; 46 | } 47 | } 48 | return diff; 49 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Dynamic Programming/OptimalGameStrategy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int game(int n, vector v, int s, int e){ 5 | 6 | if(s==e || s==e-1){ 7 | return max(v[s],v[e]); 8 | } 9 | 10 | int op1=v[s] + min(game(n,v,s+2,e),game(n,v,s+1,e-1)); 11 | int op2=v[e] + min(game(n,v,s+1,e-1),game(n,v,s,e-2)); 12 | return max(op1,op2); 13 | } 14 | 15 | int MaxValue(int n, vector v){ 16 | int res=game(n,v,0,n-1); 17 | return res; 18 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Dynamic Programming/Vacation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | using ll = long long; 5 | using vi = vector; 6 | using vl = vector; 7 | using vvl = vector; 8 | using vs = vector; 9 | using mi = map; 10 | using ml = map; 11 | using umi = unordered_map; 12 | using uml = unordered_map; 13 | using pi = pair; 14 | using pl = pair; 15 | using ti = tuple; 16 | using tl = tuple; 17 | using vii = vector; 18 | using viii = vector; 19 | using vll = vector; 20 | using vlll = vector; 21 | #define mem(dp) memset(dp, -1, sizeof(dp)) 22 | #define aut(a, b) for (auto&(a) : (b)) 23 | #define out(x, v) for (auto&(x) : (v)) cout << x << " "; cout << '\n'; 24 | #define rep(i, n) for (ll (i) = 0; (i) < (n); ++(i) ) 25 | #define repp(i, n) for (ll (i) = 1; (i) <= (n); ++(i) ) 26 | #define all(v) v.begin(), v.end() 27 | #define fi get<0> 28 | #define se get<1> 29 | #define th get<2> 30 | #define F first 31 | #define S second 32 | #define mp make_pair 33 | #define mt make_tuple 34 | #define pb push_back 35 | int topDown(viii &v, int n, int i, int dp[][4], int prev) 36 | { 37 | if (i == n) return 0; 38 | if (dp[i][prev] != -1) return dp[i][prev]; 39 | 40 | int op1 = INT_MIN, op2 = INT_MIN, op3 = INT_MIN; 41 | 42 | if (prev != 1) op1 = fi(v[i]) + topDown(v, n, i + 1, dp, 1); 43 | if (prev != 2) op2 = se(v[i]) + topDown(v, n, i + 1, dp, 2); 44 | if (prev != 3) op3 = th(v[i]) + topDown(v, n, i + 1, dp, 3); 45 | 46 | return dp[i][prev] = max(op1, max(op2, op3)); 47 | } 48 | int vacation(vector a, vector b, vector c) 49 | { 50 | viii v; 51 | int n = a.size(); 52 | rep(i, n) 53 | { 54 | v.pb(mt(a[i], b[i], c[i])); 55 | } 56 | int dp[n][4]; 57 | mem(dp); 58 | return topDown(v, n, 0, dp, 0); 59 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Graphs/AllPathsFromSourceToTarget.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void dfs(vector>& graph, vector>& result, vector path, int src, int dst) { 4 | path.push_back(src); 5 | if(src == dst) { 6 | result.push_back(path); 7 | return; 8 | } 9 | 10 | for(auto node : graph[src]) 11 | dfs(graph, result, path, node, dst); 12 | } 13 | vector> allPathsSourceTarget(vector>& graph) { 14 | vector> paths; vector path; 15 | int nodes = graph.size(); 16 | if(nodes == 0) return paths; 17 | dfs(graph, paths, path, 0, nodes - 1); 18 | return paths; 19 | } 20 | 21 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Graphs/FindStarInGraph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int findCenter(vector>& v) { 5 | 6 | pair f={v[0][0],v[0][1]}; 7 | pair s={v[1][0],v[1][1]}; 8 | 9 | if(f.first==s.first){ 10 | return f.first; 11 | } 12 | else if(f. first==s.second){ 13 | return f.first; 14 | } 15 | else if(f.second==s.first){ 16 | return f.second; 17 | } 18 | else{ 19 | return f.second; 20 | } 21 | 22 | 23 | 24 | 25 | } 26 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Graphs/KeysAndRooms.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool canVisitAllRooms(vector>& rooms) { 5 | unordered_map map; 6 | int n=rooms.size(); 7 | for(int i=0;i q; 11 | q.push(0); 12 | while(!q.empty()){ 13 | int k=q.size(); 14 | while(k--){ 15 | int a=q.front(); 16 | q.pop(); 17 | map[a]=true; 18 | for(int j=0;j 2 | using namespace std; 3 | 4 | 5 | vector intersection(vector& nums1, vector& nums2) { 6 | 7 | unordered_map map; 8 | vector result; 9 | 10 | for(int i=0;i 0) 17 | { 18 | result.push_back(nums2[i]); 19 | map[nums2[i]] = 0; 20 | } 21 | } 22 | sort(result.begin(), result.end()); 23 | return result; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Hashing/KSumSubarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int longestSubarrayKSum(vector arr,int k){ 6 | int n = arr.size(); 7 | unordered_map m; 8 | int pre = 0; 9 | 10 | int len = 0; 11 | 12 | for(int i=0;i 2 | using namespace std; 3 | 4 | 5 | int maxProduct(vector& nums) { 6 | priority_queue q; 7 | for(int i=0; i 3 | using namespace std; 4 | 5 | int minSetSize(vector& arr) { 6 | int n=arr.size(); 7 | priority_queue q; 8 | unordered_map mp; 9 | for(int i=0; in/2){ 18 | sum+=q.top(); 19 | q.pop(); 20 | cnt++; 21 | 22 | } 23 | return cnt; 24 | } 25 | 26 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Heaps/RelativeRanks.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | vector findRelativeRanks(vector& score) { 4 | priority_queue> pq; 5 | for(int i=0; i vec(n); 12 | 13 | 14 | int cnt=0; 15 | 16 | 17 | while(!pq.empty()){ 18 | cnt++; 19 | 20 | if(cnt==1){ 21 | cout<<"hey"< 2 | using namespace std; 3 | 4 | 5 | vector kWeakestRows(vector>& mat, int k) { 6 | priority_queue , vector>, greater> > pq; //Min-heap 7 | for(int i=0;i x; 20 | while(k>0) 21 | { 22 | pair temp=pq.top(); 23 | x.push_back(temp.second); 24 | pq.pop(); 25 | k--; 26 | } 27 | return x; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Linked List/AlternateMerge.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | class node{ 8 | public: 9 | int data; 10 | node* next; 11 | 12 | node(int data){ 13 | this->data = data; 14 | next = NULL; 15 | } 16 | }; 17 | 18 | node* apend(node* root, int d){ 19 | if(root == NULL) return new node(d); 20 | node* temp = root; 21 | while(temp->next){ 22 | temp = temp->next; 23 | } 24 | temp->next = new node(d); 25 | return root; 26 | } 27 | 28 | node* alternateMerge(node * root1, node* root2){ 29 | //Complete this function 30 | node* root = NULL; 31 | if(!root1) return root2; 32 | if(!root2) return root1; 33 | while(root1 && root2){ 34 | root = apend(root, root1->data); 35 | root = apend(root, root2->data); 36 | root1 = root1->next; 37 | root2 = root2->next; 38 | } 39 | if(root1){ 40 | while(root1){ 41 | root = apend(root, root1->data); 42 | root1 = root1->next; 43 | } 44 | } 45 | if(root2){ 46 | while(root2){ 47 | root = apend(root, root2->data); 48 | root2 = root2->next; 49 | } 50 | } 51 | 52 | return root; 53 | } 54 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Linked List/BubbleSortOnLinkedList.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n^2) 2 | 3 | #include 4 | using namespace std; 5 | class node 6 | { 7 | public: 8 | int data; 9 | node *next; 10 | node(int data) 11 | { 12 | this->data = data; 13 | this->next = NULL; 14 | } 15 | }; 16 | 17 | 18 | int len(node* head) 19 | { 20 | node* temp = head ; 21 | int i = 0 ; 22 | while(temp!=NULL) 23 | { 24 | i++; 25 | temp=temp->next ; 26 | } 27 | 28 | return i ; 29 | } 30 | node* bubble_sort_LinkedList_itr(node* head) 31 | { 32 | int n = len(head)-1; 33 | 34 | while(n--) 35 | 36 | { 37 | node* prev =NULL; 38 | node*cur = head; 39 | while(cur->next!=NULL) 40 | { 41 | if(cur->data >=cur->next->data) 42 | { 43 | 44 | if(prev==NULL) 45 | { 46 | //first node 47 | node* nxt = cur->next ; 48 | cur->next = nxt->next ; 49 | nxt->next = cur ; 50 | prev=nxt ; 51 | head = prev ; 52 | 53 | 54 | } 55 | 56 | else 57 | { 58 | 59 | node* nxt = cur->next ; 60 | prev->next = nxt ; 61 | cur->next = nxt->next ; 62 | nxt->next = cur ; 63 | prev = nxt ; 64 | 65 | 66 | } 67 | 68 | } 69 | else 70 | { 71 | 72 | prev = cur ; 73 | cur=cur->next ; 74 | 75 | } 76 | 77 | 78 | 79 | } 80 | 81 | } 82 | 83 | 84 | 85 | return head ; 86 | 87 | } 88 | 89 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Linked List/DeleteTail.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | class node{ 8 | public: 9 | int data; 10 | node* next; 11 | 12 | node(int data){ 13 | this->data = data; 14 | next = NULL; 15 | } 16 | }; 17 | 18 | node* deleteTail(node * head){ 19 | //Complete this function 20 | if (head == NULL) 21 | return NULL; 22 | 23 | if (head->next == NULL) { 24 | delete head; 25 | return NULL; 26 | } 27 | 28 | // Find the second last node 29 | node* second_last = head; 30 | while (second_last->next->next != NULL) 31 | second_last = second_last->next; 32 | 33 | // Delete last node 34 | delete (second_last->next); 35 | 36 | // Change next of second last 37 | second_last->next = NULL; 38 | 39 | return head; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Linked List/KthLastElement.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | 7 | class node{ 8 | public: 9 | int data; 10 | node* next; 11 | 12 | node(int data){ 13 | this->data = data; 14 | next = NULL; 15 | } 16 | }; 17 | 18 | int kthLastElement(node * head,int k){ 19 | //Complete this function to return kth last element 20 | node * fast = head; 21 | node * slow = head; 22 | 23 | int cnt = 0; 24 | while(cnt < k){ 25 | fast = fast->next; 26 | cnt++; 27 | } 28 | 29 | while(fast!=NULL){ 30 | slow = slow->next; 31 | fast = fast->next; 32 | } 33 | 34 | return slow->data; 35 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Queues/FirstNonRepeatingLetter.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | const int MAX_CHAR = 26; 6 | 7 | vector firstnonrepeating(vector str) 8 | { 9 | queue q; 10 | vector v; 11 | int charCount[MAX_CHAR] = { 0 }; 12 | 13 | for (int i = 0; i 1) 21 | q.pop(); 22 | else { 23 | v.push_back(q.front()); 24 | break; 25 | } 26 | } 27 | 28 | if (q.empty()) 29 | v.push_back('0'); 30 | } 31 | return v; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Queues/InterleaveTwoHalvesOfQueue.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | queue interLeave(queue q){ 7 | int n=q.size(); 8 | queue q1, q2; 9 | for (int i=0;i<(n/2);i++) { 10 | q1.push(q.front()); 11 | q.pop(); //Expected Time Complexity: O(2^n) 12 | 13 | 14 | } 15 | for (int i=0;i<(n/2);i++) { 16 | q2.push(q.front()); 17 | q.pop(); 18 | } 19 | 20 | for (int i=0;i<(n/2);i++) { 21 | q.push(q1.front()); 22 | q1.pop(); 23 | q.push(q2.front()); 24 | q2.pop(); 25 | } 26 | return q; 27 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Queues/SortQueueWithConstantSpace.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int minIndex(queue &q, int sortedIndex) 5 | { 6 | int min_index = -1; 7 | int min_val = INT_MAX; 8 | int n = q.size(); 9 | for (int i=0; i &q, int min_index) 25 | { 26 | int min_val; 27 | int n = q.size(); 28 | for (int i = 0; i < n; i++) 29 | { 30 | int curr = q.front(); 31 | q.pop(); 32 | if (i != min_index) 33 | q.push(curr); 34 | else 35 | min_val = curr; 36 | } 37 | q.push(min_val); 38 | } 39 | 40 | void sortQueue(queue &q) 41 | { 42 | for (int i = 1; i <= q.size(); i++) 43 | { 44 | int min_index = minIndex(q, q.size() - i); 45 | insertMinToRear(q, min_index); 46 | } 47 | } 48 | 49 | queue sortqueue(queue &q) 50 | { 51 | sortQueue(q); 52 | return q; 53 | } 54 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Recursion/2DArrayMerge.cpp: -------------------------------------------------------------------------------- 1 | Hint: Divide, sort row-wise, sort col-wise 2 | 3 | #include 4 | using namespace std; 5 | 6 | void merge_row(vector> &mat,int i, int cs, int cm, int ce){ 7 | vector sorted; 8 | int x=cs; 9 | int y=cm+1; 10 | //cout<> &mat,int j, int rs, int rm, int re){ 39 | vector sorted; 40 | int x=rs; 41 | int y=rm+1; 42 | while(x<=rm && y<=re){ 43 | if(mat[x][j]> &mat, int rs, int rm, int re,int cs, int cm, int ce){ 70 | 71 | 72 | 73 | //for sorting rows 74 | for(int i=rs; i<=re; i++){ 75 | merge_row(mat,i,cs,cm,ce); 76 | } 77 | 78 | //for sorting columns 79 | for(int j=cs; j<=ce; j++){ 80 | merge_col(mat,j,rs,rm,re); 81 | } 82 | return; 83 | 84 | } 85 | 86 | void merge_sort(int m, int n, vector> &mat, int rs, int re, int cs, int ce){ 87 | //cout<=re && cs>=ce){ 90 | return; 91 | } 92 | 93 | 94 | int rm=(rs+re)/2; 95 | int cm=(cs+ce)/2; 96 | 97 | // cout<> mergeSort(int m, int n, vector> v){ 113 | merge_sort(m,n,v,0,m-1,0,n-1); 114 | return v; 115 | } 116 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Recursion/AllOccurences.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(N) 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | vector vec; 8 | 9 | 10 | void helper(int k, vector v, int i){ 11 | if(i==v.size()){ 12 | return; 13 | } 14 | if(v[i]==k){ 15 | vec.push_back(i); 16 | 17 | } 18 | helper(k,v,i+1); 19 | return; 20 | } 21 | 22 | vector findAllOccurences(int k, vector v){ 23 | vec.clear(); 24 | helper(k,v,0); 25 | return vec; 26 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Recursion/BinaryStrings.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(2^n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | vector v; 7 | 8 | void helper(string str,int n,int i){ 9 | if(i==n){ 10 | v.push_back(str); 11 | return; 12 | } 13 | string s1= str; 14 | s1.push_back('0'); 15 | helper(s1,n,i+1); 16 | 17 | if(i>0 && str[i-1]=='0'){ 18 | str.push_back('1'); 19 | helper(str,n,i+1); 20 | } 21 | else if(i==0){ 22 | str.push_back('1'); 23 | helper(str,n,i+1); 24 | } 25 | 26 | return; 27 | } 28 | 29 | vector binaryStrings(int n){ 30 | v.clear(); 31 | string str; 32 | helper(str,n,0); 33 | return v; 34 | 35 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Recursion/FriendsParty.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(2^n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | int help(int n) 7 | { 8 | if (n <= 0) return 0; 9 | if(n == 2 || n == 1) return n; 10 | return help(n - 1) + (n - 1) * help(n - 2); 11 | } 12 | 13 | int friendsPairing(int n){ 14 | 15 | return help(n); 16 | 17 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Recursion/PrintIncreasingNumbers.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | void help(int i, int n, vector &v) 7 | { 8 | if(i > n) return; 9 | v.push_back(i); 10 | help(i+1, n, v); 11 | } 12 | 13 | vector increasingNumbers(int N) { 14 | vector v; 15 | help(1, N, v); 16 | return v; 17 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Recursion/TilingProblem.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(2^n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | int tiles(int n,int m){ 7 | if(n 5 | using namespace std; 6 | 7 | bool duplicateParentheses(string str){ 8 | 9 | stack Stack; 10 | 11 | for (char ch : str) 12 | { 13 | if (ch == ')') 14 | { 15 | char top = Stack.top(); 16 | Stack.pop(); 17 | 18 | int elementsInside = 0; 19 | while (top != '(') 20 | { 21 | elementsInside++; 22 | top = Stack.top(); 23 | Stack.pop(); 24 | } 25 | if(elementsInside < 1) { 26 | return true; 27 | } 28 | } 29 | 30 | else 31 | Stack.push(ch); 32 | } 33 | 34 | return false; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Stacks/MaximumRectangularAreaInHistogram.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | int getMaxArea(vector hist) 7 | { 8 | int n = hist.size(); 9 | stack s; 10 | 11 | int max_area = 0; 12 | int tp; 13 | int area_with_top; 14 | 15 | int i = 0; 16 | while (i < n) 17 | { 18 | if (s.empty() || hist[s.top()] <= hist[i]) 19 | s.push(i++); 20 | else 21 | { 22 | tp = s.top(); 23 | s.pop(); 24 | area_with_top = hist[tp] * (s.empty() ? i : 25 | i - s.top() - 1); 26 | 27 | if (max_area < area_with_top) 28 | max_area = area_with_top; 29 | } 30 | } 31 | 32 | while (s.empty() == false) 33 | { 34 | tp = s.top(); 35 | s.pop(); 36 | area_with_top = hist[tp] * (s.empty() ? i : 37 | i - s.top() - 1); 38 | 39 | if (max_area < area_with_top) 40 | max_area = area_with_top; 41 | } 42 | 43 | return max_area; 44 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Stacks/NextGreaterElement.cpp: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | using namespace std; 5 | 6 | vector nextGreaterElement(vector arr){ 7 | int n = arr.size(); 8 | vector arr1(n, 0); 9 | stack s; 10 | 11 | for (int i = n - 1; i >= 0; i--) 12 | { 13 | while (!s.empty() && s.top() <= arr[i]) 14 | s.pop(); 15 | 16 | if (s.empty()) 17 | arr1[i] = -1; 18 | else 19 | arr1[i] = s.top(); 20 | 21 | s.push(arr[i]); 22 | } 23 | 24 | return arr1; 25 | } 26 | 27 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Stacks/ReverseANumberUsingStack.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | int reverse(int n){ 7 | 8 | int number = n; 9 | stack st; 10 | while (number != 0) 11 | { 12 | st.push(number % 10); 13 | number = number / 10; 14 | } 15 | 16 | int rev = 0; 17 | int i = 1; 18 | 19 | while (!st.empty()) 20 | { 21 | rev = rev + (st.top() * i); 22 | st.pop(); 23 | i = i * 10; 24 | } 25 | 26 | return rev; 27 | 28 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Stacks/StockSpanProblem.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity: O(n) 2 | 3 | #include 4 | using namespace std; 5 | 6 | vector stockSpanner(vector &a){ 7 | stack s; 8 | int n = a.size(); 9 | s.push(0); 10 | vector arr(n, 1); 11 | for (int i = 1; i < n; i++) { 12 | while (!s.empty() and a[s.top()] <= a[i]) { 13 | s.pop(); 14 | } 15 | if (!s.empty()) { 16 | arr[i] = i - s.top(); 17 | } else arr[i] = i + 1; 18 | s.push(i); 19 | } 20 | return arr; 21 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Strings/ArePermutation.cpp: -------------------------------------------------------------------------------- 1 | //Expected Time Complexity= O(N log N) 2 | //Hint: Permuatations are just different arrangements of same alphabets. Can you make the arrangement same? 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | bool arePermutation(string str1, string str2) 9 | { 10 | // Get lenghts of both strings 11 | int n1 = str1.length(); 12 | int n2 = str2.length(); 13 | 14 | // If length of both strings is not same, 15 | // then they cannot be Permutation 16 | if (n1 != n2) 17 | return false; 18 | 19 | // Sort both strings 20 | sort(str1.begin(), str1.end()); 21 | sort(str2.begin(), str2.end()); 22 | 23 | // Compare sorted strings 24 | for (int i = 0; i < n1; i++) 25 | if (str1[i] != str2[i]) 26 | return false; 27 | 28 | return true; 29 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Strings/BinaryStringToNumber.cpp: -------------------------------------------------------------------------------- 1 | Expected Time Complexity : O(N) 2 | 3 | 4 | #include 5 | #include 6 | using namespace std; 7 | 8 | // Function to convert binary to decimal 9 | int binaryToDecimal(string n) 10 | { 11 | string num = n; 12 | int dec_value = 0; 13 | 14 | // Initializing base value to 1, i.e 2^0 15 | int base = 1; 16 | 17 | int len = num.length(); 18 | for (int i = len - 1; i >= 0; i--) { 19 | if (num[i] == '1') 20 | dec_value += base; 21 | base = base * 2; 22 | } 23 | 24 | return dec_value; 25 | } 26 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Strings/CheckPalindrome.cpp: -------------------------------------------------------------------------------- 1 | Expected Time Complexity : O(N) 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | bool isPalindrome(string str) 8 | { 9 | // Start from leftmost and rightmost corners of str 10 | int l = 0; 11 | int h = str.length() - 1; 12 | 13 | // Keep comparing characters while they are same 14 | while (h > l) 15 | { 16 | if (str[l++] != str[h--]) 17 | { 18 | return false; 19 | } 20 | } 21 | return true; 22 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Strings/RemoveDuplicates.cpp: -------------------------------------------------------------------------------- 1 | Expected Time Complexity : O(N) 2 | 3 | 4 | #include 5 | using namespace std; 6 | 7 | string removeDuplicate(string s){ 8 | // your code goes here 9 | set ss(s.begin(), s.end()); 10 | string str; 11 | 12 | for (auto x : ss) 13 | str.push_back(x); 14 | 15 | return str; 16 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Strings/StringCompression.cpp: -------------------------------------------------------------------------------- 1 | Expected Time Complexity : O(N) 2 | 3 | 4 | 5 | #include 6 | using namespace std; 7 | 8 | int compress(vector& chars) { 9 | 10 | int count_=1; 11 | string ans; 12 | 13 | for(int i=0;i 5 | using namespace std; 6 | 7 | string vowel(string S){ 8 | // your code goes here 9 | string out; 10 | for(auto x : S){ 11 | if(x=='a' || x=='e' || x=='i' || x=='o' || x=='u') out.push_back(x); 12 | } 13 | return out; 14 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Trie/PrefixStrings.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node{ 5 | public: 6 | char ch; 7 | unordered_map next; 8 | bool isTerminal; 9 | node(char a){ 10 | ch=a; 11 | bool isTerminal=false; 12 | } 13 | }; 14 | class Trie{ 15 | public: 16 | node*root= new node('\0'); 17 | 18 | void insert(string str){ 19 | 20 | node*temp=root; 21 | for(int i=0; inext.count(str[i])==0){ 23 | temp->next[str[i]]=new node(str[i]); 24 | } 25 | temp=temp->next[str[i]]; 26 | } 27 | temp->isTerminal=true; 28 | return; 29 | } 30 | void dfs(node*temp, vector &v, string word ){ 31 | if(temp->isTerminal){ 32 | v.push_back(word); 33 | } 34 | if(temp->next.empty()){ 35 | return; 36 | } 37 | for(auto p:temp->next){ 38 | word.push_back(p.first); 39 | dfs(temp->next[p.first],v,word); 40 | word.pop_back(); 41 | } 42 | return; 43 | } 44 | 45 | 46 | 47 | vector find(string str){ 48 | vector v; 49 | node* temp=root; 50 | string word=""; 51 | for(int i=0; inext.count(str[i])==0){ 53 | return v; 54 | } 55 | word.push_back(str[i]); 56 | temp=temp->next[str[i]]; 57 | } 58 | if(temp->isTerminal){ 59 | v.push_back(word); 60 | } 61 | dfs(temp,v,word); 62 | sort(v.begin(),v.end()); 63 | return v; 64 | } 65 | 66 | 67 | 68 | 69 | }; 70 | 71 | 72 | 73 | vector findPrefixStrings(vector words, string prefix){ 74 | Trie t; 75 | for(auto s:words){ 76 | t.insert(s); 77 | } 78 | vector res=t.find(prefix); 79 | return res; 80 | } 81 | -------------------------------------------------------------------------------- /DSA Essentials Solutions/Vectors/MakeZeroes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector> makeZeroes(vector> arr){ 5 | // your code goes here 6 | vector r,c; 7 | int n = arr.size(), m = arr[0].size(); 8 | 9 | for(int i=0; i 2 | using namespace std; 3 | 4 | void rotate(vector>& matrix) { 5 | int n = matrix.size(); 6 | int a = 0; 7 | int b = n-1; 8 | while(a 2 | using namespace std; 3 | 4 | bool comp(pair a, pair b){ 5 | return a.second < b.second; 6 | } 7 | 8 | vector> sortFruits(vector> v, string S){ 9 | // your code goes here 10 | if(S=="name") sort(v.begin(), v.end()); 11 | else sort(v.begin(), v.end(), comp); 12 | return v; 13 | } -------------------------------------------------------------------------------- /DSA Essentials Solutions/Vectors/SortingCabs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool comp(pair a, pair b){ 5 | float x = sqrt((a.first*a.first) + (a.second*a.second)); 6 | float y = sqrt((b.first*b.first) + (b.second*b.second)); 7 | return x < y; 8 | } 9 | 10 | vector> sortCabs(vector> v){ 11 | // your code goes here 12 | sort(v.begin(), v.end(), comp); 13 | return v; 14 | } --------------------------------------------------------------------------------