code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
// CPP program to make a permutation of numbers // from 1 to n using minimum changes. #include <bits/stdc++.h> using namespace std; void makePermutation(int a[], int n) { // Store counts of all elements. unordered_map<int, int> count; for (int i = 0; i < n; i++) count[a[i]]++; int next_missing = 1; for (int i = 0; i < n; i++) { if (count[a[i]] != 1 || a[i] > n || a[i] < 1) { count[a[i]]--; // Find next missing element to put // in place of current element. while (count.find(next_missing) != count.end()) next_missing++; // Replace with next missing and insert the // missing element in hash. a[i] = next_missing; count[next_missing] = 1; } } } // Driver Code int main() { int A[] = { 2, 2, 3, 3 }; int n = sizeof(A) / sizeof(A[0]); makePermutation(A, n); for (int i = 0; i < n; i++) cout << A[i] << " "; return 0; }
linear
nlogn
// C++ implementation of simple method to find count of // pairs with given sum. #include <bits/stdc++.h> using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount(int arr[], int n, int sum) { int count = 0; // Initialize result // Consider all possible pairs and check their sums for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] + arr[j] == sum) count++; return count; } // Driver function to test the above function int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << "Count of pairs is " << getPairsCount(arr, n, sum); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
quadratic
// C++ code to implement the approach #include <bits/stdc++.h> using namespace std; // Function to find the count of pairs int getPairsCount(int arr[], int n, int k) { sort(arr, arr + n); int x = 0, c = 0, y, z; for (int i = 0; i < n - 1; i++) { x = k - arr[i]; // Lower bound from i+1 int y = lower_bound(arr + i + 1, arr + n, x) - arr; // Upper bound from i+1 int z = upper_bound(arr + i + 1, arr + n, x) - arr; c = c + z - y; } return c; } // Driver code int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 6; // Function call cout << "Count of pairs is " << getPairsCount(arr, n, k); return 0; }
constant
nlogn
// C++ implementation of simple method to find count of // pairs with given sum. #include <bits/stdc++.h> using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount(int arr[], int n, int sum) { unordered_map<int, int> m; // Store counts of all elements in map m for (int i = 0; i < n; i++) m[arr[i]]++; int twice_count = 0; // iterate through each element and increment the // count (Notice that every pair is counted twice) for (int i = 0; i < n; i++) { twice_count += m[sum - arr[i]]; // if (arr[i], arr[i]) pair satisfies the condition, // then we need to ensure that the count is // decreased by one such that the (arr[i], arr[i]) // pair is not considered if (sum - arr[i] == arr[i]) twice_count--; } // return the half of twice_count return twice_count / 2; } // Driver function to test the above function int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; cout << "Count of pairs is " << getPairsCount(arr, n, sum); return 0; }
linear
linear
// C++ implementation of simple method to // find count of pairs with given sum. #include <bits/stdc++.h> using namespace std; // Returns number of pairs in arr[0..n-1] with sum equal // to 'sum' int getPairsCount(int arr[], int n, int k) { unordered_map<int, int> m; int count = 0; for (int i = 0; i < n; i++) { if (m.find(k - arr[i]) != m.end()) { count += m[k - arr[i]]; } m[arr[i]]++; } return count; } // Driver code int main() { int arr[] = { 1, 5, 7, -1, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 6; // Function Call cout << "Count of pairs is " << getPairsCount(arr, n, sum); return 0; }
linear
linear
// C++ implementation to count pairs from both linked // lists whose sum is equal to a given value #include <bits/stdc++.h> using namespace std; /* A Linked list node */ struct Node { int data; struct Node* next; }; // function to insert a node at the // beginning of the linked list void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // function to count all pairs from both the linked lists // whose sum is equal to a given value int countPairs(struct Node* head1, struct Node* head2, int x) { int count = 0; struct Node *p1, *p2; // traverse the 1st linked list for (p1 = head1; p1 != NULL; p1 = p1->next) // for each node of 1st list // traverse the 2nd list for (p2 = head2; p2 != NULL; p2 = p2->next) // if sum of pair is equal to 'x' // increment count if ((p1->data + p2->data) == x) count++; // required count of pairs return count; } // Driver program to test above int main() { struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 3->1->5->7 push(&head1, 7); push(&head1, 5); push(&head1, 1); push(&head1, 3); // create linked list2 8->2->5->3 push(&head2, 3); push(&head2, 5); push(&head2, 2); push(&head2, 8); int x = 10; cout << "Count = " << countPairs(head1, head2, x); return 0; }
constant
quadratic
// C++ implementation to count pairs from both linked // lists whose sum is equal to a given value #include <bits/stdc++.h> using namespace std; /* A Linked list node */ struct Node { int data; struct Node* next; }; // function to insert a node at the // beginning of the linked list void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // function to count all pairs from both the linked // lists whose sum is equal to a given value int countPairs(struct Node* head1, struct Node* head2, int x) { int count = 0; // sort head1 in ascending order and // head2 in descending order // sort (head1), sort (head2) // For simplicity both lists are considered to be // sorted in the respective orders // traverse both the lists from left to right while (head1 != NULL && head2 != NULL) { // if this sum is equal to 'x', then move both // the lists to next nodes and increment 'count' if ((head1->data + head2->data) == x) { head1 = head1->next; head2 = head2->next; count++; } // if this sum is greater than x, then // move head2 to next node else if ((head1->data + head2->data) > x) head2 = head2->next; // else move head1 to next node else head1 = head1->next; } // required count of pairs return count; } // Driver program to test above int main() { struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 1->3->5->7 // assumed to be in ascending order push(&head1, 7); push(&head1, 5); push(&head1, 3); push(&head1, 1); // create linked list2 8->5->3->2 // assumed to be in descending order push(&head2, 2); push(&head2, 3); push(&head2, 5); push(&head2, 8); int x = 10; cout << "Count = " << countPairs(head1, head2, x); return 0; }
constant
nlogn
// C++ implementation to count pairs from both linked // lists whose sum is equal to a given value #include <bits/stdc++.h> using namespace std; /* A Linked list node */ struct Node { int data; struct Node* next; }; // function to insert a node at the // beginning of the linked list void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list to the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // function to count all pairs from both the linked // lists whose sum is equal to a given value int countPairs(struct Node* head1, struct Node* head2, int x) { int count = 0; unordered_set<int> us; // insert all the elements of 1st list // in the hash table(unordered_set 'us') while (head1 != NULL) { us.insert(head1->data); // move to next node head1 = head1->next; } // for each element of 2nd list while (head2 != NULL) { // find (x - head2->data) in 'us' if (us.find(x - head2->data) != us.end()) count++; // move to next node head2 = head2->next; } // required count of pairs return count; } // Driver program to test above int main() { struct Node* head1 = NULL; struct Node* head2 = NULL; // create linked list1 3->1->5->7 push(&head1, 7); push(&head1, 5); push(&head1, 1); push(&head1, 3); // create linked list2 8->2->5->3 push(&head2, 3); push(&head2, 5); push(&head2, 2); push(&head2, 8); int x = 10; cout << "Count = " << countPairs(head1, head2, x); return 0; }
linear
linear
// C++ implementation to count quadruples from four sorted arrays // whose sum is equal to a given value x #include <bits/stdc++.h> using namespace std; // function to count all quadruples from // four sorted arrays whose sum is equal // to a given value x int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // generate all possible quadruples from // the four sorted arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) // check whether elements of // quadruple sum up to x or not if ((arr1[i] + arr2[j] + arr3[k] + arr4[l]) == x) count++; // required count of quadruples return count; } // Driver program to test above int main() { // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << "Count = " << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0; }
constant
np
// C++ implementation to count quadruples from // four sorted arrays whose sum is equal to a // given value x #include <bits/stdc++.h> using namespace std; // find the 'value' in the given array 'arr[]' // binary search technique is applied bool isPresent(int arr[], int low, int high, int value) { while (low <= high) { int mid = (low + high) / 2; // 'value' found if (arr[mid] == value) return true; else if (arr[mid] > value) high = mid - 1; else low = mid + 1; } // 'value' not found return false; } // function to count all quadruples from four // sorted arrays whose sum is equal to a given value x int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // generate all triplets from the 1st three arrays for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) for (int k = 0; k < n; k++) { // calculate the sum of elements in // the triplet so generated int T = arr1[i] + arr2[j] + arr3[k]; // check if 'x-T' is present in 4th // array or not if (isPresent(arr4, 0, n, x - T)) // increment count count++; } // required count of quadruples return count; } // Driver program to test above int main() { // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << "Count = " << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0; }
constant
cubic
// C++ implementation to count quadruples from // four sorted arrays whose sum is equal to a // given value x #include <bits/stdc++.h> using namespace std; // count pairs from the two sorted array whose sum // is equal to the given 'value' int countPairs(int arr1[], int arr2[], int n, int value) { int count = 0; int l = 0, r = n - 1; // traverse 'arr1[]' from left to right // traverse 'arr2[]' from right to left while (l < n & amp; &r >= 0) { int sum = arr1[l] + arr2[r]; // if the 'sum' is equal to 'value', then // increment 'l', decrement 'r' and // increment 'count' if (sum == value) { l++, r--; count++; } // if the 'sum' is greater than 'value', then // decrement r else if (sum > value) r--; // else increment l else l++; } // required count of pairs return count; } // function to count all quadruples from four sorted arrays // whose sum is equal to a given value x int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // generate all pairs from arr1[] and arr2[] for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { // calculate the sum of elements in // the pair so generated int p_sum = arr1[i] + arr2[j]; // count pairs in the 3rd and 4th array // having value 'x-p_sum' and then // accumulate it to 'count' count += countPairs(arr3, arr4, n, x - p_sum); } // required count of quadruples return count; } // Driver program to test above int main() { // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << "Count = " << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0; }
constant
cubic
// C++ implementation to count quadruples from // four sorted arrays whose sum is equal to a // given value x #include <bits/stdc++.h> using namespace std; // function to count all quadruples from four sorted // arrays whose sum is equal to a given value x int countQuadruples(int arr1[], int arr2[], int arr3[], int arr4[], int n, int x) { int count = 0; // unordered_map 'um' implemented as hash table // for <sum, frequency> tuples unordered_map<int, int> um; // count frequency of each sum obtained from the // pairs of arr1[] and arr2[] and store them in 'um' for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) um[arr1[i] + arr2[j]]++; // generate pair from arr3[] and arr4[] for (int k = 0; k < n; k++) for (int l = 0; l < n; l++) { // calculate the sum of elements in // the pair so generated int p_sum = arr3[k] + arr4[l]; // if 'x-p_sum' is present in 'um' then // add frequency of 'x-p_sum' to 'count' if (um.find(x - p_sum) != um.end()) count += um[x - p_sum]; } // required count of quadruples return count; } // Driver program to test above int main() { // four sorted arrays each of size 'n' int arr1[] = { 1, 4, 5, 6 }; int arr2[] = { 2, 3, 7, 8 }; int arr3[] = { 1, 4, 6, 10 }; int arr4[] = { 2, 4, 7, 8 }; int n = sizeof(arr1) / sizeof(arr1[0]); int x = 30; cout << "Count = " << countQuadruples(arr1, arr2, arr3, arr4, n, x); return 0; }
quadratic
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; int main() { int arr[] = {10, 2, -2, -20, 10}; int k = -10; int n = sizeof(arr) / sizeof(arr[0]); int res = 0; // Calculate all subarrays for (int i = 0; i < n; i++) { int sum = 0; for (int j = i; j < n; j++) { // Calculate required sum sum += arr[j]; // Check if sum is equal to required sum if (sum == k) res++; } } cout << (res) << endl; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
quadratic
// C++ program to find number of subarrays with sum exactly // equal to k. #include <bits/stdc++.h> using namespace std; // Function to find number of subarrays with sum exactly // equal to k. int findSubarraySum(int arr[], int n, int sum) { // STL map to store number of subarrays starting from // index zero having particular value of sum. unordered_map<int, int> prevSum; int res = 0; // Sum of elements so far. int currSum = 0; for (int i = 0; i < n; i++) { // Add current element to sum so far. currSum += arr[i]; // If currsum is equal to desired sum, then a new // subarray is found. So increase count of // subarrays. if (currSum == sum) res++; // currsum exceeds given sum by currsum - sum. Find // number of subarrays having this sum and exclude // those subarrays from currsum by increasing count // by same amount. if (prevSum.find(currSum - sum) != prevSum.end()) res += (prevSum[currSum - sum]); // Add currsum value to count of different values of // sum. prevSum[currSum]++; } return res; } int main() { int arr[] = { 10, 2, -2, -20, 10 }; int sum = -10; int n = sizeof(arr) / sizeof(arr[0]); cout << findSubarraySum(arr, n, sum); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
linear
linear
// C++ program to find all pairs in both arrays // whose sum is equal to given value x #include <bits/stdc++.h> using namespace std; // Function to print all pairs in both arrays // whose sum is equal to given value x void findPairs(int arr1[], int arr2[], int n, int m, int x) { for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) if (arr1[i] + arr2[j] == x) cout << arr1[i] << " " << arr2[j] << endl; } // Driver code int main() { int arr1[] = { 1, 2, 3, 7, 5, 4 }; int arr2[] = { 0, 7, 4, 3, 2, 1 }; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); int x = 8; findPairs(arr1, arr2, n, m, x); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
quadratic
// C++ program to find all pair in both arrays // whose sum is equal to given value x #include <bits/stdc++.h> using namespace std; // Function to find all pairs in both arrays // whose sum is equal to given value x void findPairs(int arr1[], int arr2[], int n, int m, int x) { // Insert all elements of first array in a hash unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(arr1[i]); // Subtract sum from second array elements one // by one and check it's present in array first // or not for (int j = 0; j < m; j++) if (s.find(x - arr2[j]) != s.end()) cout << x - arr2[j] << " " << arr2[j] << endl; } // Driver code int main() { int arr1[] = { 1, 0, -4, 7, 6, 4 }; int arr2[] = { 0, 2, 4, -3, 2, 1 }; int x = 8; int n = sizeof(arr1) / sizeof(int); int m = sizeof(arr2) / sizeof(int); findPairs(arr1, arr2, n, m, x); return 0; }
linear
linear
#include <bits/stdc++.h> using namespace std; // Function to print the cumulative frequency according to // the order given void countFreq(int a[], int n) { // Declaring a map so values get inserted in a sorted // manner map<int, int> m; // Inserting values into the map for (int i = 0; i < n; i++) { m[a[i]]++; } // Variable to store the count of previous number // cumulative frequency int cumul = 0; for (auto v : m) { cout << v.first << " " << v.second + cumul << endl; cumul += v.second; } } int main() { int arr[] = { 1, 3, 2, 4, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0; } // This code is contributed by Vinayak Pareek (Kargil)
linear
nlogn
// C++ program to print the cumulative frequency // according to the order given #include <bits/stdc++.h> using namespace std; // Function to print the cumulative frequency // according to the order given void countFreq(int a[], int n) { // Insert elements and their // frequencies in hash map. unordered_map<int, int> hm; for (int i=0; i<n; i++) hm[a[i]]++; int cumul = 0; // traverse in the array for(int i=0;i<n;i++) { // add the frequencies cumul += hm[a[i]]; // if the element has not been // visited previously if(hm[a[i]]) { cout << a[i] << "->" << cumul << endl; } // mark the hash 0 // as the element's cumulative frequency // has been printed hm[a[i]]=0; } } // Driver Code int main() { int a[] = {1, 3, 2, 4, 2, 1}; int n = sizeof(a)/sizeof(a[0]); countFreq(a, n); return 0; }
linear
linear
// CPP program for the above approach #include <bits/stdc++.h> using namespace std; // Used for sorting by frequency. And if frequency is same, // then by appearance bool sortByVal(const pair<int, int>& a, const pair<int, int>& b) { // If frequency is same then sort by index if (a.second == b.second) return a.first < b.first; return a.second > b.second; } // function to sort elements by frequency vector<int>sortByFreq(int a[], int n) { vector<int>res; unordered_map<int, int> m; vector<pair<int, int> > v; for (int i = 0; i < n; ++i) { // Map m is used to keep track of count // of elements in array m[a[i]]++; } // Copy map to vector copy(m.begin(), m.end(), back_inserter(v)); // Sort the element of array by frequency sort(v.begin(), v.end(), sortByVal); for (int i = 0; i < v.size(); ++i) while(v[i].second--) { res.push_back(v[i].first); } return res; } // Driver program int main() { int a[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 }; int n = sizeof(a) / sizeof(a[0]); vector<int>res; res = sortByFreq(a, n); for(int i = 0;i < res.size(); i++) cout<<res[i]<<" "; return 0; }
linear
linear
// A simple C++ program to find pair whose sum // already exists in array #include <bits/stdc++.h> using namespace std; // Function to find pair whose sum exists in arr[] void findPair(int arr[], int n) { bool found = false; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { for (int k = 0; k < n; k++) { if (arr[i] + arr[j] == arr[k]) { cout << arr[i] << " " << arr[j] << endl; found = true; } } } } if (found == false) cout << "Not exist" << endl; } // Driven code int main() { int arr[] = { 10, 4, 8, 13, 5 }; int n = sizeof(arr) / sizeof(arr[0]); findPair(arr, n); return 0; }
constant
cubic
// C++ program to find pair whose sum already // exists in array #include <bits/stdc++.h> using namespace std; // Function to find pair whose sum exists in arr[] void findPair(int arr[], int n) { // Hash to store all element of array unordered_set<int> s; for (int i = 0; i < n; i++) s.insert(arr[i]); bool found = false; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Check sum already exists or not if (s.find(arr[i] + arr[j]) != s.end()) { cout << arr[i] << " " << arr[j] << endl; found = true; } } } if (found == false) cout << "Not exist" << endl; } // Driven code int main() { int arr[] = { 10, 4, 8, 13, 5 }; int n = sizeof(arr) / sizeof(arr[0]); findPair(arr, n); return 0; }
quadratic
quadratic
// C++ implementation to find such pairs #include <bits/stdc++.h> using namespace std; // Function to find pair such that (a % b = k) bool printPairs(int arr[], int n, int k) { bool isPairFound = true; // Consider each and every pair for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { cout << "(" << arr[i] << ", " << arr[j] << ")" << " "; isPairFound = true; } } } return isPairFound; } // Driver program int main() { int arr[] = { 2, 3, 5, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; if (printPairs(arr, n, k) == false) cout << "No such pair exists"; return 0; }
constant
quadratic
// C++ program to find all pairs such that // a % b = k. #include <bits/stdc++.h> using namespace std; // Utility function to find the divisors of // n and store in vector v[] vector<int> findDivisors(int n) { vector<int> v; // Vector is used to store the divisors for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // If n is a square number, push // only one occurrence if (n / i == i) v.push_back(i); else { v.push_back(i); v.push_back(n / i); } } } return v; } // Function to find pairs such that (a%b = k) bool printPairs(int arr[], int n, int k) { // Store all the elements in the map // to use map as hash for finding elements // in O(1) time. unordered_map<int, bool> occ; for (int i = 0; i < n; i++) occ[arr[i]] = true; bool isPairFound = false; for (int i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ[k] && k < arr[i]) { cout << "(" << k << ", " << arr[i] << ") "; isPairFound = true; } // Now check for the current element as 'a' // how many b exists such that a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) vector<int> v = findDivisors(arr[i] - k); // Check for each divisor i.e. arr[i] % b = k // or not, if yes then print that pair. for (int j = 0; j < v.size(); j++) { if (arr[i] % v[j] == k && arr[i] != v[j] && occ[v[j]]) { cout << "(" << arr[i] << ", " << v[j] << ") "; isPairFound = true; } } // Clear vector v.clear(); } } return isPairFound; } // Driver program int main() { int arr[] = { 3, 1, 2, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; if (printPairs(arr, n, k) == false) cout << "No such pair exists"; return 0; }
linear
linear
// C++ program to convert an array in reduced // form #include <bits/stdc++.h> using namespace std; void convert(int arr[], int n) { // Create a temp array and copy contents // of arr[] to temp int temp[n]; memcpy(temp, arr, n*sizeof(int)); // Sort temp array sort(temp, temp + n); // Create a hash table. Refer // http://tinyurl.com/zp5wgef unordered_map<int, int> umap; // One by one insert elements of sorted // temp[] and assign them values from 0 // to n-1 int val = 0; for (int i = 0; i < n; i++) umap[temp[i]] = val++; // Convert array by taking positions from // umap for (int i = 0; i < n; i++) arr[i] = umap[arr[i]]; } void printArr(int arr[], int n) { for (int i=0; i<n; i++) cout << arr[i] << " "; } // Driver program to test above method int main() { int arr[] = {10, 20, 15, 12, 11, 50}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Given Array is \n"; printArr(arr, n); convert(arr , n); cout << "\n\nConverted Array is \n"; printArr(arr, n); return 0; }
linear
nlogn
// C++ program to output the maximum occurring character // in a string #include <bits/stdc++.h> #define ASCII_SIZE 256 using namespace std; char getMaxOccurringChar(char* str) { // Create array to keep the count of individual // characters and initialize the array as 0 int count[ASCII_SIZE] = { 0 }; // Construct character count array from the input // string. int len = strlen(str); int max = 0; // Initialize max count char result; // Initialize result // Traversing through the string and maintaining // the count of each character for (int i = 0; i < len; i++) { count[str[i]]++; if (max < count[str[i]]) { max = count[str[i]]; result = str[i]; } } return result; } // Driver program to test the above function int main() { char str[] = "sample string"; cout << "Max occurring character is " << getMaxOccurringChar(str); }
constant
linear
// C++ program to print all words that have // the same unique character set #include<bits/stdc++.h> using namespace std; #define MAX_CHAR 26 // Generates a key from given string. The key // contains all unique characters of given string in // sorted order consisting of only distinct elements. string getKey(string &str) { bool visited[MAX_CHAR] = { false }; // store all unique characters of current // word in key for (int j = 0; j < str.length(); j++) visited[str[j] - 'a'] = true ; string key = ""; for (int j=0; j < MAX_CHAR; j++) if (visited[j]) key = key + (char)('a'+j); return key; } // Print all words together with same character sets. void wordsWithSameCharSet(string words[], int n) { // Stores indexes of all words that have same // set of unique characters. unordered_map <string, vector <int> > Hash; // Traverse all words for (int i=0; i<n; i++) { string key = getKey(words[i]); Hash[key].push_back(i); } // print all words that have the same unique character set for (auto it = Hash.begin(); it!=Hash.end(); it++) { for (auto v=(*it).second.begin(); v!=(*it).second.end(); v++) cout << words[*v] << ", "; cout << endl; } } // Driver program to test above function int main() { string words[] = { "may", "student", "students", "dog", "studentssess", "god", "cat", "act", "tab", "bat", "flow", "wolf", "lambs", "amy", "yam", "balms", "looped", "poodle"}; int n = sizeof(words)/sizeof(words[0]); wordsWithSameCharSet(words, n); return 0; }
linear
linear
// C++ program to find out the second // most repeated word #include <bits/stdc++.h> using namespace std; // Function to find the word string secMostRepeated(vector<string> seq) { // Store all the words with its occurrence unordered_map<string, int> occ; for (int i = 0; i < seq.size(); i++) occ[seq[i]]++; // find the second largest occurrence int first_max = INT_MIN, sec_max = INT_MIN; for (auto it = occ.begin(); it != occ.end(); it++) { if (it->second > first_max) { sec_max = first_max; first_max = it->second; } else if (it->second > sec_max && it->second != first_max) sec_max = it->second; } // Return string with occurrence equals // to sec_max for (auto it = occ.begin(); it != occ.end(); it++) if (it->second == sec_max) return it->first; } // Driver program int main() { vector<string> seq = { "ccc", "aaa", "ccc", "ddd", "aaa", "aaa" }; cout << secMostRepeated(seq); return 0; }
linear
linear
// C++ program to find the smallest element // with frequency exactly k. #include <bits/stdc++.h> using namespace std; int smallestKFreq(int a[], int n, int k) { unordered_map<int, int> m; // Map is used to store the count of // elements present in the array for (int i = 0; i < n; i++) m[a[i]]++; // Traverse the map and find minimum // element with frequency k. int res = INT_MAX; for (auto it = m.begin(); it != m.end(); ++it) if (it->second == k) res = min(res, it->first); return (res != INT_MAX)? res : -1; } // Driver code int main() { int arr[] = { 2, 2, 1, 3, 1 }; int k = 2; int n = sizeof(arr) / (sizeof(arr[0])); cout << smallestKFreq(arr, n, k); return 0; }
linear
linear
// C++ code to find number // occurring prime number // of times with frequency >= k #include <bits/stdc++.h> using namespace std; // Check if the number of // occurrences are primes // or not bool isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function to find number // with prime occurrences void primeOccurrences(int arr[], int k) { unordered_map<int, int> map; // Insert values and // their frequencies for (int i = 0; i < 12; i++) map[arr[i]]++; // Traverse map and find // elements with prime // frequencies and frequency // at least k for (auto x : map) { if (isPrime(x.second) && x.second >= k) cout << x.first << endl; } } // Driver code int main() { int arr[] = {11, 11, 11, 23, 11, 37, 37, 51, 51, 51, 51, 51}; int k = 2; primeOccurrences(arr, k); return 0; } // This code is contributed by // Manish Shaw(manishshaw1)
linear
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; }
logn
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++ program to find first repeating element in arr[] */ #include <bits/stdc++.h> using namespace std; // This function prints the first repeating element in arr[] void printFirstRepeating(int arr[], int n) { // Initialize index of first repeating element int min = -1; // Creates an empty hashset set<int> myset; // Traverse the input array from right to left for (int i = n - 1; i >= 0; i--) { // If element is already in hash set, update min if (myset.find(arr[i]) != myset.end()) min = i; else // Else add element to hash set myset.insert(arr[i]); } // Print the result if (min != -1) cout << "The first repeating element is " << arr[min]; else cout << "There are no repeating elements"; } // Driver Code int main() { int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); printFirstRepeating(arr, n); } // This article is contributed by Chhavi
linear
linear
/* C++ program to find first repeating element in arr[] */ #include <bits/stdc++.h> using namespace std; // This function prints the // first repeating element in arr[] void printFirstRepeating(int arr[], int n) { // This will set k=1, if any // repeating element found int k = 0; // max = maximum from (all elements & n) int max = n; for (int i = 0; i < n; i++) if (max < arr[i]) max = arr[i]; // Array a is for storing // 1st time occurrence of element // initialized by 0 int a[max + 1] = {}; // Store 1 in array b // if element is duplicate // initialized by 0 int b[max + 1] = {}; for (int i = 0; i < n; i++) { // Duplicate element found if (a[arr[i]]) { b[arr[i]] = 1; k = 1; continue; } else // storing 1st occurrence of arr[i] a[arr[i]] = i + 1; } if (k == 0) cout << "No repeating element found" << endl; else { int min = max + 1; // trace array a & find repeating element // with min index for (int i = 0; i < max + 1; i++) if (a[i] && min > a[i] && b[i]) min = a[i]; cout << arr[min - 1]; } cout << endl; } // Driver method to test above method int main() { int arr[] = { 10, 5, 3, 4, 3, 5, 6 }; int N = sizeof(arr) / sizeof(arr[0]); printFirstRepeating(arr, N); }
linear
linear
// Simple CPP program to find first non- // repeating element. #include <bits/stdc++.h> using namespace std; int firstNonRepeating(int arr[], int n) { // Loop for checking each element for (int i = 0; i < n; i++) { int j; // Checking if ith element is present in array for (j = 0; j < n; j++) if (i != j && arr[i] == arr[j]) break; // if ith element is not present in array // except at ith index then return element if (j == n) return arr[i]; } return -1; } // Driver code int main() { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << firstNonRepeating(arr, n); return 0; }
constant
quadratic
// Efficient CPP program to find first non- // repeating element. #include <bits/stdc++.h> using namespace std; int firstNonRepeating(int arr[], int n) { // Insert all array elements in hash // table unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Traverse array again and return // first element with count 1. for (int i = 0; i < n; i++) if (mp[arr[i]] == 1) return arr[i]; return -1; } // Driver code int main() { int arr[] = { 9, 4, 9, 6, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << firstNonRepeating(arr, n); return 0; }
linear
linear
// C++ program to print k-th distinct // element in a given array #include <bits/stdc++.h> using namespace std; // Returns k-th distinct // element in arr. int printKDistinct(int arr[], int n, int k) { int dist_count = 0; for (int i = 0; i < n; i++) { // Check if current element is // present somewhere else. int j; for (j = 0; j < n; j++) if (i != j && arr[j] == arr[i]) break; // If element is unique if (j == n) dist_count++; if (dist_count == k) return arr[i]; } return -1; } // Driver Code int main () { int ar[] = {1, 2, 1, 3, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); int k = 2; cout << printKDistinct(ar, n, k); return 0; }
constant
quadratic
// C++ program to print k-th // distinct element in a // given array #include <bits/stdc++.h> using namespace std; // Returns k-th distinct // element in arr int printKDistinct(int arr[], int n, int k) { // Traverse input array and // store counts if individual // elements. unordered_map<int, int> h; for (int i = 0; i < n; i++) h[arr[i]]++; // If size of hash is // less than k. if (h.size() < k) return -1; // Traverse array again and // find k-th element with // count as 1. int dist_count = 0; for (int i = 0; i < n; i++) { if (h[arr[i]] == 1) dist_count++; if (dist_count == k) return arr[i]; } return -1; } // Driver Code int main () { int ar[] = {1, 2, 1, 3, 4, 2}; int n = sizeof(ar) / sizeof(ar[0]); cout << printKDistinct(ar, n, 2); return 0; }
linear
linear
// 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
// Simple CPP program to find pairs of positive // and negative values present in an array. #include <bits/stdc++.h> using namespace std; // Print pair with negative and positive value void printPairs(int arr[], int n) { vector<int> v; // For each element of array. for (int i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (int j = i + 1; j < n; j++) // If absolute values are equal print pair. if (abs(arr[i]) == abs(arr[j])) v.push_back(abs(arr[i])); // If size of vector is 0, therefore there is no // element with positive negative value, print "0" if (v.size() == 0) return; // Print the pair with negative positive value. for (int i = 0; i < v.size(); i++) cout << -v[i] << " " << v[i] << " "; } // Driver code int main() { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call printPairs(arr, n); return 0; }
linear
quadratic
// CPP program to find pairs of // positive and negative values present in // an array. #include <bits/stdc++.h> using namespace std; // Print pair with negative and positive value void printPairs(int arr[], int n) { vector<int> v; unordered_map<int, bool> cnt; // For each element of array. for (int i = 0; i < n; i++) { // If element has not encounter early, // mark it on cnt array. if (cnt[abs(arr[i])] == 0) cnt[abs(arr[i])] = 1; // If seen before, push it in vector ( // given that elements are distinct) else { v.push_back(abs(arr[i])); cnt[abs(arr[i])] = 0; } } if (v.size() == 0) return; for (int i = 0; i < v.size(); i++) cout << "-" << v[i] << " " << v[i] << " "; } // Driver code int main() { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call printPairs(arr, n); return 0; }
linear
linear
// CPP program to find pairs of // positive and negative values present in // an array. #include <bits/stdc++.h> using namespace std; // Print pair with negative and positive value void printPairs(int arr[], int n) { unordered_set<int> hs; vector<int> ans; for (int i = 0; i < n; i++) { if (hs.find((arr[i]) * -1) != hs.end()) { if (arr[i] < 0) { cout << arr[i] << " "; cout << (arr[i] * -1) << " "; } else { cout << (arr[i] * -1) << " "; cout << arr[i] << " "; } } hs.insert(arr[i]); } return; } // Driver code int main() { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call printPairs(arr, n); return 0; }
linear
linear
// CPP program to count divisible pairs. #include <bits/stdc++.h> using namespace std; int countDivisibles(int arr[], int n) { int res = 0; // Iterate through all pairs for (int i=0; i<n; i++) for (int j=i+1; j<n; j++) // Increment count if one divides // other if (arr[i] % arr[j] == 0 || arr[j] % arr[i] == 0) res++; return res; } int main() { int a[] = {1, 2, 3, 9}; int n = sizeof(a) / sizeof(a[0]); cout << countDivisibles(a, n); return 0; }
constant
quadratic
// C++ code to implement above approach #include <bits/stdc++.h> using namespace std; // Function to return the total // count of pairs such that // arr[i]%arr[j]==0 int total_count(int arr[], int n) { int count = 0; // Storing the occurrence of // every element in array in // unordered_map unordered_map<int, int> freq; for(int i=0;i<n;i++) { freq[arr[i]]++; } // Iterating through every element // and finding all the divisors of // that element and then checking // how many of them are present // in array arr[] for(int i=0;i<n;i++) { for (int j=1;j<=sqrt(arr[i]);j++) { if(arr[i]%j==0) { if(arr[i]==j*j) { // If divisors are equal, // then take only one as // it will be perfect square // root of arr[i] count+=freq[j]; } else { // Else take both j and arr[i]/j // as both will be divisors count+=freq[j]+ freq[arr[i]/j]; } } } // As all the elements is divisible // by itself and is counted in freq[] // so reducing its count count=count-1; } // Returning final count return count; } // Driver code int main() { int arr[] = { 1, 2, 3, 9 }; int N = sizeof(arr) / sizeof(arr[0]); cout<<total_count(arr,N); return 0; } // This code is contributed by Pushpesh Raj
constant
quadratic
// A C++ program to check if arr[0..n-1] // can be divided in pairs such that // every pair is divisible by k #include <bits/stdc++.h> using namespace std; bool canPairs(int nums[], int n, int k) { // Array with odd length // cannot be divided if (n % 2 == 1) return false; // Initialize count = 0 int count = 0; vector<int> vis(n, -1); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if ((nums[i] + nums[j]) % k == 0 and vis[i] == -1 and vis[j] == -1) { // if pair is divisible increment // the count and mark elements // as visited count++; vis[i] = 1; vis[j] = 1; } } } if (count == n / 2) return true; else return false; } // Driver code int main() { int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call canPairs(arr, n, k) ? cout << "True" : cout << "False"; return 0; } // This code is contributed by Arpit Jain
linear
quadratic
// A C++ program to check if arr[0..n-1] can be divided // in pairs such that every pair is divisible by k. #include <bits/stdc++.h> using namespace std; // Returns true if arr[0..n-1] can be divided into pairs // with sum divisible by k. bool canPairs(int arr[], int n, int k) { // An odd length array cannot be divided into pairs if (n & 1) return false; // Create a frequency array to count occurrences // of all remainders when divided by k. unordered_map<int, int> freq; // Count occurrences of all remainders for (int i = 0; i < n; i++) freq[((arr[i] % k) + k) % k]++; // Traverse input array and use freq[] to decide // if given array can be divided in pairs for (int i = 0; i < n; i++) { // Remainder of current element int rem = ((arr[i] % k) + k) % k; // If remainder with current element divides // k into two halves. if (2 * rem == k) { // Then there must be even occurrences of // such remainder if (freq[rem] % 2 != 0) return false; } // If remainder is 0, then there must be even // number of elements with 0 remainder else if (rem == 0) { if (freq[rem] & 1) return false; } // Else number of occurrences of remainder // must be equal to number of occurrences of // k - remainder else if (freq[rem] != freq[k - rem]) return false; } return true; } // Driver code int main() { int arr[] = { 92, 75, 65, 48, 45, 35 }; int k = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call canPairs(arr, n, k) ? cout << "True" : cout << "False"; return 0; }
linear
linear
// C++ implementation to find the longest subarray // with sum divisible by k #include <bits/stdc++.h> using namespace std; // function to find the longest subarray // with sum divisible by k int longestSubarrWthSumDivByK(int arr[], int n, int k) { // unordered map 'um' implemented as // hash table unordered_map<int, int> um; // 'mod_arr[i]' stores (sum[0..i] % k) int mod_arr[n], max_len = 0; int curr_sum = 0; // traverse arr[] and build up the // array 'mod_arr[]' for (int i = 0; i < n; i++) { curr_sum += arr[i]; // as the sum can be negative, taking modulo twice mod_arr[i] = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible by k if (mod_arr[i] == 0) // update 'max' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.find(mod_arr[i]) == um.end()) um[mod_arr[i]] = i; else // if true, then update 'max' if (max_len < (i - um[mod_arr[i]])) max_len = i - um[mod_arr[i]]; } // return the required length of longest subarray // with sum divisible by 'k' return max_len; } // Driver code int main() { int arr[] = { 2, 7, 6, 1, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << "Length = " << longestSubarrWthSumDivByK(arr, n, k); return 0; } // Code updated by Kshitij Dwivedi
linear
linear
#include <bits/stdc++.h> using namespace std; // function to find the longest subarray // with sum divisible by k int longestSubarrWthSumDivByK(int arr[], int n, int k) { // unordered map 'um' implemented as // hash table unordered_map<int, int> um; int max_len = 0; int curr_sum = 0; for (int i = 0; i < n; i++) { curr_sum += arr[i]; int mod = ((curr_sum % k) + k) % k; // if true then sum(0..i) is divisible // by k if (mod == 0) // update 'max_len' max_len = i + 1; // if value 'mod_arr[i]' not present in 'um' // then store it in 'um' with index of its // first occurrence else if (um.find(mod) == um.end()) um[mod] = i; else // if true, then update 'max_len' if (max_len < (i - um[mod])) max_len = i - um[mod]; } // return the required length of longest subarray with // sum divisible by 'k' return max_len; } // Driver code int main() { int arr[] = { 2, 7, 6, 1, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << "Length = " << longestSubarrWthSumDivByK(arr, n, k); return 0; } // Code Updated by Kshitij Dwivedi
linear
linear
// CPP code to find the subarray with // no pair sum divisible by K #include<bits/stdc++.h> using namespace std; // function to find the subarray with // no pair sum divisible by k void subarrayDivisibleByK(int arr[], int n, int k) { // hash table to store the remainders // obtained on dividing by K map<int,int> mp; // s : starting index of the // current subarray, e : ending // index of the current subarray, maxs : // starting index of the maximum // size subarray so far, maxe : ending // index of the maximum size subarray // so far int s = 0, e = 0, maxs = 0, maxe = 0; // insert the first element in the set mp[arr[0] % k]++; for (int i = 1; i < n; i++) { int mod = arr[i] % k; // Removing starting elements of current // subarray while there is an element in // set which makes a pair with mod[i] such // that the pair sum is divisible. while (mp[k - mod] != 0 || (mod == 0 && mp[mod] != 0)) { mp[arr[s] % k]--; s++; } // include the current element in // the current subarray the ending // index of the current subarray // increments by one mp[mod]++; e++; // compare the size of the current // subarray with the maximum size so // far if ((e - s) > (maxe - maxs)) { maxe = e; maxs = s; } } cout << "The maximum size is " << maxe - maxs + 1 << " and " "the subarray is as follows\n"; for (int i=maxs; i<=maxe; i++) cout << arr[i] << " "; } int main() { int k = 3; int arr[] = {5, 10, 15, 20, 25}; int n = sizeof(arr)/sizeof(arr[0]); subarrayDivisibleByK(arr, n, k); return 0; }
linear
nlogn
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to find special numbers void divisibilityCheck(int arr[], int n) { // Storing all array elements in a hash // and finding maximum element in the array unordered_set<int> s; int max_ele = INT_MIN; for (int i = 0; i < n; i++) { s.insert(arr[i]); // Update the maximum element of the array max_ele = max(max_ele, arr[i]); } // Traversing the array elements and storing the array // multiples that are present in s in res unordered_set<int> res; for (int i = 0; i < n; i++) { // Check for non-zero values only if (arr[i] != 0) { // Checking the factors of current element for (int j = arr[i] * 2; j <= max_ele; j += arr[i]) { // If current factor is already part // of the array then store it if (s.find(j) != s.end()) res.insert(j); } } } // For non-distinct elmments // To store the frequency of elements unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; unordered_map<int, int>::iterator it; vector<int> ans; for (it = mp.begin(); it != mp.end(); it++) { // If frequency is at least 2 if (it->second >= 2) { if (res.find(it->first) == res.end()) { // If frequency is greater than 1 and // the number is not divisible by // any other number int val = it->second; // Then we push the element number of // times it is present in the vector while (val--) ans.push_back(it->first); } } // If frequency is greater than 1 and the number // is divisible by any other number if (res.find(it->first) != res.end()) { int val = it->second; // Then we push the element number of // times it is present in the vector while (val--) ans.push_back(it->first); } } // Print the elements that are divisible by // at least one other element from the array for (auto x : ans) cout << x << " "; } // Driver code int main() { int arr[] = { 2, 3, 8, 6, 9, 10 }; int n = sizeof(arr) / sizeof(arr[0]); divisibilityCheck(arr, n); return 0; }
linear
quadratic
// C++ program to find three element // from different three arrays such // that a + b + c is equal to // given sum #include<bits/stdc++.h> using namespace std; // Function to check if there is // an element from each array such // that sum of the three elements // is equal to given sum. bool findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum) { for (int i = 0; i < n1; i++) for (int j = 0; j < n2; j++) for (int k = 0; k < n3; k++) if (a1[i] + a2[j] + a3[k] == sum) return true; return false; } // Driver Code int main() { int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = sizeof(a1) / sizeof(a1[0]); int n2 = sizeof(a2) / sizeof(a2[0]); int n3 = sizeof(a3) / sizeof(a3[0]); findTriplet(a1, a2, a3, n1, n2, n3, sum)? cout << "Yes" : cout << "No"; return 0; }
constant
cubic
// C++ program to find three element // from different three arrays such // that a + b + c is equal to // given sum #include<bits/stdc++.h> using namespace std; // Function to check if there is // an element from each array such // that sum of the three elements is // equal to given sum. bool findTriplet(int a1[], int a2[], int a3[], int n1, int n2, int n3, int sum) { // Store elements of // first array in hash unordered_set <int> s; for (int i = 0; i < n1; i++) s.insert(a1[i]); // sum last two arrays // element one by one for (int i = 0; i < n2; i++) { for (int j = 0; j < n3; j++) { // Consider current pair and // find if there is an element // in a1[] such that these three // form a required triplet if (s.find(sum - a2[i] - a3[j]) != s.end()) return true; } } return false; } // Driver Code int main() { int a1[] = { 1 , 2 , 3 , 4 , 5 }; int a2[] = { 2 , 3 , 6 , 1 , 2 }; int a3[] = { 3 , 2 , 4 , 5 , 6 }; int sum = 9; int n1 = sizeof(a1) / sizeof(a1[0]); int n2 = sizeof(a2) / sizeof(a2[0]); int n3 = sizeof(a3) / sizeof(a3[0]); findTriplet(a1, a2, a3, n1, n2, n3, sum)? cout << "Yes" : cout << "No"; return 0; }
linear
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Returns length of the largest // subarray with 0 sum int maxLen(int arr[], int N) { // Initialize result int max_len = 0; // Pick a starting point for (int i = 0; i < N; i++) { // Initialize currr_sum for // every starting point int curr_sum = 0; // Try all subarrays starting with 'i' for (int j = i; j < N; j++) { curr_sum += arr[j]; // If curr_sum becomes 0, // then update max_len // if required if (curr_sum == 0) max_len = max(max_len, j - i + 1); } } return max_len; } // Driver's Code int main() { int arr[] = {15, -2, 2, -8, 1, 7, 10, 23}; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << "Length of the longest 0 sum subarray is " << maxLen(arr, N); return 0; }
constant
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Returns Length of the required subarray int maxLen(int arr[], int N) { // Map to store the previous sums unordered_map<int, int> presum; int sum = 0; // Initialize the 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]; if (sum == 0) max_len = i + 1; // Look for this sum in Hash table if (presum.find(sum) != presum.end()) { // If this sum is seen before, then update // max_len max_len = max(max_len, i - presum[sum]); } else { // Else insert this sum with index // in hash table presum[sum] = i; } } return max_len; } // Driver's Code int main() { int arr[] = { 15, -2, 2, -8, 1, 7, 10, 23 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << "Length of the longest 0 sum subarray is " << maxLen(arr, N); return 0; }
linear
linear
// CPP program to find length of the // longest increasing subsequence // whose adjacent element differ by 1 #include <bits/stdc++.h> using namespace std; // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 void longestSubsequence(int a[], int n) { // stores the index of elements unordered_map<int, int> mp; // stores the length of the longest // subsequence that ends with a[i] int dp[n]; memset(dp, 0, sizeof(dp)); int maximum = INT_MIN; // iterate for all element int index = -1; for (int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.find(a[i] - 1) != mp.end()) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length if (maximum < dp[i]) { maximum = dp[i]; index = i; } } // We know last element of sequence is // a[index]. We also know that length // of subsequence is "maximum". So We // print these many consecutive elements // starting from "a[index] - maximum + 1" // to a[index]. for (int curr = a[index] - maximum + 1; curr <= a[index]; curr++) cout << curr << " "; } // Driver Code int main() { int a[] = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = sizeof(a) / sizeof(a[0]); longestSubsequence(a, n); return 0; }
linear
linear
// CPP program to find length of the // longest increasing subsequence // whose adjacent element differ by 1 #include <bits/stdc++.h> using namespace std; // function that returns the length of the // longest increasing subsequence // whose adjacent element differ by 1 int longestSubsequence(int a[], int n) { // stores the index of elements unordered_map<int, int> mp; // stores the length of the longest // subsequence that ends with a[i] int dp[n]; memset(dp, 0, sizeof(dp)); int maximum = INT_MIN; // iterate for all element for (int i = 0; i < n; i++) { // if a[i]-1 is present before i-th index if (mp.find(a[i] - 1) != mp.end()) { // last index of a[i]-1 int lastIndex = mp[a[i] - 1] - 1; // relation dp[i] = 1 + dp[lastIndex]; } else dp[i] = 1; // stores the index as 1-index as we need to // check for occurrence, hence 0-th index // will not be possible to check mp[a[i]] = i + 1; // stores the longest length maximum = max(maximum, dp[i]); } return maximum; } // Driver Code int main() { int a[] = { 3, 10, 3, 11, 4, 5, 6, 7, 8, 12 }; int n = sizeof(a) / sizeof(a[0]); cout << longestSubsequence(a, n); return 0; }
linear
linear
// C++ implementation to find longest subsequence // such that difference between adjacents is one #include <bits/stdc++.h> using namespace std; // function to find longest subsequence such // that difference between adjacents is one int longLenSub(int arr[], int n) { // hash table to map the array element with the // length of the longest subsequence of which // it is a part of and is the last element of // that subsequence unordered_map<int, int> um; // to store the longest length subsequence int longLen = 0; // traverse the array elements for (int i=0; i<n; i++) { // initialize current length // for element arr[i] as 0 int len = 0; // if 'arr[i]-1' is in 'um' and its length // of subsequence is greater than 'len' if (um.find(arr[i]-1) != um.end() && len < um[arr[i]-1]) len = um[arr[i]-1]; // if 'arr[i]+1' is in 'um' and its length // of subsequence is greater than 'len' if (um.find(arr[i]+1) != um.end() && len < um[arr[i]+1]) len = um[arr[i]+1]; // update arr[i] subsequence length in 'um' um[arr[i]] = len + 1; // update longest length if (longLen < um[arr[i]]) longLen = um[arr[i]]; } // required longest length subsequence return longLen; } // Driver program to test above int main() { int arr[] = {1, 2, 3, 4, 5, 3, 2}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Longest length subsequence = " << longLenSub(arr, n); return 0; }
linear
linear
// C++ implementation of longest continuous increasing // subsequence #include <bits/stdc++.h> using namespace std; // Function for LIS int findLIS(int A[], int n) { unordered_map<int, int> hash; // Initialize result int LIS_size = 1; int LIS_index = 0; hash[A[0]] = 1; // iterate through array and find // end index of LIS and its Size for (int i = 1; i < n; i++) { hash[A[i]] = hash[A[i] - 1] + 1; if (LIS_size < hash[A[i]]) { LIS_size = hash[A[i]]; LIS_index = A[i]; } } // print LIS size cout << "LIS_size = " << LIS_size << "\n"; // print LIS after setting start element cout << "LIS : "; int start = LIS_index - LIS_size + 1; while (start <= LIS_index) { cout << start << " "; start++; } } // driver int main() { int A[] = { 2, 5, 3, 7, 4, 8, 5, 13, 6 }; int n = sizeof(A) / sizeof(A[0]); findLIS(A, n); return 0; }
linear
linear
// C++ implementation to count subsets having // even numbers only and all are distinct #include <bits/stdc++.h> using namespace std; // function to count the // required subsets int countSubsets(int arr[], int n) { unordered_set<int> us; int even_count = 0; // inserting even numbers in the set 'us' // single copy of each number is retained for (int i=0; i<n; i++) if (arr[i] % 2 == 0) us.insert(arr[i]); unordered_set<int>:: iterator itr; // distinct even numbers even_count = us.size(); // total count of required subsets return (pow(2, even_count) - 1); } // Driver program to test above int main() { int arr[] = {4, 2, 1, 9, 2, 6, 5, 3}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Number of subsets = " << countSubsets(arr, n); return 0; }
linear
linear
// C++ program to count distinct // elements in every window of size K #include <bits/stdc++.h> using namespace std; // Counts distinct elements in window of size K int countWindowDistinct(int win[], int K) { int dist_count = 0; // Traverse the window for (int i = 0; i < K; i++) { // Check if element arr[i] exists in arr[0..i-1] int j; for (j = 0; j < i; j++) if (win[i] == win[j]) break; if (j == i) dist_count++; } return dist_count; } // Counts distinct elements in all windows of size k void countDistinct(int arr[], int N, int K) { // Traverse through every window for (int i = 0; i <= N - K; i++) cout << countWindowDistinct(arr + i, K) << endl; } // Driver's code int main() { int arr[] = {1, 2, 1, 3, 4, 2, 3}, K = 4; int N = sizeof(arr) / sizeof(arr[0]); // Function call countDistinct(arr, N, K); return 0; }
constant
quadratic
// C++ program for the above approach #include <iostream> #include <unordered_map> using namespace std; void countDistinct(int arr[], int K, int N) { // Creates an empty hashmap hm unordered_map<int, int> hm; // initialize distinct element count for current window int dist_count = 0; // Traverse the first window and store count // of every element in hash map for (int i = 0; i < K; i++) { if (hm[arr[i]] == 0) { dist_count++; } hm[arr[i]] += 1; } // Print count of first window cout << dist_count << endl; // Traverse through the remaining array for (int i = K; i < N; i++) { // Remove first element of previous window // If there was only one occurrence, then reduce distinct count. if (hm[arr[i - K]] == 1) { dist_count--; } // reduce count of the removed element hm[arr[i - K]] -= 1; // Add new element of current window // If this element appears first time, // increment distinct element count if (hm[arr[i]] == 0) { dist_count++; } hm[arr[i]] += 1; // Print count of current window cout << dist_count << endl; } } // Driver's code int main() { int arr[] = {1, 2, 1, 3, 4, 2, 3}; int N = sizeof(arr) / sizeof(arr[0]); int K = 4; // Function call countDistinct(arr, K, N); return 0; } // This solution is contributed by Aditya Goel
linear
linear
// C++ program to find the maximum // possible sum of a window in one // array such that elements in same // window of other array are unique. #include <bits/stdc++.h> using namespace std; // Function to return maximum sum of window // in B[] according to given constraints. int returnMaxSum(int A[], int B[], int n) { // Map is used to store elements // and their counts. unordered_set<int> mp; int result = 0; // Initialize result // calculating the maximum possible // sum for each subarray containing // unique elements. int curr_sum = 0, curr_begin = 0; for (int i = 0; i < n; ++i) { // Remove all duplicate // instances of A[i] in // current window. while (mp.find(A[i]) != mp.end()) { mp.erase(A[curr_begin]); curr_sum -= B[curr_begin]; curr_begin++; } // Add current instance of A[i] // to map and to current sum. mp.insert(A[i]); curr_sum += B[i]; // Update result if current // sum is more. result = max(result, curr_sum); } return result; } // Driver code int main() { int A[] = { 0, 1, 2, 3, 0, 1, 4 }; int B[] = { 9, 8, 1, 2, 3, 4, 5 }; int n = sizeof(A)/sizeof(A[0]); cout << returnMaxSum(A, B, n); return 0; }
linear
linear
// C++ program to find if // there is a zero sum subarray #include <bits/stdc++.h> using namespace std; bool subArrayExists(int arr[], int N) { unordered_set<int> sumSet; // Traverse through array // and store prefix sums int sum = 0; for (int i = 0; i < N; i++) { sum += arr[i]; // If prefix sum is 0 or // it is already present if (sum == 0 || sumSet.find(sum) != sumSet.end()) return true; sumSet.insert(sum); } return false; } // Driver's code int main() { int arr[] = {-3, 2, 3, 1, 6}; int N = sizeof(arr) / sizeof(arr[0]); // Function call if (subArrayExists(arr, N)) cout << "Found a subarray with 0 sum"; else cout << "No Such Sub Array Exists!"; return 0; }
linear
linear
// C++ program to print all subarrays // in the array which has sum 0 #include <bits/stdc++.h> using namespace std; vector<pair<int, int> > findSubArrays(int arr[], int n) { // Array to store all the start and end // indices of subarrays with 0 sum vector<pair<int, int> > out; for (int i = 0; i < n; i++) { int prefix = 0; for (int j = i; j < n; j++) { prefix += arr[j]; if (prefix == 0) out.push_back({ i, j }); } } return out; } // Function to print all subarrays with 0 sum void print(vector<pair<int, int> > out) { for (auto it = out.begin(); it != out.end(); it++) cout << "Subarray found from Index " << it->first << " to " << it->second << endl; } // Driver code int main() { // Given array int arr[] = { 6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call vector<pair<int, int> > out = findSubArrays(arr, n); // if we didn’t find any subarray with 0 sum, // then subarray doesn’t exists if (out.size() == 0) { cout << "No subarray exists"; } else { print(out); } return 0; } // This article is contributed by Arpit Jain
constant
quadratic
// C++ program to print all subarrays // in the array which has sum 0 #include <bits/stdc++.h> using namespace std; // Function to print all subarrays in the array which // has sum 0 vector< pair<int, int> > findSubArrays(int arr[], int n) { // create an empty map unordered_map<int, vector<int> > map; // create an empty vector of pairs to store // subarray starting and ending index vector <pair<int, int>> out; // Maintains sum of elements so far int sum = 0; for (int i = 0; i < n; i++) { // add current element to sum sum += arr[i]; // if sum is 0, we found a subarray starting // from index 0 and ending at index i if (sum == 0) out.push_back(make_pair(0, i)); // If sum already exists in the map there exists // at-least one subarray ending at index i with // 0 sum if (map.find(sum) != map.end()) { // map[sum] stores starting index of all subarrays vector<int> vc = map[sum]; for (auto it = vc.begin(); it != vc.end(); it++) out.push_back(make_pair(*it + 1, i)); } // Important - no else map[sum].push_back(i); } // return output vector return out; } // Utility function to print all subarrays with sum 0 void print(vector<pair<int, int>> out) { for (auto it = out.begin(); it != out.end(); it++) cout << "Subarray found from Index " << it->first << " to " << it->second << endl; } // Driver code int main() { int arr[] = {6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7}; int n = sizeof(arr)/sizeof(arr[0]); vector<pair<int, int> > out = findSubArrays(arr, n); // if we didn’t find any subarray with 0 sum, // then subarray doesn’t exists if (out.size() == 0) cout << "No subarray exists"; else print(out); return 0; }
linear
linear
/* A simple program to print subarray with sum as given sum */ #include <bits/stdc++.h> using namespace std; /* Returns true if the there is a subarray of arr[] with sum equal to 'sum' otherwise returns false. Also, prints the result */ int subArraySum(int arr[], int n, int sum) { int curr_sum, i, j; // Pick a starting point for (i = 0; i < n; i++) { curr_sum = 0; // try all subarrays starting with 'i' for (j = i; j < n; j++) { curr_sum = curr_sum + arr[j]; if (curr_sum == sum) { cout << "Sum found between indexes " << i << " and " << j; return 1; } } } cout << "No subarray found"; return 0; } // Driver Code int main() { int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = 23; // Function call subArraySum(arr, n, sum); return 0; }
constant
quadratic
// C++ program to print subarray with sum as given sum #include <bits/stdc++.h> using namespace std; // Function to print subarray with sum as given sum void subArraySum(int arr[], int n, int sum) { // create an empty map unordered_map<int, int> map; // Maintains sum of elements so far int curr_sum = 0; for (int i = 0; i < n; i++) { // add current element to curr_sum curr_sum = curr_sum + arr[i]; // if curr_sum is equal to target sum // we found a subarray starting from index 0 // and ending at index i if (curr_sum == sum) { cout << "Sum found between indexes " << 0 << " to " << i << endl; return; } // If curr_sum - sum already exists in map // we have found a subarray with target sum if (map.find(curr_sum - sum) != map.end()) { cout << "Sum found between indexes " << map[curr_sum - sum] + 1 << " to " << i << endl; return; } map[curr_sum] = i; } // If we reach here, then no subarray exists cout << "No subarray with given sum exists"; } // Driver code int main() { int arr[] = { 10, 2, -2, -20, 10 }; int n = sizeof(arr) / sizeof(arr[0]); int sum = -10; // Function call subArraySum(arr, n, sum); return 0; }
linear
linear
// CPP program to find minimum number // of insertions to make a string // palindrome #include <bits/stdc++.h> using namespace std; // Function will return number of // characters to be added int minInsertion(string str) { // To store string length int n = str.length(); // To store number of characters // occurring odd number of times int res = 0; // To store count of each // character int count[26] = { 0 }; // To store occurrence of each // character for (int i = 0; i < n; i++) count[str[i] - 'a']++; // To count characters with odd // occurrence for (int i = 0; i < 26; i++) if (count[i] % 2 == 1) res++; // As one character can be odd return // res - 1 but if string is already // palindrome return 0 return (res == 0) ? 0 : res - 1; } // Driver program int main() { string str = "geeksforgeeks"; cout << minInsertion(str); return 0; }
constant
linear
// C++ implementation to find maximum length // subsequence with difference between adjacent // elements as either 0 or 1 #include <bits/stdc++.h> using namespace std; // function to find maximum length subsequence // with difference between adjacent elements as // either 0 or 1 int maxLenSub(int arr[], int n) { // hash table to map the array element with the // length of the longest subsequence of which // it is a part of and is the last element of // that subsequence unordered_map<int, int> um; // to store the maximum length subsequence int maxLen = 0; // traverse the array elements for (int i=0; i<n; i++) { // initialize current length // for element arr[i] as 0 int len = 0; // if 'arr[i]-1' is in 'um' and its length of // subsequence is greater than 'len' if (um.find(arr[i]-1) != um.end() && len < um[arr[i]-1]) len = um[arr[i]-1]; // if 'arr[i]' is in 'um' and its length of // subsequence is greater than 'len' if (um.find(arr[i]) != um.end() && len < um[arr[i]]) len = um[arr[i]]; // if 'arr[i]+1' is in 'um' and its length of // subsequence is greater than 'len' if (um.find(arr[i]+1) != um.end() && len < um[arr[i]+1]) len = um[arr[i]+1]; // update arr[i] subsequence length in 'um' um[arr[i]] = len + 1; // update maximum length if (maxLen < um[arr[i]]) maxLen = um[arr[i]]; } // required maximum length subsequence return maxLen; } // Driver program to test above int main() { int arr[] = {2, 5, 6, 3, 7, 6, 5, 8}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum length subsequence = " << maxLenSub(arr, n); return 0; }
linear
linear
// C++ program to find maximum difference // between frequency of any two element // such that element with greater frequency // is also greater in value. #include<bits/stdc++.h> using namespace std; // Return the maximum difference between // frequencies of any two elements such that // element with greater frequency is also // greater in value. int maxdiff(int arr[], int n) { unordered_map<int, int> freq; // Finding the frequency of each element. for (int i = 0; i < n; i++) freq[arr[i]]++; int ans = 0; for (int i=0; i<n; i++) { for (int j=0; j<n; j++) { // finding difference such that element // having greater frequency is also // greater in value. if (freq[arr[i]] > freq[arr[j]] && arr[i] > arr[j] ) ans = max(ans, freq[arr[i]]-freq[arr[j]]); else if (freq[arr[i]] < freq[arr[j]] && arr[i] < arr[j] ) ans = max(ans, freq[arr[j]]-freq[arr[i]]); } } return ans; } // Driven Program int main() { int arr[] = { 3, 1, 3, 2, 3, 2 }; int n = sizeof(arr)/sizeof(arr[0]); cout << maxdiff(arr, n) << endl; return 0; }
linear
quadratic
// Efficient C++ program to find maximum // difference between frequency of any two // elements such that element with greater // frequency is also greater in value. #include<bits/stdc++.h> using namespace std; // Return the maximum difference between // frequencies of any two elements such that // element with greater frequency is also // greater in value. int maxdiff(int arr[], int n) { unordered_map<int, int> freq; int dist[n]; // Finding the frequency of each element. int j = 0; for (int i = 0; i < n; i++) { if (freq.find(arr[i]) == freq.end()) dist[j++] = arr[i]; freq[arr[i]]++; } // Sorting the distinct element sort(dist, dist + j); int min_freq = n+1; // Iterate through all sorted distinct elements. // For each distinct element, maintaining the // element with minimum frequency than that // element and also finding the maximum // frequency difference int ans = 0; for (int i=0; i<j; i++) { int cur_freq = freq[dist[i]]; ans = max(ans, cur_freq - min_freq); min_freq = min(min_freq, cur_freq); } return ans; } // Driven Program int main() { int arr[] = { 3, 1, 3, 2, 3, 2 }; int n = sizeof(arr)/sizeof(arr[0]); cout << maxdiff(arr, n) << endl; return 0; }
linear
nlogn
// CPP code to find the difference between highest // and least frequencies #include <bits/stdc++.h> using namespace std; int findDiff(int arr[], int n) { // sort the array sort(arr, arr + n); int count = 0, max_count = 0, min_count = n; for (int i = 0; i < (n - 1); i++) { // checking consecutive elements if (arr[i] == arr[i + 1]) { count += 1; continue; } else { max_count = max(max_count, count); min_count = min(min_count, count); count = 0; } } return (max_count - min_count); } // Driver code int main() { int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findDiff(arr, n) << "\n"; return 0; }
constant
nlogn
// CPP code to find the difference between highest // and least frequencies #include <bits/stdc++.h> using namespace std; int findDiff(int arr[], int n) { // Put all elements in a hash map unordered_map<int, int> hm; for (int i = 0; i < n; i++) hm[arr[i]]++; // Find counts of maximum and minimum // frequent elements int max_count = 0, min_count = n; for (auto x : hm) { max_count = max(max_count, x.second); min_count = min(min_count, x.second); } return (max_count - min_count); } // Driver int main() { int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findDiff(arr, n) << "\n"; return 0; }
linear
linear
// C++ program to find minimum range that // contains exactly k distinct numbers. #include <bits/stdc++.h> using namespace std; // Prints the minimum range that contains exactly // k distinct numbers. void minRange(int arr[], int n, int k) { // Starting and ending index of resultant subarray int start = 0, end = n; // Selecting each element as the start index for // subarray for (int i = 0; i < n; i++) { // Initialize a set to store all distinct elements unordered_set<int> set; // Selecting the end index for subarray int j; for (j = i; j < n; j++) { set.insert(arr[j]); /* If set contains exactly k elements, then check subarray[i, j] is smaller in size than the current resultant subarray */ if (set.size() == k) { if (j - i < end - start) { start = i; end = j; } // There are already k distinct elements // now, no need to consider further elements break; } } // If there are no k distinct elements // left in the array starting from index i we will // break if (j == n) { break; } } // If no window found then print -1 if (start == 0 && end == n) cout << "Invalid k"; else cout << start << " " << end; } // Driver code for above function. int main() { int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; minRange(arr, n, k); return 0; } // This code is contributed by Rajdeep
linear
quadratic
// C++ program to find minimum range that // contains exactly k distinct numbers. #include <bits/stdc++.h> using namespace std; // prints the minimum range that contains exactly // k distinct numbers. void minRange(int arr[], int n, int k) { /* start = starting index of resultant subarray end = ending index of resultant subarray */ int start = 0, end = n; unordered_map<int, int> map; /* i = starting index of the window (on left side) j = ending index of the window (on right side) */ int i = 0, j = 0; while (j < n) { // Add the current element to the map map[arr[j]]++; j++; // Nothing to do when having less element if (map.size() < k) continue; /* If map contains exactly k elements, consider subarray[i, j - 1] keep removing left most elements */ while (map.size() == k) { // as considering the (j-1)th and i-th index int windowLen = (j - 1) - i + 1; int subArrayLen = end - start + 1; if (subArrayLen > windowLen) { start = i; end = j - 1; } // Remove elements from left // If freq == 1 then totally erase if (map[arr[i]] == 1) map.erase(arr[i]); // decrease freq by 1 else map[arr[i]]--; // move the starting index of window i++; } } if (start == 0 && end == n) cout << "Invalid k" << endl; else cout << start << " " << end << endl; } // Driver code for above function. int main() { int arr[] = { 1, 1, 2, 2, 3, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; minRange(arr, n, k); return 0; } // This code is contributed by Rajdeep
linear
linear
// CPP program to find longest subarray with // k or less distinct elements. #include <bits/stdc++.h> using namespace std; // function to print the longest sub-array void longest(int a[], int n, int k) { unordered_map<int, int> freq; int start = 0, end = 0, now = 0, l = 0; for (int i = 0; i < n; i++) { // mark the element visited freq[a[i]]++; // if its visited first time, then increase // the counter of distinct elements by 1 if (freq[a[i]] == 1) now++; // When the counter of distinct elements // increases from k, then reduce it to k while (now > k) { // from the left, reduce the number of // time of visit freq[a[l]]--; // if the reduced visited time element // is not present in further segment // then decrease the count of distinct // elements if (freq[a[l]] == 0) now--; // increase the subsegment mark l++; } // check length of longest sub-segment // when greater than previous best // then change it if (i - l + 1 >= end - start + 1) end = i, start = l; } // print the longest sub-segment for (int i = start; i <= end; i++) cout << a[i] << " "; } // driver program to test the above function int main() { int a[] = { 6, 5, 1, 2, 3, 2, 1, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); int k = 3; longest(a, n, k); return 0; }
linear
linear
// C++ program to find number of pairs in an array such that // their XOR is 0 #include <bits/stdc++.h> using namespace std; // Function to calculate the count int calculate(int a[], int n) { // Sorting the list using built in function sort(a, a + n); int count = 1; int answer = 0; // Traversing through the elements for (int i = 1; i < n; i++) { if (a[i] == a[i - 1]) // Counting frequency of each elements count += 1; else { // Adding the contribution of the frequency to // the answer answer = answer + (count * (count - 1)) / 2; count = 1; } } answer = answer + (count * (count - 1)) / 2; return answer; } // Driver Code int main() { int a[] = { 1, 2, 1, 2, 4 }; int n = sizeof(a) / sizeof(a[0]); cout << calculate(a, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
nlogn
// C++ program to find number of pairs // in an array such that their XOR is 0 #include <bits/stdc++.h> using namespace std; // Function to calculate the answer int calculate(int a[], int n){ // Finding the maximum of the array int *maximum = max_element(a, a + n); // Creating frequency array // With initial value 0 int frequency[*maximum + 1] = {0}; // Traversing through the array for(int i = 0; i < n; i++) { // Counting frequency frequency[a[i]] += 1; } int answer = 0; // Traversing through the frequency array for(int i = 0; i < (*maximum)+1; i++) { // Calculating answer answer = answer + frequency[i] * (frequency[i] - 1) ; } return answer/2; } // Driver Code int main() { int a[] = {1, 2, 1, 2, 4}; int n = sizeof(a) / sizeof(a[0]); // Function calling cout << (calculate(a,n)); } // This code is contributed by Smitha
linear
linear
// C++ implementation to count subarrays with // equal number of 1's and 0's #include <bits/stdc++.h> using namespace std; // function to count subarrays with // equal number of 1's and 0's int countSubarrWithEqualZeroAndOne(int arr[], int n) { // 'um' implemented as hash table to store // frequency of values obtained through // cumulative sum unordered_map<int, int> um; int curr_sum = 0; // Traverse original array and compute cumulative // sum and increase count by 1 for this sum // in 'um'. Adds '-1' when arr[i] == 0 for (int i = 0; i < n; i++) { curr_sum += (arr[i] == 0) ? -1 : arr[i]; um[curr_sum]++; } int count = 0; // traverse the hash table 'um' for (auto itr = um.begin(); itr != um.end(); itr++) { // If there are more than one prefix subarrays // with a particular sum if (itr->second > 1) count += ((itr->second * (itr->second - 1)) / 2); } // add the subarrays starting from 1st element and // have equal number of 1's and 0's if (um.find(0) != um.end()) count += um[0]; // required count of subarrays return count; } // Driver program to test above int main() { int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Count = " << countSubarrWithEqualZeroAndOne(arr, n); return 0; }
linear
linear
#include <bits/stdc++.h> using namespace std; int countSubarrWithEqualZeroAndOne(int arr[], int n) { unordered_map<int, int> mp; int sum = 0; int count = 0; for (int i = 0; i < n; i++) { // Replacing 0's in array with -1 if (arr[i] == 0) arr[i] = -1; sum += arr[i]; // If sum = 0, it implies number of 0's and 1's are // equal from arr[0]..arr[i] if (sum == 0) count++; // if mp[sum] exists then add "frequency-1" to count if (mp[sum]) count += mp[sum]; // if frequency of "sum" is zero then we initialize // that frequency to 1 if its not 0, we increment it if (mp[sum] == 0) mp[sum] = 1; else mp[sum]++; } return count; } int main() { int arr[] = { 1, 0, 0, 1, 0, 1, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "count=" << countSubarrWithEqualZeroAndOne(arr, n); }
linear
linear
// C++ implementation to find the length of // longest subarray having count of 1's one // more than count of 0's #include <bits/stdc++.h> using namespace std; // function to find the length of longest // subarray having count of 1's one more // than count of 0's int lenOfLongSubarr(int arr[], int n) { // unordered_map 'um' implemented as // hash table unordered_map<int, int> um; int sum = 0, maxLen = 0; // traverse the given array for (int i = 0; i < n; i++) { // consider '0' as '-1' sum += arr[i] == 0 ? -1 : 1; // when subarray starts form index '0' if (sum == 1) maxLen = i + 1; // make an entry for 'sum' if it is // not present in 'um' else if (um.find(sum) == um.end()) um[sum] = i; // check if 'sum-1' is present in 'um' // or not if (um.find(sum - 1) != um.end()) { // update maxLength if (maxLen < (i - um[sum - 1])) maxLen = i - um[sum - 1]; } } // required maximum length return maxLen; } // Driver program to test above int main() { int arr[] = { 0, 1, 1, 0, 0, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Length = " << lenOfLongSubarr(arr, n); return 0; }
linear
linear
// C++ program to print all triplets in given // array that form Arithmetic Progression // C++ program to print all triplets in given // array that form Arithmetic Progression #include <bits/stdc++.h> using namespace std; // Function to print all triplets in // given sorted array that forms AP void printAllAPTriplets(int arr[], int n) { unordered_set<int> s; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // Use hash to find if there is // a previous element with difference // equal to arr[j] - arr[i] int diff = arr[j] - arr[i]; if (s.find(arr[i] - diff) != s.end()) cout << arr[i] - diff << " " << arr[i] << " " << arr[j] << endl; } s.insert(arr[i]); } } // Driver code int main() { int arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 }; int n = sizeof(arr) / sizeof(arr[0]); printAllAPTriplets(arr, n); return 0; }
linear
quadratic
// C++ program to print all triplets in given // array that form Arithmetic Progression #include <bits/stdc++.h> using namespace std; // Function to print all triplets in // given sorted array that forms AP void printAllAPTriplets(int arr[], int n) { for (int i = 1; i < n - 1; i++) { // Search other two elements of // AP with arr[i] as middle. for (int j = i - 1, k = i + 1; j >= 0 && k < n;) { // if a triplet is found if (arr[j] + arr[k] == 2 * arr[i]) { cout << arr[j] << " " << arr[i] << " " << arr[k] << endl; // Since elements are distinct, // arr[k] and arr[j] cannot form // any more triplets with arr[i] k++; j--; } // If middle element is more move to // higher side, else move lower side. else if (arr[j] + arr[k] < 2 * arr[i]) k++; else j--; } } } // Driver code int main() { int arr[] = { 2, 6, 9, 12, 17, 22, 31, 32, 35, 42 }; int n = sizeof(arr) / sizeof(arr[0]); printAllAPTriplets(arr, n); return 0; }
constant
quadratic
// C++ program to find unique triplets // that sum up to a given value. #include <bits/stdc++.h> using namespace std; // Structure to define a triplet. struct triplet { int first, second, third; }; // Function to find unique triplets that // sum up to a given value. int findTriplets(int nums[], int n, int sum) { int i, j, k; // Vector to store all unique triplets. vector<triplet> triplets; // Set to store already found triplets // to avoid duplication. unordered_set<string> uniqTriplets; // Variable used to hold triplet // converted to string form. string temp; // Variable used to store current // triplet which is stored in vector // if it is unique. triplet newTriplet; // Sort the input array. sort(nums, nums + n); // Iterate over the array from the // start and consider it as the // first element. for (i = 0; i < n - 2; i++) { // index of the first element in // the remaining elements. j = i + 1; // index of the last element. k = n - 1; while (j < k) { // If sum of triplet is equal to // given value, then check if // this triplet is unique or not. // To check uniqueness, convert // triplet to string form and // then check if this string is // present in set or not. If // triplet is unique, then store // it in vector. if (nums[i] + nums[j] + nums[k] == sum) { temp = to_string(nums[i]) + " : " + to_string(nums[j]) + " : " + to_string(nums[k]); if (uniqTriplets.find(temp) == uniqTriplets.end()) { uniqTriplets.insert(temp); newTriplet.first = nums[i]; newTriplet.second = nums[j]; newTriplet.third = nums[k]; triplets.push_back(newTriplet); } // Increment the first index // and decrement the last // index of remaining elements. j++; k--; } // If sum is greater than given // value then to reduce sum // decrement the last index. else if (nums[i] + nums[j] + nums[k] > sum) k--; // If sum is less than given value // then to increase sum increment // the first index of remaining // elements. else j++; } } // If no unique triplet is found, then // return 0. if (triplets.size() == 0) return 0; // Print all unique triplets stored in // vector. for (i = 0; i < triplets.size(); i++) { cout << "[" << triplets[i].first << ", " << triplets[i].second << ", " << triplets[i].third << "], "; } } // Driver Code int main() { int nums[] = { 12, 3, 6, 1, 6, 9 }; int n = sizeof(nums) / sizeof(nums[0]); int sum = 24; // Function call if (!findTriplets(nums, n, sum)) cout << "No triplets can be formed."; return 0; } // This code is contributed by NIKHIL JINDAL.
linear
quadratic
// A simple C++ program to find three elements // whose sum is equal to zero #include <bits/stdc++.h> using namespace std; // Prints all triplets in arr[] with 0 sum void findTriplets(int arr[], int n) { bool found = false; for (int i = 0; i < n - 2; i++) { for (int j = i + 1; j < n - 1; j++) { for (int k = j + 1; k < n; k++) { if (arr[i] + arr[j] + arr[k] == 0) { cout << arr[i] << " " << arr[j] << " " << arr[k] << endl; found = true; } } } } // If no triplet with 0 sum found in array if (found == false) cout << " not exist " << endl; } // Driver code int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
cubic
// C++ program to find triplets in a given // array whose sum is zero #include <bits/stdc++.h> using namespace std; // function to print triplets with 0 sum void findTriplets(int arr[], int n) { bool found = false; for (int i = 0; i < n - 1; i++) { // Find all pairs with sum equals to // "-arr[i]" unordered_set<int> s; for (int j = i + 1; j < n; j++) { int x = -(arr[i] + arr[j]); if (s.find(x) != s.end()) { printf("%d %d %d\n", x, arr[i], arr[j]); found = true; } else s.insert(arr[j]); } } if (found == false) cout << " No Triplet Found" << endl; } // Driver code int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; }
linear
quadratic
// C++ program to find triplets in a given // array whose sum is zero #include <bits/stdc++.h> using namespace std; // function to print triplets with 0 sum void findTriplets(int arr[], int n) { bool found = false; // sort array elements sort(arr, arr + n); for (int i = 0; i < n - 1; i++) { // initialize left and right int l = i + 1; int r = n - 1; int x = arr[i]; while (l < r) { if (x + arr[l] + arr[r] == 0) { // print elements if it's sum is zero printf("%d %d %d\n", x, arr[l], arr[r]); l++; r--; found = true; // break; } // If sum of three elements is less // than zero then increment in left else if (x + arr[l] + arr[r] < 0) l++; // if sum is greater than zero then // decrement in right side else r--; } } if (found == false) cout << " No Triplet Found" << endl; } // Driven source int main() { int arr[] = { 0, -1, 2, -3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); findTriplets(arr, n); return 0; }
constant
quadratic
// C++ program to count triplets with given // product m #include <iostream> using namespace std; // Function to count such triplets int countTriplets(int arr[], int n, int m) { int count = 0; // Consider all triplets and count if // their product is equal to m for (int i = 0; i < n - 2; i++) for (int j = i + 1; j < n - 1; j++) for (int k = j + 1; k < n; k++) if (arr[i] * arr[j] * arr[k] == m) count++; return count; } // Drivers code int main() { int arr[] = { 1, 4, 6, 2, 3, 8 }; int n = sizeof(arr) / sizeof(arr[0]); int m = 24; cout << countTriplets(arr, n, m); return 0; }
constant
cubic
// C++ program to count triplets with given // product m #include <bits/stdc++.h> using namespace std; // Function to count such triplets int countTriplets(int arr[], int n, int m) { // Store all the elements in a set unordered_map<int, int> occ; for (int i = 0; i < n; i++) occ[arr[i]] = i; int count = 0; // Consider all pairs and check for a // third number so their product is equal to m for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { // Check if current pair divides m or not // If yes, then search for (m / arr[i]*arr[j]) if ((arr[i] * arr[j] <= m) && (arr[i] * arr[j] != 0) && (m % (arr[i] * arr[j]) == 0)) { int check = m / (arr[i] * arr[j]); auto it = occ.find(check); // Check if the third number is present // in the map and it is not equal to any // other two elements and also check if // this triplet is not counted already // using their indexes if (check != arr[i] && check != arr[j] && it != occ.end() && it->second > i && it->second > j) count++; } } } // Return number of triplets return count; } // Drivers code int main() { int arr[] = { 1, 4, 6, 2, 3, 8 }; int n = sizeof(arr) / sizeof(arr[0]); int m = 24; cout << countTriplets(arr, n, m); return 0; }
linear
quadratic
// C++ program to count of pairs with equal // elements in an array. #include<bits/stdc++.h> using namespace std; // Return the number of pairs with equal // values. int countPairs(int arr[], int n) { int ans = 0; // for each index i and j for (int i = 0; i < n; i++) for (int j = i+1; j < n; j++) // finding the index with same // value but different index. if (arr[i] == arr[j]) ans++; return ans; } // Driven Program int main() { int arr[] = { 1, 1, 2 }; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0; }
constant
quadratic
// C++ program to count of index pairs with // equal elements in an array. #include<bits/stdc++.h> using namespace std; // Return the number of pairs with equal // values. int countPairs(int arr[], int n) { unordered_map<int, int> mp; // Finding frequency of each number. for (int i = 0; i < n; i++) mp[arr[i]]++; // Calculating pairs of each value. int ans = 0; for (auto it=mp.begin(); it!=mp.end(); it++) { int count = it->second; ans += (count * (count - 1))/2; } return ans; } // Driven Program int main() { int arr[] = {1, 1, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << countPairs(arr, n) << endl; return 0; }
linear
linear
/* A C++ program to answer queries to check whether the substrings are palindrome or not efficiently */ #include <bits/stdc++.h> using namespace std; #define p 101 #define MOD 1000000007 // Structure to represent a query. A query consists // of (L, R) and we have to answer whether the substring // from index-L to R is a palindrome or not struct Query { int L, R; }; // A function to check if a string str is palindrome // in the range L to R bool isPalindrome(string str, int L, int R) { // Keep comparing characters while they are same while (R > L) if (str[L++] != str[R--]) return (false); return (true); } // A Function to find pow (base, exponent) % MOD // in log (exponent) time unsigned long long int modPow( unsigned long long int base, unsigned long long int exponent) { if (exponent == 0) return 1; if (exponent == 1) return base; unsigned long long int temp = modPow(base, exponent / 2); if (exponent % 2 == 0) return (temp % MOD * temp % MOD) % MOD; else return (((temp % MOD * temp % MOD) % MOD) * base % MOD) % MOD; } // A Function to calculate Modulo Multiplicative Inverse of 'n' unsigned long long int findMMI(unsigned long long int n) { return modPow(n, MOD - 2); } // A Function to calculate the prefix hash void computePrefixHash( string str, int n, unsigned long long int prefix[], unsigned long long int power[]) { prefix[0] = 0; prefix[1] = str[0]; for (int i = 2; i <= n; i++) prefix[i] = (prefix[i - 1] % MOD + (str[i - 1] % MOD * power[i - 1] % MOD) % MOD) % MOD; return; } // A Function to calculate the suffix hash // Suffix hash is nothing but the prefix hash of // the reversed string void computeSuffixHash( string str, int n, unsigned long long int suffix[], unsigned long long int power[]) { suffix[0] = 0; suffix[1] = str[n - 1]; for (int i = n - 2, j = 2; i >= 0 && j <= n; i--, j++) suffix[j] = (suffix[j - 1] % MOD + (str[i] % MOD * power[j - 1] % MOD) % MOD) % MOD; return; } // A Function to answer the Queries void queryResults(string str, Query q[], int m, int n, unsigned long long int prefix[], unsigned long long int suffix[], unsigned long long int power[]) { for (int i = 0; i <= m - 1; i++) { int L = q[i].L; int R = q[i].R; // Hash Value of Substring [L, R] unsigned long long hash_LR = ((prefix[R + 1] - prefix[L] + MOD) % MOD * findMMI(power[L]) % MOD) % MOD; // Reverse Hash Value of Substring [L, R] unsigned long long reverse_hash_LR = ((suffix[n - L] - suffix[n - R - 1] + MOD) % MOD * findMMI(power[n - R - 1]) % MOD) % MOD; // If both are equal then // the substring is a palindrome if (hash_LR == reverse_hash_LR) { if (isPalindrome(str, L, R) == true) printf("The Substring [%d %d] is a " "palindrome\n", L, R); else printf("The Substring [%d %d] is not a " "palindrome\n", L, R); } else printf("The Substring [%d %d] is not a " "palindrome\n", L, R); } return; } // A Dynamic Programming Based Approach to compute the // powers of 101 void computePowers(unsigned long long int power[], int n) { // 101^0 = 1 power[0] = 1; for (int i = 1; i <= n; i++) power[i] = (power[i - 1] % MOD * p % MOD) % MOD; return; } /* Driver program to test above function */ int main() { string str = "abaaabaaaba"; int n = str.length(); // A Table to store the powers of 101 unsigned long long int power[n + 1]; computePowers(power, n); // Arrays to hold prefix and suffix hash values unsigned long long int prefix[n + 1], suffix[n + 1]; // Compute Prefix Hash and Suffix Hash Arrays computePrefixHash(str, n, prefix, power); computeSuffixHash(str, n, suffix, power); Query q[] = { { 0, 10 }, { 5, 8 }, { 2, 5 }, { 5, 9 } }; int m = sizeof(q) / sizeof(q[0]); queryResults(str, q, m, n, prefix, suffix, power); return (0); }
linear
quadratic
// C++ program to finds out smallest range that includes // elements from each of the given sorted lists. #include <bits/stdc++.h> using namespace std; // array for storing the current index of list i int ptr[501]; // This function takes an k sorted lists in the form of // 2D array as an argument. It finds out smallest range // that includes elements from each of the k lists. void findSmallestRange(vector<vector<int> >& arr, int N, int K) { int i, minval, maxval, minrange, minel, maxel, flag, minind; // initializing to 0 index; for (i = 0; i <= K; i++) ptr[i] = 0; minrange = INT_MAX; while (1) { // for maintaining the index of list containing the // minimum element minind = -1; minval = INT_MAX; maxval = INT_MIN; flag = 0; // iterating over all the list for (i = 0; i < K; i++) { // if every element of list[i] is traversed then // break the loop if (ptr[i] == N) { flag = 1; break; } // find minimum value among all the list // elements pointing by the ptr[] array if (ptr[i] < N && arr[i][ptr[i]] < minval) { minind = i; // update the index of the list minval = arr[i][ptr[i]]; } // find maximum value among all the list // elements pointing by the ptr[] array if (ptr[i] < N && arr[i][ptr[i]] > maxval) { maxval = arr[i][ptr[i]]; } } // if any list exhaust we will not get any better // answer, so break the while loop if (flag) break; ptr[minind]++; // updating the minrange if ((maxval - minval) < minrange) { minel = minval; maxel = maxval; minrange = maxel - minel; } } printf("The smallest range is [%d, %d]\n", minel, maxel); } // Driver's code int main() { vector<vector<int> > arr = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int K = arr.size(); int N = arr[0].size(); // Function call findSmallestRange(arr, N, K); return 0; } // This code is contributed by Aditya Krishna Namdeo
linear
linear
// C++ program to finds out smallest range that includes // elements from each of the given sorted lists. #include <bits/stdc++.h> using namespace std; #define N 5 // A min heap node struct MinHeapNode { // The element to be stored int element; // index of the list from which the element is taken int i; // index of the next element to be picked from list int j; }; // Prototype of a utility function to swap two min heap // nodes void swap(MinHeapNode* x, MinHeapNode* y); // A class for Min Heap class MinHeap { // pointer to array of elements in heap MinHeapNode* harr; // size of min heap int heap_size; public: // Constructor: creates a min heap of given size MinHeap(MinHeapNode a[], int size); // to heapify a subtree with root at given index void MinHeapify(int); // to get index of left child of node at index i int left(int i) { return (2 * i + 1); } // to get index of right child of node at index i int right(int i) { return (2 * i + 2); } // to get the root MinHeapNode getMin() { return harr[0]; } // to replace root with new node x and heapify() new // root void replaceMin(MinHeapNode x) { harr[0] = x; MinHeapify(0); } }; // Constructor: Builds a heap from a // given array a[] of given size MinHeap::MinHeap(MinHeapNode a[], int size) { heap_size = size; harr = a; // store address of array int i = (heap_size - 1) / 2; while (i >= 0) { MinHeapify(i); i--; } } // A recursive method to heapify a subtree with root at // given index. This method assumes that the subtrees // are already heapified void MinHeap::MinHeapify(int i) { int l = left(i); int r = right(i); int smallest = i; if (l < heap_size && harr[l].element < harr[i].element) smallest = l; if (r < heap_size && harr[r].element < harr[smallest].element) smallest = r; if (smallest != i) { swap(harr[i], harr[smallest]); MinHeapify(smallest); } } // This function takes an K sorted lists in the form of // 2D array as an argument. It finds out smallest range // that includes elements from each of the k lists. void findSmallestRange(int arr[][N], int K) { // Create a min heap with k heap nodes. Every heap node // has first element of an list int range = INT_MAX; int min = INT_MAX, max = INT_MIN; int start, end; MinHeapNode* harr = new MinHeapNode[K]; for (int i = 0; i < K; i++) { // Store the first element harr[i].element = arr[i][0]; // index of list harr[i].i = i; // Index of next element to be stored // from list harr[i].j = 1; // store max element if (harr[i].element > max) max = harr[i].element; } // Create the heap MinHeap hp(harr, K); // Now one by one get the minimum element from min // heap and replace it with next element of its list while (1) { // Get the minimum element and store it in output MinHeapNode root = hp.getMin(); // update min min = hp.getMin().element; // update range if (range > max - min + 1) { range = max - min + 1; start = min; end = max; } // Find the next element that will replace current // root of heap. The next element belongs to same // list as the current root. if (root.j < N) { root.element = arr[root.i][root.j]; root.j += 1; // update max element if (root.element > max) max = root.element; } // break if we have reached end of any list else break; // Replace root with next element of list hp.replaceMin(root); } cout << "The smallest range is " << "[" << start << " " << end << "]" << endl; ; } // Driver's code int main() { int arr[][N] = { { 4, 7, 9, 12, 15 }, { 0, 8, 10, 14, 20 }, { 6, 12, 16, 30, 50 } }; int K = sizeof(arr) / sizeof(arr[0]); // Function call findSmallestRange(arr, K); return 0; }
linear
linear
// 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 for above implementation #include <bits/stdc++.h> using namespace std; // Function to count numbers to be added int countNum(int arr[], int n) { int count = 0; // Sort the array sort(arr, arr + n); // Check if elements are consecutive // or not. If not, update count for (int i = 0; i < n - 1; i++) if (arr[i] != arr[i+1] && arr[i] != arr[i + 1] - 1) count += arr[i + 1] - arr[i] - 1; return count; } // Drivers code int main() { int arr[] = { 3, 5, 8, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countNum(arr, n) << endl; return 0; }
constant
nlogn
// C++ program for above implementation #include <bits/stdc++.h> using namespace std; // Function to count numbers to be added int countNum(int arr[], int n) { unordered_set<int> s; int count = 0, maxm = INT_MIN, minm = INT_MAX; // Make a hash of elements // and store minimum and maximum element for (int i = 0; i < n; i++) { s.insert(arr[i]); if (arr[i] < minm) minm = arr[i]; if (arr[i] > maxm) maxm = arr[i]; } // Traverse all elements from minimum // to maximum and count if it is not // in the hash for (int i = minm; i <= maxm; i++) if (s.find(arr[i]) == s.end()) count++; return count; } // Drivers code int main() { int arr[] = { 3, 5, 8, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countNum(arr, n) << endl; return 0; }
constant
linear
// C++ program to calculate sum of lengths of subarrays // of distinct elements. #include<bits/stdc++.h> using namespace std; // Returns sum of lengths of all subarrays with distinct // elements. int sumoflength(int arr[], int n) { // For maintaining distinct elements. unordered_set<int> s; // Initialize ending point and result int j = 0, ans = 0; // Fix starting point for (int i=0; i<n; i++) { // Find ending point for current subarray with // distinct elements. while (j < n && s.find(arr[j]) == s.end()) { s.insert(arr[j]); j++; } // Calculating and adding all possible length // subarrays in arr[i..j] ans += ((j - i) * (j - i + 1))/2; // Remove arr[i] as we pick new starting point // from next s.erase(arr[i]); } return ans; } // Driven Code int main() { int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); cout << sumoflength(arr, n) << endl; return 0; }
linear
linear