text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Count Triplets such that one of the numbers can be written as sum of the other two | C ++ program to count Triplets such that at least one of the numbers can be written as sum of the other two ; Function to count the number of ways to choose the triples ; compute the max value in the array and create frequency array of size max_val + 1. We can also use HashMap to store frequencies . We have used an array to keep remaining code simple . ; Case 1 : 0 , 0 , 0 ; Case 2 : 0 , x , x ; Case 3 : x , x , 2 * x ; Case 4 : x , y , x + y iterate through all pairs ( x , y ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int arr [ ] , int n ) { int max_val = 0 ; for ( int i = 0 ; i < n ; i ++ ) max_val = max ( max_val , arr [ i ] ) ; int freq [ max_val + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) freq [ arr [ i ] ] ++ ; ans += freq [ 0 ] * ( freq [ 0 ] - 1 ) * ( freq [ 0 ] - 2 ) / 6 ; for ( int i = 1 ; i <= max_val ; i ++ ) ans += freq [ 0 ] * freq [ i ] * ( freq [ i ] - 1 ) / 2 ; for ( int i = 1 ; 2 * i <= max_val ; i ++ ) ans += freq [ i ] * ( freq [ i ] - 1 ) / 2 * freq [ 2 * i ] ; for ( int i = 1 ; i <= max_val ; i ++ ) { for ( int j = i + 1 ; i + j <= max_val ; j ++ ) ans += freq [ i ] * freq [ j ] * freq [ i + j ] ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << ( countWays ( arr , n ) ) ; return 0 ; }
Count pairs from two arrays having sum equal to K | C ++ implementation of above approach . ; Function to return the count of pairs having sum equal to K ; Initialize pairs to 0 ; create map of elements of array A1 ; count total pairs ; Every element can be part of at most one pair . ; return total pairs ; Driver program ; function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int A1 [ ] , int A2 [ ] , int n1 , int n2 , int K ) { int res = 0 ; unordered_map < int , int > m ; for ( int i = 0 ; i < n1 ; ++ i ) m [ A1 [ i ] ] ++ ; for ( int i = 0 ; i < n2 ; ++ i ) { int temp = K - A2 [ i ] ; if ( m [ temp ] != 0 ) { res ++ ; m [ temp ] -- ; } } return res ; } int main ( ) { int A1 [ ] = { 1 , 1 , 3 , 4 , 5 , 6 , 6 } ; int A2 [ ] = { 1 , 4 , 4 , 5 , 7 } , K = 10 ; int n1 = sizeof ( A1 ) / sizeof ( A1 [ 0 ] ) ; int n2 = sizeof ( A2 ) / sizeof ( A2 [ 0 ] ) ; cout << countPairs ( A1 , A2 , n1 , n2 , K ) ; return 0 ; }
Count pairs in an array such that frequency of one is at least value of other | C ++ program to find number of ordered pairs ; Function to find count of Ordered pairs ; Initialize pairs to 0 ; Store frequencies ; Count total Ordered_pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOrderedPairs ( int A [ ] , int n ) { int orderedPairs = 0 ; unordered_map < int , int > m ; for ( int i = 0 ; i < n ; ++ i ) m [ A [ i ] ] ++ ; for ( auto entry : m ) { int X = entry . first ; int Y = entry . second ; for ( int j = 1 ; j <= Y ; j ++ ) { if ( m [ j ] >= X ) orderedPairs ++ ; } } return orderedPairs ; } int main ( ) { int A [ ] = { 1 , 1 , 2 , 2 , 3 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << countOrderedPairs ( A , n ) ; return 0 ; }
Longest subarray with elements having equal modulo K | C ++ implementation of above approach ; function to find longest sub - array whose elements gives same remainder when divided with K ; Iterate in the array ; check if array element greater then X or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestSubarray ( int arr [ ] , int n , int k ) { int count = 1 ; int max_length = 1 ; int prev_mod = arr [ 0 ] % k ; for ( int i = 1 ; i < n ; i ++ ) { int curr_mod = arr [ i ] % k ; if ( curr_mod == prev_mod ) { count ++ ; } else { max_length = max ( max_length , count ) ; count = 1 ; prev_mod = curr_mod ; } } return max ( max_length , count ) ; } int main ( ) { int arr [ ] = { 4 , 9 , 7 , 18 , 29 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 11 ; cout << LongestSubarray ( arr , n , k ) ; return 0 ; }
Search in a sorted 2D matrix ( Stored in row major order ) | C ++ program to find whether a given element is present in the given 2 - D matrix ; Basic binary search to find an element in a 1 - D array ; if element found return true ; if middle less than K then skip the left part of the array else skip the right part ; if not found return false ; Function to search an element in a matrix based on Divide and conquer approach ; if the element lies in the range of this row then call 1 - D binary search on this row ; if the element is less then the starting element of that row then search in upper rows else search in the lower rows ; if not found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 3 NEW_LINE #define N 4 NEW_LINE bool binarySearch1D ( int arr [ ] , int K ) { int low = 0 ; int high = N - 1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( arr [ mid ] == K ) return true ; if ( arr [ mid ] < K ) low = mid + 1 ; else high = mid - 1 ; } return false ; } bool searchMatrix ( int matrix [ M ] [ N ] , int K ) { int low = 0 ; int high = M - 1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( K >= matrix [ mid ] [ 0 ] && K <= matrix [ mid ] [ N - 1 ] ) return binarySearch1D ( matrix [ mid ] , K ) ; if ( K < matrix [ mid ] [ 0 ] ) high = mid - 1 ; else low = mid + 1 ; } return false ; } int main ( ) { int matrix [ M ] [ N ] = { { 1 , 3 , 5 , 7 } , { 10 , 11 , 16 , 20 } , { 23 , 30 , 34 , 50 } } ; int K = 3 ; if ( searchMatrix ( matrix , K ) ) cout << " Found " << endl ; else cout << " Not ▁ found " << endl ; }
Program to find Nth term divisible by a or b | C ++ program to find nth term divisible by a or b ; Function to return gcd of a and b ; Function to calculate how many numbers from 1 to num are divisible by a or b ; calculate number of terms divisible by a and by b then , remove the terms which is are divisible by both a and b ; Binary search to find the nth term divisible by a or b ; set low to 1 and high to max ( a , b ) * n , here we have taken high as 10 ^ 18 ; if the current term is less than n then we need to increase low to mid + 1 ; if current term is greater than equal to n then high = mid ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int divTermCount ( int a , int b , int lcm , int num ) { return num / a + num / b - num / lcm ; } int findNthTerm ( int a , int b , int n ) { int low = 1 , high = INT_MAX , mid ; int lcm = ( a * b ) / gcd ( a , b ) ; while ( low < high ) { mid = low + ( high - low ) / 2 ; if ( divTermCount ( a , b , lcm , mid ) < n ) low = mid + 1 ; else high = mid ; } return low ; } int main ( ) { int a = 2 , b = 5 , n = 10 ; cout << findNthTerm ( a , b , n ) << endl ; return 0 ; }
Replace all occurrences of pi with 3.14 in a given string | C ++ program to replace all pi in a given string with 3.14 ; Function to replace all occurrences of pi in a given with 3.14 ; Iterate through second last element of the string ; If current and current + 1 alphabets form the word ' pi ' append 3.14 to output ; Append the current letter ; Return the output string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string replacePi ( string input ) { string output ; int size = input . length ( ) ; for ( int i = 0 ; i < size ; ++ i ) { if ( i + 1 < size and input [ i ] == ' p ' and input [ i + 1 ] == ' i ' ) { output += "3.14" ; i ++ ; } else { output += input [ i ] ; } } return output ; } int main ( ) { string input = "2 ▁ * ▁ pi ▁ + ▁ 3 ▁ * ▁ pi ▁ = ▁ 5 ▁ * ▁ pi " ; cout << replacePi ( input ) ; return 0 ; }
Number of elements that can be seen from right side | CPP program to find number of elements that can be seen from right side . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfElements ( int height [ ] , int n ) { int max_so_far = 0 ; int coun = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( height [ i ] > max_so_far ) { max_so_far = height [ i ] ; coun ++ ; } } return coun ; } int main ( ) { int n = 6 ; int height [ ] = { 4 , 8 , 2 , 0 , 0 , 5 } ; cout << numberOfElements ( height , n ) ; return 0 ; }
Check if a pair with given product exists in Linked list | CPP code to find the pair with given product ; Link list node ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; Function to check if pair with the given product exists in the list Takes head pointer of the linked list and product ; Check if pair exits ; Driver program to test above function ; Start with the empty list ; Use push ( ) to construct linked list ; function to print the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } bool check_pair_product ( struct Node * head , int prod ) { unordered_set < int > s ; struct Node * p = head ; while ( p != NULL ) { int curr = p -> data ; if ( ( prod % curr == 0 ) && ( s . find ( prod / curr ) != s . end ( ) ) ) { cout << curr << " ▁ " << prod / curr ; return true ; } s . insert ( p -> data ) ; p = p -> next ; } return false ; } int main ( ) { struct Node * head = NULL ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; push ( & head , 12 ) ; push ( & head , 1 ) ; push ( & head , 18 ) ; push ( & head , 47 ) ; push ( & head , 16 ) ; push ( & head , 12 ) ; push ( & head , 14 ) ; bool res = check_pair_product ( head , 24 ) ; if ( res == false ) cout << " NO ▁ PAIR ▁ EXIST " ; return 0 ; }
Largest element in the array that is repeated exactly k times | C ++ implementation of the approach ; Function that finds the largest element which is repeated ' k ' times ; sort the array ; if the value of ' k ' is 1 and the largest appears only once in the array ; counter to count the repeated elements ; check if the element at index ' i ' is equal to the element at index ' i + 1' then increase the count ; else set the count to 1 to start counting the frequency of the new number ; if the count is equal to k and the previous element is not equal to this element ; if there is no such element ; Driver code ; find the largest element that is repeated K times
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; if ( k == 1 && arr [ n - 2 ] != arr [ n - 1 ] ) { cout << arr [ n - 1 ] << endl ; return ; } int count = 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] == arr [ i + 1 ] ) count ++ ; else count = 1 ; if ( count == k && ( i == 0 || ( arr [ i - 1 ] != arr [ i ] ) ) ) { cout << arr [ i ] << endl ; return ; } } cout << " No ▁ such ▁ element " << endl ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 , 3 , 4 , 5 , 5 , 6 , 6 , 6 } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( int ) ; solve ( arr , n , k ) ; return 0 ; }
Largest element in the array that is repeated exactly k times | C ++ implementation of above approach ; Function that finds the largest element that occurs exactly ' k ' times ; store the frequency of each element ; to store the maximum element ; if current element has frequency ' k ' and current maximum hasn 't been set ; set the current maximum ; if current element has frequency ' k ' and it is greater than the current maximum ; change the current maximum ; if there is no element with frequency ' k ' ; print the largest element with frequency ' k ' ; Driver code ; find the largest element that is repeated K times
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int arr [ ] , int n , int k ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) { m [ arr [ i ] ] ++ ; } int max = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { if ( m [ arr [ i ] ] == k && max == INT_MIN ) { max = arr [ i ] ; } else if ( m [ arr [ i ] ] == k && max < arr [ i ] ) { max = arr [ i ] ; } } if ( max == INT_MIN ) cout << " No ▁ such ▁ element " << endl ; else cout << max << endl ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 , 3 , 4 , 5 , 5 , 6 , 6 , 6 } ; int k = 4 ; int n = sizeof ( arr ) / sizeof ( int ) ; solve ( arr , n , k ) ; return 0 ; }
Sum and Product of minimum and maximum element of an Array | CPP program to find the sum and product of minimum and maximum element in an array ; Function to find minimum element ; Function to find maximum element ; Function to get Sum ; Function to get product ; Driver Code ; Sum of min and max element ; Product of min and max element
#include <iostream> NEW_LINE using namespace std ; int getMin ( int arr [ ] , int n ) { int res = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) res = min ( res , arr [ i ] ) ; return res ; } int getMax ( int arr [ ] , int n ) { int res = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) res = max ( res , arr [ i ] ) ; return res ; } int findSum ( int arr [ ] , int n ) { int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; return min + max ; } int findProduct ( int arr [ ] , int n ) { int min = getMin ( arr , n ) ; int max = getMax ( arr , n ) ; return min * max ; } int main ( ) { int arr [ ] = { 12 , 1234 , 45 , 67 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Sum ▁ = ▁ " << findSum ( arr , n ) << endl ; cout << " Product ▁ = ▁ " << findProduct ( arr , n ) ; return 0 ; }
Count the number of pop operations on stack to get each element of the array | C ++ program to implement above approach ; Function to find the count ; Hashmap to store all the elements which are popped once . ; Check if the number is present in the hashmap Or in other words been popped out from the stack before . ; Keep popping the elements while top is not equal to num ; Pop the top ie . equal to num ; Print the number of elements popped . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countEle ( stack < int > & s , int a [ ] , int N ) { unordered_map < int , bool > mp ; for ( int i = 0 ; i < N ; ++ i ) { int num = a [ i ] ; if ( mp . find ( num ) != mp . end ( ) ) cout << "0 ▁ " ; else { int cnt = 0 ; while ( s . top ( ) != num ) { mp [ s . top ( ) ] = true ; s . pop ( ) ; cnt ++ ; } s . pop ( ) ; cnt ++ ; cout << cnt << " ▁ " ; } } } int main ( ) { int N = 5 ; stack < int > s ; s . push ( 1 ) ; s . push ( 2 ) ; s . push ( 3 ) ; s . push ( 4 ) ; s . push ( 6 ) ; int a [ ] = { 6 , 3 , 4 , 1 , 2 } ; countEle ( s , a , N ) ; return 0 ; }
Queries to check whether a given digit is present in the given Range | CPP program to answer Queries to check whether a given digit is present in the given range ; Segment Tree with set at each node ; Funtiom to build the segment tree ; Left child node ; Right child node ; Merging child nodes to get parent node . Since set is used , it will remove redundant digits . ; Function to query a range ; Complete Overlapp condition return true if digit is present . else false . ; No Overlapp condition Return false ; If digit is found in any child return true , else False ; Driver Code ; Build the tree ; Query 1 ; Query 2
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 6 NEW_LINE set < int > Tree [ 6 * N ] ; void buildTree ( int * arr , int idx , int s , int e ) { if ( s == e ) { Tree [ idx ] . insert ( arr [ s ] ) ; return ; } int mid = ( s + e ) >> 1 ; buildTree ( arr , 2 * idx , s , mid ) ; buildTree ( arr , 2 * idx + 1 , mid + 1 , e ) ; for ( auto it : Tree [ 2 * idx ] ) { Tree [ idx ] . insert ( it ) ; } for ( auto it : Tree [ 2 * idx + 1 ] ) { Tree [ idx ] . insert ( it ) ; } } bool query ( int idx , int s , int e , int qs , int qe , int x ) { if ( qs <= s && e <= qe ) { if ( Tree [ idx ] . count ( x ) != 0 ) { return true ; } else return false ; } if ( qe < s e < qs ) { return false ; } int mid = ( s + e ) >> 1 ; bool LeftAns = query ( 2 * idx , s , mid , qs , qe , x ) ; bool RightAns = query ( 2 * idx + 1 , mid + 1 , e , qs , qe , x ) ; return LeftAns or RightAns ; } int main ( ) { int arr [ ] = { 1 , 3 , 3 , 9 , 8 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; buildTree ( arr , 1 , 0 , n - 1 ) ; int l , r , x ; l = 0 , r = 3 , x = 2 ; if ( query ( 1 , 0 , n - 1 , l , r , x ) ) cout << " YES " << ' ' ; else cout << " NO " << ' ' ; l = 2 , r = 5 , x = 3 ; if ( query ( 1 , 0 , n - 1 , l , r , x ) ) cout << " YES " << ' ' ; else cout << " NO " << ' ' ; return 0 ; }
Count characters with same neighbors | C ++ implementation of above approach ; Function to count the characters with same adjacent characters ; if length is less than 3 then return length as there will be only two characters ; Traverse the string ; Increment the count if the previous and next character is same ; Return count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countChar ( string str ) { int n = str . length ( ) ; if ( n <= 2 ) return n ; int count = 2 ; for ( int i = 1 ; i < n - 1 ; i ++ ) if ( str [ i - 1 ] == str [ i + 1 ] ) count ++ ; return count ; } int main ( ) { string str = " egeeksk " ; cout << countChar ( str ) ; return 0 ; }
Length of largest sub | C ++ implementation of above approach ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to find the length of longest subarray having count of primes more than count of non - primes ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider - 1 as non primes and 1 as primes ; when subarray starts form index '0' ; make an entry for ' sum ' if it is not present in ' um ' ; check if ' sum - 1' is present in ' um ' or not ; update maxLength ; required maximum length ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 1000000 + 5 ] ; void findPrime ( ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= 1000000 ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= 1000000 ; i += p ) prime [ i ] = false ; } } } int lenOfLongSubarr ( int arr [ ] , int n ) { unordered_map < int , int > um ; int sum = 0 , maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += prime [ arr [ i ] ] == 0 ? -1 : 1 ; if ( sum == 1 ) maxLen = i + 1 ; else if ( um . find ( sum ) == um . end ( ) ) um [ sum ] = i ; if ( um . find ( sum - 1 ) != um . end ( ) ) { if ( maxLen < ( i - um [ sum - 1 ] ) ) maxLen = i - um [ sum - 1 ] ; } } return maxLen ; } int main ( ) { findPrime ( ) ; int arr [ ] = { 1 , 9 , 3 , 4 , 5 , 6 , 7 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << lenOfLongSubarr ( arr , n ) << endl ; return 0 ; }
First strictly smaller element in a sorted array in Java | C ++ program to find first element that is strictly smaller than given target . ; Minimum size of the array should be 1 ; If target lies beyond the max element , than the index of strictly smaller value than target should be ( end - 1 ) ; Move to the left side if the target is smaller ; Move right side ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int next ( int arr [ ] , int target , int end ) { if ( end == 0 ) return -1 ; if ( target > arr [ end - 1 ] ) return end - 1 ; int start = 0 ; int ans = -1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( arr [ mid ] >= target ) { end = mid - 1 ; } else { ans = mid ; start = mid + 1 ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 5 , 8 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( next ( arr , 5 , n ) ) ; return 0 ; }
First strictly greater element in a sorted array in Java | C ++ program to find first element that is strictly greater than given target . ; Move to right side if target is greater . ; Move left side . ; Driver code
#include <iostream> NEW_LINE using namespace std ; int next ( int arr [ ] , int target , int end ) { int start = 0 ; int ans = -1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( arr [ mid ] <= target ) start = mid + 1 ; else { ans = mid ; end = mid - 1 ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 5 , 8 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << next ( arr , 8 , n ) ; return 0 ; }
Josephus Problem | ( Iterative Solution ) | Iterative solution for Josephus Problem ; Function for finding the winning child . ; For finding out the removed chairs in each iteration ; Driver function to find the winning child
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int find ( long long int n , long long int k ) { long long int sum = 0 , i ; for ( i = 2 ; i <= n ; i ++ ) sum = ( sum + k ) % i ; return sum + 1 ; } int main ( ) { int n = 14 , k = 2 ; cout << find ( n , k ) ; return 0 ; }
Reallocation of elements based on Locality of Reference | C ++ program to implement search for an item that is searched again and again . ; A function to perform sequential search . ; Linearly search the element ; If not found ; Shift elements before one position ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool search ( int arr [ ] , int n , int x ) { int res = -1 ; for ( int i = 0 ; i < n ; i ++ ) if ( x == arr [ i ] ) res = i ; if ( res == -1 ) return false ; int temp = arr [ res ] ; for ( int i = res ; i > 0 ; i -- ) arr [ i ] = arr [ i - 1 ] ; arr [ 0 ] = temp ; return true ; } int main ( ) { int arr [ ] = { 12 , 25 , 36 , 85 , 98 , 75 , 89 , 15 , 63 , 66 , 64 , 74 , 27 , 83 , 97 } ; int q [ ] = { 63 , 63 , 86 , 63 , 78 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; for ( int i = 0 ; i < m ; i ++ ) search ( arr , n , q [ i ] ) ? cout << " Yes ▁ " : cout << " No ▁ " ; return 0 ; }
Probability of a key K present in array | C ++ code to find the probability of search key K present in array ; Function to find the probability ; find probability ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float kPresentProbability ( int a [ ] , int n , int k ) { float count = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( a [ i ] == k ) count ++ ; return count / n ; } int main ( ) { int A [ ] = { 4 , 7 , 2 , 0 , 8 , 7 , 5 } ; int K = 3 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << kPresentProbability ( A , N , K ) ; return 0 ; }
Largest subarray having sum greater than k | CPP program to find largest subarray having sum greater than k . ; Comparison function used to sort preSum vector . ; Function to find index in preSum vector upto which all prefix sum values are less than or equal to val . ; Starting and ending index of search space . ; To store required index value . ; If middle value is less than or equal to val then index can lie in mid + 1. . n else it lies in 0. . mid - 1. ; Function to find largest subarray having sum greater than or equal to k . ; Length of largest subarray . ; Vector to store pair of prefix sum and corresponding ending index value . ; To store current value of prefix sum . ; To store minimum index value in range 0. . i of preSum vector . ; Insert values in preSum vector . ; Update minInd array . ; If sum is greater than k , then answer is i + 1. ; If the sum is less than or equal to k , then find if there is a prefix array having sum that needs to be added to the current sum to make its value greater than k . If yes , then compare the length of updated subarray with maximum length found so far . ; Driver code .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool compare ( const pair < int , int > & a , const pair < int , int > & b ) { if ( a . first == b . first ) return a . second < b . second ; return a . first < b . first ; } int findInd ( vector < pair < int , int > > & preSum , int n , int val ) { int l = 0 ; int h = n - 1 ; int mid ; int ans = -1 ; while ( l <= h ) { mid = ( l + h ) / 2 ; if ( preSum [ mid ] . first <= val ) { ans = mid ; l = mid + 1 ; } else h = mid - 1 ; } return ans ; } int largestSub ( int arr [ ] , int n , int k ) { int i ; int maxlen = 0 ; vector < pair < int , int > > preSum ; int sum = 0 ; int minInd [ n ] ; for ( i = 0 ; i < n ; i ++ ) { sum = sum + arr [ i ] ; preSum . push_back ( { sum , i } ) ; } sort ( preSum . begin ( ) , preSum . end ( ) , compare ) ; minInd [ 0 ] = preSum [ 0 ] . second ; for ( i = 1 ; i < n ; i ++ ) { minInd [ i ] = min ( minInd [ i - 1 ] , preSum [ i ] . second ) ; } sum = 0 ; for ( i = 0 ; i < n ; i ++ ) { sum = sum + arr [ i ] ; if ( sum > k ) maxlen = i + 1 ; else { int ind = findInd ( preSum , n , sum - k - 1 ) ; if ( ind != -1 && minInd [ ind ] < i ) maxlen = max ( maxlen , i - minInd [ ind ] ) ; } } return maxlen ; } int main ( ) { int arr [ ] = { -2 , 1 , 6 , -3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 5 ; cout << largestSub ( arr , n , k ) ; return 0 ; }
Find the slope of the given number | C ++ implementation to find slope of a number ; function to find slope of a number ; to store slope of the given number ' num ' ; loop from the 2 nd digit up to the 2 nd last digit of the given number ' num ' ; if the digit is a maxima ; if the digit is a minima ; required slope ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int slopeOfNum ( string num , int n ) { int slope = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( num [ i ] > num [ i - 1 ] && num [ i ] > num [ i + 1 ] ) slope ++ ; else if ( num [ i ] < num [ i - 1 ] && num [ i ] < num [ i + 1 ] ) slope ++ ; } return slope ; } int main ( ) { string num = "1213321" ; int n = num . size ( ) ; cout << " Slope ▁ = ▁ " << slopeOfNum ( num , n ) ; return 0 ; }
Sudo Placement | Beautiful Pairs | C ++ code for finding required pairs ; The function to check if beautiful pair exists ; Set for hashing ; Traversing the first array ; Traversing the second array to check for every j corresponding to single i ; x + y = z = > x = y - z ; if such x exists then we return true ; hash to make use of it next time ; no pair exists ; Driver Code ; If pair exists then 1 else 0 2 nd argument as size of first array fourth argument as sizeof 2 nd array
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool pairExists ( int arr1 [ ] , int m , int arr2 [ ] , int n ) { unordered_set < int > s ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( s . find ( arr2 [ j ] - arr1 [ i ] ) != s . end ( ) ) return true ; } s . insert ( arr1 [ i ] ) ; } return false ; } int main ( ) { int arr1 [ ] = { 1 , 5 , 10 , 8 } ; int arr2 [ ] = { 2 , 20 , 13 } ; if ( pairExists ( arr1 , 4 , arr2 , 3 ) ) cout << 1 << endl ; else cout << 0 << endl ; return 0 ; }
Sudo Placement | Placement Tour | CPP Program to find the optimal number of elements such that the cumulative value should be less than given number ; This function returns true if the value cumulative according to received integer K is less than budget B , otherwise returns false ; Initialize a temporary array which stores the cumulative value of the original array ; Sort the array to find the smallest K values ; Check if the value is less than budget ; This function prints the optimal number of elements and respective cumulative value which is less than the given number ; Initialize answer as zero as optimal value may not exists ; If the current Mid Value is an optimal value , then try to maximize it ; Call Again to set the corresponding cumulative value for the optimal ans ; Driver Code ; Budget
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBeOptimalValue ( int K , int arr [ ] , int N , int B , int & value ) { int tmp [ N ] ; for ( int i = 0 ; i < N ; i ++ ) tmp [ i ] = ( arr [ i ] + K * ( i + 1 ) ) ; sort ( tmp , tmp + N ) ; value = 0 ; for ( int i = 0 ; i < K ; i ++ ) value += tmp [ i ] ; return value <= B ; } void findNoOfElementsandValue ( int arr [ ] , int N , int B ) { int ans = 0 ; int cumulativeValue = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( canBeOptimalValue ( mid , arr , N , B , cumulativeValue ) ) { ans = mid ; start = mid + 1 ; } else end = mid - 1 ; } canBeOptimalValue ( ans , arr , N , B , cumulativeValue ) ; cout << ans << " ▁ " << cumulativeValue << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 6 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int B = 90 ; findNoOfElementsandValue ( arr , N , B ) ; return 0 ; }
Previous greater element | C ++ program previous greater element A naive solution to print previous greater element for every element in an array . ; Previous greater for first element never exists , so we print - 1. ; Let us process remaining elements . ; Find first element on left side that is greater than arr [ i ] . ; If all elements on left are smaller . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void prevGreater ( int arr [ ] , int n ) { cout << " - 1 , ▁ " ; for ( int i = 1 ; i < n ; i ++ ) { int j ; for ( j = i - 1 ; j >= 0 ; j -- ) { if ( arr [ i ] < arr [ j ] ) { cout << arr [ j ] << " , ▁ " ; break ; } } if ( j == -1 ) cout << " - 1 , ▁ " ; } } int main ( ) { int arr [ ] = { 10 , 4 , 2 , 20 , 40 , 12 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; prevGreater ( arr , n ) ; return 0 ; }
Previous greater element | C ++ program previous greater element An efficient solution to print previous greater element for every element in an array . ; Create a stack and push index of first element to it ; Previous greater for first element is always - 1. ; Traverse remaining elements ; Pop elements from stack while stack is not empty and top of stack is smaller than arr [ i ] . We always have elements in decreasing order in a stack . ; If stack becomes empty , then no element is greater on left side . Else top of stack is previous greater . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void prevGreater ( int arr [ ] , int n ) { stack < int > s ; s . push ( arr [ 0 ] ) ; cout << " - 1 , ▁ " ; for ( int i = 1 ; i < n ; i ++ ) { while ( s . empty ( ) == false && s . top ( ) < arr [ i ] ) s . pop ( ) ; s . empty ( ) ? cout << " - 1 , ▁ " : cout << s . top ( ) << " , ▁ " ; s . push ( arr [ i ] ) ; } } int main ( ) { int arr [ ] = { 10 , 4 , 2 , 20 , 40 , 12 , 30 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; prevGreater ( arr , n ) ; return 0 ; }
Duplicates in an array in O ( n ) time and by using O ( 1 ) extra space | Set | C ++ program to print all elements that appear more than once . ; Function to find repeating elements ; Flag variable used to represent whether repeating element is found or not . ; Check if current element is repeating or not . If it is repeating then value will be greater than or equal to n . ; Check if it is first repetition or not . If it is first repetition then value at index arr [ i ] is less than 2 * n . Print arr [ i ] if it is first repetition . ; Add n to index arr [ i ] to mark presence of arr [ i ] or to mark repetition of arr [ i ] . ; If flag variable is not set then no repeating element is found . So print - 1. ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printDuplicates ( int arr [ ] , int n ) { int i ; int fl = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ arr [ i ] % n ] >= n ) { if ( arr [ arr [ i ] % n ] < 2 * n ) { cout << arr [ i ] % n << " ▁ " ; fl = 1 ; } } arr [ arr [ i ] % n ] += n ; } if ( ! fl ) cout << " - 1" ; } int main ( ) { int arr [ ] = { 1 , 6 , 3 , 1 , 3 , 6 , 6 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printDuplicates ( arr , arr_size ) ; return 0 ; }
Find the smallest positive number missing from an unsorted array | Set 2 | CPP program to find the smallest positive missing number ; Function to find smallest positive missing number . ; to store current array element ; to store next array element in current traversal ; if value is negative or greater than array size , then it cannot be marked in array . So move to next element . ; traverse the array until we reach at an element which is already marked or which could not be marked . ; find first array index which is not marked which is also the smallest positive missing number . ; if all indices are marked , then smallest missing positive number is array_size + 1. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMissingNo ( int arr [ ] , int n ) { int val ; int nextval ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] <= 0 arr [ i ] > n ) continue ; val = arr [ i ] ; while ( arr [ val - 1 ] != val ) { nextval = arr [ val - 1 ] ; arr [ val - 1 ] = val ; val = nextval ; if ( val <= 0 val > n ) break ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != i + 1 ) { return i + 1 ; } } return n + 1 ; } int main ( ) { int arr [ ] = { 2 , 3 , 7 , 6 , 8 , -1 , -10 , 15 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int missing = findMissingNo ( arr , arr_size ) ; cout << " The ▁ smallest ▁ positive ▁ missing ▁ number ▁ is ▁ " << missing ; return 0 ; }
Print all triplets with given sum | A simple C ++ program to find three elements whose sum is equal to given sum ; Prints all triplets in arr [ ] with given sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findTriplets ( int arr [ ] , int n , int sum ) { 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 ] == sum ) { cout << arr [ i ] << " ▁ " << arr [ j ] << " ▁ " << arr [ k ] << endl ; } } } } } int main ( ) { int arr [ ] = { 0 , -1 , 2 , -3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findTriplets ( arr , n , -2 ) ; return 0 ; }
Print all triplets with given sum | C ++ program to find triplets in a given array whose sum is equal to given sum . ; function to print triplets with given sum ; Find all pairs with sum equals to " sum - arr [ i ] " ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findTriplets ( int arr [ ] , int n , int sum ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { unordered_set < int > s ; for ( int j = i + 1 ; j < n ; j ++ ) { int x = sum - ( arr [ i ] + arr [ j ] ) ; if ( s . find ( x ) != s . end ( ) ) printf ( " % d ▁ % d ▁ % d STRNEWLINE " , x , arr [ i ] , arr [ j ] ) ; else s . insert ( arr [ j ] ) ; } } } int main ( ) { int arr [ ] = { 0 , -1 , 2 , -3 , 1 } ; int sum = -2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findTriplets ( arr , n , sum ) ; return 0 ; }
Maximum product quadruple ( sub | A C ++ program to find a maximum product of a quadruple in array of integers ; Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; will contain max product ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProduct ( int arr [ ] , int n ) { if ( n < 4 ) return -1 ; int max_product = INT_MIN ; for ( int i = 0 ; i < n - 3 ; i ++ ) for ( int j = i + 1 ; j < n - 2 ; j ++ ) for ( int k = j + 1 ; k < n - 1 ; k ++ ) for ( int l = k + 1 ; l < n ; l ++ ) max_product = max ( max_product , arr [ i ] * arr [ j ] * arr [ k ] * arr [ l ] ) ; return max_product ; } int main ( ) { int arr [ ] = { 10 , 3 , 5 , 6 , 20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max = maxProduct ( arr , n ) ; if ( max == -1 ) cout << " No ▁ Quadruple ▁ Exists " ; else cout << " Maximum ▁ product ▁ is ▁ " << max ; return 0 ; }
Maximum product quadruple ( sub | A C ++ program to find a maximum product of a quadruple in array of integers ; Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; Sort the array in ascending order ; Return the maximum of x , y and z ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProduct ( int arr [ ] , int n ) { if ( n < 4 ) return -1 ; sort ( arr , arr + n ) ; int x = arr [ n - 1 ] * arr [ n - 2 ] * arr [ n - 3 ] * arr [ n - 4 ] ; int y = arr [ 0 ] * arr [ 1 ] * arr [ 2 ] * arr [ 3 ] ; int z = arr [ 0 ] * arr [ 1 ] * arr [ n - 1 ] * arr [ n - 2 ] ; return max ( x , max ( y , z ) ) ; } int main ( ) { int arr [ ] = { -10 , -3 , 5 , 6 , -20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int max = maxProduct ( arr , n ) ; if ( max == -1 ) cout << " No ▁ Quadruple ▁ Exists " ; else cout << " Maximum ▁ product ▁ is ▁ " << max ; return 0 ; }
Minimum value of " max ▁ + ▁ min " in a subarray | CPP program to find sum of maximum and minimum in any subarray of an array of positive numbers . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int n ) { if ( n < 2 ) return -1 ; int ans = arr [ 0 ] + arr [ 1 ] ; for ( int i = 1 ; i + 1 < n ; i ++ ) ans = min ( ans , ( arr [ i ] + arr [ i + 1 ] ) ) ; return ans ; } int main ( ) { int arr [ ] = { 1 , 12 , 2 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSum ( arr , n ) ; return 0 ; }
Stella Octangula Number | Program to check if a number is Stella Octangula Number ; Returns value of n * ( 2 * n * n - 1 ) ; Finds if a value of f ( n ) is equal to x where n is in interval [ low . . high ] ; Returns true if x isStella Octangula Number . Else returns false . ; Find ' high ' for binary search by repeated doubling ; If condition is satisfied for a power of 2. ; Call binary search ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int f ( int n ) { return n * ( 2 * n * n - 1 ) ; } bool binarySearch ( int low , int high , int x ) { while ( low <= high ) { long long mid = ( low + high ) / 2 ; if ( f ( mid ) < x ) low = mid + 1 ; else if ( f ( mid ) > x ) high = mid - 1 ; else return true ; } return false ; } bool isStellaOctangula ( int x ) { if ( x == 0 ) return true ; int i = 1 ; while ( f ( i ) < x ) i = i * 2 ; if ( f ( i ) == x ) return true ; return binarySearch ( i / 2 , i , x ) ; } int main ( ) { int n = 51 ; if ( isStellaOctangula ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Sort the given string using character search | C ++ implementation to sort the given string without using any sorting technique ; function to sort the given string without using any sorting technique ; to store the final sorted string ; for each character ' i ' ; if character ' i ' is present at a particular index then add character ' i ' to ' new _ str ' ; required final sorted string ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; string sortString ( string str , int n ) { string new_str = " " ; for ( int i = ' a ' ; i <= ' z ' ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( str [ j ] == i ) new_str += str [ j ] ; return new_str ; } int main ( ) { string str = " geeksforgeeks " ; int n = str . size ( ) ; cout << sortString ( str , n ) ; return 0 ; }
Sort the given string using character search | C ++ implementation to sort the given string without using any sorting technique ; A character array to store the no . of occurrences of each character between ' a ' to ' z ' ; to store the final sorted string ; To store each occurrence of character by relative indexing ; To traverse the character array and append it to new_str ; Driver program to test above
#include <iostream> NEW_LINE using namespace std ; string sortString ( string str , int n ) { int i ; char arr [ 26 ] = { 0 } ; string new_str = " " ; for ( i = 0 ; i < n ; i ++ ) ++ arr [ str [ i ] - ' a ' ] ; for ( i = 0 ; i < 26 ; i ++ ) while ( arr [ i ] -- ) new_str += i + ' a ' ; return new_str ; } int main ( ) { string str = " geeksforgeeks " ; int n = str . size ( ) ; cout << sortString ( str , n ) ; return 0 ; }
Maximum occurring character in a linked list | C ++ program to count the maximum occurring character in linked list ; Link list node ; Storing element 's frequencies in a hash table. ; calculating the first maximum element ; Push a node to linked list . Note that this function changes the head ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { char data ; struct Node * next ; } ; char maxChar ( struct Node * head ) { struct Node * p = head ; int hash [ 256 ] = { 0 } ; while ( p != NULL ) { hash [ p -> data ] ++ ; p = p -> next ; } p = head ; int max = -1 ; char res ; while ( p != NULL ) { if ( max < hash [ p -> data ] ) { res = p -> data ; max = hash [ p -> data ] ; } p = p -> next ; } return res ; } void push ( struct Node * * head_ref , char new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { struct Node * head = NULL ; char str [ ] = " skeegforskeeg " ; for ( int i = 0 ; str [ i ] != ' \0' ; i ++ ) push ( & head , str [ i ] ) ; cout << maxChar ( head ) ; return 0 ; }
Maximum sum of elements from each row in the matrix | CPP Program to find row - wise maximum element sum considering elements in increasing order . ; Function to perform given task ; Getting the maximum element from last row ; Comparing it with the elements of above rows ; Maximum of current row . ; If we could not an element smaller than prev_max . ; Driver code
#include <bits/stdc++.h> NEW_LINE #define N 3 NEW_LINE using namespace std ; int getGreatestSum ( int a [ ] [ N ] ) { int prev_max = 0 ; for ( int j = 0 ; j < N ; j ++ ) if ( prev_max < a [ N - 1 ] [ j ] ) prev_max = a [ N - 1 ] [ j ] ; int sum = prev_max ; for ( int i = N - 2 ; i >= 0 ; i -- ) { int curr_max = INT_MIN ; for ( int j = 0 ; j < N ; j ++ ) if ( prev_max > a [ i ] [ j ] && a [ i ] [ j ] > curr_max ) curr_max = a [ i ] [ j ] ; if ( curr_max == INT_MIN ) return -1 ; prev_max = curr_max ; sum += prev_max ; } return sum ; } int main ( ) { int a [ 3 ] [ 3 ] = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; cout << getGreatestSum ( a ) << endl ; int b [ 3 ] [ 3 ] = { { 4 , 5 , 6 } , { 4 , 5 , 6 } , { 4 , 5 , 6 } } ; cout << getGreatestSum ( b ) << endl ; return 0 ; }
Find the number of times every day occurs in a month | C ++ program to count occurrence of days in a month ; function to find occurrences ; stores days in a week ; Initialize all counts as 4. ; find index of the first day ; number of days whose occurrence will be 5 ; mark the occurrence to be 5 of n - 28 days ; print the days ; driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void occurrenceDays ( int n , string firstday ) { string days [ ] = { " Monday " , " Tuesday " , " Wednesday " , " Thursday " , " Friday " , " Saturday " , " Sunday " } ; int count [ 7 ] ; for ( int i = 0 ; i < 7 ; i ++ ) count [ i ] = 4 ; int pos ; for ( int i = 0 ; i < 7 ; i ++ ) { if ( firstday == days [ i ] ) { pos = i ; break ; } } int inc = n - 28 ; for ( int i = pos ; i < pos + inc ; i ++ ) { if ( i > 6 ) count [ i % 7 ] = 5 ; else count [ i ] = 5 ; } for ( int i = 0 ; i < 7 ; i ++ ) { cout << days [ i ] << " ▁ " << count [ i ] << endl ; } } int main ( ) { int n = 31 ; string firstday = " Tuesday " ; occurrenceDays ( n , firstday ) ; return 0 ; }
Value of k | CPP program to fin k - th element after append and insert middle operations ; int ans = n ; Middle element of the sequence ; length of the resulting sequence . ; Updating the middle element of next sequence ; Moving to the left side of the middle element . ; Moving to the right side of the middle element . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findElement ( int n , int k ) { int left = 1 ; int right = pow ( 2 , n ) - 1 ; while ( 1 ) { int mid = ( left + right ) / 2 ; if ( k == mid ) { cout << ans << endl ; break ; } ans -- ; if ( k < mid ) right = mid - 1 ; else left = mid + 1 ; } } int main ( ) { int n = 4 , k = 8 ; findElement ( n , k ) ; return 0 ; }
First common element in two linked lists | C ++ program to find first common element in two unsorted linked list ; Link list node ; A utility function to insert a node at the beginning of a linked list ; Returns the first repeating element in linked list ; Traverse through every node of first list ; If current node is present in second list ; If no common node ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int firstCommon ( struct Node * head1 , struct Node * head2 ) { for ( ; head1 != NULL ; head1 = head1 -> next ) for ( Node * p = head2 ; p != NULL ; p = p -> next ) if ( p -> data == head1 -> data ) return head1 -> data ; return 0 ; } int main ( ) { struct Node * head1 = NULL ; push ( & head1 , 20 ) ; push ( & head1 , 5 ) ; push ( & head1 , 15 ) ; push ( & head1 , 10 ) ; struct Node * head2 = NULL ; push ( & head2 , 10 ) ; push ( & head2 , 2 ) ; push ( & head2 , 15 ) ; push ( & head2 , 8 ) ; cout << firstCommon ( head1 , head2 ) ; return 0 ; }
Print pair with maximum AND value in an array | CPP Program to find pair with maximum AND value ; Utility function to check number of elements having set msb as of pattern ; Function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; Find the elements ; print the pair of elements ; inc count value after printing element ; return the result value ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int checkBit ( int pattern , int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( ( pattern & arr [ i ] ) == pattern ) count ++ ; return count ; } int maxAND ( int arr [ ] , int n ) { int res = 0 , count ; for ( int bit = 31 ; bit >= 0 ; bit -- ) { count = checkBit ( res | ( 1 << bit ) , arr , n ) ; if ( count >= 2 ) res |= ( 1 << bit ) ; } if ( res == 0 ) cout << " Not ▁ Possible STRNEWLINE " ; else { cout << " Pair ▁ = ▁ " ; count = 0 ; for ( int i = 0 ; i < n && count < 2 ; i ++ ) { if ( ( arr [ i ] & res ) == res ) { count ++ ; cout << arr [ i ] << " ▁ " ; } } } return res ; } int main ( ) { int arr [ ] = { 4 , 8 , 6 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum AND Value = " << maxAND ( arr , n ) ; return 0 ; }
Probability of choosing a random pair with maximum sum in an array | CPP program of choosing a random pair such that A [ i ] + A [ j ] is maximum . ; Function to get max first and second ; If current element is smaller than first , then update both first and second ; If arr [ i ] is in between first and second then update second ; cnt1 ++ ; frequency of first maximum ; cnt2 ++ ; frequency of second maximum ; Returns probability of choosing a pair with maximum sum . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMaxSumPairs ( int a [ ] , int n ) { int first = INT_MIN , second = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > first ) { second = first ; first = a [ i ] ; } else if ( a [ i ] > second && a [ i ] != first ) second = a [ i ] ; } int cnt1 = 0 , cnt2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == first ) if ( a [ i ] == second ) } if ( cnt1 == 1 ) return cnt2 ; if ( cnt1 > 1 ) return cnt1 * ( cnt1 - 1 ) / 2 ; } float findMaxSumProbability ( int a [ ] , int n ) { int total = n * ( n - 1 ) / 2 ; int max_sum_pairs = countMaxSumPairs ( a , n ) ; return ( float ) max_sum_pairs / ( float ) total ; } int main ( ) { int a [ ] = { 1 , 2 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << findMaxSumProbability ( a , n ) ; return 0 ; }
The painter 's partition problem | ; sum from 1 to i elements of arr
int sum [ n + 1 ] = { 0 } ; for ( int i = 1 ; i <= n ; i ++ ) sum [ i ] = sum [ i - 1 ] + arr [ i - 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) dp [ 1 ] [ i ] = sum [ i ] ; and using it to calculate the result as : best = min ( best , max ( dp [ i - 1 ] [ p ] , sum [ j ] - sum [ p ] ) ) ;
The painter 's partition problem |
for ( int i = k - 1 ; i <= n ; i ++ ) best = min ( best , max ( partition ( arr , i , k - 1 ) , sum ( arr , i , n - 1 ) ) ) ;
Find if given number is sum of first n natural numbers | C ++ program for above implementation ; Function to find no . of elements to be added from 1 to get n ; Start adding numbers from 1 ; If sum becomes equal to s return n ; Drivers code
#include <iostream> NEW_LINE using namespace std ; int findS ( int s ) { int sum = 0 ; for ( int n = 1 ; sum < s ; n ++ ) { sum += n ; if ( sum == s ) return n ; } return -1 ; } int main ( ) { int s = 15 ; int n = findS ( s ) ; n == -1 ? cout << " - 1" : cout << n ; return 0 ; }
Find if given number is sum of first n natural numbers | C ++ program of the above approach ; Function to check if the s is the sum of first N natural number ; Solution of Quadratic Equation ; Condition to check if the solution is a integer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE # define ll long long NEW_LINE using namespace std ; ll int isvalid ( ll int s ) { float k = ( -1 + sqrt ( 1 + 8 * s ) ) / 2 ; if ( ceil ( k ) == floor ( k ) ) return k ; else return -1 ; } int main ( ) { int s = 15 ; cout << isvalid ( s ) ; return 0 ; }
Save from Bishop in chessboard | CPP program to find total safe position to place your Bishop ; function to calc total safe position ; i , j denotes row and column of position of bishop ; calc distance in four direction ; calc total sum of distance + 1 for unsafe positions ; return total safe positions ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calcSafe ( int pos ) { int j = pos % 10 ; int i = pos / 10 ; int dis_11 = min ( abs ( 1 - i ) , abs ( 1 - j ) ) ; int dis_18 = min ( abs ( 1 - i ) , abs ( 8 - j ) ) ; int dis_81 = min ( abs ( 8 - i ) , abs ( 1 - j ) ) ; int dis_88 = min ( abs ( 8 - i ) , abs ( 8 - j ) ) ; int sum = dis_11 + dis_18 + dis_81 + dis_88 + 1 ; return ( 64 - sum ) ; } int main ( ) { int pos = 34 ; cout << " Safe ▁ Positions ▁ = ▁ " << calcSafe ( pos ) ; return 0 ; }
Counting cross lines in an array | c ++ program to count cross line in array ; Merges two subarrays of arr [ ] . First subarray is arr [ l . . m ] Second subarray is arr [ m + 1. . r ] ; create temp arrays ; Copy data to temp arrays L [ ] and R [ ] ; i = 0 ; Initial index of first subarray j = 0 ; Initial index of second subarray k = l ; Initial index of merged subarray ; == == == == == == == == == == == == == == == == == == == == == = MAIN PORTION OF CODE == == == == == == == == == == == == == == == == == == == == = add all line which is cross by current element ; Copy the remaining elements of L [ ] , if there are any ; Copy the remaining elements of R [ ] , if there are any ; l is for left index and r is right index of the sub - array of arr to be sorted ; Same as ( l + r ) / 2 , but avoids overflow for large l and h ; Sort first and second halves ; function return count of cross line in an array ; driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void merge ( int arr [ ] , int l , int m , int r , int * count_crossline ) { int i , j , k ; int n1 = m - l + 1 ; int n2 = r - m ; int L [ n1 ] , R [ n2 ] ; for ( i = 0 ; i < n1 ; i ++ ) L [ i ] = arr [ l + i ] ; for ( j = 0 ; j < n2 ; j ++ ) R [ j ] = arr [ m + 1 + j ] ; while ( i < n1 && j < n2 ) { if ( L [ i ] <= R [ j ] ) { arr [ k ] = L [ i ] ; i ++ ; } else { arr [ k ] = R [ j ] ; * count_crossline += ( n1 - i ) ; j ++ ; } k ++ ; } while ( i < n1 ) { arr [ k ] = L [ i ] ; i ++ ; k ++ ; } while ( j < n2 ) { arr [ k ] = R [ j ] ; j ++ ; k ++ ; } } void mergeSort ( int arr [ ] , int l , int r , int * count_crossline ) { if ( l < r ) { int m = l + ( r - l ) / 2 ; mergeSort ( arr , l , m , count_crossline ) ; mergeSort ( arr , m + 1 , r , count_crossline ) ; merge ( arr , l , m , r , count_crossline ) ; } } int countCrossLine ( int arr [ ] , int n ) { int count_crossline = 0 ; mergeSort ( arr , 0 , n - 1 , & count_crossline ) ; return count_crossline ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countCrossLine ( arr , n ) << endl ; return 0 ; }
Count number of elements between two given elements in array | Program to count number of elements between two given elements . ; Function to count number of elements occurs between the elements . ; Find num1 ; If num1 is not present or present at end ; Find num2 ; If num2 is not present ; return number of elements between the two elements . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getCount ( int arr [ ] , int n , int num1 , int num2 ) { int i = 0 ; for ( i = 0 ; i < n ; i ++ ) if ( arr [ i ] == num1 ) break ; if ( i >= n - 1 ) return 0 ; int j ; for ( j = n - 1 ; j >= i + 1 ; j -- ) if ( arr [ j ] == num2 ) break ; if ( j == i ) return 0 ; return ( j - i - 1 ) ; } int main ( ) { int arr [ ] = { 3 , 5 , 7 , 6 , 4 , 9 , 12 , 4 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int num1 = 5 , num2 = 4 ; cout << getCount ( arr , n , num1 , num2 ) ; return 0 ; }
Best meeting point in 2D binary array | C ++ program to find best meeting point in 2D array ; Find all members home 's position ; Sort positions so we can find most beneficial point ; middle position will always beneficial for all group members but it will be sorted which we have already done ; Now find total distance from best meeting point ( x , y ) using Manhattan Distance formula ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ROW 3 NEW_LINE #define COL 5 NEW_LINE int minTotalDistance ( int grid [ ] [ COL ] ) { if ( ROW == 0 COL == 0 ) return 0 ; vector < int > vertical ; vector < int > horizontal ; for ( int i = 0 ; i < ROW ; i ++ ) { for ( int j = 0 ; j < COL ; j ++ ) { if ( grid [ i ] [ j ] == 1 ) { vertical . push_back ( i ) ; horizontal . push_back ( j ) ; } } } sort ( vertical . begin ( ) , vertical . end ( ) ) ; sort ( horizontal . begin ( ) , horizontal . end ( ) ) ; int size = vertical . size ( ) / 2 ; int x = vertical [ size ] ; int y = horizontal [ size ] ; int distance = 0 ; for ( int i = 0 ; i < ROW ; i ++ ) for ( int j = 0 ; j < COL ; j ++ ) if ( grid [ i ] [ j ] == 1 ) distance += abs ( x - i ) + abs ( y - j ) ; return distance ; } int main ( ) { int grid [ ROW ] [ COL ] = { { 1 , 0 , 1 , 0 , 1 } , { 0 , 1 , 0 , 0 , 0 } , { 0 , 1 , 1 , 0 , 0 } } ; cout << minTotalDistance ( grid ) ; return 0 ; }
Count numbers with difference between number and its digit sum greater than specific value | C ++ program to count total numbers which have difference with sum of digits greater than specific value ; Utility method to get sum of digits of K ; loop until K is not zero ; method returns count of numbers smaller than N , satisfying difference condition ; binary search while loop ; if difference between number and its sum of digit is smaller than given difference then smallest number will be on left side ; if difference between number and its sum of digit is greater than or equal to given difference then smallest number will be on right side ; return the difference between ' smallest ▁ number ▁ ▁ found ' and ' N ' as result ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigit ( int K ) { int sod = 0 ; while ( K ) { sod += K % 10 ; K /= 10 ; } return sod ; } int totalNumbersWithSpecificDifference ( int N , int diff ) { int low = 1 , high = N ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( mid - sumOfDigit ( mid ) < diff ) low = mid + 1 ; else high = mid - 1 ; } return ( N - high ) ; } int main ( ) { int N = 13 ; int diff = 2 ; cout << totalNumbersWithSpecificDifference ( N , diff ) ; return 0 ; }
Randomized Binary Search Algorithm | C ++ program to implement iterative randomized algorithm . ; To generate random number between x and y ie . . [ x , y ] ; A iterative randomized binary search function . It returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; Here we have defined middle as random index between l and r ie . . [ l , r ] ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; if we reach here , then element was not present ; Driver code
#include <iostream> NEW_LINE #include <ctime> NEW_LINE using namespace std ; int getRandom ( int x , int y ) { srand ( time ( NULL ) ) ; return ( x + rand ( ) % ( y - x + 1 ) ) ; } int randomizedBinarySearch ( int arr [ ] , int l , int r , int x ) { while ( l <= r ) { int m = getRandom ( l , r ) ; if ( arr [ m ] == x ) return m ; if ( arr [ m ] < x ) l = m + 1 ; else r = m - 1 ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 10 ; int result = randomizedBinarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? printf ( " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ) : printf ( " Element ▁ is ▁ present ▁ at ▁ index ▁ % d " , result ) ; return 0 ; }
Number of buildings facing the sun | C ++ program to count buildings that can see sunlight . ; Returns count buildings that can see sunlight ; Initialuze result ( Note that first building always sees sunlight ) ; Start traversing element ; If curr_element is maximum or current element is equal , update maximum and increment count ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countBuildings ( int arr [ ] , int n ) { int count = 1 ; int curr_max = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] > curr_max arr [ i ] == curr_max ) { count ++ ; curr_max = arr [ i ] ; } } return count ; } int main ( ) { int arr [ ] = { 7 , 4 , 8 , 2 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countBuildings ( arr , n ) ; return 0 ; }
Find index of an extra element present in one sorted array | C ++ program to find an extra element present in arr1 [ ] ; Returns index of extra element in arr1 [ ] . n is size of arr2 [ ] . Size of arr1 [ ] is n - 1. ; Driver code ; Solve is passed both arrays
#include <iostream> NEW_LINE using namespace std ; int findExtra ( int arr1 [ ] , int arr2 [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( arr1 [ i ] != arr2 [ i ] ) return i ; return n ; } int main ( ) { int arr1 [ ] = { 2 , 4 , 6 , 8 , 10 , 12 , 13 } ; int arr2 [ ] = { 2 , 4 , 6 , 8 , 10 , 12 } ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << findExtra ( arr1 , arr2 , n ) ; return 0 ; }
Find index of an extra element present in one sorted array | C ++ program to find an extra element present in arr1 [ ] ; Returns index of extra element in arr1 [ ] . n is size of arr2 [ ] . Size of arr1 [ ] is n - 1. ; Initialize result ; left and right are end points denoting the current range . ; If middle element is same of both arrays , it means that extra element is after mid so we update left to mid + 1 ; If middle element is different of the arrays , it means that the index we are searching for is either mid , or before mid . Hence we update right to mid - 1. ; when right is greater than left our search is complete . ; Driver code ; Solve is passed both arrays
#include <iostream> NEW_LINE using namespace std ; int findExtra ( int arr1 [ ] , int arr2 [ ] , int n ) { int index = n ; int left = 0 , right = n - 1 ; while ( left <= right ) { int mid = ( left + right ) / 2 ; if ( arr2 [ mid ] == arr1 [ mid ] ) left = mid + 1 ; else { index = mid ; right = mid - 1 ; } } return index ; } int main ( ) { int arr1 [ ] = { 2 , 4 , 6 , 8 , 10 , 12 , 13 } ; int arr2 [ ] = { 2 , 4 , 6 , 8 , 10 , 12 } ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << findExtra ( arr1 , arr2 , n ) ; return 0 ; }
Make all array elements equal with minimum cost | C ++ program to find minimum cost to make all elements equal ; Utility method to compute cost , when all values of array are made equal to X ; Method to find minimum cost to make all elements equal ; setting limits for ternary search by smallest and largest element ; loop until difference between low and high become less than 3 , because after that mid1 and mid2 will start repeating ; mid1 and mid2 are representative array equal values of search space ; if mid2 point gives more total cost , skip third part ; if mid1 point gives more total cost , skip first part ; computeCost gets optimum cost by sending average of low and high as X ; Driver code to test above method
#include <bits/stdc++.h> NEW_LINE using namespace std ; int computeCost ( int arr [ ] , int N , int X ) { int cost = 0 ; for ( int i = 0 ; i < N ; i ++ ) cost += abs ( arr [ i ] - X ) ; return cost ; } int minCostToMakeElementEqual ( int arr [ ] , int N ) { int low , high ; low = high = arr [ 0 ] ; for ( int i = 0 ; i < N ; i ++ ) { if ( low > arr [ i ] ) low = arr [ i ] ; if ( high < arr [ i ] ) high = arr [ i ] ; } while ( ( high - low ) > 2 ) { int mid1 = low + ( high - low ) / 3 ; int mid2 = high - ( high - low ) / 3 ; int cost1 = computeCost ( arr , N , mid1 ) ; int cost2 = computeCost ( arr , N , mid2 ) ; if ( cost1 < cost2 ) high = mid2 ; else low = mid1 ; } return computeCost ( arr , N , ( low + high ) / 2 ) ; } int main ( ) { int arr [ ] = { 1 , 100 , 101 } ; int N = sizeof ( arr ) / sizeof ( int ) ; cout << minCostToMakeElementEqual ( arr , N ) ; return 0 ; }
Minimum number of jumps required to sort numbers placed on a number line | C ++ program for the above approach ; Function to find the minimum number of jumps required to sort the array ; Base Case ; Store the required result ; Stores the current position of elements and their respective maximum jump ; Used to check if a position is already taken by another element ; Stores the sorted array a [ ] ; Traverse the array w [ ] & update positions jumps array a [ ] ; Sort the array a [ ] ; Traverse the array a [ ] over the range [ 1 , N - 1 ] ; Store the index of current element and its just smaller element in array w [ ] ; Iterate until current element position is at most its just smaller element position ; Update the position of the current element ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minJumps ( int w [ ] , int l [ ] , int n ) { if ( n == 1 ) { cout << 0 ; return ; } int ans = 0 ; unordered_map < int , int > pos , jump ; unordered_map < int , bool > filled ; int a [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { pos [ w [ i ] ] = i ; filled [ i ] = true ; jump [ w [ i ] ] = l [ i ] ; a [ i ] = w [ i ] ; } sort ( a , a + n ) ; for ( int curr = 1 ; curr < n ; curr ++ ) { int currElementPos = pos [ a [ curr ] ] ; int prevElementPos = pos [ a [ curr - 1 ] ] ; if ( currElementPos > prevElementPos ) continue ; while ( currElementPos <= prevElementPos filled [ currElementPos ] ) { currElementPos += jump [ a [ curr ] ] ; ans ++ ; } pos [ a [ curr ] ] = currElementPos ; filled [ currElementPos ] = true ; } cout << ans ; } int main ( ) { int W [ ] = { 2 , 1 , 4 , 3 } ; int L [ ] = { 4 , 1 , 2 , 4 } ; int N = sizeof ( W ) / sizeof ( W [ 0 ] ) ; minJumps ( W , L , N ) ; return 0 ; }
Make an array strictly increasing by repeatedly subtracting and adding arr [ i | C ++ program for the above approach ; Function to check if an array can be made strictly increasing ; Traverse the given array arr [ ] ; Update the value of p , arr [ i ] , and arr [ i - 1 ] ; Traverse the given array ; Check if the array arr [ ] is strictly increasing or not ; Otherwise , array is increasing order , print Yes ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void check ( int arr [ ] , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i - 1 ] >= ( i - 1 ) ) { int p = arr [ i - 1 ] - ( i - 1 ) ; arr [ i ] += p ; arr [ i - 1 ] -= p ; } } for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] <= arr [ i - 1 ] ) { cout << " No " ; return ; } } cout << " Yes " ; } int main ( ) { int arr [ ] = { 1 , 5 , 2 , 7 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; check ( arr , N ) ; return 0 ; }
Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted | C ++ program for the above approach ; Function to reverse the bits of a number ; Stores the reversed number ; Divide rev by 2 ; If the value of N is odd ; Update the value of N ; Return the final value of rev ; Function for rearranging the array element according to the given rules ; Stores the new array elements ; Function for rearranging the array ; Stores the new array ; Function to sort the array by reversing binary representation ; Creating a new array ; Sort the array with the key ; Get arr from newArr ; Print the sorted array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int keyFunc ( int n ) { int rev = 0 ; while ( n > 0 ) { rev = rev << 1 ; if ( n & 1 == 1 ) rev = rev ^ 1 ; n = n >> 1 ; } return rev ; } vector < vector < int > > getNew ( vector < int > arr ) { vector < vector < int > > ans ; for ( int i : arr ) ans . push_back ( { keyFunc ( i ) , i } ) ; return ans ; } vector < int > getArr ( vector < vector < int > > arr ) { vector < int > ans ; for ( auto i : arr ) ans . push_back ( i [ 1 ] ) ; return ans ; } void sortArray ( vector < int > arr ) { vector < vector < int > > newArr = getNew ( arr ) ; sort ( newArr . begin ( ) , newArr . end ( ) ) ; arr = getArr ( newArr ) ; int n = arr . size ( ) ; cout << " [ " ; for ( int i = 0 ; i < n - 1 ; i ++ ) cout << arr [ i ] << " , ▁ " ; cout << arr [ n - 1 ] << " ] " ; } int main ( ) { vector < int > arr = { 43 , 52 , 61 , 41 } ; sortArray ( arr ) ; return 0 ; }
Minimize maximum array element by splitting array elements into powers of two at most K times | C ++ program for the above approach ; Function to find the minimum value of the maximum element of the array by splitting at most K array element into perfect powers of 2 ; Sort the array element in the ascending order ; Reverse the array ; If count of 0 is equal to N ; Otherwise , if K is greater than or equal to N ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumSize ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; reverse ( arr , arr + N ) ; if ( count ( arr , arr + N , 0 ) == N ) cout << 0 ; else if ( K >= N ) cout << 1 << endl ; else cout << arr [ K ] << endl ; } int main ( ) { int arr [ ] = { 2 , 4 , 8 , 2 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumSize ( arr , N , K ) ; return 0 ; }
Check if removal of a subsequence of non | C ++ program for the above approach ; Function to check if it is possible to sort the array or not ; Stores the index if there are two consecutive 1 's in the array ; Traverse the given array ; Check adjacent same elements having values 1 s ; If there are no two consecutive 1 s , then always remove all the 1 s from array & make it sorted ; If two consecutive 0 ' s ▁ are ▁ ▁ present ▁ after ▁ two ▁ consecutive ▁ ▁ 1' s then array can 't be sorted ; Otherwise , print Yes ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void isPossibleToSort ( int arr [ ] , int N ) { int idx = -1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] == 1 && arr [ i - 1 ] == 1 ) { idx = i ; break ; } } if ( idx == -1 ) { cout << " YES " ; return ; } for ( int i = idx + 1 ; i < N ; i ++ ) { if ( arr [ i ] == 0 && arr [ i - 1 ] == 0 ) { cout << " NO " ; return ; } } cout << " YES " ; } int main ( ) { int arr [ ] = { 1 , 0 , 1 , 0 , 1 , 1 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; isPossibleToSort ( arr , N ) ; return 0 ; }
Maximize ropes of consecutive length possible by connecting given ropes | C ++ program for the above approach ; Function to find maximized count of ropes of consecutive length ; Stores the maximum count of ropes of consecutive length ; Sort the ropes by their length ; Traverse the array ; If size of the current rope is less than or equal to current maximum possible size + 1 , update the range to curSize + ropes [ i ] ; If a rope of size ( curSize + 1 ) cannot be obtained ; Driver Code ; Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxConsecutiveRopes ( int ropes [ ] , int N ) { int curSize = 0 ; sort ( ropes , ropes + N ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( ropes [ i ] <= curSize + 1 ) { curSize = curSize + ropes [ i ] ; } else break ; } return curSize ; } int main ( ) { int N = 5 ; int ropes [ ] = { 1 , 2 , 7 , 1 , 1 } ; cout << maxConsecutiveRopes ( ropes , N ) ; return 0 ; }
Maximum ranges that can be uniquely represented by any integer from the range | C ++ program for the above approach ; Function to find the maximum number of ranges where each range can be uniquely represented by an integer ; Sort the ranges in ascending order ; Stores the count of ranges ; Stores previously assigned range ; Traverse the vector arr [ ] ; Skip the similar ranges of size 1 ; Find the range of integer available to be assigned ; Check if an integer is available to be assigned ; Update the previously assigned range ; Update the count of range ; Return the maximum count of ranges ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxRanges ( vector < vector < int > > arr , int N ) { sort ( arr . begin ( ) , arr . end ( ) ) ; int count = 1 ; vector < int > prev = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { vector < int > last = arr [ i - 1 ] ; vector < int > current = arr [ i ] ; if ( last [ 0 ] == current [ 0 ] && last [ 1 ] == current [ 1 ] && current [ 1 ] == current [ 0 ] ) continue ; int start = max ( prev [ 0 ] , current [ 0 ] - 1 ) ; int end = max ( prev [ 1 ] , current [ 1 ] ) ; if ( end - start > 0 ) { prev [ 0 ] = 1 + start ; prev [ 1 ] = end ; count ++ ; } } return count ; } int main ( ) { vector < vector < int > > range = { { 1 , 4 } , { 4 , 4 } , { 2 , 2 } , { 3 , 4 } , { 1 , 1 } } ; int N = range . size ( ) ; cout << maxRanges ( range , N ) ; return 0 ; }
Sort a string lexicographically by reversing a substring | C ++ program for the above approach ; Function to find the substring in S required to be reversed ; Stores the size of the string ; Stores the starting point of the substring ; Iterate over the string S while i < N ; Increment the value of i ; Stores the ending index of the substring ; If start <= 0 or i >= N ; If start >= 1 and i <= N ; Return the boolean value ; If start >= 1 ; Return the boolean value ; If i < N ; Return true if S [ start ] is less than or equal to S [ i ] ; Otherwise ; Function to check if it is possible to sort the string or not ; Stores the starting and the ending index of substring ; Stores whether it is possible to sort the substring ; Traverse the range [ 1 , N ] ; If S [ i ] is less than S [ i - 1 ] ; If flag stores true ; If adjust ( S , i , start , end ) return false ; Print - 1 ; Unset the flag ; Otherwise ; Print - 1 ; If start is equal to - 1 ; Update start and end ; Print the value of start and end ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool adjust ( string & S , int & i , int & start , int & end ) { int N = S . length ( ) ; start = i - 1 ; while ( i < N && S [ i ] < S [ i - 1 ] ) { i ++ ; } end = i - 1 ; if ( start <= 0 && i >= N ) return true ; if ( start >= 1 && i <= N ) { return ( S [ end ] >= S [ start - 1 ] && S [ start ] <= S [ i ] ) ; } if ( start >= 1 ) { return S [ end ] >= S [ start - 1 ] ; } if ( i < N ) { return S [ start ] <= S [ i ] ; } return false ; } void isPossible ( string & S , int N ) { int start = -1 , end = -1 ; bool flag = true ; for ( int i = 1 ; i < N ; i ++ ) { if ( S [ i ] < S [ i - 1 ] ) { if ( flag ) { if ( adjust ( S , i , start , end ) == false ) { cout << -1 << endl ; return ; } flag = false ; } else { cout << -1 << endl ; return ; } } } if ( start == -1 ) { start = end = 1 ; } cout << start << " ▁ " << end << " STRNEWLINE " ; } int main ( ) { string S = " abcyxuz " ; int N = S . length ( ) ; isPossible ( S , N ) ; return 0 ; }
Maximum amount of capital required for selecting at most K projects | C ++ program for the above approach ; Function to calculate maximum capital obtained after choosing at most K projects whose capital is less than the given cost of projects ; Stores all projects with capital at most W ; Stores the pair of { C [ i ] , i } ; Traverse the vector C [ ] ; Sort the vector v ; If capital is at most W ; Push the profit into priority queue ; Increment j by one ; If pq is not empty ; Update the capital W ; Delete the top of pq ; Decrement K by one ; Return the maximum capital ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximizedCapital ( int K , int W , vector < int > & profits , vector < int > & capital ) { priority_queue < int > pq ; vector < pair < int , int > > v ; for ( int i = 0 ; i < capital . size ( ) ; i ++ ) { v . push_back ( { capital [ i ] , i } ) ; } sort ( v . begin ( ) , v . end ( ) ) ; int j = 0 ; while ( K ) { while ( j < ( int ) capital . size ( ) && v [ j ] . first <= W ) { pq . push ( profits [ v [ j ] . second ] ) ; j ++ ; } if ( ! pq . empty ( ) ) { W = W + pq . top ( ) ; pq . pop ( ) ; } K -- ; } return W ; } int main ( ) { int K = 2 ; int W = 0 ; vector < int > P = { 1 , 2 , 3 } ; vector < int > C = { 0 , 1 , 1 } ; cout << maximizedCapital ( K , W , P , C ) ; return 0 ; }
Split array into K non | C ++ program for the above approach ; Function find maximum sum of minimum and maximum of K subsets ; Stores the result ; Sort the array arr [ ] in decreasing order ; Traverse the range [ 0 , K ] ; Sort the array S [ ] in ascending order ; Traverse the array S [ ] ; If S { i ] is 1 ; Stores the index of the minimum element of the i - th subset ; Traverse the array S [ ] ; Update the counter ; Return the resultant sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( int arr [ ] , int S [ ] , int N , int K ) { int ans = 0 ; sort ( arr , arr + N , greater < int > ( ) ) ; for ( int i = 0 ; i < K ; i ++ ) ans += arr [ i ] ; sort ( S , S + K ) ; for ( int i = 0 ; i < K ; i ++ ) { if ( S [ i ] == 1 ) ans += arr [ i ] ; S [ i ] -- ; } int counter = K - 1 ; for ( int i = 0 ; i < K ; i ++ ) { counter = counter + S [ i ] ; if ( S [ i ] != 0 ) ans += arr [ counter ] ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 13 , 7 , 17 } ; int S [ ] = { 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = sizeof ( S ) / sizeof ( S [ 0 ] ) ; cout << maximumSum ( arr , S , N , K ) ; return 0 ; }
Modify an array by sorting after reversal of bits of each array element | C ++ implementation of the above approach ; Function to convert binary number to equivalent decimal ; Set base value to 1 , i . e 2 ^ 0 ; Function to convert a decimal to equivalent binary representation ; Stores the binary representation ; Since ASCII value of '0' , '1' are 48 and 49 ; As the string is already reversed , no further reversal is required ; Function to convert the reversed binary representation to equivalent integer ; Stores reversed binary representation of given decimal ; Stores equivalent decimal value of the binary representation ; Return the resultant integer ; Utility function to print the sorted array ; Sort the array ; Traverse the array ; Print the array elements ; Utility function to reverse the binary representations of all array elements and sort the modified array ; Traverse the array ; Passing array elements to reversedBinaryDecimal function ; Pass the array to the sorted array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binaryToDecimal ( string n ) { string num = n ; int dec_value = 0 ; int base = 1 ; int len = num . length ( ) ; for ( int i = len - 1 ; i >= 0 ; i -- ) { if ( num [ i ] == '1' ) dec_value += base ; base = base * 2 ; } return dec_value ; } string decimalToBinary ( int n ) { string binstr = " " ; while ( n > 0 ) { binstr += ( n % 2 + 48 ) ; n = n / 2 ; } return binstr ; } int reversedBinaryDecimal ( int N ) { string decimal_to_binar = decimalToBinary ( N ) ; int binary_to_decimal = binaryToDecimal ( decimal_to_binar ) ; return binary_to_decimal ; } void printSortedArray ( int arr [ ] , int size ) { sort ( arr , arr + size ) ; for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } void modifyArray ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { arr [ i ] = reversedBinaryDecimal ( arr [ i ] ) ; } printSortedArray ( arr , size ) ; } int main ( ) { int arr [ ] = { 98 , 43 , 66 , 83 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; modifyArray ( arr , n ) ; return 0 ; }
Check if sequence of removed middle elements from an array is sorted or not | C ++ program for the above approach ; Function to check if sequence of removed middle elements from an array is sorted or not ; Points to the ends of the array ; Iterate l + 1 < r ; If the element at index L and R is greater than ( L + 1 ) - th and ( R - 1 ) - th elements ; If true , then decrement R by 1 and increment L by 1 ; Otherwise , return false ; If an increasing sequence is formed , then return true ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSortedArray ( int arr [ ] , int n ) { int l = 0 , r = ( n - 1 ) ; while ( ( l + 1 ) < r ) { if ( arr [ l ] >= max ( arr [ l + 1 ] , arr [ r - 1 ] ) && arr [ r ] >= max ( arr [ r - 1 ] , arr [ l + 1 ] ) ) { l ++ ; r -- ; } else { return false ; } } return true ; } int main ( ) { int arr [ ] = { 4 , 3 , 1 , 2 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( isSortedArray ( arr , N ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Length of longest strictly increasing subset with each pair of adjacent elements satisfying the condition 2 * A [ i ] Γ’ ‰Β₯ A [ i + 1 ] | C ++ program for the above approach ; Function to find the length of the longest subset satisfying given conditions ; Sort the array in ascending order ; Stores the starting index and maximum length of the required subset ; Pointer to traverse the array ; Iterate while i < n ; Stores end point of current subset ; Store the length of the current subset ; Continue adding elements to the current subset till the condition satisfies ; Increment length of the current subset ; Increment the pointer j ; If length of the current subset exceeds overall maximum length ; Update maxlen ; Update index ; Increment j ; Update i ; Store the starting index of the required subset in i ; Print the required subset ; Print the array element ; Decrement maxlen ; Increment i ; Driver Code ; Given array ; Store the size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxLenSubset ( int a [ ] , int n ) { sort ( a , a + n ) ; int index = 0 , maxlen = -1 ; int i = 0 ; while ( i < n ) { int j = i ; int len = 1 ; while ( j < n - 1 ) { if ( 2 * a [ j ] >= a [ j + 1 ] ) { len ++ ; } else break ; j ++ ; } if ( maxlen < len ) { maxlen = len ; index = i ; } j ++ ; i = j ; } i = index ; while ( maxlen > 0 ) { cout << a [ i ] << " ▁ " ; maxlen -- ; i ++ ; } } int main ( ) { int a [ ] = { 3 , 1 , 5 , 11 } ; int n = sizeof ( a ) / sizeof ( int ) ; maxLenSubset ( a , n ) ; return 0 ; }
Maximize count of intersecting line segments | C ++ program for the above approach ; Function to find the maximum number of intersecting line segments possible ; Stores pairs of line segments { X [ i ] , Y [ i ] ) ; Push { X [ i ] , Y [ i ] } into p ; Sort p in ascending order of points on X number line ; Stores the points on Y number line in descending order ; Insert the first Y point from p ; Binary search to find the lower bound of p [ i ] . second ; If lower_bound doesn 't exist ; Insert p [ i ] . second into the set ; Erase the next lower _bound from the set ; Insert p [ i ] . second into the set ; Return the size of the set as the final result ; Driver Code ; Given Input ; Function call to find the maximum number of intersecting line segments
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int N , int X [ ] , int Y [ ] ) { vector < pair < int , int > > p ; for ( int i = 0 ; i < N ; i ++ ) { p . push_back ( { X [ i ] , Y [ i ] } ) ; } sort ( p . begin ( ) , p . end ( ) ) ; set < int , greater < int > > s ; s . insert ( p [ 0 ] . second ) ; for ( int i = 0 ; i < N ; i ++ ) { auto it = s . lower_bound ( p [ i ] . second ) ; if ( it == s . end ( ) ) { s . insert ( p [ i ] . second ) ; } else { s . erase ( * it ) ; s . insert ( p [ i ] . second ) ; } } return s . size ( ) ; } int main ( ) { int N = 3 ; int X [ ] = { 1 , 2 , 0 } ; int Y [ ] = { 2 , 0 , 1 } ; int maxintersection = solve ( N , X , Y ) ; cout << maxintersection ; }
Reduce an array to a single element by repeatedly removing larger element from a pair with absolute difference at most K | C ++ program for the above approach ; Function to check if an array can be reduced to single element by removing maximum element among any chosen pairs ; Sort the array in descending order ; Traverse the array ; If the absolute difference of 2 consecutive array elements is greater than K ; If the array can be reduced to a single element ; Driver Code ; Function Call to check if an array can be reduced to a single element
#include <bits/stdc++.h> NEW_LINE using namespace std ; void canReduceArray ( int arr [ ] , int N , int K ) { sort ( arr , arr + N , greater < int > ( ) ) ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] - arr [ i + 1 ] > K ) { cout << " No " ; return ; } } cout << " Yes " ; } int main ( ) { int arr [ ] = { 2 , 1 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 1 ; canReduceArray ( arr , N , K ) ; return 0 ; }
Lexicographically smallest string possible by merging two sorted strings | C ++ program for the above approach ; Function to find lexicographically smallest string possible by merging two sorted strings ; Stores length of string s1 ; Stores length of string s2 ; Pointer to beginning of string1 i . e . , s1 ; Pointer to beginning of string2 i . e . , s2 ; Stores the final string ; Traverse the strings ; Append the smaller of the two current characters ; Append the remaining characters of any of the two strings ; Print the final string ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void mergeStrings ( string s1 , string s2 ) { int len1 = s1 . size ( ) ; int len2 = s2 . size ( ) ; int pntr1 = 0 ; int pntr2 = 0 ; string ans = " " ; while ( pntr1 < len1 && pntr2 < len2 ) { if ( s1 [ pntr1 ] < s2 [ pntr2 ] ) { ans += s1 [ pntr1 ] ; pntr1 ++ ; } else { ans += s2 [ pntr2 ] ; pntr2 ++ ; } } if ( pntr1 < len1 ) { ans += s1 . substr ( pntr1 , len1 ) ; } if ( pntr2 < len2 ) { ans += s2 . substr ( pntr2 , len2 ) ; } cout << ans ; } int main ( ) { string S1 = " abdcdtx " ; string S2 = " achilp " ; mergeStrings ( S1 , S2 ) ; return 0 ; }
Sort a string without altering the position of vowels | C ++ program for the above approach ; Function to sort the string leaving the vowels unchanged ; Length of string S ; Traverse the string S ; Sort the string temp ; Pointer to traverse the sorted string of consonants ; Traverse the string S ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortStr ( string S ) { int N = S . size ( ) ; string temp = " " ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] != ' a ' && S [ i ] != ' e ' && S [ i ] != ' i ' && S [ i ] != ' o ' && S [ i ] != ' u ' ) temp += S [ i ] ; } if ( temp . size ( ) ) sort ( temp . begin ( ) , temp . end ( ) ) ; int ptr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] != ' a ' && S [ i ] != ' e ' && S [ i ] != ' i ' && S [ i ] != ' o ' && S [ i ] != ' u ' ) S [ i ] = temp [ ptr ++ ] ; } cout << S ; } int main ( ) { string S = " geeksforgeeks " ; sortStr ( S ) ; return 0 ; }
Count pairs from an array whose quotient of division of larger number by the smaller number does not exceed K | C ++ program for the above approach ; Function to count the number having quotient of division of larger element by the smaller element in the pair not exceeding K ; Sort the array in ascending order ; Store the required result ; Traverse the array ; Store the upper bound for the current array element ; Update the number of pairs ; Print the result ; Driver Code ; Given array , arr [ ] ; Store the size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int high = upper_bound ( arr , arr + n , k * arr [ i ] ) - arr ; ans += high - i - 1 ; } cout << ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 9 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 2 ; countPairs ( arr , n , k ) ; return 0 ; }
Kth highest XOR of diagonal elements from a Matrix | C ++ Program to implement the above approach ; Function to find K - th maximum XOR of any diagonal in the matrix ; Number or rows ; Number of columns ; Store XOR of diagonals ; Traverse each diagonal ; Starting column of diagonal ; Count total elements in the diagonal ; Store XOR of current diagonal ; Push XOR of current diagonal ; Sort XOR values of diagonals ; Print the K - th Maximum XOR ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findXOR ( vector < vector < int > > mat , int K ) { int N = mat . size ( ) ; int M = mat [ 0 ] . size ( ) ; vector < int > digXOR ; for ( int l = 1 ; l <= ( N + M - 1 ) ; l ++ ) { int s_col = max ( 0 , l - N ) ; int count = min ( { l , ( M - s_col ) , N } ) ; int currXOR = 0 ; for ( int j = 0 ; j < count ; j ++ ) { currXOR = ( currXOR ^ mat [ min ( N , l ) - j - 1 ] [ s_col + j ] ) ; } digXOR . push_back ( currXOR ) ; } sort ( digXOR . begin ( ) , digXOR . end ( ) ) ; cout << digXOR [ N + M - 1 - K ] ; } int main ( ) { vector < vector < int > > mat = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; int K = 3 ; findXOR ( mat , K ) ; return 0 ; }
Maximum sum of absolute differences between distinct pairs of a triplet from an array | C ++ program for the above approach ; Function to find the maximum sum of absolute differences between distinct pairs of triplet in array ; Stores the maximum sum ; Sort the array in ascending order ; Sum of differences between pairs of the triplet ; Print the sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSum ( int arr [ ] , int N ) { int sum ; sort ( arr , arr + N ) ; sum = ( arr [ N - 1 ] - arr [ 0 ] ) + ( arr [ N - 2 ] - arr [ 0 ] ) + ( arr [ N - 1 ] - arr [ N - 2 ] ) ; cout << sum ; } int main ( ) { int arr [ ] = { 1 , 3 , 4 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumSum ( arr , N ) ; return 0 ; }
Maximum and minimum sum of Bitwise XOR of pairs from an array | C ++ program for the above approach ; Function to find the required sum ; Keeps the track of the visited array elements ; Stores the result ; Keeps count of visited elements ; Traverse the vector , V ; If n elements are visited , break out of the loop ; Store the pair ( i , j ) and their Bitwise XOR ; If i and j both are unvisited ; Add xorResult to res and mark i and j as visited ; Increment count by 2 ; Return the result ; Function to find the maximum and minimum possible sum of Bitwise XOR of all the pairs from the array ; Stores the XOR of all pairs ( i , j ) ; Store the XOR of all pairs ( i , j ) ; Update Bitwise XOR ; Sort the vector ; Initialize variables to store maximum and minimum possible sums ; Find the minimum sum possible ; Reverse the vector , v ; Find the maximum sum possible ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( vector < pair < int , pair < int , int > > > v , int n ) { unordered_map < int , bool > um ; int res = 0 ; int cnt = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { if ( cnt == n ) break ; int x = v [ i ] . second . first ; int y = v [ i ] . second . second ; int xorResult = v [ i ] . first ; if ( um [ x ] == false && um [ y ] == false ) { res += xorResult ; um [ x ] = true ; um [ y ] = true ; cnt += 2 ; } } return res ; } void findMaxMinSum ( int a [ ] , int n ) { vector < pair < int , pair < int , int > > > v ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int xorResult = a [ i ] ^ a [ j ] ; v . push_back ( { xorResult , { a [ i ] , a [ j ] } } ) ; } } sort ( v . begin ( ) , v . end ( ) ) ; int maxi = 0 , mini = 0 ; mini = findSum ( v , n ) ; reverse ( v . begin ( ) , v . end ( ) ) ; maxi = findSum ( v , n ) ; cout << mini << " ▁ " << maxi ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMaxMinSum ( arr , N ) ; return 0 ; }
Lexicographically smallest permutation having maximum sum of differences between adjacent elements | C ++ program for the above approach ; Function to find the lexicographically smallest permutation of an array such that the sum of the difference between adjacent elements is maximum ; Stores the size of the array ; Sort the given array in increasing order ; Swap the first and last array elements ; Print the required permutation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumSumPermutation ( vector < int > & arr ) { int N = arr . size ( ) ; sort ( arr . begin ( ) , arr . end ( ) ) ; swap ( arr [ 0 ] , arr [ N - 1 ] ) ; for ( int i : arr ) { cout << i << " ▁ " ; } } int main ( ) { vector < int > arr = { 1 , 2 , 3 , 4 , 5 } ; maximumSumPermutation ( arr ) ; return 0 ; }
Maximize count of 1 s in an array by repeated division of array elements by 2 at most K times | C ++ program for the above approach ; Function to count the maximum number of array elements that can be reduced to 1 by repeatedly dividing array elements by 2 ; Sort the array in ascending order ; Store the count of array elements ; Traverse the array ; Store the number of operations required to reduce arr [ i ] to 1 ; Decrement k by opr ; If k becomes less than 0 , then break out of the loop ; Increment cnt by 1 ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxNumbers ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int opr = ceil ( log2 ( arr [ i ] ) ) ; k -= opr ; if ( k < 0 ) { break ; } cnt ++ ; } cout << cnt ; } int main ( ) { int arr [ ] = { 5 , 8 , 4 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 5 ; findMaxNumbers ( arr , N , K ) ; return 0 ; }
Mean of given array after removal of K percent of smallest and largest array elements | C ++ program for the above approach ; Function to calculate the mean of a given array after removal of Kth percent of smallest and largest array elements ; Sort the array ; Find the K - th percent of the array size ; Traverse the array ; Skip the first K - th percent & last K - th percent array elements ; Mean of the rest of elements ; Print mean upto 5 decimal places ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void meanOfRemainingElements ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; int kthPercent = ( N * K ) / 100 ; float sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) if ( i >= kthPercent && i < ( N - kthPercent ) ) sum += arr [ i ] ; float mean = sum / ( N - 2 * kthPercent ) ; cout << fixed << setprecision ( 5 ) << mean << endl ; } int main ( ) { int arr [ ] = { 6 , 2 , 7 , 5 , 1 , 2 , 0 , 3 , 10 , 2 , 5 , 0 , 5 , 5 , 0 , 8 , 7 , 6 , 8 , 0 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 5 ; meanOfRemainingElements ( arr , arr_size , K ) ; return 0 ; }
Make the array elements equal by performing given operations minimum number of times | C ++ Program for the above approach ; Function to calculate the minimum operations of given type required to make the array elements equal ; Stores the total count of operations ; Traverse the array ; Update difference between pairs of adjacent elements ; Store the maximum count of operations ; Rest of the elements ; Total Operation - Maximum Operation ; Driver Code ; Given array ; Size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperation ( int a [ ] , int N ) { int totOps = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { totOps += abs ( a [ i ] - a [ i + 1 ] ) ; } int maxOps = max ( abs ( a [ 0 ] - a [ 1 ] ) , abs ( a [ N - 1 ] - a [ N - 2 ] ) ) ; for ( int i = 1 ; i < N - 1 ; i ++ ) { maxOps = max ( maxOps , abs ( a [ i ] - a [ i - 1 ] ) + abs ( a [ i ] - a [ i + 1 ] ) - abs ( a [ i - 1 ] - a [ i + 1 ] ) ) ; } cout << totOps - maxOps << endl ; } int main ( ) { int arr [ ] = { 1 , -1 , 0 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minOperation ( arr , N ) ; return 0 ; }
Find the segment that overlaps with maximum number of segments | C ++ program for the above approach ; Function to find the segment which overlaps with maximum number of segments ; ' L ' & ' R ' co - ordinates of all segments are stored in lvalues & rvalues ; Assign co - ordinates ; Co - ordinate compression ; Stores the required segment ; Stores the current maximum number of intersections ; Find number of ' R ' coordinates which are less than the ' L ' value of the current segment ; Find number of ' L ' coordinates which are greater than the ' R ' value of the current segment ; Segments excluding ' lesser ' and ' greater ' gives the number of intersections ; Update the current maximum ; Print segment coordinates ; Driver Code ; Given segments ; Size of segments array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxIntersection ( int segments [ ] [ 2 ] , int N ) { vector < int > rvalues ( N ) , lvalues ( N ) ; for ( int i = 0 ; i < N ; ++ i ) { lvalues [ i ] = segments [ i ] [ 0 ] ; rvalues [ i ] = segments [ i ] [ 1 ] ; } sort ( lvalues . begin ( ) , lvalues . end ( ) ) ; sort ( rvalues . begin ( ) , rvalues . end ( ) ) ; pair < int , int > answer = { -1 , -1 } ; int numIntersections = 0 ; for ( int i = 0 ; i < N ; ++ i ) { int lesser = lower_bound ( rvalues . begin ( ) , rvalues . end ( ) , segments [ i ] [ 0 ] ) - rvalues . begin ( ) ; int greater = max ( 0 , N - ( int ) ( upper_bound ( lvalues . begin ( ) , lvalues . end ( ) , segments [ i ] [ 1 ] ) - lvalues . begin ( ) ) ) ; if ( ( N - lesser - greater ) >= numIntersections ) { answer = { segments [ i ] [ 0 ] , segments [ i ] [ 1 ] } ; numIntersections = ( N - lesser - greater ) ; } } cout << answer . first << " ▁ " << answer . second ; } int main ( ) { int segments [ ] [ 2 ] = { { 1 , 4 } , { 2 , 3 } , { 3 , 6 } } ; int N = sizeof ( segments ) / sizeof ( segments [ 0 ] ) ; maxIntersection ( segments , N ) ; }
Count swaps required to sort an array using Insertion Sort | C ++ Program to implement the above approach ; Stores the sorted array elements ; Function to count the number of swaps required to merge two sorted subarray in a sorted form ; Stores the count of swaps ; Function to count the total number of swaps required to sort the array ; Stores the total count of swaps required ; Find the middle index splitting the two halves ; Count the number of swaps required to sort the left subarray ; Count the number of swaps required to sort the right subarray ; Count the number of swaps required to sort the two sorted subarrays ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int temp [ 100000 ] ; long int merge ( int A [ ] , int left , int mid , int right ) { long int swaps = 0 ; int i = left , j = mid , k = left ; while ( i < mid && j <= right ) { if ( A [ i ] <= A [ j ] ) { temp [ k ] = A [ i ] ; k ++ , i ++ ; } else { temp [ k ] = A [ j ] ; k ++ , j ++ ; swaps += mid - i ; } } while ( i < mid ) { temp [ k ] = A [ i ] ; k ++ , i ++ ; } while ( j <= right ) { temp [ k ] = A [ j ] ; k ++ , j ++ ; } while ( left <= right ) { A [ left ] = temp [ left ] ; left ++ ; } return swaps ; } long int mergeInsertionSwap ( int A [ ] , int left , int right ) { long int swaps = 0 ; if ( left < right ) { int mid = left + ( right - left ) / 2 ; swaps += mergeInsertionSwap ( A , left , mid ) ; swaps += mergeInsertionSwap ( A , mid + 1 , right ) ; swaps += merge ( A , left , mid + 1 , right ) ; } return swaps ; } int main ( ) { int A [ ] = { 2 , 1 , 3 , 1 , 2 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << mergeInsertionSwap ( A , 0 , N - 1 ) ; return 0 ; }
Maximum removals possible from an array such that sum of its elements is greater than or equal to that of another array | C ++ program to implement the above approach ; Function to maximize the count of elements required to be removed from arr [ ] such that the sum of arr [ ] is greater than or equal to sum of the array brr [ ] ; Sort the array arr [ ] ; Stores index of smallest element of arr [ ] ; Stores sum of elements of the array arr [ ] ; Traverse the array arr [ ] ; Update sumArr ; Stores sum of elements of the array brr [ ] ; Traverse the array brr [ ] ; Update sumArr ; Stores count of removed elements ; Repeatedly remove the smallest element of arr [ ] ; Update sumArr ; Remove the smallest element ; If the sum of remaining elements in arr [ ] >= sum of brr [ ] ; Update cntRemElem ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCntRemovedfromArray ( int arr [ ] , int N , int brr [ ] , int M ) { sort ( arr , arr + N ) ; int i = 0 ; int sumArr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sumArr += arr [ i ] ; } int sumBrr = 0 ; for ( int i = 0 ; i < M ; i ++ ) { sumBrr += brr [ i ] ; } int cntRemElem = 0 ; while ( i < N and sumArr > = sumBrr ) { sumArr -= arr [ i ] ; i += 1 ; if ( sumArr >= sumBrr ) { cntRemElem += 1 ; } } return cntRemElem ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 6 } ; int brr [ ] = { 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = sizeof ( brr ) / sizeof ( brr [ 0 ] ) ; cout << maxCntRemovedfromArray ( arr , N , brr , M ) ; }
Find any two pairs ( a , b ) and ( c , d ) such that a d | C ++ program for the above approach ; Function to find two pairs ( a , b ) and ( c , d ) such that a < c and b > d ; If no such pair is found ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPair ( pair < int , int > * arr , int N ) { for ( int i = 0 ; i < N ; i ++ ) { int a = arr [ i ] . first , b = arr [ i ] . second ; for ( int j = i + 1 ; j < N ; j ++ ) { int c = arr [ j ] . first , d = arr [ j ] . second ; if ( a < c && b > d ) { cout << " ( " << a << " ▁ " << b << " ) , ▁ ( " << c << " ▁ " << d << " ) STRNEWLINE " ; return ; } } } cout << " NO ▁ SUCH ▁ PAIR ▁ EXIST STRNEWLINE " ; } int main ( ) { pair < int , int > arr [ ] = { { 3 , 7 } , { 21 , 23 } , { 4 , 13 } , { 1 , 2 } , { 7 , -1 } } ; findPair ( arr , 5 ) ; }
Find any two pairs ( a , b ) and ( c , d ) such that a d | C ++ program for the above approach ; Function to find two pairs ( a , b ) and ( c , d ) such that a < c and b > d ; Sort the array in increasing order of first element of pairs ; Traverse the array ; If no such pair found ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPair ( pair < int , int > * arr , int N ) { sort ( arr , arr + N ) ; for ( int i = 1 ; i < N ; i ++ ) { int b = arr [ i - 1 ] . second ; int d = arr [ i ] . second ; if ( b > d ) { cout << " ( " << arr [ i - 1 ] . first << " ▁ " << b << " ) , ▁ ( " << arr [ i ] . first << " ▁ " << d << " ) " ; return ; } } cout << " NO ▁ SUCH ▁ PAIR ▁ EXIST STRNEWLINE " ; } int main ( ) { pair < int , int > arr [ ] = { { 3 , 7 } , { 21 , 23 } , { 4 , 13 } , { 1 , 2 } , { 7 , -1 } } ; findPair ( arr , 5 ) ; }
Print indices in non | C ++ program for the above approach ; Function to print the order of array elements generating non - decreasing quotient after division by X ; Stores the quotient and the order ; Traverse the array ; Sort the vector ; Print the order ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printOrder ( int order [ ] , int N , int X ) { vector < pair < int , int > > vect ; for ( int i = 0 ; i < N ; i ++ ) { if ( order [ i ] % X == 0 ) { vect . push_back ( { order [ i ] / X , i + 1 } ) ; } else { vect . push_back ( { order [ i ] / X + 1 , i + 1 } ) ; } } sort ( vect . begin ( ) , vect . end ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { cout << vect [ i ] . second << " ▁ " ; } cout << endl ; } int main ( ) { int N = 3 , X = 3 ; int order [ ] = { 2 , 7 , 4 } ; printOrder ( order , N , X ) ; return 0 ; }
Reduce sum of same | C ++ program for the above approach ; Function to check if elements of B [ ] can be rearranged such that A [ i ] + B [ i ] <= X ; Checks the given condition ; Sort A [ ] in ascending order ; Sort B [ ] in descending order ; Traverse the arrays A [ ] and B [ ] ; If A [ i ] + B [ i ] exceeds X ; Rearrangement not possible , set flag to false ; If flag is true ; Otherwise ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrange ( int A [ ] , int B [ ] , int N , int X ) { bool flag = true ; sort ( A , A + N ) ; sort ( B , B + N , greater < int > ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] + B [ i ] > X ) { flag = false ; break ; } } if ( flag ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int B [ ] = { 1 , 1 , 2 } ; int X = 4 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; rearrange ( A , B , N , X ) ; return 0 ; }
Minimum increments or decrements by D required to make all array elements equal | C ++ program for the above approach ; Function to find minimum count of operations required to make all array elements equal by incrementing or decrementing array elements by d ; Sort the array ; Traverse the array ; If difference between two consecutive elements are not divisible by D ; Store minimum count of operations required to make all array elements equal by incrementing or decrementing array elements by d ; Stores middle element of the array ; Traverse the array ; Update count ; Driver Code ; Given N & D ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void numOperation ( int arr [ ] , int N , int D ) { sort ( arr , arr + N ) ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( ( arr [ i + 1 ] - arr [ i ] ) % D != 0 ) { cout << " - 1" ; return ; } } int count = 0 ; int mid = arr [ N / 2 ] ; for ( int i = 0 ; i < N ; i ++ ) { count += abs ( mid - arr [ i ] ) / D ; } cout << count ; } int main ( ) { int N = 4 , D = 2 ; int arr [ ] = { 2 , 4 , 6 , 8 } ; numOperation ( arr , N , D ) ; }
Maximize sum of second minimums of each K length partitions of the array | C ++ program for the above approach ; Function to find the maximum sum of second smallest of each partition of size K ; Sort the array A [ ] in ascending order ; Store the maximum sum of second smallest of each partition of size K ; Select every ( K - 1 ) th element as second smallest element ; Update sum ; Print the maximum sum ; Driver Code ; Given size of partitions ; Given array A [ ] ; Size of the given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSum ( int A [ ] , int N , int K ) { sort ( A , A + N ) ; int sum = 0 ; for ( int i = N / K ; i < N ; i += K - 1 ) { sum += A [ i ] ; } cout << sum ; } int main ( ) { int K = 4 ; int A [ ] = { 2 , 3 , 1 , 4 , 7 , 5 , 6 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; findSum ( A , N , K ) ; return 0 ; }
Minimize remaining array element by removing pairs and replacing them with their average | C ++ program to implement the above approach ; Function to find the smallest element left in the array by removing pairs and inserting their average ; Stores array elements such that the largest element present at top of PQ ; Traverse the array ; Insert arr [ i ] into PQ ; Iterate over elements of PQ while count of elements in PQ greater than 1 ; Stores largest element of PQ ; Pop the largest element of PQ ; Stores largest element of PQ ; Pop the largest element of PQ ; Insert the ceil value of average of top1 and top2 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSmallestNumLeft ( int arr [ ] , int N ) { priority_queue < int > PQ ; for ( int i = 0 ; i < N ; i ++ ) { PQ . push ( arr [ i ] ) ; } while ( PQ . size ( ) > 1 ) { int top1 = PQ . top ( ) ; PQ . pop ( ) ; int top2 = PQ . top ( ) ; PQ . pop ( ) ; PQ . push ( ( top1 + top2 + 1 ) / 2 ) ; } return PQ . top ( ) ; } int main ( ) { int arr [ ] = { 30 , 16 , 40 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSmallestNumLeft ( arr , N ) ; return 0 ; }
Find the array element from indices not divisible by K having largest composite product of digits | C ++ program to implement the above approach ; Function to check if a number is a composite number or not ; Corner cases ; Check if number is divisible by 2 or 3 ; Check if number is a multiple of any other prime number ; Function to calculate the product of digits of a number ; Stores the product of digits ; Extract digits of a number ; Calculate product of digits ; Function to check if the product of digits of a number is a composite number or not ; Stores product of digits ; If product of digits is equal to 1 ; If product of digits is not prime ; Function to find the number with largest composite product of digits from the indices not divisible by k from the given array ; Traverse the array ; If index is divisible by k ; Check if product of digits is a composite number or not ; Sort the products ; Driver Code
#include <bits/stdc++.h> NEW_LINE #include <vector> NEW_LINE using namespace std ; bool isComposite ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return false ; if ( n % 2 == 0 n % 3 == 0 ) return true ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return true ; return false ; } int digitProduct ( int number ) { int product = 1 ; while ( number > 0 ) { product *= ( number % 10 ) ; number /= 10 ; } return product ; } bool compositedigitProduct ( int num ) { int res = digitProduct ( num ) ; if ( res == 1 ) { return false ; } if ( isComposite ( res ) ) { return true ; } return false ; } int largestCompositeDigitProduct ( int a [ ] , int n , int k ) { vector < pair < int , int > > pq ; for ( int i = 0 ; i < n ; i ++ ) { if ( ( i % k ) == 0 ) { continue ; } if ( compositedigitProduct ( a [ i ] ) ) { int b = digitProduct ( a [ i ] ) ; pq . push_back ( make_pair ( b , a [ i ] ) ) ; } } sort ( pq . begin ( ) , pq . end ( ) ) ; return pq . back ( ) . second ; } int main ( ) { int arr [ ] = { 233 , 144 , 89 , 71 , 13 , 21 , 11 , 34 , 55 , 23 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; int ans = largestCompositeDigitProduct ( arr , n , k ) ; cout << ans << endl ; return 0 ; }
Split array into K | C ++ implementation for above approach ; Function to find the minimum sum of 2 nd smallest elements of each subset ; Sort the array ; Stores minimum sum of second elements of each subset ; Traverse first K 2 nd smallest elements ; Update their sum ; Print the sum ; Driver Code ; Given Array ; Given size of the array ; Given subset lengths
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimum ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; int ans = 0 ; for ( int i = 1 ; i < 2 * ( N / K ) ; i += 2 ) { ans += arr [ i ] ; } cout << ans ; } int main ( ) { int arr [ ] = { 11 , 20 , 5 , 7 , 8 , 14 , 2 , 17 , 16 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 5 ; findMinimum ( arr , N , K ) ; return 0 ; }
Find two non | C ++ program for the above approach ; Function to check if two non - intersecting subarrays with equal sum exists or not ; Sort the given array ; Traverse the array ; Check for duplicate elements ; If no duplicate element is present in the array ; Driver Code ; Given array ; Size of array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubarrays ( int arr [ ] , int N ) { sort ( arr , arr + N ) ; int i = 0 ; for ( i = 0 ; i < N - 1 ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) { cout << " YES " << endl ; return ; } } cout << " NO " << endl ; } int main ( ) { int arr [ ] = { 4 , 3 , 0 , 1 , 2 , 0 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findSubarrays ( arr , N ) ; return 0 ; }
Queries to check if sweets of given type can be eaten on given day or not | C ++ program for the above approach ; Function to find queries to check if a sweet of given type can be eaten on a given day or not ; Stores pairs { priority , quantity } of each sweet - type ; Sorting the order of sweets in decreasing order of their priority ; Stores the window { min_days , max_days } for each sweet - type ; Variables to calculate the windows ; Traverse the array ; Calculating maximum and minimum number of days required to complete the sweets of the current type ; Creating the window and storing it ; Traversing the queries ; x : Type of sweet , y : Day ; Find the window for the sweet of type x ; If the given day lies within the window ; Driver Code ; Quantites of sweets of each type ; Priorites of each type sweet ; Maximum sweet of one type that can be eaten on a day ; Queries ; Calculating number of types
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sweetTypeOnGivenDay ( int a [ ] , int b [ ] , int n , int k , vector < pair < int , int > > & q ) { vector < pair < int , pair < int , int > > > v ; for ( int i = 0 ; i < n ; i ++ ) v . push_back ( { b [ i ] , { a [ i ] , i + 1 } } ) ; sort ( v . begin ( ) , v . end ( ) , greater < pair < int , pair < int , int > > > ( ) ) ; map < int , pair < int , int > > mp ; int lowerbound = 0 , upperbound = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int maxi_days = v [ i ] . second . first ; int mini_days = v [ i ] . second . first / k ; if ( v [ i ] . second . first % k != 0 ) mini_days ++ ; upperbound += maxi_days ; mp [ v [ i ] . second . second ] = { lowerbound , upperbound } ; lowerbound += mini_days ; } for ( int i = 0 ; i < q . size ( ) ; i ++ ) { int x = q [ i ] . first , y = q [ i ] . second ; int e = mp [ x ] . first ; int f = mp [ x ] . second ; if ( y >= e && y <= f ) cout << " Yes " << " ▁ " ; else cout << " No " << " ▁ " ; } } int main ( ) { int A [ ] = { 6 , 3 , 7 , 5 , 2 } ; int B [ ] = { 1 , 2 , 3 , 4 , 5 } ; int K = 3 ; vector < pair < int , int > > Queries = { { 4 , 4 } , { 3 , 16 } , { 2 , 7 } } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; sweetTypeOnGivenDay ( A , B , n , K , Queries ) ; }
Selection Sort VS Bubble Sort | C ++ program for the above approach ; Function for bubble sort ; Iterate from 1 to n - 1 ; Iterate from 0 to n - i - 1 ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void Bubble_Sort ( int arr [ ] , int n ) { bool flag ; for ( int i = 1 ; i < n ; ++ i ) { flag = false ; for ( int j = 0 ; j <= ( n - i - 1 ) ; ++ j ) { if ( arr [ j ] > arr [ j + 1 ] ) { swap ( arr [ j ] , arr [ j + 1 ] ) ; flag = true ; } } if ( flag == false ) break ; } } int main ( ) { int n = 5 ; int arr [ 5 ] = { 2 , 0 , 1 , 4 , 3 } ; Bubble_Sort ( arr , n ) ; cout << " The ▁ Sorted ▁ Array ▁ by ▁ using ▁ Bubble ▁ Sort ▁ is ▁ : ▁ " ; for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Print all array elements appearing more than N / K times | C ++ program to implement the above approach ; Function to print all array elements whose frequency is greater than N / K ; Sort the array , arr [ ] ; Traverse the array ; Stores frequency of arr [ i ] ; Traverse array elements which is equal to arr [ i ] ; Update cnt ; Update i ; If frequency of arr [ i ] is greater than ( N / K ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void NDivKWithFreq ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; ) { int cnt = 1 ; while ( ( i + 1 ) < N && arr [ i ] == arr [ i + 1 ] ) { cnt ++ ; i ++ ; } if ( cnt > ( N / K ) ) { cout << arr [ i ] << " ▁ " ; } i ++ ; } } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 4 ; NDivKWithFreq ( arr , N , K ) ; return 0 ; }
Sort M elements of given circular array starting from index K | C ++ program for the above approach ; Function to print the circular array ; Print the array ; Function to sort m elements of diven circular array starting from index k ; Traverse M elements ; Iterate from index k to k + m - 1 ; Check if the next element in the circular array is less than the current element ; Swap current element with the next element ; Print the circular array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printCircularArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " ▁ " ; } } void sortCircularArray ( int arr [ ] , int n , int k , int m ) { for ( int i = 0 ; i < m ; i ++ ) { for ( int j = k ; j < k + m - 1 ; j ++ ) { if ( arr [ j % n ] > arr [ ( j + 1 ) % n ] ) { swap ( arr [ j % n ] , arr [ ( j + 1 ) % n ] ) ; } } } printCircularArray ( arr , n ) ; } int main ( ) { int arr [ ] = { 4 , 1 , 6 , 5 , 3 } ; int K = 2 , M = 3 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortCircularArray ( arr , N , K , M ) ; return 0 ; }