text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Sum of all second largest divisors after splitting a number into one or more parts | CPP program to find sum of all second largest divisor after splitting a number into one or more parts ; Function to find a number is prime or not ; If there is any divisor ; Function to find the sum of all second largest divisor after splitting a number into one or more parts ; If number is prime ; If n is even ; If the number is odd ; If N - 2 is prime ; There exists 3 primes x1 , x2 , x3 such that x1 + x2 + x3 = n ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime ( int n ) { if ( n == 1 ) return false ; for ( int i = 2 ; i * i <= n ; ++ i ) if ( n % i == 0 ) return false ; return true ; } int Min_Sum ( int n ) { if ( prime ( n ) ) return 1 ; if ( n % 2 == 0 ) return 2 ; else { if ( prime ( n - 2 ) ) return 2 ; else return 3 ; } } int main ( ) { int n = 27 ; cout << Min_Sum ( n ) ; return 0 ; }
Count pairs of strings that satisfy the given conditions | C ++ implementation of the approach ; Function that returns true if c is vowel ; Function to return the count of required pairs ; For every string of the array ; Vector to store the vowels of the current string ; If current character is a vowel ; If current string contains vowels ; Create tuple ( first vowel , last vowel , total vowels ) ; v stores the indices for which the given condition satisfies Total valid pairs will be half the size ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_vowel ( char c ) { return ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } int count ( string s [ ] , int n ) { map < tuple < char , char , int > , vector < int > > map ; for ( int i = 0 ; i < n ; i ++ ) { vector < char > vowel ; for ( int j = 0 ; j < s [ i ] . size ( ) ; j ++ ) { if ( is_vowel ( s [ i ] [ j ] ) ) vowel . push_back ( s [ i ] [ j ] ) ; } if ( vowel . size ( ) > 0 ) { int len = vowel . size ( ) ; map [ make_tuple ( vowel [ 0 ] , vowel [ len - 1 ] , len ) ] . push_back ( i ) ; } } int count = 0 ; for ( auto i : map ) { vector < int > v = i . second ; count += v . size ( ) / 2 ; } return count ; } int main ( ) { string s [ ] = { " geeks " , " for " , " geeks " } ; int n = sizeof ( s ) / sizeof ( string ) ; cout << count ( s , n ) ; return 0 ; }
Find maximum value of the last element after reducing the array with given operations | C ++ implementation of the approach ; Function to return the maximized value ; Overall minimum absolute value of some element from the array ; Add all absolute values ; Count positive and negative elements ; Both positive and negative values are present ; Only positive or negative values are present ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_maximum_value ( int a [ ] , int n ) { int sum = 0 ; int minimum = INT_MAX ; int pos = 0 , neg = 0 ; for ( int i = 0 ; i < n ; i ++ ) { minimum = min ( minimum , abs ( a [ i ] ) ) ; sum += abs ( a [ i ] ) ; if ( a [ i ] >= 0 ) pos += 1 ; else neg += 1 ; } if ( pos > 0 && neg > 0 ) return sum ; return ( sum - 2 * minimum ) ; } int main ( ) { int a [ ] = { 5 , 4 , 6 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << find_maximum_value ( a , n ) ; return 0 ; }
Find Nth smallest number that is divisible by 100 exactly K times | C ++ implementation of above approach ; Function to find the Nth smallest number ; If N is divisible by 100 then we multiply N + 1 otherwise , it will be divisible by 100 more than K times ; convert integer to string ; if N is not divisible by 100 ; convert integer to string ; add 2 * K 0 's at the end to be divisible by 100 exactly K times ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string find_number ( int N , int K ) { string r ; if ( N % 100 == 0 ) { N += 1 ; r = to_string ( N ) ; } else { r = to_string ( N ) ; } for ( int i = 1 ; i <= K ; i ++ ) r += "00" ; return r ; } int main ( ) { int N = 1000 , K = 2 ; string ans = find_number ( N , K ) ; cout << ans << " STRNEWLINE " ; return 0 ; }
Count of adjacent Vowel Consonant Pairs | C ++ Program to implement the above approach ; Function to count the adjacent pairs of consonant and vowels in the string ; Using a set to store the vowels so that checking each character becomes easier ; Variable to store number of consonant - vowel pairs ; If the ith character is not found in the set , means it is a consonant And if the ( i + 1 ) th character is found in the set , means it is a vowel We increment the count of such pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( string s ) { set < char > st ; st . insert ( ' a ' ) ; st . insert ( ' e ' ) ; st . insert ( ' i ' ) ; st . insert ( ' o ' ) ; st . insert ( ' u ' ) ; int count = 0 ; int n = s . size ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( st . find ( s [ i ] ) == st . end ( ) && st . find ( s [ i + 1 ] ) != st . end ( ) ) count ++ ; } return count ; } int main ( ) { string s = " geeksforgeeks " ; cout << countPairs ( s ) ; return 0 ; }
Find the original coordinates whose Manhattan distances are given | C ++ implementation of the approach ; Function to find the original coordinated ; Maximum of the given distances ; Sum of the given distances ; Conditions when the solution doesn 't exist ; First coordinate ; Second coordinate ; Third coordinate ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int d1 , int d2 , int d3 ) { int maxx = max ( d1 , max ( d2 , d3 ) ) ; int sum = ( d1 + d2 + d3 ) ; if ( 2 * maxx > sum or sum % 2 == 1 ) { cout << " - 1" ; return ; } int x1 = 0 , y1 = 0 ; int x2 = d1 , y2 = 0 ; int x3 = ( d1 + d2 - d3 ) / 2 ; int y3 = ( d2 + d3 - d1 ) / 2 ; cout << " ( " << x1 << " , ▁ " << y1 << " ) , ▁ ( " << x2 << " , ▁ " << y2 << " ) ▁ and ▁ ( " << x3 << " , ▁ " << y3 << " ) " ; } int main ( ) { int d1 = 3 , d2 = 4 , d3 = 5 ; solve ( d1 , d2 , d3 ) ; return 0 ; }
Find the largest interval that contains exactly one of the given N integers . | C ++ implementation of the approach ; Function to return the maximum size of the required interval ; Insert the borders for array ; Sort the elements in ascending order ; To store the maximum size ; To store the range [ L , R ] such that only v [ i ] lies within the range ; Total integers in the range ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSize ( vector < int > & v , int n ) { v . push_back ( 0 ) ; v . push_back ( 100001 ) ; n += 2 ; sort ( v . begin ( ) , v . end ( ) ) ; int mx = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { int L = v [ i - 1 ] + 1 ; int R = v [ i + 1 ] - 1 ; int cnt = R - L + 1 ; mx = max ( mx , cnt ) ; } return mx ; } int main ( ) { vector < int > v = { 200 , 10 , 5 } ; int n = v . size ( ) ; cout << maxSize ( v , n ) ; return 0 ; }
Maximum length of subarray such that sum of the subarray is even | C ++ implementation of the above approach ; Function to find length of the longest subarray such that sum of the subarray is even ; Check if sum of complete array is even ; if ( sum % 2 == 0 ) total sum is already even ; Find an index i such the a [ i ] is odd and compare length of both halfs excluding a [ i ] to find max length subarray ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( int a [ ] , int n ) { int sum = 0 , len = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += a [ i ] ; return n ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 1 ) len = max ( len , max ( n - i - 1 , i ) ) ; } return len ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxLength ( a , n ) << " STRNEWLINE " ; return 0 ; }
Find a Symmetric matrix of order N that contain integers from 0 to N | C ++ implementation of the approach ; Function to generate the required matrix ; Form cyclic array of elements 1 to n - 1 ; Store initial array into final array ; Fill the last row and column with 0 's ; Swap 0 and the number present at the current indexed row ; Also make changes in the last row with the number we swapped ; Print the final array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( long long n ) { long long initial_array [ n - 1 ] [ n - 1 ] , final_array [ n ] [ n ] ; for ( long long i = 0 ; i < n - 1 ; ++ i ) initial_array [ 0 ] [ i ] = i + 1 ; for ( long long i = 1 ; i < n - 1 ; ++ i ) for ( long long j = 0 ; j < n - 1 ; ++ j ) initial_array [ i ] [ j ] = initial_array [ i - 1 ] [ ( j + 1 ) % ( n - 1 ) ] ; for ( long long i = 0 ; i < n - 1 ; ++ i ) for ( long long j = 0 ; j < n - 1 ; ++ j ) final_array [ i ] [ j ] = initial_array [ i ] [ j ] ; for ( long long i = 0 ; i < n ; ++ i ) final_array [ i ] [ n - 1 ] = final_array [ n - 1 ] [ i ] = 0 ; for ( long long i = 0 ; i < n ; ++ i ) { long long t0 = final_array [ i ] [ i ] ; long long t1 = final_array [ i ] [ n - 1 ] ; swap ( final_array [ i ] [ i ] , final_array [ i ] [ n - 1 ] ) ; final_array [ n - 1 ] [ i ] = t0 ; } for ( long long i = 0 ; i < n ; ++ i ) { for ( long long j = 0 ; j < n ; ++ j ) cout << final_array [ i ] [ j ] << " ▁ " ; cout << endl ; } } int main ( ) { long long n = 5 ; solve ( n ) ; return 0 ; }
Generate original array from difference between every two consecutive elements | C ++ implementation of the approach ; Function to print the required permutation ; Take x = 0 for simplicity ; Calculate aint the differences and store it in a vector ; Preserve the original array ; Check if aint the consecutive elements have difference = 1 ; If consecutive elements don 't have difference 1 at any position then the answer is impossible ; Else store the indices and values at those indices in a map and finainty print them ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPerm ( int n , vector < int > & differences ) { vector < int > ans ; ans . clear ( ) ; ans . push_back ( 0 ) ; int x = 0 ; for ( int i = 0 ; i <= n - 2 ; ++ i ) { int diff = differences [ i ] ; x = x + diff ; ans . push_back ( x ) ; } vector < int > anss = ans ; sort ( ans . begin ( ) , ans . end ( ) ) ; int flag = -1 ; for ( int i = 1 ; i <= n - 1 ; ++ i ) { int res = ans [ i ] - ans [ i - 1 ] ; if ( res != 1 ) { flag = 0 ; } } if ( flag == 0 ) { cout << -1 ; return ; } else { unordered_map < int , int > mpp ; mpp . clear ( ) ; int j = 1 ; vector < int > value_at_index ; for ( auto & x : ans ) { mpp [ x ] = j ; ++ j ; } for ( auto & x : anss ) { value_at_index . push_back ( mpp [ x ] ) ; } for ( auto & x : value_at_index ) { cout << x << " ▁ " ; } cout << endl ; } } int main ( ) { vector < int > differences ; differences . push_back ( 2 ) ; differences . push_back ( -3 ) ; differences . push_back ( 2 ) ; int n = differences . size ( ) + 1 ; findPerm ( n , differences ) ; return 0 ; }
Find smallest number K such that K % p = 0 and q % K = 0 | C ++ implementation of the approach ; Function to return the minimum value K such that K % p = 0 and q % k = 0 ; If K is possible ; No such K is possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinVal ( int p , int q ) { if ( q % p == 0 ) return p ; return -1 ; } int main ( ) { int p = 24 , q = 48 ; cout << getMinVal ( p , q ) ; return 0 ; }
Sort the numbers according to their sum of digits | C ++ implementation of the approach ; Function to return the sum of the digits of n ; Function to sort the array according to the sum of the digits of elements ; Vector to store digit sum with respective element ; Inserting digit sum with element in the vector pair ; Quick sort the vector , this will sort the pair according to sum of the digits of elements ; Print the sorted vector content ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigit ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += n % 10 ; n = n / 10 ; } return sum ; } void sortArr ( int arr [ ] , int n ) { vector < pair < int , int > > vp ; for ( int i = 0 ; i < n ; i ++ ) { vp . push_back ( make_pair ( sumOfDigit ( arr [ i ] ) , arr [ i ] ) ) ; } sort ( vp . begin ( ) , vp . end ( ) ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) cout << vp [ i ] . second << " ▁ " ; } int main ( ) { int arr [ ] = { 14 , 1101 , 10 , 35 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArr ( arr , n ) ; return 0 ; }
Count all Prime Length Palindromic Substrings | C ++ implementation of the approach ; Function that returns true if sub - string starting at i and ending at j in str is a palindrome ; Function to count all palindromic substring whose lwngth is a prime number ; 0 and 1 are non - primes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; To store the required number of sub - strings ; Starting from the smallest prime till the largest length of the sub - string possible ; If j is prime ; Check all the sub - strings of length j ; If current sub - string is a palindrome ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str , int i , int j ) { while ( i < j ) { if ( str [ i ] != str [ j ] ) return false ; i ++ ; j -- ; } return true ; } int countPrimePalindrome ( string str , int len ) { bool prime [ len + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= len ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * p ; i <= len ; i += p ) prime [ i ] = false ; } } int count = 0 ; for ( int j = 2 ; j <= len ; j ++ ) { if ( prime [ j ] ) { for ( int i = 0 ; i + j - 1 < len ; i ++ ) { if ( isPalindrome ( str , i , i + j - 1 ) ) count ++ ; } } } return count ; } int main ( ) { string s = " geeksforgeeks " ; int len = s . length ( ) ; cout << countPrimePalindrome ( s , len ) ; return 0 ; }
Minimum operations of the given type required to make a complete graph | C ++ implementation of the approach ; Function to return the minimum number of steps required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int N ) { double x = log2 ( N ) ; int ans = ceil ( x ) ; return ans ; } int main ( ) { int N = 10 ; cout << minOperations ( N ) ; return 0 ; }
Greatest divisor which divides all natural number in range [ L , R ] | C ++ implementation of the approach ; Function to return the greatest divisor that divides all the natural numbers in the range [ l , r ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_greatest_divisor ( int l , int r ) { if ( l == r ) return l ; return 1 ; } int main ( ) { int l = 2 , r = 12 ; cout << find_greatest_divisor ( l , r ) ; }
Probability of getting two consecutive heads after choosing a random coin among two different types of coins | C ++ program to get the probability of getting two consecutive heads ; Function to return the probability of getting two consecutive heads ; Formula derived from Bayes 's theorem ; Driver code ; given the probability of getting a head for both the coins
#include <bits/stdc++.h> NEW_LINE using namespace std ; double getProbability ( double p , double q ) { p /= 100 ; q /= 100 ; double probability = ( p * p + q * q ) / ( p + q ) ; return probability ; } int main ( ) { double p , q ; p = 80 ; q = 40 ; cout << fixed << setprecision ( 15 ) << getProbability ( p , q ) << endl ; return 0 ; }
Check whether bitwise OR of N numbers is Even or Odd | C ++ implementation to check whether bitwise OR of n numbers is even or odd ; Function to check if bitwise OR of n numbers is even or odd ; if at least one odd number is found , then the bitwise OR of all numbers will be odd ; Bitwise OR is an odd number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & 1 ) return true ; } return false ; } int main ( ) { int arr [ ] = { 3 , 9 , 12 , 13 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( check ( arr , n ) ) cout << " Odd ▁ Bit - wise ▁ OR " ; else cout << " Even ▁ Bit - wise ▁ OR " ; return 0 ; }
Amortized analysis for increment in counter |
#include <bits / stdc++.h> NEW_LINE using namespace std ; int main ( ) { char str [ ] = "10010111" ; int length = strlen ( str ) ; int i = length - 1 ; while ( str [ i ] == '1' ) { str [ i ] = '0' ; i -- ; } if ( i >= 0 ) str [ i ] = '1' ; printf ( " % ▁ s " , str ) ; }
Time taken by Loop unrolling vs Normal loop | CPP program to compare normal loops and loops with unrolling technique ; n is 8 lakhs ; t to note start time ; to store the sum ; Normal loop ; to mark end time ; to mark start time of unrolling ; Unrolling technique ( assuming that n is a multiple of 8 ) . ; to mark the end of loop
#include <iostream> NEW_LINE #include <time.h> NEW_LINE using namespace std ; int main ( ) { int n = 800000 ; clock_t t = clock ( ) ; long long int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) sum += i ; t = clock ( ) - t ; cout << " sum ▁ is : ▁ " << sum << endl ; cout << " time ▁ taken ▁ by ▁ normal ▁ loops : " " ( float ) t ▁ / ▁ CLOCKS _ PER _ SEC ▁ < < ▁ " seconds " << endl ; t = clock ( ) ; sum = 0 ; for ( int i = 1 ; i <= n ; i += 8 ) { sum += i sum += ( i + 1 ) ; sum += ( i + 2 ) ; sum += ( i + 3 ) ; sum += ( i + 4 ) ; sum += ( i + 5 ) ; sum += ( i + 6 ) ; sum += ( i + 7 ) ; } t = clock ( ) - t ; cout << " Sum ▁ is : ▁ " << sum << endl ; cout << " Time ▁ taken ▁ by ▁ unrolling : ▁ " " ( float ) t ▁ / ▁ CLOCKS _ PER _ SEC ▁ < < ▁ " seconds " return 0 ; }
Iterated Logarithm log * ( n ) | Recursive CPP program to find value of Iterated Logarithm ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int _log ( double x , double base ) { return ( int ) ( log ( x ) / log ( base ) ) ; } double recursiveLogStar ( double n , double b ) { if ( n > 1.0 ) return 1.0 + recursiveLogStar ( _log ( n , b ) , b ) ; else return 0 ; } int main ( ) { int n = 100 , base = 5 ; cout << " Log * ( " << n << " ) ▁ = ▁ " << recursiveLogStar ( n , base ) << " STRNEWLINE " ; return 0 ; }
Iterated Logarithm log * ( n ) | Iterative CPP function to find value of Iterated Logarithm
int iterativeLogStar ( double n , double b ) { int count = 0 ; while ( n >= 1 ) { n = _log ( n , b ) ; count ++ ; } return count ; }
Analysis of Algorithms | Set 5 ( Practice Problems ) |
void function ( int n ) { int count = 0 ; for ( int i = n / 2 ; i <= n ; i ++ ) for ( int j = 1 ; j <= n ; j = 2 * j ) for ( int k = 1 ; k <= n ; k = k * 2 ) count ++ ; }
Auxiliary Space with Recursive Functions |
int sum ( int sum ) { if ( n <= 0 ) return 0 ; return n + sum ( n - 1 ) ; }
Find the maximum among the count of positive or negative integers in the array | C ++ program for the above approach ; Function to find the maximum of the count of positive or negative elements ; Initialize the pointers ; Find the value of mid ; If element is negative then ignore the left half ; If element is positive then ignore the right half ; Return maximum among the count of positive & negative element ; Driver Code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int findMaximum ( int arr [ ] , int size ) { int i = 0 , j = size - 1 , mid ; while ( i <= j ) { mid = i + ( j - i ) / 2 ; if ( arr [ mid ] < 0 ) i = mid + 1 ; else if ( arr [ mid ] > 0 ) j = mid - 1 ; } return max ( i , size - i ) ; } int main ( ) { int arr [ ] = { -9 , -7 , -4 , 1 , 5 , 8 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMaximum ( arr , N ) ; return 0 ; }
Perform given queries on Queue according to the given rules | C ++ program for the above approach ; Function to perform all the queries operations on the given queue ; Stores the count query of type 1 ; Event E1 : increase countE1 ; Event E2 : add the X in set ; Event E3 : Find position of X ; Initial position is ( position - countE1 ) ; If X is already removed or popped out ; Finding the position of X in queue ; Traverse set to decrease position of X for all the number removed in front ; Print the position of X ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int n , int m , int * * queries ) { int countE1 = 0 ; set < int > removed ; for ( int i = 0 ; i < m ; i ++ ) { if ( queries [ i ] [ 0 ] == 1 ) ++ countE1 ; else if ( queries [ i ] [ 0 ] == 2 ) removed . insert ( queries [ i ] [ 1 ] ) ; else { int position = queries [ i ] [ 1 ] - countE1 ; if ( removed . find ( queries [ i ] [ 1 ] ) != removed . end ( ) position <= 0 ) cout << " - 1 STRNEWLINE " ; else { for ( int it : removed ) { if ( it > queries [ i ] [ 1 ] ) break ; position -- ; } cout << position << " STRNEWLINE " ; } } } } int main ( ) { int N = 5 , Q = 3 ; int * * queries = new int * [ Q ] ; for ( int i = 0 ; i < Q ; i ++ ) { queries [ i ] = new int [ 2 ] ; } queries [ 0 ] [ 0 ] = 1 ; queries [ 0 ] [ 1 ] = 0 ; queries [ 1 ] [ 0 ] = 3 ; queries [ 1 ] [ 1 ] = 3 ; queries [ 2 ] [ 0 ] = 2 ; queries [ 2 ] [ 1 ] = 2 ; solve ( N , Q , queries ) ; return 0 ; }
Maximum index a pointer can reach in N steps by avoiding a given index B | C ++ program for the above approach ; Function to find the maximum index reachable ; Store the answer ; Store the maximum index possible i . e , N * ( N - 1 ) ; Add bthe previous elements ; Run a loop ; Binary Search ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxIndex ( int N , int B ) { int maximumIndexReached = 0 ; vector < int > Ans ; for ( int i = 1 ; i <= N ; i ++ ) { maximumIndexReached += i ; Ans . push_back ( i ) ; } reverse ( Ans . begin ( ) , Ans . end ( ) ) ; for ( int i = 1 ; i < ( int ) Ans . size ( ) ; i ++ ) { Ans [ i ] += Ans [ i - 1 ] ; } while ( maximumIndexReached ) { auto it = lower_bound ( Ans . begin ( ) , Ans . end ( ) , maximumIndexReached - B ) ; if ( it == Ans . end ( ) ) { break ; } if ( * it == maximumIndexReached - B ) { maximumIndexReached -- ; } else { break ; } } return maximumIndexReached ; } int main ( ) { int N = 3 , B = 2 ; cout << maxIndex ( N , B ) ; return 0 ; }
Maximize Kth largest element after splitting the given Array at most C times | C ++ program for the above approach ; Function to find the K - th maximum element after upto C operations ; Check for the base case ; Stores the count iterations of BS ; Create the left and right bounds of binary search ; Perform binary search ; Find the value of mid ; Traverse the array ; Update the ranges ; Return the maximum value obtained ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double maxKth ( int arr [ ] , int N , int C , int K ) { if ( N + C < K ) { return -1 ; } int iter = 300 ; double l = 0 , r = 1000000000.0 ; while ( iter -- ) { double mid = ( l + r ) * 0.5 ; double a = 0 ; double b = 0 ; for ( int i = 0 ; i < N ; i ++ ) { a += int ( ( double ) arr [ i ] / mid ) ; if ( ( double ) arr [ i ] >= mid ) { b ++ ; } } if ( a >= K && b + C >= K ) { l = mid ; } else { r = mid ; } } return l ; } int main ( ) { int arr [ ] = { 5 , 8 } ; int K = 1 , C = 1 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxKth ( arr , N , C , K ) ; return 0 ; }
Maximize the minimum difference between any element pair by selecting K elements from given Array | C ++ implementation for the above approach ; To check if selection of K elements is possible such that difference between them is greater than dif ; Selecting first element in the sorted array ; prev is the previously selected element initially at index 0 as first element is already selected ; Check if selection of K - 1 elements from array with a minimum difference of dif is possible ; If the current element is atleast dif difference apart from the previously selected element then select the current element and increase the count ; If selection of K elements with a min difference of dif is possible then return true ; Prev will become current element for the next iteration ; If selection of K elements with minimum difference of dif is not possible then return false ; Minimum largest difference possible is 1 ; Check if selection of K elements is possible with a minimum difference of dif ; If dif is greater than previous ans we update ans ; Continue to search for better answer . Try finding greater dif ; K elements cannot be selected ; Driver code ; arr should be in a sorted order
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossibleToSelect ( int arr [ ] , int N , int dif , int K ) { int count = 1 ; int prev = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] >= ( prev + dif ) ) { count ++ ; if ( count == K ) return true ; prev = arr [ i ] ; } } return false ; } int binarySearch ( int arr [ ] , int left , int right , int K , int N ) { int ans = 1 ; while ( left <= right ) { int dif = left + ( right - left ) / 2 ; if ( isPossibleToSelect ( arr , N , dif , K ) ) { ans = max ( ans , dif ) ; left = dif + 1 ; } else right = dif - 1 ; } return ans ; } int main ( ) { int N , K ; N = 7 , K = 4 ; int arr [ ] = { 1 , 4 , 9 , 0 , 2 , 13 , 3 } ; sort ( arr , arr + N ) ; cout << binarySearch ( arr , 0 , arr [ N - 1 ] , K , N ) << " STRNEWLINE " ; return 0 ; }
Find maximum height to cut all chocolates horizontally such that at least K amount remains | C ++ program for the above approach ; Function to find the sum of remaining chocolate after making the horizontal cut at height mid ; Stores the sum of chocolates ; Traverse the array arr [ ] ; If the height is at least mid ; Return the possible sum ; Function to find the maximum horizontal cut made to all the chocolates such that the sum of the remaining element is at least K ; Ranges of Binary Search ; Perform the Binary Search ; Find the sum of removed after making cut at height mid ; If the chocolate removed is same as the chocolate needed then return the height ; If the chocolate removed is less than chocolate needed then shift to the left range ; Otherwise , shift to the right range ; Return the possible cut ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cal ( vector < int > arr , int mid ) { int chocolate = 0 ; for ( auto i : arr ) { if ( i >= mid ) chocolate += i - mid ; } return chocolate ; } int maximumCut ( vector < int > arr , int K ) { int low = 0 ; int high = * max_element ( arr . begin ( ) , arr . end ( ) ) ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int chocolate = cal ( arr , mid ) ; if ( chocolate == K ) return mid ; else if ( chocolate < K ) high = mid - 1 ; else { low = mid + 1 ; if ( mid > high ) high = mid ; } } return high ; } int main ( ) { int N = 4 ; int K = 7 ; vector < int > arr { 15 , 20 , 8 , 17 } ; cout << ( maximumCut ( arr , K ) ) ; }
Find MEX of every subtree in given Tree | C ++ program for the above approach ; Stores the edges of the tree ; Function to add edges ; Function to merge two sorted vectors ; To store the result ; Iterating both vectors ; Pushing remaining elements of vector a ; Pushing remaining elements of vector b ; Function to perform the DFS Traversal that returns the subtree of node in sorted manner ; Iterate the childrens ; All values of subtree i in sorted manner ; Binary search to find MEX ; Find the mid ; Update the ranges ; Update the MEX for the current tree node ; Function to find MEX of each subtree of tree ; Function Call ; Printe the ans for each nodes ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > edges ; void add_edge ( int x , int y ) { edges . push_back ( { x , y } ) ; } vector < int > merge ( vector < int > & a , vector < int > & b ) { vector < int > res ; int i = 0 , j = 0 ; int n = a . size ( ) , m = b . size ( ) ; while ( i < n && j < m ) { if ( a [ i ] < b [ j ] ) res . push_back ( a [ i ++ ] ) ; else if ( b [ j ] < a [ i ] ) res . push_back ( b [ j ++ ] ) ; } while ( i < n ) res . push_back ( a [ i ++ ] ) ; while ( j < m ) res . push_back ( b [ j ++ ] ) ; return res ; } vector < int > help ( vector < int > tree [ ] , int x , int p , vector < int > & c , vector < int > & sol ) { vector < int > res ; res . push_back ( c [ x ] ) ; for ( auto i : tree [ x ] ) { if ( i != p ) { vector < int > tmp = help ( tree , i , x , c , sol ) ; res = merge ( res , tmp ) ; } } int l = 0 , r = res . size ( ) - 1 ; int ans = res . size ( ) ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( res [ mid ] > mid ) r = mid - 1 ; else { ans = mid + 1 ; l = mid + 1 ; } } if ( res [ 0 ] != 0 ) ans = 0 ; sol [ x ] = ans ; return res ; } void solve ( int A , vector < int > C ) { int n = A ; vector < int > tree [ n + 1 ] ; for ( auto i : edges ) { tree [ i [ 0 ] ] . push_back ( i [ 1 ] ) ; tree [ i [ 1 ] ] . push_back ( i [ 0 ] ) ; } vector < int > sol ( n , 0 ) ; help ( tree , 0 , -1 , C , sol ) ; for ( auto i : sol ) cout << i << " ▁ " ; } int main ( ) { int N = 6 ; add_edge ( 0 , 1 ) ; add_edge ( 1 , 2 ) ; add_edge ( 0 , 3 ) ; add_edge ( 3 , 4 ) ; add_edge ( 3 , 5 ) ; vector < int > val = { 4 , 3 , 5 , 1 , 0 , 2 } ; solve ( N , val ) ; return 0 ; }
Koko Eating Bananas | C ++ implementation for the above approach ; to get the ceil value ; in case of odd number ; in case of even number ; check if time is less than or equals to given hour ; as minimum speed of eating must be 1 ; Maximum speed of eating is the maximum bananas in given piles ; Check if the mid ( hours ) is valid ; If valid continue to search lower speed ; If cant finish bananas in given hours , then increase the speed ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( vector < int > & bananas , int mid_val , int H ) { int time = 0 ; for ( int i = 0 ; i < bananas . size ( ) ; i ++ ) { if ( bananas [ i ] % mid_val != 0 ) { time += ( ( bananas [ i ] / mid_val ) + 1 ) ; } else { time += ( bananas [ i ] / mid_val ) ; } } if ( time <= H ) { return true ; } else { return false ; } } int minEatingSpeed ( vector < int > & piles , int H ) { int start = 1 ; int end = * max_element ( piles . begin ( ) , piles . end ( ) ) ; while ( start < end ) { int mid = start + ( end - start ) / 2 ; if ( ( check ( piles , mid , H ) ) == true ) { end = mid ; } else { start = mid + 1 ; } } return end ; } int main ( ) { vector < int > piles = { 30 , 11 , 23 , 4 , 20 } ; int H = 6 ; cout << minEatingSpeed ( piles , H ) ; return 0 ; }
Minimize the sum of pair which upon removing divides the Array into 3 subarrays | C ++ implementation of the above approach ; Function to find minimum possible sum of pair which breaks the array into 3 non - empty subarrays ; prefixMin [ i ] contains minimum element till i ; Driver Code ; Given array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSumPair ( int arr [ ] , int N ) { if ( N < 5 ) { return -1 ; } int prefixMin [ N ] ; prefixMin [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N - 1 ; i ++ ) { prefixMin [ i ] = min ( arr [ i ] , prefixMin [ i - 1 ] ) ; } int ans = INT_MAX ; for ( int i = 3 ; i < N - 1 ; i ++ ) { ans = min ( ans , arr [ i ] + prefixMin [ i - 2 ] ) ; } return ans ; } int main ( ) { int arr [ ] = { 5 , 2 , 4 , 6 , 3 , 7 } ; int N = sizeof ( arr ) / sizeof ( int ) ; cout << minSumPair ( arr , N ) << endl ; return 0 ; }
Minimum time remaining for safety alarm to start | C ++ program for the above approach ; Function to check if the value of mid as the minimum number of hours satisfies the condition ; Stores the sum of speed ; Iterate over the range [ 0 , N ] ; Find the value of speed ; If the bike is considered to be fast add it in sum ; Return the resultant sum ; Function to find the minimum number of time required ; Stores the range of Binary Search ; Stores the minimum number of time required ; Find the value of mid ; If the mid is the resultant speed required ; Update the ans and high ; Otherwise ; Return the minimum number of hours ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long check ( long H [ ] , long A [ ] , long mid , long N , long M , long L ) { long sum = 0 ; for ( long i = 0 ; i < N ; i ++ ) { long speed = mid * A [ i ] + H [ i ] ; if ( speed >= L ) { sum += speed ; } } return sum ; } long buzzTime ( long N , long M , long L , long H [ ] , long A [ ] ) { long low = 0 , high = 1e10 ; long ans = 0 ; while ( high >= low ) { long mid = low + ( high - low ) / 2 ; if ( check ( H , A , mid , N , M , L ) >= M ) { ans = mid ; high = mid - 1 ; } else low = mid + 1 ; } return ans ; } int main ( ) { long M = 400 , L = 120 ; long H [ ] = { 20 , 50 , 20 } ; long A [ ] = { 20 , 70 , 90 } ; long N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << buzzTime ( N , M , L , H , A ) ; return 0 ; }
Count of different numbers divisible by 3 that can be obtained by changing at most one digit | C ++ program fo the above approach ; Function to count the number of possible numbers divisible by 3 ; Calculate the sum ; Store the answer ; Iterate over the range ; Decreasing the sum ; Iterate over the range ; Checking if the new sum is divisible by 3 or not ; If yes increment the value of the count ; Driver Code ; Given number
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findCount ( string number ) { int sum = 0 ; for ( int i = 0 ; i < number . length ( ) ; ++ i ) { sum += number [ i ] - 48 ; } int count = 0 ; for ( int i = 0 ; i < number . length ( ) ; ++ i ) { int remaining_sum = sum - ( number [ i ] - 48 ) ; for ( int j = 0 ; j <= 9 ; ++ j ) { if ( ( remaining_sum + j ) % 3 == 0 && j != number [ i ] - 48 ) { ++ count ; } } } cout << count ; } int main ( ) { string number = "235" ; findCount ( number ) ; }
Maximum number of teams of size K possible with each player from different country | C ++ program for the above approach ; Function to find if T number of teams can be formed or not ; Store the sum of array elements ; Traverse the array teams [ ] ; Required Condition ; Function to find the maximum number of teams possible ; Lower and Upper part of the range ; Perform the Binary Search ; Find the value of mid ; Perform the Binary Search ; Otherwise , update the search range ; Otherwise , update the search range ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_possible ( vector < int > & teams , int T , int k ) { int sum = 0 ; for ( int i = 0 ; i < teams . size ( ) ; i ++ ) { sum += min ( T , teams [ i ] ) ; } return ( sum >= ( T * k ) ) ; } int countOfTeams ( vector < int > & teams_list , int N , int K ) { int lb = 0 , ub = 1e9 ; while ( lb <= ub ) { int mid = lb + ( ub - lb ) / 2 ; if ( is_possible ( teams_list , mid , K ) ) { if ( ! is_possible ( teams_list , mid + 1 , K ) ) { return mid ; } else { lb = mid + 1 ; } } else { ub = mid - 1 ; } } return 0 ; } int main ( ) { vector < int > arr = { 2 , 3 , 4 } ; int K = 2 ; int N = arr . size ( ) ; cout << countOfTeams ( arr , N , K ) ; return 0 ; }
Minimum number of decrements by 1 required to reduce all elements of a circular array to 0 | C ++ program for the above approach ; Function to find minimum operation require to make all elements 0 ; Stores the maximum element and its position in the array ; Traverse the array ; Update the maximum element and its index ; Print the minimum number of operations required ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumOperations ( int arr [ ] , int N ) { int mx = 0 , pos = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= mx ) { mx = arr [ i ] ; pos = i ; } } cout << ( mx - 1 ) * N + pos + 1 ; } int main ( ) { int arr [ ] = { 2 , 0 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumOperations ( arr , N ) ; return 0 ; }
Maximize the smallest array element by incrementing all elements in a K | C ++ program for above approach ; Function to check if the smallest value of v is achievable or not ; Create array to store previous moves ; Remove previous moves ; Add balance to ans ; Update contiguous subarray of length k ; Number of moves should not exceed m ; Function to find the maximum value of the smallest array element that can be obtained ; Perform Binary search ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long NEW_LINE ll n , m , k , l , r , i ; ll check ( ll v , vector < ll > & a ) { ll tec = 0 , ans = 0 ; vector < ll > b ( n + k + 1 ) ; for ( i = 0 ; i < n ; i ++ ) { tec -= b [ i ] ; if ( a [ i ] + tec < v ) { ll mov = v - a [ i ] - tec ; ans = ans + mov ; tec += mov ; b [ i + k ] = mov ; } } return ( ans <= m ) ; } ll FindLargest ( vector < ll > a ) { l = 1 ; r = pow ( 10 , 10 ) ; while ( r - l > 0 ) { ll tm = ( l + r + 1 ) / 2 ; if ( check ( tm , a ) ) l = tm ; else r = tm - 1 ; } return l ; } int main ( ) { vector < ll > a { 2 , 2 , 2 , 2 , 1 , 1 } ; m = 2 ; k = 3 ; n = a . size ( ) ; cout << FindLargest ( a ) ; return 0 ; }
Altitude of largest Triangle that can be inscribed in a Rectangle | C ++ program for the above approach ; Function to find the greatest altitude of the largest triangle triangle that can be inscribed in the rectangle ; If L is greater than B ; Variables to perform binary search ; Stores the maximum altitude possible ; Iterate until low is less than high ; Stores the mid value ; If mide is less than or equal to the B / 2 ; Update res ; Update low ; Update high ; Print the result ; Driver Code ; Given Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestAltitude ( int L , int B ) { if ( L > B ) { swap ( B , L ) ; } int low = 0 , high = L ; int res = 0 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( mid <= ( B / 2 ) ) { res = mid ; low = mid + 1 ; } else high = mid - 1 ; } return res ; } int main ( ) { int L = 3 ; int B = 4 ; cout << largestAltitude ( L , B ) ; return 0 ; }
Find the frequency of each element in a sorted array | C ++ program for the above approach ; Function to print the frequency of each element of the sorted array ; Stores the frequency of an element ; Traverse the array arr [ ] ; If the current element is equal to the previous element ; Increment the freq by 1 ; Otherwise , ; Update freq ; Print the frequency of the last element ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printFreq ( vector < int > & arr , int N ) { int freq = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) { freq ++ ; } else { cout << " Frequency ▁ of ▁ " << arr [ i - 1 ] << " ▁ is : ▁ " << freq << endl ; freq = 1 ; } } cout << " Frequency ▁ of ▁ " << arr [ N - 1 ] << " ▁ is : ▁ " << freq << endl ; } int main ( ) { vector < int > arr = { 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 } ; int N = arr . size ( ) ; printFreq ( arr , N ) ; return 0 ; }
Count pairs from a given array whose sum lies from a given range | C ++ program for the above approach ; Function to count pairs whose sum lies over the range [ L , R ] ; Sort the given array ; Iterate until right > 0 ; Starting index of element whose sum with arr [ right ] >= L ; Ending index of element whose sum with arr [ right ] <= R ; Update the value of end ; Add the count of elements to the variable count ; Return the value of count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairSum ( int arr [ ] , int L , int R , int N ) { sort ( arr , arr + N ) ; int right = N - 1 , count = 0 ; while ( right > 0 ) { auto it1 = lower_bound ( arr , arr + N , L - arr [ right ] ) ; int start = it1 - arr ; auto it2 = upper_bound ( arr , arr + N , R - arr [ right ] ) ; -- it2 ; int end = it2 - arr ; end = min ( end , right - 1 ) ; if ( end - start >= 0 ) { count += ( end - start + 1 ) ; } right -- ; } return count ; } int main ( ) { int arr [ ] = { 5 , 1 , 2 , 4 , 3 } ; int L = 5 , R = 8 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairSum ( arr , L , R , N ) ; return 0 ; }
Maximize median of a KxK sub | C ++ program for the above approach ; Function to determine if a given value can be median ; Stores the prefix sum array ; Traverse the matrix arr [ ] [ ] ; Update Pre [ i + 1 ] [ j + 1 ] ; If arr [ i ] [ j ] is less than or equal to mid ; Stores the count of elements should be less than mid ; Stores if the median mid can be possible or not ; Iterate over the range [ K , N ] ; Iterate over the range [ K , N ] ; Stores count of elements less than or equal to the value mid in submatrix with bottom right vertices at ( i , j ) ; If X is less than or equal to required ; Return flag ; Function to find the maximum median of a subsquare of the given size ; Stores the range of the search space ; Iterate until low is less than high ; Stores the mid value of the range [ low , high ] ; If the current median can be possible ; Update the value of low ; Update the value of high ; Return value stored in low as answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isMaximumMedian ( vector < vector < int > > & arr , int N , int K , int mid ) { vector < vector < int > > Pre ( N + 5 , vector < int > ( N + 5 , 0 ) ) ; for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) { Pre [ i + 1 ] [ j + 1 ] = Pre [ i + 1 ] [ j ] + Pre [ i ] [ j + 1 ] - Pre [ i ] [ j ] ; if ( arr [ i ] [ j ] <= mid ) Pre [ i + 1 ] [ j + 1 ] ++ ; } } int required = ( K * K + 1 ) / 2 ; bool flag = 0 ; for ( int i = K ; i <= N ; ++ i ) { for ( int j = K ; j <= N ; ++ j ) { int X = Pre [ i ] [ j ] - Pre [ i - K ] [ j ] - Pre [ i ] [ j - K ] + Pre [ i - K ] [ j - K ] ; if ( X < required ) flag = 1 ; } } return flag ; } int maximumMedian ( vector < vector < int > > & arr , int N , int K ) { int low = 0 , high = 1e9 ; while ( low < high ) { int mid = low + ( high - low ) / 2 ; if ( isMaximumMedian ( arr , N , K , mid ) ) { low = mid + 1 ; } else { high = mid ; } } return low ; } int main ( ) { vector < vector < int > > arr = { { 1 , 5 , 12 } , { 6 , 7 , 11 } , { 8 , 9 , 10 } } ; int N = arr . size ( ) ; int K = 2 ; cout << maximumMedian ( arr , N , K ) ; return 0 ; }
Minimum days to make Array elements with value at least K sum at least X | C ++ program for the above approach ; Function to find the minimum number of days such that the sum of array elements >= K is at least X ; Initialize the boundaries of search space ; Perform the binary search ; Find the value of mid ; Traverse the array , arr [ ] ; Find the value of arr [ i ] after mid number of days ; Check if temp is not less than K ; Update the value of sum ; Check if the value of sum is greater than X ; Update value of high ; Update the value of low ; Print the minimum number of days ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMinDays ( int arr [ ] , int R [ ] , int N , int X , int K ) { int low = 0 , high = X ; int minDays ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int temp = arr [ i ] + R [ i ] * mid ; if ( temp >= K ) { sum += temp ; } } if ( sum >= X ) { minDays = mid ; high = mid - 1 ; } else { low = mid + 1 ; } } cout << minDays ; } int main ( ) { int X = 100 , K = 45 ; int arr [ ] = { 2 , 5 , 2 , 6 } ; int R [ ] = { 10 , 13 , 15 , 12 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findMinDays ( arr , R , N , X , K ) ; return 0 ; }
Count of indices pairs such that product of elements at these indices is equal to absolute difference of indices | C ++ program for the above approach ; Function to count the number of pairs ( i , j ) such that arr [ i ] * arr [ j ] is equal to abs ( i - j ) ; Stores the resultant number of pairs ; Generate all possible pairs from the array arr [ ] ; If the given condition satisfy then increment the value of count ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getPairsCount ( int a [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( ( a [ i ] * a [ j ] ) == abs ( i - j ) ) count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getPairsCount ( arr , N ) ; return 0 ; }
Lexicographically smallest string formed repeatedly deleting character from substring 10 | C ++ program for the above approach ; Function to find smallest lexicogra - phically smallest string ; Stores the index of last occuring 0 ; Stores the lexicographically smallest string ; Traverse the string S ; If str [ i ] is 0 ; Assign i to lastZe ; Traverse the string str ; If i is less than or equal to lastZe and str [ i ] is 0 ; If i is greater than lastZe ; Return ans ; Driver Code ; Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string lexicographicallySmallestString ( string S , int N ) { int LastZe = -1 ; string ans ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( S [ i ] == '0' ) { LastZe = i ; break ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( i <= LastZe && S [ i ] == '0' ) ans += S [ i ] ; else if ( i > LastZe ) ans += S [ i ] ; } return ans ; } int main ( ) { string S = "11001101" ; int N = S . size ( ) ; cout << lexicographicallySmallestString ( S , N ) ; return 0 ; }
Count of Nodes at distance K from S in its subtree for Q queries | C ++ program for the above approach ; Function to add edges ; Function to perform Depth First Search ; Stores the entry time of a node ; Stores the entering time of a node at depth d ; Iterate over the children of node ; Stores the Exit time of a node ; Function to find number of nodes at distance K from node S in the subtree of S ; Distance from root node ; Index of node with greater tin value then tin [ S ] ; Index of node with greater tout value then tout [ S ] ; Answer to the Query ; Function for performing DFS and answer to queries ; DFS function call ; Traverse the array Q [ ] ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int tin [ 100 ] , tout [ 100 ] , depth [ 100 ] ; int t = 0 ; void Add_edge ( int parent , int child , vector < vector < int > > & adj ) { adj [ parent ] . push_back ( child ) ; adj [ child ] . push_back ( parent ) ; } void dfs ( int node , int parent , vector < vector < int > > & adj , vector < vector < int > > & levels , int d ) { tin [ node ] = t ++ ; levels [ d ] . push_back ( tin [ node ] ) ; depth [ node ] = d ; for ( auto x : adj [ node ] ) { if ( x != parent ) dfs ( x , node , adj , levels , d + 1 ) ; } tout [ node ] = t ++ ; } void numberOfNodes ( int node , int dist , vector < vector < int > > & levels ) { dist += depth [ node ] ; int start = lower_bound ( levels [ dist ] . begin ( ) , levels [ dist ] . end ( ) , tin [ node ] ) - levels [ dist ] . begin ( ) ; int ed = lower_bound ( levels [ dist ] . begin ( ) , levels [ dist ] . end ( ) , tout [ node ] ) - levels [ dist ] . begin ( ) ; cout << ed - start << endl ; } void numberOfNodesUtil ( pair < int , int > Q [ ] , int M , int N ) { vector < vector < int > > adj ( N + 5 ) , levels ( N + 5 ) ; Add_edge ( 1 , 2 , adj ) ; Add_edge ( 1 , 3 , adj ) ; Add_edge ( 2 , 4 , adj ) ; Add_edge ( 2 , 5 , adj ) ; Add_edge ( 2 , 6 , adj ) ; t = 1 ; dfs ( 1 , 1 , adj , levels , 0 ) ; for ( int i = 0 ; i < M ; ++ i ) { numberOfNodes ( Q [ i ] . first , Q [ i ] . second , levels ) ; } } int main ( ) { int N = 6 ; pair < int , int > Q [ ] = { { 2 , 1 } , { 1 , 1 } } ; int M = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; numberOfNodesUtil ( Q , M , N ) ; }
Maximize boxes required to keep at least one black and one white shirt | C ++ program for the above approach ; Function to find the maximum number of boxes such that each box contains three shirts comprising of at least one white and black shirt ; Stores the low and high pointers for binary search ; Store the required answer ; Loop while low <= high ; Store the mid value ; Check if the mid number of boxes can be used ; Update answer and recur for the right half ; Else , recur for the left half ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void numberofBoxes ( int W , int B , int O ) { int low = 0 , high = min ( W , B ) ; int ans = 0 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( ( ( W >= mid ) and ( B >= mid ) ) and ( ( W - mid ) + ( B - mid ) + O ) >= mid ) { ans = mid ; low = mid + 1 ; } else high = mid - 1 ; } cout << ans ; } int main ( ) { int W = 3 , B = 3 , O = 1 ; numberofBoxes ( W , B , O ) ; return 0 ; }
Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B | C ++ program for the above approach ; Function to count the minimum number of swaps required to convert matrix A to matrix B ; Stores number of cells such that matrix A contains 0 and matrix B contains 1 ; Stores number of cells such that matrix A contains 1 and matrix B contains 0 ; Iterate over the range [ 0 , N - 1 ] ; Iterate over the range [ 0 , M - 1 ] ; If A [ i ] [ j ] = 1 and B [ i ] [ j ] = 0 ; If A [ i ] [ j ] = 0 and B [ i ] [ j ] = 1 ; If count01 is equal to count10 ; Otherwise , ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSwaps ( int N , int M , vector < vector < int > > & A , vector < vector < int > > & B ) { int count01 = 0 ; int count10 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( A [ i ] [ j ] != B [ i ] [ j ] ) { if ( A [ i ] [ j ] == 1 ) count10 ++ ; else count01 ++ ; } } } if ( count01 == count10 ) return count01 ; else return -1 ; } int main ( ) { vector < vector < int > > A = { { 1 , 1 , 0 } , { 0 , 0 , 1 } , { 0 , 1 , 0 } } ; vector < vector < int > > B = { { 0 , 0 , 1 } , { 0 , 1 , 0 } , { 1 , 1 , 0 } } ; int N = A . size ( ) ; int M = B [ 0 ] . size ( ) ; cout << minSwaps ( N , M , A , B ) ; }
Maximize X such that sum of numbers in range [ 1 , X ] is at most K | C ++ program for the above approach ; Function to count the elements with sum of the first that many natural numbers less than or equal to K ; If K equals to 0 ; Stores sum of first i natural numbers ; Stores the result ; Iterate over the range [ 1 , N ] ; Increment sum by i ; Is sum is less than or equal to K ; Otherwise , ; Return res ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Count ( int N , int K ) { if ( K == 0 ) return 0 ; int sum = 0 ; int res = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { sum += i ; if ( sum <= K ) res ++ ; else break ; } return res ; } int main ( ) { int N = 6 , K = 14 ; cout << Count ( N , K ) ; return 0 ; }
Remove last occurrence of a word from a given sentence string | C ++ program for the above approach ; Function to remove last occurrence of W from S ; If M is greater than N ; Iterate while i is greater than or equal to 0 ; Stores if occurrence of W has been found or not ; Iterate over the range [ 0 , M ] ; If S [ j + 1 ] is not equal to W [ j ] ; Mark flag true and break ; If occurrence has been found ; Delete the substring over the range [ i , i + M ] ; Resize the string S ; Return S ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeLastOccurrence ( string S , string W , int N , int M ) { if ( M > N ) return S ; for ( int i = N - M ; i >= 0 ; i -- ) { int flag = 0 ; for ( int j = 0 ; j < M ; j ++ ) { if ( S [ j + i ] != W [ j ] ) { flag = 1 ; break ; } } if ( flag == 0 ) { for ( int j = i ; j < N - M ; j ++ ) S [ j ] = S [ j + M ] ; S . resize ( N - M ) ; break ; } } return S ; } int main ( ) { string S = " This ▁ is ▁ GeeksForGeeks " ; string W = " Geeks " ; int N = S . length ( ) ; int M = W . length ( ) ; cout << removeLastOccurrence ( S , W , N , M ) << endl ; return 0 ; }
Rearrange the Array to maximize the elements which is smaller than both its adjacent elements | C ++ program for the above approach ; Function to rearrange array such that count of element that are smaller than their adjacent elements is maximum ; Stores the rearranged array ; Stores the maximum count of elements ; Sort the given array ; Place the smallest ( N - 1 ) / 2 elements at odd indices ; Placing the rest of the elements at remaining indices ; If no element of the array has been placed here ; Print the resultant array ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maximumIndices ( int arr [ ] , int N ) { int temp [ N ] = { 0 } ; int maxIndices = ( N - 1 ) / 2 ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < maxIndices ; i ++ ) { temp [ 2 * i + 1 ] = arr [ i ] ; } int j = 0 ; for ( int i = maxIndices ; i < N ; ) { if ( temp [ j ] == 0 ) { temp [ j ] = arr [ i ] ; i ++ ; } j ++ ; } for ( int i = 0 ; i < N ; i ++ ) { cout << temp [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumIndices ( arr , N ) ; return 0 ; }
Check if given Strings can be made equal by inserting at most 1 String | C ++ program for the above approach ; Function to check whether two sentences can be made equal by inserting at most one sentence in one of them ; size of sentence S1 ; size of sentence S2 ; check if S1 and S2 are of equal sizes ; if both sentences are the same , return true ; Otherwise , return false ; Declare 2 deques X and Y ; insert ' ▁ ' at the end of both sentences so that the last word can be identified ; traverse the sentence S1 ; push temp in deque when a space comes in sentence i . e a word has been formed ; temp stores words of the sentence ; traverse the sentence S1 ; push temp in deque when a space comes in sentence i . e a word has been formed ; temp stores words of the sentence ; check for prefixes of both sentences ; pop the prefix from both deques till they are equal ; check for suffixes of both sentences ; pop the suffix from both deques till they are equal ; if any of the deques is empty return true ; if both the deques are not empty return false ; Driver code ; Input ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool areSimilar ( string S1 , string S2 ) { int N = S1 . size ( ) ; int M = S2 . size ( ) ; if ( N == M ) { if ( S1 == S2 ) return true ; return false ; } deque < string > X , Y ; S1 . push_back ( ' ▁ ' ) ; S2 . push_back ( ' ▁ ' ) ; string temp = " " ; for ( int i = 0 ; i < N + 1 ; i ++ ) { if ( S1 [ i ] == ' ▁ ' ) { X . push_back ( temp ) ; temp = " " ; } else { temp += S1 [ i ] ; } } for ( int i = 0 ; i < M + 1 ; i ++ ) { if ( S2 [ i ] == ' ▁ ' ) { Y . push_back ( temp ) ; temp = " " ; } else { temp += S2 [ i ] ; } } while ( X . size ( ) > 0 && Y . size ( ) > 0 && X . front ( ) == Y . front ( ) ) { X . pop_front ( ) ; Y . pop_front ( ) ; } while ( X . size ( ) > 0 && Y . size ( ) > 0 && X . back ( ) == Y . back ( ) ) { X . pop_back ( ) ; Y . pop_back ( ) ; } if ( X . size ( ) == 0 || Y . size ( ) == 0 ) return true ; return false ; } int main ( ) { string S1 = " Start ▁ practicing ▁ on ▁ GeeksforGeeks " ; string S2 = " Start ▁ GeeksforGeeks " ; if ( areSimilar ( S1 , S2 ) ) cout << " True " << endl ; else cout << " False " << endl ; return 0 ; }
Find the repeating element in an Array of size N consisting of first M natural numbers | C ++ program for the above approach ; Function to calculate the repeating character in a given permutation ; variables to store maximum element and sum of the array respectively . ; calculate sum of array ; calculate maximum element in the array ; calculating sum of permutation ; calculate required answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int repeatingElement ( int arr [ ] , int N ) { int M = 0 , sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; M = max ( M , arr [ i ] ) ; } int sum1 = M * ( M + 1 ) / 2 ; int ans = ( sum - sum1 ) / ( N - M ) ; return ans ; } int main ( ) { int arr [ ] = { 2 , 6 , 4 , 3 , 1 , 5 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << repeatingElement ( arr , N ) << endl ; return 0 ; }
Maximize value at Kth index to create N size array with adjacent difference 1 and sum less than M | C ++ program for the above approach ; Function to calculate maximum value that can be placed at the Kth index in a distribution in which difference of adjacent elements is less than 1 and total sum of distribution is M . ; variable to store final answer ; variables for binary search ; Binary search ; variable for binary search ; variable to store total sum of array ; number of indices on the left excluding the Kth index ; number of indices on the left excluding the Kth index ; add mid to final sum ; distribution on left side is possible ; sum of distribution on the left side ; sum of distribution on the left side with ( L - mid ) 1 s ; distribution on right side is possible ; sum of distribution on the right side ; sum of distribution on the left side with ( R - mid ) 1 s ; Distribution is valid ; return answer ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateMax ( int N , int M , int K ) { int ans = -1 ; int low = 0 , high = M ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int val = 0 ; int L = K - 1 ; int R = N - K ; val += mid ; if ( mid >= L ) { val += ( L ) * ( 2 * mid - L - 1 ) / 2 ; } else { val += mid * ( mid - 1 ) / 2 + ( L - mid ) ; } if ( mid >= R ) { val += ( R ) * ( 2 * mid - R - 1 ) / 2 ; } else { val += mid * ( mid - 1 ) / 2 + ( R - mid ) ; } if ( val <= M ) { ans = max ( ans , mid ) ; low = mid + 1 ; } else high = mid - 1 ; } return ans ; } int main ( ) { int N = 7 , M = 100 , K = 6 ; cout << calculateMax ( N , M , K ) << endl ; return 0 ; }
Minimum time required to color all edges of a Tree | C ++ program for the above approach ; Stores the required answer ; Stores the graph ; Function to add edges ; Function to calculate the minimum time required to color all the edges of a tree ; Starting from time = 0 , for all the child edges ; If the edge is not visited yet . ; Time of coloring of the current edge ; If the parent edge has been colored at the same time ; Update the maximum time ; Recursively call the function to its child node ; Driver Code ; Function call ; Finally , print the answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; int ans = 0 ; vector < int > edges [ 100000 ] ; void Add_edge ( int u , int v ) { edges [ u ] . push_back ( v ) ; edges [ v ] . push_back ( u ) ; } void minTimeToColor ( int node , int parent , int arrival_time ) { int current_time = 0 ; for ( auto x : edges [ node ] ) { if ( x != parent ) { ++ current_time ; if ( current_time == arrival_time ) ++ current_time ; ans = max ( ans , current_time ) ; minTimeToColor ( x , node , current_time ) ; } } } int main ( ) { pair < int , int > A [ ] = { { 1 , 2 } , { 2 , 3 } , { 3 , 4 } } ; for ( auto i : A ) { Add_edge ( i . first , i . second ) ; } minTimeToColor ( 1 , -1 , 0 ) ; cout << ans << " STRNEWLINE " ; }
Largest number having both positive and negative values present in the array | C ++ program for the above approach ; Function to find the largest number k such that both k and - k are present in the array ; Stores the resultant value of K ; Sort the array arr [ ] ; Initialize two variables to use two pointers technique ; Iterate until the value of l is less than r ; Find the value of the sum ; If the sum is 0 , then the resultant element is found ; If the sum is negative ; Otherwise , decrement r ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNum ( vector < int > arr ) { int res = 0 ; sort ( arr . begin ( ) , arr . end ( ) ) ; int l = 0 , r = arr . size ( ) - 1 ; while ( l < r ) { int sum = arr [ l ] + arr [ r ] ; if ( sum == 0 ) { res = max ( res , max ( arr [ l ] , arr [ r ] ) ) ; return res ; } else if ( sum < 0 ) { l ++ ; } else { r -- ; } } return res ; } int main ( ) { vector < int > arr = { 3 , 2 , -2 , 5 , -3 } ; cout << ( largestNum ( arr ) ) ; }
Find elements larger than half of the elements in an array | Set 2 | C ++ program for the above approach ; Function to find the element that are larger than half of elements of the array ; Find the value of mid ; Stores the maximum element ; Stores the frequency of each array element ; Traverse the array in the reverse order ; Decrement the value of count [ i ] and mid ; Print the current element ; Check if the value of mid is equal to 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findLarger ( int arr [ ] , int n ) { int mid = ( n + 1 ) / 2 ; int mx = * max_element ( arr , arr + n ) ; int count [ mx + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { count [ arr [ i ] ] ++ ; } for ( int i = mx ; i >= 0 ; i -- ) { while ( count [ i ] > 0 ) { count [ i ] -- ; mid -- ; cout << i << ' ▁ ' ; if ( mid == 0 ) break ; } if ( mid == 0 ) break ; } } int main ( ) { int arr [ ] = { 10 , 4 , 2 , 8 , 9 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findLarger ( arr , N ) ; return 0 ; }
Probability of obtaining pairs from two arrays such that element from the first array is smaller than that of the second array | C ++ program for the above approach ; Function to find probability such that x < y and X belongs to arr1 [ ] and Y belongs to arr2 [ ] ; Stores the length of arr1 ; Stores the length of arr2 ; Stores the result ; Traverse the arr1 [ ] ; Stores the count of elements in arr2 that are greater than arr [ i ] ; Traverse the arr2 [ ] ; If arr2 [ j ] is greater than arr1 [ i ] ; Increment res by y ; Update the value of res ; Return resultant probability ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double probability ( vector < int > arr1 , vector < int > arr2 ) { int N = arr1 . size ( ) ; int M = arr2 . size ( ) ; double res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int y = 0 ; for ( int j = 0 ; j < M ; j ++ ) { if ( arr2 [ j ] > arr1 [ i ] ) y ++ ; } res += y ; } res = ( double ) res / ( double ) ( N * M ) ; return res ; } int main ( ) { vector < int > arr1 = { 5 , 2 , 6 , 1 } ; vector < int > arr2 = { 1 , 6 , 10 , 1 } ; cout << probability ( arr1 , arr2 ) ; }
Probability of obtaining pairs from two arrays such that element from the first array is smaller than that of the second array | C ++ program for the above approach ; Function to find probability such that x < y and X belongs to arr1 [ ] & Y belongs to arr2 [ ] ; Stores the length of arr1 ; Stores the length of arr2 ; Stores the result ; Sort the arr2 [ ] in the ascending order ; Traverse the arr1 [ ] ; Stores the count of elements in arr2 that are greater than arr [ i ] ; Increment res by y ; Update the resultant probability ; Return the result ; Function to return the count of elements from the array which are greater than k ; Stores the index of the leftmost element from the array which is at least k ; Finds number of elements greater than k ; If mid element is at least K , then update the value of leftGreater and r ; Update leftGreater ; Update r ; If mid element is at most K , then update the value of 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 k ) ; float probability ( int * arr1 , int * arr2 ) { int N = 4 ; int M = 4 ; float res = 0 ; sort ( arr2 , arr2 + M ) ; for ( int i = 0 ; i < N ; i ++ ) { int y = countGreater ( arr2 , arr1 [ i ] ) ; res += y ; } res = res / ( N * M ) ; return res ; } int countGreater ( int * arr , int k ) { int n = 4 ; 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 arr1 [ ] = { 5 , 2 , 6 , 1 } ; int arr2 [ ] = { 1 , 6 , 10 , 1 } ; cout << probability ( arr1 , arr2 ) ; return 0 ; }
Minimize cost to cover floor using tiles of dimensions 1 * 1 and 1 * 2 | C ++ program for the above approach ; Function to find the minimum cost of flooring with the given tiles ; Store the size of the 2d array ; Stores the minimum cost of flooring ; Traverse the 2d array row - wise ; If the current character is ' * ' , then skip it ; Choose the 1 * 1 tile if j is m - 1 ; If consecutive ' . ' are present , the greedily choose tile with the minimum cost ; Otherwise choose the 1 * 1 tile ; Print the minimum cost ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minCost ( vector < vector < char > > arr , int A , int B ) { int n = arr . size ( ) ; int m = arr [ 0 ] . size ( ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( arr [ i ] [ j ] == ' * ' ) continue ; if ( j == m - 1 ) ans += A ; else { if ( arr [ i ] [ j + 1 ] == ' . ' ) { ans += min ( 2 * A , B ) ; j ++ ; } else ans += A ; } } } cout << ans ; } int main ( ) { vector < vector < char > > arr = { { ' . ' , ' . ' , ' * ' } , { ' . ' , ' * ' , ' * ' } } ; int A = 2 , B = 10 ; minCost ( arr , A , B ) ; return 0 ; }
Count inversions in a permutation of first N natural numbers | C ++ program for the above approach ; Function to count number of inversions in a permutation of first N natural numbers ; Store array elements in sorted order ; Store the count of inversions ; Traverse the array ; Store the index of first occurrence of arr [ i ] in vector V ; Add count of smaller elements than current element ; Erase current element from vector and go to next index ; Print the result ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countInversions ( int arr [ ] , int n ) { vector < int > v ; for ( int i = 1 ; i <= n ; i ++ ) { v . push_back ( i ) ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { auto itr = lower_bound ( v . begin ( ) , v . end ( ) , arr [ i ] ) ; ans += itr - v . begin ( ) ; v . erase ( itr ) ; } cout << ans ; return 0 ; } int main ( ) { int arr [ ] = { 2 , 3 , 1 , 5 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countInversions ( arr , n ) ; return 0 ; }
Find all possible pairs with given Bitwise OR and Bitwise XOR values | C ++ code for the above approach ; Function to find pairs with XOR equal to A and OR equal to B ; Iterate from 1 to B ; Check if ( i OR y ) is B ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPairs ( int A , int B ) { for ( int i = 1 ; i <= B ; i ++ ) { int y = A ^ i ; if ( y > 0 and ( i y ) == B ) { cout << i << " ▁ " << y << endl ; } } } int main ( ) { int A = 8 , B = 10 ; findPairs ( A , B ) ; return 0 ; }
Count distinct elements from a range of a sorted sequence from a given frequency array | C ++ program for the above approach ; Function to find the first index with value is at least element ; Update the value of left ; Binary search for the element ; Find the middle element ; Check if the value lies between the elements at index mid - 1 and mid ; Check in the right subarray ; Update the value of left ; Check in left subarray ; Update the value of right ; Function to count the number of distinct elements over the range [ L , R ] in the sorted sequence ; Stores the count of distinct elements ; Create the prefix sum array ; Update the value of count ; Update the value of pref [ i ] ; Calculating the first index of L and R using binary search ; Print the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binarysearch ( int array [ ] , int right , int element ) { int left = 1 ; while ( left <= right ) { int mid = ( left + right / 2 ) ; if ( array [ mid ] == element ) { return mid ; } if ( mid - 1 > 0 && array [ mid ] > element && array [ mid - 1 ] < element ) { return mid ; } else if ( array [ mid ] < element ) { left = mid + 1 ; } else { right = mid - 1 ; } } return 1 ; } void countDistinct ( vector < int > arr , int L , int R ) { int count = 0 ; int pref [ arr . size ( ) + 1 ] ; for ( int i = 1 ; i <= arr . size ( ) ; ++ i ) { count += arr [ i - 1 ] ; pref [ i ] = count ; } int left = binarysearch ( pref , arr . size ( ) + 1 , L ) ; int right = binarysearch ( pref , arr . size ( ) + 1 , R ) ; cout << right - left + 1 ; } int main ( ) { vector < int > arr { 3 , 6 , 7 , 1 , 8 } ; int L = 3 ; int R = 7 ; countDistinct ( arr , L , R ) ; }
Count substrings having frequency of a character exceeding that of another character in a string | C ++ program for the above approach ; Function to find the number of substrings having the frequency of ' a ' greater than frequency of ' c ' ; Stores the size of the string ; Stores the resultant count of substrings ; Traverse the given string ; Store the difference between frequency of ' a ' and ' c ' ; Traverse all substrings beginning at index i ; If the frequency of ' a ' is greater than ' c ' ; Print the answer ; Drive Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countSubstrings ( string & s ) { int n = s . length ( ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; for ( int j = i ; j < n ; j ++ ) { if ( s [ j ] == ' a ' ) cnt ++ ; else if ( s [ j ] == ' c ' ) cnt -- ; if ( cnt > 0 ) { ans ++ ; } } } cout << ans ; } int main ( ) { string S = " abccaab " ; countSubstrings ( S ) ; return 0 ; }
Find Unique ID and Domain Name of a Website from a string | C ++ program for the above approach ; Function to check if a character is alphabet or not ; Function to check if a character is a numeric or not ; Function to find ID and Domain name from a given string ; Stores ID and the domain names ; Stores the words of string S ; Stores the temporary word ; Traverse the string S ; If the current character is space ; Push the curr in words ; Update the curr ; Otherwise ; If curr is not empty ; If length of ss is 10 ; Traverse the string ss ; If j is in the range [ 5 , 9 ) ; If current character is not numeric ; Mark flag 1 ; Otherwise ; If current character is not alphabet ; Mark flag 1 ; If flag is false ; Assign ss to ID ; If substring formed by the first 3 character is " www " and last 3 character is " moc " ; Update the domain name ; Print ID and Domain ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool ischar ( char x ) { if ( ( x >= ' A ' && x <= ' Z ' ) || ( x >= ' a ' && x <= ' z ' ) ) { return 1 ; } return 0 ; } bool isnum ( char x ) { if ( x >= '0' && x <= '9' ) return 1 ; return 0 ; } void findIdandDomain ( string S , int N ) { string ID , Domain ; vector < string > words ; string curr = " " ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' ▁ ' ) { words . push_back ( curr ) ; curr = " " ; } else { if ( S [ i ] == ' . ' ) { if ( i + 1 == N || ( i + 1 < N && S [ i + 1 ] == ' ▁ ' ) ) continue ; } curr += S [ i ] ; } } if ( curr . length ( ) ) words . push_back ( curr ) ; for ( string ss : words ) { if ( ss . size ( ) == 10 ) { bool flag = 0 ; for ( int j = 0 ; j <= 9 ; j ++ ) { if ( j >= 5 && j < 9 ) { if ( isnum ( ss [ j ] ) == 0 ) flag = 1 ; } else { if ( ischar ( ss [ j ] ) == 0 ) flag = 1 ; } } if ( ! flag ) { ID = ss ; } } if ( ss . substr ( 0 , 3 ) == " www " && ss . substr ( ss . length ( ) - 3 , 3 ) == " com " ) { Domain = ss . substr ( 4 , ss . size ( ) - 4 ) ; } } cout << " ID ▁ = ▁ " << ID << endl ; cout << " Domain ▁ = ▁ " << Domain ; } int main ( ) { string S = " We ▁ thank ▁ ABCDE1234F ▁ for ▁ visiting ▁ " " us ▁ and ▁ buying ▁ " " products ▁ item ▁ AMZrr @ ! k . ▁ For ▁ more ▁ " " offers , ▁ visit ▁ " " us ▁ at ▁ www . amazon . com " ; int N = S . length ( ) ; findIdandDomain ( S , N ) ; return 0 ; }
Capacity To Ship Packages Within D Days | C ++ program for the above approach ; Function to check if the weights can be delivered in D days or not ; Stores the count of days required to ship all the weights if the maximum capacity is mx ; Traverse all the weights ; If total weight is more than the maximum capacity ; If days are more than D , then return false ; Return true for the days < D ; Function to find the least weight capacity of a boat to ship all the weights within D days ; Stores the total weights to be shipped ; Find the sum of weights ; Stores the maximum weight in the array that has to be shipped ; Store the ending value for the search space ; Store the required result ; Perform binary search ; Store the middle value ; If mid can be shipped , then update the result and end value of the search space ; Search for minimum value in the right part ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( int weight [ ] , int n , int D , int mx ) { int st = 1 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += weight [ i ] ; if ( sum > mx ) { st ++ ; sum = weight [ i ] ; } if ( st > D ) return false ; } return true ; } void shipWithinDays ( int weight [ ] , int D , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += weight [ i ] ; int s = weight [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { s = max ( s , weight [ i ] ) ; } int e = sum ; int res = -1 ; while ( s <= e ) { int mid = s + ( e - s ) / 2 ; if ( isValid ( weight , n , D , mid ) ) { res = mid ; e = mid - 1 ; } else s = mid + 1 ; } cout << res ; } int main ( ) { int weight [ ] = { 9 , 8 , 10 } ; int D = 3 ; int N = sizeof ( weight ) / sizeof ( weight [ 0 ] ) ; shipWithinDays ( weight , D , N ) ; return 0 ; }
Shortest path for a thief to reach the Nth house avoiding policemen | C ++ program for the above approach ; Function to create graph edges where node A and B can be visited ; Visit all the connections ; If a policeman is at any point of connection , leave that connection . Insert the connect otherwise . ; Function to find the shortest path ; If police is at either at the 1 - st house or at N - th house ; The thief cannot reach the N - th house ; Stores Edges of graph ; Function call to store connections ; Stores wheather node is visited or not ; Stores distances from the root node ; Visit all nodes that are currently in the queue ; If current node is not visited already ; Driver Code ; N : Number of houses E : Number of edges ; Given positions ; Given Paths ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void createGraph ( unordered_map < int , vector < int > > & adj , int paths [ ] [ 2 ] , int A [ ] , int N , int E ) { for ( int i = 0 ; i < E ; i ++ ) { if ( ! A [ paths [ i ] [ 0 ] ] && ! A [ paths [ i ] [ 1 ] ] ) { adj [ paths [ i ] [ 0 ] ] . push_back ( paths [ i ] [ 1 ] ) ; } } } int minPath ( int paths [ ] [ 2 ] , int A [ ] , int N , int E ) { if ( A [ 0 ] == 1 A [ N - 1 ] == 1 ) return -1 ; unordered_map < int , vector < int > > adj ; createGraph ( adj , paths , A , N , E ) ; vector < int > visited ( N , 0 ) ; int dist [ N ] ; dist [ 0 ] = 0 ; queue < int > q ; q . push ( 0 ) ; visited [ 0 ] = 1 ; while ( ! q . empty ( ) ) { int temp = q . front ( ) ; q . pop ( ) ; for ( auto x : adj [ temp ] ) { if ( ! visited [ x ] ) { q . push ( x ) ; visited [ x ] = 1 ; dist [ x ] = dist [ temp ] + 1 ; } } } if ( ! visited [ N - 1 ] ) return -1 ; else return dist [ N - 1 ] ; } int main ( ) { int N = 5 , E = 5 ; int A [ ] = { 0 , 1 , 0 , 0 , 0 } ; int paths [ ] [ 2 ] = { { 0 , 1 } , { 0 , 2 } , { 1 , 4 } , { 2 , 3 } , { 3 , 4 } } ; cout << minPath ( paths , A , N , E ) ; return 0 ; }
Find a point whose sum of distances from all given points on a line is K | C ++ program for the above approach ; Function to find the sum of distances of all points from a given point ; Stores sum of distances ; Traverse the array ; Return the sum ; Function to find such a point having sum of distances of all other points from this point equal to K ; If N is odd keep left as arr [ n / 2 ] else keep left as arr [ n / 2 - 1 ] + 1 ; ; Keep right as arr [ N - 1 ] ; Perform binary search in the right half ; Calculate the mid index of the range ; If temp is equal to K ; Print the value of mid ; If the value of K < temp ; Update right to mid - 1 ; If the value of K > temp ; Update left to mid + 1 ; Update the value of left ; Update the value of right ; Perform binary search on the left half ; Calculate the mid index of the range ; If temp is equal to K ; Print mid ; if K > temp ; Update right to mid - 1 ; If K < temp ; Update left to mid + 1 ; If no such point found ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int * arr , int N , int pt ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += abs ( arr [ i ] - pt ) ; } return sum ; } void findPoint ( int * arr , int N , int K ) { int left ; if ( N % 2 ) { left = arr [ N / 2 ] ; } else { left = arr [ N / 2 - 1 ] + 1 ; } int right = arr [ N - 1 ] ; while ( left <= right ) { int mid = ( left + right ) / 2 ; int temp = findSum ( arr , N , mid ) ; if ( temp == K ) { cout << mid << endl ; return ; } else if ( K < temp ) { right = mid - 1 ; } else { left = mid + 1 ; } } left = arr [ 0 ] ; right = arr [ N / 2 ] - 1 ; while ( left <= right ) { int mid = ( left + right ) / 2 ; int temp = findSum ( arr , N , mid ) ; if ( temp == K ) { cout << mid << endl ; return ; } else if ( K > temp ) { right = mid - 1 ; } else { left = mid + 1 ; } } cout << " - 1" << endl ; } int main ( ) { int arr [ ] = { 1 , 3 , 6 , 7 , 11 } ; int K = 18 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findPoint ( arr , N , K ) ; return 0 ; }
Generate an array consisting of most frequent greater elements present on the right side of each array element | C ++ program for the above approach ; Function to generate an array containing the most frequent greater element on the right side of each array element ; Stores the generated array ; Traverse the array arr [ ] ; Store the result for the current index and its frequency ; Iterate over the right subarray ; Store the frequency of the current array element ; If the frequencies are equal ; Update ans to smaller of the two elements ; If count of new element is more than count of ans ; Insert answer in the array ; Print the resultant array ; Driver Code ; Given Input
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findArray ( int arr [ ] , int n ) { vector < int > v ; for ( int i = 0 ; i < n ; i ++ ) { int ans = -1 , old_c = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] > arr [ i ] ) { int curr_c = count ( & arr [ j ] , & arr [ n ] , arr [ j ] ) ; if ( curr_c == old_c ) { if ( arr [ j ] < ans ) ans = arr [ j ] ; } if ( curr_c > old_c ) { ans = arr [ j ] ; old_c = curr_c ; } } } v . push_back ( ans ) ; } for ( int i = 0 ; i < v . size ( ) ; i ++ ) cout << v [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 4 , 5 , 2 , 25 , 10 , 5 , 10 , 3 , 10 , 5 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findArray ( arr , size ) ; return 0 ; }
Smallest index that splits an array into two subarrays with equal product | C ++ program for the above approach ; Function to find the smallest index that splits the array into two subarrays with equal product ; Stores the product of the array ; Traverse the given array ; Stores the product of left and the right subarrays ; Traverse the given array ; Update the products ; Check if product is equal ; Print resultant index ; If no partition exists , then print - 1. ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void prodEquilibrium ( int arr [ ] , int N ) { int product = 1 ; for ( int i = 0 ; i < N ; i ++ ) { product *= arr [ i ] ; } int left = 1 ; int right = product ; for ( int i = 0 ; i < N ; i ++ ) { left = left * arr [ i ] ; right = right / arr [ i ] ; if ( left == right ) { cout << i + 1 << endl ; return ; } } cout << -1 << endl ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 3 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; prodEquilibrium ( arr , N ) ; return 0 ; }
Count triplets from a sorted array having difference between adjacent elements equal to D | C ++ program for the above approach ; Function to count the number of triplets having difference between adjacent elements equal to D ; Stores the frequency of array elements ; Stores the count of resultant triplets ; Traverse the array ; Check if arr [ i ] - D and arr [ i ] - 2 * D exists in the Hashmap or not ; Update the value of ans ; Increase the frequency of the current element ; Return the resultant count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int D , vector < int > & arr ) { unordered_map < int , int > freq ; int ans = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { if ( freq . find ( arr [ i ] - D ) != freq . end ( ) && freq . find ( arr [ i ] - 2 * D ) != freq . end ( ) ) { ans += freq [ arr [ i ] - D ] * freq [ arr [ i ] - 2 * D ] ; } freq [ arr [ i ] ] ++ ; } return ans ; } int main ( ) { vector < int > arr { 1 , 2 , 4 , 5 , 7 , 8 , 10 } ; int D = 1 ; cout << countTriplets ( D , arr ) ; return 0 ; }
Find the array element having equal sum of Prime Numbers on its left and right | C ++ program for the above approach ; Function to find an index in the array having sum of prime numbers to its left and right equal ; Stores the maximum value present in the array ; Stores all positive elements which are <= max_value ; If 1 is present ; Remove 1 ; Sieve of Eratosthenes to store all prime numbers which are <= max_value in the Map ; Erase non - prime numbers ; Stores the sum of prime numbers from left ; Stores the sum of prime numbers to the left of each index ; Stores the sum of prime numbers to the left of the current index ; Add current value to the prime sum if the current value is prime ; Stores the sum of prime numbers from right ; Stores the sum of prime numbers to the right of each index ; Stores the sum of prime numbers to the right of the current index ; Add current value to the prime sum if the current value is prime ; Traverse through the two arrays to find the index ; Compare the values present at the current index ; Return the index where both the values are same ; No index is found . ; Driver Code ; Given array arr [ ] ; Size of Array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_index ( int arr [ ] , int N ) { int max_value = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { max_value = max ( max_value , arr [ i ] ) ; } map < int , int > store ; for ( int i = 1 ; i <= max_value ; i ++ ) { store [ i ] ++ ; } if ( store . find ( 1 ) != store . end ( ) ) { store . erase ( 1 ) ; } for ( int i = 2 ; i <= sqrt ( max_value ) ; i ++ ) { int multiple = 2 ; while ( ( i * multiple ) <= max_value ) { if ( store . find ( i * multiple ) != store . end ( ) ) { store . erase ( i * multiple ) ; } multiple ++ ; } } int prime_sum_from_left = 0 ; int first_array [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { first_array [ i ] = prime_sum_from_left ; if ( store . find ( arr [ i ] ) != store . end ( ) ) { prime_sum_from_left += arr [ i ] ; } } int prime_sum_from_right = 0 ; int second_array [ N ] ; for ( int i = N - 1 ; i >= 0 ; i -- ) { second_array [ i ] = prime_sum_from_right ; if ( store . find ( arr [ i ] ) != store . end ( ) ) { prime_sum_from_right += arr [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( first_array [ i ] == second_array [ i ] ) { return i ; } } return -1 ; } int main ( ) { int arr [ ] = { 11 , 4 , 7 , 6 , 13 , 1 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << find_index ( arr , N ) ; return 0 ; }
Convert an array to reduced form | Set 3 ( Binary Search ) | C ++ program for the above approach ; Function to find the reduced form of the given array arr [ ] ; Stores the sorted form of the the given array arr [ ] ; Sort the array brr [ ] ; Traverse the given array arr [ ] ; Perform the Binary Search ; Calculate the value of mid ; Print the current index and break ; Update the value of l ; Update the value of r ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void convert ( int arr [ ] , int n ) { int brr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) brr [ i ] = arr [ i ] ; sort ( brr , brr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { int l = 0 , r = n - 1 , mid ; while ( l <= r ) { mid = ( l + r ) / 2 ; if ( brr [ mid ] == arr [ i ] ) { cout << mid << ' ▁ ' ; break ; } else if ( brr [ mid ] < arr [ i ] ) { l = mid + 1 ; } else { r = mid - 1 ; } } } } int main ( ) { int arr [ ] = { 10 , 20 , 15 , 12 , 11 , 50 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; convert ( arr , N ) ; return 0 ; }
Find the array element having equal count of Prime Numbers on its left and right | C ++ program for the above approach ; Function to find the index of the array such that the count of prime numbers to its either ends are same ; Store the maximum value in the array ; Traverse the array arr [ ] ; Stores all the numbers ; Iterate over the range [ 1 , Max ] ; Increment the value of st [ i ] ; Removes 1 from the map St ; Perform Sieve of Prime Numbers ; While i * j is less than the maxValue ; If i * j is in map St ; Erase the value ( i * j ) ; Increment the value of j ; Stores the count of prime from index 0 to i ; Stores the count of prime numbers ; Traverse the array arr [ ] ; If arr [ i ] is present in the map st ; Stores the count of prime from index i to N - 1 ; Stores the count of prime numbers ; Iterate over the range [ 0 , N - 1 ] in reverse order ; If arr [ i ] is in map st ; Iterate over the range [ 0 , N - 1 ] ; If prefix [ i ] is equal to the Suffix [ i ] ; Return - 1 if no such index is present ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findIndex ( int arr [ ] , int N ) { int maxValue = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { maxValue = max ( maxValue , arr [ i ] ) ; } map < int , int > St ; for ( int i = 1 ; i <= maxValue ; i ++ ) { St [ i ] ++ ; } if ( St . find ( 1 ) != St . end ( ) ) { St . erase ( 1 ) ; } for ( int i = 2 ; i <= sqrt ( maxValue ) ; i ++ ) { int j = 2 ; while ( ( i * j ) <= maxValue ) { if ( St . find ( i * j ) != St . end ( ) ) { St . erase ( i * j ) ; } j ++ ; } } int LeftCount = 0 ; int Prefix [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { Prefix [ i ] = LeftCount ; if ( St . find ( arr [ i ] ) != St . end ( ) ) { LeftCount ++ ; } } int RightCount = 0 ; int Suffix [ N ] ; for ( int i = N - 1 ; i >= 0 ; i -- ) { Suffix [ i ] = RightCount ; if ( St . find ( arr [ i ] ) != St . end ( ) ) { RightCount ++ ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( Prefix [ i ] == Suffix [ i ] ) { return i ; } } return -1 ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 7 , 5 , 10 , 1 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findIndex ( arr , N ) ; return 0 ; }
Numbers of pairs from an array whose average is also present in the array | C ++ program for the above approach ; Function to count the number of pairs from the array having sum S ; Stores the total count of pairs whose sum is 2 * S ; Generate all possible pairs and check their sums ; If the sum is S , then increment the count ; Return the total count of pairs ; Function to count of pairs having whose average exists in the array ; Initialize the count ; Use set to remove duplicates ; Add elements in the set ; For every sum , count all possible pairs ; Return the total count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getCountPairs ( vector < int > arr , int N , int S ) { int count = 0 ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < arr . size ( ) ; j ++ ) { if ( ( arr [ i ] + arr [ j ] ) == S ) count ++ ; } } return count ; } int countPairs ( vector < int > arr , int N ) { int count = 0 ; unordered_set < int > S ; for ( int i = 0 ; i < N ; i ++ ) S . insert ( arr [ i ] ) ; for ( int ele : S ) { int sum = 2 * ele ; count += getCountPairs ( arr , N , sum ) ; } return count ; } int main ( ) { vector < int > arr = { 4 , 2 , 5 , 1 , 3 , 5 } ; int N = arr . size ( ) ; cout << countPairs ( arr , N ) ; return 0 ; }
Count numbers up to N having exactly 5 divisors | C ++ program for the above approach ; Function to calculate the value of ( x ^ y ) using binary exponentiation ; Stores the value of x ^ y ; Base Case ; If y is odd multiply x with result ; Otherwise , divide y by 2 ; Function to perform the Sieve Of Eratosthenes to find the prime number over the range [ 1 , 10 ^ 5 ] ; If prime [ p ] is not changed then it is a prime ; Set all the multiples of p to non - prime ; Iterate over the range [ 1 , MAX ] ; Store all the prime number ; Function to find the primes having only 5 divisors ; Base Case ; First value of the pair has the prime number and the second value has the count of primes till that prime numbers ; Precomputing all the primes ; Perform the Binary search ; Calculate the fourth power of the curr and prev ; Return value of mid ; Return value of mid - 1 ; Update the value of high ; Update the value of low ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE const int MAX = 1e5 ; using namespace std ; ll power ( ll x , unsigned ll y ) { ll res = 1 ; if ( x == 0 ) return 0 ; while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) ; y = y >> 1 ; x = ( x * x ) ; } return res ; } void SieveOfEratosthenes ( vector < pair < ll , ll > > & v ) { bool prime [ MAX + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } int num = 1 ; for ( int i = 1 ; i <= MAX ; i ++ ) { if ( prime [ i ] ) { v . push_back ( { i , num } ) ; num ++ ; } } } int countIntegers ( ll n ) { if ( n < 16 ) { return 0 ; } vector < pair < ll , ll > > v ; SieveOfEratosthenes ( v ) ; int low = 0 ; int high = v . size ( ) - 1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; ll curr = power ( v [ mid ] . first , 4 ) ; ll prev = power ( v [ mid - 1 ] . first , 4 ) ; if ( curr == n ) { return v [ mid ] . second ; } else if ( curr > n and prev <= n ) { return v [ mid - 1 ] . second ; } else if ( curr > n ) { high = mid - 1 ; } else { low = mid + 1 ; } } return 0 ; } int main ( ) { ll N = 100 ; cout << countIntegers ( N ) ; return 0 ; }
Sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2 | C ++ program for the above approach ; Function to check if N is power of 2 or not ; Base Case ; Return true if N is power of 2 ; Function to print array of strings in ascending order ; Sort strings in ascending order ; Print the array ; Function to sort the strings after modifying each string according to the given conditions ; Store the frequency of each characters of the string ; Stores the required array of strings ; Traverse the array of strings ; Temporary string ; Stores frequency of each alphabet of the string ; Update frequency of S [ i ] [ j ] ; Traverse the map freq ; Check if the frequency of i . first is a power of 2 ; Update string st ; Clear the map ; Null string ; Sort the string in descending order ; Update res ; Print the array of strings ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfTwo ( int n ) { if ( n == 0 ) return false ; return ( ceil ( log2 ( n ) ) == floor ( log2 ( n ) ) ) ; } void printArray ( vector < string > res ) { sort ( res . begin ( ) , res . end ( ) ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { cout << res [ i ] << " ▁ " ; } } void sortedStrings ( string S [ ] , int N ) { unordered_map < char , int > freq ; vector < string > res ; for ( int i = 0 ; i < N ; i ++ ) { string st = " " ; for ( int j = 0 ; j < S [ i ] . size ( ) ; j ++ ) { freq [ S [ i ] [ j ] ] ++ ; } for ( auto i : freq ) { if ( isPowerOfTwo ( i . second ) ) { for ( int j = 0 ; j < i . second ; j ++ ) { st += i . first ; } } } freq . clear ( ) ; if ( st . size ( ) == 0 ) continue ; sort ( st . begin ( ) , st . end ( ) , greater < char > ( ) ) ; res . push_back ( st ) ; } printArray ( res ) ; } int main ( ) { string arr [ ] = { " aaacbb " , " geeks " , " aaa " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortedStrings ( arr , N ) ; return 0 ; }
Modify string by replacing all occurrences of given characters by specified replacing characters | C ++ program for the above approach ; Function to modify given string by replacing characters ; Store the size of string and the number of pairs ; Initialize 2 character arrays ; Traverse the string s Update arrays arr [ ] and brr [ ] ; Traverse the array of pairs p ; a -> Character to be replaced b -> Replacing character ; Iterate over the range [ 0 , 25 ] ; If it is equal to current character , then replace it in the array b ; Print the array brr [ ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void replaceCharacters ( string s , vector < vector < char > > p ) { int n = s . size ( ) , k = p . size ( ) ; char arr [ 26 ] ; char brr [ 26 ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ s [ i ] - ' a ' ] = s [ i ] ; brr [ s [ i ] - ' a ' ] = s [ i ] ; } for ( int j = 0 ; j < k ; j ++ ) { char a = p [ j ] [ 0 ] , b = p [ j ] [ 1 ] ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( arr [ i ] == a ) { brr [ i ] = b ; } } } for ( int i = 0 ; i < n ; i ++ ) { cout << brr [ s [ i ] - ' a ' ] ; } } int main ( ) { string S = " aabbgg " ; vector < vector < char > > P { { ' a ' , ' b ' } , { ' b ' , ' g ' } , { ' g ' , ' a ' } } ; replaceCharacters ( S , P ) ; return 0 ; }
Smallest Semi | C ++ program for the above approach ; Function to find all the prime numbers using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is a prime ; Set all multiples of p as non - prime ; Function to find the smallest semi - prime number having a difference between any of its two divisors at least N ; Stores the prime numbers ; Fill the prime array ; Initialize the first divisor ; Find the value of the first prime number ; Initialize the second divisor ; Find the second prime number ; Print the semi - prime number ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define MAX 100001 NEW_LINE using namespace std ; void SieveOfEratosthenes ( bool prime [ ] ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p < MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i < MAX ; i += p ) prime [ i ] = false ; } } } void smallestSemiPrime ( int n ) { bool prime [ MAX ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime ) ; int num1 = n + 1 ; while ( prime [ num1 ] != true ) { num1 ++ ; } int num2 = num1 + n ; while ( prime [ num2 ] != true ) { num2 ++ ; } cout << num1 * 1LL * num2 ; } int main ( ) { int N = 2 ; smallestSemiPrime ( N ) ; return 0 ; }
Check if a number can be represented as product of two positive perfect cubes | C ++ program for the above approach ; Function to check if N can be represented as the product of two perfect cubes or not ; Stores the perfect cubes ; Traverse the Map ; Stores the first number ; Stores the second number ; Search the pair for the first number to obtain product N from the Map ; If N cannot be represented as the product of the two positive perfect cubes ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void productOfTwoPerfectCubes ( int N ) { map < int , int > cubes ; for ( int i = 1 ; i * i * i <= N ; i ++ ) cubes [ i * i * i ] = i ; for ( auto itr = cubes . begin ( ) ; itr != cubes . end ( ) ; itr ++ ) { int firstNumber = itr -> first ; if ( N % itr -> first == 0 ) { int secondNumber = N / itr -> first ; if ( cubes . find ( secondNumber ) != cubes . end ( ) ) { cout << " Yes " ; return ; } } } cout << " No " ; } int main ( ) { int N = 216 ; productOfTwoPerfectCubes ( N ) ; return 0 ; }
Check if a number can be represented as product of two positive perfect cubes | C ++ program for the above approach ; Function to check if the number N can be represented as the product of two perfect cubes or not ; If cube of cube_root is N ; Otherwise , print No ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void productOfTwoPerfectCubes ( int N ) { int cube_root ; cube_root = round ( cbrt ( N ) ) ; if ( cube_root * cube_root * cube_root == N ) { cout << " Yes " ; return ; } else { cout << " No " ; return ; } } int main ( ) { int N = 216 ; productOfTwoPerfectCubes ( N ) ; return 0 ; }
Size of smallest square that contains N non | CPP program for the above approach ; Function to check if side of square X can pack all the N rectangles or not ; Find the number of rectangle it can pack ; If val is atleast N , then return true ; Otherwise , return false ; Function to find the size of the smallest square that can contain N rectangles of dimensions W * H ; Stores the lower bound ; Stores the upper bound ; Iterate until i is less than j ; Calculate the mid value ; If the current size of square cam contain N rectangles ; Otherwise , update i ; Return the minimum size of the square required ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool bound ( int w , int h , int N , int x ) { int val = ( x / w ) * ( x / h ) ; if ( val >= N ) return true ; else return false ; } int FindSquare ( int N , int W , int H ) { int i = 1 ; int j = W * H * N ; while ( i < j ) { int mid = i + ( j - i ) / 2 ; if ( bound ( W , H , N , mid ) ) j = mid ; else i = mid + 1 ; } return j ; } int main ( ) { int W = 2 ; int H = 3 ; int N = 10 ; cout << FindSquare ( N , W , H ) ; }
Count integers up to N that are equal to at least 2 nd power of any integer exceeding 1 | C ++ program for the above approach ; Function to count the integers up to N that can be represented as a ^ b , where a & b > 1 ; Initialize a HashSet ; Iterating over the range [ 2 , sqrt ( N ) ] ; Generate all possible power of x ; Multiply x by i ; If the generated number lies in the range [ 1 , N ] then insert it in HashSet ; Print the total count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNumberOfPairs ( int N ) { unordered_set < int > st ; for ( int i = 2 ; i * i <= N ; i ++ ) { int x = i ; while ( x <= N ) { x *= i ; if ( x <= N ) { st . insert ( x ) ; } } } cout << st . size ( ) ; } int main ( ) { int N = 10000 ; printNumberOfPairs ( N ) ; return 0 ; }
Maximize product of lengths of strings having no common characters | C ++ program for the above approach ; Function to count the number of set bits in the integer n ; Stores the count of set bits in n ; Return the count ; Function to find the maximum product of pair of strings having no common characters ; Stores the integer equivalent of the strings ; Traverse the array of strings ; Traverse the current string ; Store the current bit position in bits [ i ] ; Store the required result ; Traverse the array , bits [ ] to get all unique pairs ( i , j ) ; Check whether the strings have no common characters ; Update the overall maximum product ; Print the maximum product ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { count += n & 1 ; n >>= 1 ; } return count ; } void maximumProduct ( vector < string > words ) { vector < int > bits ( words . size ( ) , 0 ) ; for ( int i = 0 ; i < words . size ( ) ; i ++ ) { for ( int j = 0 ; j < words [ i ] . length ( ) ; j ++ ) { bits [ i ] = bits [ i ] | 1 << ( words [ i ] [ j ] - ' a ' ) ; } } int result = 0 ; for ( int i = 0 ; i < bits . size ( ) ; i ++ ) { for ( int j = i + 1 ; j < bits . size ( ) ; j ++ ) { if ( ( bits [ i ] & bits [ j ] ) == 0 ) { int L = countSetBits ( bits [ i ] ) ; int R = countSetBits ( bits [ j ] ) ; result = max ( L * R , result ) ; } } } cout << result ; } int main ( ) { vector < string > arr = { " abcw " , " baz " , " foo " , " bar " , " xtfn " , " abcdef " } ; maximumProduct ( arr ) ; return 0 ; }
Modify a sentence by reversing order of occurrences of all Palindrome Words | Function to check if a string S is a palindrome ; Function to print the modified string after reversing teh order of occurrences of all palindromic words in the sentence ; Stores the palindromic words ; Stores the words in the list ; Traversing the list ; If current word is a palindrome ; Update newlist ; Reverse the newlist ; Traverse the list ; If current word is a palindrome ; Update lis [ i ] ; Increment j ; Print the updated sentence ; Driver Code
function palindrome ( str ) { var st = 0 ; var ed = str . length - 1 ; while ( st < ed ) { if ( str [ st ] == str [ ed ] ) { st ++ ; ed -- ; } else return false ; } return true ; } function printReverse ( sentence ) { var newlist = [ ] ; var lis = [ ] ; var temp = " " ; for ( var i = 0 ; i < sentence . length ; i ++ ) { if ( sentence [ i ] == ' ▁ ' ) { lis . push ( temp ) ; temp = " " ; } else temp += sentence [ i ] ; } lis . push ( temp ) ; for ( var i = 0 ; i < lis . length ; i ++ ) { if ( palindrome ( lis [ i ] ) ) newlist . push ( lis [ i ] ) ; } newlist . reverse ( ) ; var j = 0 ; for ( var i = 0 ; i < lis . length ; i ++ ) { if ( palindrome ( lis [ i ] ) ) { lis [ i ] = newlist [ j ] ; j = j + 1 ; } } for ( var i = 0 ; i < lis . length ; i ++ ) { document . write ( lis [ i ] + " ▁ " ) ; } } var sentence = " mom ▁ and ▁ dad ▁ went ▁ to ▁ eye ▁ hospital " ; printReverse ( sentence ) ;
Convert an array into another by repeatedly removing the last element and placing it at any arbitrary index | C ++ program for the above approach ; Function to count the minimum number of operations required to convert the array A [ ] into array B [ ] ; Stores the index in the first permutation A [ ] which is same as the subsequence in B [ ] ; Find the first i elements in A [ ] which is a subsequence in B [ ] ; If element A [ i ] is same as B [ j ] ; Return the count of operations required ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int minCount ( int A [ ] , int B [ ] , int N ) { int i = 0 ; for ( int j = 0 ; j < N ; j ++ ) { if ( A [ i ] == B [ j ] ) { i ++ ; } } return N - i ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 } ; int B [ ] = { 1 , 5 , 2 , 3 , 4 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minCount ( A , B , N ) ; return 0 ; }
Minimize maximum array element possible by at most K splits on the given array | C ++ program for the above approach ; Function to check if all array elements can be reduced to at most mid by at most K splits ; Stores the number of splits required ; Traverse the array arr [ ] ; Update count ; If possible , return true . Otherwise return false ; Function to find the minimum possible value of maximum array element that can be obtained by at most K splits ; Set lower and upper limits ; Perform Binary Search ; Calculate mid ; Check if all array elements can be reduced to at most mid value by at most K splits ; Update the value of hi ; Otherwise ; Update the value of lo ; Return the minimized maximum element in the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int possible ( int A [ ] , int N , int mid , int K ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { count += ( A [ i ] - 1 ) / mid ; } return count <= K ; } int minimumMaximum ( int A [ ] , int N , int K ) { int lo = 1 ; int hi = * max_element ( A , A + N ) ; int mid ; while ( lo < hi ) { mid = ( lo + hi ) / 2 ; if ( possible ( A , N , mid , K ) ) { hi = mid ; } else { lo = mid + 1 ; } } return hi ; } int main ( ) { int arr [ ] = { 2 , 4 , 8 , 2 } ; int K = 4 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minimumMaximum ( arr , N , K ) ; return 0 ; }
Maximum value of X such that difference between any array element and X does not exceed K | C ++ program for the above approach ; Function to find maximum value of X such that | A [ i ] - X | a K ; Stores the smallest array element ; Store the possible value of X ; Traverse the array A [ ] ; If required criteria is not satisfied ; Update ans ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumNumber ( int arr [ ] , int N , int K ) { int minimum = * min_element ( arr , arr + N ) ; int ans = minimum + K ; for ( int i = 0 ; i < N ; i ++ ) { if ( abs ( arr [ i ] - ans ) > K ) { ans = -1 ; break ; } } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 } ; int K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; maximumNumber ( arr , N , K ) ; return 0 ; }
Check if a number can be represented as a sum of a Prime Number and a Perfect Square | C ++ program for the above approach ; Function to check if a number is prime or not ; Base Cases ; Check if n is divisible by 2 or 3 ; Iterate over every 6 number from the range [ 5 , sqrt ( N ) ] ; If n is found to be non - prime ; Otherwise , return true ; Function to check if a number can be represented as the sum of a prime number and a perfect square or not ; Stores all perfect squares less than N ; Store the perfect square in the array ; Iterate over all perfect squares ; Store the difference of perfect square from n ; If difference is prime ; Update flag ; Break out of the loop ; If N is the sum of a prime number and a perfect square ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) { return false ; } } return true ; } void sumOfPrimeSquare ( int n ) { int i = 0 ; vector < int > squares ; while ( i * i < n ) { squares . push_back ( i * i ) ; i ++ ; } bool flag = false ; for ( i = 0 ; i < squares . size ( ) ; i ++ ) { int difference = n - squares [ i ] ; if ( isPrime ( difference ) ) { flag = true ; break ; } } if ( flag ) { cout << " Yes " ; } else cout << " No " ; } int main ( ) { int N = 27 ; sumOfPrimeSquare ( N ) ; return 0 ; }
Check if a number can be represented as a sum of a Prime Number and a Perfect Square | C ++ program for the above approach ; Function to store all prime numbers less than or equal to N ; Update prime [ 0 ] and prime [ 1 ] as false ; Iterate over the range [ 2 , sqrt ( N ) ] ; If p is a prime ; Update all multiples of p which are <= n as non - prime ; Function to check whether a number can be represented as the sum of a prime number and a perfect square ; Stores all the prime numbers less than or equal to n ; Update the array prime [ ] ; Iterate over the range [ 0 , n ] ; If current number is non - prime ; Update difference ; If difference is a perfect square ; If true , update flag and break out of loop ; If N can be expressed as sum of prime number and perfect square ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SieveOfEratosthenes ( bool prime [ ] , int n ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) { prime [ i ] = false ; } } } } void sumOfPrimeSquare ( int n ) { bool flag = false ; bool prime [ n + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , n ) ; for ( int i = 0 ; i <= n ; i ++ ) { if ( ! prime [ i ] ) continue ; int dif = n - i ; if ( ceil ( ( double ) sqrt ( dif ) ) == floor ( ( double ) sqrt ( dif ) ) ) { flag = true ; break ; } } if ( flag ) { cout << " Yes " ; } else cout << " No " ; } int main ( ) { int N = 27 ; sumOfPrimeSquare ( N ) ; return 0 ; }
Check if any subarray of length M repeats at least K times consecutively or not | C ++ program for the above approach ; Function to check if there exists any subarray of length M repeating at least K times consecutively ; Iterate from i equal 0 to M ; Iterate from j equals 1 to K ; If elements at pos + i and pos + i + j * M are not equal ; Function to check if a subarray repeats at least K times consecutively or not ; Iterate from ind equal 0 to M ; Check if subarray arr [ i , i + M ] repeats atleast K times or not ; Otherwise , return false ; Driver Code
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; bool check ( int arr [ ] , int M , int K , int ind ) { for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 1 ; j < K ; j ++ ) { if ( arr [ ind + i ] != arr [ ind + i + j * M ] ) { return false ; } } } return true ; } bool SubarrayRepeatsKorMore ( int arr [ ] , int N , int M , int K ) { for ( int ind = 0 ; ind <= N - M * K ; ind ++ ) { if ( check ( arr , M , K , ind ) ) { return true ; } } return false ; } int main ( ) { int arr [ ] = { 2 , 1 , 2 , 1 , 1 , 1 , 3 } ; int M = 2 , K = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( SubarrayRepeatsKorMore ( arr , N , M , K ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; }
Check if any subarray of length M repeats at least K times consecutively or not | C ++ program for the above approach ; Function to check if any subarray of length M repeats at least K times consecutively or not ; Stores the required count of repeated subarrays ; Check if the next continuous subarray has equal elements ; Check if K continuous subarray of length M are found or not ; If no subarrays are found ; Driver Code
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; bool checkExists ( int arr [ ] , int N , int M , int K ) { int count = 0 ; for ( int i = 0 ; i < N - M ; i ++ ) { if ( arr [ i ] == arr [ i + M ] ) count ++ ; else count = 0 ; if ( count == M * ( K - 1 ) ) return true ; } return false ; } int main ( ) { int arr [ ] = { 2 , 1 , 2 , 1 , 1 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int M = 2 , K = 2 ; if ( checkExists ( arr , N , M , K ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; }
Number of common digits present in two given numbers | C ++ program for the above approach ; Function to count number of digits that are common in both N and M ; Stores the count of common digits ; Stores the count of digits of N ; Stores the count of digits of M ; Iterate over the digits of N ; Increment the count of last digit of N ; Update N ; Iterate over the digits of M ; Increment the count of last digit of M ; Update M ; Iterate over the range [ 0 , 9 ] ; If freq1 [ i ] and freq2 [ i ] both exceeds 0 ; Increment count by 1 ; Return the count ; Driver Code ; Input
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CommonDigits ( int N , int M ) { int count = 0 ; int freq1 [ 10 ] = { 0 } ; int freq2 [ 10 ] = { 0 } ; while ( N > 0 ) { freq1 [ N % 10 ] ++ ; N = N / 10 ; } while ( M > 0 ) { freq2 [ M % 10 ] ++ ; M = M / 10 ; } for ( int i = 0 ; i < 10 ; i ++ ) { if ( freq1 [ i ] > 0 & freq2 [ i ] > 0 ) { count ++ ; } } return count ; } int main ( ) { int N = 748294 ; int M = 34298156 ; cout << CommonDigits ( N , M ) ; return 0 ; }
Smallest value of N such that the sum of all natural numbers from K to N is at least X | C ++ program for the above approach ; Function to find the minimum possible value of N such that sum of natural numbers from K to N is at least X ; If K is greater than X ; Stores value of minimum N ; Stores the sum of values over the range [ K , ans ] ; Iterate over the range [ K , N ] ; Check if sum of first i natural numbers is >= X ; Print the possible value of ans ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumNumber ( int K , int X ) { if ( K > X ) { cout << " - 1" ; return ; } int ans = 0 ; int sum = 0 ; for ( int i = K ; i <= X ; i ++ ) { sum += i ; if ( sum >= X ) { ans = i ; break ; } } cout << ans ; } int main ( ) { int K = 5 , X = 13 ; minimumNumber ( K , X ) ; return 0 ; }
Smallest value of N such that the sum of all natural numbers from K to N is at least X | C ++ program for the above approach ; Function to check if the sum of natural numbers from K to N is >= X ; Function to find the minimum value of N such that the sum of natural numbers from K to N is at least X ; If K is greater than X ; Perform the Binary Search ; If the sum of the natural numbers from K to mid is atleast X ; Update res ; Update high ; Otherwise , update low ; Print the value of res as the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isGreaterEqual ( int N , int K , int X ) { return ( ( N * 1LL * ( N + 1 ) / 2 ) - ( ( K - 1 ) * 1LL * K / 2 ) ) >= X ; } void minimumNumber ( int K , int X ) { if ( K > X ) { cout << " - 1" ; return ; } int low = K , high = X , res = -1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( isGreaterEqual ( mid , K , X ) ) { res = mid ; high = mid - 1 ; } else low = mid + 1 ; } cout << res ; } int main ( ) { int K = 5 , X = 13 ; minimumNumber ( K , X ) ; return 0 ; }
Count pairs with product of indices equal to the product of elements present at those indices | C ++ program for the above approach ; Function to count the number of pairs having product of indices equal to the product of elements at that indices ; Stores the count of valid pairs ; Generate all possible pairs ; If the condition is satisfied ; Increment the count ; Return the total count ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int CountPairs ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( ( i * j ) == ( arr [ i ] * arr [ j ] ) ) count ++ ; } } return count ; } int main ( ) { int arr [ ] = { 1 , 0 , 3 , 2 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CountPairs ( arr , N ) ; return 0 ; }
Maximize remainder of sum of a pair of array elements with different parity modulo K | C ++ program for the above approach ; Function to find the maximum remainder of sum of a pair of array elements modulo K ; Stores all even numbers ; Stores all odd numbers ; Segregate remainders of even and odd numbers in respective sets ; Stores the maximum remainder obtained ; Find the complement of remainder of each even number in odd set ; Find the complement of remainder x ; Print the answer ; Driver code ; Given array ; Size of the array ; Given value of K
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxRemainder ( int A [ ] , int N , int K ) { unordered_set < int > even ; set < int > odd ; for ( int i = 0 ; i < N ; i ++ ) { int num = A [ i ] ; if ( num % 2 == 0 ) even . insert ( num % K ) ; else odd . insert ( num % K ) ; } int max_rem = 0 ; for ( int x : even ) { int y = K - 1 - x ; auto it = odd . upper_bound ( y ) ; if ( it != odd . begin ( ) ) { it -- ; max_rem = max ( max_rem , x + * it ) ; } } cout << max_rem ; } int main ( ) { int arr [ ] = { 3 , 2 , 4 , 11 , 6 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 7 ; maxRemainder ( arr , N , K ) ; return 0 ; }
Length of the longest path ending at vertex V in a Graph | C ++ program for the above approach ; Function to perform DFS Traversal from source node to the deepest node and update maximum distance to the deepest node ; Mark source as visited ; Update the maximum distance ; Traverse the adjacency list of the current source node ; Recursively call for the child node ; Backtracking step ; Function to calculate maximum length of the path ending at vertex V from any source node ; Stores the maximum length of the path ending at vertex V ; Stores the size of the matrix ; Stores the adjacency list of the given graph ; Traverse the matrix to create adjacency list ; Perform DFS Traversal to update the maximum distance ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void dfs ( int src , vector < int > Adj [ ] , vector < bool > & visited , int level , int & distance ) { visited [ src ] = true ; distance = max ( distance , level ) ; for ( auto & child : Adj [ src ] ) { if ( child != src and visited [ child ] == false ) { dfs ( child , Adj , visited , level + 1 , distance ) ; } } visited [ src ] = false ; } int maximumLength ( vector < vector < int > > & mat , int V ) { int distance = 0 ; int N = ( int ) mat . size ( ) ; vector < int > Adj [ N ] ; vector < bool > visited ( N , false ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { Adj [ i ] . push_back ( j ) ; } } } dfs ( V , Adj , visited , 0 , distance ) ; return distance ; } int main ( ) { vector < vector < int > > mat = { { 0 , 1 , 0 , 0 } , { 1 , 0 , 1 , 1 } , { 0 , 1 , 0 , 0 } , { 0 , 1 , 0 , 0 } } ; int V = 2 ; cout << maximumLength ( mat , V ) ; return 0 ; }
Minimum removals required such that given string consists only of a pair of alternating characters | C ++ program for the above approach ; Function to find the maximum length of alternating occurrences of a pair of characters in a string s ; Stores the next character for alternating sequence ; Stores the length of alternating occurrences of a pair of characters ; Traverse the given string ; If current character is same as the required character ; Increase length by 1 ; Reset required character ; Return the length ; Function to find minimum characters required to be deleted from S to obtain an alternating sequence ; Stores maximum length of alternating sequence of two characters ; Stores length of the string ; Generate every pair of English alphabets ; Function call to find length of alternating sequence for current pair of characters ; Update len to store the maximum of len and newLen in len ; Return n - len as the final result ; Driver Code ; Given Input ; Function call to find minimum characters required to be removed from S to make it an alternating sequence of a pair of characters
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLength ( string s , char i , char j ) { char required = i ; int length = 0 ; for ( char curr : s ) { if ( curr == required ) { length += 1 ; if ( required == i ) required = j ; else required = i ; } } return length ; } int minimumDeletions ( string S ) { int len = 0 ; int n = S . length ( ) ; for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { for ( char j = i + 1 ; j <= ' z ' ; j ++ ) { int newLen = findLength ( S , i , j ) ; len = max ( len , newLen ) ; } } return n - len ; } int main ( ) { string S = " adebbeeaebd " ; cout << minimumDeletions ( S ) ; return 0 ; }
Smallest value of X satisfying the condition X % A [ i ] = B [ i ] for two given arrays | C ++ program for the above approach ; Function to calculate modulo inverse of a w . r . t m using Extended Euclid Algorithm ; Base Case ; Perform extended euclid algorithm ; q is quotient ; m is remainder now , process same as euclid 's algorithm ; If x1 is negative ; Make x1 positive ; Function to implement Chinese Remainder Theorem to find X ; Stores the product of array elements ; Traverse the array ; Update product ; Initialize the result ; Apply the above formula ; Function to calculate the product of all elements of the array a [ ] ; Stores product of all array elements ; Traverse the array ; Return the product ; Function to find the value of X that satisfies the given condition ; Stores the required smallest value using Chinese Remainder Theorem ; Stores the product of all array elements ; The equation is Y + K * M >= P Therefore , calculate K = ceil ( ( P - Y ) / M ) ; So , X = Y + K * M ; Print the resultant value of X ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int inv ( int a , int m ) { int m0 = m , t , q ; int x0 = 0 , x1 = 1 ; if ( m == 1 ) return 0 ; while ( a > 1 ) { q = a / m ; t = m ; m = a % m ; a = t ; t = x0 ; x0 = x1 - q * x0 ; x1 = t ; } if ( x1 < 0 ) x1 += m0 ; return x1 ; } int findMinX ( int A [ ] , int B [ ] , int N ) { int prod = 1 ; for ( int i = 0 ; i < N ; i ++ ) prod *= A [ i ] ; int result = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int pp = prod / A [ i ] ; result += B [ i ] * inv ( pp , A [ i ] ) * pp ; } return result % prod ; } int product ( int a [ ] , int n ) { int ans = 1 ; for ( int i = 0 ; i < n ; i ++ ) { ans *= a [ i ] ; } return ans ; } void findSmallestInteger ( int A [ ] , int B [ ] , int P , int n ) { int Y = findMinX ( A , B , n ) ; int M = product ( A , n ) ; int K = ceil ( ( ( double ) P - ( double ) Y ) / ( double ) M ) ; int X = Y + K * M ; cout << X ; } int main ( ) { int A [ ] = { 3 , 4 , 5 } ; int B [ ] = { 2 , 3 , 1 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int P = 72 ; findSmallestInteger ( A , B , P , n ) ; }
Minimum Time Taken for N Points to coincide | C ++ program for the above approach ; Function to check for common area between three circles ; Find the distance between the centers of circle 1 & circle 2 ; Find the distance between the centers of circle 1 & circle 3 ; Find the distance between the centers of circle 2 & circle 3 ; If sum of radius is less than the distance between their centers then false ; If circle 1 lies within circle 2 or if circle 2 lies within circle 1 ; If circle 1 lies within circle 2 ; Check whether R1 ( common area between R1 and R2 ) and R3 intersect ; Check whether R2 ( common area between R1 and R2 ) and R3 intersect ; If circle 1 lies within circle 3 or if circle 3 lies within circle 1 ; If circle 1 lies within circle 3 ; Check whether R1 ( common area between R1 and R3 ) and R2 intersect ; Check whether R3 ( common area between R1 and R3 ) and R2 intersect ; If circle 2 lies within circle 3 or if circle 3 lies within circle 2 ; If circle 2 lies within circle 3 ; Check whether R2 ( common area between R2 and R3 ) and R1 intersect ; Check whether R3 ( common area between R2 and R3 ) and R1 intersect ; Find the point of intersection for circle 1 & circle 2 ; First point of intersection ( x121 , y121 ) ; Check whether the point of intersection lies within circle 3 or not ; Second point of intersection ( x122 , y122 ) ; Check whether the point of intersection lies within circle 3 or not ; Find the point of intersection for circle 1 & circle 3 ; First point of intersection ( x131 , y131 ) ; Check whether the point of intersection lies within circle 2 or not ; Second point of intersection ( x132 , y132 ) ; Check whether the point of intersection lies within circle 2 or not ; Find the point of intersection for circle 2 & circle 3 ; First point of intersection ( x231 , y231 ) ; Check whether the point of intersection lies within circle 1 or not ; Second point of intersection ( x232 , y232 ) ; Check whether the point of intersection lies within circle 1 or not ; Function to check if there is a common area between N circles ; Check for a common area for all combination of 3 circles ; t * V give the radius of the circle ; For N = 2 ; ( x2 - x1 ) ^ 2 + ( y2 - y1 ) ^ 2 <= ( r1 + r2 ) ^ 2 for 2 circles to intersect ; Function to find minimum time ; Time depends on the area of the 2D plane Area = ( Max ( X ) - Min ( X ) ) * ( Max ( Y ) - Min ( Y ) ) ; Number of iteration depends on the precision ; If there is a common area between N circles for time t ; If there is no common area between N circles for time t ; Print the minimum time ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool intersection ( int X1 , int Y1 , double R1 , int X2 , int Y2 , double R2 , int X3 , int Y3 , double R3 ) { double d12 = sqrt ( ( X1 - X2 ) * ( X1 - X2 ) + ( Y1 - Y2 ) * ( Y1 - Y2 ) ) ; double d13 = sqrt ( ( X1 - X3 ) * ( X1 - X3 ) + ( Y1 - Y3 ) * ( Y1 - Y3 ) ) ; double d23 = sqrt ( ( X2 - X3 ) * ( X2 - X3 ) + ( Y2 - Y3 ) * ( Y2 - Y3 ) ) ; if ( ( R1 + R2 < d12 ) || ( R1 + R3 < d13 ) || ( R2 + R3 < d23 ) ) { return false ; } else { if ( abs ( R1 - R2 ) >= d12 ) { if ( R1 < R2 ) { return R1 + R3 >= d13 ; } else { return R2 + R3 >= d23 ; } } else if ( abs ( R1 - R3 ) >= d13 ) { if ( R1 < R3 ) { return R1 + R2 >= d12 ; } else { return R2 + R3 >= d23 ; } } else if ( abs ( R2 - R3 ) >= d23 ) { if ( R2 < R3 ) { return R1 + R2 >= d12 ; } else { return R1 + R3 >= d13 ; } } else { double x121 , y121 , x122 , y122 , x131 , y131 , x132 , y132 , x231 , y231 , x232 , y232 , a , b ; a = ( R1 * R1 - R2 * R2 ) / ( 2 * d12 * d12 ) ; b = sqrt ( 2 * ( R1 * R1 + R2 * R2 ) / ( d12 * d12 ) - ( R1 * R1 - R2 * R2 ) * ( R1 * R1 - R2 * R2 ) / ( pow ( d12 , 4 ) ) - 1 ) / 2 ; x121 = ( X1 + X2 ) / 2.0 + a * ( X2 - X1 ) + b * ( Y2 - Y1 ) ; y121 = ( Y1 + Y2 ) / 2.0 + a * ( Y2 - Y1 ) + b * ( X1 - X2 ) ; if ( R3 >= sqrt ( ( x121 - X3 ) * ( x121 - X3 ) + ( y121 - Y3 ) * ( y121 - Y3 ) ) ) { return true ; } x122 = ( X1 + X2 ) / 2.0 + a * ( X2 - X1 ) - b * ( Y2 - Y1 ) ; y122 = ( Y1 + Y2 ) / 2.0 + a * ( Y2 - Y1 ) - b * ( X1 - X2 ) ; if ( R3 >= sqrt ( ( x122 - X3 ) * ( x122 - X3 ) + ( y122 - Y3 ) * ( y122 - Y3 ) ) ) { return true ; } a = ( R1 * R1 - R3 * R3 ) / ( 2 * d13 * d13 ) ; b = sqrt ( 2 * ( R1 * R1 + R3 * R3 ) / ( d13 * d13 ) - ( R1 * R1 - R3 * R3 ) * ( R1 * R1 - R3 * R3 ) / ( pow ( d13 , 4 ) ) - 1 ) / 2 ; x131 = ( X1 + X3 ) / 2.0 + a * ( X3 - X1 ) + b * ( Y3 - Y1 ) ; y131 = ( Y1 + Y3 ) / 2.0 + a * ( Y3 - Y1 ) + b * ( X1 - X3 ) ; if ( R2 >= sqrt ( ( x131 - X2 ) * ( x131 - X2 ) + ( y131 - Y2 ) * ( y131 - Y2 ) ) ) { return true ; } x132 = ( X1 + X3 ) / 2.0 + a * ( X3 - X1 ) - b * ( Y3 - Y1 ) ; y132 = ( Y1 + Y3 ) / 2.0 + a * ( Y3 - Y1 ) - b * ( X1 - X3 ) ; if ( R2 >= sqrt ( ( x132 - X2 ) * ( x132 - X2 ) + ( y132 - Y2 ) * ( y132 - Y2 ) ) ) { return true ; } a = ( R2 * R2 - R3 * R3 ) / ( 2 * d23 * d23 ) ; b = sqrt ( 2 * ( R2 * R2 + R3 * R3 ) / ( d23 * d23 ) - ( R2 * R2 - R3 * R3 ) * ( R2 * R2 - R3 * R3 ) / ( pow ( d23 , 4 ) ) - 1 ) / 2 ; x231 = ( X2 + X3 ) / 2.0 + a * ( X3 - X2 ) + b * ( Y3 - Y2 ) ; y231 = ( Y2 + Y3 ) / 2.0 + a * ( Y3 - Y2 ) + b * ( X2 - X3 ) ; if ( R1 >= sqrt ( ( x231 - X1 ) * ( x231 - X1 ) + ( y231 - Y1 ) * ( y231 - Y1 ) ) ) { return true ; } x232 = ( X2 + X3 ) / 2.0 + a * ( X3 - X2 ) - b * ( Y3 - Y2 ) ; y232 = ( Y2 + Y3 ) / 2.0 + a * ( Y3 - Y2 ) - b * ( X2 - X3 ) ; return R1 >= sqrt ( ( x232 - X1 ) * ( x232 - X1 ) + ( y232 - Y1 ) * ( y232 - Y1 ) ) ; } } } bool isGood ( double t , int N , int X [ ] , int Y [ ] , int V [ ] ) { if ( N >= 3 ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { for ( int k = j + 1 ; k < N ; k ++ ) { if ( intersection ( X [ i ] , Y [ i ] , t * V [ i ] , X [ j ] , Y [ j ] , t * V [ j ] , X [ k ] , Y [ k ] , t * V [ k ] ) == false ) return false ; } } } return true ; } else { return sqrt ( ( X [ 0 ] - X [ 1 ] ) * ( X [ 0 ] - X [ 1 ] ) + ( Y [ 0 ] - Y [ 1 ] ) * ( Y [ 0 ] - Y [ 1 ] ) ) <= t * ( V [ 0 ] + V [ 1 ] ) ; } } void binarySearch ( int N , int X [ ] , int Y [ ] , int V [ ] ) { double tl = 0.0 , tu = 100000.0 , t ; for ( int i = 0 ; i < 1000 ; i ++ ) { t = ( tl + tu ) / 2.0 ; if ( isGood ( t , N , X , Y , V ) ) { tu = t ; } else { tl = t ; } } cout << fixed << setprecision ( 16 ) << tu << endl ; } int main ( ) { int N = 4 ; int X [ ] = { 1 , -3 , -1 , 2 } ; int Y [ ] = { 2 , 4 , -2 , -2 } ; int V [ ] = { 3 , 2 , 4 , 5 } ; binarySearch ( N , X , Y , V ) ; }