├── C++ ├── Array │ ├── Array Subset of another array.cpp │ ├── Best Time to Buy and Sell Stock.cpp │ ├── Count Inversions.cpp │ ├── Count more than n divide k occurences.cpp │ ├── Factorial of Large Numbers.cpp │ ├── Find minimum number of merge operations to make an array palindrome.cpp │ ├── Find the Duplicate Number.cpp │ ├── Kadane's Algorithm.cpp │ ├── Kth Smallest Element in an Array.cpp │ ├── Maximum Product Subarray.cpp │ ├── Maximum profit by buying and selling a share at most twice.cpp │ ├── Merge Intervals.cpp │ ├── Minimum number of jumps.cpp │ ├── Minimum swaps and K together.cpp │ ├── Next Permutation.cpp │ ├── Rearrange the array in alternating positive and negative items.cpp │ ├── Smallest subarray with sum greater than x.cpp │ ├── Sort an array of 0's , 1's and 2's.cpp │ ├── Three way partitioning.cpp │ ├── Triplet Sum in Array.cpp │ └── find common elements In 3 sorted arrays.cpp ├── Backtracking │ └── Find Maximum number possible by doing at-most K swaps.cpp ├── Dynamic Programming │ ├── Binomial Coefficient Problem.cpp │ └── Knapsack Problem.cpp ├── Heap │ ├── Heap Sort.cpp │ └── Sort a nearly sorted (or K sorted) array.cpp ├── Linked List │ ├── Add 1 to a number represented as linked list.cpp │ ├── Add two numbers represented by linked lists.cpp │ ├── Creation of Linked List.cpp │ ├── Deletion in Linked List.cpp │ ├── Detect loop in a linked list.cpp │ ├── Insertion in Linked List.cpp │ ├── Intersection Point in Y Shapped Linked Lists.cpp │ ├── Intersection of two sorted Linked lists.cpp │ ├── Middle of the Linked List.cpp │ ├── Remove Loop from Linked List.cpp │ ├── Remove duplicate element from sorted Linked List.cpp │ ├── Remove duplicates from an unsorted linked list.cpp │ └── Split a Circular Linked List into two halves.cpp ├── Recursion │ └── Remove Invalid Parentheses.cpp └── Strings │ └── Split the binary string into substrings with equal number of 0s and 1s.cpp ├── Java ├── Backtracking │ └── Find Maximum number possible by doing at-most K swaps.java └── Linked List │ ├── Add 1 to a number represented as linked list.java │ ├── Add two numbers represented by linked lists.java │ ├── Creation of Linked List.java │ ├── Deletion in Linked List.java │ ├── Detect loop in Linked List.java │ ├── Insertion in Linked List.java │ ├── Intersection Point in Y Shapped Linked Lists.java │ ├── Intersection of two sorted Linked lists.java │ ├── Merge Two Sorted Linked Lists.cpp │ ├── Middle of the Linked List.java │ ├── Remove duplicate element from sorted Linked List.java │ ├── Remove duplicates from an unsorted linked list.java │ └── Remove loop from Linked List.java └── Python ├── Array ├── Array Subset of another array.py ├── Best Time to Buy and Sell Stock.py ├── Count Inversions.py ├── Count more than n divide k occurences.py ├── Find minimum number of merge operations to make an array palindrome.py ├── Find the Duplicate Number.py ├── Kadane's Algorithm.py ├── Kth smallest element in an array.py ├── Maximum Product Subarray.py ├── Maximum profit by buying and selling a share at most twice.py ├── Merge Intervals.py ├── Minimum number of jumps .py ├── Minimum swaps and K together.py ├── Next Permutation.py ├── Rearrange the array in alternating positive and negative items.py ├── Smallest subarray with sum greater than x.py ├── Sort an array of 0s, 1s and 2s.py ├── Three way partitioning.py └── Triplet Sum in Array.py ├── Dynamic Programming └── Knapsack Problem.py ├── Linked List ├── Add 1 to a number represented as linked list.py ├── Add two numbers represented by linked lists.py ├── Detect Loop in Linked List.py ├── Flattening a Linked List.py ├── Intersection Point in Y Shapped Linked Lists.py ├── Intersection of two sorted Linked lists.py ├── Middle of the Linked List.py ├── Remove Loop from Linked list.py ├── Remove duplicate element from sorted Linked List.py └── Remove duplicates from an unsorted linked list.py └── Strings └── Longest Palindromic Substring.py /C++/Array/Array Subset of another array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | string isSubset(int a1[], int a2[], int n, int m) { 3 | 4 | unordered_map map; 5 | for(int i = 0; i < n; i++){ 6 | map[a1[i]] = 1; 7 | } 8 | 9 | for(int j = 0; j < m; j++){ 10 | if(map[a2[j]] != 1){ 11 | return "No"; 12 | } 13 | } 14 | 15 | return "Yes"; 16 | } 17 | -------------------------------------------------------------------------------- /C++/Array/Best Time to Buy and Sell Stock.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int maxProfit(vector& prices) { 4 | 5 | int n = prices.size(); 6 | int maxRight = prices[n-1]; 7 | int maxProfit = 0; 8 | for(int i = n - 2; i >= 0; i--){ 9 | maxRight = max(prices[i], maxRight); 10 | maxProfit = max(maxProfit, maxRight - prices[i]); 11 | } 12 | 13 | return maxProfit; 14 | 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /C++/Array/Count Inversions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int _mergeSort(int arr[], int temp[], int left, int right); 5 | int merge(int arr[], int temp[], int left, int mid, 6 | int right); 7 | 8 | int mergeSort(int arr[], int array_size) 9 | { 10 | int temp[array_size]; 11 | return _mergeSort(arr, temp, 0, array_size - 1); 12 | } 13 | 14 | int _mergeSort(int arr[], int temp[], int left, int right) 15 | { 16 | int mid, inv_count = 0; 17 | if (right > left) { 18 | mid = (right + left) / 2; 19 | 20 | inv_count += _mergeSort(arr, temp, left, mid); 21 | inv_count += _mergeSort(arr, temp, mid + 1, right); 22 | 23 | inv_count += merge(arr, temp, left, mid + 1, right); 24 | } 25 | return inv_count; 26 | } 27 | 28 | 29 | int merge(int arr[], int temp[], int left, int mid, 30 | int right) 31 | { 32 | int i, j, k; 33 | int inv_count = 0; 34 | 35 | i = left; 36 | j = mid; 37 | k = left; 38 | while ((i <= mid - 1) && (j <= right)) { 39 | if (arr[i] <= arr[j]) { 40 | temp[k++] = arr[i++]; 41 | } 42 | else { 43 | temp[k++] = arr[j++]; 44 | 45 | inv_count = inv_count + (mid - i); 46 | } 47 | } 48 | 49 | while (i <= mid - 1) 50 | temp[k++] = arr[i++]; 51 | 52 | 53 | while (j <= right) 54 | temp[k++] = arr[j++]; 55 | 56 | 57 | for (i = left; i <= right; i++) 58 | arr[i] = temp[i]; 59 | 60 | return inv_count; 61 | } 62 | 63 | int main() 64 | { 65 | int arr[] = { 1, 20, 6, 4, 5 }; 66 | int n = sizeof(arr) / sizeof(arr[0]); 67 | int ans = mergeSort(arr, n); 68 | cout << " Number of inversions are " << ans; 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /C++/Array/Count more than n divide k occurences.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution 3 | { 4 | public: 5 | //Function to find all elements in array that appear more than n/k times. 6 | int countOccurence(int arr[], int n, int k) { 7 | // Your code here 8 | unordered_map m; 9 | int x = n/k, count = 0; 10 | for(int i = 0; i < n; i++){ 11 | m[arr[i]] += 1; 12 | if(m[arr[i]] > x){ 13 | count += 1; 14 | m[arr[i]] = -1000; 15 | } 16 | } 17 | 18 | 19 | return count; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/Array/Factorial of Large Numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define rep(i, a, b) for (int i = a; i <= b; i++) 6 | 7 | using namespace std; 8 | // Made a class node containing data and previous pointer as 9 | // we are using tail pointer 10 | class Node { 11 | public: 12 | int data; 13 | Node* prev; 14 | Node(int n) 15 | { 16 | data = n; 17 | prev = NULL; 18 | } 19 | }; 20 | 21 | void Multiply(Node* tail, int n) 22 | { 23 | Node *temp = tail, 24 | *prevNode = tail; // Temp variable for keeping tail 25 | int carry = 0; 26 | while (temp != NULL) { 27 | int data = temp->data * n + carry; 28 | temp->data = data % 10; // stores the last digit 29 | carry = data / 10; 30 | prevNode = temp; 31 | temp = temp->prev; // Moving temp by 1 prevNode will 32 | // now denote temp 33 | } 34 | // If carry is greater than 0 then we create another 35 | // node for it. 36 | while (carry != 0) { 37 | prevNode->prev = new Node((int)(carry % 10)); 38 | carry /= 10; 39 | prevNode = prevNode->prev; 40 | } 41 | } 42 | 43 | void print(Node* tail) 44 | { 45 | if (tail == NULL) // Using tail recursion 46 | return; 47 | print(tail->prev); 48 | cout 49 | << tail->data; // Print linked list in reverse order 50 | } 51 | 52 | // Driver code 53 | int main() 54 | { 55 | int n = 20; 56 | Node tail(1); // Create a node and initialise it by 1 57 | rep(i, 2, n) 58 | Multiply(&tail, i); // Run a loop from 2 to n and 59 | // multiply with tail's i 60 | print(&tail); // Print the linked list 61 | cout << endl; 62 | return 0; 63 | } 64 | 65 | -------------------------------------------------------------------------------- /C++/Array/Find minimum number of merge operations to make an array palindrome.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Returns minimum number of count operations 5 | // required to make arr[] palindrome 6 | int findMinOps(int arr[], int n) 7 | { 8 | int ans = 0; // Initialize result 9 | 10 | // Start from two corners 11 | for (int i=0,j=n-1; i<=j;) 12 | { 13 | // If corner elements are same, 14 | // problem reduces arr[i+1..j-1] 15 | if (arr[i] == arr[j]) 16 | { 17 | i++; 18 | j--; 19 | } 20 | 21 | // If left element is greater, then 22 | // we merge right two elements 23 | else if (arr[i] > arr[j]) 24 | { 25 | // need to merge from tail. 26 | j--; 27 | arr[j] += arr[j+1] ; 28 | ans++; 29 | } 30 | 31 | // Else we merge left two elements 32 | else 33 | { 34 | i++; 35 | arr[i] += arr[i-1]; 36 | ans++; 37 | } 38 | } 39 | 40 | return ans; 41 | } 42 | 43 | int main() 44 | { 45 | int arr[] = {1, 4, 5, 9, 1}; 46 | int n = sizeof(arr)/sizeof(arr[0]); 47 | cout << "Count of minimum operations is " 48 | << findMinOps(arr, n) << endl; 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /C++/Array/Find the Duplicate Number.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | int findDuplicate(vector& nums) { 4 | 5 | int slow=nums[0]; 6 | int fast=nums[0]; 7 | 8 | do{ 9 | slow=nums[slow]; 10 | fast=nums[nums[fast]]; 11 | }while(slow!=fast); 12 | 13 | fast=nums[0]; 14 | while(slow!=fast){ 15 | slow=nums[slow]; 16 | fast=nums[fast]; 17 | } 18 | 19 | return slow; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/Array/Kadane's Algorithm.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | // arr: input array 4 | // n: size of array 5 | //Function to find the sum of contiguous subarray with maximum sum. 6 | int maxSubarraySum(int arr[], int n){ 7 | 8 | // Your code here 9 | int maxSum = INT_MIN, sum = 0; 10 | for(int i = 0; i < n; i++){ 11 | sum = sum + arr[i]; 12 | maxSum = max(maxSum, sum); 13 | 14 | if(sum < 0){ 15 | sum = 0; 16 | } 17 | } 18 | 19 | return maxSum; 20 | 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /C++/Array/Kth Smallest Element in an Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | class Solution{ 3 | public: 4 | // arr : given array 5 | // l : starting index of the array i.e 0 6 | // r : ending index of the array i.e size-1 7 | // k : find kth smallest element and return using this function 8 | int kthSmallest(int arr[], int l, int r, int k) { 9 | //code here 10 | 11 | priority_queue maxHeap; 12 | for(int i=l;i<=r;i++){ 13 | maxHeap.push(arr[i]); 14 | if(maxHeap.size() > k){ 15 | maxHeap.pop(); 16 | } 17 | 18 | } 19 | return maxHeap.top(); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /C++/Array/Maximum Product Subarray.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | 4 | // Function to find maximum product subarray 5 | long long maxProduct(int *arr, int n) { 6 | // code here 7 | long long int maxp = INT_MIN, prod = 1; 8 | for(int i=0;i=0;i--){ 18 | prod *= arr[i]; 19 | maxp = max(maxp, prod); 20 | if(prod == 0){ 21 | prod = 1; 22 | } 23 | } 24 | 25 | return maxp; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /C++/Array/Maximum profit by buying and selling a share at most twice.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | int maxProfit(int price[], int n) 7 | { 8 | int* profit = new int[n]; 9 | for (int i = 0; i < n; i++) 10 | profit[i] = 0; 11 | 12 | int max_price = price[n - 1]; 13 | for (int i = n - 2; i >= 0; i--) { 14 | if (price[i] > max_price) 15 | max_price = price[i]; 16 | 17 | profit[i] 18 | = max(profit[i + 1], max_price - price[i]); 19 | } 20 | 21 | int min_price = price[0]; 22 | for (int i = 1; i < n; i++) { 23 | if (price[i] < min_price) 24 | min_price = price[i]; 25 | 26 | profit[i] = max(profit[i - 1], 27 | profit[i] + (price[i] - min_price)); 28 | } 29 | int result = profit[n - 1]; 30 | 31 | delete[] profit; // To avoid memory leak 32 | 33 | return result; 34 | } 35 | 36 | int main() 37 | { 38 | int price[] = { 2, 30, 15, 10, 8, 25, 80 }; 39 | int n = sizeof(price) / sizeof(price[0]); 40 | cout << "Maximum Profit = " << maxProfit(price, n); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /C++/Array/Merge Intervals.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | vector> merge(vector>& intervals) { 4 | vector> res; 5 | if(intervals.size()==0){ 6 | return res; 7 | } 8 | 9 | sort(intervals.begin(), intervals.end(),[](vector &a, vector &b){ 10 | return a[0] < b[0]; 11 | }); 12 | vector curr=intervals[0]; 13 | 14 | for(int i=1;i= maxReach) 24 | return -1; 25 | step = maxReach - i; 26 | } 27 | } 28 | 29 | return -1; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /C++/Array/Minimum swaps and K together.cpp: -------------------------------------------------------------------------------- 1 | 2 | int minSwap(int *arr, int n, int k) { 3 | // Complet the function 4 | int count = 0; 5 | for (int i = 0; i < n; ++i) 6 | if (arr[i] <= k) 7 | ++count; 8 | 9 | int bad = 0; 10 | for (int i = 0; i < count; ++i) 11 | if (arr[i] > k) 12 | ++bad; 13 | 14 | int ans = bad; 15 | for (int i = 0, j = count; j < n; ++i, ++j) { 16 | 17 | if (arr[i] > k) 18 | --bad; 19 | 20 | if (arr[j] > k) 21 | ++bad; 22 | 23 | ans = min(ans, bad); 24 | } 25 | return ans; 26 | } 27 | -------------------------------------------------------------------------------- /C++/Array/Next Permutation.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | void nextPermutation(vector& nums) { 4 | 5 | if(nums.size()==1){ 6 | return; 7 | } 8 | 9 | 10 | int idx1; 11 | for(int i=nums.size()-2;i>=0;i--){ 12 | if(nums[i]=0;i--){ 24 | if(nums[i]>nums[idx1]){ 25 | idx2=i; 26 | break; 27 | } 28 | } 29 | 30 | swap(nums[idx1],nums[idx2]); 31 | 32 | sort(nums.begin()+idx1+1,nums.end()); 33 | 34 | 35 | } 36 | 37 | 38 | 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /C++/Array/Rearrange the array in alternating positive and negative items.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | void rearrange(int arr[], int n) 6 | { 7 | int i = -1, j = n; 8 | 9 | while (i < j) 10 | { 11 | while(i <= n - 1 and arr[i] > 0) 12 | i += 1; 13 | while (j >= 0 and arr[j] < 0) 14 | j -= 1; 15 | if (i < j) 16 | swap(arr[i], arr[j]); 17 | } 18 | 19 | if (i == 0 || i == n) 20 | return; 21 | 22 | 23 | int k = 0; 24 | while (k < n && i < n) 25 | { 26 | swap(arr[k], arr[i]); 27 | i = i + 1; 28 | k = k + 2; 29 | } 30 | } 31 | 32 | // Utility function to print an array 33 | void printArray(int arr[], int n) 34 | { 35 | for (int i = 0; i < n; i++) 36 | cout << arr[i] << " "; 37 | cout << endl; 38 | } 39 | 40 | int main() 41 | { 42 | int arr[] = {2, 3, -4, -1, 6, -9}; 43 | 44 | int n = 6; 45 | 46 | cout << "Given array is \n"; 47 | printArray(arr, n); 48 | 49 | rearrange(arr, n); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /C++/Array/Smallest subarray with sum greater than x.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | 4 | int sb(int arr[], int n, int x) 5 | { 6 | int curr_sum = 0, min_len = n + 1; 7 | 8 | int start = 0, end = 0; 9 | while (end < n) { 10 | 11 | while (curr_sum <= x && end < n) 12 | curr_sum += arr[end++]; 13 | 14 | while (curr_sum > x && start < n) { 15 | if (end - start < min_len) 16 | min_len = end - start; 17 | 18 | curr_sum -= arr[start++]; 19 | } 20 | } 21 | return min_len; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /C++/Array/Sort an array of 0's , 1's and 2's.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | 5 | void swap(int &x, int &y){ 6 | int temp = x; 7 | x = y; 8 | y = temp; 9 | } 10 | 11 | void sort012(int a[], int n) 12 | { 13 | // coode here 14 | int l = 0, h = n-1, m = 0; 15 | while (m <= h){ 16 | if(a[m] == 0){ 17 | swap(a[m], a[l]); 18 | l++; 19 | m++; 20 | 21 | }else if(a[m] == 1){ 22 | m++; 23 | } 24 | else{ 25 | swap(a[m], a[h]); 26 | h--; 27 | } 28 | } 29 | } 30 | 31 | }; 32 | -------------------------------------------------------------------------------- /C++/Array/Three way partitioning.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution{ 3 | public: 4 | //Function to partition the array around the range such 5 | //that array is divided into three parts. 6 | void threeWayPartition(vector& arr,int a, int b) 7 | { 8 | // code here 9 | int start = 0, end = arr.size()-1, i = 0; 10 | 11 | while(i<=end) 12 | { 13 | if (arr[i] < a){ 14 | swap(arr[i], arr[start]); 15 | i++; 16 | start++; 17 | } 18 | 19 | else if (arr[i] > b){ 20 | swap(arr[i], arr[end]); 21 | end--; 22 | } 23 | else{ 24 | i++; 25 | } 26 | } 27 | 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /C++/Array/Triplet Sum in Array.cpp: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | public: 3 | //Function to find if there exists a triplet in the 4 | //array A[] which sums up to X. 5 | bool find3Numbers(int A[], int n, int X) 6 | { 7 | //Your Code Here 8 | sort(A, A+n); 9 | for(int i = 0; i < n; i++){ 10 | int y = X - A[i]; 11 | int low = i+1, high = n-1; 12 | while (low < high){ 13 | if(A[low] + A[high] == y){ 14 | return 1; 15 | } 16 | else if(A[low] + A[high] > y){ 17 | high--; 18 | } 19 | 20 | else if(A[low] + A[high] < y){ 21 | low++; 22 | } 23 | 24 | } 25 | 26 | } 27 | return 0; 28 | } 29 | 30 | }; 31 | -------------------------------------------------------------------------------- /C++/Array/find common elements In 3 sorted arrays.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | vector commonElements (int ar1[], int ar2[], int ar3[], int n1, int n2, int n3) 5 | { 6 | int i = 0, j = 0, k = 0; 7 | vector ans; 8 | int prev1, prev2, prev3; 9 | 10 | prev1 = prev2 = prev3 = INT_MIN; 11 | 12 | while (i < n1 && j < n2 && k < n3) { 13 | 14 | while (ar1[i] == prev1 && i < n1) 15 | i++; 16 | 17 | while (ar2[j] == prev2 && j < n2) 18 | j++; 19 | 20 | while (ar3[k] == prev3 && k < n3) 21 | k++; 22 | 23 | if (ar1[i] == ar2[j] && ar2[j] == ar3[k]) { 24 | ans.push_back(ar1[i]); 25 | prev1 = ar1[i]; 26 | prev2 = ar2[j]; 27 | prev3 = ar3[k]; 28 | i++; 29 | j++; 30 | k++; 31 | } 32 | 33 | else if (ar1[i] < ar2[j]) { 34 | prev1 = ar1[i]; 35 | i++; 36 | } 37 | 38 | else if (ar2[j] < ar3[k]) { 39 | prev2 = ar2[j]; 40 | j++; 41 | } 42 | 43 | else { 44 | prev3 = ar3[k]; 45 | k++; 46 | } 47 | } 48 | 49 | return ans; 50 | } 51 | 52 | }; 53 | -------------------------------------------------------------------------------- /C++/Backtracking/Find Maximum number possible by doing at-most K swaps.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution 3 | { 4 | public: 5 | 6 | void helper(string &max, string str, int k, int idx){ 7 | 8 | if(k==0){ 9 | return; 10 | } 11 | 12 | int n=str.length(); 13 | char maxc = str[idx]; 14 | for(int i=idx+1;i 0) 28 | max = str; 29 | 30 | helper(max, str, k, idx+1); 31 | swap(str[i],str[idx]); 32 | } 33 | 34 | } 35 | 36 | } 37 | 38 | //Function to find the largest number after k swaps. 39 | string findMaximumNum(string str, int k) 40 | { 41 | // code here. 42 | string max=str; 43 | helper(max, str, k, 0); 44 | return max; 45 | } 46 | }; 47 | -------------------------------------------------------------------------------- /C++/Dynamic Programming/Binomial Coefficient Problem.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution{ 3 | public: 4 | int nCr(int n, int r){ 5 | if(n0;j--){ 17 | dp[j]=(dp[j]+dp[j-1])%1000000007; 18 | } 19 | 20 | } 21 | 22 | return dp[r]; 23 | 24 | 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /C++/Dynamic Programming/Knapsack Problem.cpp: -------------------------------------------------------------------------------- 1 | //Memoization - Top Down Approach 2 | #include 3 | using namespace std; 4 | 5 | int max(int a, int b) { return (a > b) ? a : b; } 6 | int dp[10000][10000]; 7 | int knapSack(int W, int wt[], int val[], int n, int curr) 8 | { 9 | 10 | // Base Case 11 | if (n == curr || W == 0) 12 | return 0; 13 | 14 | if (dp[W][curr] != -1){ 15 | return dp[W][curr]; 16 | } 17 | 18 | if (wt[curr] > W) 19 | return dp[W][curr] = knapSack(W, wt, val, n , curr + 1); 20 | 21 | else 22 | return dp[W][curr] = max( 23 | val[curr] 24 | + knapSack(W - wt[curr], 25 | wt, val, n, curr + 1), 26 | knapSack(W, wt, val, n, curr + 1)); 27 | } 28 | 29 | int main() 30 | { 31 | int val[] = { 60, 100, 120 }; 32 | int wt[] = { 10, 20, 30 }; 33 | int W = 50; 34 | memset(dp, -1, 10000*10000*sizeof(int)); 35 | int n = sizeof(val) / sizeof(val[0]); 36 | cout << knapSack(W, wt, val, n, 0); 37 | return 0; 38 | } 39 | 40 | //Bottom up approach 41 | 42 | #include 43 | using namespace std; 44 | 45 | int max(int a, int b) 46 | { 47 | return (a > b) ? a : b; 48 | } 49 | 50 | int knapSack(int W, int wt[], int val[], int n) 51 | { 52 | int i, w; 53 | vector> K(n + 1, vector(W + 1)); 54 | 55 | for(i = 0; i <= n; i++) 56 | { 57 | for(w = 0; w <= W; w++) 58 | { 59 | if (i == 0 || w == 0){ 60 | K[i][w] = 0; 61 | } 62 | else if (wt[i - 1] <= w){ 63 | K[i][w] = max(val[i - 1] + 64 | K[i - 1][w - wt[i - 1]], 65 | K[i - 1][w]); 66 | } 67 | else{ 68 | K[i][w] = K[i - 1][w]; 69 | } 70 | } 71 | } 72 | return K[n][W]; 73 | } 74 | 75 | int main() 76 | { 77 | int val[] = { 60, 100, 120 }; 78 | int wt[] = { 10, 20, 30 }; 79 | int W = 50; 80 | int n = sizeof(val) / sizeof(val[0]); 81 | 82 | cout << knapSack(W, wt, val, n); 83 | 84 | return 0; 85 | } 86 | 87 | -------------------------------------------------------------------------------- /C++/Heap/Heap Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // To heapify a subtree rooted with node i which is 6 | // an index in arr[]. n is size of heap 7 | void heapify(int arr[], int n, int i) 8 | { 9 | int largest = i; // Initialize largest as root 10 | int l = 2 * i + 1; // left = 2*i + 1 11 | int r = 2 * i + 2; // right = 2*i + 2 12 | 13 | // If left child is larger than root 14 | if (l < n && arr[l] > arr[largest]) 15 | largest = l; 16 | 17 | // If right child is larger than largest so far 18 | if (r < n && arr[r] > arr[largest]) 19 | largest = r; 20 | 21 | // If largest is not root 22 | if (largest != i) { 23 | swap(arr[i], arr[largest]); 24 | 25 | // Recursively heapify the affected sub-tree 26 | heapify(arr, n, largest); 27 | } 28 | } 29 | 30 | // main function to do heap sort 31 | void heapSort(int arr[], int n) 32 | { 33 | // Build heap (rearrange array) 34 | for (int i = n / 2 - 1; i >= 0; i--) 35 | heapify(arr, n, i); 36 | 37 | // One by one extract an element from heap 38 | for (int i = n - 1; i > 0; i--) { 39 | // Move current root to end 40 | swap(arr[0], arr[i]); 41 | 42 | // call max heapify on the reduced heap 43 | heapify(arr, i, 0); 44 | } 45 | } 46 | 47 | void printArray(int arr[], int n) 48 | { 49 | for (int i = 0; i < n; ++i) 50 | cout << arr[i] << " "; 51 | cout << "\n"; 52 | } 53 | 54 | int main() 55 | { 56 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 57 | int n = sizeof(arr) / sizeof(arr[0]); 58 | 59 | heapSort(arr, n); 60 | 61 | cout << "Sorted array is \n"; 62 | printArray(arr, n); 63 | } 64 | -------------------------------------------------------------------------------- /C++/Heap/Sort a nearly sorted (or K sorted) array.cpp: -------------------------------------------------------------------------------- 1 | // A STL based C++ program to sort a nearly sorted array. 2 | #include 3 | using namespace std; 4 | 5 | // Given an array of size n, where every element 6 | // is k away from its target position, sorts the 7 | // array in O(n logk) time. 8 | int sortK(int arr[], int n, int k) 9 | { 10 | 11 | // Insert first k+1 items in a priority queue (or min 12 | // heap) 13 | //(A O(k) operation). We assume, k < n. 14 | //if size of array = k i.e k away from its target position 15 | //then 16 | int size; 17 | size=(n==k)?k:k+1; 18 | priority_queue, greater > pq(arr, arr +size); 19 | 20 | // i is index for remaining elements in arr[] and index 21 | // is target index of for current minimum element in 22 | // Min Heap 'pq'. 23 | int index = 0; 24 | for (int i = k + 1; i < n; i++) { 25 | arr[index++] = pq.top(); 26 | pq.pop(); 27 | pq.push(arr[i]); 28 | } 29 | 30 | while (pq.empty() == false) { 31 | arr[index++] = pq.top(); 32 | pq.pop(); 33 | } 34 | } 35 | 36 | // A utility function to print array elements 37 | void printArray(int arr[], int size) 38 | { 39 | for (int i = 0; i < size; i++) 40 | cout << arr[i] << " "; 41 | cout << endl; 42 | } 43 | 44 | 45 | int main() 46 | { 47 | int k = 3; 48 | int arr[] = { 2, 6, 3, 12, 56, 8 }; 49 | int n = sizeof(arr) / sizeof(arr[0]); 50 | sortK(arr, n, k); 51 | 52 | cout << "Following is sorted array" << endl; 53 | printArray(arr, n); 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /C++/Linked List/Add 1 to a number represented as linked list.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | 5 | Node* reverse(Node* head){ 6 | Node* prev = NULL, *next = NULL, *current = head; 7 | while(current != NULL){ 8 | next = current->next; 9 | current->next = prev; 10 | prev = current; 11 | current = next; 12 | } 13 | 14 | return prev; 15 | } 16 | 17 | Node* addOne(Node *head) 18 | { 19 | 20 | Node* new_head = reverse(head); 21 | Node* current = new_head, *prev = NULL, *current1 = new_head; 22 | 23 | int carry = 0; 24 | while(current != NULL){ 25 | int sum = 0; 26 | if(prev == NULL){ 27 | sum = current->data + 1; 28 | }else{ 29 | sum = current->data + carry; 30 | } 31 | 32 | carry = sum/10; 33 | current->data = sum%10; 34 | prev = current; 35 | current = current->next; 36 | 37 | } 38 | 39 | if(carry == 1){ 40 | Node* new_node = new Node(1); 41 | prev->next = new_node; 42 | } 43 | return reverse(current1); 44 | } 45 | }; 46 | -------------------------------------------------------------------------------- /C++/Linked List/Add two numbers represented by linked lists.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | 5 | struct Node* reverse(struct Node* head){ 6 | struct Node* current = head, *prev = NULL, *next = NULL; 7 | while(current != NULL){ 8 | next = current->next; 9 | current->next = prev; 10 | prev = current; 11 | current = next; 12 | } 13 | return prev; 14 | } 15 | 16 | int length(struct Node* head){ 17 | int count = 0; 18 | struct Node* current = head; 19 | while(current != NULL){ 20 | count++; 21 | current = current->next; 22 | } 23 | return count; 24 | } 25 | 26 | //Function to add two numbers represented by linked list. 27 | struct Node* addTwoLists(struct Node* first, struct Node* second) 28 | { 29 | if(length(first) < length(second)){ 30 | struct Node* temp = first; 31 | first = second; 32 | second = temp; 33 | } 34 | 35 | struct Node* f = reverse(first); 36 | struct Node* f1 = f; 37 | struct Node* s = reverse(second); 38 | struct Node* s1 = s; 39 | struct Node* prev = NULL; 40 | int carry = 0; 41 | while(f1 != NULL or s1 != NULL){ 42 | int fd = 0, sd = 0; 43 | if(f1 == NULL){ 44 | fd = 0; 45 | }else{ 46 | fd = f1->data; 47 | } 48 | 49 | if(s1 == NULL){ 50 | sd = 0; 51 | }else{ 52 | sd = s1->data; 53 | } 54 | int sum = fd + sd + carry; 55 | carry = sum/10; 56 | f1->data = sum%10; 57 | prev = f1; 58 | f1 = f1->next; 59 | if(s1 != NULL){ 60 | s1 = s1->next; 61 | } 62 | 63 | } 64 | 65 | if(carry == 1){ 66 | struct Node* new_node = new Node(1); 67 | prev->next = new_node; 68 | } 69 | 70 | return reverse(f); 71 | } 72 | }; 73 | -------------------------------------------------------------------------------- /C++/Linked List/Creation of Linked List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node { 5 | public: 6 | int data; 7 | Node* next; 8 | }; 9 | 10 | void printList(Node* head) 11 | { 12 | Node* temp = head; 13 | while (temp != NULL) { 14 | cout << temp->data << " "; 15 | temp = temp->next; 16 | } 17 | } 18 | 19 | int main() 20 | { 21 | Node* head = new Node(); 22 | Node* second = new Node(); 23 | Node* third = new Node(); 24 | 25 | head->data = 1; 26 | head->next = second; 27 | 28 | second->data = 2; 29 | second->next = third; 30 | 31 | third->data = 3; 32 | third->next = NULL; 33 | printList(head); 34 | 35 | return 0; 36 | } 37 | 38 | 39 | -------------------------------------------------------------------------------- /C++/Linked List/Deletion in Linked List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node{ 5 | public: 6 | int data; 7 | Node* next; 8 | Node(int d){ 9 | data = d; 10 | next = NULL; 11 | } 12 | }; 13 | 14 | Node* deleteFromStart(Node* head){ 15 | return head->next; 16 | } 17 | 18 | Node* deleteGivenNode(Node* head, int val){ 19 | 20 | if(head-> data == val){ 21 | return head->next; 22 | } 23 | 24 | Node* temp = head, *prev = NULL; 25 | while(temp->data != val){ 26 | prev = temp; 27 | temp = temp->next; 28 | } 29 | prev->next = temp->next; 30 | return head; 31 | } 32 | 33 | void deleteFromEnd(Node* head){ 34 | Node* temp = head; 35 | while(temp->next->next != NULL){ 36 | temp = temp->next; 37 | } 38 | temp->next = NULL; 39 | } 40 | 41 | void printList(Node* head){ 42 | Node* temp = head; 43 | while(temp != NULL){ 44 | cout<data<<" "; 45 | temp = temp->next; 46 | } 47 | cout<next = second; 57 | second->next = third; 58 | third->next = fourth; 59 | 60 | head = deleteFromStart(head); 61 | // head = deleteGivenNode(head,30); 62 | // deleteFromEnd(head); 63 | printList(head); 64 | 65 | } 66 | -------------------------------------------------------------------------------- /C++/Linked List/Detect loop in a linked list.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to check if the linked list has a loop. 5 | bool detectLoop(Node* head) 6 | { 7 | // your code here 8 | Node *slow_p = head, *fast_p = head; 9 | 10 | while (slow_p && fast_p && fast_p->next) { 11 | slow_p = slow_p->next; 12 | fast_p = fast_p->next->next; 13 | if (slow_p == fast_p) { 14 | return 1; 15 | } 16 | } 17 | return 0; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /C++/Linked List/Insertion in Linked List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node{ 5 | public: 6 | int data; 7 | Node* next; 8 | Node(int d){ 9 | data = d; 10 | next = NULL; 11 | } 12 | }; 13 | 14 | Node* insertAtStart(Node* head){ 15 | Node* new_node = new Node(50); 16 | new_node->next = head; 17 | return new_node; 18 | } 19 | 20 | void insertAfterNode(Node* head, int val){ 21 | Node* new_node = new Node(50); 22 | Node* temp = head; 23 | while(temp->data != val){ 24 | temp = temp->next; 25 | } 26 | new_node->next = temp->next; 27 | temp->next = new_node; 28 | 29 | } 30 | 31 | void insertAtEnd(Node* head){ 32 | Node* new_node = new Node(50); 33 | Node* temp = head; 34 | while(temp->next != NULL){ 35 | temp = temp->next; 36 | } 37 | temp->next = new_node; 38 | 39 | } 40 | 41 | void printList(Node* head){ 42 | Node* temp = head; 43 | while(temp != NULL){ 44 | cout<data<<" "; 45 | temp = temp->next; 46 | } 47 | cout<next = second; 57 | second->next = third; 58 | third->next = fourth; 59 | 60 | head = insertAtStart(head); 61 | // insertAfterNode(head,20); 62 | // insertAtEnd(head); 63 | printList(head); 64 | 65 | } 66 | -------------------------------------------------------------------------------- /C++/Linked List/Intersection Point in Y Shapped Linked Lists.cpp: -------------------------------------------------------------------------------- 1 | int intersectPoint(Node* head1, Node* head2) 2 | { 3 | // Your Code Here 4 | Node* x = head1, *y = head2; 5 | while(1){ 6 | 7 | if(x == y){ 8 | return x->data; 9 | } 10 | 11 | if(x == NULL){ 12 | x = head2; 13 | }else{ 14 | x = x->next; 15 | } 16 | 17 | 18 | if(y == NULL){ 19 | y = head1; 20 | }else{ 21 | y = y->next; 22 | } 23 | 24 | 25 | } 26 | return -1; 27 | } 28 | -------------------------------------------------------------------------------- /C++/Linked List/Intersection of two sorted Linked lists.cpp: -------------------------------------------------------------------------------- 1 | Node* findIntersection(Node* head1, Node* head2) 2 | { 3 | // Your Code Here 4 | Node* dummy = new Node(1), *current = dummy; 5 | Node* temp1 = head1, *temp2 = head2; 6 | while(temp1 != NULL && temp2 != NULL){ 7 | if(temp1->data == temp2->data){ 8 | Node* new_node = new Node(temp1->data); 9 | current->next = new_node; 10 | current = current->next; 11 | temp1 = temp1->next; 12 | temp2 = temp2->next; 13 | 14 | } 15 | else if(temp1->data < temp2->data){ 16 | temp1 = temp1->next; 17 | } 18 | else if(temp1->data > temp2->data){ 19 | temp2 = temp2->next; 20 | } 21 | } 22 | return dummy->next; 23 | } 24 | -------------------------------------------------------------------------------- /C++/Linked List/Middle of the Linked List.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | ListNode* middleNode(ListNode* head) { 4 | 5 | ListNode* slow = head; 6 | ListNode* fast = head; 7 | while(fast != NULL && fast->next != NULL){ 8 | slow = slow->next; 9 | fast = fast->next->next; 10 | } 11 | 12 | return slow; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /C++/Linked List/Remove Loop from Linked List.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | void removeLoop(Node* head) 5 | { 6 | if (head == NULL || head->next == NULL) 7 | return; 8 | 9 | Node *slow = head, *fast = head; 10 | 11 | slow = slow->next; 12 | fast = fast->next->next; 13 | 14 | while (fast && fast->next) { 15 | if (slow == fast) 16 | break; 17 | slow = slow->next; 18 | fast = fast->next->next; 19 | } 20 | 21 | if (slow == fast) 22 | { 23 | slow = head; 24 | 25 | if(slow == fast) { 26 | while(fast->next != slow) fast = fast->next; 27 | } 28 | else { 29 | while (slow->next != fast->next) { 30 | slow = slow->next; 31 | fast = fast->next; 32 | } 33 | } 34 | 35 | fast->next = NULL; 36 | } 37 | 38 | } 39 | }; 40 | -------------------------------------------------------------------------------- /C++/Linked List/Remove duplicate element from sorted Linked List.cpp: -------------------------------------------------------------------------------- 1 | Node *removeDuplicates(Node *head) 2 | { 3 | // your code goes here 4 | Node* current = head; 5 | while(current->next != NULL){ 6 | if(current->data == current->next->data){ 7 | current->next = current->next->next; 8 | }else{ 9 | current = current->next; 10 | } 11 | } 12 | return head; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /C++/Linked List/Remove duplicates from an unsorted linked list.cpp: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | public: 4 | //Function to remove duplicates from unsorted linked list. 5 | Node * removeDuplicates( Node *head) 6 | { 7 | // your code goes here 8 | unordered_set seen; 9 | 10 | /* Pick elements one by one */ 11 | struct Node *curr = head; 12 | struct Node *prev = NULL; 13 | while (curr != NULL) 14 | { 15 | // If current value is seen before 16 | if (seen.find(curr->data) != seen.end()) 17 | { 18 | prev->next = curr->next; 19 | delete (curr); 20 | } 21 | else 22 | { 23 | seen.insert(curr->data); 24 | prev = curr; 25 | } 26 | curr = prev->next; 27 | } 28 | return head; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /C++/Linked List/Split a Circular Linked List into two halves.cpp: -------------------------------------------------------------------------------- 1 | void splitList(Node *head, Node **head1_ref, Node **head2_ref) 2 | { 3 | // your code goes here 4 | Node* slow=head; 5 | Node* fast=slow->next; 6 | while (head!=fast and fast->next!=head){ 7 | slow=slow->next; 8 | fast=fast->next->next; 9 | } 10 | *head1_ref=head; 11 | *head2_ref=slow->next; 12 | slow->next=*head1_ref; 13 | Node*current=*head2_ref; 14 | while (current->next!=head){ 15 | current=current->next; 16 | } 17 | 18 | current->next=*head2_ref; 19 | } 20 | -------------------------------------------------------------------------------- /C++/Recursion/Remove Invalid Parentheses.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | 4 | vector res; 5 | unordered_map mp; 6 | 7 | int getMinInValid(string s) 8 | { 9 | stack stck; 10 | int i = 0; 11 | while(i < s.size()) 12 | { 13 | if(s[i] == '(') 14 | stck.push('('); 15 | else if(s[i] == ')') 16 | { 17 | if(stck.size() > 0 && stck.top() == '(') 18 | stck.pop(); 19 | else 20 | stck.push(')'); 21 | } 22 | i++; 23 | } 24 | return stck.size(); 25 | } 26 | 27 | void solve(string s,int minInv){ 28 | 29 | if(mp[s] != 0) 30 | return; 31 | else 32 | mp[s]++; //mp[s] = 1 33 | //base case 34 | if(minInv < 0){ 35 | return; 36 | } 37 | if(minInv == 0) 38 | { 39 | if(!getMinInValid(s)) 40 | res.push_back(s); 41 | return; 42 | } 43 | 44 | for(int i=0; i removeInvalidParentheses(string s) 54 | { 55 | solve(s, getMinInValid(s)); 56 | return res; 57 | } 58 | }; 59 | -------------------------------------------------------------------------------- /C++/Strings/Split the binary string into substrings with equal number of 0s and 1s.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | 6 | int maxSubStr(string str, int n) 7 | { 8 | 9 | int count0 = 0, count1 = 0; 10 | 11 | int cnt = 0; 12 | for (int i = 0; i < n; i++) { 13 | if (str[i] == '0') { 14 | couqnt0++; 15 | } 16 | else { 17 | count1++; 18 | } 19 | if (count0 == count1) { 20 | cnt++; 21 | count0 = 0; 22 | count1 = 0; 23 | } 24 | } 25 | 26 | if (cnt == 0) { 27 | return -1; 28 | } 29 | 30 | return cnt; 31 | } 32 | 33 | int main() 34 | { 35 | string str = "0100110101"; 36 | int n = str.length(); 37 | 38 | cout << maxSubStr(str, n); 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Java/Backtracking/Find Maximum number possible by doing at-most K swaps.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | class Res { 3 | static String max = ""; 4 | } 5 | 6 | class Solution { 7 | // Function to set highest possible digits at given 8 | // index. 9 | public static void findMaximumNum(char ar[], int k, 10 | Res r) 11 | { 12 | if (k == 0) 13 | return; 14 | int n = ar.length; 15 | for (int i = 0; i < n - 1; i++) { 16 | for (int j = i + 1; j < n; j++) { 17 | // if digit at position i is less than digit 18 | // at position j, we swap them and check for 19 | // maximum number so far. 20 | if (ar[j] > ar[i]) { 21 | char temp = ar[i]; 22 | ar[i] = ar[j]; 23 | ar[j] = temp; 24 | 25 | String st = new String(ar); 26 | 27 | // if current number is more than 28 | // maximum so far 29 | if (r.max.compareTo(st) < 0) { 30 | r.max = st; 31 | } 32 | // calling recursive function to set the 33 | // next digit. 34 | findMaximumNum(ar, k - 1, r); 35 | 36 | // backtracking 37 | temp = ar[i]; 38 | ar[i] = ar[j]; 39 | ar[j] = temp; 40 | } 41 | } 42 | } 43 | } 44 | 45 | // Function to find the largest number after k swaps. 46 | public static void main(String[] args) 47 | { 48 | String str = "129814999"; 49 | int k = 4; 50 | Res r = new Res(); 51 | r.max = str; 52 | findMaximumNum(str.toCharArray(), k, r); 53 | //Print the answer stored in res class 54 | System.out.println(r.max); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Java/Linked List/Add 1 to a number represented as linked list.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | 4 | public static Node reverse(Node head){ 5 | Node current = head, prev = null, next = null; 6 | 7 | while(current != null){ 8 | next = current.next; 9 | current.next = prev; 10 | prev = current; 11 | current = next; 12 | } 13 | return prev; 14 | } 15 | 16 | public static Node addOne(Node head) 17 | { 18 | //code here. 19 | Node new_head = reverse(head); 20 | Node current = new_head, current1 = new_head, prev = null; 21 | int carry = 0; 22 | 23 | while(current != null){ 24 | int sum = 0; 25 | if(prev == null){ 26 | sum = current.data + 1; 27 | }else{ 28 | sum = current.data + carry; 29 | } 30 | carry = sum/10; 31 | current.data = sum%10; 32 | prev = current; 33 | current = current.next; 34 | 35 | } 36 | if(carry == 1){ 37 | Node new_node = new Node(1); 38 | prev.next = new_node; 39 | } 40 | return reverse(current1); 41 | 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Java/Linked List/Add two numbers represented by linked lists.java: -------------------------------------------------------------------------------- 1 | class Solution{ 2 | 3 | 4 | static Node reverse(Node head){ 5 | Node current = head, prev = null, next = null; 6 | while(current != null){ 7 | next = current.next; 8 | current.next = prev; 9 | prev = current; 10 | current = next; 11 | } 12 | return prev; 13 | } 14 | 15 | static int length(Node head){ 16 | int count = 0; 17 | Node current = head; 18 | while(current != null){ 19 | count++; 20 | current = current.next; 21 | } 22 | return count; 23 | } 24 | 25 | //Function to add two numbers represented by linked list. 26 | static Node addTwoLists(Node first, Node second){ 27 | // code here 28 | // return head of sum list 29 | if(length(first) < length(second)){ 30 | Node temp = first; 31 | first = second; 32 | second = temp; 33 | } 34 | 35 | Node f = reverse(first); 36 | Node f1 = f; 37 | Node s = reverse(second); 38 | Node s1 = s; 39 | Node prev = null; 40 | int carry = 0; 41 | while(f1 != null || s1 != null){ 42 | int fd = 0, sd = 0; 43 | if(f1 == null){ 44 | fd = 0; 45 | }else{ 46 | fd = f1.data; 47 | } 48 | 49 | if(s1 == null){ 50 | sd = 0; 51 | }else{ 52 | sd = s1.data; 53 | } 54 | int sum = fd + sd + carry; 55 | carry = sum/10; 56 | f1.data = sum%10; 57 | prev = f1; 58 | f1 = f1.next; 59 | if(s1 != null){ 60 | s1 = s1.next; 61 | } 62 | 63 | } 64 | 65 | if(carry == 1){ 66 | Node new_node = new Node(1); 67 | prev.next = new_node; 68 | } 69 | 70 | return reverse(f); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Java/Linked List/Creation of Linked List.java: -------------------------------------------------------------------------------- 1 | class LinkedList { 2 | Node head; 3 | static class Node { 4 | int data; 5 | Node next; 6 | Node(int d) 7 | { 8 | data = d; 9 | next = null; 10 | } 11 | } 12 | 13 | public void printList() 14 | { 15 | Node temp = head; 16 | while (temp != null) { 17 | System.out.print(temp.data + " "); 18 | temp = temp.next; 19 | } 20 | } 21 | 22 | public static void main(String[] args) 23 | { 24 | LinkedList llist = new LinkedList(); 25 | llist.head = new Node(1); 26 | Node second = new Node(2); 27 | Node third = new Node(3); 28 | llist.head.next = second; 29 | second.next = third; 30 | llist.printList(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Java/Linked List/Deletion in Linked List.java: -------------------------------------------------------------------------------- 1 | class LinkedList 2 | { 3 | Node head; 4 | class Node 5 | { 6 | int data; 7 | Node next; 8 | Node(int d) { 9 | data = d; 10 | next = null; 11 | } 12 | } 13 | 14 | public void deleteFromStart(){ 15 | head = head.next; 16 | } 17 | 18 | public void deleteFromEnd(){ 19 | Node temp = head; 20 | while(temp.next.next != null){ 21 | temp = temp.next; 22 | } 23 | temp.next = null; 24 | } 25 | 26 | public void deleteAGivenNode(int val){ 27 | if(head.data == val){ 28 | head = head.next; 29 | return; 30 | } 31 | Node temp = head, prev = null; 32 | while(temp.data != val){ 33 | prev = temp; 34 | temp = temp.next; 35 | } 36 | prev.next = temp.next; 37 | } 38 | 39 | public void printList() 40 | { 41 | Node temp = head; 42 | while (temp != null) 43 | { 44 | System.out.print(temp.data+" "); 45 | temp = temp.next; 46 | } 47 | } 48 | 49 | public static void main(String[] args) 50 | { 51 | LinkedList llist = new LinkedList(); 52 | llist.head = new Node(10); 53 | llist.insertAfterNode(10); 54 | llist.deleteFromStart(); 55 | llist.deleteAGivenNode(20); 56 | llist.deleteFromEnd(); 57 | llist.printList(); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /Java/Linked List/Detect loop in Linked List.java: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | //Function to check if the linked list has a loop. 4 | public static boolean detectLoop(Node head){ 5 | // Add code here 6 | Node slow_p = head, fast_p = head; 7 | boolean flag = false; 8 | while (slow_p != null && fast_p != null 9 | && fast_p.next != null) { 10 | slow_p = slow_p.next; 11 | fast_p = fast_p.next.next; 12 | if (slow_p == fast_p) { 13 | flag = true; 14 | break; 15 | } 16 | } 17 | return flag; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java/Linked List/Insertion in Linked List.java: -------------------------------------------------------------------------------- 1 | 2 | class LinkedList 3 | { 4 | Node head; 5 | class Node 6 | { 7 | int data; 8 | Node next; 9 | Node(int d) { 10 | data = d; 11 | next = null; 12 | } 13 | } 14 | 15 | 16 | public void insertAtStart(){ 17 | Node new_node = new Node(50); 18 | new_node.next = head; 19 | head = new_node; 20 | } 21 | 22 | public void insertAfterNode(int val){ 23 | Node new_node = new Node(50); 24 | Node temp = head; 25 | while(temp.data != val){ 26 | temp = temp.next; 27 | } 28 | new_node.next = temp.next; 29 | temp.next = new_node; 30 | } 31 | 32 | public void insertAtEnd(){ 33 | Node new_node = new Node(50); 34 | Node temp = head; 35 | while(temp.next != null){ 36 | temp = temp.next; 37 | } 38 | 39 | temp->next = new_node; 40 | } 41 | 42 | public void printList() 43 | { 44 | Node temp = head; 45 | while (temp != null) 46 | { 47 | System.out.print(temp.data+" "); 48 | temp = temp.next; 49 | } 50 | } 51 | 52 | public static void main(String[] args) 53 | { 54 | LinkedList llist = new LinkedList(); 55 | 56 | 57 | llist.head = new Node(10); 58 | llist.insertAfterNode(10); 59 | llist.insertAtStart(); 60 | llist.printList(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Java/Linked List/Intersection Point in Y Shapped Linked Lists.java: -------------------------------------------------------------------------------- 1 | class Intersect 2 | { 3 | //Function to find intersection point in Y shaped Linked Lists. 4 | int intersectPoint(Node head1, Node head2) 5 | { 6 | // code here 7 | Node x = head1, y = head2; 8 | while(true){ 9 | 10 | if(x == y){ 11 | return x.data; 12 | } 13 | 14 | if(x == null){ 15 | x = head2; 16 | }else{ 17 | x = x.next; 18 | } 19 | 20 | 21 | if(y == null){ 22 | y = head1; 23 | }else{ 24 | y = y.next; 25 | } 26 | 27 | } 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Java/Linked List/Intersection of two sorted Linked lists.java: -------------------------------------------------------------------------------- 1 | class Sol 2 | { 3 | public static Node findIntersection(Node head1, Node head2) 4 | { 5 | // code here. 6 | Node dummy = new Node(1), current = dummy; 7 | Node temp1 = head1, temp2 = head2; 8 | while(temp1 != null && temp2 != null){ 9 | if(temp1.data == temp2.data){ 10 | Node new_node = new Node(temp1.data); 11 | current.next = new_node; 12 | current = current.next; 13 | temp1 = temp1.next; 14 | temp2 = temp2.next; 15 | 16 | } 17 | else if(temp1.data < temp2.data){ 18 | temp1 = temp1.next; 19 | } 20 | else if(temp1.data > temp2.data){ 21 | temp2 = temp2.next; 22 | } 23 | } 24 | return dummy.next; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java/Linked List/Merge Two Sorted Linked Lists.cpp: -------------------------------------------------------------------------------- 1 | 2 | Node* mergeTwoLLs(Node *head1, Node *head2) { 3 | 4 | Node *fh=NULL, *ft=NULL; 5 | while(head1!=NULL && head2!=NULL){ 6 | 7 | if(fh== NULL && ft==NULL){ 8 | if(head1->data>head2->data){ 9 | fh=head2; 10 | ft=head2; 11 | head2=head2->next; 12 | }else{ 13 | fh=head1; 14 | ft=head1; 15 | head1=head1->next; 16 | } 17 | } 18 | 19 | if(head1->datadata){ 20 | ft->next=head1; 21 | ft=ft->next; 22 | head1=head1->next; 23 | 24 | }else{ 25 | ft->next=head2; 26 | ft=ft->next; 27 | head2=head2->next; 28 | } 29 | } 30 | 31 | if(head1!=NULL){ 32 | ft->next=head1; 33 | } 34 | if(head2!=NULL){ 35 | ft->next=head2; 36 | } 37 | 38 | return fh; 39 | } 40 | -------------------------------------------------------------------------------- /Java/Linked List/Middle of the Linked List.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public ListNode middleNode(ListNode head) { 3 | ListNode slow = head; 4 | ListNode fast = head; 5 | while(fast != null && fast.next != null){ 6 | slow = slow.next; 7 | fast = fast.next.next; 8 | } 9 | 10 | return slow; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Java/Linked List/Remove duplicate element from sorted Linked List.java: -------------------------------------------------------------------------------- 1 | class GfG 2 | { 3 | //Function to remove duplicates from sorted linked list. 4 | Node removeDuplicates(Node head) 5 | { 6 | // Your code here 7 | Node current = head; 8 | while(current.next != null){ 9 | if(current.data == current.next.data){ 10 | current.next = current.next.next; 11 | }else{ 12 | current = current.next; 13 | } 14 | } 15 | 16 | return head; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Java/Linked List/Remove duplicates from an unsorted linked list.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to remove duplicates from unsorted linked list. 4 | public Node removeDuplicates(Node head) 5 | { 6 | // Your code here 7 | HashSet hs = new HashSet<>(); 8 | 9 | /* Pick elements one by one */ 10 | Node current = head; 11 | Node prev = null; 12 | while (current != null) 13 | { 14 | int curval = current.data; 15 | 16 | // If current value is seen before 17 | if (hs.contains(curval)) { 18 | prev.next = current.next; 19 | } else { 20 | hs.add(curval); 21 | prev = current; 22 | } 23 | current = current.next; 24 | } 25 | return head; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Java/Linked List/Remove loop from Linked List.java: -------------------------------------------------------------------------------- 1 | class Solution 2 | { 3 | //Function to remove a loop in the linked list. 4 | public static void removeLoop(Node node){ 5 | // code here 6 | // remove the loop without losing any nodes 7 | if (node == null || node.next == null) 8 | return; 9 | 10 | Node slow = node, fast = node; 11 | 12 | // Move slow and fast 1 and 2 steps 13 | // ahead respectively. 14 | slow = slow.next; 15 | fast = fast.next.next; 16 | 17 | // Search for loop using slow and fast pointers 18 | while (fast != null && fast.next != null) { 19 | if (slow == fast) 20 | break; 21 | 22 | slow = slow.next; 23 | fast = fast.next.next; 24 | } 25 | 26 | /* If loop exists */ 27 | if (slow == fast) { 28 | slow = node; 29 | if (slow != fast) { 30 | while (slow.next != fast.next) { 31 | slow = slow.next; 32 | fast = fast.next; 33 | } 34 | /* since fast->next is the looping point */ 35 | fast.next = null; /* remove loop */ 36 | } 37 | /* This case is added if fast and slow pointer meet at first position. */ 38 | else { 39 | while(fast.next != slow) { 40 | fast = fast.next; 41 | } 42 | fast.next = null; 43 | } 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Python/Array/Array Subset of another array.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | def isSubset( a1, a2, n, m): 3 | map = defaultdict(int) 4 | for i in range(n): 5 | map[a1[i]] = 1 6 | 7 | for j in range(m): 8 | if map[a2[j]] != 1: 9 | return "No" 10 | 11 | return "Yes" 12 | -------------------------------------------------------------------------------- /Python/Array/Best Time to Buy and Sell Stock.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def maxProfit(self, prices: List[int]) -> int: 3 | # stack approach - Next greater element to the right 4 | # O(n) 5 | if len(prices)==0: 6 | return 0 7 | 8 | l=[-1]*len(prices) 9 | max_val=prices[len(prices)-1] 10 | for i in range(len(prices)-2, -1,-1): 11 | if max_val>prices[i]: 12 | l[i]=max_val 13 | else: 14 | max_val=max(max_val,prices[i]) 15 | max_profit=float("-inf") 16 | for i in range(len(prices)): 17 | if l[i]!=-1: 18 | max_profit=max(max_profit,l[i]-prices[i]) 19 | if max_profit==float("-inf"): 20 | return 0 21 | return max_profit 22 | -------------------------------------------------------------------------------- /Python/Array/Count Inversions.py: -------------------------------------------------------------------------------- 1 | def mergeSort(arr, n): 2 | temp_arr = [0] * n 3 | return _mergeSort(arr, temp_arr, 0, n - 1) 4 | 5 | def _mergeSort(arr, temp_arr, left, right): 6 | inv_count = 0 7 | 8 | 9 | if left < right: 10 | mid = (left + right) // 2 11 | inv_count += _mergeSort(arr, temp_arr, 12 | left, mid) 13 | inv_count += _mergeSort(arr, temp_arr, 14 | mid + 1, right) 15 | inv_count += merge(arr, temp_arr, left, mid, right) 16 | 17 | return inv_count 18 | 19 | 20 | 21 | def merge(arr, temp_arr, left, mid, right): 22 | i = left 23 | j = mid + 1 24 | k = left 25 | inv_count = 0 26 | 27 | while i <= mid and j <= right: 28 | 29 | 30 | 31 | if arr[i] <= arr[j]: 32 | temp_arr[k] = arr[i] 33 | k += 1 34 | i += 1 35 | else: 36 | temp_arr[k] = arr[j] 37 | inv_count += (mid - i + 1) 38 | k += 1 39 | j += 1 40 | 41 | 42 | while i <= mid: 43 | temp_arr[k] = arr[i] 44 | k += 1 45 | i += 1 46 | 47 | 48 | while j <= right: 49 | temp_arr[k] = arr[j] 50 | k += 1 51 | j += 1 52 | 53 | 54 | for loop_var in range(left, right + 1): 55 | arr[loop_var] = temp_arr[loop_var] 56 | 57 | return inv_count 58 | 59 | 60 | arr = [1, 20, 6, 4, 5] 61 | n = len(arr) 62 | result = mergeSort(arr, n) 63 | print("Number of inversions are", result) 64 | 65 | -------------------------------------------------------------------------------- /Python/Array/Count more than n divide k occurences.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | class Solution: 3 | 4 | #Function to find all elements in array that appear more than n/k times. 5 | def countOccurence(self,arr,n,k): 6 | #Your code here 7 | m = defaultdict(int) 8 | x = n//k 9 | count = 0 10 | for i in range(n): 11 | m[arr[i]] += 1 12 | if m[arr[i]] > x: 13 | count += 1 14 | m[arr[i]] = -1000 15 | 16 | return count 17 | -------------------------------------------------------------------------------- /Python/Array/Find minimum number of merge operations to make an array palindrome.py: -------------------------------------------------------------------------------- 1 | def findMinOps(arr, n): 2 | ans = 0 # Initialize result 3 | 4 | # Start from two corners 5 | i,j = 0,n-1 6 | while i<=j: 7 | # If corner elements are same, 8 | # problem reduces arr[i+1..j-1] 9 | if arr[i] == arr[j]: 10 | i += 1 11 | j -= 1 12 | 13 | # If left element is greater, then 14 | # we merge right two elements 15 | elif arr[i] > arr[j]: 16 | # need to merge from tail. 17 | j -= 1 18 | arr[j] += arr[j+1] 19 | ans += 1 20 | 21 | # Else we merge left two elements 22 | else: 23 | i += 1 24 | arr[i] += arr[i-1] 25 | ans += 1 26 | 27 | return ans 28 | 29 | 30 | arr = [1, 4, 5, 9, 1] 31 | n = len(arr) 32 | print("Count of minimum operations is " + str(findMinOps(arr, n))) 33 | 34 | -------------------------------------------------------------------------------- /Python/Array/Find the Duplicate Number.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def findDuplicate(self, nums: List[int]) -> int: 3 | slow = fast = finder = 0 4 | while True: 5 | slow = nums[slow] 6 | fast = nums[nums[fast]] 7 | if slow == fast: 8 | while finder != slow: 9 | finder = nums[finder] 10 | slow = nums[slow] 11 | return finder 12 | -------------------------------------------------------------------------------- /Python/Array/Kadane's Algorithm.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | ##Complete this function 3 | #Function to find the sum of contiguous subarray with maximum sum. 4 | def maxSubArraySum(self,a,size): 5 | ans=0 6 | sum=0 7 | for i in range(len(a)): 8 | sum+=a[i] 9 | ans=max(ans,sum) 10 | if sum<0: 11 | sum=0 12 | 13 | return ans 14 | -------------------------------------------------------------------------------- /Python/Array/Kth smallest element in an array.py: -------------------------------------------------------------------------------- 1 | from heapq import heappush, heappop, heapify 2 | class Solution: 3 | def kthSmallest(self,arr, l, r, k): 4 | ''' 5 | arr : given array 6 | l : starting index of the array i.e 0 7 | r : ending index of the array i.e size-1 8 | k : find kth smallest element and return using this function 9 | ''' 10 | q=[] 11 | heapify(q) 12 | for i in range(k): 13 | heappush(q,-1*arr[i]) 14 | 15 | for i in range(k,len(arr)): 16 | x=-1*heappop(q) 17 | if arr[i] max_price: 22 | max_price = price[i] 23 | 24 | # we can get profit[i] by 25 | # taking maximum of: 26 | # a) previous maximum, 27 | # i.e., profit[i+1] 28 | # b) profit by buying at 29 | # price[i] and selling at 30 | # max_price 31 | profit[i] = max(profit[i+1], max_price - price[i]) 32 | 33 | # Get the maximum profit 34 | # with two transactions allowed 35 | # After this loop, profit[n-1] 36 | # contains the result 37 | min_price = price[0] 38 | 39 | for i in range(1, n): 40 | 41 | if price[i] < min_price: 42 | min_price = price[i] 43 | 44 | # Maximum profit is maximum of: 45 | # a) previous maximum, 46 | # i.e., profit[i-1] 47 | # b) (Buy, Sell) at 48 | # (min_price, A[i]) and add 49 | # profit of other trans. 50 | # stored in profit[i] 51 | profit[i] = max(profit[i-1], profit[i]+(price[i]-min_price)) 52 | 53 | result = profit[n-1] 54 | 55 | return result 56 | 57 | 58 | # Driver function 59 | price = [2, 30, 15, 10, 8, 25, 80] 60 | print "Maximum profit is", maxProfit(price, len(price)) 61 | 62 | -------------------------------------------------------------------------------- /Python/Array/Merge Intervals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]: 3 | 4 | x=[] 5 | if len(intervals)==0: 6 | return x 7 | intervals.sort() 8 | 9 | temp=intervals[0] 10 | for i in intervals: 11 | 12 | if temp[1]>=i[0]: 13 | temp[1]=max(temp[1],i[1]) 14 | 15 | else: 16 | x.append(temp) 17 | temp=i 18 | 19 | x.append(temp) 20 | 21 | return x 22 | -------------------------------------------------------------------------------- /Python/Array/Minimum number of jumps .py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minJumps(self, arr, n): 3 | if arr[0]==0: 4 | return -1 5 | 6 | maxReach=arr[0] 7 | step=arr[0] 8 | jump=1 9 | for i in range(1,n): 10 | if i==n-1: 11 | return jump 12 | 13 | 14 | maxReach=max(maxReach,i+arr[i]) 15 | 16 | step-=1 17 | if step==0: 18 | jump+=1 19 | if i>=maxReach: 20 | return -1 21 | step=maxReach-i 22 | return -1 23 | -------------------------------------------------------------------------------- /Python/Array/Minimum swaps and K together.py: -------------------------------------------------------------------------------- 1 | def minSwap (arr, n, k) : 2 | 3 | count = 0 4 | for i in range(0, n) : 5 | if (arr[i] <= k) : 6 | count = count + 1 7 | 8 | bad = 0 9 | for i in range(0, count) : 10 | if (arr[i] > k) : 11 | bad = bad + 1 12 | 13 | ans = bad 14 | j = count 15 | for i in range(0, n) : 16 | 17 | if(j == n) : 18 | break 19 | 20 | if (arr[i] > k) : 21 | bad = bad - 1 22 | 23 | if (arr[j] > k) : 24 | bad = bad + 1 25 | 26 | ans = min(ans, bad) 27 | 28 | j = j + 1 29 | 30 | return ans 31 | -------------------------------------------------------------------------------- /Python/Array/Next Permutation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def nextPermutation(self, nums: List[int]) -> None: 3 | """ 4 | Do not return anything, modify nums in-place instead. 5 | """ 6 | for i in range(len(nums)-1,-1,-1): 7 | if nums[i-1]nums[i-1]: 12 | break 13 | nums[i-1],nums[j]= nums[j],nums[i-1] 14 | nums[i:]=reversed(nums[i:]) 15 | -------------------------------------------------------------------------------- /Python/Array/Rearrange the array in alternating positive and negative items.py: -------------------------------------------------------------------------------- 1 | 2 | def rearrange(arr, n): 3 | i = 0 4 | j = n - 1 5 | 6 | while (i < j): 7 | 8 | while (i <= n - 1 and arr[i] > 0): 9 | i += 1 10 | while (j >= 0 and arr[j] < 0): 11 | j -= 1 12 | 13 | if (i < j): 14 | temp = arr[i] 15 | arr[i] = arr[j] 16 | arr[j] = temp 17 | 18 | if (i == 0 or i == n): 19 | return 0 20 | 21 | k = 0 22 | while (k < n and i < n): 23 | 24 | temp = arr[k] 25 | arr[k] = arr[i] 26 | arr[i] = temp 27 | i = i + 1 28 | k = k + 2 29 | 30 | def printArray(arr, n): 31 | for i in range(n): 32 | print(arr[i], end = " ") 33 | print("\n") 34 | 35 | arr = [2, 3] 36 | 37 | n = len(arr) 38 | 39 | print( "Given array is") 40 | printArray(arr, n) 41 | 42 | rearrange(arr, n) 43 | 44 | print( "Rearranged array is") 45 | printArray(arr, n) 46 | -------------------------------------------------------------------------------- /Python/Array/Smallest subarray with sum greater than x.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sb(self, a, n, x): 3 | # Your code goes here 4 | left=0 5 | current=0 6 | length=float("inf") 7 | for i in range(len(nums)): 8 | current+=nums[i] 9 | while current>s: 10 | length=min(length, i+1-left) 11 | 12 | current-=nums[left] 13 | left+=1 14 | if length==float("inf"): 15 | return 0 16 | return length 17 | -------------------------------------------------------------------------------- /Python/Array/Sort an array of 0s, 1s and 2s.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def sort012(self,arr,n): 3 | # code here 4 | l, m, h = 0, 0, n-1 5 | 6 | while m <= h: 7 | if arr[m] == 0: 8 | arr[m],arr[l] = arr[l], arr[m] 9 | l += 1 10 | m += 1 11 | 12 | elif arr[m] == 1: 13 | m += 1 14 | 15 | else: 16 | arr[m], arr[h] = arr[h], arr[m] 17 | h -= 1 18 | -------------------------------------------------------------------------------- /Python/Array/Three way partitioning.py: -------------------------------------------------------------------------------- 1 | def threeWayPartition(arr, n, lowVal, highVal): 2 | 3 | # Initialize ext available positions for 4 | # smaller (than range) and greater lements 5 | start = 0 6 | end = n - 1 7 | i = 0 8 | 9 | # Traverse elements from left 10 | while i <= end: 11 | 12 | # If current element is smaller than 13 | # range, put it on next available smaller 14 | # position. 15 | if arr[i] < lowVal: 16 | temp = arr[i] 17 | arr[i] = arr[start] 18 | arr[start] = temp 19 | i += 1 20 | start += 1 21 | 22 | # If current element is greater than 23 | # range, put it on next available greater 24 | # position. 25 | elif arr[i] > highVal: 26 | temp = arr[i] 27 | arr[i] = arr[end] 28 | arr[end] = temp 29 | end -= 1 30 | 31 | else: 32 | i += 1 33 | -------------------------------------------------------------------------------- /Python/Array/Triplet Sum in Array.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | #Function to find if there exists a triplet in the 4 | #array A[] which sums up to X. 5 | def find3Numbers(self,A, n, X): 6 | # Your Code Here 7 | A.sort() 8 | for i in range(n): 9 | y = X - A[i] 10 | low = i + 1 11 | high = n-1 12 | while low < high: 13 | if A[low] + A[high] == y: 14 | return 1 15 | 16 | elif A[low] + A[high] < y: 17 | low += 1 18 | 19 | elif A[low] + A[high] > y: 20 | high -= 1 21 | return 0 22 | -------------------------------------------------------------------------------- /Python/Dynamic Programming/Knapsack Problem.py: -------------------------------------------------------------------------------- 1 | # Memoization 2 | val = [60, 100, 120 ] 3 | wt = [10, 20, 30 ] 4 | W = 50 5 | n = len(val) 6 | 7 | # We initialize the matrix with -1 at first. 8 | t = [[-1 for i in range(W + 1)] for j in range(n + 1)] 9 | 10 | 11 | def knapsack(wt, val, W, n, curr): 12 | 13 | # base conditions 14 | if n == curr or W == 0: 15 | return 0 16 | if t[curr][W] != -1: 17 | return t[n][W] 18 | 19 | # choice diagram code 20 | if wt[curr] <= W: 21 | t[curr][W] = max( 22 | val[curr] + knapsack( 23 | wt, val, W-wt[curr], n, curr+1), 24 | knapsack(wt, val, W, n, curr+1)) 25 | return t[curr][W] 26 | elif wt[curr] > W: 27 | t[curr][W] = knapsack(wt, val, W, n, curr+1) 28 | return t[curr][W] 29 | 30 | 31 | print(knapsack(wt, val, W, n, 0)) 32 | 33 | #Top-down 34 | 35 | def knapSack(W, wt, val, n): 36 | K = [[0 for x in range(W + 1)] for x in range(n + 1)] 37 | 38 | # Build table K[][] in bottom up manner 39 | for i in range(n + 1): 40 | for w in range(W + 1): 41 | if i == 0 or w == 0: 42 | K[i][w] = 0 43 | elif wt[i-1] <= w: 44 | K[i][w] = max(val[i-1] 45 | + K[i-1][w-wt[i-1]], 46 | K[i-1][w]) 47 | else: 48 | K[i][w] = K[i-1][w] 49 | 50 | return K[n][W] 51 | 52 | 53 | # Driver code 54 | val = [60, 100, 120] 55 | wt = [10, 20, 30] 56 | W = 50 57 | n = len(val) 58 | print(knapSack(W, wt, val, n)) 59 | -------------------------------------------------------------------------------- /Python/Linked List/Add 1 to a number represented as linked list.py: -------------------------------------------------------------------------------- 1 | def reverse(head): 2 | current=head 3 | prev=None 4 | next=None 5 | while current!=None: 6 | next=current.next 7 | current.next=prev 8 | prev=current 9 | current=next 10 | return prev 11 | 12 | class Solution: 13 | def addOne(self,head): 14 | current1=reverse(head) 15 | current=current1 16 | carry=0 17 | prev=None 18 | while current!=None: 19 | if prev==None: 20 | sum=current.data+carry+1 21 | else: 22 | sum=current.data+carry 23 | carry=sum//10 24 | current.data=sum%10 25 | prev=current 26 | current=current.next 27 | 28 | 29 | if carry==1: 30 | new_node=Node(1) 31 | prev.next=new_node 32 | return reverse(current1) 33 | -------------------------------------------------------------------------------- /Python/Linked List/Add two numbers represented by linked lists.py: -------------------------------------------------------------------------------- 1 | def reverse(head): 2 | current=head 3 | prev=None 4 | next=None 5 | while current!=None: 6 | next=current.next 7 | current.next=prev 8 | prev=current 9 | current=next 10 | return prev 11 | 12 | def length(head): 13 | count=0 14 | current=head 15 | while current!=None: 16 | count+=1 17 | current=current.next 18 | return count 19 | 20 | class Solution: 21 | #Function to add two numbers represented by linked list. 22 | def addTwoLists(self, first, second): 23 | if length(first) ListNode: 3 | slow = head 4 | fast = head 5 | while(fast != None and fast.next != None) : 6 | slow = slow.next 7 | fast = fast.next.next 8 | 9 | 10 | return slow 11 | -------------------------------------------------------------------------------- /Python/Linked List/Remove Loop from Linked list.py: -------------------------------------------------------------------------------- 1 | def removeLoop(self, head): 2 | if self.head is None: 3 | return 4 | if self.head.next is None: 5 | return 6 | slow_p = self.head 7 | fast_p = self.head 8 | 9 | while(slow_p and fast_p and fast_p.next): 10 | slow_p = slow_p.next 11 | fast_p = fast_p.next.next 12 | 13 | # If slow_p and fast_p meet at some point then 14 | # there is a loop 15 | if slow_p == fast_p: 16 | slow_p = self.head 17 | # Finding the begining of the loop 18 | while (slow_p.next != fast_p.next): 19 | slow_p = slow_p.next 20 | fast_p = fast_p.next 21 | 22 | # Sinc fast.next is the looping point 23 | fast_p.next = None # Remove loop 24 | 25 | -------------------------------------------------------------------------------- /Python/Linked List/Remove duplicate element from sorted Linked List.py: -------------------------------------------------------------------------------- 1 | def removeDuplicates(head): 2 | #code here 3 | current=head 4 | while current.next!=None: 5 | if current.data==current.next.data: 6 | current.next=current.next.next 7 | 8 | else: 9 | current=current.next 10 | # current=current.next 11 | -------------------------------------------------------------------------------- /Python/Linked List/Remove duplicates from an unsorted linked list.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | #Function to remove duplicates from unsorted linked list. 3 | def removeDuplicates(self, head): 4 | # code here 5 | # return head after editing list 6 | d={} 7 | current=head 8 | prev=None 9 | while current!=None: 10 | if current.data in d: 11 | # print(current.data,d) 12 | prev.next=current.next 13 | current=current.next 14 | else: 15 | d[current.data]=1 16 | prev=current 17 | current=current.next 18 | return head 19 | 20 | -------------------------------------------------------------------------------- /Python/Strings/Longest Palindromic Substring.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def longestPalindrome(self, S: str) -> str: 3 | start=0 4 | maxLen=1 5 | for i in range(1,len(S)): 6 | #even 7 | l=i-1 8 | r=i 9 | print(l,r) 10 | while l>=0 and rmaxLen: 12 | maxLen=r-l+1 13 | start=l 14 | l-=1 15 | r+=1 16 | #odd 17 | l=i-1 18 | r=i+1 19 | while l>=0 and rmaxLen: 21 | maxLen=r-l+1 22 | start=l 23 | l-=1 24 | r+=1 25 | 26 | 27 | return S[start:start+maxLen] 28 | --------------------------------------------------------------------------------