code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
#include<iostream> #include<bits/stdc++.h> using namespace std; void merge(int arr1[], int arr2[], int n, int m) { int i=0; // while loop till last element of array 1(sorted) is greater than // first element of array 2(sorted) while(arr1[n-1]>arr2[0]) { if(arr1[i]>arr2[0]) { // swap arr1[i] with first element // of arr2 and sorting the updated // arr2(arr1 is already sorted) swap(arr1[i],arr2[0]); sort(arr2,arr2+m); } i++; } } int main() { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0; }
constant
linear
#include <bits/stdc++.h> using namespace std; void swap(int& a, int& b) { int temp = a; a = b; b = temp; } void rotate(int a[], int n, int idx) { int i; for (i = 0; i < idx / 2; i++) swap(a[i], a[idx - 1 - i]); for (i = idx; i < (n + idx) / 2; i++) swap(a[i], a[n - 1 - (i - idx)]); for (i = 0; i < n / 2; i++) swap(a[i], a[n - 1 - i]); } void sol(int a1[], int a2[], int n, int m) { int l = 0, h = n - 1, idx = 0; //--------------------------------------------------------- while (l <= h) { // select the median of the remaining subarray int c1 = (l + h) / 2; // select the first elements from the larger array // equal to the size of remaining portion to the // right of the smaller array int c2 = n - c1 - 1; int l1 = a1[c1]; int l2 = a2[c2 - 1]; int r1 = c1 == n - 1 ? INT_MAX : a1[c1 + 1]; int r2 = c2 == m ? INT_MAX : a2[c2]; // compare the border elements and check for the // target index if (l1 > r2) { h = c1 - 1; if (h == -1) idx = 0; } else if (l2 > r1) { l = c1 + 1; if (l == n - 1) idx = n; } else { idx = c1 + 1; break; } } for (int i = idx; i < n; i++) swap(a1[i], a2[i - idx]); sort(a1, a1 + n); sort(a2, a2 + m); } void merge(int arr1[], int arr2[], int n, int m) { // code here if (n > m) { sol(arr2, arr1, m, n); rotate(arr1, n, n - m); for (int i = 0; i < m; i++) swap(arr2[i], arr1[i]); } else { sol(arr1, arr2, n, m); } } int main() { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0; }
constant
nlogn
#include <bits/stdc++.h> using namespace std; void merge(int arr1[], int arr2[], int n, int m) { // two pointer to iterate int i = 0; int j = 0; while (i < n && j < m) { // if arr1[i] <= arr2[j] then both array is already // sorted if (arr1[i] <= arr2[j]) { i++; } else if (arr1[i] > arr2[j]) { // if arr1[i]>arr2[j] then first we swap both // element so that arr1[i] become smaller means // arr1[] become sorted then we check that // arr2[j] is smaller than all other element in // right side of arr2[j] if arr2[] is not sorted // then we linearly do sorting // means while adjacent element are less than // new arr2[j] we do sorting like by changing // position of element by shifting one position // toward left swap(arr1[i], arr2[j]); i++; if (j < m - 1 && arr2[j + 1] < arr2[j]) { int temp = arr2[j]; int tempj = j + 1; while (arr2[tempj] < temp && tempj < m) { arr2[tempj - 1] = arr2[tempj]; tempj++; } arr2[tempj - 1] = temp; } } } } int main() { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0; }
constant
quadratic
// C++ program to merge two sorted arrays without using extra space #include <bits/stdc++.h> using namespace std; void merge(int arr1[], int arr2[], int n, int m) { // three pointers to iterate int i = 0, j = 0, k = 0; // for euclid's division lemma int x = 10e7 + 1; // in this loop we are rearranging the elements of arr1 while (i < n && (j < n && k < m)) { // if both arr1 and arr2 elements are modified if (arr1[j] >= x && arr2[k] >= x) { if (arr1[j] % x <= arr2[k] % x) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if only arr1 elements are modified else if (arr1[j] >= x) { if (arr1[j] % x <= arr2[k]) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if only arr2 elements are modified else if (arr2[k] >= x) { if (arr1[j] <= arr2[k] % x) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } // if none elements are modified else { if (arr1[j] <= arr2[k]) { arr1[i] += (arr1[j++] % x) * x; } else { arr1[i] += (arr2[k++] % x) * x; } } i++; } // we can copy the elements directly as the other array // is exchausted while (j < n && i < n) { arr1[i++] += (arr1[j++] % x) * x; } while (k < m && i < n) { arr1[i++] += (arr2[k++] % x) * x; } // we need to reset i i = 0; // in this loop we are rearranging the elements of arr2 while (i < m && (j < n && k < m)) { // if both arr1 and arr2 elements are modified if (arr1[j] >= x && arr2[k] >= x) { if (arr1[j] % x <= arr2[k] % x) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } // if only arr1 elements are modified else if (arr1[j] >= x) { if (arr1[j] % x <= arr2[k]) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } // if only arr2 elements are modified else if (arr2[k] >= x) { if (arr1[j] <= arr2[k] % x) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } else { // if none elements are modified if (arr1[j] <= arr2[k]) { arr2[i] += (arr1[j++] % x) * x; } else { arr2[i] += (arr2[k++] % x) * x; } } i++; } // we can copy the elements directly as the other array // is exhausted while (j < n && i < m) { arr2[i++] += (arr1[j++] % x) * x; } while (k < m && i < m) { arr2[i++] += (arr2[k++] % x) * x; } // we need to reset i i = 0; // we need to divide the whole arr1 by x while (i < n) { arr1[i++] /= x; } // we need to reset i i = 0; // we need to divide the whole arr2 by x while (i < m) { arr2[i++] /= x; } } int main() { int ar1[] = { 1, 5, 9, 10, 15, 20 }; int ar2[] = { 2, 3, 8, 13 }; int m = sizeof(ar1) / sizeof(ar1[0]); int n = sizeof(ar2) / sizeof(ar2[0]); merge(ar1, ar2, m, n); cout << "After Merging \nFirst Array: "; for (int i = 0; i < m; i++) cout << ar1[i] << " "; cout << "\nSecond Array: "; for (int i = 0; i < n; i++) cout << ar2[i] << " "; return 0; } // This code is contributed by @ancientmoon8 (Mayank Kashyap)
constant
linear
// C++ program to calculate the // product of max element of // first array and min element // of second array #include <bits/stdc++.h> using namespace std; // Function to calculate // the product int minMaxProduct(int arr1[], int arr2[], int n1, int n2) { // Sort the arrays to find // the maximum and minimum // elements in given arrays sort(arr1, arr1 + n1); sort(arr2, arr2 + n2); // Return product of // maximum and minimum. return arr1[n1 - 1] * arr2[0]; } // Driven code int main() { int arr1[] = { 10, 2, 3, 6, 4, 1 }; int arr2[] = { 5, 1, 4, 2, 6, 9 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr1) / sizeof(arr1[0]); cout << minMaxProduct(arr1, arr2, n1, n2); return 0; }
constant
nlogn
// C++ program to find the to // calculate the product of // max element of first array // and min element of second array #include <bits/stdc++.h> using namespace std; // Function to calculate the product int minMaxProduct(int arr1[], int arr2[], int n1, int n2) { // Initialize max of first array int max = arr1[0]; // initialize min of second array int min = arr2[0]; int i; for (i = 1; i < n1 && i < n2; ++i) { // To find the maximum // element in first array if (arr1[i] > max) max = arr1[i]; // To find the minimum // element in second array if (arr2[i] < min) min = arr2[i]; } // Process remaining elements while (i < n1) { if (arr1[i] > max) max = arr1[i]; i++; } while (i < n2) { if (arr2[i] < min) min = arr2[i]; i++; } return max * min; } // Driven code int main() { int arr1[] = { 10, 2, 3, 6, 4, 1 }; int arr2[] = { 5, 1, 4, 2, 6, 9 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr1) / sizeof(arr1[0]); cout << minMaxProduct(arr1, arr2, n1, n2) << endl; return 0; }
constant
linear
// C++ program to implement linear // search in unsorted array #include <bits/stdc++.h> using namespace std; // Function to implement search operation int findElement(int arr[], int n, int key) { int i; for (i = 0; i < n; i++) if (arr[i] == key) return i; // If the key is not found return -1; } // Driver's Code int main() { int arr[] = { 12, 34, 10, 6, 40 }; int n = sizeof(arr) / sizeof(arr[0]); // Using a last element as search element int key = 40; // Function call int position = findElement(arr, n, key); if (position == -1) cout << "Element not found"; else cout << "Element Found at Position: " << position + 1; return 0; } // This code is contributed // by Akanksha Rai
constant
linear
// C++ program to implement insert // operation in an unsorted array. #include <iostream> using namespace std; // Inserts a key in arr[] of given capacity. // n is current size of arr[]. This // function returns n + 1 if insertion // is successful, else n. int insertSorted(int arr[], int n, int key, int capacity) { // Cannot insert more elements if n is // already more than or equal to capacity if (n >= capacity) return n; arr[n] = key; return (n + 1); } // Driver Code int main() { int arr[20] = { 12, 16, 20, 40, 50, 70 }; int capacity = sizeof(arr) / sizeof(arr[0]); int n = 6; int i, key = 26; cout << "\n Before Insertion: "; for (i = 0; i < n; i++) cout << arr[i] << " "; // Inserting key n = insertSorted(arr, n, key, capacity); cout << "\n After Insertion: "; for (i = 0; i < n; i++) cout << arr[i] << " "; return 0; } // This code is contributed by SHUBHAMSINGH10
constant
constant
// C Program to Insert an element // at a specific position in an Array #include <bits/stdc++.h> using namespace std; // Function to insert element // at a specific position void insertElement(int arr[], int n, int x, int pos) { // shift elements to the right // which are on the right side of pos for (int i = n - 1; i >= pos; i--) arr[i + 1] = arr[i]; arr[pos] = x; } // Driver's code int main() { int arr[15] = { 2, 4, 1, 8, 5 }; int n = 5; cout<<"Before insertion : "; for (int i = 0; i < n; i++) cout<<arr[i]<<" "; cout<<endl; int x = 10, pos = 2; // Function call insertElement(arr, n, x, pos); n++; cout<<"After insertion : "; for (int i = 0; i < n; i++) cout<<arr[i]<<" "; return 0; }
constant
linear
// C++ program to implement delete operation in a // unsorted array #include <iostream> using namespace std; // To search a key to be deleted int findElement(int arr[], int n, int key); // Function to delete an element int deleteElement(int arr[], int n, int key) { // Find position of element to be deleted int pos = findElement(arr, n, key); if (pos == -1) { cout << "Element not found"; return n; } // Deleting element int i; for (i = pos; i < n - 1; i++) arr[i] = arr[i + 1]; return n - 1; } // Function to implement search operation int findElement(int arr[], int n, int key) { int i; for (i = 0; i < n; i++) if (arr[i] == key) return i; return -1; } // Driver's code int main() { int i; int arr[] = { 10, 50, 30, 40, 20 }; int n = sizeof(arr) / sizeof(arr[0]); int key = 30; cout << "Array before deletion\n"; for (i = 0; i < n; i++) cout << arr[i] << " "; // Function call n = deleteElement(arr, n, key); cout << "\n\nArray after deletion\n"; for (i = 0; i < n; i++) cout << arr[i] << " "; return 0; } // This code is contributed by shubhamsingh10
constant
linear
// C++ program to implement binary search in sorted array #include <bits/stdc++.h> using namespace std; int binarySearch(int arr[], int low, int high, int key) { if (high < low) return -1; int mid = (low + high) / 2; /*low + (high - low)/2;*/ if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid - 1), key); } /* Driver code */ int main() { // Let us search 3 in below array int arr[] = { 5, 6, 7, 8, 9, 10 }; int n, key; n = sizeof(arr) / sizeof(arr[0]); key = 10; // Function call cout << "Index: " << binarySearch(arr, 0, n - 1, key) << endl; return 0; } // This code is contributed by NamrataSrivastava1
logn
logn
// C++ program to implement insert operation in // an sorted array. #include <bits/stdc++.h> using namespace std; // Inserts a key in arr[] of given capacity. n is current // size of arr[]. This function returns n+1 if insertion // is successful, else n. int insertSorted(int arr[], int n, int key, int capacity) { // Cannot insert more elements if n is already // more than or equal to capacity if (n >= capacity) return n; int i; for (i = n - 1; (i >= 0 && arr[i] > key); i--) arr[i + 1] = arr[i]; arr[i + 1] = key; return (n + 1); } /* Driver code */ int main() { int arr[20] = { 12, 16, 20, 40, 50, 70 }; int capacity = sizeof(arr) / sizeof(arr[0]); int n = 6; int i, key = 26; cout << "\nBefore Insertion: "; for (i = 0; i < n; i++) cout << arr[i] << " "; // Function call n = insertSorted(arr, n, key, capacity); cout << "\nAfter Insertion: "; for (i = 0; i < n; i++) cout << arr[i] << " "; return 0; } // This code is contributed by SHUBHAMSINGH10
constant
linear
// C++ program to implement delete operation in a // sorted array #include <bits/stdc++.h> using namespace std; // To search a key to be deleted int binarySearch(int arr[], int low, int high, int key); /* Function to delete an element */ int deleteElement(int arr[], int n, int key) { // Find position of element to be deleted int pos = binarySearch(arr, 0, n - 1, key); if (pos == -1) { cout << "Element not found"; return n; } // Deleting element int i; for (i = pos; i < n - 1; i++) arr[i] = arr[i + 1]; return n - 1; } int binarySearch(int arr[], int low, int high, int key) { if (high < low) return -1; int mid = (low + high) / 2; if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid - 1), key); } // Driver code int main() { int i; int arr[] = { 10, 20, 30, 40, 50 }; int n = sizeof(arr) / sizeof(arr[0]); int key = 30; cout << "Array before deletion\n"; for (i = 0; i < n; i++) cout << arr[i] << " "; // Function call n = deleteElement(arr, n, key); cout << "\n\nArray after deletion\n"; for (i = 0; i < n; i++) cout << arr[i] << " "; } // This code is contributed by shubhamsingh10
logn
linear
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find and print pair bool chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { return 1; } } } return 0; } // Driver code int main() { int A[] = { 0, -1, 2, -3, 1 }; int x = -2; int size = sizeof(A) / sizeof(A[0]); if (chkPair(A, size, x)) { cout << "Yes" << endl; } else { cout << "No" << x << endl; } return 0; } // This code is contributed by Samim Hossain Mondal.
constant
quadratic
// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include <bits/stdc++.h> using namespace std; // Function to check if array has 2 elements // whose sum is equal to the given value bool hasArrayTwoCandidates(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, A + arr_size); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[l] + A[r] > sum r--; } return 0; } /* Driver program to test above function */ int main() { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (hasArrayTwoCandidates(A, arr_size, n)) cout << "Yes"; else cout << "No"; return 0; }
constant
nlogn
// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include <bits/stdc++.h> using namespace std; bool binarySearch(int A[], int low, int high, int searchKey) { while (low <= high) { int m = low + (high - low) / 2; // Check if searchKey is present at mid if (A[m] == searchKey) return true; // If searchKey greater, ignore left half if (A[m] < searchKey) low = m + 1; // If searchKey is smaller, ignore right half else high = m - 1; } // if we reach here, then element was // not present return false; } bool checkTwoSum(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, A + arr_size); // Traversing all element in an array search for // searchKey for (int i = 0; i < arr_size - 1; i++) { int searchKey = sum - A[i]; // calling binarySearch function if (binarySearch(A, i + 1, arr_size - 1, searchKey) == true) { return true; } } return false; } /* Driver program to test above function */ int main() { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 14; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (checkTwoSum(A, arr_size, n)) cout << "Yes"; else cout << "No"; return 0; }
constant
nlogn
// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include <bits/stdc++.h> using namespace std; void printPairs(int arr[], int arr_size, int sum) { unordered_set<int> s; for (int i = 0; i < arr_size; i++) { int temp = sum - arr[i]; if (s.find(temp) != s.end()) { cout << "Yes" << endl; return; } s.insert(arr[i]); } cout << "No" << endl; } /* Driver Code */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0; }
linear
linear
// Code in cpp to tell if there exists a pair in array whose // sum results in x. #include <iostream> using namespace std; // Function to print pairs void printPairs(int a[], int n, int x) { int i; int rem[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if the element // is x, as numbers greater than x can't be used to get // a sum x. Updating the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i will // result to a sum of x. Once we get two // elements which add up to x , we print x and // break. cout << "Yes\n"; break; } } // Once we reach middle of remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 elements // with remainder x/2, then we will have two // distinct elements which add up to x. if we // dont have more than 1 element, print "No". if (rem[x / 2] > 1) cout << "Yes\n"; else cout << "No\n"; } else { // When x is odd we continue the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) cout << "Yes\n"; else cout << "No\n"; } } } /* Driver Code */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
linear
linear
// C++ program to search an element in an array // where difference between adjacent elements is atmost k #include<bits/stdc++.h> using namespace std; // x is the element to be searched in arr[0..n-1] // such that all elements differ by at-most k. int search(int arr[], int n, int x, int k) { // Traverse the given array starting from // leftmost element int i = 0; while (i < n) { // If x is found at index i if (arr[i] == x) return i; // Jump the difference between current // array element and x divided by k // We use max here to make sure that i // moves at-least one step ahead. i = i + max(1, abs(arr[i]-x)/k); } cout << "number is not present!"; return -1; } // Driver program to test above function int main() { int arr[] = {2, 4, 5, 7, 7, 6}; int x = 6; int k = 2; int n = sizeof(arr)/sizeof(arr[0]); cout << "Element " << x << " is present at index " << search(arr, n, x, k); return 0; }
constant
linear
// C++ program to print common elements in three arrays #include <bits/stdc++.h> using namespace std; // This function prints common elements in ar1 void findCommon(int ar1[], int ar2[], int ar3[], int n1, int n2, int n3) { // Initialize starting indexes for ar1[], ar2[] and // ar3[] int i = 0, j = 0, k = 0; // Iterate through three arrays while all arrays have // elements while (i < n1 && j < n2 && k < n3) { // If x = y and y = z, print any of them and move // ahead in all arrays if (ar1[i] == ar2[j] && ar2[j] == ar3[k]) { cout << ar1[i] << " "; i++; j++; k++; } // x < y else if (ar1[i] < ar2[j]) i++; // y < z else if (ar2[j] < ar3[k]) j++; // We reach here when x > y and z < y, i.e., z is // smallest else k++; } } // Driver code int main() { int ar1[] = { 1, 5, 10, 20, 40, 80 }; int ar2[] = { 6, 7, 20, 80, 100 }; int ar3[] = { 3, 4, 15, 20, 30, 70, 80, 120 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); int n3 = sizeof(ar3) / sizeof(ar3[0]); cout << "Common Elements are "; findCommon(ar1, ar2, ar3, n1, n2, n3); return 0; } // This code is contributed by Sania Kumari Gupta (kriSania804)
constant
linear
// C++ program to print common elements in three arrays #include <bits/stdc++.h> using namespace std; // This function prints common elements in ar1 void findCommon(int ar1[], int ar2[], int ar3[], int n1, int n2, int n3) { // Initialize starting indexes for ar1[], ar2[] and ar3[] int i = 0, j = 0, k = 0; // Declare three variables prev1, prev2, prev3 to track // previous element int prev1, prev2, prev3; // Initialize prev1, prev2, prev3 with INT_MIN prev1 = prev2 = prev3 = INT_MIN; // Iterate through three arrays while all arrays have // elements while (i < n1 && j < n2 && k < n3) { // If ar1[i] = prev1 and i < n1, keep incrementing i while (ar1[i] == prev1 && i < n1) i++; // If ar2[j] = prev2 and j < n2, keep incrementing j while (ar2[j] == prev2 && j < n2) j++; // If ar3[k] = prev3 and k < n3, keep incrementing k while (ar3[k] == prev3 && k < n3) k++; // If x = y and y = z, print any of them, update // prev1 prev2, prev3 and move ahead in each array if (ar1[i] == ar2[j] && ar2[j] == ar3[k]) { cout << ar1[i] << " "; prev1 = ar1[i++]; prev2 = ar2[j++]; prev3 = ar3[k++]; } // If x < y, update prev1 and increment i else if (ar1[i] < ar2[j]) prev1 = ar1[i++]; // If y < z, update prev2 and increment j else if (ar2[j] < ar3[k]) prev2 = ar2[j++]; // We reach here when x > y and z < y, i.e., z is // smallest update prev3 and increment k else prev3 = ar3[k++]; } } // Driver code int main() { int ar1[] = { 1, 5, 10, 20, 40, 80, 80 }; int ar2[] = { 6, 7, 20, 80, 80, 100 }; int ar3[] = { 3, 4, 15, 20, 30, 70, 80, 80, 120 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); int n3 = sizeof(ar3) / sizeof(ar3[0]); cout << "Common Elements are "; findCommon(ar1, ar2, ar3, n1, n2, n3); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
linear
#include <bits/stdc++.h> using namespace std; void findCommon(int a[], int b[], int c[], int n1, int n2, int n3) { // three sets to maintain frequency of elements unordered_set<int> uset, uset2, uset3; for (int i = 0; i < n1; i++) { uset.insert(a[i]); } for (int i = 0; i < n2; i++) { uset2.insert(b[i]); } // checking if elements of 3rd array are present in // first 2 sets for (int i = 0; i < n3; i++) { if (uset.find(c[i]) != uset.end() && uset2.find(c[i]) != uset.end()) { // using a 3rd set to prevent duplicates if (uset3.find(c[i]) == uset3.end()) cout << c[i] << " "; uset3.insert(c[i]); } } } // Driver code int main() { int ar1[] = { 1, 5, 10, 20, 40, 80 }; int ar2[] = { 6, 7, 20, 80, 100 }; int ar3[] = { 3, 4, 15, 20, 30, 70, 80, 120 }; int n1 = sizeof(ar1) / sizeof(ar1[0]); int n2 = sizeof(ar2) / sizeof(ar2[0]); int n3 = sizeof(ar3) / sizeof(ar3[0]); cout << "Common Elements are " << endl; findCommon(ar1, ar2, ar3, n1, n2, n3); return 0; }
linear
linear
// C++ program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (arr[i] == arr[j]) return arr[i]; } } } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; } // This code is added by Arpit Jain
constant
quadratic
// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { sort(arr, arr + N); // sort array for (int i = 0; i < N; i++) { // compare array element with its index if (arr[i] != i + 1) { return arr[i]; } } return -1; } // driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; } // this code is contributed by devendra solunke
constant
nlogn
// C++ program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { unordered_set<int> s; for (int i = 0; i < N; i++) { if (s.find(arr[i]) != s.end()) return arr[i]; s.insert(arr[i]); } // If input is correct, we should // never reach here return -1; } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }
linear
linear
// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { // Find array sum and subtract sum // first N-1 natural numbers from it // to find the result. return accumulate(arr, arr + N, 0) - ((N - 1) * N / 2); } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }
constant
linear
// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (N-1) ^ arr[0] ^ // arr[1] ^ .... arr[N-1] int res = 0; for (int i = 0; i < N - 1; i++) res = res ^ (i + 1) ^ arr[i]; res = res ^ arr[N - 1]; return res; } // Driver code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }
constant
linear
// CPP program to find the only // repeating element in an array // where elements are from 1 to N-1. #include <bits/stdc++.h> using namespace std; // Function to find repeated element int findRepeating(int arr[], int N) { int missingElement = 0; // indexing based for (int i = 0; i < N; i++) { int element = arr[abs(arr[i])]; if (element < 0) { missingElement = arr[i]; break; } arr[abs(arr[i])] = -arr[abs(arr[i])]; } return abs(missingElement); } // Driver code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }
constant
linear
#include <bits/stdc++.h> using namespace std; int findDuplicate(vector<int>& nums) { int slow = nums[0]; int fast = nums[0]; do { slow = nums[slow]; fast = nums[nums[fast]]; } while (slow != fast); fast = nums[0]; while (slow != fast) { slow = nums[slow]; fast = nums[fast]; } return slow; } // Driver code int main() { vector<int> v{ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; // Function call int ans = findDuplicate(v); cout << ans << endl; return 0; }
constant
linear
// C++ program to find the array element // that appears only once #include <iostream> using namespace std; // Function to find the int findSingle(int A[], int ar_size) { // Iterate over every element for (int i = 0; i < ar_size; i++) { // Initialize count to 0 int count = 0; for (int j = 0; j < ar_size; j++) { // Count the frequency // of the element if (A[i] == A[j]) { count++; } } // if the frequency of the // element is one if (count == 1) { return A[i]; } } // if no element exist at most once return -1; } // Driver code int main() { int ar[] = { 2, 3, 5, 4, 5, 3, 4 }; int n = sizeof(ar) / sizeof(ar[0]); // Function call cout << "Element occurring once is " << findSingle(ar, n); return 0; } // This code is contributed by Arpit Jain
constant
quadratic
// C++ program to find the array element // that appears only once #include <iostream> using namespace std; int findSingle(int ar[], int ar_size) { // Do XOR of all elements and return int res = ar[0]; for (int i = 1; i < ar_size; i++) res = res ^ ar[i]; return res; } // Driver code int main() { int ar[] = { 2, 3, 5, 4, 5, 3, 4 }; int n = sizeof(ar) / sizeof(ar[0]); cout << "Element occurring once is " << findSingle(ar, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
linear
// C++ program to find // element that appears once #include <bits/stdc++.h> using namespace std; // function which find number int singleNumber(int nums[],int n) { map<int,int> m; long sum1 = 0,sum2 = 0; for(int i = 0; i < n; i++) { if(m[nums[i]] == 0) { sum1 += nums[i]; m[nums[i]]++; } sum2 += nums[i]; } // applying the formula. return 2 * (sum1) - sum2; } // Driver code int main() { int a[] = {2, 3, 5, 4, 5, 3, 4}; int n = 7; cout << singleNumber(a,n) << "\n"; int b[] = {15, 18, 16, 18, 16, 15, 89}; cout << singleNumber(b,n); return 0; } // This code is contributed by mohit kumar 29
linear
nlogn
#include <bits/stdc++.h> using namespace std; int singleelement(int arr[], int n) { int low = 0, high = n - 2; int mid; while (low <= high) { mid = (low + high) / 2; if (arr[mid] == arr[mid ^ 1]) low = mid + 1; else high = mid - 1; } return arr[low]; } int main() { int arr[] = { 2, 3, 5, 4, 5, 3, 4 }; int size = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + size); cout << singleelement(arr, size); return 0; } // This code is contributed by Sania Kumari Gupta
constant
nlogn
// C++ Program to find max subarray // sum excluding some elements #include <bits/stdc++.h> using namespace std; // Function to check the element // present in array B bool isPresent(int B[], int m, int x) { for (int i = 0; i < m; i++) if (B[i] == x) return true; return false; } // Utility function for findMaxSubarraySum() // with the following parameters // A => Array A, // B => Array B, // n => Number of elements in Array A, // m => Number of elements in Array B int findMaxSubarraySumUtil(int A[], int B[], int n, int m) { // set max_so_far to INT_MIN int max_so_far = INT_MIN, curr_max = 0; for (int i = 0; i < n; i++) { // if the element is present in B, // set current max to 0 and move to // the next element */ if (isPresent(B, m, A[i])) { curr_max = 0; continue; } // Proceed as in Kadane's Algorithm curr_max = max(A[i], curr_max + A[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far; } // Wrapper for findMaxSubarraySumUtil() void findMaxSubarraySum(int A[], int B[], int n, int m) { int maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m); // This case will occur when all elements // of A are present in B, thus // no subarray can be formed if (maxSubarraySum == INT_MIN) { cout << "Maximum Subarray Sum cant be found" << endl; } else { cout << "The Maximum Subarray Sum = " << maxSubarraySum << endl; } } // Driver Code int main() { int A[] = { 3, 4, 5, -4, 6 }; int B[] = { 1, 8, 5 }; int n = sizeof(A) / sizeof(A[0]); int m = sizeof(B) / sizeof(B[0]); // Function call findMaxSubarraySum(A, B, n, m); return 0; }
constant
quadratic
// C++ Program to find max subarray // sum excluding some elements #include <bits/stdc++.h> using namespace std; // Utility function for findMaxSubarraySum() // with the following parameters // A => Array A, // B => Array B, // n => Number of elements in Array A, // m => Number of elements in Array B int findMaxSubarraySumUtil(int A[], int B[], int n, int m) { // set max_so_far to INT_MIN int max_so_far = INT_MIN, curr_max = 0; for (int i = 0; i < n; i++) { // if the element is present in B, // set current max to 0 and move to // the next element if (binary_search(B, B + m, A[i])) { curr_max = 0; continue; } // Proceed as in Kadane's Algorithm curr_max = max(A[i], curr_max + A[i]); max_so_far = max(max_so_far, curr_max); } return max_so_far; } // Wrapper for findMaxSubarraySumUtil() void findMaxSubarraySum(int A[], int B[], int n, int m) { // sort array B to apply Binary Search sort(B, B + m); int maxSubarraySum = findMaxSubarraySumUtil(A, B, n, m); // This case will occur when all elements // of A are present in B, thus no subarray // can be formed if (maxSubarraySum == INT_MIN) { cout << "Maximum subarray sum cant be found" << endl; } else { cout << "The Maximum subarray sum = " << maxSubarraySum << endl; } } // Driver Code int main() { int A[] = { 3, 4, 5, -4, 6 }; int B[] = { 1, 8, 5 }; int n = sizeof(A) / sizeof(A[0]); int m = sizeof(B) / sizeof(B[0]); // Function call findMaxSubarraySum(A, B, n, m); return 0; }
constant
nlogn
// C++ Program implementation of the // above idea #include<bits/stdc++.h> using namespace std; // Function to calculate the max sum of contiguous // subarray of B whose elements are not present in A int findMaxSubarraySum(vector<int> A,vector<int> B) { unordered_map<int,int> m; // mark all the elements present in B for(int i=0;i<B.size();i++) { m[B[i]]=1; } // initialize max_so_far with INT_MIN int max_so_far=INT_MIN; int currmax=0; // traverse the array A for(int i=0;i<A.size();i++) { if(currmax<0 || m[A[i]]==1) { currmax=0; continue; } currmax=max(A[i],A[i]+currmax); // if current max is greater than // max so far then update max so far if(max_so_far<currmax) { max_so_far=currmax; } } return max_so_far; } // Driver Code int main() { vector<int> a = { 3, 4, 5, -4, 6 }; vector<int> b = { 1, 8, 5 }; // Function call cout << findMaxSubarraySum(a,b); return 0; } //This code is contributed by G.Vivek
linear
linear
// CPP program to find // maximum equilibrium sum. #include <bits/stdc++.h> using namespace std; // Function to find // maximum equilibrium sum. int findMaxSum(int arr[], int n) { int res = INT_MIN; for (int i = 0; i < n; i++) { int prefix_sum = arr[i]; for (int j = 0; j < i; j++) prefix_sum += arr[j]; int suffix_sum = arr[i]; for (int j = n - 1; j > i; j--) suffix_sum += arr[j]; if (prefix_sum == suffix_sum) res = max(res, prefix_sum); } return res; } // Driver Code int main() { int arr[] = {-2, 5, 3, 1, 2, 6, -4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxSum(arr, n); return 0; }
linear
quadratic
// CPP program to find // maximum equilibrium sum. #include <bits/stdc++.h> using namespace std; // Function to find maximum // equilibrium sum. int findMaxSum(int arr[], int n) { // Array to store prefix sum. int preSum[n]; // Array to store suffix sum. int suffSum[n]; // Variable to store maximum sum. int ans = INT_MIN; // Calculate prefix sum. preSum[0] = arr[0]; for (int i = 1; i < n; i++) preSum[i] = preSum[i - 1] + arr[i]; // Calculate suffix sum and compare // it with prefix sum. Update ans // accordingly. suffSum[n - 1] = arr[n - 1]; if (preSum[n - 1] == suffSum[n - 1]) ans = max(ans, preSum[n - 1]); for (int i = n - 2; i >= 0; i--) { suffSum[i] = suffSum[i + 1] + arr[i]; if (suffSum[i] == preSum[i]) ans = max(ans, preSum[i]); } return ans; } // Driver Code int main() { int arr[] = { -2, 5, 3, 1, 2, 6, -4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxSum(arr, n); return 0; }
linear
linear
// CPP program to find // maximum equilibrium sum. #include <bits/stdc++.h> using namespace std; // Function to find // maximum equilibrium sum. int findMaxSum(int arr[], int n) { int sum = accumulate(arr, arr + n, 0); int prefix_sum = 0, res = INT_MIN; for (int i = 0; i < n; i++) { prefix_sum += arr[i]; if (prefix_sum == sum) res = max(res, prefix_sum); sum -= arr[i]; } return res; } // Driver Code int main() { int arr[] = { -2, 5, 3, 1, 2, 6, -4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxSum(arr, n); return 0; }
constant
linear
// C++ program to find equilibrium // index of an array #include <bits/stdc++.h> using namespace std; int equilibrium(int arr[], int n) { int i, j; int leftsum, rightsum; /* Check for indexes one by one until an equilibrium index is found */ for (i = 0; i < n; ++i) { /* get left sum */ leftsum = 0; for (j = 0; j < i; j++) leftsum += arr[j]; /* get right sum */ rightsum = 0; for (j = i + 1; j < n; j++) rightsum += arr[j]; /* if leftsum and rightsum are same, then we are done */ if (leftsum == rightsum) return i; } /* return -1 if no equilibrium index is found */ return -1; } // Driver code int main() { int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); // Function call cout << equilibrium(arr, arr_size); return 0; } // This code is contributed // by Akanksha Rai(Abby_akku)
constant
quadratic
// C++ program to find equilibrium // index of an array #include <bits/stdc++.h> using namespace std; int equilibrium(int arr[], int n) { int sum = 0; // initialize sum of whole array int leftsum = 0; // initialize leftsum /* Find sum of the whole array */ for (int i = 0; i < n; ++i) sum += arr[i]; for (int i = 0; i < n; ++i) { sum -= arr[i]; // sum is now right sum for index i if (leftsum == sum) return i; leftsum += arr[i]; } /* If no equilibrium index found, then return 0 */ return -1; } // Driver code int main() { int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int arr_size = sizeof(arr) / sizeof(arr[0]); // Function call cout << "First equilibrium index is " << equilibrium(arr, arr_size); return 0; } // This is code is contributed by rathbhupendra
constant
linear
// C++ program to find equilibrium index of an array #include <bits/stdc++.h> using namespace std; int equilibrium(int a[], int n) { if (n == 1) return (0); int forward[n] = { 0 }; int rev[n] = { 0 }; // Taking the prefixsum from front end array for (int i = 0; i < n; i++) { if (i) { forward[i] = forward[i - 1] + a[i]; } else { forward[i] = a[i]; } } // Taking the prefixsum from back end of array for (int i = n - 1; i > 0; i--) { if (i <= n - 2) { rev[i] = rev[i + 1] + a[i]; } else { rev[i] = a[i]; } } // Checking if forward prefix sum // is equal to rev prefix // sum for (int i = 0; i < n; i++) { if (forward[i] == rev[i]) { return i; } } return -1; // If You want all the points // of equilibrium create // vector and push all equilibrium // points in it and // return the vector } // Driver code int main() { int arr[] = { -7, 1, 5, 2, -4, 3, 0 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << "First Point of equilibrium is at index " << equilibrium(arr, n) << "\n"; return 0; }
linear
linear
#include<iostream> using namespace std; /*C++ Function to print leaders in an array */ void printLeaders(int arr[], int size) { for (int i = 0; i < size; i++) { int j; for (j = i+1; j < size; j++) { if (arr[i] <=arr[j]) break; } if (j == size) // the loop didn't break cout << arr[i] << " "; } } /* Driver program to test above function */ int main() { int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0; }
constant
quadratic
#include <iostream> using namespace std; /* C++ Function to print leaders in an array */ void printLeaders(int arr[], int size) { int max_from_right = arr[size-1]; /* Rightmost element is always leader */ cout << max_from_right << " "; for (int i = size-2; i >= 0; i--) { if (max_from_right < arr[i]) { max_from_right = arr[i]; cout << max_from_right << " "; } } } /* Driver program to test above function*/ int main() { int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0; }
constant
linear
#include <bits/stdc++.h> using namespace std; /* C++ Function to print leaders in an array */ void printLeaders(int arr[], int size) { /* create stack to store leaders*/ stack<int> sk; sk.push(arr[size-1]); for (int i = size-2; i >= 0; i--) { if(arr[i] >= sk.top()) { sk.push(arr[i]); } } /* print stack elements*/ /* run loop till stack is not empty*/ while(!sk.empty()){ cout<<sk.top()<<" "; sk.pop(); } } /* Driver program to test above function*/ int main() { int arr[] = {16, 17, 4, 3, 5, 2}; int n = sizeof(arr)/sizeof(arr[0]); printLeaders(arr, n); return 0; }
linear
linear
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std; /* Function to get index of ceiling of x in arr[low..high] */ int ceilSearch(int arr[], int low, int high, int x) { int i; /* If x is smaller than or equal to first element, then return the first element */ if(x <= arr[low]) return low; /* Otherwise, linearly search for ceil value */ for(i = low; i < high; i++) { if(arr[i] == x) return i; /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */ if(arr[i] < x && arr[i+1] >= x) return i+1; } /* If we reach here then x is greater than the last element of the array, return -1 in this case */ return -1; } /* Driver code*/ int main() { int arr[] = {1, 2, 8, 10, 10, 12, 19}; int n = sizeof(arr)/sizeof(arr[0]); int x = 3; int index = ceilSearch(arr, 0, n-1, x); if(index == -1) cout << "Ceiling of " << x << " doesn't exist in array "; else cout << "ceiling of " << x << " is " << arr[index]; return 0; } // This is code is contributed by rathbhupendra
constant
linear
#include <bits/stdc++.h> using namespace std; /* Function to get index of ceiling of x in arr[low..high]*/ int ceilSearch(int arr[], int low, int high, int x) { int mid; /* If x is smaller than or equal to the first element, then return the first element */ if (x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if (x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high) / 2; /* low + (high - low)/2 */ /* If x is same as middle element, then return mid */ if (arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if (arr[mid] < x) { if (mid + 1 <= high && x <= arr[mid + 1]) return mid + 1; else return ceilSearch(arr, mid + 1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[low...mid-1] */ else { if (mid - 1 >= low && x > arr[mid - 1]) return mid; else return ceilSearch(arr, low, mid - 1, x); } } // Driver Code int main() { int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 20; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) cout << "Ceiling of " << x << " doesn't exist in array "; else cout << "ceiling of " << x << " is " << arr[index]; return 0; } // This code is contributed by rathbhupendra
constant
logn
#include <bits/stdc++.h> using namespace std; /* Function to get index of ceiling of x in arr[low..high]*/ int ceilSearch(int arr[], int low, int high, int x) { // base condition if length of arr == 0 then return -1 if (x == 0) { return -1; } int mid; // this while loop function will run until condition not // break once condition break loop will return start and // ans is low which will be next smallest greater than // target which is ceiling while (low <= high) { mid = low + (high - low) / 2; if (arr[mid] == x) return mid; else if (x < arr[mid]) high = mid - 1; else low = mid + 1; } return low; } /* step 1 : { low = 1, 2, 8, 10= mid, 10, 12, 19= high}; if( x < mid) yes set high = mid -1; step 2 : { low = 1, 2 = mid, 8 = high, 10, 10, 12, 19}; if( x < mid) no set low = mid + 1; step 3 : {1, 2, 8 = high,low,low, 10, 10, 12, 19}; if( x == mid ) yes return mid if(x < mid ) no low = mid + 1 step 4 : {1, 2, 8 = high,mid, 10 = low, 10, 12, 19}; check while(low < = high) condition break and return low which will next greater of target */ /* Driver program to check above functions */ int main() { int arr[] = { 1, 2, 8, 10, 10, 12, 19 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 8; int index = ceilSearch(arr, 0, n - 1, x); if (index == -1) printf("Ceiling of %d does not exist in an array", x); else printf("Ceiling of %d is %d", x, arr[index]); return 0; }
constant
logn
// Hashing based C++ program to find if there // is a majority element in input array. #include <bits/stdc++.h> using namespace std; // Returns true if there is a majority element // in a[] bool isMajority(int a[], int n) { // Insert all elements in a hash table unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[a[i]]++; // Check if frequency of any element is // n/2 or more. for (auto x : mp) if (x.second >= n/2) return true; return false; } // Driver code int main() { int a[] = { 2, 3, 9, 2, 2 }; int n = sizeof(a) / sizeof(a[0]); if (isMajority(a, n)) cout << "Yes"; else cout << "No"; return 0; }
linear
linear
// A C++ program to find a peak element // using divide and conquer #include <bits/stdc++.h> using namespace std; // A binary search based function // that returns index of a peak element int findPeakUtil(int arr[], int low, int high, int n) { // Find index of middle element // low + (high - low) / 2 int mid = low + (high - low) / 2; // Compare middle element with its // neighbours (if neighbours exist) if ((mid == 0 || arr[mid - 1] <= arr[mid]) && (mid == n - 1 || arr[mid + 1] <= arr[mid])) return mid; // If middle element is not peak and its // left neighbour is greater than it, // then left half must have a peak element else if (mid > 0 && arr[mid - 1] > arr[mid]) return findPeakUtil(arr, low, (mid - 1), n); // If middle element is not peak and its // right neighbour is greater than it, // then right half must have a peak element else return findPeakUtil( arr, (mid + 1), high, n); } // A wrapper over recursive function findPeakUtil() int findPeak(int arr[], int n) { return findPeakUtil(arr, 0, n - 1, n); } // Driver Code int main() { int arr[] = { 1, 3, 20, 4, 1, 0 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Index of a peak point is " << findPeak(arr, n); return 0; } // This code is contributed by rajdeep999
logn
logn
// A C++ program to find a peak element // using divide and conquer #include <bits/stdc++.h> using namespace std; // A binary search based function // that returns index of a peak element int findPeak(int arr[], int n) { int l = 0; int r = n-1; int mid; while (l <= r) { // finding mid by binary right shifting. mid = (l + r) >> 1; // first case if mid is the answer if ((mid == 0 || arr[mid - 1] <= arr[mid]) and (mid == n - 1 || arr[mid + 1] <= arr[mid])) break; // move the right pointer if (mid > 0 and arr[mid - 1] > arr[mid]) r = mid - 1; // move the left pointer else l = mid + 1; } return mid; } // Driver Code int main() { int arr[] = { 1, 3, 20, 4, 1, 0 }; int N = sizeof(arr) / sizeof(arr[0]); cout << "Index of a peak point is " << findPeak(arr, N); return 0; } // This code is contributed by Rajdeep Mallick (rajdeep999)
constant
logn
// C++ program to Find the two repeating // elements in a given array #include <bits/stdc++.h> using namespace std; void printTwoRepeatNumber(int arr[], int size) { int i, j; cout << "Repeating elements are "; for (i = 0; i < size; i++) { for (j = i + 1; j < size; j++) { if (arr[i] == arr[j]) { cout << arr[i] << " "; break; } } } } int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printTwoRepeatNumber(arr, arr_size); return 0; }
constant
quadratic
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std; void printRepeating(int arr[], int size) { int* count = new int[sizeof(int) * (size - 2)]; int i; cout << " Repeating elements are "; for (i = 0; i < size; i++) { if (count[arr[i]] == 1) cout << arr[i] << " "; else count[arr[i]]++; } } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This is code is contributed by rathbhupendra
linear
linear
#include <bits/stdc++.h> using namespace std; /* function to get factorial of n */ int fact(int n); void printRepeating(int arr[], int size) { int S = 0; /* S is for sum of elements in arr[] */ int P = 1; /* P is for product of elements in arr[] */ int x, y; /* x and y are two repeating elements */ int D; /* D is for difference of x and y, i.e., x-y*/ int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for (i = 0; i < size; i++) { S = S + arr[i]; P = P * arr[i]; } S = S - n * (n + 1) / 2; /* S is x + y now */ P = P / fact(n); /* P is x*y now */ D = sqrt(S * S - 4 * P); /* D is x - y now */ x = (D + S) / 2; y = (S - D) / 2; cout << "Repeating elements are " << x << " " << y; } int fact(int n) { return (n == 0) ? 1 : n * fact(n - 1); } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This code is contributed by rathbhupendra
constant
linear
#include <bits/stdc++.h> using namespace std; void printRepeating(int arr[], int size) { int Xor = arr[0]; /* Will hold Xor of all elements */ int set_bit_no; /* Will have only single set bit of Xor */ int i; int n = size - 2; int x = 0, y = 0; /* Get the Xor of all elements in arr[] and {1, 2 .. n} */ for (i = 1; i < size; i++) Xor ^= arr[i]; for (i = 1; i <= n; i++) Xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = Xor & ~(Xor - 1); /* Now divide elements in two sets by comparing rightmost set bit of Xor with bit at same position in each element. */ for (i = 0; i < size; i++) { if (arr[i] & set_bit_no) x = x ^ arr[i]; /*Xor of first set in arr[] */ else y = y ^ arr[i]; /*Xor of second set in arr[] */ } for (i = 1; i <= n; i++) { if (i & set_bit_no) x = x ^ i; /*Xor of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*Xor of second set in arr[] and {1, 2, ...n } */ } cout << "Repeating elements are " << y << " " << x; } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This code is contributed by rathbhupendra
constant
linear
#include <bits/stdc++.h> using namespace std; void printRepeating(int arr[], int size) { int i; cout << "Repeating elements are "; for (i = 0; i < size; i++) { if (arr[abs(arr[i])] > 0) arr[abs(arr[i])] = -arr[abs(arr[i])]; else cout << abs(arr[i]) << " "; } } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This code is contributed by rathbhupendra
constant
linear
#include <bits/stdc++.h> using namespace std; void twoRepeated(int arr[], int N) { int m = N - 1; for (int i = 0; i < N; i++) { arr[arr[i] % m - 1] += m; if ((arr[arr[i] % m - 1] / m) == 2) cout << arr[i] % m << " "; } } // Driver Code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Repeating elements are "; twoRepeated(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
linear
// C++ program to Find the two repeating // elements in a given array #include <bits/stdc++.h> using namespace std; void printRepeating(int arr[], int size) { unordered_set<int> s; cout << "Repeating elements are "; for (int i = 0; i < size; i++) { if (s.empty() == false && s.find(arr[i]) != s.end()) cout << arr[i] << " "; s.insert(arr[i]); } } // Driver code int main() { int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int arr_size = sizeof(arr) / sizeof(arr[0]); printRepeating(arr, arr_size); return 0; } // This code is contributed by nakul amate
linear
linear
/* A simple program to print subarray with sum as given sum */ #include <bits/stdc++.h> using namespace std; /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ void subArraySum(int arr[], int n, int sum) { // Pick a starting point for (int i = 0; i < n; i++) { int currentSum = arr[i]; if (currentSum == sum) { cout << "Sum found at indexes " << i << endl; return; } else { // Try all subarrays starting with 'i' for (int j = i + 1; j < n; j++) { currentSum += arr[j]; if (currentSum == sum) { cout << "Sum found between indexes " << i << " and " << j << endl; return; } } } } cout << "No subarray found"; return; } // Driver Code int main() { int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0; } // This code is contributed // by rathbhupendra
constant
quadratic
/* An efficient program to print subarray with sum as given sum */ #include <iostream> using namespace std; /* Returns true if the there is a subarray of arr[] with a sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { /* Initialize currentSum as value of first element and starting point as 0 */ int currentSum = arr[0], start = 0, i; /* Add elements one by one to currentSum and if the currentSum exceeds the sum, then remove starting element */ for (i = 1; i <= n; i++) { // If currentSum exceeds the sum, // then remove the starting elements while (currentSum > sum && start < i - 1) { currentSum = currentSum - arr[start]; start++; } // If currentSum becomes equal to sum, // then return true if (currentSum == sum) { cout << "Sum found between indexes " << start << " and " << i - 1; return 1; } // Add this element to currentSum if (i < n) currentSum = currentSum + arr[i]; } // If we reach here, then no subarray cout << "No subarray found"; return 0; } // Driver Code int main() { int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; subArraySum(arr, n, sum); return 0; } // This code is contributed by SHUBHAMSINGH10
constant
linear
// C++ implementation of smallest difference triplet #include <bits/stdc++.h> using namespace std; // function to find maximum number int maximum(int a, int b, int c) { return max(max(a, b), c); } // function to find minimum number int minimum(int a, int b, int c) { return min(min(a, b), c); } // Finds and prints the smallest Difference Triplet void smallestDifferenceTriplet(int arr1[], int arr2[], int arr3[], int n) { // sorting all the three arrays sort(arr1, arr1+n); sort(arr2, arr2+n); sort(arr3, arr3+n); // To store resultant three numbers int res_min, res_max, res_mid; // pointers to arr1, arr2, arr3 // respectively int i = 0, j = 0, k = 0; // Loop until one array reaches to its end // Find the smallest difference. int diff = INT_MAX; while (i < n && j < n && k < n) { int sum = arr1[i] + arr2[j] + arr3[k]; // maximum number int max = maximum(arr1[i], arr2[j], arr3[k]); // Find minimum and increment its index. int min = minimum(arr1[i], arr2[j], arr3[k]); if (min == arr1[i]) i++; else if (min == arr2[j]) j++; else k++; // comparing new difference with the // previous one and updating accordingly if (diff > (max-min)) { diff = max - min; res_max = max; res_mid = sum - (max + min); res_min = min; } } // Print result cout << res_max << ", " << res_mid << ", " << res_min; } // Driver program to test above int main() { int arr1[] = {5, 2, 8}; int arr2[] = {10, 7, 12}; int arr3[] = {9, 14, 6}; int n = sizeof(arr1) / sizeof(arr1[0]); smallestDifferenceTriplet(arr1, arr2, arr3, n); return 0; }
constant
nlogn
// A simple C++ program to find three elements // whose sum is equal to zero #include <bits/stdc++.h> using namespace std; // Prints all triplets in arr[] with 0 sum void findTriplets(int arr[], int n) { bool found = false; for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == 0) { cout << arr[i] << " " << arr[j] << " " << arr[k] << endl; found = true; } } } } // If no triplet with 0 sum found in array if (found == false) cout << " not exist " << endl; } // Driver code int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
cubic
// C++ program to find triplets in a given // array whose sum is zero #include <bits/stdc++.h> using namespace std; // function to print triplets with 0 sum void findTriplets(int arr[], int n) { bool found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "-arr[i]" unordered_set<int> s; for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.find(x) != s.end()) { printf("%d %d %d\n", x, arr[i], arr[j]); found = true; } else s.insert(arr[j]); } } if (found == false) cout << " No Triplet Found" << endl; } // Driver code int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; }
linear
quadratic
// C++ program to find triplets in a given // array whose sum is zero #include <bits/stdc++.h> using namespace std; // function to print triplets with 0 sum void findTriplets(int arr[], int n) { bool found = false; // sort array elements sort(arr, arr + n); for (int i = 0; i < n - 1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero printf("%d %d %d\n", x, arr[l], arr[r]); l++; r--; found = true; // break; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) cout << " No Triplet Found" << endl; } // Driven source int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; }
constant
quadratic
// C++ program to rotate a matrix #include <bits/stdc++.h> #define R 4 #define C 4 using namespace std; // A function to rotate a matrix mat[][] of size R x C. // Initially, m = R and n = C void rotatematrix(int m, int n, int mat[R][C]) { int row = 0, col = 0; int prev, curr; /* row - Starting row index m - ending row index col - starting column index n - ending column index i - iterator */ while (row < m && col < n) { if (row + 1 == m || col + 1 == n) break; // Store the first element of next row, this // element will replace first element of current // row prev = mat[row + 1][col]; /* Move elements of first row from the remaining rows */ for (int i = col; i < n; i++) { curr = mat[row][i]; mat[row][i] = prev; prev = curr; } row++; /* Move elements of last column from the remaining columns */ for (int i = row; i < m; i++) { curr = mat[i][n-1]; mat[i][n-1] = prev; prev = curr; } n--; /* Move elements of last row from the remaining rows */ if (row < m) { for (int i = n-1; i >= col; i--) { curr = mat[m-1][i]; mat[m-1][i] = prev; prev = curr; } } m--; /* Move elements of first column from the remaining rows */ if (col < n) { for (int i = m-1; i >= row; i--) { curr = mat[i][col]; mat[i][col] = prev; prev = curr; } } col++; } // Print rotated matrix for (int i=0; i<R; i++) { for (int j=0; j<C; j++) cout << mat[i][j] << " "; cout << endl; } } /* Driver program to test above functions */ int main() { // Test Case 1 int a[R][C] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; // Test Case 2 /* int a[R][C] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ rotatematrix(R, C, a); return 0; }
constant
quadratic
// C++ program to rotate a matrix // by 90 degrees #include <bits/stdc++.h> #define N 4 using namespace std; // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction void rotateMatrix(int mat[][N]) { // Consider all squares one by one for (int x = 0; x < N / 2; x++) { // Consider elements in group // of 4 in current square for (int y = x; y < N - x - 1; y++) { // Store current cell in // temp variable int temp = mat[x][y]; // Move values from right to top mat[x][y] = mat[y][N - 1 - x]; // Move values from bottom to right mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]; // Move values from left to bottom mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]; // Assign temp to left mat[N - 1 - y][x] = temp; } } } // Function to print the matrix void displayMatrix(int mat[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << mat[i][j] << " "; } cout << endl; } cout << endl; } /* Driver code */ int main() { // Test Case 1 int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0; }
constant
quadratic
// C++ program to rotate a matrix // by 90 degrees #include <bits/stdc++.h> using namespace std; #define N 4 // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction void rotateMatrix(int mat[][N]) { // REVERSE every row for (int i = 0; i < N; i++) reverse(mat[i], mat[i] + N); // Performing Transpose for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) swap(mat[i][j], mat[j][i]); } } // Function to print the matrix void displayMatrix(int mat[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << mat[i][j] << " "; } cout << endl; } cout << endl; } /* Driver code */ int main() { int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0; }
constant
quadratic
#include <bits/stdc++.h> using namespace std; //Function to rotate matrix anticlockwise by 90 degrees. void rotateby90(vector<vector<int> >& matrix) { int n=matrix.size(); int mid; if(n%2==0) mid=n/2-1; else mid=n/2; for(int i=0,j=n-1;i<=mid;i++,j--) { for(int k=0;k<j-i;k++) { swap(matrix[i][j-k],matrix[j][i+k]); //ru ld swap(matrix[i+k][i],matrix[j][i+k]); //lu ld swap(matrix[i][j-k],matrix[j-k][j]); //ru rd } } } void printMatrix(vector<vector<int>>& arr) { int n=arr.size(); for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cout<<arr[i][j]<<" "; } cout<<endl; } } int main() { vector<vector<int>> arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateby90(arr); printMatrix(arr); return 0; }
constant
quadratic
// C++ program to rotate a matrix by 180 degrees #include <bits/stdc++.h> #define N 3 using namespace std; // Function to Rotate the matrix by 180 degree void rotateMatrix(int mat[][N]) { // Simply print from last cell to first cell. for (int i = N - 1; i >= 0; i--) { for (int j = N - 1; j >= 0; j--) printf("%d ", mat[i][j]); printf("\n"); } } // Driven code int main() { int mat[N][N] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; rotateMatrix(mat); return 0; }
constant
quadratic
// C++ program for left rotation of matrix by 180 #include <bits/stdc++.h> using namespace std; #define R 4 #define C 4 // Function to rotate the matrix by 180 degree void reverseColumns(int arr[R][C]) { for (int i = 0; i < C; i++) for (int j = 0, k = C - 1; j < k; j++, k--) swap(arr[j][i], arr[k][i]); } // Function for transpose of matrix void transpose(int arr[R][C]) { for (int i = 0; i < R; i++) for (int j = i; j < C; j++) swap(arr[i][j], arr[j][i]); } // Function for display the matrix void printMatrix(int arr[R][C]) { for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) cout << arr[i][j] << " "; cout << '\n'; } } // Function to anticlockwise rotate matrix // by 180 degree void rotate180(int arr[R][C]) { transpose(arr); reverseColumns(arr); transpose(arr); reverseColumns(arr); } // Driven code int main() { int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotate180(arr); printMatrix(arr); return 0; }
constant
quadratic
#include <bits/stdc++.h> using namespace std; /** * Reverse Row at specified index in the matrix * @param data matrix * @param index row index */ void reverseRow(vector<vector<int>>& data, int index) { int cols = data[index].size(); for(int i = 0; i < cols / 2; i++) { int temp = data[index][i]; data[index][i] = data[index][cols - i - 1]; data[index][cols - i - 1] = temp; } } /** * Print Matrix data * @param data matrix */ void printMatrix(vector<vector<int>>& data) { for(int i = 0; i < data.size(); i++) { for(int j = 0; j < data[i].size(); j++) { cout << data[i][j] << " "; } cout << endl; } } /** * Rotate Matrix by 180 degrees * @param data matrix */ void rotateMatrix180(vector<vector<int>>& data) { int rows = data.size(); int cols = data[0].size(); if (rows % 2 != 0) { // If N is odd reverse the middle // row in the matrix reverseRow(data, data.size() / 2); } // Swap the value of matrix [i][j] with // [rows - i - 1][cols - j - 1] for half // the rows size. for(int i = 0; i <= (rows/2) - 1; i++) { for(int j = 0; j < cols; j++) { int temp = data[i][j]; data[i][j] = data[rows - i - 1][cols - j - 1]; data[rows - i - 1][cols - j - 1] = temp; } } } // Driver code int main() { vector<vector<int>> data{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 }, { 21, 22, 23, 24, 25 } }; // Rotate Matrix rotateMatrix180(data); // Print Matrix printMatrix(data); return 0; } // This code is contributed by divyeshrabadiya07
constant
quadratic
// C++ program to rotate individual rings by k in // spiral order traversal. #include<bits/stdc++.h> #define MAX 100 using namespace std; // Fills temp array into mat[][] using spiral order // traversal. void fillSpiral(int mat[][MAX], int m, int n, int temp[]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index */ int tIdx = 0; // Index in temp array while (k < m && l < n) { /* first row from the remaining rows */ for (int i = l; i < n; ++i) mat[k][i] = temp[tIdx++]; k++; /* last column from the remaining columns */ for (int i = k; i < m; ++i) mat[i][n-1] = temp[tIdx++]; n--; /* last row from the remaining rows */ if (k < m) { for (int i = n-1; i >= l; --i) mat[m-1][i] = temp[tIdx++]; m--; } /* first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= k; --i) mat[i][l] = temp[tIdx++]; l++; } } } // Function to spirally traverse matrix and // rotate each ring of matrix by K elements // mat[][] --> matrix of elements // M --> number of rows // N --> number of columns void spiralRotate(int mat[][MAX], int M, int N, int k) { // Create a temporary array to store the result int temp[M*N]; /* s - starting row index m - ending row index l - starting column index n - ending column index; */ int m = M, n = N, s = 0, l = 0; int *start = temp; // Start position of current ring int tIdx = 0; // Index in temp while (s < m && l < n) { // Initialize end position of current ring int *end = start; // copy the first row from the remaining rows for (int i = l; i < n; ++i) { temp[tIdx++] = mat[s][i]; end++; } s++; // copy the last column from the remaining columns for (int i = s; i < m; ++i) { temp[tIdx++] = mat[i][n-1]; end++; } n--; // copy the last row from the remaining rows if (s < m) { for (int i = n-1; i >= l; --i) { temp[tIdx++] = mat[m-1][i]; end++; } m--; } /* copy the first column from the remaining columns */ if (l < n) { for (int i = m-1; i >= s; --i) { temp[tIdx++] = mat[i][l]; end++; } l++; } // if elements in current ring greater than // k then rotate elements of current ring if (end-start > k) { // Rotate current ring using reversal // algorithm for rotation reverse(start, start+k); reverse(start+k, end); reverse(start, end); // Reset start for next ring start = end; } } // Fill temp array in original matrix. fillSpiral(mat, M, N, temp); } // Driver program to run the case int main() { // Your C++ Code int M = 4, N = 4, k = 3; int mat[][MAX]= {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} }; spiralRotate(mat, M, N, k); // print modified matrix for (int i=0; i<M; i++) { for (int j=0; j<N; j++) cout << mat[i][j] << " "; cout << endl; } return 0; }
quadratic
quadratic
// C++ program to check if all rows of a matrix // are rotations of each other #include <bits/stdc++.h> using namespace std; const int MAX = 1000; // Returns true if all rows of mat[0..n-1][0..n-1] // are rotations of each other. bool isPermutedMatrix( int mat[MAX][MAX], int n) { // Creating a string that contains elements of first // row. string str_cat = ""; for (int i = 0 ; i < n ; i++) str_cat = str_cat + "-" + to_string(mat[0][i]); // Concatenating the string with itself so that // substring search operations can be performed on // this str_cat = str_cat + str_cat; // Start traversing remaining rows for (int i=1; i<n; i++) { // Store the matrix into vector in the form // of strings string curr_str = ""; for (int j = 0 ; j < n ; j++) curr_str = curr_str + "-" + to_string(mat[i][j]); // Check if the current string is present in // the concatenated string or not if (str_cat.find(curr_str) == string::npos) return false; } return true; } // Drivers code int main() { int n = 4 ; int mat[MAX][MAX] = {{1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} }; isPermutedMatrix(mat, n)? cout << "Yes" : cout << "No"; return 0; }
linear
cubic
// C++ implementation to sort the given matrix #include <bits/stdc++.h> using namespace std; #define SIZE 10 // function to sort the given matrix void sortMat(int mat[SIZE][SIZE], int n) { // temporary matrix of size n^2 int temp[n * n]; int k = 0; // copy the elements of matrix one by one // into temp[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) temp[k++] = mat[i][j]; // sort temp[] sort(temp, temp + k); // copy the elements of temp[] one by one // in mat[][] k = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) mat[i][j] = temp[k++]; } // function to print the given matrix void printMat(int mat[SIZE][SIZE], int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << mat[i][j] << " "; cout << endl; } } // Driver program to test above int main() { int mat[SIZE][SIZE] = { { 5, 4, 7 }, { 1, 3, 8 }, { 2, 9, 6 } }; int n = 3; cout << "Original Matrix:\n"; printMat(mat, n); sortMat(mat, n); cout << "\nMatrix After Sorting:\n"; printMat(mat, n); return 0; }
quadratic
quadratic
// C++ program to find median of a matrix // sorted row wise #include<bits/stdc++.h> using namespace std; const int MAX = 100; // function to find median in the matrix int binaryMedian(int m[][MAX], int r ,int c) { int min = INT_MAX, max = INT_MIN; for (int i=0; i<r; i++) { // Finding the minimum element if (m[i][0] < min) min = m[i][0]; // Finding the maximum element if (m[i][c-1] > max) max = m[i][c-1]; } int desired = (r * c + 1) / 2; while (min < max) { int mid = min + (max - min) / 2; int place = 0; // Find count of elements smaller than or equal to mid for (int i = 0; i < r; ++i) place += upper_bound(m[i], m[i]+c, mid) - m[i]; if (place < desired) min = mid + 1; else max = mid; } return min; } // driver program to check above functions int main() { int r = 3, c = 3; int m[][MAX]= { {1,3,5}, {2,6,9}, {3,6,9} }; cout << "Median is " << binaryMedian(m, r, c) << endl; return 0; }
constant
nlogn
// C++ program to print Lower // triangular and Upper triangular // matrix of an array #include<iostream> using namespace std; // Function to form // lower triangular matrix void lower(int matrix[3][3], int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (i < j) { cout << "0" << " "; } else cout << matrix[i][j] << " "; } cout << endl; } } // Function to form upper triangular matrix void upper(int matrix[3][3], int row, int col) { int i, j; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { if (i > j) { cout << "0" << " "; } else cout << matrix[i][j] << " "; } cout << endl; } } // Driver Code int main() { int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int row = 3, col = 3; cout << "Lower triangular matrix: \n"; lower(matrix, row, col); cout << "Upper triangular matrix: \n"; upper(matrix, row, col); return 0; }
constant
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; vector<int> spiralOrder(vector<vector<int> >& matrix) { int m = matrix.size(), n = matrix[0].size(); vector<int> ans; if (m == 0) return ans; vector<vector<bool> > seen(m, vector<bool>(n, false)); int dr[] = { 0, 1, 0, -1 }; int dc[] = { 1, 0, -1, 0 }; int x = 0, y = 0, di = 0; // Iterate from 0 to m * n - 1 for (int i = 0; i < m * n; i++) { ans.push_back(matrix[x][y]); // on normal geeksforgeeks ui page it is showing // 'ans.push_back(matrix[x])' which gets copied as // this only and gives error on compilation, seen[x][y] = true; int newX = x + dr[di]; int newY = y + dc[di]; if (0 <= newX && newX < m && 0 <= newY && newY < n && !seen[newX][newY]) { x = newX; y = newY; } else { di = (di + 1) % 4; x += dr[di]; y += dc[di]; } } return ans; } // Driver code int main() { vector<vector<int> > a{ { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function call for (int x : spiralOrder(a)) { cout << x << " "; } return 0; } // This code is contributed by Yashvendra Singh
linear
linear
// C++ Program to print a matrix spirally #include <bits/stdc++.h> using namespace std; #define R 4 #define C 4 void spiralPrint(int m, int n, int a[R][C]) { int i, k = 0, l = 0; /* k - starting row index m - ending row index l - starting column index n - ending column index i - iterator */ while (k < m && l < n) { /* Print the first row from the remaining rows */ for (i = l; i < n; ++i) { cout << a[k][i] << " "; } k++; /* Print the last column from the remaining columns */ for (i = k; i < m; ++i) { cout << a[i][n - 1] << " "; } n--; /* Print the last row from the remaining rows */ if (k < m) { for (i = n - 1; i >= l; --i) { cout << a[m - 1][i] << " "; } m--; } /* Print the first column from the remaining columns */ if (l < n) { for (i = m - 1; i >= k; --i) { cout << a[i][l] << " "; } l++; } } } /* Driver Code */ int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call spiralPrint(R, C, a); return 0; } // This is code is contributed by rathbhupendra
constant
quadratic
// C++. program for the above approach #include <bits/stdc++.h> using namespace std; #define R 4 #define C 4 // Function for printing matrix in spiral // form i, j: Start index of matrix, row // and column respectively m, n: End index // of matrix row and column respectively void print(int arr[R][C], int i, int j, int m, int n) { // If i or j lies outside the matrix if (i >= m or j >= n) return; // Print First Row for (int p = j; p < n; p++) cout << arr[i][p] << " "; // Print Last Column for (int p = i + 1; p < m; p++) cout << arr[p][n - 1] << " "; // Print Last Row, if Last and // First Row are not same if ((m - 1) != i) for (int p = n - 2; p >= j; p--) cout << arr[m - 1][p] << " "; // Print First Column, if Last and // First Column are not same if ((n - 1) != j) for (int p = m - 2; p > i; p--) cout << arr[p][j] << " "; print(arr, i + 1, j + 1, m - 1, n - 1); } // Driver Code int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call print(a, 0, 0, R, C); return 0; } // This Code is contributed by Ankur Goel
constant
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; #define R 4 #define C 4 bool isInBounds(int i, int j) { if (i < 0 || i >= R || j < 0 || j >= C) return false; return true; } // check if the position is blocked bool isBlocked(int matrix[R][C], int i, int j) { if (!isInBounds(i, j)) return true; if (matrix[i][j] == -1) return true; return false; } // DFS code to traverse spirally void spirallyDFSTravserse(int matrix[R][C], int i, int j, int dir, vector<int>& res) { if (isBlocked(matrix, i, j)) return; bool allBlocked = true; for (int k = -1; k <= 1; k += 2) { allBlocked = allBlocked && isBlocked(matrix, k + i, j) && isBlocked(matrix, i, j + k); } res.push_back(matrix[i][j]); matrix[i][j] = -1; if (allBlocked) { return; } // dir: 0 - right, 1 - down, 2 - left, 3 - up int nxt_i = i; int nxt_j = j; int nxt_dir = dir; if (dir == 0) { if (!isBlocked(matrix, i, j + 1)) { nxt_j++; } else { nxt_dir = 1; nxt_i++; } } else if (dir == 1) { if (!isBlocked(matrix, i + 1, j)) { nxt_i++; } else { nxt_dir = 2; nxt_j--; } } else if (dir == 2) { if (!isBlocked(matrix, i, j - 1)) { nxt_j--; } else { nxt_dir = 3; nxt_i--; } } else if (dir == 3) { if (!isBlocked(matrix, i - 1, j)) { nxt_i--; } else { nxt_dir = 0; nxt_j++; } } spirallyDFSTravserse(matrix, nxt_i, nxt_j, nxt_dir, res); } // To traverse spirally vector<int> spirallyTraverse(int matrix[R][C]) { vector<int> res; spirallyDFSTravserse(matrix, 0, 0, 0, res); return res; } // Driver Code int main() { int a[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Function Call vector<int> res = spirallyTraverse(a); int size = res.size(); for (int i = 0; i < size; ++i) cout << res[i] << " "; cout << endl; return 0; } // code contributed by Ephi F
constant
quadratic
// C++ program to find unique element in matrix #include <bits/stdc++.h> using namespace std; #define R 4 #define C 4 // function that calculate unique element int unique(int mat[R][C], int n, int m) { // declare map for hashing unordered_map<int, int> mp; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) // increase freq of mat[i][j] in map mp[mat[i][j]]++; int flag = false; // print unique element for (auto p : mp) { if (p.second == 1) { cout << p.first << " "; flag = 1; } } if (!flag) { cout << "No unique element in the matrix"; } } // Driver program int main() { int mat[R][C] = { { 1, 2, 3, 20 }, { 5, 6, 20, 25 }, { 1, 3, 5, 6 }, { 6, 7, 8, 15 } }; // function that calculate unique element unique(mat, R, C); return 0; }
quadratic
quadratic
// CPP Program to swap diagonal of a matrix #include <bits/stdc++.h> using namespace std; // size of square matrix #define N 3 // Function to swap diagonal of matrix void swapDiagonal(int matrix[][N]) { for (int i = 0; i < N; i++) swap(matrix[i][i], matrix[i][N - i - 1]); } // Driver Code int main() { int matrix[N][N] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; swapDiagonal(matrix); // Displaying modified matrix for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << matrix[i][j] << " "; cout << endl; } return 0; }
constant
quadratic
// CPP program for finding max path in matrix #include <bits/stdc++.h> #define N 4 #define M 6 using namespace std; // To calculate max path in matrix int findMaxPath(int mat[][M]) { for (int i = 1; i < N; i++) { for (int j = 0; j < M; j++) { // When all paths are possible if (j > 0 && j < M - 1) mat[i][j] += max(mat[i - 1][j], max(mat[i - 1][j - 1], mat[i - 1][j + 1])); // When diagonal right is not possible else if (j > 0) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j - 1]); // When diagonal left is not possible else if (j < M - 1) mat[i][j] += max(mat[i - 1][j], mat[i - 1][j + 1]); // Store max path sum } } int res = 0; for (int j = 0; j < M; j++) res = max(mat[N-1][j], res); return res; } // Driver program to check findMaxPath int main() { int mat1[N][M] = { { 10, 10, 2, 0, 20, 4 }, { 1, 0, 0, 30, 2, 5 }, { 0, 10, 4, 0, 2, 0 }, { 1, 0, 2, 20, 0, 4 } }; cout << findMaxPath(mat1) << endl; return 0; }
constant
quadratic
// C++ code to move matrix elements // in given direction with add // element with same value #include <bits/stdc++.h> using namespace std; #define MAX 50 // Function to shift the matrix // in the given direction void moveMatrix(char d[], int n, int a[MAX][MAX]) { // For right shift move. if (d[0] == 'r') { // for each row from // top to bottom for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of // row from right to left for (j = n - 1; j >= 0; j--) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = n - 1; // Copying the temporary // array to the current row. for (auto it = w.begin(); it != w.end(); it++) a[i][j--] = *it; } } // for left shift move else if (d[0] == 'l') { // for each row for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of the // row from left to right for (j = 0; j < n; j++) { // if not 0 if (a[i][j]) v.push_back(a[i][j]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each row element to 0. for (j = 0; j < n; j++) a[i][j] = 0; j = 0; for (auto it = w.begin(); it != w.end(); it++) a[i][j++] = *it; } } // for down shift move. else if (d[0] == 'd') { // for each column for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of // column from bottom to top for (j = n - 1; j >= 0; j--) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = n - 1; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j--][i] = *it; } } // for up shift move else if (d[0] == 'u') { // for each column for (int i = 0; i < n; i++) { vector<int> v, w; int j; // for each element of column // from top to bottom for (j = 0; j < n; j++) { // if not 0 if (a[j][i]) v.push_back(a[j][i]); } // for each temporary array for (j = 0; j < v.size(); j++) { // if two element have same // value at consecutive position. if (j < v.size() - 1 && v[j] == v[j + 1]) { // insert only one element // as sum of two same element. w.push_back(2 * v[j]); j++; } else w.push_back(v[j]); } // filling the each column element to 0. for (j = 0; j < n; j++) a[j][i] = 0; j = 0; // Copying the temporary array // to the current column for (auto it = w.begin(); it != w.end(); it++) a[j++][i] = *it; } } } // Driven Program int main() { char d[2] = "l"; int n = 5; int a[MAX][MAX] = { { 32, 3, 3, 3, 3 }, { 0, 0, 1, 0, 0 }, { 10, 10, 8, 1, 2 }, { 0, 0, 0, 0, 1 }, { 4, 5, 6, 7, 8 } }; moveMatrix(d, n, a); // Printing the final array for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << a[i][j] << " "; cout << endl; } return 0; }
linear
quadratic
// C++ program to find number of subarrays // having product exactly equal to k. #include <bits/stdc++.h> using namespace std; // Function to find number of subarrays // having product equal to 1. int countOne(int arr[], int n){ int i = 0; // To store number of ones in // current segment of all 1s. int len = 0; // To store number of subarrays // having product equal to 1. int ans = 0; while(i < n){ // If current element is 1, then // find length of segment of 1s // starting from current element. if(arr[i] == 1){ len = 0; while(i < n && arr[i] == 1){ i++; len++; } // add number of possible // subarrays of 1 to result. ans += (len*(len+1)) / 2; } i++; } return ans; } /// Function to find number of subarrays having /// product exactly equal to k. int findSubarrayCount(int arr[], int n, int k) { int start = 0, endval = 0, p = 1, countOnes = 0, res = 0; while (endval < n) { p *= (arr[endval]); // If product is greater than k then we need to decrease // it. This could be done by shifting starting point of // sliding window one place to right at a time and update // product accordingly. if(p > k) { while(start <= endval && p > k) { p /= arr[start]; start++; } } if(p == k) { // Count number of succeeding ones. countOnes = 0; while(endval + 1 < n && arr[endval + 1] == 1) { countOnes++; endval++; } // Update result by adding both new subarray // and effect of succeeding ones. res += (countOnes + 1); // Update sliding window and result according // to change in sliding window. Here preceding // 1s have same effect on subarray as succeeding // 1s, so simply add. while(start <= endval && arr[start] == 1 && k!=1) { res += (countOnes + 1); start++; } // Move start to correct position to find new // subarray and update product accordingly. p /= arr[start]; start++; } endval++; } return res; } // Driver code int main() { int arr1[] = { 2, 1, 1, 1, 3, 1, 1, 4}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int k = 1; if(k != 1) cout << findSubarrayCount(arr1, n1, k) << "\n"; else cout << countOne(arr1, n1) << "\n"; int arr2[] = { 2, 1, 1, 1, 4, 5}; int n2 = sizeof(arr2) / sizeof(arr2[0]); k = 4; if(k != 1) cout << findSubarrayCount(arr2, n2, k) << "\n"; else cout << countOne(arr2, n2) << "\n"; return 0; }
constant
linear
// CPP program to find all those // elements of arr1[] that are not // present in arr2[] #include <iostream> using namespace std; void relativeComplement(int arr1[], int arr2[], int n, int m) { int i = 0, j = 0; while (i < n && j < m) { // If current element in arr2[] is // greater, then arr1[i] can't be // present in arr2[j..m-1] if (arr1[i] < arr2[j]) { cout << arr1[i] << " "; i++; // Skipping smaller elements of // arr2[] } else if (arr1[i] > arr2[j]) { j++; // Equal elements found (skipping // in both arrays) } else if (arr1[i] == arr2[j]) { i++; j++; } } // Printing remaining elements of // arr1[] while (i < n) cout << arr1[i] << " "; } // Driver code int main() { int arr1[] = {3, 6, 10, 12, 15}; int arr2[] = {1, 3, 5, 10, 16}; int n = sizeof(arr1) / sizeof(arr1[0]); int m = sizeof(arr2) / sizeof(arr2[0]); relativeComplement(arr1, arr2, n, m); return 0; }
constant
linear
// Program to make all array equal #include <bits/stdc++.h> using namespace std; // function for calculating min operations int minOps(int arr[], int n, int k) { // max elements of array int max = *max_element(arr, arr + n); int res = 0; // iterate for all elements for (int i = 0; i < n; i++) { // check if element can make equal to // max or not if not then return -1 if ((max - arr[i]) % k != 0) return -1; // else update res for required operations else res += (max - arr[i]) / k; } // return result return res; } // driver program int main() { int arr[] = { 21, 33, 9, 45, 63 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 6; cout << minOps(arr, n, k); return 0; }
constant
linear
// C++ code for above approach #include<bits/stdc++.h> using namespace std; int solve(int A[], int B[], int C[], int i, int j, int k) { int min_diff, current_diff, max_term; // calculating min difference from last // index of lists min_diff = abs(max(A[i], max(B[j], C[k])) - min(A[i], min(B[j], C[k])));; while (i != -1 && j != -1 && k != -1) { current_diff = abs(max(A[i], max(B[j], C[k])) - min(A[i], min(B[j], C[k]))); // checking condition if (current_diff < min_diff) min_diff = current_diff; // calculating max term from list max_term = max(A[i], max(B[j], C[k])); // Moving to smaller value in the // array with maximum out of three. if (A[i] == max_term) i -= 1; else if (B[j] == max_term) j -= 1; else k -= 1; } return min_diff; } // Driver code int main() { int D[] = { 5, 8, 10, 15 }; int E[] = { 6, 9, 15, 78, 89 }; int F[] = { 2, 3, 6, 6, 8, 8, 10 }; int nD = sizeof(D) / sizeof(D[0]); int nE = sizeof(E) / sizeof(E[0]); int nF = sizeof(F) / sizeof(F[0]); cout << solve(D, E, F, nD-1, nE-1, nF-1); return 0; } // This code is contributed by Ravi Maurya.
constant
linear
/* A program to convert Binary Tree to Binary Search Tree */ #include <iostream> using namespace std; /* A binary tree node structure */ struct node { int data; struct node* left; struct node* right; }; /* A helper function that stores inorder traversal of a tree rooted with node */ void storeInorder(struct node* node, int inorder[], int* index_ptr) { // Base Case if (node == NULL) return; /* first store the left subtree */ storeInorder(node->left, inorder, index_ptr); /* Copy the root's data */ inorder[*index_ptr] = node->data; (*index_ptr)++; // increase index for next entry /* finally store the right subtree */ storeInorder(node->right, inorder, index_ptr); } /* A helper function to count nodes in a Binary Tree */ int countNodes(struct node* root) { if (root == NULL) return 0; return countNodes(root->left) + countNodes(root->right) + 1; } // Following function is needed for library function qsort() int compare(const void* a, const void* b) { return (*(int*)a - *(int*)b); } /* A helper function that copies contents of arr[] to Binary Tree. This function basically does Inorder traversal of Binary Tree and one by one copy arr[] elements to Binary Tree nodes */ void arrayToBST(int* arr, struct node* root, int* index_ptr) { // Base Case if (root == NULL) return; /* first update the left subtree */ arrayToBST(arr, root->left, index_ptr); /* Now update root's data and increment index */ root->data = arr[*index_ptr]; (*index_ptr)++; /* finally update the right subtree */ arrayToBST(arr, root->right, index_ptr); } // This function converts a given Binary Tree to BST void binaryTreeToBST(struct node* root) { // base case: tree is empty if (root == NULL) return; /* Count the number of nodes in Binary Tree so that we know the size of temporary array to be created */ int n = countNodes(root); // Create a temp array arr[] and store inorder // traversal of tree in arr[] int* arr = new int[n]; int i = 0; storeInorder(root, arr, &i); // Sort the array using library function for quick sort qsort(arr, n, sizeof(arr[0]), compare); // Copy array elements back to Binary Tree i = 0; arrayToBST(arr, root, &i); // delete dynamically allocated memory to // avoid memory leak delete[] arr; } /* Utility function to create a new Binary Tree node */ struct node* newNode(int data) { struct node* temp = new struct node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } /* Utility function to print inorder traversal of Binary Tree */ void printInorder(struct node* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout <<" "<< node->data; /* now recur on right child */ printInorder(node->right); } /* Driver function to test above functions */ int main() { struct node* root = NULL; /* Constructing tree given in the above figure 10 / \ 30 15 / \ 20 5 */ root = newNode(10); root->left = newNode(30); root->right = newNode(15); root->left->left = newNode(20); root->right->right = newNode(5); // convert Binary Tree to BST binaryTreeToBST(root); cout <<"Following is Inorder Traversal of the converted BST:" << endl ; printInorder(root); return 0; } // This code is contributed by shivanisinghss2110
linear
nlogn
// C++ program to print BST in given range #include<bits/stdc++.h> using namespace std; /* A Binary Tree node */ class TNode { public: int data; TNode* left; TNode* right; }; TNode* newNode(int data); /* A function that constructs Balanced Binary Search Tree from a sorted array */ TNode* sortedArrayToBST(int arr[], int start, int end) { /* Base Case */ if (start > end) return NULL; /* Get the middle element and make it root */ int mid = (start + end)/2; TNode *root = newNode(arr[mid]); /* Recursively construct the left subtree and make it left child of root */ root->left = sortedArrayToBST(arr, start, mid - 1); /* Recursively construct the right subtree and make it right child of root */ root->right = sortedArrayToBST(arr, mid + 1, end); return root; } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ TNode* newNode(int data) { TNode* node = new TNode(); node->data = data; node->left = NULL; node->right = NULL; return node; } /* A utility function to print preorder traversal of BST */ void preOrder(TNode* node) { if (node == NULL) return; cout << node->data << " "; preOrder(node->left); preOrder(node->right); } // Driver Code int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7}; int n = sizeof(arr) / sizeof(arr[0]); /* Convert List to BST */ TNode *root = sortedArrayToBST(arr, 0, n-1); cout << "PreOrder Traversal of constructed BST \n"; preOrder(root); return 0; } // This code is contributed by rathbhupendra
logn
linear
// C++ program to transform a BST to sum tree #include<iostream> using namespace std; // A BST node struct Node { int data; struct Node *left, *right; }; // A utility function to create a new Binary Tree Node struct Node *newNode(int item) { struct Node *temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } // Recursive function to transform a BST to sum tree. // This function traverses the tree in reverse inorder so // that we have visited all greater key nodes of the currently // visited node void transformTreeUtil(struct Node *root, int *sum) { // Base case if (root == NULL) return; // Recur for right subtree transformTreeUtil(root->right, sum); // Update sum *sum = *sum + root->data; // Store old sum in current node root->data = *sum - root->data; // Recur for left subtree transformTreeUtil(root->left, sum); } // A wrapper over transformTreeUtil() void transformTree(struct Node *root) { int sum = 0; // Initialize sum transformTreeUtil(root, ∑); } // A utility function to print indorder traversal of a // binary tree void printInorder(struct Node *root) { if (root == NULL) return; printInorder(root->left); cout << root->data << " "; printInorder(root->right); } // Driver Program to test above functions int main() { struct Node *root = newNode(11); root->left = newNode(2); root->right = newNode(29); root->left->left = newNode(1); root->left->right = newNode(7); root->right->left = newNode(15); root->right->right = newNode(40); root->right->right->left = newNode(35); cout << "Inorder Traversal of given tree\n"; printInorder(root); transformTree(root); cout << "\n\nInorder Traversal of transformed tree\n"; printInorder(root); return 0; }
linear
linear
//C++ Program to convert a BST into a Min-Heap // in O(n) time and in-place #include <bits/stdc++.h> using namespace std; // Node for BST/Min-Heap struct Node { int data; Node *left, *right; }; // Utility function for allocating node for BST Node* newNode(int data) { Node* node = new Node; node->data = data; node->left = node->right = NULL; return node; } // Utility function to print Min-heap level by level void printLevelOrder(Node *root) { // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<Node *> q; q.push(root); while (!q.empty()) { int nodeCount = q.size(); while (nodeCount > 0) { Node *node = q.front(); cout << node->data << " "; q.pop(); if (node->left) q.push(node->left); if (node->right) q.push(node->right); nodeCount--; } cout << endl; } } // A simple recursive function to convert a given // Binary Search tree to Sorted Linked List // root --> Root of Binary Search Tree // head_ref --> Pointer to head node of created // linked list void BSTToSortedLL(Node* root, Node** head_ref) { // Base cases if(root == NULL) return; // Recursively convert right subtree BSTToSortedLL(root->right, head_ref); // insert root into linked list root->right = *head_ref; // Change left pointer of previous head // to point to NULL if (*head_ref != NULL) (*head_ref)->left = NULL; // Change head of linked list *head_ref = root; // Recursively convert left subtree BSTToSortedLL(root->left, head_ref); } // Function to convert a sorted Linked // List to Min-Heap. // root --> Root of Min-Heap // head --> Pointer to head node of sorted // linked list void SortedLLToMinHeap(Node* &root, Node* head) { // Base Case if (head == NULL) return; // queue to store the parent nodes queue<Node *> q; // The first node is always the root node root = head; // advance the pointer to the next node head = head->right; // set right child to NULL root->right = NULL; // add first node to the queue q.push(root); // run until the end of linked list is reached while (head) { // Take the parent node from the q and remove it from q Node* parent = q.front(); q.pop(); // Take next two nodes from the linked list and // Add them as children of the current parent node // Also in push them into the queue so that // they will be parents to the future nodes Node *leftChild = head; head = head->right; // advance linked list to next node leftChild->right = NULL; // set its right child to NULL q.push(leftChild); // Assign the left child of parent parent->left = leftChild; if (head) { Node *rightChild = head; head = head->right; // advance linked list to next node rightChild->right = NULL; // set its right child to NULL q.push(rightChild); // Assign the right child of parent parent->right = rightChild; } } } // Function to convert BST into a Min-Heap // without using any extra space Node* BSTToMinHeap(Node* &root) { // head of Linked List Node *head = NULL; // Convert a given BST to Sorted Linked List BSTToSortedLL(root, &head); // set root as NULL root = NULL; // Convert Sorted Linked List to Min-Heap SortedLLToMinHeap(root, head); } // Driver code int main() { /* Constructing below tree 8 / \ 4 12 / \ / \ 2 6 10 14 */ Node* root = newNode(8); root->left = newNode(4); root->right = newNode(12); root->right->left = newNode(10); root->right->right = newNode(14); root->left->left = newNode(2); root->left->right = newNode(6); BSTToMinHeap(root); /* Output - Min Heap 2 / \ 4 6 / \ / \ 8 10 12 14 */ printLevelOrder(root); return 0; }
linear
linear
// C++ implementation to convert the given // BST to Min Heap #include <bits/stdc++.h> using namespace std; // Structure of a node of BST struct Node { int data; Node *left, *right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct Node* getNode(int data) { struct Node* newNode = new Node; newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // function prototype for preorder traversal // of the given tree void preorderTraversal(Node*); // function for the inorder traversal of the tree // so as to store the node values in 'arr' in // sorted order void inorderTraversal(Node* root, vector<int>& arr) { if (root == NULL) return; // first recur on left subtree inorderTraversal(root->left, arr); // then copy the data of the node arr.push_back(root->data); // now recur for right subtree inorderTraversal(root->right, arr); } // function to convert the given BST to MIN HEAP // performs preorder traversal of the tree void BSTToMinHeap(Node* root, vector<int> arr, int* i) { if (root == NULL) return; // first copy data at index 'i' of 'arr' to // the node root->data = arr[++*i]; // then recur on left subtree BSTToMinHeap(root->left, arr, i); // now recur on right subtree BSTToMinHeap(root->right, arr, i); } // utility function to convert the given BST to // MIN HEAP void convertToMinHeapUtil(Node* root) { // vector to store the data of all the // nodes of the BST vector<int> arr; int i = -1; // inorder traversal to populate 'arr' inorderTraversal(root, arr); // BST to MIN HEAP conversion BSTToMinHeap(root, arr, &i); } // function for the preorder traversal of the tree void preorderTraversal(Node* root) { if (!root) return; // first print the root's data cout << root->data << " "; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right); } // Driver program to test above int main() { // BST formation struct Node* root = getNode(4); root->left = getNode(2); root->right = getNode(6); root->left->left = getNode(1); root->left->right = getNode(3); root->right->left = getNode(5); root->right->right = getNode(7); // Function call convertToMinHeapUtil(root); cout << "Preorder Traversal:" << endl; preorderTraversal(root); return 0; }
linear
linear
// C++ implementation to construct a BST // from its level order traversal #include <bits/stdc++.h> using namespace std; // node of a BST struct Node { int data; Node *left, *right; }; // function to get a new node Node* getNode(int data) { // Allocate memory Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } // function to construct a BST from // its level order traversal Node* LevelOrder(Node* root, int data) { if (root == NULL) { root = getNode(data); return root; } if (data <= root->data) root->left = LevelOrder(root->left, data); else root->right = LevelOrder(root->right, data); return root; } Node* constructBst(int arr[], int n) { if (n == 0) return NULL; Node* root = NULL; for (int i = 0; i < n; i++) root = LevelOrder(root, arr[i]); return root; } // function to print the inorder traversal void inorderTraversal(Node* root) { if (!root) return; inorderTraversal(root->left); cout << root->data << " "; inorderTraversal(root->right); } // Driver program to test above int main() { int arr[] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 }; int n = sizeof(arr) / sizeof(arr[0]); Node* root = constructBst(arr, n); cout << "Inorder Traversal: "; inorderTraversal(root); return 0; }
linear
nlogn
// C++ implementation to construct a BST // from its level order traversal #include <bits/stdc++.h> using namespace std; // node of a BST struct Node { int data; Node *left, *right; Node(int x) { data = x; right = NULL; left = NULL; } }; // Function to construct a BST from // its level order traversal Node* constructBst(int arr[], int n) { // Create queue to store the tree nodes queue<pair<Node*, pair<int, int> > > q; // If array is empty we return NULL if (n == 0) return NULL; // Create root node and store a copy of it in head Node *root = new Node(arr[0]), *head = root; // Push the root node and the initial range q.push({ root, { INT_MIN, INT_MAX } }); // Loop over the contents of arr to process all the // elements for (int i = 1; i < n; i++) { // Get the node and the range at the front of the // queue Node* temp = q.front().first; pair<int, int> range = q.front().second; // Check if arr[i] can be a child of the temp node if (arr[i] > range.first && arr[i] < range.second) { // Check if arr[i] can be left child if (arr[i] < temp->data) { // Set the left child and range temp->left = new Node(arr[i]); q.push({ temp->left, { range.first, temp->data } }); } // Check if arr[i] can be left child else { // Pop the temp node from queue, set the // right child and new range q.pop(); temp->right = new Node(arr[i]); q.push({ temp->right, { temp->data, range.second } }); } } else { q.pop(); i--; } } return head; } // Function to print the inorder traversal void inorderTraversal(Node* root) { if (!root) return; inorderTraversal(root->left); cout << root->data << " "; inorderTraversal(root->right); } // Driver program to test above int main() { int arr[] = { 7, 4, 12, 3, 6, 8, 1, 5, 10 }; int n = sizeof(arr) / sizeof(arr[0]); Node* root = constructBst(arr, n); cout << "Inorder Traversal: "; inorderTraversal(root); return 0; } // This code is contributed by Rohit Iyer (rohit_iyer)
linear
linear
/* CPP program to convert a Binary tree to BST using sets as containers. */ #include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *left, *right; }; // function to store the nodes in set while // doing inorder traversal. void storeinorderInSet(Node* root, set<int>& s) { if (!root) return; // visit the left subtree first storeinorderInSet(root->left, s); // insertion takes order of O(logn) for sets s.insert(root->data); // visit the right subtree storeinorderInSet(root->right, s); } // Time complexity = O(nlogn) // function to copy items of set one by one // to the tree while doing inorder traversal void setToBST(set<int>& s, Node* root) { // base condition if (!root) return; // first move to the left subtree and // update items setToBST(s, root->left); // iterator initially pointing to the // beginning of set auto it = s.begin(); // copying the item at beginning of // set(sorted) to the tree. root->data = *it; // now erasing the beginning item from set. s.erase(it); // now move to right subtree and update items setToBST(s, root->right); } // T(n) = O(nlogn) time // Converts Binary tree to BST. void binaryTreeToBST(Node* root) { set<int> s; // populating the set with the tree's // inorder traversal data storeinorderInSet(root, s); // now sets are by default sorted as // they are implemented using self- // balancing BST // copying items from set to the tree // while inorder traversal which makes a BST setToBST(s, root); } // Time complexity = O(nlogn), // Auxiliary Space = O(n) for set. // helper function to create a node Node* newNode(int data) { // dynamically allocating memory Node* temp = new Node(); temp->data = data; temp->left = temp->right = NULL; return temp; } // function to do inorder traversal void inorder(Node* root) { if (!root) return; inorder(root->left); cout << root->data << " "; inorder(root->right); } int main() { Node* root = newNode(5); root->left = newNode(7); root->right = newNode(9); root->right->left = newNode(10); root->left->left = newNode(1); root->left->right = newNode(6); root->right->right = newNode(11); /* Constructing tree given in the above figure 5 / \ 7 9 /\ / \ 1 6 10 11 */ // converting the above Binary tree to BST binaryTreeToBST(root); cout << "Inorder traversal of BST is: " << endl; inorder(root); return 0; }
linear
nlogn
// C++ Code for the above approach #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, a pointer to left child and a pointer to right child */ class Node { public: int data; Node* left; Node* right; }; // Function to return a new Node Node* newNode(int data) { Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; return (node); } // Function to convert bst to // a doubly linked list void bstTodll(Node* root, Node*& head) { // if root is NULL if (!root) return; // Convert right subtree recursively bstTodll(root->right, head); // Update root root->right = head; // if head is not NULL if (head) { // Update left of the head head->left = root; } // Update head head = root; // Convert left subtree recursively bstTodll(root->left, head); } // Function to merge two sorted linked list Node* mergeLinkedList(Node* head1, Node* head2) { /*Create head and tail for result list*/ Node* head = NULL; Node* tail = NULL; while (head1 && head2) { if (head1->data < head2->data) { if (!head) head = head1; else { tail->right = head1; head1->left = tail; } tail = head1; head1 = head1->right; } else { if (!head) head = head2; else { tail->right = head2; head2->left = tail; } tail = head2; head2 = head2->right; } } while (head1) { tail->right = head1; head1->left = tail; tail = head1; head1 = head1->right; } while (head2) { tail->right = head2; head2->left = tail; tail = head2; head2 = head2->right; } // Return the created DLL return head; } // function to convert list to bst Node* sortedListToBST(Node*& head, int n) { // if no element is left or head is null if (n <= 0 || !head) return NULL; // Create left part from the list recursively Node* left = sortedListToBST(head, n / 2); Node* root = head; root->left = left; head = head->right; // Create left part from the list recursively root->right = sortedListToBST(head, n - (n / 2) - 1); // Return the root of BST return root; } // This function merges two balanced BSTs Node* mergeTrees(Node* root1, Node* root2, int m, int n) { // Convert BSTs into sorted Doubly Linked Lists Node* head1 = NULL; bstTodll(root1, head1); head1->left = NULL; Node* head2 = NULL; bstTodll(root2, head2); head2->left = NULL; // Merge the two sorted lists into one Node* head = mergeLinkedList(head1, head2); // Construct a tree from the merged lists return sortedListToBST(head, m + n); } void printInorder(Node* node) { // if current node is NULL if (!node) { return; } printInorder(node->left); // Print node of current data cout << node->data << " "; printInorder(node->right); } /* Driver code*/ int main() { /* Create following tree as first balanced BST 100 / \ 50 300 / \ 20 70 */ Node* root1 = newNode(100); root1->left = newNode(50); root1->right = newNode(300); root1->left->left = newNode(20); root1->left->right = newNode(70); /* Create following tree as second balanced BST 80 / \ 40 120 */ Node* root2 = newNode(80); root2->left = newNode(40); root2->right = newNode(120); // Function Call Node* mergedTree = mergeTrees(root1, root2, 5, 3); cout << "Following is Inorder traversal of the merged " "tree \n"; printInorder(mergedTree); return 0; } // This code is contributed by Tapesh(tapeshdua420)
constant
linear
#include <bits/stdc++.h> using namespace std; // Structure of a BST Node class node { public: int data; node *left; node *right; }; //.................... START OF STACK RELATED STUFF.................... // A stack node class snode { public: node *t; snode *next; }; // Function to add an element k to stack void push(snode **s, node *k) { snode *tmp = new snode(); //perform memory check here tmp->t = k; tmp->next = *s; (*s) = tmp; } // Function to pop an element t from stack node *pop(snode **s) { node *t; snode *st; st=*s; (*s) = (*s)->next; t = st->t; free(st); return t; } // Function to check whether the stack is empty or not int isEmpty(snode *s) { if (s == NULL ) return 1; return 0; } //.................... END OF STACK RELATED STUFF.................... /* Utility function to create a new Binary Tree node */ node* newNode (int data) { node *temp = new node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp; } /* A utility function to print Inorder traversal of a Binary Tree */ void inorder(node *root) { if (root != NULL) { inorder(root->left); cout<<root->data<<" "; inorder(root->right); } } // The function to print data of two BSTs in sorted order void merge(node *root1, node *root2) { // s1 is stack to hold nodes of first BST snode *s1 = NULL; // Current node of first BST node *current1 = root1; // s2 is stack to hold nodes of second BST snode *s2 = NULL; // Current node of second BST node *current2 = root2; // If first BST is empty, then output is inorder // traversal of second BST if (root1 == NULL) { inorder(root2); return; } // If second BST is empty, then output is inorder // traversal of first BST if (root2 == NULL) { inorder(root1); return ; } // Run the loop while there are nodes not yet printed. // The nodes may be in stack(explored, but not printed) // or may be not yet explored while (current1 != NULL || !isEmpty(s1) || current2 != NULL || !isEmpty(s2)) { // Following steps follow iterative Inorder Traversal if (current1 != NULL || current2 != NULL ) { // Reach the leftmost node of both BSTs and push ancestors of // leftmost nodes to stack s1 and s2 respectively if (current1 != NULL) { push(&s1, current1); current1 = current1->left; } if (current2 != NULL) { push(&s2, current2); current2 = current2->left; } } else { // If we reach a NULL node and either of the stacks is empty, // then one tree is exhausted, print the other tree if (isEmpty(s1)) { while (!isEmpty(s2)) { current2 = pop (&s2); current2->left = NULL; inorder(current2); } return ; } if (isEmpty(s2)) { while (!isEmpty(s1)) { current1 = pop (&s1); current1->left = NULL; inorder(current1); } return ; } // Pop an element from both stacks and compare the // popped elements current1 = pop(&s1); current2 = pop(&s2); // If element of first tree is smaller, then print it // and push the right subtree. If the element is larger, // then we push it back to the corresponding stack. if (current1->data < current2->data) { cout<<current1->data<<" "; current1 = current1->right; push(&s2, current2); current2 = NULL; } else { cout<<current2->data<<" "; current2 = current2->right; push(&s1, current1); current1 = NULL; } } } } /* Driver program to test above functions */ int main() { node *root1 = NULL, *root2 = NULL; /* Let us create the following tree as first tree 3 / \ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted nodes of both trees merge(root1, root2); return 0; } //This code is contributed by rathbhupendra
logn
linear
#include <bits/stdc++.h> using namespace std; // Structure of a BST Node class Node { public: int val; Node* left; Node* right; }; /* Utility function to create a new Binary Tree Node */ Node* newNode(int data) { Node* temp = new Node; temp->val = data; temp->left = nullptr; temp->right = nullptr; return temp; } vector<int> mergeTwoBST(Node* root1, Node* root2) { vector<int> res; stack<Node*> s1, s2; while (root1 || root2 || !s1.empty() || !s2.empty()) { while (root1) { s1.push(root1); root1 = root1->left; } while (root2) { s2.push(root2); root2 = root2->left; } // Step 3 Case 1:- if (s2.empty() || (!s1.empty() && s1.top()->val <= s2.top()->val)) { root1 = s1.top(); s1.pop(); res.push_back(root1->val); root1 = root1->right; } // Step 3 case 2 :- else { root2 = s2.top(); s2.pop(); res.push_back(root2->val); root2 = root2->right; } } return res; } /* Driver program to test above functions */ int main() { Node *root1 = nullptr, *root2 = nullptr; /* Let us create the following tree as first tree 3 / \ 1 5 */ root1 = newNode(3); root1->left = newNode(1); root1->right = newNode(5); /* Let us create the following tree as second tree 4 / \ 2 6 */ root2 = newNode(4); root2->left = newNode(2); root2->right = newNode(6); // Print sorted Nodes of both trees vector<int> ans = mergeTwoBST(root1, root2); for (auto it : ans) cout << it << " "; return 0; } // This code is contributed by Aditya kumar (adityakumar129)
logn
linear
// C++ program to find minimum value node in binary search // Tree. #include <bits/stdc++.h> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct node { int data; struct node* left; struct node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } /* Give a binary search tree and a number, inserts a new node with the given number in the correct place in the tree. Returns the new root pointer which the caller should then use (the standard trick to avoid using reference parameters). */ struct node* insert(struct node* node, int data) { /* 1. If the tree is empty, return a new, single node */ if (node == NULL) return (newNode(data)); else { /* 2. Otherwise, recur down the tree */ if (data <= node->data) node->left = insert(node->left, data); else node->right = insert(node->right, data); /* return the (unchanged) node pointer */ return node; } } /* Given a non-empty binary search tree, return the minimum data value found in that tree. Note that the entire tree does not need to be searched. */ int minValue(struct node* node) { struct node* current = node; /* loop down to find the leftmost leaf */ while (current->left != NULL) { current = current->left; } return (current->data); } /* Driver Code*/ int main() { struct node* root = NULL; root = insert(root, 4); insert(root, 2); insert(root, 1); insert(root, 3); insert(root, 6); insert(root, 5); // Function call cout << "\n Minimum value in BST is " << minValue(root); getchar(); return 0; } // This code is contributed by Mukul Singh.
linear
linear