text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Min number of moves to traverse entire Matrix through connected cells with equal values | C ++ program to find the minimum number of moves to traverse a given matrix ; Function to find the minimum number of moves to traverse the given matrix ; Constructing another matrix consisting of distinct values ; Updating the array B by checking the values of A that if there are same values connected through an edge or not ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Check for boundary condition of the matrix ; If adjacent cells have same value ; Store all distinct elements in a set ; Return answer ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int A [ ] [ 10 ] , int N , int M ) { int B [ N ] [ M ] ; int c = 1 ; set < int > s ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) B [ i ] [ j ] = c ++ ; } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( i != 0 ) { if ( A [ i - 1 ] [ j ] == A [ i ] [ j ] ) B [ i - 1 ] [ j ] = B [ i ] [ j ] ; } if ( i != N - 1 ) { if ( A [ i + 1 ] [ j ] == A [ i ] [ j ] ) B [ i + 1 ] [ j ] = B [ i ] [ j ] ; } if ( j != 0 ) { if ( A [ i ] [ j - 1 ] == A [ i ] [ j ] ) B [ i ] [ j - 1 ] = B [ i ] [ j ] ; } if ( j != M - 1 ) { if ( A [ i ] [ j + 1 ] == A [ i ] [ j ] ) B [ i ] [ j + 1 ] = B [ i ] [ j ] ; } } } for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) s . insert ( B [ i ] [ j ] ) ; } return s . size ( ) ; } int main ( ) { int N = 2 , M = 3 ; int A [ ] [ 10 ] = { { 2 , 1 , 3 } , { 1 , 1 , 2 } } ; cout << solve ( A , N , M ) ; }
Number of times an array can be partitioned repetitively into two subarrays with equal sum | C ++ program for the above approach ; Recursion Function to calculate the possible splitting ; If there are less than two elements , we cannot partition the sub - array . ; Iterate from the start to end - 1. ; Recursive call to the left and the right sub - array . ; If there is no such partition , then return 0 ; Function to find the total splitting ; Prefix array to store the prefix - sum using 1 based indexing ; Store the prefix - sum ; Function Call to count the number of splitting ; Driver Code ; Given array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int splitArray ( int start , int end , int * arr , int * prefix_sum ) { if ( start >= end ) return 0 ; for ( int k = start ; k < end ; ++ k ) { if ( ( prefix_sum [ k ] - prefix_sum [ start - 1 ] ) == ( prefix_sum [ end ] - prefix_sum [ k ] ) ) { return 1 + splitArray ( start , k , arr , prefix_sum ) + splitArray ( k + 1 , end , arr , prefix_sum ) ; } } return 0 ; } void solve ( int arr [ ] , int n ) { int prefix_sum [ n + 1 ] ; prefix_sum [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; ++ i ) { prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i - 1 ] ; } cout << splitArray ( 1 , n , arr , prefix_sum ) ; } int main ( ) { int arr [ ] = { 12 , 3 , 3 , 0 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; solve ( arr , N ) ; return 0 ; }
Minimise the maximum element of N subarrays of size K | C ++ implementation to choose N subarrays of size K such that the maximum element of subarrays is minimum ; Function to choose N subarrays of size K such that the maximum element of subarrays is minimum ; Condition to check if it is not possible to choose k sized N subarrays ; Using binary search ; calculating mid ; Loop to find the count of the K sized subarrays possible with elements less than mid ; Condition to check if the answer is in right subarray ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDays ( vector < int > & arr , int n , int k ) { int l = arr . size ( ) , left = 1 , right = 1e9 ; if ( n * k > l ) return -1 ; while ( left < right ) { int mid = ( left + right ) / 2 , cnt = 0 , product = 0 ; for ( int j = 0 ; j < l ; ++ j ) { if ( arr [ j ] > mid ) { cnt = 0 ; } else if ( ++ cnt >= k ) { product ++ ; cnt = 0 ; } } if ( product < n ) { left = mid + 1 ; } else { right = mid ; } } return left ; } int main ( ) { vector < int > arr { 1 , 10 , 3 , 10 , 2 } ; int n = 3 , k = 1 ; cout << minDays ( arr , n , k ) << endl ; return 0 ; }
Count of distinct power of prime factor of N | C ++ program for the above approach ; Function to count the number of distinct positive power of prime factor of integer N ; Iterate for all prime factor ; If it is a prime factor , count the total number of times it divides n . ; Find the Number of distinct possible positive numbers ; Return the final count ; Driver Code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countFac ( int n ) { int m = n ; int count = 0 ; for ( int i = 2 ; ( i * i ) <= m ; ++ i ) { int total = 0 ; while ( n % i == 0 ) { n /= i ; ++ total ; } int temp = 0 ; for ( int j = 1 ; ( temp + j ) <= total ; ++ j ) { temp += j ; ++ count ; } } if ( n != 1 ) ++ count ; return count ; } int main ( ) { int N = 24 ; cout << countFac ( N ) ; return 0 ; }
Minimum total sum from the given two arrays | C ++ program for the above approach ; Function that prints minimum sum after selecting N elements ; Initialise the dp array ; Base Case ; Adding the element of array a if previous element is also from array a ; Adding the element of array a if previous element is from array b ; Adding the element of array b if previous element is from array a with an extra penalty of integer C ; Adding the element of array b if previous element is also from array b ; Print the minimum sum ; Driver Code ; Given array arr1 [ ] and arr2 [ ] ; Given cost ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumSum ( int a [ ] , int b [ ] , int c , int n ) { vector < vector < int > > dp ( n , vector < int > ( 2 , 1e6 ) ) ; dp [ 0 ] [ 0 ] = a [ 0 ] ; dp [ 0 ] [ 1 ] = b [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { dp [ i ] [ 0 ] = min ( dp [ i ] [ 0 ] , dp [ i - 1 ] [ 0 ] + a [ i ] ) ; dp [ i ] [ 0 ] = min ( dp [ i ] [ 0 ] , dp [ i - 1 ] [ 1 ] + a [ i ] + c ) ; dp [ i ] [ 1 ] = min ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 0 ] + b [ i ] + c ) ; dp [ i ] [ 1 ] = min ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 1 ] + b [ i ] ) ; } cout << min ( dp [ n - 1 ] [ 0 ] , dp [ n - 1 ] [ 1 ] ) << " STRNEWLINE " ; } int main ( ) { int arr1 [ ] = { 7 , 6 , 18 , 6 , 16 , 18 , 1 , 17 , 17 } ; int arr2 [ ] = { 6 , 9 , 3 , 10 , 9 , 1 , 10 , 1 , 5 } ; int C = 2 ; int N = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; minimumSum ( arr1 , arr2 , C , N ) ; return 0 ; }
Minimum flips required in a binary string such that all K | C ++ program to find the minimum numbers of flips required in a binary string such that all substrings of size K has atleast one 1 ; Function to calculate and return the minimum number of flips to make string valid ; Stores the count of required flips ; Stores the last index of '1' in the string ; Check for the first substring of length K ; If i - th character is '1' ; If the substring had no '1' ; Increase the count of required flips ; Flip the last index of the window ; Update the last index which contains 1 ; Check for remaining substrings ; If last_idx does not belong to current window make it - 1 ; If the last character of the current substring is '1' , then update last_idx to i + k - 1 ; ; If last_idx == - 1 , then the current substring has no 1 ; Increase the count of flips ; Update the last index of the current window ; Store the last index of current window as the index of last '1' in the string ; Return the number of operations ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumMoves ( string S , int K ) { int N = S . length ( ) ; int ops = 0 ; int last_idx = -1 ; for ( int i = 0 ; i < K ; i ++ ) { if ( S [ i ] == '1' ) last_idx = i ; } if ( last_idx == -1 ) { ++ ops ; S [ K - 1 ] = '1' ; last_idx = K - 1 ; } for ( int i = 1 ; i < N - K + 1 ; i ++ ) { if ( last_idx < i ) last_idx = -1 ; if ( S [ i + K - 1 ] == '1' ) last_idx = i + K - 1 ; if ( last_idx == -1 ) { ++ ops ; S [ i + K - 1 ] = '1' ; last_idx = i + K - 1 ; } } return ops ; } int main ( ) { string S = "001010000" ; int K = 3 ; cout << minimumMoves ( S , K ) ; return 0 ; }
Lexicographically smallest string which differs from given strings at exactly K indices | C ++ program for the above approach ; Function to find the string which differ at exactly K positions ; Initialise s3 as s2 ; Number of places at which s3 differ from s2 ; Minimum possible value is ceil ( d / 2 ) if it is not possible then - 1 ; Case 2 when K is less equal d ; X show the modification such that this position only differ from only one string ; modify the position such that this differ from both S1 & S2 & decrease the T at each step ; Finding the character which is different from both S1 and S2 ; After we done T start modification to meet our requirement for X type ; Resultant string ; Case 1 when K > d In first step , modify all the character which are not same in S1 and S3 ; Finding character which is different from both S1 and S2 ; Our requirement not satisfied by performing step 1. We need to modify the position which matches in both string ; Finding the character which is different from both S1 and S2 ; Resultant string ; Driver Code ; Given two strings ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; char arr [ ] = { ' a ' , ' b ' , ' c ' } ; void findString ( int n , int k , string s1 , string s2 ) { string s3 = s2 ; int d = 0 ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) d ++ ; } if ( ( d + 1 ) / 2 > k ) { cout << " - 1" << endl ; return ; } else { if ( k <= d ) { int X = d - k ; int T = 2 * k - d ; for ( int i = 0 ; i < s3 . size ( ) ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) { if ( T > 0 ) { for ( int j = 0 ; j < 3 ; j ++ ) { if ( arr [ j ] != s1 [ i ] && arr [ j ] != s2 [ i ] ) { s3 [ i ] = arr [ j ] ; T -- ; break ; } } } else if ( X > 0 ) { s3 [ i ] = s1 [ i ] ; X -- ; } } } cout << s3 << endl ; } else { for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) { if ( s1 [ i ] != s3 [ i ] ) { for ( int j = 0 ; j < 3 ; j ++ ) { if ( arr [ j ] != s1 [ i ] && arr [ j ] != s3 [ i ] ) { s3 [ i ] = arr [ j ] ; k -- ; break ; } } } } for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) { if ( s1 [ i ] == s3 [ i ] && k ) { for ( int j = 0 ; j < 3 ; j ++ ) { if ( arr [ j ] != s1 [ i ] && arr [ j ] != s3 [ i ] ) { s3 [ i ] = arr [ j ] ; k -- ; break ; } } } } cout << s3 << endl ; } } } int main ( ) { int N = 4 , k = 2 ; string S1 = " zzyy " ; string S2 = " zxxy " ; findString ( N , k , S1 , S2 ) ; return 0 ; }
Count of pairs of integers whose difference of squares is equal to N | C ++ program for the above approach ; Function to find the integral solutions of the given equation ; Initialise count to 0 ; Iterate till sqrt ( N ) ; If divisor 's pair sum is even ; Print the total possible solutions ; Driver Code ; Given number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSolutions ( int N ) { int count = 0 ; for ( int i = 1 ; i <= sqrt ( N ) ; i ++ ) { if ( N % i == 0 ) { if ( ( i + N / i ) % 2 == 0 ) { count ++ ; } } } cout << 4 * count << endl ; } int main ( ) { int N = 80 ; findSolutions ( N ) ; return 0 ; }
Find the integral roots of a given Cubic equation | C ++ program for the above approach ; Function to find the value at x of the given equation ; Find the value equation at x ; Return the value of ans ; Function to find the integral solution of the given equation ; Initialise start and end ; Implement Binary Search ; Find mid ; Find the value of f ( x ) using current mid ; Check if current mid satisfy the equation ; Print mid and return ; Print " NA " if not found any integral solution ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int check ( int A , int B , int C , int D , long long int x ) { long long int ans ; ans = ( A * x * x * x + B * x * x + C * x + D ) ; return ans ; } void findSolution ( int A , int B , int C , int D , int E ) { int start = 0 , end = 100000 ; long long int mid , ans ; while ( start <= end ) { mid = start + ( end - start ) / 2 ; ans = check ( A , B , C , D , mid ) ; if ( ans == E ) { cout << mid << endl ; return ; } if ( ans < E ) start = mid + 1 ; else end = mid - 1 ; } cout << " NA " ; } int main ( ) { int A = 1 , B = 0 , C = 0 ; int D = 0 , E = 27 ; findSolution ( A , B , C , D , E ) ; }
Count of ordered triplets ( R , G , B ) in a given original string | C ++ code for the above program ; function to count the ordered triplets ( R , G , B ) ; count the B ( blue ) colour ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( string color ) { int result = 0 , Blue_Count = 0 ; int Red_Count = 0 ; for ( char c : color ) { if ( c == ' B ' ) Blue_Count ++ ; } for ( char c : color ) { if ( c == ' B ' ) Blue_Count -- ; if ( c == ' R ' ) Red_Count ++ ; if ( c == ' G ' ) result += Red_Count * Blue_Count ; } return result ; } int main ( ) { string color = " RRGGBBRGGBB " ; cout << countTriplets ( color ) ; return 0 ; }
Minimum value of K such that sum of cubes of first K natural number is greater than equal to N | C ++ program to determine the minimum value of K such that the sum of cubes of first K natural number is greater than or equal to N ; Function to determine the minimum value of K such that the sum of cubes of first K natural number is greater than or equal to N ; Variable to store the sum of cubes ; Loop to find the number K ; If C is just greater then N , then break the loop ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int naive_find_x ( int N ) { int c = 0 , i ; for ( i = 1 ; i < N ; i ++ ) { c += i * i * i ; if ( c >= N ) break ; } return i ; } int main ( ) { int N = 100 ; cout << naive_find_x ( N ) ; return 0 ; }
Minimum value of K such that sum of cubes of first K natural number is greater than equal to N | C ++ program to determine the minimum value of K such that the sum of cubes of first K natural number is greater than or equal to N ; Function to determine the minimum value of K such that the sum of cubes of first K natural number is greater than or equal to N ; Left bound ; Right bound ; Variable to store the answer ; Applying binary search ; Calculating mid value of the range ; If the sum of cubes of first mid natural numbers is greater than equal to N iterate the left half ; Sum of cubes of first mid natural numbers is less than N , then move to the right segment ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binary_searched_find_x ( int k ) { int l = 0 ; int r = k ; int ans = 0 ; while ( l <= r ) { int mid = l + ( r - l ) / 2 ; if ( pow ( ( ( mid * ( mid + 1 ) ) / 2 ) , 2 ) >= k ) { ans = mid ; r = mid - 1 ; } else { l = mid + 1 ; } } return ans ; } int main ( ) { int N = 100 ; cout << binary_searched_find_x ( N ) ; return 0 ; }
Length of the longest ZigZag subarray of the given array | C ++ implementation to find the length of longest zigzag subarray of the given array ; Function to find the length of longest zigZag contiguous subarray ; ' max ' to store the length of longest zigZag subarray ; ' len ' to store the lengths of longest zigZag subarray at different instants of time ; Traverse the array from the beginning ; Check if ' max ' length is less than the length of the current zigzag subarray . If true , then update ' max ' ; Reset ' len ' to 1 as from this element , again the length of the new zigzag subarray is being calculated ; comparing the length of the last zigzag subarray with ' max ' ; Return required maximum length ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lenOfLongZigZagArr ( int a [ ] , int n ) { int max = 1 , len = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( i % 2 == 0 && ( a [ i ] < a [ i + 1 ] ) ) len ++ ; else if ( i % 2 == 1 && ( a [ i ] > a [ i + 1 ] ) ) len ++ ; else { if ( max < len ) max = len ; len = 1 ; } } if ( max < len ) max = len ; return max ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << lenOfLongZigZagArr ( arr , n ) ; return 0 ; }
Check if a given number is a Perfect square using Binary Search | C ++ program to check if a given number is Perfect square using Binary Search ; function to check for perfect square number ; Find the mid value from start and last ; check if we got the number which is square root of the perfect square number N ; if the square ( mid ) is greater than N it means only lower values then mid will be possibly the square root of N ; if the square ( mid ) is less than N it means only higher values then mid will be possibly the square root of N ; Driver code
#include <iostream> NEW_LINE using namespace std ; int checkPerfectSquare ( long int N , long int start , long int last ) { long int mid = ( start + last ) / 2 ; if ( start > last ) { return -1 ; } if ( mid * mid == N ) { return mid ; } else if ( mid * mid > N ) { return checkPerfectSquare ( N , start , mid - 1 ) ; } else { return checkPerfectSquare ( N , mid + 1 , last ) ; } } int main ( ) { long int N = 65 ; cout << checkPerfectSquare ( N , 1 , N ) ; return 0 ; }
Maximum count number of valley elements in a subarray of size K | C ++ implementation to find the maximum number of valley elements in the subarrays of size K ; Function to find the valley elements in the array which contains in the subarrays of the size K ; Increment min_point if element at index i is smaller than element at index i + 1 and i - 1 ; final_point to maintain maximum of min points of subarray ; Iterate over array from kth element ; Leftmost element of subarray ; Rightmost element of subarray ; if new subarray have greater number of min points than previous subarray , then final_point is modified ; Max minimum points in subarray of size k ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minpoint ( int arr [ ] , int n , int k ) { int min_point = 0 ; for ( int i = 1 ; i < k - 1 ; i ++ ) { if ( arr [ i ] < arr [ i - 1 ] && arr [ i ] < arr [ i + 1 ] ) min_point += 1 ; } int final_point = min_point ; for ( int i = k ; i < n ; i ++ ) { if ( arr [ i - ( k - 1 ) ] < arr [ i - ( k - 1 ) + 1 ] && arr [ i - ( k - 1 ) ] < arr [ i - ( k - 1 ) - 1 ] ) min_point -= 1 ; if ( arr [ i - 1 ] < arr [ i ] && arr [ i - 1 ] < arr [ i - 2 ] ) min_point += 1 ; if ( min_point > final_point ) final_point = min_point ; } cout << ( final_point ) ; } int main ( ) { int arr [ ] = { 2 , 1 , 4 , 2 , 3 , 4 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 4 ; minpoint ( arr , n , k ) ; return 0 ; }
For each lowercase English alphabet find the count of strings having these alphabets | C ++ program to find count of strings for each letter [ a - z ] in english alphabet ; Function to find the countStrings for each letter [ a - z ] ; Initialize result as zero ; Mark all letter as not visited ; Loop through each strings ; Increment the global counter for current character of string ; Instead of re - initialising boolean vector every time we just reset all visited letter to false ; Print count for each letter ; Driver program ; Given array of strings ; Call the countStrings function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CountStrings ( vector < string > & str ) { int size = str . size ( ) ; vector < int > count ( 26 , 0 ) ; vector < bool > visited ( 26 , false ) ; for ( int i = 0 ; i < size ; ++ i ) { for ( int j = 0 ; j < str [ i ] . length ( ) ; ++ j ) { if ( visited [ str [ i ] [ j ] ] == false ) count [ str [ i ] [ j ] - ' a ' ] ++ ; visited [ str [ i ] [ j ] ] = true ; } for ( int j = 0 ; j < str [ i ] . length ( ) ; ++ j ) { visited [ str [ i ] [ j ] ] = false ; } } for ( int i = 0 ; i < 26 ; ++ i ) { cout << count [ i ] << " ▁ " ; } } int main ( ) { vector < string > str = { " i " , " will " , " practice " , " everyday " } ; CountStrings ( str ) ; return 0 ; }
Find subarray of Length K with Maximum Peak | C ++ implementation to Find subarray of Length K with Maximum Peak ; Function to find the subarray ; Make prefix array to store the prefix sum of peak count ; Count peak for previous index ; Check if this element is a peak ; Increment the count ; Check if number of peak in the sub array whose l = i is greater or not ; Print the result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findSubArray ( int * a , int n , int k ) { int pref [ n ] ; pref [ 0 ] = 0 ; for ( int i = 1 ; i < n - 1 ; ++ i ) { pref [ i ] = pref [ i - 1 ] ; if ( a [ i ] > a [ i - 1 ] && a [ i ] > a [ i + 1 ] ) pref [ i ] ++ ; } int peak = 0 , left = 0 ; for ( int i = 0 ; i + k - 1 < n ; ++ i ) if ( pref [ i + k - 2 ] - pref [ i ] > peak ) { peak = pref [ i + k - 2 ] - pref [ i ] ; left = i ; } cout << " Left ▁ = ▁ " << left + 1 << endl ; cout << " Right ▁ = ▁ " << left + k << endl ; cout << " Peak ▁ = ▁ " << peak << endl ; } int main ( ) { int arr [ ] = { 3 , 2 , 3 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; findSubArray ( arr , n , k ) ; return 0 ; }
Sort integers in array according to their distance from the element K | C ++ implementation to Sort the integers in array according to their distance from given element K present in the array ; Function to get sorted array based on their distance from given integer K ; Vector to store respective elements with their distance from integer K ; Find the position of integer K ; Insert the elements with their distance from K in vector ; Element at distance 0 ; Elements at left side of K ; Elements at right side of K ; Print the vector content in sorted order ; Sort elements at same distance ; Print elements at distance i from K ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void distanceSort ( int arr [ ] , int K , int n ) { vector < int > vd [ n ] ; int pos ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == K ) { pos = i ; break ; } } int i = pos - 1 , j = pos + 1 ; vd [ 0 ] . push_back ( arr [ pos ] ) ; while ( i >= 0 ) { vd [ pos - i ] . push_back ( arr [ i ] ) ; -- i ; } while ( j < n ) { vd [ j - pos ] . push_back ( arr [ j ] ) ; ++ j ; } for ( int i = 0 ; i <= max ( pos , n - pos - 1 ) ; ++ i ) { sort ( begin ( vd [ i ] ) , end ( vd [ i ] ) ) ; for ( auto element : vd [ i ] ) cout << element << " ▁ " ; } } int main ( ) { int arr [ ] = { 14 , 1101 , 10 , 35 , 0 } , K = 35 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; distanceSort ( arr , K , n ) ; return 0 ; }
Find Quotient and Remainder of two integer without using division operators | C ++ implementation to Find Quotient and Remainder of two integer without using / and % operator using Binary search ; Function to the quotient and remainder ; Check if start is greater than the end ; Calculate mid ; Check if n is greater than divisor then increment the mid by 1 ; Check if n is less than 0 then decrement the mid by 1 ; Check if n equals to divisor ; Return the final answer ; Recursive calls ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , int > find ( int dividend , int divisor , int start , int end ) { if ( start > end ) return { 0 , dividend } ; int mid = start + ( end - start ) / 2 ; int n = dividend - divisor * mid ; if ( n > divisor ) start = mid + 1 ; else if ( n < 0 ) end = mid - 1 ; else { if ( n == divisor ) { ++ mid ; n = 0 ; } return { mid , n } ; } return find ( dividend , divisor , start , end ) ; } pair < int , int > divide ( int dividend , int divisor ) { return find ( dividend , divisor , 1 , dividend ) ; } int main ( int argc , char * argv [ ] ) { int dividend = 10 , divisor = 3 ; pair < int , int > ans ; ans = divide ( dividend , divisor ) ; cout << ans . first << " , ▁ " ; cout << ans . second << endl ; return 0 ; }
Count the number of unordered triplets with elements in increasing order and product less than or equal to integer X | C ++ implementation to Count the number of unordered triplets such that the numbers are in increasing order and the product of them is less than or equal to integer X ; Function to count the number of triplets ; Iterate through all the triplets ; Rearrange the numbers in ascending order ; Check if the necessary conditions satisfy ; Increment count ; Return the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int a [ ] , int n , int x ) { int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { vector < int > temp ; temp . push_back ( a [ i ] ) ; temp . push_back ( a [ j ] ) ; temp . push_back ( a [ k ] ) ; sort ( temp . begin ( ) , temp . end ( ) ) ; if ( temp [ 0 ] < temp [ 1 ] && temp [ 1 ] < temp [ 2 ] && temp [ 0 ] * temp [ 1 ] * temp [ 2 ] <= x ) answer ++ ; } } } return answer ; } int main ( ) { int A [ ] = { 3 , 2 , 5 , 7 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int X = 42 ; cout << countTriplets ( A , N , X ) ; return 0 ; }
Largest value of x such that axx is N | C ++ implementation of the above approach ; Function to find log_b ( a ) ; Set two pointer for binary search ; Calculating number of digits of a * mid ^ mid in base b ; If number of digits > n we can simply ignore it and decrease our pointer ; if number of digits <= n , we can go higher to reach value exactly equal to n ; return the largest value of x ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double log ( int a , int b ) { return log10 ( a ) / log10 ( b ) ; } int get ( int a , int b , int n ) { int lo = 0 , hi = 1e6 ; int ans = 0 ; while ( lo <= hi ) { int mid = ( lo + hi ) / 2 ; int dig = ceil ( ( mid * log ( mid , b ) + log ( a , b ) ) ) ; if ( dig > n ) { hi = mid - 1 ; } else { ans = mid ; lo = mid + 1 ; } } return ans ; } int main ( ) { int a = 2 , b = 2 , n = 6 ; cout << get ( a , b , n ) << " STRNEWLINE " ; return 0 ; }
Maximum size square Sub | C ++ program for the above approach ; Function to find the maximum size of matrix with sum <= K ; N size of rows and M size of cols ; To store the prefix sum of matrix ; Create Prefix Sum ; Traverse each rows ; Update the prefix sum till index i x j ; To store the maximum size of matrix with sum <= K ; Traverse the sum matrix ; Index out of bound ; Maximum possible size of matrix ; Binary Search ; Find middle index ; Check whether sum <= K or not If Yes check for other half of the search ; Else check it in first half ; Update the maximum size matrix ; Print the final answer ; Driver Code ; Given target sum ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxMatrixSize ( vector < vector < int > > arr , int K ) { int i , j ; int n = arr . size ( ) ; int m = arr [ 0 ] . size ( ) ; int sum [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= m ; j ++ ) { if ( i == 0 j == 0 ) { sum [ i ] [ j ] = 0 ; continue ; } sum [ i ] [ j ] = arr [ i - 1 ] [ j - 1 ] + sum [ i - 1 ] [ j ] + sum [ i ] [ j - 1 ] - sum [ i - 1 ] [ j - 1 ] ; } } int ans = 0 ; for ( i = 1 ; i <= n ; i ++ ) { for ( j = 1 ; j <= m ; j ++ ) { if ( i + ans - 1 > n j + ans - 1 > m ) break ; int mid , lo = ans ; int hi = min ( n - i + 1 , m - j + 1 ) ; while ( lo < hi ) { mid = ( hi + lo + 1 ) / 2 ; if ( sum [ i + mid - 1 ] [ j + mid - 1 ] + sum [ i - 1 ] [ j - 1 ] - sum [ i + mid - 1 ] [ j - 1 ] - sum [ i - 1 ] [ j + mid - 1 ] <= K ) { lo = mid ; } else { hi = mid - 1 ; } } ans = max ( ans , lo ) ; } } cout << ans << endl ; } int main ( ) { vector < vector < int > > arr ; arr = { { 1 , 1 , 3 , 2 , 4 , 3 , 2 } , { 1 , 1 , 3 , 2 , 4 , 3 , 2 } , { 1 , 1 , 3 , 2 , 4 , 3 , 2 } } ; int K = 4 ; findMaxMatrixSize ( arr , K ) ; return 0 ; }
Rank of all elements in a Stream in descending order when they arrive | C ++ program to rank of all elements in a Stream in descending order when they arrive ; FindRank function to find rank ; Rank of first element is always 1 ; Iterate over array ; As element let say its rank is 1 ; Element is compared with previous elements ; If greater than previous than rank is incremented ; print rank ; Driver code ; array named arr ; length of arr
#include <iostream> NEW_LINE using namespace std ; void FindRank ( int arr [ ] , int length ) { cout << "1" << " ▁ " ; for ( int i = 1 ; i < length ; i ++ ) { int rank = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( arr [ j ] > arr [ i ] ) rank ++ ; } cout << rank << " ▁ " ; } } int main ( ) { int arr [ ] = { 88 , 14 , 69 , 30 , 29 , 89 } ; int len = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; FindRank ( arr , len ) ; return 0 ; }
Longest permutation subsequence in a given array | C ++ Program to find length of Longest Permutation Subsequence in a given array ; Function to find the longest permutation subsequence ; Map data structure to count the frequency of each element ; If frequency of element is 0 , then we can not move forward as every element should be present ; Increasing the length by one ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestPermutation ( int a [ ] , int n ) { map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) { freq [ a [ i ] ] ++ ; } int len = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( freq [ i ] == 0 ) { break ; } len ++ ; } return len ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 6 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestPermutation ( arr , n ) << " STRNEWLINE " ; return 0 ; }
Pair of fibonacci numbers with a given sum and minimum absolute difference | C ++ program to find the pair of Fibonacci numbers with a given sum and minimum absolute difference ; Hash to store all the Fibonacci numbers ; Function to generate fibonacci Series and create hash table to check Fibonacci numbers ; Adding the first two Fibonacci numbers into the Hash set ; Computing the remaining Fibonacci numbers based on the previous two numbers ; Function to find the pair of Fibonacci numbers with the given sum and minimum absolute difference ; Start from N / 2 such that the difference between i and N - i will be minimum ; If both ' i ' and ' sum ▁ - ▁ i ' are fibonacci numbers then print them and break the loop ; If there is no Fibonacci pair possible ; Driver code ; Generate the Fibonacci numbers ; Find the Fibonacci pair
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000005 NEW_LINE set < int > fib ; void fibonacci ( ) { int prev = 0 , curr = 1 , len = 2 ; fib . insert ( prev ) ; fib . insert ( curr ) ; while ( len <= MAX ) { int temp = curr + prev ; fib . insert ( temp ) ; prev = curr ; curr = temp ; len ++ ; } } void findFibonacci ( int N ) { for ( int i = N / 2 ; i > 1 ; i -- ) { if ( fib . find ( i ) != fib . end ( ) && fib . find ( N - i ) != fib . end ( ) ) { cout << i << " ▁ " << ( N - i ) << endl ; return ; } } cout << " - 1" << endl ; } int main ( ) { fibonacci ( ) ; int sum = 199 ; findFibonacci ( sum ) ; return 0 ; }
Check if sum of Fibonacci elements in an Array is a Fibonacci number or not | C ++ program to check whether the sum of fibonacci elements of the array is a Fibonacci number or not ; Hash to store the Fibonacci numbers up to Max ; Function to create the hash table to check Fibonacci numbers ; Inserting the first two Fibonacci numbers into the hash ; Add the remaining Fibonacci numbers based on the previous two numbers ; Function to check if the sum of Fibonacci numbers is Fibonacci or not ; Find the sum of all Fibonacci numbers ; Iterating through the array ; If the sum is Fibonacci then return true ; Driver code ; array of elements ; Creating a set containing all fibonacci numbers
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE #define MAX 100005 NEW_LINE using namespace std ; set < int > fibonacci ; void createHash ( ) { int prev = 0 , curr = 1 ; fibonacci . insert ( prev ) ; fibonacci . insert ( curr ) ; while ( curr <= MAX ) { int temp = curr + prev ; fibonacci . insert ( temp ) ; prev = curr ; curr = temp ; } } bool checkArray ( int arr [ ] , int n ) { ll sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( fibonacci . find ( arr [ i ] ) != fibonacci . end ( ) ) sum += arr [ i ] ; if ( fibonacci . find ( sum ) != fibonacci . end ( ) ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 8 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; createHash ( ) ; if ( checkArray ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count of numbers whose difference with Fibonacci count upto them is atleast K | C ++ program to find the count of numbers whose difference with Fibonacci count upto them is atleast K ; fibUpto [ i ] denotes the count of fibonacci numbers upto i ; Function to compute all the Fibonacci numbers and update fibUpto array ; Store the first two Fibonacci numbers ; Compute the Fibonacci numbers and store them in isFib array ; Compute fibUpto array ; Function to return the count of valid numbers ; Compute fibUpto array ; Binary search to find the minimum number that follows the condition ; Check if the number is valid , try to reduce it ; Ans is the minimum valid number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000005 ; int fibUpto [ MAX + 1 ] ; void compute ( int sz ) { bool isFib [ sz + 1 ] ; memset ( isFib , false , sizeof ( isFib ) ) ; int prev = 0 , curr = 1 ; isFib [ prev ] = isFib [ curr ] = true ; while ( curr <= sz ) { int temp = curr + prev ; isFib [ temp ] = true ; prev = curr ; curr = temp ; } fibUpto [ 0 ] = 1 ; for ( int i = 1 ; i <= sz ; i ++ ) { fibUpto [ i ] = fibUpto [ i - 1 ] ; if ( isFib [ i ] ) fibUpto [ i ] ++ ; } } int countOfNumbers ( int N , int K ) { compute ( N ) ; int low = 1 , high = N , ans = 0 ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; if ( mid - fibUpto [ mid ] >= K ) { ans = mid ; high = mid - 1 ; } else low = mid + 1 ; } return ( ans ? N - ans + 1 : 0 ) ; } int main ( ) { int N = 10 , K = 3 ; cout << countOfNumbers ( N , K ) ; }
Smallest Palindromic Subsequence of Even Length in Range [ L , R ] | C ++ program to find lexicographically smallest palindromic subsequence of even length ; Frequency array for each character ; Preprocess the frequency array calculation ; Frequency array to track each character in position ' i ' ; Calculating prefix sum over this frequency array to get frequency of a character in a range [ L , R ] . ; Util function for palindromic subsequences ; Find frequency of all characters ; For each character find it 's frequency in range [L, R] ; If frequency in this range is > 1 , then we must take this character , as it will give lexicographically smallest one ; There is no character in range [ L , R ] such that it 's frequency is > 1. ; Return the character 's value ; Function to find lexicographically smallest palindromic subsequence of even length ; Find in the palindromic subsequences ; No such subsequence exists ; Driver Code ; Function calls
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 100001 ; int f [ 26 ] [ N ] ; void precompute ( string s , int n ) { for ( int i = 0 ; i < n ; i ++ ) { f [ s [ i ] - ' a ' ] [ i ] ++ ; } for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { f [ i ] [ j ] += f [ i ] [ j - 1 ] ; } } } int palindromicSubsequencesUtil ( int L , int R ) { int c , ok = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { int cnt = f [ i ] [ R ] ; if ( L > 0 ) cnt -= f [ i ] [ L - 1 ] ; if ( cnt > 1 ) { ok = 1 ; c = i ; break ; } } if ( ok == 0 ) { return -1 ; } return c ; } void palindromicSubsequences ( int Q [ ] [ 2 ] , int l ) { for ( int i = 0 ; i < l ; i ++ ) { int x = palindromicSubsequencesUtil ( Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) ; if ( x == -1 ) { cout << -1 << " STRNEWLINE " ; } else { char c = ' a ' + x ; cout << c << c << " STRNEWLINE " ; } } } int main ( ) { string str = " dbdeke " ; int Q [ ] [ 2 ] = { { 0 , 5 } , { 1 , 5 } , { 1 , 3 } } ; int n = str . size ( ) ; int l = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; precompute ( str , n ) ; palindromicSubsequences ( Q , l ) ; return 0 ; }
Length of longest Fibonacci subarray formed by removing only one element | C ++ program to find length of the longest subarray with all fibonacci numbers ; Function to create hash table to check for Fibonacci numbers ; Insert first two fibnonacci numbers ; Summation of last two numbers ; Update the variable each time ; Function to find the longest fibonacci subarray ; Find maximum value in the array ; Creating a set containing Fibonacci numbers ; Left array is used to count number of continuous fibonacci numbers starting from left of current element ; Check if current element is a fibonacci number ; Right array is used to count number of continuous fibonacci numbers starting from right of current element ; Check if current element is a fibonacci number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100000 NEW_LINE void createHash ( set < int > & hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . insert ( prev ) ; hash . insert ( curr ) ; while ( curr <= maxElement ) { int temp = curr + prev ; hash . insert ( temp ) ; prev = curr ; curr = temp ; } } int longestFibSubarray ( int arr [ ] , int n ) { int max_val = * max_element ( arr , arr + n ) ; set < int > hash ; createHash ( hash , max_val ) ; int left [ n ] , right [ n ] ; int fibcount = 0 , res = -1 ; for ( int i = 0 ; i < n ; i ++ ) { left [ i ] = fibcount ; if ( hash . find ( arr [ i ] ) != hash . end ( ) ) { fibcount ++ ; } else fibcount = 0 ; } fibcount = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { right [ i ] = fibcount ; if ( hash . find ( arr [ i ] ) != hash . end ( ) ) { fibcount ++ ; } else fibcount = 0 ; } for ( int i = 0 ; i < n ; i ++ ) res = max ( res , left [ i ] + right [ i ] ) ; return res ; } int main ( ) { int arr [ ] = { 2 , 8 , 5 , 7 , 3 , 5 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestFibSubarray ( arr , n ) << endl ; return 0 ; }
Minimum window size containing atleast P primes in every window of given range | C ++ implementation to find the minimum window size in the range such that each window of that size contains atleast P primes ; Function to check that a number is a prime or not in O ( sqrt ( N ) ) ; Loop to check if any number number is divisible by any other number or not ; Function to check whether window size satisfies condition or not ; Loop to check each window of size have atleast P primes ; Checking condition using prefix sum ; Function to find the minimum window size possible for the given range in X and Y ; Prefix array ; Mark those numbers which are primes as 1 ; Convert to prefix sum ; Applying binary search over window size ; Check whether mid satisfies the condition or not ; If satisfies search in first half ; Else search in second half ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int N ) { if ( N < 2 ) return false ; if ( N < 4 ) return true ; if ( ( N & 1 ) == 0 ) return false ; if ( N % 3 == 0 ) return false ; int curr = 5 , s = sqrt ( N ) ; while ( curr <= s ) { if ( N % curr == 0 ) return false ; curr += 2 ; if ( N % curr == 0 ) return false ; curr += 4 ; } return true ; } bool check ( int s , int p , int prefix_sum [ ] , int n ) { bool satisfies = true ; for ( int i = 0 ; i < n ; i ++ ) { if ( i + s - 1 >= n ) break ; if ( prefix_sum [ i + s - 1 ] - ( i - 1 >= 0 ? prefix_sum [ i - 1 ] : 0 ) < p ) satisfies = false ; } return satisfies ; } int minimumWindowSize ( int x , int y , int p ) { int prefix_sum [ y - x + 1 ] = { 0 } ; for ( int i = x ; i <= y ; i ++ ) { if ( isPrime ( i ) ) prefix_sum [ i - x ] = 1 ; } for ( int i = 1 ; i < y - x + 1 ; i ++ ) prefix_sum [ i ] += prefix_sum [ i - 1 ] ; int low = 1 , high = y - x + 1 ; int mid ; while ( high - low > 1 ) { mid = ( low + high ) / 2 ; if ( check ( mid , p , prefix_sum , y - x + 1 ) ) { high = mid ; } else low = mid ; } if ( check ( low , p , prefix_sum , y - x + 1 ) ) return low ; return high ; } int main ( ) { int x = 12 ; int y = 42 ; int p = 3 ; cout << minimumWindowSize ( x , y , p ) ; return 0 ; }
XOR of pairwise sum of every unordered pairs in an array | C ++ implementation to find XOR of pairwise sum of every unordered pairs in an array ; Function to find XOR of pairwise sum of every unordered pairs ; Loop to choose every possible pairs in the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorOfSum ( int a [ ] , int n ) { int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) answer ^= ( a [ i ] + a [ j ] ) ; } return answer ; } int main ( ) { int n = 3 ; int A [ n ] = { 1 , 2 , 3 } ; cout << xorOfSum ( A , n ) ; return 0 ; }
Maximum size of square such that all submatrices of that size have sum less than K | C ++ implementation to find the maximum size square submatrix such that their sum is less than K ; Size of matrix ; Function to preprocess the matrix for computing the sum of every possible matrix of the given size ; Loop to copy the first row of the matrix into the aux matrix ; Computing the sum column - wise ; Computing row wise sum ; Function to find the sum of a submatrix with the given indices ; Overall sum from the top to right corner of matrix ; Removing the sum from the top corer of the matrix ; Remove the overlapping sum ; Add the sum of top corner which is subtracted twice ; Function to find the maximum square size possible with the such that every submatrix have sum less than the given sum ; Loop to choose the size of matrix ; Loop to find the sum of the matrix of every possible submatrix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE #define M 5 NEW_LINE void preProcess ( int mat [ N ] [ M ] , int aux [ N ] [ M ] ) { for ( int i = 0 ; i < M ; i ++ ) aux [ 0 ] [ i ] = mat [ 0 ] [ i ] ; for ( int i = 1 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) aux [ i ] [ j ] = mat [ i ] [ j ] + aux [ i - 1 ] [ j ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 1 ; j < M ; j ++ ) aux [ i ] [ j ] += aux [ i ] [ j - 1 ] ; } int sumQuery ( int aux [ N ] [ M ] , int tli , int tlj , int rbi , int rbj ) { int res = aux [ rbi ] [ rbj ] ; if ( tli > 0 ) res = res - aux [ tli - 1 ] [ rbj ] ; if ( tlj > 0 ) res = res - aux [ rbi ] [ tlj - 1 ] ; if ( tli > 0 && tlj > 0 ) res = res + aux [ tli - 1 ] [ tlj - 1 ] ; return res ; } int maximumSquareSize ( int mat [ N ] [ M ] , int K ) { int aux [ N ] [ M ] ; preProcess ( mat , aux ) ; for ( int i = min ( N , M ) ; i >= 1 ; i -- ) { bool satisfies = true ; for ( int x = 0 ; x < N ; x ++ ) { for ( int y = 0 ; y < M ; y ++ ) { if ( x + i - 1 <= N - 1 && y + i - 1 <= M - 1 ) { if ( sumQuery ( aux , x , y , x + i - 1 , y + i - 1 ) > K ) satisfies = false ; } } } if ( satisfies == true ) return ( i ) ; } return 0 ; } int main ( ) { int K = 30 ; int mat [ N ] [ M ] = { { 1 , 2 , 3 , 4 , 6 } , { 5 , 3 , 8 , 1 , 2 } , { 4 , 6 , 7 , 5 , 5 } , { 2 , 4 , 8 , 9 , 4 } } ; cout << maximumSquareSize ( mat , K ) ; return 0 ; }
Find two Fibonacci numbers whose sum can be represented as N | C ++ program to find two Fibonacci numbers whose sum can be represented as N ; Function to create hash table to check Fibonacci numbers ; Storing the first two numbers in the hash ; Finding Fibonacci numbers up to N and storing them in the hash ; Function to find the Fibonacci pair with the given sum ; creating a set containing all fibonacci numbers ; Traversing all numbers to find first pair ; If both i and ( N - i ) are Fibonacci ; Printing the pair because i + ( N - i ) = N ; If no fibonacci pair is found whose sum is equal to n ; Driven code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void createHash ( set < int > & hash , int maxElement ) { int prev = 0 , curr = 1 ; hash . insert ( prev ) ; hash . insert ( curr ) ; while ( curr < maxElement ) { int temp = curr + prev ; hash . insert ( temp ) ; prev = curr ; curr = temp ; } } void findFibonacciPair ( int n ) { set < int > hash ; createHash ( hash , n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( hash . find ( i ) != hash . end ( ) && hash . find ( n - i ) != hash . end ( ) ) { cout << i << " , ▁ " << ( n - i ) << endl ; return ; } } cout << " - 1 STRNEWLINE " ; } int main ( ) { int N = 90 ; findFibonacciPair ( N ) ; return 0 ; }
Count of multiples in an Array before every element | C ++ program to count of multiples in an Array before every element ; Function to find all factors of N and keep their count in map ; Traverse from 1 to sqrt ( N ) if i divides N , increment i and N / i in map ; Function to count of multiples in an Array before every element ; To store factors all of all numbers ; Traverse for all possible i 's ; Printing value of a [ i ] in map ; Now updating the factors of a [ i ] in the map ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void add_factors ( int n , unordered_map < int , int > & mp ) { for ( int i = 1 ; i <= int ( sqrt ( n ) ) ; i ++ ) { if ( n % i == 0 ) { if ( n / i == i ) mp [ i ] ++ ; else { mp [ i ] ++ ; mp [ n / i ] ++ ; } } } } void count_divisors ( int a [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { cout << mp [ a [ i ] ] << " ▁ " ; add_factors ( a [ i ] , mp ) ; } } int main ( ) { int arr [ ] = { 8 , 1 , 28 , 4 , 2 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; count_divisors ( arr , n ) ; return 0 ; }
Reduce the array such that each element appears at most 2 times | C ++ program to reduce the array such that each element appears at most 2 times ; Function to remove duplicates ; Initialise 2 nd pointer ; Iterate over the array ; Updating the 2 nd pointer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void removeDuplicates ( int arr [ ] , int n ) { int st = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < n - 2 && arr [ i ] == arr [ i + 1 ] && arr [ i ] == arr [ i + 2 ] ) continue ; else { arr [ st ] = arr [ i ] ; st ++ ; } } cout << " { " ; for ( int i = 0 ; i < st ; i ++ ) { cout << arr [ i ] ; if ( i != st - 1 ) cout << " , ▁ " ; } cout << " } " ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 2 , 2 , 2 , 3 , 3 , 3 , 3 , 3 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; removeDuplicates ( arr , n ) ; return 0 ; }
Check if an Array is a permutation of numbers from 1 to N | C ++ Program to decide if an array represents a permutation or not ; Function to check if an array represents a permutation or not ; Set to check the count of non - repeating elements ; Insert all elements in the set ; Calculating the max element ; Check if set size is equal to n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool permutation ( int arr [ ] , int n ) { set < int > hash ; int maxEle = 0 ; for ( int i = 0 ; i < n ; i ++ ) { hash . insert ( arr [ i ] ) ; maxEle = max ( maxEle , arr [ i ] ) ; } if ( maxEle != n ) return false ; if ( hash . size ( ) == n ) return true ; return false ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; if ( permutation ( arr , n ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
D 'Esopo | C ++ implementation for D 'Esopo-Pape algorithm ; Number of vertices in graph ; Adjacency list of graph ; Queue to store unoperated vertices ; Distance from source vertex distance = [ float ( ' inf ' ) ] * v ; Status of vertex ; let 0 be the source vertex ; Pop from front of the queue ; Scan adjacent vertices of u ; e < - [ weight , vertex ] ; if e . second is entering first time in the queue ; Append at back of queue ; Append at front of queue ; Driver Code ; Adjacency matrix of graph
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define inf INT_MAX NEW_LINE vector < int > desopo ( vector < vector < int > > & graph ) { int v = graph . size ( ) ; map < int , vector < pair < int , int > > > adj ; for ( int i = 0 ; i < v ; i ++ ) { for ( int j = i + 1 ; j < v ; j ++ ) { if ( graph [ i ] [ j ] != 0 ) { adj [ i ] . push_back ( { graph [ i ] [ j ] , j } ) ; adj [ j ] . push_back ( { graph [ i ] [ j ] , i } ) ; } } } deque < int > q ; vector < int > distance ( v , inf ) ; vector < bool > is_in_queue ( v , false ) ; int source = 0 ; distance = 0 ; q . push_back ( source ) ; is_in_queue = true ; while ( ! q . empty ( ) ) { int u = q . front ( ) ; q . pop_front ( ) ; is_in_queue [ u ] = false ; for ( auto e : adj [ u ] ) { if ( distance [ e . second ] > distance [ u ] + e . first ) { distance [ e . second ] = distance [ u ] + e . first ; if ( ! is_in_queue [ e . second ] ) { if ( distance [ e . second ] == inf ) q . push_back ( e . second ) ; else q . push_front ( e . second ) ; is_in_queue [ e . second ] = true ; } } } } return distance ; } int main ( int argc , char const * argv [ ] ) { vector < vector < int > > graph = { { 0 , 4 , 0 , 0 , 8 } , { 0 , 0 , 8 , 0 , 11 } , { 0 , 8 , 0 , 2 , 0 } , { 0 , 0 , 2 , 0 , 1 } , { 8 , 11 , 0 , 1 , 0 } } ; for ( auto i : desopo ( graph ) ) { cout << i << " ▁ " ; } return 0 ; }
Count of Subsets of a given Set with element X present in it | C ++ code to implement the above approach ; N stores total number of subsets ; Generate each subset one by one ; Check every bit of i ; if j 'th bit of i is set, check arr[j] with X ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountSubSet ( int arr [ ] , int n , int X ) { int N = pow ( 2 , n ) ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i & ( 1 << j ) ) if ( arr [ j ] == X ) count += 1 ; } } return count ; } int main ( ) { int arr [ ] = { 4 , 5 , 6 , 7 } ; int X = 5 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountSubSet ( arr , n , X ) ; return 0 ; }
Count of Subsets of a given Set with element X present in it | C ++ implementation of above approach ; Function to calculate ( 2 ^ ( n - 1 ) ) ; Initially initialize answer to 1 ; If e is odd , multiply b with answer ; Function to count subsets in which X element is present ; Check if X is present in given subset or not ; If X is present in set then calculate 2 ^ ( n - 1 ) as count ; if X is not present in a given set ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculatePower ( int b , int e ) { int ans = 1 ; while ( e > 0 ) { if ( e % 2 == 1 ) ans = ans * b ; e = e / 2 ; b = b * b ; } return ans ; } int CountSubSet ( int arr [ ] , int n , int X ) { int count = 0 , checkX = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == X ) { checkX = 1 ; break ; } } if ( checkX == 1 ) count = calculatePower ( 2 , n - 1 ) ; else count = 0 ; return count ; } int main ( ) { int arr [ ] = { 4 , 5 , 6 , 7 } ; int X = 5 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountSubSet ( arr , n , X ) ; return 0 ; }
Value to be subtracted from array elements to make sum of all elements equals K | C ++ implementation of the approach ; Function to return the amount of wood collected if the cut is made at height m ; Function that returns Height at which cut should be made ; Sort the heights of the trees ; The minimum and the maximum cut that can be made ; Binary search to find the answer ; The amount of wood collected when cut is made at the mid ; If the current collected wood is equal to the required amount ; If it is more than the required amount then the cut needs to be made at a height higher than the current height ; Else made the cut at a lower height ; Driver code
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int woodCollected ( int height [ ] , int n , int m ) { int sum = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( height [ i ] - m <= 0 ) break ; sum += ( height [ i ] - m ) ; } return sum ; } int collectKWood ( int height [ ] , int n , int k ) { sort ( height , height + n ) ; int low = 0 , high = height [ n - 1 ] ; while ( low <= high ) { int mid = low + ( ( high - low ) / 2 ) ; int collected = woodCollected ( height , n , mid ) ; if ( collected == k ) return mid ; if ( collected > k ) low = mid + 1 ; else high = mid - 1 ; } return -1 ; } int main ( ) { int height [ ] = { 1 , 2 , 1 , 2 } ; int n = sizeof ( height ) / sizeof ( height [ 0 ] ) ; int k = 2 ; cout << collectKWood ( height , n , k ) ; return 0 ; }
Check if given string contains all the digits | C ++ implementation of the approach ; Function that returns true if ch is a digit ; Function that returns true if str contains all the digits from 0 to 9 ; To mark the present digits ; For every character of the string ; If the current character is a digit ; Mark the current digit as present ; For every digit from 0 to 9 ; If the current digit is not present in str ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10 ; bool isDigit ( char ch ) { if ( ch >= '0' && ch <= '9' ) return true ; return false ; } bool allDigits ( string str , int len ) { bool present [ MAX ] = { false } ; for ( int i = 0 ; i < len ; i ++ ) { if ( isDigit ( str [ i ] ) ) { int digit = str [ i ] - '0' ; present [ digit ] = true ; } } for ( int i = 0 ; i < MAX ; i ++ ) { if ( ! present [ i ] ) return false ; } return true ; } int main ( ) { string str = " Geeks12345for69708" ; int len = str . length ( ) ; if ( allDigits ( str , len ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check if a symmetric plus is possible from the elements of the given array | C ++ implementation of the approach ; Function that return true if a symmetric is possible with the elements of the array ; Map to store the frequency of the array elements ; Traverse through array elements and count frequencies ; For every unique element ; Element has already been found ; The frequency of the element something other than 0 and 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPlusPossible ( int arr [ ] , int n ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ arr [ i ] ] ++ ; bool foundModOne = false ; for ( auto x : mp ) { int element = x . first ; int frequency = x . second ; if ( frequency % 4 == 0 ) continue ; if ( frequency % 4 == 1 ) { if ( foundModOne ) return false ; foundModOne = true ; } else return false ; } } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 1 , 2 , 2 , 2 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( isPlusPossible ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Queries for elements greater than K in the given index range using Segment Tree | C ++ implementation of the approach ; Merge procedure to merge two vectors into a single vector ; Final vector to return after merging ; Loop continues until it reaches the end of one of the vectors ; Here , simply add the remaining elements to the vector v ; Procedure to build the segment tree ; Reached the leaf node of the segment tree ; Recursively call the buildTree on both the nodes of the tree ; Storing the final vector after merging the two of its sorted child vector ; Query procedure to get the answer for each query l and r are query range ; out of bound or no overlap ; Complete overlap Query range completely lies in the segment tree node range ; binary search to find index of k ; Partially overlap Query range partially lies in the segment tree node range ; Function to perform the queries ; Driver code ; 1 - based indexing ; Number of queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > merge ( vector < int > & v1 , vector < int > & v2 ) { int i = 0 , j = 0 ; vector < int > v ; while ( i < v1 . size ( ) && j < v2 . size ( ) ) { if ( v1 [ i ] <= v2 [ j ] ) { v . push_back ( v1 [ i ] ) ; i ++ ; } else { v . push_back ( v2 [ j ] ) ; j ++ ; } } for ( int k = i ; k < v1 . size ( ) ; k ++ ) v . push_back ( v1 [ k ] ) ; for ( int k = j ; k < v2 . size ( ) ; k ++ ) v . push_back ( v2 [ k ] ) ; return v ; } void buildTree ( vector < int > * tree , int * arr , int index , int s , int e ) { if ( s == e ) { tree [ index ] . push_back ( arr [ s ] ) ; return ; } int mid = ( s + e ) / 2 ; buildTree ( tree , arr , 2 * index , s , mid ) ; buildTree ( tree , arr , 2 * index + 1 , mid + 1 , e ) ; tree [ index ] = merge ( tree [ 2 * index ] , tree [ 2 * index + 1 ] ) ; } int query ( vector < int > * tree , int index , int s , int e , int l , int r , int k ) { if ( r < s l > e ) return 0 ; if ( s >= l && e <= r ) { return ( tree [ index ] . size ( ) - ( lower_bound ( tree [ index ] . begin ( ) , tree [ index ] . end ( ) , k ) - tree [ index ] . begin ( ) ) ) ; } int mid = ( s + e ) / 2 ; return ( query ( tree , 2 * index , s , mid , l , r , k ) + query ( tree , 2 * index + 1 , mid + 1 , e , l , r , k ) ) ; } void performQueries ( int L [ ] , int R [ ] , int K [ ] , int n , int q , vector < int > tree [ ] ) { for ( int i = 0 ; i < q ; i ++ ) { cout << query ( tree , 1 , 0 , n - 1 , L [ i ] - 1 , R [ i ] - 1 , K [ i ] ) << endl ; } } int main ( ) { int arr [ ] = { 7 , 3 , 9 , 13 , 5 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < int > tree [ 4 * n + 1 ] ; buildTree ( tree , arr , 1 , 0 , n - 1 ) ; int L [ ] = { 1 , 2 } ; int R [ ] = { 4 , 6 } ; int K [ ] = { 6 , 8 } ; int q = sizeof ( L ) / sizeof ( L [ 0 ] ) ; performQueries ( L , R , K , n , q , tree ) ; return 0 ; }
Queries for elements greater than K in the given index range using Segment Tree | C ++ implementation of the approach ; combine function to make parent node ; building the tree ; leaf node ; merging the nodes while backtracking . ; performing query ; Out of Bounds ; completely overlaps ; partially overlaps ; Driver Code ; 1 - based indexing
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > arr ( 1000000 ) , tree ( 4 * arr . size ( ) ) ; int combine ( int a , int b ) { if ( a != 0 && b != 0 ) { return a ; } if ( a >= b ) { return a ; } return b ; } void buildTree ( int ind , int low , int high , int x ) { if ( low == high ) { if ( arr [ low ] > x ) { tree [ ind ] = arr [ low ] ; } else { tree [ ind ] = 0 ; } return ; } int mid = ( low + high ) / 2 ; buildTree ( 2 * ind + 1 , low , mid , x ) ; buildTree ( 2 * ind + 2 , mid + 1 , high , x ) ; tree [ ind ] = combine ( tree [ 2 * ind + 1 ] , tree [ 2 * ind + 2 ] ) ; } int query ( int ind , int low , int high , int l , int r ) { int mid = ( low + high ) / 2 ; if ( low > r high < l ) { return 0 ; } if ( l <= low && r >= high ) { return tree [ ind ] ; } return combine ( query ( 2 * ind + 1 , low , mid , l , r ) , query ( 2 * ind + 2 , mid + 1 , high , l , r ) ) ; } int main ( ) { arr = { 7 , 3 , 9 , 13 , 5 , 4 } ; int n = 6 ; int k = 6 ; int l = 1 , r = 4 ; buildTree ( 0 , 0 , n - 1 , k ) ; cout << query ( 0 , 0 , n - 1 , l - 1 , r - 1 ) ; return 0 ; }
Calculate the Sum of GCD over all subarrays | C ++ program to find Sum of GCD over all subarrays . ; Utility function to calculate sum of gcd of all sub - arrays . ; Fixing the starting index of a subarray ; Fixing the ending index of a subarray ; Finding the GCD of this subarray ; Adding this GCD in our sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findGCDSum ( int n , int a [ ] ) { int GCDSum = 0 ; int tempGCD = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { tempGCD = 0 ; for ( int k = i ; k <= j ; k ++ ) { tempGCD = __gcd ( tempGCD , a [ k ] ) ; } GCDSum += tempGCD ; } } return GCDSum ; } int main ( ) { int n = 5 ; int a [ ] = { 1 , 2 , 3 , 4 , 5 } ; int totalSum = findGCDSum ( n , a ) ; cout << totalSum << " STRNEWLINE " ; }
Check if the array has an element which is equal to XOR of remaining elements | C ++ implementation of the approach ; Function that returns true if the array contains an element which is equal to the XOR of the remaining elements ; To store the XOR of all the array elements ; For every element of the array ; Take the XOR after excluding the current element ; If the XOR of the remaining elements is equal to the current element ; If no such element is found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool containsElement ( int arr [ ] , int n ) { int xorArr = 0 ; for ( int i = 0 ; i < n ; ++ i ) xorArr ^= arr [ i ] ; for ( int i = 0 ; i < n ; ++ i ) { int x = xorArr ^ arr [ i ] ; if ( arr [ i ] == x ) return true ; } return false ; } int main ( ) { int arr [ ] = { 8 , 2 , 4 , 15 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( containsElement ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find the winner of the match | Multiple Queries | C ++ program to find winner of the match ; Function to add edge between two nodes ; Function returns topological order of given graph ; Indeg vector will store indegrees of all vertices ; Answer vector will have our final topological order ; Visited will be true if that vertex has been visited ; q will store the vertices that have indegree equal to zero ; Iterate till queue is not empty ; Push the front of queue to answer ; For all neighbours of u , decrement their indegree value ; If indegree of any vertex becomes zero and it is not marked then push it to queue ; Mark this vertex as visited ; Return the resultant topological order ; Function to return the winner between u and v ; Player who comes first wins ; Driver code ; Total number of players ; Build the graph add ( adj , x , y ) means x wins over y ; Resultant topological order in topotable ; Queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; void add ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; } vector < int > topo ( vector < int > adj [ ] , int n ) { vector < int > indeg ( n , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( auto x : adj [ i ] ) indeg [ x ] ++ ; } vector < int > answer ; vector < bool > visited ( n , false ) ; queue < int > q ; for ( int i = 0 ; i < n ; i ++ ) { if ( indeg [ i ] == 0 ) { q . push ( i ) ; visited [ i ] = true ; } } while ( ! q . empty ( ) ) { int u = q . front ( ) ; answer . push_back ( u ) ; q . pop ( ) ; for ( auto x : adj [ u ] ) { indeg [ x ] -- ; if ( indeg [ x ] == 0 && ! visited [ x ] ) { q . push ( x ) ; visited [ x ] = true ; } } } return answer ; } int who_wins ( vector < int > topotable , int u , int v ) { for ( auto x : topotable ) { if ( x == u ) return u ; if ( x == v ) return v ; } } int main ( ) { vector < int > adj [ 10 ] ; int n = 7 ; add ( adj , 0 , 1 ) ; add ( adj , 0 , 2 ) ; add ( adj , 0 , 3 ) ; add ( adj , 1 , 5 ) ; add ( adj , 2 , 5 ) ; add ( adj , 3 , 4 ) ; add ( adj , 4 , 5 ) ; add ( adj , 6 , 0 ) ; vector < int > topotable = topo ( adj , n ) ; cout << who_wins ( topotable , 3 , 5 ) << endl ; cout << who_wins ( topotable , 1 , 2 ) << endl ; return 0 ; }
Square root of a number without using sqrt ( ) function | C ++ implementation of the approach ; Recursive function that returns square root of a number with precision upto 5 decimal places ; If mid itself is the square root , return mid ; If mul is less than n , recur second half ; Else recur first half ; Function to find the square root of n ; While the square root is not found ; If n is a perfect square ; Square root will lie in the interval i - 1 and i ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double Square ( double n , double i , double j ) { double mid = ( i + j ) / 2 ; double mul = mid * mid ; if ( ( mul == n ) || ( abs ( mul - n ) < 0.00001 ) ) return mid ; else if ( mul < n ) return Square ( n , mid , j ) ; else return Square ( n , i , mid ) ; } void findSqrt ( double n ) { double i = 1 ; bool found = false ; while ( ! found ) { if ( i * i == n ) { cout << fixed << setprecision ( 0 ) << i ; found = true ; } else if ( i * i > n ) { double res = Square ( n , i - 1 , i ) ; cout << fixed << setprecision ( 5 ) << res ; found = true ; } i ++ ; } } int main ( ) { double n = 3 ; findSqrt ( n ) ; return 0 ; }
Pair with largest sum which is less than K in the array | CPP program for the above approach ; Function to find max sum less than k ; Sort the array ; While l is less than r ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( vector < int > arr , int k ) { sort ( arr . begin ( ) , arr . end ( ) ) ; int n = arr . size ( ) , l = 0 , r = n - 1 , ans = 0 ; while ( l < r ) { if ( arr [ l ] + arr [ r ] < k ) { ans = max ( ans , arr [ l ] + arr [ r ] ) ; l ++ ; } else { r -- ; } } return ans ; } int main ( ) { vector < int > A = { 20 , 10 , 30 , 100 , 110 } ; int k = 85 ; cout << maxSum ( A , k ) << endl ; }
Length of longest substring having all characters as K | C ++ program for the above approach ; Function to find the length of longest sub - string having all characters same as character K ; Initialize variables ; Iterate till size of string ; Check if current character is K ; Assingning the max value to max_len ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int length_substring ( string S , char K ) { int curr_cnt = 0 , prev_cnt = 0 , max_len ; for ( int i = 0 ; i < S . size ( ) ; i ++ ) { if ( S [ i ] == K ) { curr_cnt += 1 ; } else { prev_cnt = max ( prev_cnt , curr_cnt ) ; curr_cnt = 0 ; } } prev_cnt = max ( prev_cnt , curr_cnt ) ; max_len = prev_cnt ; return max_len ; } int main ( ) { string S = " abcd1111aabc " ; char K = '1' ; cout << length_substring ( S , K ) ; return 0 ; }
Find a partition point in array to maximize its xor sum | CPP program to find partition point in array to maximize xor sum ; Function to find partition point in array to maximize xor sum ; Traverse through the array ; Calculate xor of elements left of index i including ith element ; Calculate xor of the elements right of index i ; Keep the maximum possible xor sum ; Return the 1 based index of the array ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Xor_Sum ( int arr [ ] , int n ) { int sum = 0 , index , left_xor = 0 , right_xor = 0 ; for ( int i = 0 ; i < n ; i ++ ) { left_xor = left_xor ^ arr [ i ] ; right_xor = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) { right_xor = right_xor ^ arr [ j ] ; } if ( left_xor + right_xor > sum ) { sum = left_xor + right_xor ; index = i ; } } return index + 1 ; } int main ( ) { int arr [ ] = { 1 , 4 , 6 , 3 , 8 , 13 , 34 , 2 , 21 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << Xor_Sum ( arr , n ) ; return 0 ; }
Find a partition point in array to maximize its xor sum | CPP program to find partition point in array to maximize xor sum ; Function to calculate Prefix Xor array ; Calculating prefix xor ; Function to find partition point in array to maximize xor sum ; To store prefix xor ; Compute the prefix xor ; To store sum and index ; Calculate the maximum sum that can be obtained splitting the array at some index i ; PrefixXor [ i ] = Xor of all arr elements till i ' th ▁ index ▁ PrefixXor [ n - 1 ] ▁ ▁ ^ ▁ PrefixXor [ i ] ▁ = ▁ Xor ▁ of ▁ all ▁ elements ▁ ▁ from ▁ i + 1' th index to n - 1 'th index ; Return the index ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void ComputePrefixXor ( int arr [ ] , int PrefixXor [ ] , int n ) { PrefixXor [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) PrefixXor [ i ] = PrefixXor [ i - 1 ] ^ arr [ i ] ; } int Xor_Sum ( int arr [ ] , int n ) { int PrefixXor [ n ] ; ComputePrefixXor ( arr , PrefixXor , n ) ; int sum = 0 , index ; for ( int i = 0 ; i < n ; i ++ ) { if ( PrefixXor [ i ] + ( PrefixXor [ n - 1 ] ^ PrefixXor [ i ] ) > sum ) { sum = PrefixXor [ i ] + ( PrefixXor [ n - 1 ] ^ PrefixXor [ i ] ) ; index = i ; } } return index + 1 ; } int main ( ) { int arr [ ] = { 1 , 4 , 6 , 3 , 8 , 13 , 34 , 2 , 21 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << Xor_Sum ( arr , n ) ; return 0 ; }
Strings from an array which are not prefix of any other string | C ++ implementation of the approach ; Trie node ; isEndOfWord is true if the node represents end of a word ; Returns new trie node ( initialized to NULLs ) ; Function to insert a string into trie ; While inerting a word make each isEndOfWord as false ; Check if this word is prefix of some already inserted word If it is then don 't insert this word ; If present word is not prefix of any other word then insert it ; Function to display words in Trie ; If node is leaf node , it indicates end of string , so a null character is added and string is displayed ; If NON NULL child is found add parent key to str and call the display function recursively for child node ; Driver code ; Construct trie
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int ALPHABET_SIZE = 26 ; struct TrieNode { struct TrieNode * children [ ALPHABET_SIZE ] ; bool isEndOfWord ; } ; struct TrieNode * getNode ( void ) { struct TrieNode * pNode = new TrieNode ; pNode -> isEndOfWord = false ; for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) pNode -> children [ i ] = NULL ; return pNode ; } void insert ( struct TrieNode * root , string key ) { struct TrieNode * pCrawl = root ; for ( int i = 0 ; i < key . length ( ) ; i ++ ) { int index = key [ i ] - ' a ' ; if ( ! pCrawl -> children [ index ] ) pCrawl -> children [ index ] = getNode ( ) ; pCrawl -> isEndOfWord = false ; pCrawl = pCrawl -> children [ index ] ; } int i ; for ( i = 0 ; i < 26 ; i ++ ) { if ( pCrawl -> children [ i ] ) { break ; } } if ( i == 26 ) { pCrawl -> isEndOfWord = true ; } } void display ( struct TrieNode * root , char str [ ] , int level ) { if ( root -> isEndOfWord ) { str [ level ] = ' \0' ; cout << str << endl ; } int i ; for ( i = 0 ; i < ALPHABET_SIZE ; i ++ ) { if ( root -> children [ i ] ) { str [ level ] = i + ' a ' ; display ( root -> children [ i ] , str , level + 1 ) ; } } } int main ( ) { string keys [ ] = { " apple " , " app " , " there " , " the " , " like " } ; int n = sizeof ( keys ) / sizeof ( string ) ; struct TrieNode * root = getNode ( ) ; for ( int i = 0 ; i < n ; i ++ ) insert ( root , keys [ i ] ) ; char str [ 100 ] ; display ( root , str , 0 ) ; return 0 ; }
Find the color of given node in an infinite binary tree | CPP program to find color of the node ; Function to find color of the node ; Maximum is to store maximum color ; Loop to check all the parent values to get maximum color ; Find the number into map and get maximum color ; Take the maximum color and assign into maximum variable ; Find parent index ; Return maximum color ; Function to build hash map with color ; To store color of each node ; For each number add a color number ; Assigning color ; Return hash map ; Driver code ; Build mapWithColor ; Print the maximum color
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findColor ( map < int , int > mapWithColor , int query ) { int maximum = 0 ; while ( query >= 1 ) { if ( mapWithColor . find ( query ) != mapWithColor . end ( ) ) { maximum = max ( maximum , mapWithColor [ query ] ) ; } if ( query % 2 == 1 ) query = ( query - 1 ) / 2 ; else query = query / 2 ; } return maximum ; } map < int , int > buildMapWithColor ( int arr [ ] , int n ) { map < int , int > mapWithColor ; for ( int i = 0 ; i < n ; i ++ ) { mapWithColor [ arr [ i ] ] = i + 1 ; } return mapWithColor ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 7 ; map < int , int > mapWithColor = buildMapWithColor ( arr , n ) ; cout << findColor ( mapWithColor , k ) ; return 0 ; }
Count of strings in the first array which are smaller than every string in the second array | C ++ implementation of the approach ; Function to count the number of smaller strings in A [ ] for every string in B [ ] ; Count the frequency of all characters ; Iterate for all possible strings in A [ ] ; Increase the frequency of every character ; Check for the smallest character 's frequency ; Get the smallest character frequency ; Insert it in the vector ; Sort the count of all the frequency of the smallest character in every string ; Iterate for every string in B [ ] ; Hash set every frequency 0 ; Count the frequency of every character ; Find the frequency of the smallest character ; Count the number of strings in A [ ] which has the frequency of the smaller character less than the frequency of the smaller character of the string in B [ ] ; Store the answer ; Function to print the answer ; Get the answer ; Print the number of strings for every answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE vector < int > findCount ( string a [ ] , string b [ ] , int n , int m ) { int freq [ MAX ] = { 0 } ; vector < int > smallestFreq ; for ( int i = 0 ; i < n ; i ++ ) { string s = a [ i ] ; memset ( freq , 0 , sizeof freq ) ; for ( int j = 0 ; j < s . size ( ) ; j ++ ) { freq [ s [ j ] - ' a ' ] ++ ; } for ( int j = 0 ; j < MAX ; j ++ ) { if ( freq [ j ] ) { smallestFreq . push_back ( freq [ j ] ) ; break ; } } } sort ( smallestFreq . begin ( ) , smallestFreq . end ( ) ) ; vector < int > ans ; for ( int i = 0 ; i < m ; i ++ ) { string s = b [ i ] ; memset ( freq , 0 , sizeof freq ) ; for ( int j = 0 ; j < s . size ( ) ; j ++ ) { freq [ s [ j ] - ' a ' ] ++ ; } int frequency = 0 ; for ( int j = 0 ; j < MAX ; j ++ ) { if ( freq [ j ] ) { frequency = freq [ j ] ; break ; } } int ind = lower_bound ( smallestFreq . begin ( ) , smallestFreq . end ( ) , frequency ) - smallestFreq . begin ( ) ; ans . push_back ( ind ) ; } return ans ; } void printAnswer ( string a [ ] , string b [ ] , int n , int m ) { vector < int > ans = findCount ( a , b , n , m ) ; for ( auto it : ans ) { cout << it << " ▁ " ; } } int main ( ) { string A [ ] = { " aaa " , " aa " , " bdc " } ; string B [ ] = { " cccch " , " cccd " } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int m = sizeof ( B ) / sizeof ( B [ 0 ] ) ; printAnswer ( A , B , n , m ) ; return 0 ; }
Find Leftmost and Rightmost node of BST from its given preorder traversal | C ++ program to find leftmost and rightmost node from given preorder sequence ; Function to return the leftmost and rightmost nodes of the BST whose preorder traversal is given ; Variables for finding minimum and maximum values of the array ; Update the minimum ; Update the maximum ; Print the values ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void LeftRightNode ( int preorder [ ] , int n ) { int min = INT_MAX , max = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { if ( min > preorder [ i ] ) min = preorder [ i ] ; if ( max < preorder [ i ] ) max = preorder [ i ] ; } cout << " Leftmost ▁ node ▁ is ▁ " << min << " STRNEWLINE " ; cout << " Rightmost ▁ node ▁ is ▁ " << max ; } int main ( ) { int preorder [ ] = { 3 , 2 , 1 , 5 , 4 } ; int n = 5 ; LeftRightNode ( preorder , n ) ; return 0 ; }
Find the position of the given row in a 2 | C ++ implementation of the approach ; Function that compares both the arrays and returns - 1 , 0 and 1 accordingly ; Return 1 if mid row is less than arr [ ] ; Return 1 if mid row is greater than arr [ ] ; Both the arrays are equal ; Function to find a row in the given matrix using binary search ; If current row is equal to the given array then return the row number ; If arr [ ] is greater , ignore left half ; If arr [ ] is smaller , ignore right half ; No valid row found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int m = 6 , n = 4 ; int compareRow ( int a1 [ ] , int a2 [ ] ) { for ( int i = 0 ; i < n ; i ++ ) { if ( a1 [ i ] < a2 [ i ] ) return 1 ; else if ( a1 [ i ] > a2 [ i ] ) return -1 ; } return 0 ; } int binaryCheck ( int ar [ ] [ n ] , int arr [ ] ) { int l = 0 , r = m - 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; int temp = compareRow ( ar [ mid ] , arr ) ; if ( temp == 0 ) return mid + 1 ; else if ( temp == 1 ) l = mid + 1 ; else r = mid - 1 ; } return -1 ; } int main ( ) { int mat [ m ] [ n ] = { { 0 , 0 , 1 , 0 } , { 10 , 9 , 22 , 23 } , { 40 , 40 , 40 , 40 } , { 43 , 44 , 55 , 68 } , { 81 , 73 , 100 , 132 } , { 100 , 75 , 125 , 133 } } ; int row [ n ] = { 10 , 9 , 22 , 23 } ; cout << binaryCheck ( mat , row ) ; return 0 ; }
Number of subarrays having absolute sum greater than K | Set | C ++ implementation of the above approach ; Function to find required value ; Variable to store final answer ; Loop to find prefix - sum ; Sorting prefix - sum array ; Loop to find upper_bound for each element ; Returning final answer ; Driver code ; Function to find required value
#include <bits/stdc++.h> NEW_LINE #define maxLen 30 NEW_LINE using namespace std ; int findCnt ( int arr [ ] , int n , int k ) { int ans = 0 ; for ( int i = 1 ; i < n ; i ++ ) { arr [ i ] += arr [ i - 1 ] ; if ( arr [ i ] > k or arr [ i ] < -1 * k ) ans ++ ; } if ( arr [ 0 ] > k arr [ 0 ] < -1 * k ) ans ++ ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) ans += n - ( upper_bound ( arr , arr + n , arr [ i ] + k ) - arr ) ; return ans ; } int main ( ) { int arr [ ] = { -1 , 4 , -5 , 6 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 0 ; cout << findCnt ( arr , n , k ) ; }
Number of intersections between two ranges | C ++ implementation of above approach ; Function to return total number of intersections ; Maximum possible number of intersections ; Store all starting points of type1 ranges ; Store all endpoints of type1 ranges ; Starting point of type2 ranges ; Ending point of type2 ranges ; Subtract those ranges which are starting after R ; Subtract those ranges which are ending before L ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int FindIntersection ( pair < int , int > type1 [ ] , int n , pair < int , int > type2 [ ] , int m ) { int ans = n * m ; vector < int > start , end ; for ( int i = 0 ; i < n ; i ++ ) { start . push_back ( type1 [ i ] . first ) ; end . push_back ( type1 [ i ] . second ) ; } sort ( start . begin ( ) , start . end ( ) ) ; sort ( end . begin ( ) , end . end ( ) ) ; for ( int i = 0 ; i < m ; i ++ ) { int L = type2 [ i ] . first ; int R = type2 [ i ] . second ; ans -= ( start . end ( ) - upper_bound ( start . begin ( ) , start . end ( ) , R ) ) ; ans -= ( upper_bound ( end . begin ( ) , end . end ( ) , L - 1 ) - end . begin ( ) ) ; } return ans ; } int main ( ) { pair < int , int > type1 [ ] = { { 1 , 2 } , { 2 , 3 } , { 4 , 5 } , { 6 , 7 } } ; pair < int , int > type2 [ ] = { { 1 , 5 } , { 2 , 3 } , { 4 , 7 } , { 5 , 7 } } ; int n = sizeof ( type1 ) / ( sizeof ( type1 [ 0 ] ) ) ; int m = sizeof ( type2 ) / sizeof ( type2 [ 0 ] ) ; cout << FindIntersection ( type1 , n , type2 , m ) ; return 0 ; }
Find the Nth term divisible by a or b or c | C ++ implementation of the approach ; Function to return gcd of a and b ; Function to return the lcm of a and b ; Function to return the count of numbers from 1 to num which are divisible by a , b or c ; Calculate number of terms divisible by a and by b and by c then , remove the terms which is are divisible by both a and b , both b and c , both c and a and then add which are divisible by a and b and c ; Function to find the nth term divisible by a , b or c by using binary search ; Set low to 1 and high to max ( a , b , c ) * n ; 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 lcm ( int a , int b ) { return ( a * b ) / gcd ( a , b ) ; } int divTermCount ( int a , int b , int c , int num ) { return ( ( num / a ) + ( num / b ) + ( num / c ) - ( num / lcm ( a , b ) ) - ( num / lcm ( b , c ) ) - ( num / lcm ( a , c ) ) + ( num / lcm ( a , lcm ( b , c ) ) ) ) ; } int findNthTerm ( int a , int b , int c , int n ) { int low = 1 , high = INT_MAX , mid ; while ( low < high ) { mid = low + ( high - low ) / 2 ; if ( divTermCount ( a , b , c , mid ) < n ) low = mid + 1 ; else high = mid ; } return low ; } int main ( ) { int a = 2 , b = 3 , c = 5 , n = 10 ; cout << findNthTerm ( a , b , c , n ) ; return 0 ; }
Split the given array into K sub | C ++ implementation of the above approach ; Function to check if mid can be maximum sub - arrays sum ; If individual element is greater maximum possible sum ; Increase sum of current sub - array ; If the sum is greater than mid increase count ; Check condition ; Function to find maximum subarray sum which is minimum ; int start = * max ; Max subarray sum , considering subarray of length 1 ; end += array [ i ] ; Max subarray sum , considering subarray of length n ; Answer stores possible maximum sub array sum ; If mid is possible solution Put answer = mid ; ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int mid , int array [ ] , int n , int K ) { int count = 0 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( array [ i ] > mid ) return false ; sum += array [ i ] ; if ( sum > mid ) { count ++ ; sum = array [ i ] ; } } count ++ ; if ( count <= K ) return true ; return false ; } int solve ( int array [ ] , int n , int K ) { int * max = max_element ( array , array + n ) ; int end = 0 ; for ( int i = 0 ; i < n ; i ++ ) { } int answer = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( check ( mid , array , n , K ) ) { answer = mid ; end = mid - 1 ; } else { start = mid + 1 ; } } return answer ; } int main ( ) { int array [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( array ) / sizeof ( array [ 0 ] ) ; int K = 3 ; cout << solve ( array , n , K ) ; }
Count number of common elements between two arrays by using Bitset and Bitwise operation | C ++ implementation of the approach ; Function to return the count of common elements ; Traverse the first array ; Set 1 at position a [ i ] ; Traverse the second array ; Set 1 at position b [ i ] ; Bitwise AND of both the bitsets ; Find the count of 1 's ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100000 NEW_LINE bitset < MAX > bit1 , bit2 , bit3 ; int count_common ( int a [ ] , int n , int b [ ] , int m ) { for ( int i = 0 ; i < n ; i ++ ) { bit1 . set ( a [ i ] ) ; } for ( int i = 0 ; i < m ; i ++ ) { bit2 . set ( b [ i ] ) ; } bit3 = bit1 & bit2 ; int count = bit3 . count ( ) ; return count ; } int main ( ) { int a [ ] = { 1 , 4 , 7 , 2 , 3 } ; int b [ ] = { 2 , 11 , 7 , 4 , 15 , 20 , 24 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; cout << count_common ( a , n , b , m ) ; return 0 ; }
Create a Sorted Array Using Binary Search | C ++ program to create a sorted array using Binary Search ; Function to create a new sorted array using Binary Search ; Auxiliary Array ; if b is empty any element can be at first place ; Perform Binary Search to find the correct position of current element in the new array ; let the element should be at first index ; if a [ j ] is already present in the new array ; add a [ j ] at mid + 1. you can add it at mid ; if a [ j ] is lesser than b [ mid ] go right side ; means pos should be between start and mid - 1 ; else pos should be between mid + 1 and end ; if a [ j ] is the largest push it at last ; here max ( 0 , pos ) is used because sometimes pos can be negative as smallest duplicates can be present in the array ; Print the new generated sorted array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void createSorted ( int a [ ] , int n ) { vector < int > b ; for ( int j = 0 ; j < n ; j ++ ) { if ( b . empty ( ) ) b . push_back ( a [ j ] ) ; else { int start = 0 , end = b . size ( ) - 1 ; int pos = 0 ; while ( start <= end ) { int mid = start + ( end - start ) / 2 ; if ( b [ mid ] == a [ j ] ) { b . emplace ( b . begin ( ) + max ( 0 , mid + 1 ) , a [ j ] ) ; break ; } else if ( b [ mid ] > a [ j ] ) pos = end = mid - 1 ; else pos = start = mid + 1 ; if ( start > end ) { pos = start ; b . emplace ( b . begin ( ) + max ( 0 , pos ) , a [ j ] ) ; break ; } } } } for ( int i = 0 ; i < n ; i ++ ) cout << b [ i ] << " ▁ " ; } int main ( ) { int a [ ] = { 2 , 5 , 4 , 9 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; createSorted ( a , n ) ; return 0 ; }
Largest sub | C ++ implementation of the approach ; Function that return true if frequency of all the present characters is at least k ; If the character is present and its frequency is less than k ; Function to set every frequency to zero ; Function to return the length of the longest sub - string such that it contains every character at least k times ; To store the required maximum length ; Starting index of the sub - string ; Ending index of the sub - string ; If the frequency of every character of the current sub - string is at least k ; Update the maximum possible length ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE bool atLeastK ( int freq [ ] , int k ) { for ( int i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] != 0 && freq [ i ] < k ) return false ; } return true ; } void setZero ( int freq [ ] ) { for ( int i = 0 ; i < MAX ; i ++ ) freq [ i ] = 0 ; } int findlength ( string str , int n , int k ) { int maxLen = 0 ; int freq [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { setZero ( freq ) ; for ( int j = i ; j < n ; j ++ ) { freq [ str [ j ] - ' a ' ] ++ ; if ( atLeastK ( freq , k ) ) { maxLen = max ( maxLen , j - i + 1 ) ; } } } return maxLen ; } int main ( ) { string str = " xyxyyz " ; int n = str . length ( ) ; int k = 2 ; cout << findlength ( str , n , k ) ; return 0 ; }
Minimum increments to convert to an array of consecutive integers | C ++ implementation of the approach ; Function that return true if the required array can be generated with m as the last element ; Build the desired array ; Check if the given array can be converted to the desired array with the given operation ; Function to return the minimum number of operations required to convert the given array to an increasing AP series with common difference as 1 ; Apply Binary Search ; If array can be generated with mid as the last element ; Current ans is mid ; Check whether the same can be achieved with even less operations ; Build the desired array ; Calculate the number of operations required ; Return the number of operations required ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int m , int n , int arr [ ] ) { int desired [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { desired [ i ] = m ; m -- ; } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > desired [ i ] desired [ i ] < 1 ) { return false ; } } return true ; } int minOperations ( int arr [ ] , int n ) { int start = ( int ) arr [ n - 1 ] ; int end = * ( max_element ( arr , arr + n ) ) + n ; int max_arr = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( check ( mid , n , arr ) ) { max_arr = mid ; end = mid - 1 ; } else { start = mid + 1 ; } } int desired [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { desired [ i ] = max_arr ; max_arr -- ; } int operations = 0 ; for ( int i = 0 ; i < n ; i ++ ) { operations += ( desired [ i ] - arr [ i ] ) ; } return operations ; } int main ( ) { int arr [ ] = { 4 , 4 , 5 , 5 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperations ( arr , n ) ; return 0 ; }
Count duplicates in a given linked list | C ++ implementation of the approach ; Representation of node ; Function to insert a node at the beginning ; Function to count the number of duplicate nodes in the linked list ; Create a hash table insert head ; Traverse through remaining nodes ; Return the count of duplicate nodes ; Driver code
#include <iostream> NEW_LINE #include <unordered_set> NEW_LINE using namespace std ; struct Node { int data ; Node * next ; } ; void insert ( Node * * head , int item ) { Node * temp = new Node ( ) ; temp -> data = item ; temp -> next = * head ; * head = temp ; } int countNode ( Node * head ) { if ( head == NULL ) return 0 ; ; unordered_set < int > s ; s . insert ( head -> data ) ; int count = 0 ; for ( Node * curr = head -> next ; curr != NULL ; curr = curr -> next ) { if ( s . find ( curr -> data ) != s . end ( ) ) count ++ ; s . insert ( curr -> data ) ; } return count ; } int main ( ) { Node * head = NULL ; insert ( & head , 5 ) ; insert ( & head , 7 ) ; insert ( & head , 5 ) ; insert ( & head , 1 ) ; insert ( & head , 7 ) ; cout << countNode ( head ) ; return 0 ; }
Minimize the number of steps required to reach the end of the array | Set 2 | C ++ implementation of the approach ; Function to return the minimum steps required to reach the end of the given array ; Array to determine whether a cell has been visited before ; Queue for bfs ; Push the source i . e . index 0 ; Variable to store the depth of search ; BFS algorithm ; Current queue size ; Top - most element of queue ; Base case ; If we reach the destination i . e . index ( n - 1 ) ; Marking the cell visited ; Pushing the adjacent nodes i . e . indices reachable from the current index ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( int arr [ ] , int n ) { bool v [ n ] = { 0 } ; queue < int > q ; q . push ( 0 ) ; int depth = 0 ; while ( q . size ( ) != 0 ) { int x = q . size ( ) ; while ( x -- ) { int i = q . front ( ) ; q . pop ( ) ; if ( v [ i ] ) continue ; if ( i == n - 1 ) return depth ; v [ i ] = 1 ; if ( i + arr [ i ] < n ) q . push ( i + arr [ i ] ) ; if ( i - arr [ i ] >= 0 ) q . push ( i - arr [ i ] ) ; } depth ++ ; } return -1 ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; cout << minSteps ( arr , n ) ; return 0 ; }
Find the winner of the game based on greater number of divisors | C ++ implementation of the approach ; Function to return the count of divisors of elem ; Function to return the winner of the game ; Convert every element of A [ ] to their divisor count ; Convert every element of B [ ] to their divisor count ; Sort both the arrays ; For every element of A apply Binary Search to find number of pairs where A wins ; B wins if A doesnot win ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE int divisorcount ( int elem ) { int ans = 0 ; for ( int i = 1 ; i <= sqrt ( elem ) ; i ++ ) { if ( elem % i == 0 ) { if ( i * i == elem ) ans ++ ; else ans += 2 ; } } return ans ; } string findwinner ( int A [ ] , int B [ ] , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { A [ i ] = divisorcount ( A [ i ] ) ; } for ( int i = 0 ; i < M ; i ++ ) { B [ i ] = divisorcount ( B [ i ] ) ; } sort ( A , A + N ) ; sort ( B , B + M ) ; int winA = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int val = A [ i ] ; int start = 0 ; int end = M - 1 ; int index = -1 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; if ( B [ mid ] <= val ) { index = mid ; start = mid + 1 ; } else { end = mid - 1 ; } } winA += ( index + 1 ) ; } int winB = N * M - winA ; if ( winA > winB ) { return " A " ; } else if ( winB > winA ) { return " B " ; } return " Draw " ; } int main ( ) { int A [ ] = { 4 , 12 , 24 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int B [ ] = { 25 , 28 , 13 , 45 } ; int M = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << findwinner ( A , B , N , M ) ; return 0 ; }
Minimum time required to transport all the boxes from source to the destination under the given constraints | C ++ implementation of the approach ; Function that returns true if it is possible to transport all the boxes in the given amount of time ; If all the boxes can be transported in the given time ; If all the boxes can 't be transported in the given time ; Function to return the minimum time required ; Sort the two arrays ; Stores minimum time in which all the boxes can be transported ; Check for the minimum time in which all the boxes can be transported ; If it is possible to transport all the boxes in mid amount of time ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int box [ ] , int truck [ ] , int n , int m , int min_time ) { int temp = 0 ; int count = 0 ; while ( count < m ) { for ( int j = 0 ; j < min_time && temp < n && truck [ count ] >= box [ temp ] ; j += 2 ) temp ++ ; count ++ ; } if ( temp == n ) return true ; return false ; } int minTime ( int box [ ] , int truck [ ] , int n , int m ) { sort ( box , box + n ) ; sort ( truck , truck + m ) ; int l = 0 ; int h = 2 * n ; int min_time = 0 ; while ( l <= h ) { int mid = ( l + h ) / 2 ; if ( isPossible ( box , truck , n , m , mid ) ) { min_time = mid ; h = mid - 1 ; } else l = mid + 1 ; } return min_time ; } int main ( ) { int box [ ] = { 10 , 2 , 16 , 19 } ; int truck [ ] = { 29 , 25 } ; int n = sizeof ( box ) / sizeof ( int ) ; int m = sizeof ( truck ) / sizeof ( int ) ; printf ( " % d " , minTime ( box , truck , n , m ) ) ; return 0 ; }
Maximum points covered after removing an Interval | C ++ implementation of the approach ; Function To find the required interval ; Total Count of covered numbers ; Array to store numbers that occur exactly in one interval till ith interval ; Calculate New count by removing all numbers in range [ l , r ] occurring exactly once ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; void solve ( int interval [ ] [ 2 ] , int N , int Q ) { int Mark [ Q ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) { int l = interval [ i ] [ 0 ] - 1 ; int r = interval [ i ] [ 1 ] - 1 ; for ( int j = l ; j <= r ; j ++ ) Mark [ j ] ++ ; } int count = 0 ; for ( int i = 0 ; i < Q ; i ++ ) { if ( Mark [ i ] ) count ++ ; } int count1 [ Q ] = { 0 } ; if ( Mark [ 0 ] == 1 ) count1 [ 0 ] = 1 ; for ( int i = 1 ; i < Q ; i ++ ) { if ( Mark [ i ] == 1 ) count1 [ i ] = count1 [ i - 1 ] + 1 ; else count1 [ i ] = count1 [ i - 1 ] ; } int maxindex ; int maxcoverage = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int l = interval [ i ] [ 0 ] - 1 ; int r = interval [ i ] [ 1 ] - 1 ; int elem1 ; if ( l != 0 ) elem1 = count1 [ r ] - count1 [ l - 1 ] ; else elem1 = count1 [ r ] ; if ( count - elem1 >= maxcoverage ) { maxcoverage = count - elem1 ; maxindex = i ; } } cout << " Maximum ▁ Coverage ▁ is ▁ " << maxcoverage << " ▁ after ▁ removing ▁ interval ▁ at ▁ index ▁ " << maxindex ; } int main ( ) { int interval [ ] [ 2 ] = { { 1 , 4 } , { 4 , 5 } , { 5 , 6 } , { 6 , 7 } , { 3 , 5 } } ; int N = sizeof ( interval ) / sizeof ( interval [ 0 ] ) ; int Q = 7 ; solve ( interval , N , Q ) ; return 0 ; }
Find the minimum of maximum length of a jump required to reach the last island in exactly k jumps | C ++ implementation of the approach ; Function that returns true if it is possible to reach end of the array in exactly k jumps ; Variable to store the number of steps required to reach the end ; If it is possible to reach the end in exactly k jumps ; Returns the minimum maximum distance required to reach the end of the array in exactly k jumps ; Stores the answer ; Binary search to calculate the result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int arr [ ] , int n , int dist , int k ) { int req = 0 ; int curr = 0 ; int prev = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( curr != n && arr [ curr ] - arr [ prev ] <= dist ) curr ++ ; req ++ ; if ( curr == n ) break ; prev = curr - 1 ; } if ( curr != n ) return false ; if ( req <= k ) return true ; return false ; } int minDistance ( int arr [ ] , int n , int k ) { int l = 0 ; int h = arr [ n - 1 ] ; int ans = 0 ; while ( l <= h ) { int m = ( l + h ) / 2 ; if ( isPossible ( arr , n , m , k ) ) { ans = m ; h = m - 1 ; } else l = m + 1 ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 15 , 36 , 43 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int k = 2 ; cout << minDistance ( arr , n , k ) ; return 0 ; }
Find the kth element in the series generated by the given N ranges | C ++ implementation of the approach ; Function to return the kth element of the required series ; To store the number of integers that lie upto the ith index ; Compute the number of integers ; Stores the index , lying from 1 to n , ; Using binary search , find the index in which the kth element will lie ; Find the position of the kth element in the interval in which it lies ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getKthElement ( int n , int k , int L [ ] , int R [ ] ) { int l = 1 ; int h = n ; int total [ n + 1 ] ; total [ 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { total [ i + 1 ] = total [ i ] + ( R [ i ] - L [ i ] ) + 1 ; } int index = -1 ; while ( l <= h ) { int m = ( l + h ) / 2 ; if ( total [ m ] > k ) { index = m ; h = m - 1 ; } else if ( total [ m ] < k ) l = m + 1 ; else { index = m ; break ; } } l = L [ index - 1 ] ; h = R [ index - 1 ] ; int x = k - total [ index - 1 ] ; while ( l <= h ) { int m = ( l + h ) / 2 ; if ( ( m - L [ index - 1 ] ) + 1 == x ) { return m ; } else if ( ( m - L [ index - 1 ] ) + 1 > x ) h = m - 1 ; else l = m + 1 ; } } int main ( ) { int L [ ] = { 1 , 8 , 21 } ; int R [ ] = { 4 , 10 , 23 } ; int n = sizeof ( L ) / sizeof ( int ) ; int k = 6 ; cout << getKthElement ( n , k , L , R ) ; return 0 ; }
Find minimum positive integer x such that a ( x ^ 2 ) + b ( x ) + c >= k | C ++ implementation of the approach ; Function to return the minimum positive integer satisfying the given equation ; Binary search to find the value of x ; Return the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumX ( int a , int b , int c , int k ) { int x = INT_MAX ; if ( k <= c ) return 0 ; int h = k - c ; int l = 0 ; while ( l <= h ) { int m = ( l + h ) / 2 ; if ( ( a * m * m ) + ( b * m ) > ( k - c ) ) { x = min ( x , m ) ; h = m - 1 ; } else if ( ( a * m * m ) + ( b * m ) < ( k - c ) ) l = m + 1 ; else return m ; } return x ; } int main ( ) { int a = 3 , b = 2 , c = 4 , k = 15 ; cout << MinimumX ( a , b , c , k ) ; return 0 ; }
Divide array into two parts with equal sum according to the given constraints | C ++ implementation of the approach ; Function that checks if the given conditions are satisfied ; To store the prefix sum of the array elements ; Sort the array ; Compute the prefix sum array ; Maximum element in the array ; Variable to check if there exists any number ; Stores the index of the largest number present in the array smaller than i ; Stores the index of the smallest number present in the array greater than i ; Find index of smallest number greater than i ; Find index of smallest number greater than i ; If there exists a number ; If no such number exists print no ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void IfExists ( int arr [ ] , int n ) { int sum [ n ] ; sort ( arr , arr + n ) ; sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) sum [ i ] = sum [ i - 1 ] + arr [ i ] ; int max = arr [ n - 1 ] ; bool flag = false ; for ( int i = 1 ; i <= max ; i ++ ) { int findex = 0 ; int lindex = 0 ; int l = 0 ; int r = n - 1 ; while ( l <= r ) { int m = ( l + r ) / 2 ; if ( arr [ m ] < i ) { findex = m ; l = m + 1 ; } else r = m - 1 ; } l = 1 ; r = n ; flag = false ; while ( l <= r ) { int m = ( r + l ) / 2 ; if ( arr [ m ] > i ) { lindex = m ; r = m - 1 ; } else l = m + 1 ; } if ( sum [ findex ] == sum [ n - 1 ] - sum [ lindex - 1 ] ) { flag = true ; break ; } } if ( flag ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 5 } ; int n = sizeof ( arr ) / sizeof ( int ) ; IfExists ( arr , n ) ; return 0 ; }
Find missing element in a sorted array of consecutive numbers | CPP implementation of the approach ; Function to return the missing element ; Check if middle element is consistent ; No inconsistency till middle elements When missing element is just after the middle element ; Move right ; Inconsistency found When missing element is just before the middle element ; Move left ; No missing element found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMissing ( int arr [ ] , int n ) { int l = 0 , h = n - 1 ; int mid ; while ( h > l ) { mid = l + ( h - l ) / 2 ; if ( arr [ mid ] - mid == arr [ 0 ] ) { if ( arr [ mid + 1 ] - arr [ mid ] > 1 ) return arr [ mid ] + 1 ; else { l = mid + 1 ; } } else { if ( arr [ mid ] - arr [ mid - 1 ] > 1 ) return arr [ mid ] - 1 ; else { h = mid - 1 ; } } } return -1 ; } int main ( ) { int arr [ ] = { -9 , -8 , -7 , -5 , -4 , -3 , -2 , -1 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( findMissing ( arr , n ) ) ; }
Find maximum sum taking every Kth element in the array | C ++ implementation of the approach ; Function to return the maximum sum for every possible sequence such that a [ i ] + a [ i + k ] + a [ i + 2 k ] + ... + a [ i + qk ] is maximized ; Initialize the maximum with the smallest value ; Find maximum from all sequences ; Sum of the sequence starting from index i ; Update maximum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int n , int K ) { int maximum = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { int sumk = 0 ; for ( int j = i ; j < n ; j += K ) sumk = sumk + arr [ j ] ; maximum = max ( maximum , sumk ) ; } return maximum ; } int main ( ) { int arr [ ] = { 3 , 6 , 4 , 7 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << maxSum ( arr , n , K ) ; return ( 0 ) ; }
Find the number of elements greater than k in a sorted array | C ++ implementation of the approach ; Function to return the count of elements from the array which are greater than k ; Stores the index of the left most element from the array which is greater than k ; Finds number of elements greater than k ; If mid element is greater than k update leftGreater and r ; If mid element is less than or equal to k update l ; Return the count of elements greater than k ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countGreater ( int arr [ ] , int n , int k ) { int l = 0 ; int r = n - 1 ; int leftGreater = n ; while ( l <= r ) { int m = l + ( r - l ) / 2 ; if ( arr [ m ] > k ) { leftGreater = m ; r = m - 1 ; } else l = m + 1 ; } return ( n - leftGreater ) ; } int main ( ) { int arr [ ] = { 3 , 3 , 4 , 7 , 7 , 7 , 11 , 13 , 13 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 7 ; cout << countGreater ( arr , n , k ) ; return 0 ; }
Count the number of operations required to reduce the given number | C ++ implementation of the approach ; To store the normalized value of all the operations ; Minimum possible value for a series of operations ; If k can be reduced with first ( i + 1 ) operations ; Impossible to reduce k ; Number of times all the operations can be performed on k without reducing it to <= 0 ; Perform operations ; Final check ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int operations ( int op [ ] , int n , int k ) { int i , count = 0 ; int nVal = 0 ; int minimum = INT_MAX ; for ( i = 0 ; i < n ; i ++ ) { nVal += op [ i ] ; minimum = min ( minimum , nVal ) ; if ( ( k + nVal ) <= 0 ) return ( i + 1 ) ; } if ( nVal >= 0 ) return -1 ; int times = ( k - abs ( minimum ) ) / abs ( nVal ) ; k = ( k - ( times * abs ( nVal ) ) ) ; count = ( times * n ) ; while ( k > 0 ) { for ( i = 0 ; i < n ; i ++ ) { k = k + op [ i ] ; count ++ ; if ( k <= 0 ) break ; } } return count ; } int main ( ) { int op [ ] = { -60 , 65 , -1 , 14 , -25 } ; int n = sizeof ( op ) / sizeof ( op [ 0 ] ) ; int k = 100000 ; cout << operations ( op , n , k ) << endl ; }
Uniform Binary Search | C ++ implementation of above approach ; lookup table ; create the lookup table for an array of length n ; power and count variable ; multiply by 2 ; initialize the lookup table ; binary search ; mid point of the array ; count ; if the value is found ; if value is less than the mid value ; if value is greater than the mid value ; main function ; create the lookup table ; print the position of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_SIZE = 1000 ; int lookup_table [ MAX_SIZE ] ; void create_table ( int n ) { int pow = 1 ; int co = 0 ; do { pow <<= 1 ; lookup_table [ co ] = ( n + ( pow >> 1 ) ) / pow ; } while ( lookup_table [ co ++ ] != 0 ) ; } int binary ( int arr [ ] , int v ) { int index = lookup_table [ 0 ] - 1 ; int co = 0 ; while ( lookup_table [ co ] != 0 ) { if ( v == arr [ index ] ) return index ; else if ( v < arr [ index ] ) index -= lookup_table [ ++ co ] ; else index += lookup_table [ ++ co ] ; } } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 6 , 7 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; create_table ( n ) ; cout << " Position ▁ of ▁ 3 ▁ in ▁ array ▁ = ▁ " << binary ( arr , 3 ) << endl ; return 0 ; }
Find the smallest number X such that X ! contains at least Y trailing zeros . | C ++ implementation of the approach ; Function to count the number of factors P in X ! ; Function to find the smallest X such that X ! contains Y trailing zeros ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countFactor ( int P , int X ) { if ( X < P ) return 0 ; return ( X / P + countFactor ( P , X / P ) ) ; } int findSmallestX ( int Y ) { int low = 0 , high = 5 * Y ; int N = 0 ; while ( low <= high ) { int mid = ( high + low ) / 2 ; if ( countFactor ( 5 , mid ) < Y ) { low = mid + 1 ; } else { N = mid ; high = mid - 1 ; } } return N ; } int main ( ) { int Y = 10 ; cout << findSmallestX ( Y ) ; return 0 ; }
Find maximum N such that the sum of square of first N natural numbers is not more than X | C ++ implementation of the approach ; Function to return the sum of the squares of first N natural numbers ; Function to return the maximum N such that the sum of the squares of first N natural numbers is not more than X ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int squareSum ( int N ) { int sum = ( int ) ( N * ( N + 1 ) * ( 2 * N + 1 ) ) / 6 ; return sum ; } int findMaxN ( int X ) { int low = 1 , high = 100000 ; int N = 0 ; while ( low <= high ) { int mid = ( high + low ) / 2 ; if ( squareSum ( mid ) <= X ) { N = mid ; low = mid + 1 ; } else high = mid - 1 ; } return N ; } int main ( ) { int X = 25 ; cout << findMaxN ( X ) ; return 0 ; }
Search an element in given N ranges | C ++ implementation of the approach ; Function to return the index of the range in which K lies and uses linear search ; Iterate and find the element ; If K lies in the current range ; K doesn 't lie in any of the given ranges ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumber ( pair < int , int > a [ ] , int n , int K ) { for ( int i = 0 ; i < n ; i ++ ) { if ( K >= a [ i ] . first && K <= a [ i ] . second ) return i ; } return -1 ; } int main ( ) { pair < int , int > a [ ] = { { 1 , 3 } , { 4 , 7 } , { 8 , 11 } } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 6 ; int index = findNumber ( a , n , k ) ; if ( index != -1 ) cout << index ; else cout << -1 ; return 0 ; }
Search an element in given N ranges | C ++ implementation of the approach ; Function to return the index of the range in which K lies and uses binary search ; Binary search ; Find the mid element ; If element is found ; Check in first half ; Check in second half ; Not found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumber ( pair < int , int > a [ ] , int n , int K ) { int low = 0 , high = n - 1 ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; if ( K >= a [ mid ] . first && K <= a [ mid ] . second ) return mid ; else if ( K < a [ mid ] . first ) high = mid - 1 ; else low = mid + 1 ; } return -1 ; } int main ( ) { pair < int , int > a [ ] = { { 1 , 3 } , { 4 , 7 } , { 8 , 11 } } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 6 ; int index = findNumber ( a , n , k ) ; if ( index != -1 ) cout << index ; else cout << -1 ; return 0 ; }
Two equal sum segment range queries | C ++ implementation of the approach ; Function to find the required prefix sum ; Function to hash all the values of prefix sum array in an unordered map ; Function to check if a range can be divided into two equal parts ; To store the value of sum of entire range ; If value of sum is odd ; To store p_arr [ l - 1 ] ; If the value exists in the map ; Driver code ; prefix - sum array ; Map to store the values of prefix - sum ; Perform queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; void prefixSum ( int * p_arr , int * arr , int n ) { p_arr [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) p_arr [ i ] = arr [ i ] + p_arr [ i - 1 ] ; } void hashPrefixSum ( int * p_arr , int n , unordered_set < int > & q ) { for ( int i = 0 ; i < n ; i ++ ) q . insert ( p_arr [ i ] ) ; } void canDivide ( int * p_arr , int n , unordered_set < int > & q , int l , int r ) { int sum ; if ( l == 0 ) sum = p_arr [ r ] ; else sum = p_arr [ r ] - p_arr [ l - 1 ] ; if ( sum % 2 == 1 ) { cout << " No " << endl ; return ; } int beg = 0 ; if ( l != 0 ) beg = p_arr [ l - 1 ] ; if ( q . find ( beg + sum / 2 ) != q . end ( ) ) cout << " Yes " << endl ; else cout << " No " << endl ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int p_arr [ n ] ; prefixSum ( p_arr , arr , n ) ; unordered_set < int > q ; hashPrefixSum ( p_arr , n , q ) ; canDivide ( p_arr , n , q , 0 , 1 ) ; canDivide ( p_arr , n , q , 1 , 3 ) ; canDivide ( p_arr , n , q , 1 , 2 ) ; return 0 ; }
Search element in a Spirally sorted Matrix | C ++ implementation of the above approach ; Function to return the ring , the number x belongs to . ; Returns - 1 if number x is smaller than least element of arr ; l and r represent the diagonal elements to search in ; Returns - 1 if number x is greater than the largest element of arr ; Function to perform binary search on an array sorted in increasing order l and r represent the left and right index of the row to be searched ; Function to perform binary search on a particular column of the 2D array t and b represent top and bottom rows ; Function to perform binary search on an array sorted in decreasing order ; Function to perform binary search on a particular column of the 2D array ; Function to find the position of the number x ; Finding the ring ; To store row and column ; Edge case if n is odd ; Check which of the 4 sides , the number x lies in ; Printing the position ; Driver code
#include <iostream> NEW_LINE #define n 4 NEW_LINE using namespace std ; int findRing ( int arr [ ] [ n ] , int x ) { if ( arr [ 0 ] [ 0 ] > x ) return -1 ; int l = 0 , r = ( n + 1 ) / 2 - 1 ; if ( n % 2 == 1 && arr [ r ] [ r ] < x ) return -1 ; if ( n % 2 == 0 && arr [ r + 1 ] [ r ] < x ) return -1 ; while ( l < r ) { int mid = ( l + r ) / 2 ; if ( arr [ mid ] [ mid ] <= x ) if ( mid == ( n + 1 ) / 2 - 1 arr [ mid + 1 ] [ mid + 1 ] > x ) return mid ; else l = mid + 1 ; else r = mid - 1 ; } return r ; } int binarySearchRowInc ( int arr [ ] [ n ] , int row , int l , int r , int x ) { while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( arr [ row ] [ mid ] == x ) return mid ; if ( arr [ row ] [ mid ] < x ) l = mid + 1 ; else r = mid - 1 ; } return -1 ; } int binarySearchColumnInc ( int arr [ ] [ n ] , int col , int t , int b , int x ) { while ( t <= b ) { int mid = ( t + b ) / 2 ; if ( arr [ mid ] [ col ] == x ) return mid ; if ( arr [ mid ] [ col ] < x ) t = mid + 1 ; else b = mid - 1 ; } return -1 ; } int binarySearchRowDec ( int arr [ ] [ n ] , int row , int l , int r , int x ) { while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( arr [ row ] [ mid ] == x ) return mid ; if ( arr [ row ] [ mid ] < x ) r = mid - 1 ; else l = mid + 1 ; } return -1 ; } int binarySearchColumnDec ( int arr [ ] [ n ] , int col , int t , int b , int x ) { while ( t <= b ) { int mid = ( t + b ) / 2 ; if ( arr [ mid ] [ col ] == x ) return mid ; if ( arr [ mid ] [ col ] < x ) b = mid - 1 ; else t = mid + 1 ; } return -1 ; } void spiralBinary ( int arr [ ] [ n ] , int x ) { int f1 = findRing ( arr , x ) ; int r , c ; if ( f1 == -1 ) { cout << " - 1" ; return ; } if ( n % 2 == 1 && f1 == ( n + 1 ) / 2 - 1 ) { cout << f1 << " ▁ " << f1 << endl ; return ; } if ( x < arr [ f1 ] [ n - f1 - 1 ] ) { c = binarySearchRowInc ( arr , f1 , f1 , n - f1 - 2 , x ) ; r = f1 ; } else if ( x < arr [ n - f1 - 1 ] [ n - f1 - 1 ] ) { c = n - f1 - 1 ; r = binarySearchColumnInc ( arr , n - f1 - 1 , f1 , n - f1 - 2 , x ) ; } else if ( x < arr [ n - f1 - 1 ] [ f1 ] ) { c = binarySearchRowDec ( arr , n - f1 - 1 , f1 + 1 , n - f1 - 1 , x ) ; r = n - f1 - 1 ; } else { r = binarySearchColumnDec ( arr , f1 , f1 + 1 , n - f1 - 1 , x ) ; c = f1 ; } if ( c == -1 r == -1 ) cout << " - 1" ; else cout << r << " ▁ " << c ; return ; } int main ( ) { int arr [ ] [ n ] = { { 1 , 2 , 3 , 4 } , { 12 , 13 , 14 , 5 } , { 11 , 16 , 15 , 6 } , { 10 , 9 , 8 , 7 } } ; spiralBinary ( arr , 7 ) ; return 0 ; }
Cost to make a string Panagram | Set 2 | C ++ implementation of the approach ; Function to return the cost to make str a Panagram ; Count the occurrences of each lowercase character ; To store the total gain ; If some character is missing , it has to be added at twice the cost ; If some character appears more than once , all of its occurrences except 1 can be traded for some gain ; If gain is more than the cost ; Return the total cost if gain < 0 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int costToPanagram ( string str , int cost [ ] ) { int i , n = str . length ( ) ; int occurrences [ 26 ] = { 0 } ; for ( i = 0 ; i < n ; i ++ ) occurrences [ str [ i ] - ' a ' ] ++ ; int gain = 0 ; for ( i = 0 ; i < 26 ; i ++ ) { if ( occurrences [ i ] == 0 ) gain -= ( 2 * cost [ i ] ) ; else if ( occurrences [ i ] > 1 ) gain += ( cost [ i ] * ( occurrences [ i ] - 1 ) ) ; } if ( gain >= 0 ) return 0 ; return ( gain * -1 ) ; } int main ( ) { int cost [ ] = { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } ; string str = " geeksforgeeks " ; cout << costToPanagram ( str , cost ) ; }
Weighted sum of the characters of a string in an array | Set 2 | C ++ implementation of the approach ; Function to return the required string score ; create a hash map of strings in str ; Store every string in the map along with its position in the array ; If given string is not present in str [ ] ; Multiply sum of alphabets with position ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int strScore ( string str [ ] , string s , int n ) { unordered_map < string , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ str [ i ] ] = i + 1 ; if ( m . find ( s ) == m . end ( ) ) return 0 ; int score = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) score += s [ i ] - ' a ' + 1 ; score = score * m [ s ] ; return score ; } int main ( ) { string str [ ] = { " geeksforgeeks " , " algorithms " , " stack " } ; string s = " algorithms " ; int n = sizeof ( str ) / sizeof ( str [ 0 ] ) ; int score = strScore ( str , s , n ) ; cout << score ; return 0 ; }
Number of subarrays have bitwise OR >= K | C ++ implementation of the approach ; Function to return the count of required sub - arrays ; Traverse sub - array [ i . . j ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubArrays ( const int * arr , int n , int K ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int bitwise_or = 0 ; for ( int k = i ; k <= j ; k ++ ) { bitwise_or = bitwise_or | arr [ k ] ; } if ( bitwise_or >= K ) count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 6 ; cout << countSubArrays ( arr , n , k ) ; return 0 ; }
Number of subarrays have bitwise OR >= K | C ++ implementation of the approach ; Function to build the segment tree ; Function to return the bitwise OR of segment [ L . . R ] ; Function to return the count of required sub - arrays ; Build segment tree ; Query segment tree for bitwise OR of sub - array [ i . . j ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 100002 NEW_LINE int tree [ 4 * N ] ; void build ( int * arr , int node , int start , int end ) { if ( start == end ) { tree [ node ] = arr [ start ] ; return ; } int mid = ( start + end ) >> 1 ; build ( arr , 2 * node , start , mid ) ; build ( arr , 2 * node + 1 , mid + 1 , end ) ; tree [ node ] = tree [ 2 * node ] | tree [ 2 * node + 1 ] ; } int query ( int node , int start , int end , int l , int r ) { if ( start > end start > r end < l ) { return 0 ; } if ( start >= l && end <= r ) { return tree [ node ] ; } int mid = ( start + end ) >> 1 ; int q1 = query ( 2 * node , start , mid , l , r ) ; int q2 = query ( 2 * node + 1 , mid + 1 , end , l , r ) ; return q1 | q2 ; } int countSubArrays ( int arr [ ] , int n , int K ) { build ( arr , 1 , 0 , n - 1 ) ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int bitwise_or = query ( 1 , 0 , n - 1 , i , j ) ; if ( bitwise_or >= K ) count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 6 ; cout << countSubArrays ( arr , n , k ) ; return 0 ; }
Number of subarrays have bitwise OR >= K | C ++ program to implement the above approach ; Function which builds the segment tree ; Function that returns bitwise OR of segment [ L . . R ] ; Function to count requisite number of subarrays ; Check for subarrays starting with index i ; If OR of subarray [ i . . mid ] >= K , then all subsequent subarrays will have OR >= K therefore reduce high to mid - 1 to find the minimal length subarray [ i . . mid ] having OR >= K ; Increase count with number of subarrays having OR >= K and starting with index i ; Driver code ; Build segment tree .
#include <bits/stdc++.h> NEW_LINE #define N 100002 NEW_LINE using namespace std ; int tree [ 4 * N ] ; void build ( int * arr , int node , int start , int end ) { if ( start == end ) { tree [ node ] = arr [ start ] ; return ; } int mid = ( start + end ) >> 1 ; build ( arr , 2 * node , start , mid ) ; build ( arr , 2 * node + 1 , mid + 1 , end ) ; tree [ node ] = tree [ 2 * node ] | tree [ 2 * node + 1 ] ; } int query ( int node , int start , int end , int l , int r ) { if ( start > end start > r end < l ) { return 0 ; } if ( start >= l && end <= r ) { return tree [ node ] ; } int mid = ( start + end ) >> 1 ; int q1 = query ( 2 * node , start , mid , l , r ) ; int q2 = query ( 2 * node + 1 , mid + 1 , end , l , r ) ; return q1 | q2 ; } int countSubArrays ( const int * arr , int n , int K ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int low = i , high = n - 1 , index = INT_MAX ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; if ( query ( 1 , 0 , n - 1 , i , mid ) >= K ) { index = min ( index , mid ) ; high = mid - 1 ; } else { low = mid + 1 ; } } if ( index != INT_MAX ) { count += n - index ; } } return count ; } int main ( ) { int arr [ ] = { 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; build ( arr , 1 , 0 , n - 1 ) ; int k = 6 ; cout << countSubArrays ( arr , n , k ) ; return 0 ; }
Occurrences of a pattern in binary representation of a number | C ++ program to find the number of times pattern p occurred in binary representation on n . ; Function to return the count of occurrence of pat in binary representation of n ; To store decimal value of the pattern ; To store a number that has all ones in its binary representation and length of ones equal to length of the pattern ; Find values of pattern_int and all_ones ; If the pattern occurs in the last digits of n ; Right shift n by 1 bit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPattern ( int n , string pat ) { int pattern_int = 0 ; int power_two = 1 ; int all_ones = 0 ; for ( int i = pat . length ( ) - 1 ; i >= 0 ; i -- ) { int current_bit = pat [ i ] - '0' ; pattern_int += ( power_two * current_bit ) ; all_ones = all_ones + power_two ; power_two = power_two * 2 ; } int count = 0 ; while ( n && n >= pattern_int ) { if ( ( n & all_ones ) == pattern_int ) { count ++ ; } n = n >> 1 ; } return count ; } int main ( ) { int n = 500 ; string pat = "10" ; cout << countPattern ( n , pat ) ; }
Pairs with same Manhattan and Euclidean distance | C ++ implementation of the above approach ; Function to return the number of non coincident pairs of points with manhattan distance equal to euclidean distance ; To store frequency of all distinct Xi ; To store Frequency of all distinct Yi ; To store Frequency of all distinct points ( Xi , Yi ) ; ; Hash xi coordinate ; Hash yi coordinate ; Hash the point ( xi , yi ) ; find pairs with same Xi ; calculate ( ( xFrequency ) C2 ) ; find pairs with same Yi ; calculate ( ( yFrequency ) C2 ) ; find pairs with same ( Xi , Yi ) ; calculate ( ( xyFrequency ) C2 ) ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findManhattanEuclidPair ( pair < int , int > arr [ ] , int n ) { map < int , int > X ; map < int , int > Y ; map < pair < int , int > , int > XY ; for ( int i = 0 ; i < n ; i ++ ) { int xi = arr [ i ] . first ; int yi = arr [ i ] . second ; X [ xi ] ++ ; Y [ yi ] ++ ; XY [ arr [ i ] ] ++ ; } int xAns = 0 , yAns = 0 , xyAns = 0 ; for ( auto xCoordinatePair : X ) { int xFrequency = xCoordinatePair . second ; int sameXPairs = ( xFrequency * ( xFrequency - 1 ) ) / 2 ; xAns += sameXPairs ; } for ( auto yCoordinatePair : Y ) { int yFrequency = yCoordinatePair . second ; int sameYPairs = ( yFrequency * ( yFrequency - 1 ) ) / 2 ; yAns += sameYPairs ; } for ( auto XYPair : XY ) { int xyFrequency = XYPair . second ; int samePointPairs = ( xyFrequency * ( xyFrequency - 1 ) ) / 2 ; xyAns += samePointPairs ; } return ( xAns + yAns - xyAns ) ; } int main ( ) { pair < int , int > arr [ ] = { { 1 , 2 } , { 2 , 3 } , { 1 , 3 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findManhattanEuclidPair ( arr , n ) << endl ; return 0 ; }
Remove exactly one element from the array such that max | C ++ implementation of the above approach ; function to calculate max - min ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_min ( int a [ ] , int n ) { sort ( a , a + n ) ; return min ( a [ n - 2 ] - a [ 0 ] , a [ n - 1 ] - a [ 1 ] ) ; } int main ( ) { int a [ ] = { 1 , 3 , 3 , 7 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << max_min ( a , n ) ; return 0 ; }
Count numbers < = N whose difference with the count of primes upto them is > = K | C ++ implementation of the above approach ; primeUpto [ i ] denotes count of prime numbers upto i ; Function to compute all prime numbers and update primeUpto array ; 0 and 1 are not primes ; If i is prime ; Set all multiples of i as non - prime ; Compute primeUpto array ; Function to return the count of valid numbers ; Compute primeUpto array ; Check if the number is valid , try to reduce it ; ans is the minimum valid number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000001 ; int primeUpto [ MAX ] ; void SieveOfEratosthenes ( ) { bool isPrime [ MAX ] ; memset ( isPrime , 1 , sizeof ( isPrime ) ) ; isPrime [ 0 ] = isPrime [ 1 ] = 0 ; for ( int i = 2 ; i * i < MAX ; i ++ ) { if ( isPrime [ i ] ) { for ( int j = i * 2 ; j < MAX ; j += i ) isPrime [ j ] = 0 ; } } for ( int i = 1 ; i < MAX ; i ++ ) { primeUpto [ i ] = primeUpto [ i - 1 ] ; if ( isPrime [ i ] ) primeUpto [ i ] ++ ; } } int countOfNumbers ( int N , int K ) { SieveOfEratosthenes ( ) ; int low = 1 , high = N , ans = 0 ; while ( low <= high ) { int mid = ( low + high ) >> 1 ; if ( mid - primeUpto [ mid ] >= K ) { ans = mid ; high = mid - 1 ; } else low = mid + 1 ; } return ( ans ? N - ans + 1 : 0 ) ; } int main ( ) { int N = 10 , K = 3 ; cout << countOfNumbers ( N , K ) ; }
Find the element whose multiplication with | C ++ program to find minimum index such that sum becomes 0 when the element is multiplied by - 1 ; Function to find minimum index such that sum becomes 0 when the element is multiplied by - 1 ; Find array sum ; Find element with value equal to sum / 2 ; when sum is equal to 2 * element then this is our required element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minIndex ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( 2 * arr [ i ] == sum ) return ( i + 1 ) ; } return -1 ; } int main ( ) { int arr [ ] = { 1 , 3 , -5 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minIndex ( arr , n ) << endl ; return 0 ; }
Ceiling of every element in same array | C ++ implementation of efficient algorithm to find floor of every element ; Prints greater elements on left side of every element ; Create a sorted copy of arr [ ] ; Traverse through arr [ ] and do binary search for every element . ; Find the first element that is greater than the given element ; Since arr [ i ] also exists in array , * ( it - 1 ) will be same as arr [ i ] . Let us check * ( it - 2 ) is also same as arr [ i ] . If true , then arr [ i ] exists twice in array , so ceiling is same same as arr [ i ] ; If next element is also same , then there are multiple occurrences , so print it ; Driver program to test insertion sort
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printPrevGreater ( int arr [ ] , int n ) { if ( n == 1 ) { cout << " - 1" ; return ; } vector < int > v ( arr , arr + n ) ; sort ( v . begin ( ) , v . end ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { auto it = upper_bound ( v . begin ( ) , v . end ( ) , arr [ i ] ) ; if ( ( it - 1 ) != v . begin ( ) && * ( it - 2 ) == arr [ i ] ) { cout << arr [ i ] << " ▁ " ; } else if ( it != v . end ( ) ) cout << * it << " ▁ " ; else cout << -1 << " ▁ " ; } } int main ( ) { int arr [ ] = { 10 , 5 , 11 , 10 , 20 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPrevGreater ( arr , n ) ; return 0 ; }
Floor of every element in same array | C ++ implementation of efficient algorithm to find floor of every element ; Prints greater elements on left side of every element ; Create a sorted copy of arr [ ] ; Traverse through arr [ ] and do binary search for every element . ; Floor of first element is - 1 if there is only one occurrence of it . ; Find the first element that is greater than or or equal to given element ; If next element is also same , then there are multiple occurrences , so print it ; Otherwise print previous element ; Driver program to test insertion sort
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printPrevGreater ( int arr [ ] , int n ) { vector < int > v ( arr , arr + n ) ; sort ( v . begin ( ) , v . end ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == v [ 0 ] ) { ( arr [ i ] == v [ 1 ] ) ? cout << arr [ i ] : cout << -1 ; cout << " ▁ " ; continue ; } auto it = lower_bound ( v . begin ( ) , v . end ( ) , arr [ i ] ) ; if ( it != v . end ( ) && * ( it + 1 ) == arr [ i ] ) cout << arr [ i ] << " ▁ " ; else cout << * ( it - 1 ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 6 , 11 , 7 , 8 , 20 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printPrevGreater ( arr , n ) ; return 0 ; }
Find smallest and largest element from square matrix diagonals | C ++ program to find smallest and largest elements of both diagonals ; Function to find smallest and largest element from principal and secondary diagonal ; take length of matrix ; declare and initialize variables with appropriate value ; take new smallest value ; take new largest value ; Condition for secondary diagonal is mat [ n - 1 - i ] [ i ] take new smallest value ; take new largest value ; Driver code ; Declare and initialize 5 X5 matrix
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 5 ; void diagonalsMinMax ( int mat [ n ] [ n ] ) { if ( n == 0 ) return ; int principalMin = mat [ 0 ] [ 0 ] , principalMax = mat [ 0 ] [ 0 ] ; int secondaryMin = mat [ n - 1 ] [ 0 ] , secondaryMax = mat [ n - 1 ] [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( mat [ i ] [ i ] < principalMin ) { principalMin = mat [ i ] [ i ] ; } if ( mat [ i ] [ i ] > principalMax ) { principalMax = mat [ i ] [ i ] ; } if ( mat [ n - 1 - i ] [ i ] < secondaryMin ) { secondaryMin = mat [ n - 1 - i ] [ i ] ; } if ( mat [ n - 1 - i ] [ i ] > secondaryMax ) { secondaryMax = mat [ n - 1 - i ] [ i ] ; } } cout << " Principal ▁ Diagonal ▁ Smallest ▁ Element : ▁ " << principalMin << " STRNEWLINE " ; cout << " Principal ▁ Diagonal ▁ Greatest ▁ Element ▁ : ▁ " << principalMax << " STRNEWLINE " ; cout << " Secondary ▁ Diagonal ▁ Smallest ▁ Element : ▁ " << secondaryMin << " STRNEWLINE " ; cout << " Secondary ▁ Diagonal ▁ Greatest ▁ Element : ▁ " << secondaryMax ; } int main ( ) { int matrix [ n ] [ n ] = { { 1 , 2 , 3 , 4 , -10 } , { 5 , 6 , 7 , 8 , 6 } , { 1 , 2 , 11 , 3 , 4 } , { 5 , 6 , 70 , 5 , 8 } , { 4 , 9 , 7 , 1 , -5 } } ; diagonalsMinMax ( matrix ) ; }
Check if array can be sorted with one swap | A linear CPP program to check if array becomes sorted after one swap ; Find counts and positions of elements that are out of order . ; If there are more than two elements are out of order . ; If all elements are sorted already ; Cases like { 1 , 5 , 3 , 4 , 2 } We swap 5 and 2. ; Cases like { 1 , 2 , 4 , 3 , 5 } ; Now check if array becomes sorted for cases like { 4 , 1 , 2 , 3 } ; Driver Program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int checkSorted ( int n , int arr [ ] ) { int first = 0 , second = 0 ; int count = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ i - 1 ] ) { count ++ ; if ( first == 0 ) first = i ; else second = i ; } } if ( count > 2 ) return false ; if ( count == 0 ) return true ; if ( count == 2 ) swap ( arr [ first - 1 ] , arr [ second ] ) ; else if ( count == 1 ) swap ( arr [ first - 1 ] , arr [ first ] ) ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] < arr [ i - 1 ] ) return false ; return true ; } int main ( ) { int arr [ ] = { 1 , 4 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkSorted ( n , arr ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find the intersection of two Matrices | CPP program to find intersection of two matrices ; Function to print the resultant matrix ; print element value for equal elements else * ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define N 4 NEW_LINE #define M 4 NEW_LINE using namespace std ; void printIntersection ( int A [ ] [ N ] , int B [ ] [ N ] ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( A [ i ] [ j ] == B [ i ] [ j ] ) cout << A [ i ] [ j ] << " ▁ " ; else cout << " * ▁ " ; } cout << " STRNEWLINE " ; } } int main ( ) { int A [ M ] [ N ] = { { 2 , 4 , 6 , 8 } , { 1 , 3 , 5 , 7 } , { 8 , 6 , 4 , 2 } , { 7 , 5 , 3 , 1 } } ; int B [ M ] [ N ] = { { 2 , 3 , 6 , 8 } , { 1 , 3 , 5 , 2 } , { 8 , 1 , 4 , 2 } , { 3 , 5 , 4 , 1 } } ; printIntersection ( A , B ) ; return 0 ; }