code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
// C++ program to find maximum // in arr[] of size n #include <bits/stdc++.h> using namespace std; int largest(int arr[], int n) { int i; // Initialize maximum element int max = arr[0]; // Traverse array elements // from second and compare // every element with current max for (i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } // Driver Code int main() { int arr[] = {10, 324, 45, 90, 9808}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Largest in given array is " << largest(arr, n); return 0; } // This Code is contributed // by Shivi_Aggarwal
constant
linear
// C++ program to find maximum // in arr[] of size n #include <bits/stdc++.h> using namespace std; int largest(int arr[], int n, int i) { // last index // return the element if (i == n - 1) { return arr[i]; } // find the maximum from rest of the array int recMax = largest(arr, n, i + 1); // compare with i-th element and return return max(recMax, arr[i]); } // Driver Code int main() { int arr[] = { 10, 324, 45, 90, 9808 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Largest in given array is " << largest(arr, n, 0); return 0; } // This Code is contributed by Rajdeep Mallick
linear
linear
// C++ program to find maximum in arr[] of size n #include <bits/stdc++.h> using namespace std; // returns maximum in arr[] of size n int largest(int arr[], int n) { return *max_element(arr, arr+n); } int main() { int arr[] = {10, 324, 45, 90, 9808}; int n = sizeof(arr)/sizeof(arr[0]); cout << largest(arr, n); return 0; }
constant
linear
// C++ program for find the largest // three elements in an array #include <bits/stdc++.h> using namespace std; // Function to print three largest elements void print3largest(int arr[], int arr_size) { int first, second, third; // There should be atleast three elements if (arr_size < 3) { cout << " Invalid Input "; return; } third = first = second = INT_MIN; for(int i = 0; i < arr_size; i++) { // If current element is // greater than first if (arr[i] > first) { third = second; second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second && arr[i] != first) { third = second; second = arr[i]; } else if (arr[i] > third && arr[i] != second) third = arr[i]; } cout << "Three largest elements are " << first << " " << second << " " << third << endl; } // Driver code int main() { int arr[] = { 12, 13, 1, 10, 34, 11 }; int n = sizeof(arr) / sizeof(arr[0]); print3largest(arr, n); return 0; } // This code is contributed by Anjali_Chauhan
constant
linear
// C++ code to find largest three elements in an array #include <bits/stdc++.h> using namespace std; void find3largest(int arr[], int n) { sort(arr, arr + n); // It uses Tuned Quicksort with // avg. case Time complexity = O(nLogn) int check = 0, count = 1; for (int i = 1; i <= n; i++) { if (count < 4) { if (check != arr[n - i]) { // to handle duplicate values cout << arr[n - i] << " "; check = arr[n - i]; count++; } } else break; } } // Driver code int main() { int arr[] = { 12, 45, 1, -1, 45, 54, 23, 5, 0, -10 }; int n = sizeof(arr) / sizeof(arr[0]); find3largest(arr, n); } // This code is contributed by Aditya Kumar (adityakumar129)
constant
nlogn
#include <bits/stdc++.h> using namespace std; int main() { vector<int> V = { 11, 65, 193, 36, 209, 664, 32 }; partial_sort(V.begin(), V.begin() + 3, V.end(), greater<int>()); cout << "first = " << V[0] << "\n"; cout << "second = " << V[1] << "\n"; cout << "third = " << V[2] << "\n"; return 0; }
constant
nlogn
// Simple C++ program to find // all elements in array which // have at-least two greater // elements itself. #include<bits/stdc++.h> using namespace std; void findElements(int arr[], int n) { // Pick elements one by one and // count greater elements. If // count is more than 2, print // that element. for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) if (arr[j] > arr[i]) count++; if (count >= 2) cout << arr[i] << " "; } } // Driver code int main() { int arr[] = { 2, -6 ,3 , 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0; }
constant
quadratic
// Sorting based C++ program to // find all elements in array // which have atleast two greater // elements itself. #include<bits/stdc++.h> using namespace std; void findElements(int arr[], int n) { sort(arr, arr + n); for (int i = 0; i < n - 2; i++) cout << arr[i] << " "; } // Driver Code int main() { int arr[] = { 2, -6 ,3 , 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0; }
constant
nlogn
// C++ program to find all elements // in array which have atleast two // greater elements itself. #include<bits/stdc++.h> using namespace std; void findElements(int arr[], int n) { int first = INT_MIN, second = INT_MIN; for (int i = 0; i < n; i++) { /* If current element is smaller than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second) second = arr[i]; } for (int i = 0; i < n; i++) if (arr[i] < second) cout << arr[i] << " "; } // Driver code int main() { int arr[] = { 2, -6, 3, 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); findElements(arr, n); return 0; }
constant
linear
// CPP program to find mean and median of // an array #include <bits/stdc++.h> using namespace std; // Function for calculating mean double findMean(int a[], int n) { int sum = 0; for (int i = 0; i < n; i++) sum += a[i]; return (double)sum / (double)n; } // Function for calculating median double findMedian(int a[], int n) { // First we sort the array sort(a, a + n); // check for even case if (n % 2 != 0) return (double)a[n / 2]; return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; } // Driver code int main() { int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 }; int N = sizeof(a) / sizeof(a[0]); // Function call cout << "Mean = " << findMean(a, N) << endl; cout << "Median = " << findMedian(a, N) << endl; return 0; }
constant
nlogn
// C++ program to find med in // stream of running integers #include<bits/stdc++.h> using namespace std; // function to calculate med of stream void printMedians(double arr[], int n) { // max heap to store the smaller half elements priority_queue<double> s; // min heap to store the greater half elements priority_queue<double,vector<double>,greater<double> > g; double med = arr[0]; s.push(arr[0]); cout << med << endl; // reading elements of stream one by one /* At any time we try to make heaps balanced and their sizes differ by at-most 1. If heaps are balanced,then we declare median as average of min_heap_right.top() and max_heap_left.top() If heaps are unbalanced,then median is defined as the top element of heap of larger size */ for (int i=1; i < n; i++) { double x = arr[i]; // case1(left side heap has more elements) if (s.size() > g.size()) { if (x < med) { g.push(s.top()); s.pop(); s.push(x); } else g.push(x); med = (s.top() + g.top())/2.0; } // case2(both heaps are balanced) else if (s.size()==g.size()) { if (x < med) { s.push(x); med = (double)s.top(); } else { g.push(x); med = (double)g.top(); } } // case3(right side heap has more elements) else { if (x > med) { s.push(g.top()); g.pop(); g.push(x); } else s.push(x); med = (s.top() + g.top())/2.0; } cout << med << endl; } } // Driver program to test above functions int main() { // stream of integers double arr[] = {5, 15, 10, 20, 3}; int n = sizeof(arr)/sizeof(arr[0]); printMedians(arr, n); return 0; }
linear
nlogn
// CPP program to find minimum product of // k elements in an array #include <bits/stdc++.h> using namespace std; int minProduct(int arr[], int n, int k) { priority_queue<int, vector<int>, greater<int> > pq; for (int i = 0; i < n; i++) pq.push(arr[i]); int count = 0, ans = 1; // One by one extract items from max heap while (pq.empty() == false && count < k) { ans = ans * pq.top(); pq.pop(); count++; } return ans; } // Driver code int main() { int arr[] = { 198, 76, 544, 123, 154, 675 }; int k = 2; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum product is " << minProduct(arr, n, k); return 0; }
linear
nlogn
// A simple C++ program to find N maximum // combinations from two arrays, #include <bits/stdc++.h> using namespace std; // function to display first N maximum sum // combinations void KMaxCombinations(int A[], int B[], int N, int K) { // max heap. priority_queue<int> pq; // insert all the possible combinations // in max heap. for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) pq.push(A[i] + B[j]); // pop first N elements from max heap // and display them. int count = 0; while (count < K) { cout << pq.top() << endl; pq.pop(); count++; } } // Driver Code. int main() { int A[] = { 4, 2, 5, 1 }; int B[] = { 8, 0, 5, 3 }; int N = sizeof(A) / sizeof(A[0]); int K = 3; // Function call KMaxCombinations(A, B, N, K); return 0; }
quadratic
quadratic
// An efficient C++ program to find top K elements // from two arrays. #include <bits/stdc++.h> using namespace std; // Function prints k maximum possible combinations void KMaxCombinations(vector<int>& A, vector<int>& B, int K) { // sort both arrays A and B sort(A.begin(), A.end()); sort(B.begin(), B.end()); int N = A.size(); // Max heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue<pair<int, pair<int, int> > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices does not repeat inside max heap. set<pair<int, int> > my_set; // initialize the heap with the maximum sum // combination ie (A[N - 1] + B[N - 1]) // and also push indices (N - 1, N - 1) along // with sum. pq.push(make_pair(A[N - 1] + B[N - 1], make_pair(N - 1, N - 1))); my_set.insert(make_pair(N - 1, N - 1)); // iterate upto K for (int count = 0; count < K; count++) { // tuple format (sum, (i, j)). pair<int, pair<int, int> > temp = pq.top(); pq.pop(); cout << temp.first << endl; int i = temp.second.first; int j = temp.second.second; int sum = A[i - 1] + B[j]; // insert (A[i - 1] + B[j], (i - 1, j)) // into max heap. pair<int, int> temp1 = make_pair(i - 1, j); // insert only if the pair (i - 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } // insert (A[i] + B[j - 1], (i, j - 1)) // into max heap. sum = A[i] + B[j - 1]; temp1 = make_pair(i, j - 1); // insert only if the pair (i, j - 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } } } // Driver Code. int main() { vector<int> A = { 1, 4, 2, 3 }; vector<int> B = { 2, 5, 1, 6 }; int K = 4; // Function call KMaxCombinations(A, B, K); return 0; }
linear
nlogn
// CPP for printing smallest k numbers in order #include <algorithm> #include <iostream> using namespace std; // Function to print smallest k numbers // in arr[0..n-1] void printSmall(int arr[], int n, int k) { // For each arr[i] find whether // it is a part of n-smallest // with insertion sort concept for (int i = k; i < n; ++i) { // find largest from first k-elements int max_var = arr[k - 1]; int pos = k - 1; for (int j = k - 2; j >= 0; j--) { if (arr[j] > max_var) { max_var = arr[j]; pos = j; } } // if largest is greater than arr[i] // shift all element one place left if (max_var > arr[i]) { int j = pos; while (j < k - 1) { arr[j] = arr[j + 1]; j++; } // make arr[k-1] = arr[i] arr[k - 1] = arr[i]; } } // print result for (int i = 0; i < k; i++) cout << arr[i] << " "; } // Driver program int main() { int arr[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 5; printSmall(arr, n, k); return 0; }
constant
quadratic
// C++ program to prints first k pairs with least sum from two // arrays. #include<bits/stdc++.h> using namespace std; // Function to find k pairs with least sum such // that one element of a pair is from arr1[] and // other element is from arr2[] void kSmallestPair(int arr1[], int n1, int arr2[], int n2, int k) { if (k > n1*n2) { cout << "k pairs don't exist"; return ; } // Stores current index in arr2[] for // every element of arr1[]. Initially // all values are considered 0. // Here current index is the index before // which all elements are considered as // part of output. int index2[n1]; memset(index2, 0, sizeof(index2)); while (k > 0) { // Initialize current pair sum as infinite int min_sum = INT_MAX; int min_index = 0; // To pick next pair, traverse for all elements // of arr1[], for every element, find corresponding // current element in arr2[] and pick minimum of // all formed pairs. for (int i1 = 0; i1 < n1; i1++) { // Check if current element of arr1[] plus // element of array2 to be used gives minimum // sum if (index2[i1] < n2 && arr1[i1] + arr2[index2[i1]] < min_sum) { // Update index that gives minimum min_index = i1; // update minimum sum min_sum = arr1[i1] + arr2[index2[i1]]; } } cout << "(" << arr1[min_index] << ", " << arr2[index2[min_index]] << ") "; index2[min_index]++; k--; } } // Driver code int main() { int arr1[] = {1, 3, 11}; int n1 = sizeof(arr1) / sizeof(arr1[0]); int arr2[] = {2, 4, 8}; int n2 = sizeof(arr2) / sizeof(arr2[0]); int k = 4; kSmallestPair( arr1, n1, arr2, n2, k); return 0; }
linear
linear
// C++ program to Prints // first k pairs with // least sum from two arrays. #include <bits/stdc++.h> using namespace std; // Function to find k pairs // with least sum such // that one element of a pair // is from arr1[] and // other element is from arr2[] void kSmallestPair(vector<int> A, vector<int> B, int K) { int n = A.size(); // Min heap which contains tuple of the format // (sum, (i, j)) i and j are the indices // of the elements from array A // and array B which make up the sum. priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >, greater<pair<int, pair<int, int> > > > pq; // my_set is used to store the indices of // the pair(i, j) we use my_set to make sure // the indices does not repeat inside min heap. set<pair<int, int> > my_set; // initialize the heap with the minimum sum // combination i.e. (A[0] + B[0]) // and also push indices (0,0) along // with sum. pq.push(make_pair(A[0] + B[0], make_pair(0, 0))); my_set.insert(make_pair(0, 0)); // iterate upto K int flag = 1; for (int count = 0; count < K && flag; count++) { // tuple format (sum, i, j). pair<int, pair<int, int> > temp = pq.top(); pq.pop(); int i = temp.second.first; int j = temp.second.second; cout << "(" << A[i] << ", " << B[j] << ")" << endl; // Extracting pair with least sum such // that one element is from arr1 and // another is from arr2 // check if i+1 is in the range of our first array A flag = 0; if (i + 1 < A.size()) { int sum = A[i + 1] + B[j]; // insert (A[i + 1] + B[j], (i + 1, j)) // into min heap. pair<int, int> temp1 = make_pair(i + 1, j); // insert only if the pair (i + 1, j) is // not already present inside the map i.e. // no repeating pair should be present inside // the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag = 1; } // check if j+1 is in the range of our second array // B if (j + 1 < B.size()) { // insert (A[i] + B[j + 1], (i, j + 1)) // into min heap. int sum = A[i] + B[j + 1]; pair<int, int> temp1 = make_pair(i, j + 1); // insert only if the pair (i, j + 1) // is not present inside the heap. if (my_set.find(temp1) == my_set.end()) { pq.push(make_pair(sum, temp1)); my_set.insert(temp1); } flag = 1; } } } // Driver Code. int main() { vector<int> A = { 1 }; vector<int> B = { 2, 4, 5, 9 }; int K = 8; kSmallestPair(A, B, K); return 0; } // This code is contributed by Dhairya.
linear
nlogn
// C++ program to find k-th absolute difference // between two elements #include<bits/stdc++.h> using namespace std; // returns number of pairs with absolute difference // less than or equal to mid. int countPairs(int *a, int n, int mid) { int res = 0; for (int i = 0; i < n; ++i) // Upper bound returns pointer to position // of next higher number than a[i]+mid in // a[i..n-1]. We subtract (a + i + 1) from // this position to count res += upper_bound(a+i, a+n, a[i] + mid) - (a + i + 1); return res; } // Returns k-th absolute difference int kthDiff(int a[], int n, int k) { // Sort array sort(a, a+n); // Minimum absolute difference int low = a[1] - a[0]; for (int i = 1; i <= n-2; ++i) low = min(low, a[i+1] - a[i]); // Maximum absolute difference int high = a[n-1] - a[0]; // Do binary search for k-th absolute difference while (low < high) { int mid = (low+high)>>1; if (countPairs(a, n, mid) < k) low = mid + 1; else high = mid; } return low; } // Driver code int main() { int k = 3; int a[] = {1, 2, 3, 4}; int n = sizeof(a)/sizeof(a[0]); cout << kthDiff(a, n, k); return 0; }
constant
nlogn
// C++ program to find second largest element in an array #include <bits/stdc++.h> using namespace std; /* Function to print the second largest elements */ void print2largest(int arr[], int arr_size) { int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { printf(" Invalid Input "); return; } // sort the array sort(arr, arr + arr_size); // start from second last element as the largest element // is at last for (i = arr_size - 2; i >= 0; i--) { // if the element is not equal to largest element if (arr[i] != arr[arr_size - 1]) { printf("The second largest element is %d\n",arr[i]); return; } } printf("There is no second largest element\n"); } /* Driver program to test above function */ int main() { int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print2largest(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
nlogn
// C++ program to find the second largest element in the array #include <iostream> using namespace std; int secondLargest(int arr[], int n) { int largest = 0, secondLargest = -1; // finding the largest element in the array for (int i = 1; i < n; i++) { if (arr[i] > arr[largest]) largest = i; } // finding the largest element in the array excluding // the largest element calculated above for (int i = 0; i < n; i++) { if (arr[i] != arr[largest]) { // first change the value of second largest // as soon as the next element is found if (secondLargest == -1) secondLargest = i; else if (arr[i] > arr[secondLargest]) secondLargest = i; } } return secondLargest; } int main() { int arr[] = {10, 12, 20, 4}; int n = sizeof(arr)/sizeof(arr[0]); int second_Largest = secondLargest(arr, n); if (second_Largest == -1) cout << "Second largest didn't exit\n"; else cout << "Second largest : " << arr[second_Largest]; }
constant
linear
// C++ program to find the second largest element #include <iostream> using namespace std; // returns the index of second largest // if second largest didn't exist return -1 int secondLargest(int arr[], int n) { int first = 0, second = -1; for (int i = 1; i < n; i++) { if (arr[i] > arr[first]) { second = first; first = i; } else if (arr[i] < arr[first]) { if (second == -1 || arr[second] < arr[i]) second = i; } } return second; } int main() { int arr[] = {10, 12, 20, 4}; int index = secondLargest(arr, sizeof(arr)/sizeof(arr[0])); if (index == -1) cout << "Second Largest didn't exist"; else cout << "Second largest : " << arr[index]; }
constant
linear
// C++ implementation to find k numbers with most // occurrences in the given array #include <bits/stdc++.h> using namespace std; // Comparison function to sort the 'freq_arr[]' bool compare(pair<int, int> p1, pair<int, int> p2) { // If frequencies of two elements are same // then the larger number should come first if (p1.second == p2.second) return p1.first > p2.first; // Sort on the basis of decreasing order // of frequencies return p1.second > p2.second; } // Function to print the k numbers with most occurrences void print_N_mostFrequentNumber(int arr[], int N, int K) { // unordered_map 'mp' implemented as frequency hash // table unordered_map<int, int> mp; for (int i = 0; i < N; i++) mp[arr[i]]++; // store the elements of 'mp' in the vector 'freq_arr' vector<pair<int, int> > freq_arr(mp.begin(), mp.end()); // Sort the vector 'freq_arr' on the basis of the // 'compare' function sort(freq_arr.begin(), freq_arr.end(), compare); // display the top k numbers cout << K << " numbers with most occurrences are:\n"; for (int i = 0; i < K; i++) cout << freq_arr[i].first << " "; } // Driver's code int main() { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; // Function call print_N_mostFrequentNumber(arr, N, K); return 0; }
linear
nlogn
// C++ program to find k numbers with most // occurrences in the given array #include <bits/stdc++.h> using namespace std; // Function to print the k numbers with most occurrences void print_N_mostFrequentNumber(int arr[], int N, int K) { // HashMap to store count of the elements unordered_map<int, int> elementCount; for (int i = 0; i < N; i++) { elementCount[arr[i]]++; } // Array to store the elements according // to their frequency vector<vector<int> > frequency(N + 1); // Inserting elements in the frequency array for (auto element : elementCount) { frequency[element.second].push_back(element.first); } int count = 0; cout << K << " numbers with most occurrences are:\n"; for (int i = frequency.size() - 1; i >= 0; i--) { for (auto element : frequency[i]) { count++; cout << element << " "; } // if K elements have been printed if (count == K) return; } return; } // Driver's code int main() { int arr[] = { 3, 1, 4, 4, 5, 2, 6, 1 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 2; // Function call print_N_mostFrequentNumber(arr, N, K); return 0; }
linear
linear
//C++ simple approach to print smallest //and second smallest element. #include<bits/stdc++.h> using namespace std; int main() { int arr[]={111, 13, 25, 9, 34, 1}; int n=sizeof(arr)/sizeof(arr[0]); //sorting the array using //in-built sort function sort(arr,arr+n); //printing the desired element cout<<"smallest element is "<<arr[0]<<endl; cout<<"second smallest element is "<<arr[1]; return 0; } //this code is contributed by Machhaliya Muhammad
constant
nlogn
// C++ program to find smallest and // second smallest elements #include <bits/stdc++.h> using namespace std; /* For INT_MAX */ void print2Smallest(int arr[], int arr_size) { int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { cout<<" Invalid Input "; return; } first = second = INT_MAX; for (i = 0; i < arr_size ; i ++) { /* If current element is smaller than first then update both first and second */ if (arr[i] < first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] < second && arr[i] != first) second = arr[i]; } if (second == INT_MAX) cout << "There is no second smallest element\n"; else cout << "The smallest element is " << first << " and second " "Smallest element is " << second << endl; } /* Driver code */ int main() { int arr[] = {12, 13, 1, 10, 34, 1}; int n = sizeof(arr)/sizeof(arr[0]); print2Smallest(arr, n); return 0; } // This is code is contributed by rathbhupendra
constant
linear
// C++ program to find the smallest elements // missing in a sorted array. #include<bits/stdc++.h> using namespace std; int findFirstMissing(int array[], int start, int end) { if (start > end) return end + 1; if (start != array[start]) return start; int mid = (start + end) / 2; // Left half has all elements // from 0 to mid if (array[mid] == mid) return findFirstMissing(array, mid+1, end); return findFirstMissing(array, start, mid); } // Driver code int main() { int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Smallest missing element is " << findFirstMissing(arr, 0, n-1) << endl; } // This code is contributed by // Shivi_Aggarwal
logn
logn
//C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Program to find missing element int findFirstMissing(vector<int> arr , int start , int end,int first) { if (start < end) { int mid = (start + end) / 2; /** Index matches with value at that index, means missing element cannot be upto that po*/ if (arr[mid] != mid+first) return findFirstMissing(arr, start, mid , first); else return findFirstMissing(arr, mid + 1, end , first); } return start + first; } // Program to find Smallest // Missing in Sorted Array int findSmallestMissinginSortedArray(vector<int> arr) { // Check if 0 is missing // in the array if(arr[0] != 0) return 0; // Check is all numbers 0 to n - 1 // are present in array if(arr[arr.size() - 1] == arr.size() - 1) return arr.size(); int first = arr[0]; return findFirstMissing(arr, 0, arr.size() - 1, first); } // Driver program to test the above function int main() { vector<int> arr = {0, 1, 2, 3, 4, 5, 7}; int n = arr.size(); // Function Call cout<<"First Missing element is : "<<findSmallestMissinginSortedArray(arr); } // This code is contributed by mohit kumar 29.
logn
logn
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std; // Function to find the maximum sum int findMaxSum(vector<int> arr, int N) { // Declare dp array int dp[N][2]; if (N == 1) { return arr[0]; } // Initialize the values in dp array dp[0][0] = 0; dp[0][1] = arr[0]; // Loop to find the maximum possible sum for (int i = 1; i < N; i++) { dp[i][1] = dp[i - 1][0] + arr[i]; dp[i][0] = max(dp[i - 1][1], dp[i - 1][0]); } // Return the maximum sum return max(dp[N - 1][0], dp[N - 1][1]); } // Driver Code int main() { // Creating the array vector<int> arr = { 5, 5, 10, 100, 10, 5 }; int N = arr.size(); // Function call cout << findMaxSum(arr, N) << endl; return 0; }
linear
linear
// C++ code to implement the above approach #include <bits/stdc++.h> using namespace std; // Function to return max sum such that // no two elements are adjacent int FindMaxSum(vector<int> arr, int n) { int incl = arr[0]; int excl = 0; int excl_new; int i; for (i = 1; i < n; i++) { // Current max excluding i excl_new = max(incl, excl); // Current max including i incl = excl + arr[i]; excl = excl_new; } // Return max of incl and excl return max(incl, excl); } // Driver code int main() { vector<int> arr = { 5, 5, 10, 100, 10, 5 }; int N = arr.size(); // Function call cout << FindMaxSum(arr, N); return 0; } // This approach is contributed by Debanjan
constant
linear
// C++ program to demonstrate working of Square Root // Decomposition. #include "iostream" #include "math.h" using namespace std; #define MAXN 10000 #define SQRSIZE 100 int arr[MAXN]; // original array int block[SQRSIZE]; // decomposed array int blk_sz; // block size // Time Complexity : O(1) void update(int idx, int val) { int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val; } // Time Complexity : O(sqrt(n)) int query(int l, int r) { int sum = 0; while (l<r and l%blk_sz!=0 and l!=0) { // traversing first block in range sum += arr[l]; l++; } while (l+blk_sz-1 <= r) { // traversing completely overlapped blocks in range sum += block[l/blk_sz]; l += blk_sz; } while (l<=r) { // traversing last block in range sum += arr[l]; l++; } return sum; } // Fills values in input[] void preprocess(int input[], int n) { // initiating block pointer int blk_idx = -1; // calculating size of block blk_sz = sqrt(n); // building the decomposed array for (int i=0; i<n; i++) { arr[i] = input[i]; if (i%blk_sz == 0) { // entering next block // incrementing block pointer blk_idx++; } block[blk_idx] += arr[i]; } } // Driver code int main() { // We have used separate array for input because // the purpose of this code is to explain SQRT // decomposition in competitive programming where // we have multiple inputs. int input[] = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10}; int n = sizeof(input)/sizeof(input[0]); preprocess(input, n); cout << "query(3,8) : " << query(3, 8) << endl; cout << "query(1,6) : " << query(1, 6) << endl; update(8, 0); cout << "query(8,8) : " << query(8, 8) << endl; return 0; }
linear
linear
// C++ program to do range minimum query // using sparse table #include <bits/stdc++.h> using namespace std; #define MAX 500 // lookup[i][j] is going to store minimum // value in arr[i..j]. Ideally lookup table // size should not be fixed and should be // determined using n Log n. It is kept // constant to keep code simple. int lookup[MAX][MAX]; // Fills lookup array lookup[][] in bottom up manner. void buildSparseTable(int arr[], int n) { // Initialize M for the intervals with length 1 for (int i = 0; i < n; i++) lookup[i][0] = arr[i]; // Compute values from smaller to bigger intervals for (int j = 1; (1 << j) <= n; j++) { // Compute minimum value for all intervals with // size 2^j for (int i = 0; (i + (1 << j) - 1) < n; i++) { // For arr[2][10], we compare arr[lookup[0][7]] // and arr[lookup[3][10]] if (lookup[i][j - 1] < lookup[i + (1 << (j - 1))][j - 1]) lookup[i][j] = lookup[i][j - 1]; else lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1]; } } } // Returns minimum of arr[L..R] int query(int L, int R) { // Find highest power of 2 that is smaller // than or equal to count of elements in given // range. For [2, 10], j = 3 int j = (int)log2(R - L + 1); // Compute minimum of last 2^j elements with first // 2^j elements in range. // For [2, 10], we compare arr[lookup[0][3]] and // arr[lookup[3][3]], if (lookup[L][j] <= lookup[R - (1 << j) + 1][j]) return lookup[L][j]; else return lookup[R - (1 << j) + 1][j]; } // Driver program int main() { int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = sizeof(a) / sizeof(a[0]); buildSparseTable(a, n); cout << query(0, 4) << endl; cout << query(4, 7) << endl; cout << query(7, 8) << endl; return 0; }
nlogn
nlogn
// C++ program to do range minimum query // using sparse table #include <bits/stdc++.h> using namespace std; #define MAX 500 // lookup[i][j] is going to store GCD of // arr[i..j]. Ideally lookup table // size should not be fixed and should be // determined using n Log n. It is kept // constant to keep code simple. int table[MAX][MAX]; // it builds sparse table. void buildSparseTable(int arr[], int n) { // GCD of single element is element itself for (int i = 0; i < n; i++) table[i][0] = arr[i]; // Build sparse table for (int j = 1; j <= log2(n); j++) for (int i = 0; i <= n - (1 << j); i++) table[i][j] = __gcd(table[i][j - 1], table[i + (1 << (j - 1))][j - 1]); } // Returns GCD of arr[L..R] int query(int L, int R) { // Find highest power of 2 that is smaller // than or equal to count of elements in given // range.For [2, 10], j = 3 int j = (int)log2(R - L + 1); // Compute GCD of last 2^j elements with first // 2^j elements in range. // For [2, 10], we find GCD of arr[lookup[0][3]] and // arr[lookup[3][3]], return __gcd(table[L][j], table[R - (1 << j) + 1][j]); } // Driver program int main() { int a[] = { 7, 2, 3, 0, 5, 10, 3, 12, 18 }; int n = sizeof(a) / sizeof(a[0]); buildSparseTable(a, n); cout << query(0, 2) << endl; cout << query(1, 3) << endl; cout << query(4, 5) << endl; return 0; }
nlogn
nlogn
// C++ program to find total count of an element // in a range #include<bits/stdc++.h> using namespace std; // Returns count of element in arr[left-1..right-1] int findFrequency(int arr[], int n, int left, int right, int element) { int count = 0; for (int i=left-1; i<=right; ++i) if (arr[i] == element) ++count; return count; } // Driver Code int main() { int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Print frequency of 2 from position 1 to 6 cout << "Frequency of 2 from 1 to 6 = " << findFrequency(arr, n, 1, 6, 2) << endl; // Print frequency of 8 from position 4 to 9 cout << "Frequency of 8 from 4 to 9 = " << findFrequency(arr, n, 4, 9, 8); return 0; }
constant
linear
// C++ program to get updated array after many array range // add operation #include <bits/stdc++.h> using namespace std; // Utility method to add value val, to range [lo, hi] void add(int arr[], int N, int lo, int hi, int val) { arr[lo] += val; if (hi != N - 1) arr[hi + 1] -= val; } // Utility method to get actual array from operation array void updateArray(int arr[], int N) { // convert array into prefix sum array for (int i = 1; i < N; i++) arr[i] += arr[i - 1]; } // method to print final updated array void printArr(int arr[], int N) { updateArray(arr, N); for (int i = 0; i < N; i++) cout << arr[i] << " "; cout << endl; } // Driver code int main() { int N = 6; int arr[N] = {0}; // Range add Queries add(arr, N, 0, 2, 100); add(arr, N, 1, 5, 100); add(arr, N, 2, 3, 100); printArr(arr, N); return 0; }
constant
linear
// C++ program for queries of GCD excluding // given range of elements. #include<bits/stdc++.h> using namespace std; // Filling the prefix and suffix array void FillPrefixSuffix(int prefix[], int arr[], int suffix[], int n) { // Filling the prefix array following relation // prefix(i) = __gcd(prefix(i-1), arr(i)) prefix[0] = arr[0]; for (int i=1 ;i<n; i++) prefix[i] = __gcd(prefix[i-1], arr[i]); // Filling the suffix array following the // relation suffix(i) = __gcd(suffix(i+1), arr(i)) suffix[n-1] = arr[n-1]; for (int i=n-2; i>=0 ;i--) suffix[i] = __gcd(suffix[i+1], arr[i]); } // To calculate gcd of the numbers outside range int GCDoutsideRange(int l, int r, int prefix[], int suffix[], int n) { // If l=0, we need to tell GCD of numbers // from r+1 to n if (l==0) return suffix[r+1]; // If r=n-1 we need to return the gcd of // numbers from 1 to l if (r==n-1) return prefix[l-1]; return __gcd(prefix[l-1], suffix[r+1]); } // Driver function int main() { int arr[] = {2, 6, 9}; int n = sizeof(arr)/sizeof(arr[0]); int prefix[n], suffix[n]; FillPrefixSuffix(prefix, arr, suffix, n); int l = 0, r = 0; cout << GCDoutsideRange(l, r, prefix, suffix, n) << endl; l = 1 ; r = 1; cout << GCDoutsideRange(l, r, prefix, suffix, n) << endl; l = 1 ; r = 2; cout << GCDoutsideRange(l, r, prefix, suffix, n) << endl; return 0; }
linear
nlogn
// C++ implementation of finding number // represented by binary subarray #include <bits/stdc++.h> using namespace std; // Fills pre[] void precompute(int arr[], int n, int pre[]) { memset(pre, 0, n * sizeof(int)); pre[n - 1] = arr[n - 1] * pow(2, 0); for (int i = n - 2; i >= 0; i--) pre[i] = pre[i + 1] + arr[i] * (1 << (n - 1 - i)); } // returns the number represented by a binary // subarray l to r int decimalOfSubarr(int arr[], int l, int r, int n, int pre[]) { // if r is equal to n-1 r+1 does not exist if (r != n - 1) return (pre[l] - pre[r + 1]) / (1 << (n - 1 - r)); return pre[l] / (1 << (n - 1 - r)); } // Driver Function int main() { int arr[] = { 1, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); int pre[n]; precompute(arr, n, pre); cout << decimalOfSubarr(arr, 2, 4, n, pre) << endl; cout << decimalOfSubarr(arr, 4, 5, n, pre) << endl; return 0; }
linear
linear
// CPP program to perform range queries over range // queries. #include <bits/stdc++.h> #define max 10000 using namespace std; // For prefix sum array void update(int arr[], int l) { arr[l] += arr[l - 1]; } // This function is used to apply square root // decomposition in the record array void record_func(int block_size, int block[], int record[], int l, int r, int value) { // traversing first block in range while (l < r && l % block_size != 0 && l != 0) { record[l] += value; l++; } // traversing completely overlapped blocks in range while (l + block_size <= r + 1) { block[l / block_size] += value; l += block_size; } // traversing last block in range while (l <= r) { record[l] += value; l++; } } // Function to print the resultant array void print(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; } // Driver code int main() { int n = 5, m = 5; int arr[n], record[m]; int block_size = sqrt(m); int block[max]; int command[5][3] = { { 1, 1, 2 }, { 1, 4, 5 }, { 2, 1, 2 }, { 2, 1, 3 }, { 2, 3, 4 } }; memset(arr, 0, sizeof arr); memset(record, 0, sizeof record); memset(block, 0, sizeof block); for (int i = m - 1; i >= 0; i--) { // If query is of type 2 then function // call to record_func if (command[i][0] == 2) { int x = i / (block_size); record_func(block_size, block, record, command[i][1] - 1, command[i][2] - 1, (block[x] + record[i] + 1)); } // If query is of type 1 then simply add // 1 to the record array else record[i]++; } // Merging the value of the block in the record array for (int i = 0; i < m; i++) { int check = (i / block_size); record[i] += block[check]; } for (int i = 0; i < m; i++) { // If query is of type 1 then the array // elements are over-written by the record // array if (command[i][0] == 1) { arr[command[i][1] - 1] += record[i]; if ((command[i][2] - 1) < n - 1) arr[(command[i][2])] -= record[i]; } } // The prefix sum of the array for (int i = 1; i < n; i++) update(arr, i); // Printing the resultant array print(arr, n); return 0; }
linear
logn
// CPP program to count the number of indexes // in range L R such that Ai = Ai+1 #include <bits/stdc++.h> using namespace std; // function that answers every query in O(r-l) int answer_query(int a[], int n, int l, int r) { // traverse from l to r and count // the required indexes int count = 0; for (int i = l; i < r; i++) if (a[i] == a[i + 1]) count += 1; return count; } // Driver Code int main() { int a[] = { 1, 2, 2, 2, 3, 3, 4, 4, 4 }; int n = sizeof(a) / sizeof(a[0]); // 1-st query int L, R; L = 1; R = 8; cout << answer_query(a, n, L, R) << endl; // 2nd query L = 0; R = 4; cout << answer_query(a, n, L, R) << endl; return 0; }
constant
constant
// CPP program to count the number of indexes // in range L R such that Ai=Ai+1 #include <bits/stdc++.h> using namespace std; const int N = 1000; // array to store count of index from 0 to // i that obey condition int prefixans[N]; // precomputing prefixans[] array int countIndex(int a[], int n) { // traverse to compute the prefixans[] array for (int i = 0; i < n; i++) { if (a[i] == a[i + 1]) prefixans[i] = 1; if (i != 0) prefixans[i] += prefixans[i - 1]; } } // function that answers every query in O(1) int answer_query(int l, int r) { if (l == 0) return prefixans[r - 1]; else return prefixans[r - 1] - prefixans[l - 1]; } // Driver Code int main() { int a[] = { 1, 2, 2, 2, 3, 3, 4, 4, 4 }; int n = sizeof(a) / sizeof(a[0]); // pre-computation countIndex(a, n); int L, R; // 1-st query L = 1; R = 8; cout << answer_query(L, R) << endl; // 2nd query L = 0; R = 4; cout << answer_query(L, R) << endl; return 0; }
linear
linear
// C++ program to print largest contiguous array sum #include <bits/stdc++.h> using namespace std; int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } // Driver Code int main() { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = sizeof(a) / sizeof(a[0]); // Function Call int max_sum = maxSubArraySum(a, n); cout << "Maximum contiguous sum is " << max_sum; return 0; }
constant
linear
// C++ program to print largest contiguous array sum #include <climits> #include <iostream> using namespace std; void maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0, start = 0, end = 0, s = 0; for (int i = 0; i < size; i++) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } cout << "Maximum contiguous sum is " << max_so_far << endl; cout << "Starting index " << start << endl << "Ending index " << end << endl; } /*Driver program to test maxSubArraySum*/ int main() { int a[] = { -2, -3, 4, -1, -2, 1, 5, -3 }; int n = sizeof(a) / sizeof(a[0]); int max_sum = maxSubArraySum(a, n); return 0; }
constant
linear
// C++ program to find maximum // possible profit with at most // two transactions #include <bits/stdc++.h> using namespace std; // Returns maximum profit with // two transactions on a given // list of stock prices, price[0..n-1] int maxProfit(int price[], int n) { // Create profit array and // initialize it as 0 int* profit = new int[n]; for (int i = 0; i < n; i++) profit[i] = 0; /* Get the maximum profit with only one transaction allowed. After this loop, profit[i] contains maximum profit from price[i..n-1] using at most one trans. */ int max_price = price[n - 1]; for (int i = n - 2; i >= 0; i--) { // max_price has maximum // of price[i..n-1] if (price[i] > max_price) max_price = price[i]; // we can get profit[i] by taking maximum of: // a) previous maximum, i.e., profit[i+1] // b) profit by buying at price[i] and selling at // max_price profit[i] = max(profit[i + 1], max_price - price[i]); } /* Get the maximum profit with two transactions allowed After this loop, profit[n-1] contains the result */ int min_price = price[0]; for (int i = 1; i < n; i++) { // min_price is minimum price in price[0..i] if (price[i] < min_price) min_price = price[i]; // Maximum profit is maximum of: // a) previous maximum, i.e., profit[i-1] // b) (Buy, Sell) at (min_price, price[i]) and add // profit of other trans. stored in profit[i] profit[i] = max(profit[i - 1], profit[i] + (price[i] - min_price)); } int result = profit[n - 1]; delete[] profit; // To avoid memory leak return result; } // Driver code int main() { int price[] = { 2, 30, 15, 10, 8, 25, 80 }; int n = sizeof(price) / sizeof(price[0]); cout << "Maximum Profit = " << maxProfit(price, n); return 0; }
linear
linear
#include <iostream> #include<climits> using namespace std; int maxtwobuysell(int arr[],int size) { int first_buy = INT_MIN; int first_sell = 0; int second_buy = INT_MIN; int second_sell = 0; for(int i=0;i<size;i++) { first_buy = max(first_buy,-arr[i]);//we set prices to negative, so the calculation of profit will be convenient first_sell = max(first_sell,first_buy+arr[i]); second_buy = max(second_buy,first_sell-arr[i]);//we can buy the second only after first is sold second_sell = max(second_sell,second_buy+arr[i]); } return second_sell; } int main() { int arr[] = {2, 30, 15, 10, 8, 25, 80}; int size = sizeof(arr)/sizeof(arr[0]); cout<<maxtwobuysell(arr,size); return 0; }
constant
linear
//C++ code of Naive approach to //find subarray with minimum average #include<bits/stdc++.h> using namespace std; //function to find subarray void findsubarrayleast(int arr[],int k,int n){ int min=INT_MAX,minindex; for (int i = 0; i <= n-k; i++) { int sum=0; for (int j = i; j < i+k; j++) { sum+=arr[j]; } if(sum<min){ min=sum; minindex=i; } } //printing the desired subarray cout<<"subarray with minimum average is: "; for (int i = minindex; i < minindex+k; i++) { cout<<arr[i]<<" "; } } //driver code int main() { int arr[]={3, 7, 90, 20, 10, 50, 40}; int n=sizeof(arr)/sizeof(arr[0]),k=3; //function call findsubarrayleast(arr,k,n); return 0; } //this code is contributed by Machhaliya Muhammad
constant
quadratic
// A Simple C++ program to find minimum average subarray #include <bits/stdc++.h> using namespace std; // Prints beginning and ending indexes of subarray // of size k with minimum average void findMinAvgSubarray(int arr[], int n, int k) { // k must be smaller than or equal to n if (n < k) return; // Initialize beginning index of result int res_index = 0; // Compute sum of first subarray of size k int curr_sum = 0; for (int i = 0; i < k; i++) curr_sum += arr[i]; // Initialize minimum sum as current sum int min_sum = curr_sum; // Traverse from (k+1)'th element to n'th element for (int i = k; i < n; i++) { // Add current item and remove first item of // previous subarray curr_sum += arr[i] - arr[i - k]; // Update result if needed if (curr_sum < min_sum) { min_sum = curr_sum; res_index = (i - k + 1); } } cout << "Subarray between [" << res_index << ", " << res_index + k - 1 << "] has minimum average"; } // Driver program int main() { int arr[] = { 3, 7, 90, 20, 10, 50, 40 }; int k = 3; // Subarray size int n = sizeof arr / sizeof arr[0]; findMinAvgSubarray(arr, n, k); return 0; }
constant
linear
// C++ program to Find the minimum // distance between two numbers #include <bits/stdc++.h> using namespace std; int minDist(int arr[], int n, int x, int y) { int i, j; int min_dist = INT_MAX; for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j]) && min_dist > abs(i - j)) { min_dist = abs(i - j); } } } if (min_dist > n) { return -1; } return min_dist; } /* Driver code */ int main() { int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << "Minimum distance between " << x << " and " << y << " is " << minDist(arr, n, x, y) << endl; } // This code is contributed by Shivi_Aggarwal
constant
quadratic
// C++ implementation of above approach #include <bits/stdc++.h> using namespace std; int minDist(int arr[], int n, int x, int y) { //previous index and min distance int p = -1, min_dist = INT_MAX; for(int i=0 ; i<n ; i++) { if(arr[i]==x || arr[i]==y) { //we will check if p is not equal to -1 and //If the element at current index matches with //the element at index p , If yes then update //the minimum distance if needed if( p != -1 && arr[i] != arr[p]) min_dist = min(min_dist , i-p); //update the previous index p=i; } } //If distance is equal to int max if(min_dist==INT_MAX) return -1; return min_dist; } /* Driver code */ int main() { int arr[] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3}; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << "Minimum distance between " << x << " and " << y << " is "<< minDist(arr, n, x, y) << endl; return 0; } // This code is contributed by Mukul singh.
constant
linear
// C++ program to Find the minimum // distance between two numbers #include <bits/stdc++.h> using namespace std; int minDist(int arr[], int n, int x, int y) { //idx1 and idx2 will store indices of //x or y and min_dist will store the minimum difference int idx1=-1,idx2=-1,min_dist = INT_MAX; for(int i=0;i<n;i++) { //if current element is x then change idx1 if(arr[i]==x) { idx1=i; } //if current element is y then change idx2 else if(arr[i]==y) { idx2=i; } //if x and y both found in array //then only find the difference and store it in min_dist if(idx1!=-1 && idx2!=-1) min_dist=min(min_dist,abs(idx1-idx2)); } //if left or right did not found in array //then return -1 if(idx1==-1||idx2==-1) return -1; //return the minimum distance else return min_dist; } /* Driver code */ int main() { int arr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 3; int y = 6; cout << "Minimum distance between " << x << " and " << y << " is " << minDist(arr, n, x, y) << endl; }
constant
linear
// C++ Code for the Approach #include <bits/stdc++.h> using namespace std; // User function Template int getMinDiff(int arr[], int n, int k) { sort(arr, arr + n); // Maximum possible height difference int ans = arr[n - 1] - arr[0]; int tempmin, tempmax; tempmin = arr[0]; tempmax = arr[n - 1]; for (int i = 1; i < n; i++) { // If on subtracting k we got // negative then continue if (arr[i] - k < 0) continue; // Minimum element when we // add k to whole array tempmin = min(arr[0] + k, arr[i] - k); // Maximum element when we // subtract k from whole array tempmax = max(arr[i - 1] + k, arr[n - 1] - k); ans = min(ans, tempmax - tempmin); } return ans; } // Driver Code Starts int main() { int k = 6, n = 6; int arr[n] = { 7, 4, 8, 8, 8, 9 }; // Function Call int ans = getMinDiff(arr, n, k); cout << ans; }
constant
nlogn
// C++ program to find Minimum // number of jumps to reach end #include <bits/stdc++.h> using namespace std; // Function to return the minimum number // of jumps to reach arr[h] from arr[l] int minJumps(int arr[], int n) { // Base case: when source and // destination are same if (n == 1) return 0; // Traverse through all the points // reachable from arr[l] // Recursively, get the minimum number // of jumps needed to reach arr[h] from // these reachable points int res = INT_MAX; for (int i = n - 2; i >= 0; i--) { if (i + arr[i] >= n - 1) { int sub_res = minJumps(arr, i + 1); if (sub_res != INT_MAX) res = min(res, sub_res + 1); } } return res; } // Driver Code int main() { int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Minimum number of jumps to"; cout << " reach the end is " << minJumps(arr, n); return 0; } // This code is contributed // by Shivi_Aggarwal
linear
np
// C++ program for Minimum number // of jumps to reach end #include <bits/stdc++.h> using namespace std; int min(int x, int y) { return (x < y) ? x : y; } // Returns minimum number of jumps // to reach arr[n-1] from arr[0] int minJumps(int arr[], int n) { // jumps[n-1] will hold the result int* jumps = new int[n]; int i, j; if (n == 0 || arr[0] == 0) return INT_MAX; jumps[0] = 0; // Find the minimum number of jumps to reach arr[i] // from arr[0], and assign this value to jumps[i] for (i = 1; i < n; i++) { jumps[i] = INT_MAX; for (j = 0; j < i; j++) { if (i <= j + arr[j] && jumps[j] != INT_MAX) { jumps[i] = min(jumps[i], jumps[j] + 1); break; } } } return jumps[n - 1]; } // Driver code int main() { int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 }; int size = sizeof(arr) / sizeof(int); cout << "Minimum number of jumps to reach end is " << minJumps(arr, size); return 0; } // This is code is contributed by rathbhupendra
linear
np
// C++ program to find Minimum number of jumps to reach end #include <bits/stdc++.h> using namespace std; // Returns Minimum number of jumps to reach end int minJumps(int arr[], int n) { // jumps[0] will hold the result int* jumps = new int[n]; int min; // Minimum number of jumps needed to reach last element // from last elements itself is always 0 jumps[n - 1] = 0; // Start from the second element, move from right to // left and construct the jumps[] array where jumps[i] // represents minimum number of jumps needed to reach // arr[m-1] from arr[i] for (int i = n - 2; i >= 0; i--) { // If arr[i] is 0 then arr[n-1] can't be reached // from here if (arr[i] == 0) jumps[i] = INT_MAX; // If we can directly reach to the end point from // here then jumps[i] is 1 else if (arr[i] >= n - i - 1) jumps[i] = 1; // Otherwise, to find out the minimum number of // jumps needed to reach arr[n-1], check all the // points reachable from here and jumps[] value for // those points else { // initialize min value min = INT_MAX; // following loop checks with all reachable // points and takes the minimum for (int j = i + 1; j < n && j <= arr[i] + i; j++) { if (min > jumps[j]) min = jumps[j]; } // Handle overflow if (min != INT_MAX) jumps[i] = min + 1; else jumps[i] = min; // or INT_MAX } } return jumps[0]; } // Driver program to test above function int main() { int arr[] = { 1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9 }; int size = sizeof(arr) / sizeof(int); cout << "Minimum number of jumps to reach" << " end is " << minJumps(arr, size); return 0; } // This code is contributed by Sania Kumari Gupta
linear
quadratic
/* Dynamic Programming implementation of Maximum Sum Increasing Subsequence (MSIS) problem */ #include <bits/stdc++.h> using namespace std; /* maxSumIS() returns the maximum sum of increasing subsequence in arr[] of size n */ int maxSumIS(int arr[], int n) { int i, j, max = 0; int msis[n]; /* Initialize msis values for all indexes */ for ( i = 0; i < n; i++ ) msis[i] = arr[i]; /* Compute maximum sum values in bottom up manner */ for ( i = 1; i < n; i++ ) for ( j = 0; j < i; j++ ) if (arr[i] > arr[j] && msis[i] < msis[j] + arr[i]) msis[i] = msis[j] + arr[i]; /* Pick maximum of all msis values */ for ( i = 0; i < n; i++ ) if ( max < msis[i] ) max = msis[i]; return max; } // Driver Code int main() { int arr[] = {1, 101, 2, 3, 100, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Sum of maximum sum increasing " "subsequence is " << maxSumIS( arr, n ) << endl; return 0; } // This is code is contributed by rathbhupendra
linear
quadratic
# include <iostream> using namespace std; // Returns length of smallest subarray with sum greater than x. // If there is no subarray with given sum, then returns n+1 int smallestSubWithSum(int arr[], int n, int x) { // Initialize length of smallest subarray as n+1 int min_len = n + 1; // Pick every element as starting point for (int start=0; start<n; start++) { // Initialize sum starting with current start int curr_sum = arr[start]; // If first element itself is greater if (curr_sum > x) return 1; // Try different ending points for current start for (int end=start+1; end<n; end++) { // add last element to current sum curr_sum += arr[end]; // If sum becomes more than x and length of // this subarray is smaller than current smallest // length, update the smallest length (or result) if (curr_sum > x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len; } /* Driver program to test above function */ int main() { int arr1[] = {1, 4, 45, 6, 10, 19}; int x = 51; int n1 = sizeof(arr1)/sizeof(arr1[0]); int res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1+1)? cout << "Not possible\n" : cout << res1 << endl; int arr2[] = {1, 10, 5, 2, 7}; int n2 = sizeof(arr2)/sizeof(arr2[0]); x = 9; int res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2+1)? cout << "Not possible\n" : cout << res2 << endl; int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; int n3 = sizeof(arr3)/sizeof(arr3[0]); x = 280; int res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3+1)? cout << "Not possible\n" : cout << res3 << endl; return 0; }
constant
quadratic
// O(n) solution for finding smallest subarray with sum // greater than x #include <iostream> using namespace std; // Returns length of smallest subarray with sum greater than // x. If there is no subarray with given sum, then returns // n+1 int smallestSubWithSum(int arr[], int n, int x) { // Initialize current sum and minimum length int curr_sum = 0, min_len = n + 1; // Initialize starting and ending indexes int start = 0, end = 0; while (end < n) { // Keep adding array elements while current sum // is smaller than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes greater than x. while (curr_sum > x && start < n) { // Update minimum length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len; } /* Driver program to test above function */ int main() { int arr1[] = { 1, 4, 45, 6, 10, 19 }; int x = 51; int n1 = sizeof(arr1) / sizeof(arr1[0]); int res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1 + 1) ? cout << "Not possible\n" : cout << res1 << endl; int arr2[] = { 1, 10, 5, 2, 7 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); x = 9; int res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2 + 1) ? cout << "Not possible\n" : cout << res2 << endl; int arr3[] = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 }; int n3 = sizeof(arr3) / sizeof(arr3[0]); x = 280; int res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3 + 1) ? cout << "Not possible\n" : cout << res3 << endl; return 0; }
constant
linear
// C++ program to find maximum average subarray // of given length. #include<bits/stdc++.h> using namespace std; // Returns beginning index of maximum average // subarray of length 'k' int findMaxAverage(int arr[], int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Create and fill array to store cumulative // sum. csum[i] stores sum of arr[0] to arr[i] int *csum = new int[n]; csum[0] = arr[0]; for (int i=1; i<n; i++) csum[i] = csum[i-1] + arr[i]; // Initialize max_sm as sum of first subarray int max_sum = csum[k-1], max_end = k-1; // Find sum of other subarrays and update // max_sum if required. for (int i=k; i<n; i++) { int curr_sum = csum[i] - csum[i-k]; if (curr_sum > max_sum) { max_sum = curr_sum; max_end = i; } } delete [] csum; // To avoid memory leak // Return starting index return max_end - k + 1; } // Driver program int main() { int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << "The maximum average subarray of " "length "<< k << " begins at index " << findMaxAverage(arr, n, k); return 0; }
linear
linear
// C++ program to find maximum average subarray // of given length. #include<bits/stdc++.h> using namespace std; // Returns beginning index of maximum average // subarray of length 'k' int findMaxAverage(int arr[], int n, int k) { // Check if 'k' is valid if (k > n) return -1; // Compute sum of first 'k' elements int sum = arr[0]; for (int i=1; i<k; i++) sum += arr[i]; int max_sum = sum, max_end = k-1; // Compute sum of remaining subarrays for (int i=k; i<n; i++) { sum = sum + arr[i] - arr[i-k]; if (sum > max_sum) { max_sum = sum; max_end = i; } } // Return starting index return max_end - k + 1; } // Driver program int main() { int arr[] = {1, 12, -5, -6, 50, 3}; int k = 4; int n = sizeof(arr)/sizeof(arr[0]); cout << "The maximum average subarray of " "length "<< k << " begins at index " << findMaxAverage(arr, n, k); return 0; }
constant
linear
/* C++ program to count minimum number of operations to get the given target array */ #include <bits/stdc++.h> using namespace std; // Returns count of minimum operations to convert a // zero array to target array with increment and // doubling operations. // This function computes count by doing reverse // steps, i.e., convert target to zero array. int countMinOperations(unsigned int target[], int n) { // Initialize result (Count of minimum moves) int result = 0; // Keep looping while all elements of target // don't become 0. while (1) { // To store count of zeroes in current // target array int zero_count = 0; int i; // To find first odd element for (i=0; i<n; i++) { // If odd number found if (target[i] & 1) break; // If 0, then increment zero_count else if (target[i] == 0) zero_count++; } // All numbers are 0 if (zero_count == n) return result; // All numbers are even if (i == n) { // Divide the whole array by 2 // and increment result for (int j=0; j<n; j++) target[j] = target[j]/2; result++; } // Make all odd numbers even by subtracting // one and increment result. for (int j=i; j<n; j++) { if (target[j] & 1) { target[j]--; result++; } } } } /* Driver program to test above functions*/ int main() { unsigned int arr[] = {16, 16, 16}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Minimum number of steps required to " "get the given target array is " << countMinOperations(arr, n); return 0; }
constant
linear
// C++ program to find number of operations // to make an array palindrome #include <bits/stdc++.h> using namespace std; // Returns minimum number of count operations // required to make arr[] palindrome int findMinOps(int arr[], int n) { int ans = 0; // Initialize result // Start from two corners for (int i=0,j=n-1; i<=j;) { // If corner elements are same, // problem reduces arr[i+1..j-1] if (arr[i] == arr[j]) { i++; j--; } // If left element is greater, then // we merge right two elements else if (arr[i] > arr[j]) { // need to merge from tail. j--; arr[j] += arr[j+1] ; ans++; } // Else we merge left two elements else { i++; arr[i] += arr[i-1]; ans++; } } return ans; } // Driver program to test above int main() { int arr[] = {1, 4, 5, 9, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Count of minimum operations is " << findMinOps(arr, n) << endl; return 0; }
constant
linear
// C++ program to find the smallest positive value that cannot be // represented as sum of subsets of a given sorted array #include<iostream> #include<vector> #include<algorithm> using namespace std; // Returns the smallest number that cannot be represented as sum // of subset of elements from set represented by sorted array arr[0..n-1] long long smallestpositive(vector<long long> arr, int n) { long long int res = 1; // Initialize result sort(arr.begin(), arr.end()); // Traverse the array and increment 'res' if arr[i] is // smaller than or equal to 'res'. for (int i = 0; i < n && arr[i] <= res; i++) res = res + arr[i]; return res; } // Driver program to test above function int main() { vector<long long> arr1 = {1, 3, 4, 5}; cout << smallestpositive(arr1, arr1.size()) << endl; vector<long long> arr2 = {1, 2, 6, 10, 11, 15}; cout << smallestpositive(arr2, arr2.size()) << endl; vector<long long> arr3 = {1, 1, 1, 1}; cout << smallestpositive(arr3, arr3.size()) << endl; vector<long long> arr4 = {1, 1, 3, 4}; cout << smallestpositive(arr4, arr4.size()) << endl; return 0; }
constant
nlogn
// C++ program to print length of the largest // contiguous array sum #include<bits/stdc++.h> using namespace std; int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0, start =0, end = 0, s=0; for (int i=0; i< size; i++ ) { max_ending_here += a[i]; if (max_so_far < max_ending_here) { max_so_far = max_ending_here; start = s; end = i; } if (max_ending_here < 0) { max_ending_here = 0; s = i + 1; } } return (end - start + 1); } /*Driver program to test maxSubArraySum*/ int main() { int a[] = {-2, -3, 4, -1, -2, 1, 5, -3}; int n = sizeof(a)/sizeof(a[0]); cout << maxSubArraySum(a, n); return 0; }
constant
linear
// C++ implementation of simple method to find // minimum difference between any pair #include <bits/stdc++.h> using namespace std; // Returns minimum difference between any pair int findMinDiff(int arr[], int n) { // Initialize difference as infinite int diff = INT_MAX; // Find the min diff by comparing difference // of all possible pairs in given array for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (abs(arr[i] - arr[j]) < diff) diff = abs(arr[i] - arr[j]); // Return min diff return diff; } // Driver code int main() { int arr[] = { 1, 5, 3, 19, 18, 25 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << "Minimum difference is " << findMinDiff(arr, n); return 0; }
constant
quadratic
// C++ program to find minimum difference between // any pair in an unsorted array #include <bits/stdc++.h> using namespace std; // Returns minimum difference between any pair int findMinDiff(int arr[], int n) { // Sort array in non-decreasing order sort(arr, arr + n); // Initialize difference as infinite int diff = INT_MAX; // Find the min diff by comparing adjacent // pairs in sorted array for (int i = 0; i < n - 1; i++) if (arr[i + 1] - arr[i] < diff) diff = arr[i + 1] - arr[i]; // Return min diff return diff; } // Driver code int main() { int arr[] = { 1, 5, 3, 19, 18, 25 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << "Minimum difference is " << findMinDiff(arr, n); return 0; }
constant
nlogn
// A Simple C++ program to find longest common // subarray of two binary arrays with same sum #include<bits/stdc++.h> using namespace std; // Returns length of the longest common subarray // with same sum int longestCommonSum(bool arr1[], bool arr2[], int n) { // Initialize result int maxLen = 0; // One by one pick all possible starting points // of subarrays for (int i=0; i<n; i++) { // Initialize sums of current subarrays int sum1 = 0, sum2 = 0; // Consider all points for starting with arr[i] for (int j=i; j<n; j++) { // Update sums sum1 += arr1[j]; sum2 += arr2[j]; // If sums are same and current length is // more than maxLen, update maxLen if (sum1 == sum2) { int len = j-i+1; if (len > maxLen) maxLen = len; } } } return maxLen; } // Driver program to test above function int main() { bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << "Length of the longest common span with same " "sum is "<< longestCommonSum(arr1, arr2, n); return 0; }
constant
quadratic
// A O(n) and O(n) extra space C++ program to find // longest common subarray of two binary arrays with // same sum #include<bits/stdc++.h> using namespace std; // Returns length of the longest common sum in arr1[] // and arr2[]. Both are of same size n. int longestCommonSum(bool arr1[], bool arr2[], int n) { // Initialize result int maxLen = 0; // Initialize prefix sums of two arrays int preSum1 = 0, preSum2 = 0; // Create an array to store starting and ending // indexes of all possible diff values. diff[i] // would store starting and ending points for // difference "i-n" int diff[2*n+1]; // Initialize all starting and ending values as -1. memset(diff, -1, sizeof(diff)); // Traverse both arrays for (int i=0; i<n; i++) { // Update prefix sums preSum1 += arr1[i]; preSum2 += arr2[i]; // Compute current diff and index to be used // in diff array. Note that diff can be negative // and can have minimum value as -1. int curr_diff = preSum1 - preSum2; int diffIndex = n + curr_diff; // If current diff is 0, then there are same number // of 1's so far in both arrays, i.e., (i+1) is // maximum length. if (curr_diff == 0) maxLen = i+1; // If current diff is seen first time, then update // starting index of diff. else if ( diff[diffIndex] == -1) diff[diffIndex] = i; // Current diff is already seen else { // Find length of this same sum common span int len = i - diff[diffIndex]; // Update max len if needed if (len > maxLen) maxLen = len; } } return maxLen; } // Driver code int main() { bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << "Length of the longest common span with same " "sum is "<< longestCommonSum(arr1, arr2, n); return 0; }
linear
linear
// C++ program to find largest subarray // with equal number of 0's and 1's. #include <bits/stdc++.h> using namespace std; // Returns largest common subarray with equal // number of 0s and 1s in both of t int longestCommonSum(bool arr1[], bool arr2[], int n) { // Find difference between the two int arr[n]; for (int i=0; i<n; i++) arr[i] = arr1[i] - arr2[i]; // Creates an empty hashMap hM unordered_map<int, int> hM; int sum = 0; // Initialize sum of elements int max_len = 0; // Initialize result // Traverse through the given array for (int i = 0; i < n; i++) { // Add current element to sum sum += arr[i]; // To handle sum=0 at last index if (sum == 0) max_len = i + 1; // If this sum is seen before, // then update max_len if required if (hM.find(sum) != hM.end()) max_len = max(max_len, i - hM[sum]); else // Else put this sum in hash table hM[sum] = i; } return max_len; } // Driver program to test above function int main() { bool arr1[] = {0, 1, 0, 1, 1, 1, 1}; bool arr2[] = {1, 1, 1, 1, 1, 0, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); cout << longestCommonSum(arr1, arr2, n); return 0; }
linear
linear
// C++ program to print an array in alternate // sorted manner. #include <bits/stdc++.h> using namespace std; // Function to print alternate sorted values void alternateSort(int arr[], int n) { // Sorting the array sort(arr, arr+n); // Printing the last element of array // first and then first element and then // second last element and then second // element and so on. int i = 0, j = n-1; while (i < j) { cout << arr[j--] << " "; cout << arr[i++] << " "; } // If the total element in array is odd // then print the last middle element. if (n % 2 != 0) cout << arr[i]; } // Driver code int main() { int arr[] = {1, 12, 4, 6, 7, 10}; int n = sizeof(arr)/sizeof(arr[0]); alternateSort(arr, n); return 0; }
constant
nlogn
// A STL based C++ program to sort a nearly sorted array. #include <bits/stdc++.h> using namespace std; // Given an array of size n, where every element // is k away from its target position, sorts the // array in O(n logk) time. void sortK(int arr[], int n, int k) { // Insert first k+1 items in a priority queue (or min // heap) //(A O(k) operation). We assume, k < n. //if size of array = k i.e k away from its target position //then int size; size=(n==k)?k:k+1; priority_queue<int, vector<int>, greater<int> > pq(arr, arr +size); // i is index for remaining elements in arr[] and index // is target index of for current minimum element in // Min Heap 'pq'. int index = 0; for (int i = k + 1; i < n; i++) { arr[index++] = pq.top(); pq.pop(); pq.push(arr[i]); } while (pq.empty() == false) { arr[index++] = pq.top(); pq.pop(); } } // A utility function to print array elements void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } // Driver program to test above functions int main() { int k = 3; int arr[] = { 2, 6, 3, 12, 56, 8 }; int n = sizeof(arr) / sizeof(arr[0]); sortK(arr, n, k); cout << "Following is sorted array" << endl; printArray(arr, n); return 0; }
constant
constant
#include <bits/stdc++.h> #include <iostream> using namespace std; int sort(vector<int>& array, int l, int h, int k) { int mid = l + (h - l) / 2; //Choose middle element as pivot int i = max(l, mid - k), j = i, end = min(mid + k, h); // Set appropriate range swap(array[mid], array[end]); //Swap middle and last element to avoid extra complications while (j < end) { if (array[j] < array[end]) { swap(array[i++], array[j]); } j = j + 1; } swap(array[end], array[i]); return i; } void ksorter(vector<int>& array, int l, int h, int k) { if (l < h) { int q = sort(array, l, h, k); ksorter(array, l, q - 1, k); ksorter(array, q + 1, h, k); } } int main() { vector<int> array( { 3, 3, 2, 1, 6, 4, 4, 5, 9, 7, 8, 11, 12 }); int k = 3; cout << "Array before k sort\n"; for (int& num : array) cout << num << ' '; cout << endl; ksorter(array, 0, array.size() - 1, k); cout << "Array after k sort\n"; for (int& num : array) cout << num << ' '; return 0; }
logn
nlogn
// C++ program to sort an array according absolute // difference with x. #include <bits/stdc++.h> using namespace std; // Function to sort an array according absolute // difference with x. void rearrange(int arr[], int n, int x) { multimap<int, int> m; multimap<int, int>::iterator it; // Store values in a map with the difference // with X as key for (int i = 0; i < n; i++) m.insert(make_pair(abs(x - arr[i]), arr[i])); // Update the values of array int i = 0; for (it = m.begin(); it != m.end(); it++) arr[i++] = (*it).second; } // Function to print the array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; } // Driver code int main() { int arr[] = { 10, 5, 3, 9, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; // Function call rearrange(arr, n, x); printArray(arr, n); return 0; }
linear
nlogn
// CPP program for the above approach #include <bits/stdc++.h> using namespace std; void rearrange(int arr[], int n, int x) { /* We can send the value x into lambda expression as follows: [capture]() { //statements //capture value can be used inside } */ stable_sort(arr, arr + n, [x](int a, int b) { if (abs(a - x) < abs(b - x)) return true; else return false; }); } // Driver code int main() { int arr[] = { 10, 5, 3, 9, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 7; // Function call rearrange(arr, n, x); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0; }
constant
nlogn
// A C++ program to sort an array in wave form using // a sorting function #include<iostream> #include<algorithm> using namespace std; // A utility method to swap two numbers. void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // This function sorts arr[0..n-1] in wave form, i.e., // arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5].. void sortInWave(int arr[], int n) { // Sort the input array sort(arr, arr+n); // Swap adjacent elements for (int i=0; i<n-1; i += 2) swap(&arr[i], &arr[i+1]); } // Driver program to test above function int main() { int arr[] = {10, 90, 49, 2, 1, 5, 23}; int n = sizeof(arr)/sizeof(arr[0]); sortInWave(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0; }
constant
nlogn
// A O(n) program to sort an input array in wave form #include<iostream> using namespace std; // A utility method to swap two numbers. void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } // This function sorts arr[0..n-1] in wave form, i.e., arr[0] >= // arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5] .... void sortInWave(int arr[], int n) { // Traverse all even elements for (int i = 0; i < n; i+=2) { // If current even element is smaller than previous if (i>0 && arr[i-1] > arr[i] ) swap(&arr[i], &arr[i-1]); // If current even element is smaller than next if (i<n-1 && arr[i] < arr[i+1] ) swap(&arr[i], &arr[i + 1]); } } // Driver program to test above function int main() { int arr[] = {10, 90, 49, 2, 1, 5, 23}; int n = sizeof(arr)/sizeof(arr[0]); sortInWave(arr, n); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0; }
constant
linear
// C++ program to Merge an array of // size n into another array of size m + n #include <bits/stdc++.h> using namespace std; /* Assuming -1 is filled for the places where element is not available */ #define NA -1 /* Function to move m elements at the end of array mPlusN[] */ void moveToEnd(int mPlusN[], int size) { int j = size - 1; for (int i = size - 1; i >= 0; i--) if (mPlusN[i] != NA) { mPlusN[j] = mPlusN[i]; j--; } } /* Merges array N[] of size n into array mPlusN[] of size m+n*/ int merge(int mPlusN[], int N[], int m, int n) { int i = n; /* Current index of i/p part of mPlusN[]*/ int j = 0; /* Current index of N[]*/ int k = 0; /* Current index of output mPlusN[]*/ while (k < (m + n)) { /* Take an element from mPlusN[] if a) value of the picked element is smaller and we have not reached end of it b) We have reached end of N[] */ if ((j == n)||(i < (m + n) && mPlusN[i] <= N[j])) { mPlusN[k] = mPlusN[i]; k++; i++; } else // Otherwise take element from N[] { mPlusN[k] = N[j]; k++; j++; } } } /* Utility that prints out an array on a line */ void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } /* Driver code */ int main() { /* Initialize arrays */ int mPlusN[] = {2, 8, NA, NA, NA, 13, NA, 15, 20}; int N[] = {5, 7, 9, 25}; int n = sizeof(N) / sizeof(N[0]); int m = sizeof(mPlusN) / sizeof(mPlusN[0]) - n; /*Move the m elements at the end of mPlusN*/ moveToEnd(mPlusN, m + n); /*Merge N[] into mPlusN[] */ merge(mPlusN, N, m, n); /* Print the resultant mPlusN */ printArray(mPlusN, m+n); return 0; }
constant
linear
// CPP program to test whether array // can be sorted by swapping adjacent // elements using boolean array #include <bits/stdc++.h> using namespace std; // Return true if array can be // sorted otherwise false bool sortedAfterSwap(int A[], bool B[], int n) { int i, j; // Check bool array B and sorts // elements for continuous sequence of 1 for (i = 0; i < n - 1; i++) { if (B[i]) { j = i; while (B[j]) j++; // Sort array A from i to j sort(A + i, A + 1 + j); i = j; } } // Check if array is sorted or not for (i = 0; i < n; i++) { if (A[i] != i + 1) return false; } return true; } // Driver program to test sortedAfterSwap() int main() { int A[] = { 1, 2, 5, 3, 4, 6 }; bool B[] = { 0, 1, 1, 1, 0 }; int n = sizeof(A) / sizeof(A[0]); if (sortedAfterSwap(A, B, n)) cout << "A can be sorted\n"; else cout << "A can not be sorted\n"; return 0; }
constant
quadratic
// CPP program to test whether array // can be sorted by swapping adjacent // elements using boolean array #include <bits/stdc++.h> using namespace std; // Return true if array can be // sorted otherwise false bool sortedAfterSwap(int A[], bool B[], int n) { for (int i = 0; i < n - 1; i++) { if (B[i]) { if (A[i] != i + 1) swap(A[i], A[i + 1]); } } // Check if array is sorted or not for (int i = 0; i < n; i++) { if (A[i] != i + 1) return false; } return true; } // Driver program to test sortedAfterSwap() int main() { int A[] = { 1, 2, 5, 3, 4, 6 }; bool B[] = { 0, 1, 1, 1, 0 }; int n = sizeof(A) / sizeof(A[0]); if (sortedAfterSwap(A, B, n)) cout << "A can be sorted\n"; else cout << "A can not be sorted\n"; return 0; }
constant
linear
// CPP program to sort an array with two types // of values in one traversal. #include <bits/stdc++.h> using namespace std; /* Method for segregation 0 and 1 given input array */ void segregate0and1(int arr[], int n) { int type0 = 0; int type1 = n - 1; while (type0 < type1) { if (arr[type0] == 1) { swap(arr[type0], arr[type1]); type1--; } else { type0++; } } } // Driver program int main() { int arr[] = { 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1 }; int n = sizeof(arr)/sizeof(arr[0]); segregate0and1(arr, n); for (int a : arr) cout << a << " "; }
constant
linear
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Used for sorting struct ele { int count, index, val; }; // Used for sorting by value bool mycomp(struct ele a, struct ele b) { return (a.val < b.val); } // Used for sorting by frequency. And if frequency is same, // then by appearance bool mycomp2(struct ele a, struct ele b) { if (a.count != b.count) return (a.count < b.count); else return a.index > b.index; } void sortByFrequency(int arr[], int n) { struct ele element[n]; for (int i = 0; i < n; i++) { // Fill Indexes element[i].index = i; // Initialize counts as 0 element[i].count = 0; // Fill values in structure // elements element[i].val = arr[i]; } /* Sort the structure elements according to value, we used stable sort so relative order is maintained. */ stable_sort(element, element + n, mycomp); /* initialize count of first element as 1 */ element[0].count = 1; /* Count occurrences of remaining elements */ for (int i = 1; i < n; i++) { if (element[i].val == element[i - 1].val) { element[i].count += element[i - 1].count + 1; /* Set count of previous element as -1, we are doing this because we'll again sort on the basis of counts (if counts are equal than on the basis of index)*/ element[i - 1].count = -1; /* Retain the first index (Remember first index is always present in the first duplicate we used stable sort. */ element[i].index = element[i - 1].index; } /* Else If previous element is not equal to current so set the count to 1 */ else element[i].count = 1; } /* Now we have counts and first index for each element so now sort on the basis of count and in case of tie use index to sort.*/ stable_sort(element, element + n, mycomp2); for (int i = n - 1, index = 0; i >= 0; i--) if (element[i].count != -1) for (int j = 0; j < element[i].count; j++) arr[index++] = element[i].val; } // Driver code int main() { int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call sortByFrequency(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0; }
linear
nlogn
// CPP program for above approach #include <bits/stdc++.h> using namespace std; // Compare function bool fcompare(pair<int, pair<int, int> > p, pair<int, pair<int, int> > p1) { if (p.second.second != p1.second.second) return (p.second.second > p1.second.second); else return (p.second.first < p1.second.first); } void sortByFrequency(int arr[], int n) { unordered_map<int, pair<int, int> > hash; // hash map for (int i = 0; i < n; i++) { if (hash.find(arr[i]) != hash.end()) hash[arr[i]].second++; else hash[arr[i]] = make_pair(i, 1); } // store the count of all the elements in the hashmap // Iterator to Traverse the Hashmap auto it = hash.begin(); // Vector to store the Final Sortted order vector<pair<int, pair<int, int> > > b; for (it; it != hash.end(); ++it) b.push_back(make_pair(it->first, it->second)); sort(b.begin(), b.end(), fcompare); // Printing the Sorted sequence for (int i = 0; i < b.size(); i++) { int count = b[i].second.second; while (count--) cout << b[i].first << " "; } } // Driver code int main() { int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call sortByFrequency(arr, n); return 0; }
linear
nlogn
// CPP program to find shortest subarray which is // unsorted. #include <bits/stdc++.h> using namespace std; // bool function for checking an array elements // are in increasing. bool increasing(int a[], int n) { for (int i = 0; i < n - 1; i++) if (a[i] >= a[i + 1]) return false; return true; } // bool function for checking an array // elements are in decreasing. bool decreasing(int a[], int n) { for (int i = 0; i < n - 1; i++) if (a[i] < a[i + 1]) return false; return true; } int shortestUnsorted(int a[], int n) { // increasing and decreasing are two functions. // if function return true value then print // 0 otherwise 3. if (increasing(a, n) == true || decreasing(a, n) == true) return 0; else return 3; } // Driver code int main() { int ar[] = { 7, 9, 10, 8, 11 }; int n = sizeof(ar) / sizeof(ar[0]); cout << shortestUnsorted(ar, n); return 0; }
constant
linear
// C++ program to find // minimum number of swaps // required to sort an array #include<bits/stdc++.h> using namespace std; // Function returns the // minimum number of swaps // required to sort the array int minSwaps(int arr[], int n) { // Create an array of // pairs where first // element is array element // and second element // is position of first element pair<int, int> arrPos[n]; for (int i = 0; i < n; i++) { arrPos[i].first = arr[i]; arrPos[i].second = i; } // Sort the array by array // element values to // get right position of // every element as second // element of pair. sort(arrPos, arrPos + n); // To keep track of visited elements. // Initialize // all elements as not visited or false. vector<bool> vis(n, false); // Initialize result int ans = 0; // Traverse array elements for (int i = 0; i < n; i++) { // already swapped and corrected or // already present at correct pos if (vis[i] || arrPos[i].second == i) continue; // find out the number of node in // this cycle and add in ans int cycle_size = 0; int j = i; while (!vis[j]) { vis[j] = 1; // move to next node j = arrPos[j].second; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } // Return result return ans; } // Driver program to test the above function int main() { int arr[] = {1, 5, 4, 3, 2}; int n = (sizeof(arr) / sizeof(int)); cout << minSwaps(arr, n); return 0; }
linear
nlogn
#include <bits/stdc++.h> using namespace std; // Function returns the // minimum number of swaps // required to sort the array int minSwaps(int nums[], int n) { int len = n; map<int, int> map; for (int i = 0; i < len; i++) map[nums[i]] = i; sort(nums, nums + n); // To keep track of visited elements. Initialize // all elements as not visited or false. bool visited[len] = { 0 }; // Initialize result int ans = 0; for (int i = 0; i < len; i++) { // already swapped and corrected or // already present at correct pos if (visited[i] || map[nums[i]] == i) continue; int j = i, cycle_size = 0; while (!visited[j]) { visited[j] = true; // move to next node j = map[nums[j]]; cycle_size++; } // Update answer by adding current cycle. if (cycle_size > 0) { ans += (cycle_size - 1); } } return ans; } int main() { // Driver program to test the above function int a[] = { 1, 5, 4, 3, 2 }; int n = 5; cout << minSwaps(a, n); return 0; } // This code is contributed by Harshal Khond
linear
nlogn
// C++ program to find minimum number // of swaps required to sort an array #include <bits/stdc++.h> using namespace std; void swap(vector<int> &arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } int indexOf(vector<int> &arr, int ele) { for(int i = 0; i < arr.size(); i++) { if (arr[i] == ele) { return i; } } return -1; } // Return the minimum number // of swaps required to sort the array int minSwaps(vector<int> arr, int N) { int ans = 0; vector<int> temp(arr.begin(),arr.end()); sort(temp.begin(),temp.end()); for(int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; // Swap the current element // with the right index // so that arr[0] to arr[i] is sorted swap(arr, i, indexOf(arr, temp[i])); } } return ans; } // Driver Code int main() { vector<int> a = {101, 758, 315, 730, 472, 619, 460, 479}; int n = a.size(); // Output will be 5 cout << minSwaps(a, n); } // This code is contributed by mohit kumar 29
linear
quadratic
// C++ program to find // minimum number of swaps // required to sort an array #include<bits/stdc++.h> using namespace std; void swap(vector<int> &arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Return the minimum number // of swaps required to sort // the array int minSwaps(vector<int>arr, int N) { int ans = 0; vector<int>temp = arr; // Hashmap which stores the // indexes of the input array map <int, int> h; sort(temp.begin(), temp.end()); for (int i = 0; i < N; i++) { h[arr[i]] = i; } for (int i = 0; i < N; i++) { // This is checking whether // the current element is // at the right place or not if (arr[i] != temp[i]) { ans++; int init = arr[i]; // If not, swap this element // with the index of the // element which should come here swap(arr, i, h[temp[i]]); // Update the indexes in // the hashmap accordingly h[init] = h[temp[i]]; h[temp[i]] = i; } } return ans; } // Driver class int main() { // Driver program to // test the above function vector <int> a = {101, 758, 315, 730, 472, 619, 460, 479}; int n = a.size(); // Output will be 5 cout << minSwaps(a, n); } // This code is contributed by Stream_Cipher
linear
nlogn
// C++ program to sort an array // with 0, 1 and 2 in a single pass #include <bits/stdc++.h> using namespace std; // Function to sort the input array, // the array is assumed // to have values in {0, 1, 2} void sort012(int a[], int arr_size) { int lo = 0; int hi = arr_size - 1; int mid = 0; // Iterate till all the elements // are sorted while (mid <= hi) { switch (a[mid]) { // If the element is 0 case 0: swap(a[lo++], a[mid++]); break; // If the element is 1 . case 1: mid++; break; // If the element is 2 case 2: swap(a[mid], a[hi--]); break; } } } // Function to print array arr[] void printArray(int arr[], int arr_size) { // Iterate and print every element for (int i = 0; i < arr_size; i++) cout << arr[i] << " "; } // Driver Code int main() { int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = sizeof(arr) / sizeof(arr[0]); sort012(arr, n); printArray(arr, n); return 0; } // This code is contributed by Shivi_Aggarwal
constant
linear
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Utility function to print the contents of an array void printArr(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; } // Function to sort the array of 0s, 1s and 2s void sortArr(int arr[], int n) { int i, cnt0 = 0, cnt1 = 0, cnt2 = 0; // Count the number of 0s, 1s and 2s in the array for (i = 0; i < n; i++) { switch (arr[i]) { case 0: cnt0++; break; case 1: cnt1++; break; case 2: cnt2++; break; } } // Update the array i = 0; // Store all the 0s in the beginning while (cnt0 > 0) { arr[i++] = 0; cnt0--; } // Then all the 1s while (cnt1 > 0) { arr[i++] = 1; cnt1--; } // Finally all the 2s while (cnt2 > 0) { arr[i++] = 2; cnt2--; } // Print the sorted array printArr(arr, n); } // Driver code int main() { int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; int n = sizeof(arr) / sizeof(int); sortArr(arr, n); return 0; }
constant
linear
// This code is contributed by Anjali Saxena #include <bits/stdc++.h> using namespace std; // Function to find position to insert current element of // stream using binary search int binarySearch(int arr[], int item, int low, int high) { if (low >= high) { return (item > arr[low]) ? (low + 1) : low; } int mid = (low + high) / 2; if (item == arr[mid]) return mid + 1; if (item > arr[mid]) return binarySearch(arr, item, mid + 1, high); return binarySearch(arr, item, low, mid - 1); } // Function to print median of stream of integers void printMedian(int arr[], int n) { int i, j, pos, num; int count = 1; cout << "Median after reading 1" << " element is " << arr[0] << "\n"; for (i = 1; i < n; i++) { float median; j = i - 1; num = arr[i]; // find position to insert current element in sorted // part of array pos = binarySearch(arr, num, 0, j); // move elements to right to create space to insert // the current element while (j >= pos) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = num; // increment count of sorted elements in array count++; // if odd number of integers are read from stream // then middle element in sorted order is median // else average of middle elements is median if (count % 2 != 0) { median = arr[count / 2]; } else { median = (arr[(count / 2) - 1] + arr[count / 2]) / 2; } cout << "Median after reading " << i + 1 << " elements is " << median << "\n"; } } // Driver Code int main() { int arr[] = { 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 }; int n = sizeof(arr) / sizeof(arr[0]); printMedian(arr, n); return 0; }
constant
quadratic
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std; // Function to find the median of stream of data void streamMed(int A[], int n) { // Declared two max heap priority_queue<int> g, s; for (int i = 0; i < n; i++) { s.push(A[i]); int temp = s.top(); s.pop(); // Negation for treating it as min heap g.push(-1 * temp); if (g.size() > s.size()) { temp = g.top(); g.pop(); s.push(-1 * temp); } if (g.size() != s.size()) cout << (double)s.top() << "\n"; else cout << (double)((s.top() * 1.0 - g.top() * 1.0) / 2) << "\n"; } } // Driver code int main() { int A[] = { 5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4 }; int N = sizeof(A) / sizeof(A[0]); // Function call streamMed(A, N); return 0; }
linear
nlogn
// C++ code to count the number of possible triangles using // brute force approach #include <bits/stdc++.h> using namespace std; // Function to count all possible triangles with arr[] // elements int findNumberOfTriangles(int arr[], int n) { // Count of triangles int count = 0; // The three loops select three different values from // array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // The innermost loop checks for the triangle // property for (int k = j + 1; k < n; k++) // Sum of two sides is greater than the // third if (arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count; } // Driver code int main() { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); // Function call cout << "Total number of triangles possible is " << findNumberOfTriangles(arr, size); return 0; } // This code is contributed by Sania Kumari Gupta
constant
cubic
// C++ program to count number of triangles that can be // formed from given array #include <bits/stdc++.h> using namespace std; // Function to count all possible triangles with arr[] // elements int findNumberOfTriangles(int arr[], int n) { // Sort the array elements in non-decreasing order sort(arr, arr + n); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 // as the other two elements are selected from // arr[i+1...n-1] for (int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for (int j = i + 1; j < n; ++j) { // Find the rightmost element which is smaller // than the sum of two fixed elements The // important thing to note here is, we use the // previous value of k. If value of arr[i] + // arr[j-1] was greater than arr[k], then arr[i] // + arr[j] must be greater than k, because the // array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and // arr[j]. One is subtracted from k because k is // incremented one extra in above while loop. k // will always be greater than j. If j becomes // equal to k, then above loop will increment k, // because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count; } // Driver code int main() { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof(arr) / sizeof(arr[0]); // Function call cout << "Total number of triangles possible is " << findNumberOfTriangles(arr, size); return 0; } // This code is contributed by Sania Kumari Gupta
constant
quadratic
// C++ implementation of the above approach #include <bits/stdc++.h> using namespace std; void CountTriangles(vector<int> A) { int n = A.size(); sort(A.begin(), A.end()); int count = 0; for (int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] l++; } } cout << "No of possible solutions: " << count; } // Driver code int main() { vector<int> A = { 10, 21, 22, 100, 101, 200, 300 }; // Function call CountTriangles(A); }
constant
quadratic
// C++ program to finds the number of pairs (x, y) // in an array such that x^y > y^x #include <bits/stdc++.h> using namespace std; // Function to return count of pairs with x as one element // of the pair. It mainly looks for all values in Y[] where // x ^ Y[i] > Y[i] ^ x int count(int x, int Y[], int n, int NoOfY[]) { // If x is 0, then there cannot be any value in Y such // that x^Y[i] > Y[i]^x if (x == 0) return 0; // If x is 1, then the number of pairs is equal to number // of zeroes in Y[] if (x == 1) return NoOfY[0]; // Find number of elements in Y[] with values greater // than x upper_bound() gets address of first greater // element in Y[0..n-1] int* idx = upper_bound(Y, Y + n, x); int ans = (Y + n) - idx; // If we have reached here, then x must be greater than // 1, increase number of pairs for y=0 and y=1 ans += (NoOfY[0] + NoOfY[1]); // Decrease number of pairs for x=2 and (y=4 or y=3) if (x == 2) ans -= (NoOfY[3] + NoOfY[4]); // Increase number of pairs for x=3 and y=2 if (x == 3) ans += NoOfY[2]; return ans; } // Function to return count of pairs (x, y) such that // x belongs to X[], y belongs to Y[] and x^y > y^x int countPairs(int X[], int Y[], int m, int n) { // To store counts of 0, 1, 2, 3 and 4 in array Y int NoOfY[5] = { 0 }; for (int i = 0; i < n; i++) if (Y[i] < 5) NoOfY[Y[i]]++; // Sort Y[] so that we can do binary search in it sort(Y, Y + n); int total_pairs = 0; // Initialize result // Take every element of X and count pairs with it for (int i = 0; i < m; i++) total_pairs += count(X[i], Y, n, NoOfY); return total_pairs; } // Driver program int main() { int X[] = { 2, 1, 6 }; int Y[] = { 1, 5 }; int m = sizeof(X) / sizeof(X[0]); int n = sizeof(Y) / sizeof(Y[0]); cout << "Total pairs = " << countPairs(X, Y, m, n); return 0; }
constant
nlogn
/* A simple program to count pairs with difference k*/ #include <iostream> using namespace std; int countPairsWithDiffK(int arr[], int n, int k) { int count = 0; // Pick all elements one by one for (int i = 0; i < n; i++) { // See if there is a pair of this picked element for (int j = i + 1; j < n; j++) if (arr[i] - arr[j] == k || arr[j] - arr[i] == k) count++; } return count; } // Driver program to test above function int main() { int arr[] = { 1, 5, 3, 4, 2 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << "Count of pairs with given diff is " << countPairsWithDiffK(arr, n, k); return 0; } // This code is contributed by Sania Kumari Gupta
constant
quadratic
/* A sorting based program to count pairs with difference k*/ #include <iostream> #include <algorithm> using namespace std; /* Returns count of pairs with difference k in arr[] of size n. */ int countPairsWithDiffK(int arr[], int n, int k) { int count = 0; sort(arr, arr+n); // Sort array elements int l = 0; int r = 0; while(r < n) { if(arr[r] - arr[l] == k) { count++; l++; r++; } else if(arr[r] - arr[l] > k) l++; else // arr[r] - arr[l] < sum r++; } return count; } // Driver program to test above function int main() { int arr[] = {1, 5, 3, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); int k = 3; cout << "Count of pairs with given diff is " << countPairsWithDiffK(arr, n, k); return 0; }
constant
nlogn
#include <bits/stdc++.h> using namespace std; int BS(int arr[], int X, int low, int N) { int high = N - 1; int ans = N; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] >= X) { ans = mid; high = mid - 1; } else low = mid + 1; } return ans; } int countPairsWithDiffK(int arr[], int N, int k) { int count = 0; sort(arr, arr + N); for (int i = 0; i < N; ++i) { int X = BS(arr, arr[i] + k, i + 1, N); if (X != N) { int Y = BS(arr, arr[i] + k + 1, i + 1, N); count += Y - X; } } return count; } int main() { int arr[] = { 1, 3, 5, 8, 6, 4, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << "Count of pairs with given diff is " << countPairsWithDiffK(arr, n, k); return 0; } // This code is contributed by umadevi9616
constant
nlogn
// C++ program to print all distinct elements in a given array #include <bits/stdc++.h> using namespace std; void printDistinct(int arr[], int n) { // Pick all elements one by one for (int i=0; i<n; i++) { // Check if the picked element is already printed int j; for (j=0; j<i; j++) if (arr[i] == arr[j]) break; // If not printed earlier, then print it if (i == j) cout << arr[i] << " "; } } // Driver program to test above function int main() { int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}; int n = sizeof(arr)/sizeof(arr[0]); printDistinct(arr, n); return 0; }
constant
quadratic
// C++ program to print all distinct elements in a given array #include <bits/stdc++.h> using namespace std; void printDistinct(int arr[], int n) { // First sort the array so that all occurrences become consecutive sort(arr, arr + n); // Traverse the sorted array for (int i=0; i<n; i++) { // Move the index ahead while there are duplicates while (i < n-1 && arr[i] == arr[i+1]) i++; // print last occurrence of the current element cout << arr[i] << " "; } } // Driver program to test above function int main() { int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10}; int n = sizeof(arr)/sizeof(arr[0]); printDistinct(arr, n); return 0; }
constant
nlogn
/* CPP program to print all distinct elements of a given array */ #include<bits/stdc++.h> using namespace std; // This function prints all distinct elements void printDistinct(int arr[],int n) { // Creates an empty hashset unordered_set<int> s; // Traverse the input array for (int i=0; i<n; i++) { // if element is not present then s.count(element) return 0 else return 1 // hashtable and print it if (!s.count(arr[i])) // <--- avg O(1) time { s.insert(arr[i]); cout << arr[i] << " "; } } } // Driver method to test above method int main () { int arr[] = {10, 5, 3, 4, 3, 5, 6}; int n=7; printDistinct(arr,n); return 0; }
linear
linear
// C++ approach #include <bits/stdc++.h> using namespace std; int main() { int ar[] = { 10, 5, 3, 4, 3, 5, 6 }; map<int ,int> hm; for (int i = 0; i < sizeof(ar)/sizeof(ar[0]); i++) { // total = O(n*logn) hm.insert({ar[i], i}); // time complexity for insert() in map O(logn) } cout <<"["; for (auto const &pair: hm) { cout << pair.first << ", "; } cout <<"]"; } // This code is contributed by Shubham Singh
linear
nlogn
// C++ program to merge two sorted arrays with O(1) extra // space. #include <bits/stdc++.h> using namespace std; // Merge ar1[] and ar2[] with O(1) extra space void merge(int ar1[], int ar2[], int m, int n) { // Iterate through all elements // of ar2[] starting from the last element for (int i = n - 1; i >= 0; i--) { // Find the smallest element greater than ar2[i]. // Move all elements one position ahead till the // smallest greater element is not found */ int j, last = ar1[m - 1]; for (j = m - 2; j >= 0 && ar1[j] > ar2[i]; j--) ar1[j + 1] = ar1[j]; // If there was a greater element if (last > ar2[i]) { ar1[j + 1] = ar2[i]; ar2[i] = last; } } } // Driver program 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