text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Find whether a given number is a power of 4 or not | C ++ program to find whether a given number is a power of 4 or not ; Function to check if x is power of 4 ; Driver code
#include <iostream> NEW_LINE using namespace std ; #define bool int NEW_LINE class GFG { public : bool isPowerOfFour ( int n ) { if ( n == 0 ) return 0 ; while ( n != 1 ) { if ( n % 4 != 0 ) return 0 ; n = n / 4 ; } return 1 ; } } ; int main ( ) { GFG g ; int test_no = 64 ; if ( g . isPowerOfFour ( test_no ) ) cout << test_no << " ▁ is ▁ a ▁ power ▁ of ▁ 4" ; else cout << test_no << " is ▁ not ▁ a ▁ power ▁ of ▁ 4" ; getchar ( ) ; }
Find whether a given number is a power of 4 or not | C ++ program to check if given number is power of 4 or not ; Function to check if x is power of 4 ; Check if there is only one bit set in n ; count 0 bits before set bit ; If count is even then return true else false ; If there are more than 1 bit set then n is not a power of 4 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfFour ( unsigned int n ) { int count = 0 ; if ( n && ! ( n & ( n - 1 ) ) ) { while ( n > 1 ) { n >>= 1 ; count += 1 ; } return ( count % 2 == 0 ) ? 1 : 0 ; } return 0 ; } int main ( ) { int test_no = 64 ; if ( isPowerOfFour ( test_no ) ) cout << test_no << " ▁ is ▁ a ▁ power ▁ of ▁ 4" ; else cout << test_no << " ▁ is ▁ not ▁ a ▁ power ▁ of ▁ 4" ; }
Find whether a given number is a power of 4 or not | C ++ program to check if given number is power of 4 or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPowerOfFour ( unsigned int n ) { return n != 0 && ( ( n & ( n - 1 ) ) == 0 ) && ! ( n & 0xAAAAAAAA ) ; } int main ( ) { int test_no = 64 ; if ( isPowerOfFour ( test_no ) ) cout << test_no << " ▁ is ▁ a ▁ power ▁ of ▁ 4" ; else cout << test_no << " ▁ is ▁ not ▁ a ▁ power ▁ of ▁ 4" ; }
Find whether a given number is a power of 4 or not | C ++ program to check if given number is power of 4 or not ; 0 is not considered as a power of 4 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; float logn ( int n , int r ) { return log ( n ) / log ( r ) ; } bool isPowerOfFour ( int n ) { if ( n == 0 ) return false ; return floor ( logn ( n , 4 ) ) == ceil ( logn ( n , 4 ) ) ; } int main ( ) { int test_no = 64 ; if ( isPowerOfFour ( test_no ) ) cout << test_no << " ▁ is ▁ a ▁ power ▁ of ▁ 4" ; else cout << test_no << " ▁ is ▁ not ▁ a ▁ power ▁ of ▁ 4" ; return 0 ; }
Find whether a given number is a power of 4 or not | C ++ program to check if given number is power of 4 or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isPowerOfFour ( int n ) { return ( n > 0 and pow ( 4 , int ( log2 ( n ) / log2 ( 4 ) ) == n ) ) ; } int main ( ) { int test_no = 64 ; if ( isPowerOfFour ( test_no ) ) cout << test_no << " ▁ is ▁ a ▁ power ▁ of ▁ 4" ; else cout << test_no << " ▁ is ▁ not ▁ a ▁ power ▁ of ▁ 4" ; return 0 ; }
Compute the minimum or maximum of two integers without branching | C ++ program to Compute the minimum or maximum of two integers without branching ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver code
#include <iostream> NEW_LINE using namespace std ; class gfg { public : int min ( int x , int y ) { return y ^ ( ( x ^ y ) & - ( x < y ) ) ; } int max ( int x , int y ) { return x ^ ( ( x ^ y ) & - ( x < y ) ) ; } } ; int main ( ) { gfg g ; int x = 15 ; int y = 6 ; cout << " Minimum ▁ of ▁ " << x << " ▁ and ▁ " << y << " ▁ is ▁ " ; cout << g . min ( x , y ) ; cout << " Maximum of " ▁ < < ▁ x ▁ < < STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL TABSYMBOL " and " ▁ < < ▁ y ▁ < < ▁ " is " cout << g . max ( x , y ) ; getchar ( ) ; }
Compute the minimum or maximum of two integers without branching | ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define CHARBIT 8 NEW_LINE int min ( int x , int y ) { return y + ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHARBIT - 1 ) ) ) ; } int max ( int x , int y ) { return x - ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHARBIT - 1 ) ) ) ; } int main ( ) { int x = 15 ; int y = 6 ; cout << " Minimum ▁ of ▁ " << x << " ▁ and ▁ " << y << " ▁ is ▁ " ; cout << min ( x , y ) ; cout << " Maximum of " < < x < < " and " < < y < < " is " cout << max ( x , y ) ; }
Compute the minimum or maximum of two integers without branching | C ++ program for the above approach ; absbit32 function ; max function ; min function ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int absbit32 ( int x , int y ) { int sub = x - y ; int mask = ( sub >> 31 ) ; return ( sub ^ mask ) - mask ; } int max ( int x , int y ) { int abs = absbit32 ( x , y ) ; return ( x + y + abs ) / 2 ; } int min ( int x , int y ) { int abs = absbit32 ( x , y ) ; return ( x + y - abs ) / 2 ; } int main ( ) { cout << max ( 2 , 3 ) << endl ; cout << max ( 2 , -3 ) << endl ; cout << max ( -2 , -3 ) << endl ; cout << min ( 2 , 3 ) << endl ; cout << min ( 2 , -3 ) << endl ; cout << min ( -2 , -3 ) << endl ; return 0 ; }
Find the Number Occurring Odd Number of Times | C ++ program to find the element occurring odd number of times ; Function to find the element occurring odd number of times ; driver code ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getOddOccurrence ( int arr [ ] , int arr_size ) { for ( int i = 0 ; i < arr_size ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < arr_size ; j ++ ) { if ( arr [ i ] == arr [ j ] ) count ++ ; } if ( count % 2 != 0 ) return arr [ i ] ; } return -1 ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getOddOccurrence ( arr , n ) ; return 0 ; }
Find the Number Occurring Odd Number of Times | C ++ program to find the element occurring odd number of times ; function to find the element occurring odd number of times ; Putting all elements into the HashMap ; Iterate through HashMap to check an element occurring odd number of times and return it ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getOddOccurrence ( int arr [ ] , int size ) { unordered_map < int , int > hash ; for ( int i = 0 ; i < size ; i ++ ) { hash [ arr [ i ] ] ++ ; } for ( auto i : hash ) { if ( i . second % 2 != 0 ) { return i . first ; } } return -1 ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 4 , 5 , 2 , 4 , 3 , 5 , 2 , 4 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getOddOccurrence ( arr , n ) ; return 0 ; }
Check for Integer Overflow | ; Takes pointer to result and two numbers as arguments . If there is no overflow , the function places the resultant = sum a + b in result and returns 0 , otherwise it returns - 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int addOvf ( int * result , int a , int b ) { * result = a + b ; if ( a > 0 && b > 0 && * result < 0 ) return -1 ; if ( a < 0 && b < 0 && * result > 0 ) return -1 ; return 0 ; } int main ( ) { int * res = new int [ ( sizeof ( int ) ) ] ; int x = 2147483640 ; int y = 10 ; cout << addOvf ( res , x , y ) ; cout << " STRNEWLINE " << * res ; return 0 ; }
Check for Integer Overflow |
#include <bits/stdc++.h> NEW_LINE using namespace std ; int addOvf ( int * result , int a , int b ) { if ( a > INT_MAX - b ) return -1 ; else { * result = a + b ; return 0 ; } } int main ( ) { int * res = new int [ ( sizeof ( int ) ) ] ; int x = 2147483640 ; int y = 10 ; cout << addOvf ( res , x , y ) << endl ; cout << * res ; return 0 ; }
Little and Big Endian Mystery |
#include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { unsigned int i = 1 ; char * c = ( char * ) & i ; if ( * c ) cout << " Little ▁ endian " ; else cout << " Big ▁ endian " ; return 0 ; }
Count number of bits to be flipped to convert A to B | Count number of bits to be flipped to convert A into B ; Function that count set bits ; Function that return count of flipped number ; Return count of set bits in a XOR b ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { count ++ ; n &= ( n - 1 ) ; } return count ; } int FlippedCount ( int a , int b ) { return countSetBits ( a ^ b ) ; } int main ( ) { int a = 10 ; int b = 20 ; cout << FlippedCount ( a , b ) << endl ; return 0 ; }
Position of rightmost set bit | C ++ program for Position of rightmost set bit ; Driver code
#include <iostream> NEW_LINE #include <math.h> NEW_LINE using namespace std ; class gfg { public : unsigned int getFirstSetBitPos ( int n ) { return log2 ( n & - n ) + 1 ; } } ; int main ( ) { gfg g ; int n = 12 ; cout << g . getFirstSetBitPos ( n ) ; return 0 ; }
Position of rightmost set bit | C ++ program to find the first rightmost set bit using XOR operator ; function to find the rightmost set bit ; Position variable initialize with 1 m variable is used to check the set bit ; left shift ; Driver Code ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int PositionRightmostSetbit ( int n ) { int position = 1 ; int m = 1 ; while ( ! ( n & m ) ) { m = m << 1 ; position ++ ; } return position ; } int main ( ) { int n = 16 ; cout << PositionRightmostSetbit ( n ) ; return 0 ; }
Position of rightmost set bit | C ++ implementation of above approach ; for num == 0 there is zero set bit ; counting the position of first set bit ; Driver code
#include <iostream> NEW_LINE using namespace std ; #define INT_SIZE 32 NEW_LINE int Right_most_setbit ( int num ) { if ( num == 0 ) { return 0 ; } else { int pos = 1 ; for ( int i = 0 ; i < INT_SIZE ; i ++ ) { if ( ! ( num & ( 1 << i ) ) ) pos ++ ; else break ; } return pos ; } } int main ( ) { int num = 0 ; int pos = Right_most_setbit ( num ) ; cout << pos << endl ; return 0 ; }
Position of rightmost set bit | C ++ program for above approach ; Program to find position of rightmost set bit ; Iterate till number > 0 ; Checking if last bit is set ; Increment position and right shift number ; set bit not found . ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int PositionRightmostSetbit ( int n ) { int p = 1 ; while ( n > 0 ) { if ( n & 1 ) { return p ; } p ++ ; n = n >> 1 ; } return -1 ; } int main ( ) { int n = 18 ; int pos = PositionRightmostSetbit ( n ) ; if ( pos != -1 ) cout << pos ; else cout << 0 ; return 0 ; }
Binary representation of a given number | C ++ Program for the binary representation of a given number ; bin function ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void bin ( long n ) { long i ; cout << "0" ; for ( i = 1 << 30 ; i > 0 ; i = i / 2 ) { if ( ( n & i ) != 0 ) { cout << "1" ; } else { cout << "0" ; } } } int main ( void ) { bin ( 7 ) ; cout << endl ; bin ( 4 ) ; }
Binary representation of a given number | C ++ implementation of the approach ; Function to convert decimal to binary number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void bin ( unsigned n ) { if ( n > 1 ) bin ( n >> 1 ) ; printf ( " % d " , n & 1 ) ; } int main ( void ) { bin ( 131 ) ; printf ( " STRNEWLINE " ) ; bin ( 3 ) ; return 0 ; }
Swap all odd and even bits | C ++ program to swap even and odd bits of a given number ; Function to swap even and odd bits ; Get all even bits of x ; Get all odd bits of x ; Right shift even bits ; Left shift odd bits ; Combine even and odd bits ; Driver code ; 00010111 ; Output is 43 ( 00101011 )
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int swapBits ( unsigned int x ) { unsigned int even_bits = x & 0xAAAAAAAA ; unsigned int odd_bits = x & 0x55555555 ; even_bits >>= 1 ; odd_bits <<= 1 ; return ( even_bits odd_bits ) ; } int main ( ) { unsigned int x = 23 ; cout << swapBits ( x ) ; return 0 ; }
Find position of the only set bit | C ++ program to find position of only set bit in a given number ; A utility function to check whether n is a power of 2 or not . goo . gl / 17 Arj See http : ; Returns position of the only set bit in ' n ' ; Iterate through bits of n till we find a set bit i & n will be non - zero only when ' i ' and ' n ' have a set bit at same position ; Unset current bit and set the next bit in ' i ' ; increment position ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isPowerOfTwo ( unsigned n ) { return n && ( ! ( n & ( n - 1 ) ) ) ; } int findPosition ( unsigned n ) { if ( ! isPowerOfTwo ( n ) ) return -1 ; unsigned i = 1 , pos = 1 ; while ( ! ( i & n ) ) { i = i << 1 ; ++ pos ; } return pos ; } int main ( void ) { int n = 16 ; int pos = findPosition ( n ) ; ( pos == -1 ) ? cout << " n ▁ = ▁ " << n << " , ▁ Invalid ▁ number " << endl : cout << " n ▁ = ▁ " << n << " , ▁ Position ▁ " << pos << endl ; n = 12 ; pos = findPosition ( n ) ; ( pos == -1 ) ? cout << " n ▁ = ▁ " << n << " , ▁ Invalid ▁ number " << endl : cout << " n ▁ = ▁ " << n << " , ▁ Position ▁ " << pos << endl ; n = 128 ; pos = findPosition ( n ) ; ( pos == -1 ) ? cout << " n ▁ = ▁ " << n << " , ▁ Invalid ▁ number " << endl : cout << " n ▁ = ▁ " << n << " , ▁ Position ▁ " << pos << endl ; return 0 ; }
Find position of the only set bit | C ++ program to find position of only set bit in a given number ; A utility function to check whether n is power of 2 or not ; Returns position of the only set bit in ' n ' ; One by one move the only set bit to right till it reaches end ; increment count of shifts ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int isPowerOfTwo ( unsigned n ) { return n && ( ! ( n & ( n - 1 ) ) ) ; } int findPosition ( unsigned n ) { if ( ! isPowerOfTwo ( n ) ) return -1 ; unsigned count = 0 ; while ( n ) { n = n >> 1 ; ++ count ; } return count ; } int main ( void ) { int n = 0 ; int pos = findPosition ( n ) ; ( pos == -1 ) ? cout << " n ▁ = ▁ " << n << " , ▁ Invalid ▁ number STRNEWLINE " : cout << " n ▁ = ▁ " << n << " , ▁ Position ▁ " << pos << endl ; n = 12 ; pos = findPosition ( n ) ; ( pos == -1 ) ? cout << " n ▁ = ▁ " << n << " , ▁ Invalid ▁ number STRNEWLINE " : cout << " n ▁ = ▁ " << n << " , ▁ Position ▁ " << pos << endl ; n = 128 ; pos = findPosition ( n ) ; ( pos == -1 ) ? cout << " n ▁ = ▁ " << n << " , ▁ Invalid ▁ number STRNEWLINE " : cout << " n ▁ = ▁ " << n << " , ▁ Position ▁ " << pos << endl ; return 0 ; }
How to swap two numbers without using a temporary variable ? | C ++ Program to swap two numbers without using temporary variable ; Code to swap ' x ' and ' y ' x now becomes 15 ; y becomes 10 ; x becomes 5
#include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int x = 10 , y = 5 ; x = x * y ; y = x / y ; x = x / y ; cout << " After ▁ Swapping : ▁ x ▁ = " << x << " , ▁ y = " << y ; }
How to swap two numbers without using a temporary variable ? | C ++ code to swap using XOR ; Code to swap ' x ' ( 1010 ) and ' y ' ( 0101 ) x now becomes 15 ( 1111 ) ; y becomes 10 ( 1010 ) ; x becomes 5 ( 0101 )
#include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int x = 10 , y = 5 ; x = x ^ y ; y = x ^ y ; x = x ^ y ; cout << " After ▁ Swapping : ▁ x ▁ = " << x << " , ▁ y = " << y ; return 0 ; }
How to swap two numbers without using a temporary variable ? | C ++ program to implement the above approach ; Swap function ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int * xp , int * yp ) { * xp = * xp ^ * yp ; * yp = * xp ^ * yp ; * xp = * xp ^ * yp ; } int main ( ) { int x = 10 ; swap ( & x , & x ) ; cout << " After ▁ swap ( & x , ▁ & x ) : ▁ x ▁ = ▁ " << x ; return 0 ; }
How to swap two numbers without using a temporary variable ? | C ++ program to swap two numbers . Including header file . ; Function to swap the numbers . ; same as a = a + b ; same as b = a - b ; same as a = a - b ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int & a , int & b ) { a = ( a & b ) + ( a b ) ; b = a + ( ~ b ) + 1 ; a = a + ( ~ b ) + 1 ; cout << " After ▁ swapping : ▁ a ▁ = ▁ " << a << " , ▁ b ▁ = ▁ " << b ; } int main ( ) { int a = 5 , b = 10 ; swap ( a , b ) ; return 0 ; }
N Queen Problem using Branch And Bound | C ++ program to solve N Queen Problem using Branch and Bound ; A utility function to print solution ; A Optimized function to check if a queen can be placed on board [ row ] [ col ] ; A recursive utility function to solve N Queen problem ; base case : If all queens are placed then return true ; Consider this column and try placing this queen in all rows one by one ; Check if queen can be placed on board [ i ] [ col ] ; Place this queen in board [ i ] [ col ] ; recur to place rest of the queens ; Remove queen from board [ i ] [ col ] ; If queen can not be place in any row in this colum col then return false ; This function solves the N Queen problem using Branch and Bound . It mainly uses solveNQueensUtil ( ) to solve the problem . It returns false if queens cannot be placed , otherwise return true and prints placement of queens in the form of 1 s . Please note that there may be more than one solutions , this function prints one of the feasible solutions . ; helper matrices ; arrays to tell us which rows are occupied ; keep two arrays to tell us which diagonals are occupied ; initialize helper matrices ; solution found ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #define N 8 NEW_LINE void printSolution ( int board [ N ] [ N ] ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) printf ( " % 2d ▁ " , board [ i ] [ j ] ) ; printf ( " STRNEWLINE " ) ; } } bool isSafe ( int row , int col , int slashCode [ N ] [ N ] , int backslashCode [ N ] [ N ] , bool rowLookup [ ] , bool slashCodeLookup [ ] , bool backslashCodeLookup [ ] ) { if ( slashCodeLookup [ slashCode [ row ] [ col ] ] backslashCodeLookup [ backslashCode [ row ] [ col ] ] rowLookup [ row ] ) return false ; return true ; } bool solveNQueensUtil ( int board [ N ] [ N ] , int col , int slashCode [ N ] [ N ] , int backslashCode [ N ] [ N ] , bool rowLookup [ N ] , bool slashCodeLookup [ ] , bool backslashCodeLookup [ ] ) { if ( col >= N ) return true ; for ( int i = 0 ; i < N ; i ++ ) { if ( isSafe ( i , col , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) ) { board [ i ] [ col ] = 1 ; rowLookup [ i ] = true ; slashCodeLookup [ slashCode [ i ] [ col ] ] = true ; backslashCodeLookup [ backslashCode [ i ] [ col ] ] = true ; if ( solveNQueensUtil ( board , col + 1 , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) ) return true ; board [ i ] [ col ] = 0 ; rowLookup [ i ] = false ; slashCodeLookup [ slashCode [ i ] [ col ] ] = false ; backslashCodeLookup [ backslashCode [ i ] [ col ] ] = false ; } } return false ; } bool solveNQueens ( ) { int board [ N ] [ N ] ; memset ( board , 0 , sizeof board ) ; int slashCode [ N ] [ N ] ; int backslashCode [ N ] [ N ] ; bool rowLookup [ N ] = { false } ; bool slashCodeLookup [ 2 * N - 1 ] = { false } ; bool backslashCodeLookup [ 2 * N - 1 ] = { false } ; for ( int r = 0 ; r < N ; r ++ ) for ( int c = 0 ; c < N ; c ++ ) { slashCode [ r ] = r + c , backslashCode [ r ] = r - c + 7 ; } if ( solveNQueensUtil ( board , 0 , slashCode , backslashCode , rowLookup , slashCodeLookup , backslashCodeLookup ) == false ) { printf ( " Solution ▁ does ▁ not ▁ exist " ) ; return false ; } printSolution ( board ) ; return true ; } int main ( ) { solveNQueens ( ) ; return 0 ; }
Check a given sentence for a given set of simple grammer rules | C program to validate a given sentence for a set of rules ; Method to check a given sentence for given rules ; Calculate the length of the string . ; Check that the first character lies in [ A - Z ] . Otherwise return false . ; If the last character is not a full stop ( . ) no need to check further . ; Maintain 2 states . Previous and current state based on which vertex state you are . Initialise both with 0 = start state . ; Keep the index to the next character in the string . ; Loop to go over the string . ; Set states according to the input characters in the string and the rule defined in the description . If current character is [ A - Z ] . Set current state as 0. ; If current character is a space . Set current state as 1. ; If current character is [ a - z ] . Set current state as 2. ; If current state is a dot ( . ) . Set current state as 3. ; Validates all current state with previous state for the rules in the description of the problem . ; If we have reached last state and previous state is not 1 , then check next character . If next character is ' \0' , then return true , else false ; Set previous state as current state before going over to the next character . ; Driver program
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #include <stdbool.h> NEW_LINE bool checkSentence ( char str [ ] ) { int len = strlen ( str ) ; if ( str [ 0 ] < ' A ' str [ 0 ] > ' Z ' ) return false ; if ( str [ len - 1 ] != ' . ' ) return false ; int prev_state = 0 , curr_state = 0 ; int index = 1 ; while ( str [ index ] ) { if ( str [ index ] >= ' A ' && str [ index ] <= ' Z ' ) curr_state = 0 ; else if ( str [ index ] == ' ▁ ' ) curr_state = 1 ; else if ( str [ index ] >= ' a ' && str [ index ] <= ' z ' ) curr_state = 2 ; else if ( str [ index ] == ' . ' ) curr_state = 3 ; if ( prev_state == curr_state && curr_state != 2 ) return false ; if ( prev_state == 2 && curr_state == 0 ) return false ; if ( curr_state == 3 && prev_state != 1 ) return ( str [ index + 1 ] == ' \0' ) ; index ++ ; prev_state = curr_state ; } return false ; } int main ( ) { char * str [ ] = { " I ▁ love ▁ cinema . " , " The ▁ vertex ▁ is ▁ S . " , " I ▁ am ▁ single . " , " My ▁ name ▁ is ▁ KG . " , " I ▁ lovE ▁ cinema . " , " GeeksQuiz . ▁ is ▁ a ▁ quiz ▁ site . " , " I ▁ love ▁ Geeksquiz ▁ and ▁ Geeksforgeeks . " , " ▁ You ▁ are ▁ my ▁ friend . " , " I ▁ love ▁ cinema " } ; int str_size = sizeof ( str ) / sizeof ( str [ 0 ] ) ; int i = 0 ; for ( i = 0 ; i < str_size ; i ++ ) checkSentence ( str [ i ] ) ? printf ( " \" % s \" ▁ is ▁ correct ▁ STRNEWLINE " , str [ i ] ) : printf ( " \" % s \" ▁ is ▁ incorrect ▁ STRNEWLINE " , str [ i ] ) ; return 0 ; }
Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1 s in a binary array | C ++ program to find Index of 0 to be replaced with 1 to get longest continuous sequence of 1 s in a binary array ; Returns index of 0 to be replaced with 1 to get longest continuous sequence of 1 s . If there is no 0 in array , then it returns - 1. ; for maximum number of 1 around a zero ; for storing result ; index of previous zero ; index of previous to previous zero ; Traverse the input array ; If current element is 0 , then calculate the difference between curr and prev_prev_zero ; Update result if count of 1 s around prev_zero is more ; Update for next iteration ; Check for the last encountered zero ; Driver program
#include <iostream> NEW_LINE using namespace std ; int maxOnesIndex ( bool arr [ ] , int n ) { int max_count = 0 ; int max_index ; int prev_zero = -1 ; int prev_prev_zero = -1 ; for ( int curr = 0 ; curr < n ; ++ curr ) { if ( arr [ curr ] == 0 ) { if ( curr - prev_prev_zero > max_count ) { max_count = curr - prev_prev_zero ; max_index = prev_zero ; } prev_prev_zero = prev_zero ; prev_zero = curr ; } } if ( n - prev_prev_zero > max_count ) max_index = prev_zero ; return max_index ; } int main ( ) { bool arr [ ] = { 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 , 1 , 0 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Index ▁ of ▁ 0 ▁ to ▁ be ▁ replaced ▁ is ▁ " << maxOnesIndex ( arr , n ) ; return 0 ; }
Length of the largest subarray with contiguous elements | Set 1 | ; Utility functions to find minimum and maximum of two elements ; Returns length of the longest contiguous subarray ; Initialize result ; Initialize min and max for all subarrays starting with i ; Consider all subarrays starting with i and ending with j ; Update min and max in this subarray if needed ; If current subarray has all contiguous elements ; Return result ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int min ( int x , int y ) { return ( x < y ) ? x : y ; } int max ( int x , int y ) { return ( x > y ) ? x : y ; } int findLength ( int arr [ ] , int n ) { int max_len = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int mn = arr [ i ] , mx = arr [ i ] ; for ( int j = i + 1 ; j < n ; j ++ ) { mn = min ( mn , arr [ j ] ) ; mx = max ( mx , arr [ j ] ) ; if ( ( mx - mn ) == j - i ) max_len = max ( max_len , mx - mn + 1 ) ; } } return max_len ; } int main ( ) { int arr [ ] = { 1 , 56 , 58 , 57 , 90 , 92 , 94 , 93 , 91 , 45 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Length ▁ of ▁ the ▁ longest ▁ contiguous ▁ subarray ▁ is ▁ " << findLength ( arr , n ) ; return 0 ; }
Print all increasing sequences of length k from first n natural numbers | C ++ program to print all increasing sequences of length ' k ' such that the elements in every sequence are from first ' n ' natural numbers . ; A utility function to print contents of arr [ 0. . k - 1 ] ; A recursive function to print all increasing sequences of first n natural numbers . Every sequence should be length k . The array arr [ ] is used to store current sequence . ; If length of current increasing sequence becomes k , print it ; Decide the starting number to put at current position : If length is 0 , then there are no previous elements in arr [ ] . So start putting new numbers with 1. If length is not 0 , then start from value of previous element plus 1. ; Increase length ; Put all numbers ( which are greater than the previous element ) at new position . ; This is important . The variable ' len ' is shared among all function calls in recursion tree . Its value must be brought back before next iteration of while loop ; This function prints all increasing sequences of first n natural numbers . The length of every sequence must be k . This function mainly uses printSeqUtil ( ) ; An array to store individual sequences ; Initial length of current sequence ; Driver program to test above functions
#include <iostream> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int k ) { for ( int i = 0 ; i < k ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } void printSeqUtil ( int n , int k , int & len , int arr [ ] ) { if ( len == k ) { printArr ( arr , k ) ; return ; } int i = ( len == 0 ) ? 1 : arr [ len - 1 ] + 1 ; len ++ ; while ( i <= n ) { arr [ len - 1 ] = i ; printSeqUtil ( n , k , len , arr ) ; i ++ ; } len -- ; } void printSeq ( int n , int k ) { int arr [ k ] ; int len = 0 ; printSeqUtil ( n , k , len , arr ) ; } int main ( ) { int k = 3 , n = 7 ; printSeq ( n , k ) ; return 0 ; }
Given two strings , find if first string is a subsequence of second | Recursive C ++ program to check if a string is subsequence of another string ; Returns true if str1 [ ] is a subsequence of str2 [ ] . m is length of str1 and n is length of str2 ; Base Cases ; If last characters of two strings are matching ; If last characters are not matching ; Driver program to test methods of graph class
#include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; bool isSubSequence ( char str1 [ ] , char str2 [ ] , int m , int n ) { if ( m == 0 ) return true ; if ( n == 0 ) return false ; if ( str1 [ m - 1 ] == str2 [ n - 1 ] ) return isSubSequence ( str1 , str2 , m - 1 , n - 1 ) ; return isSubSequence ( str1 , str2 , m , n - 1 ) ; } int main ( ) { char str1 [ ] = " gksrek " ; char str2 [ ] = " geeksforgeeks " ; int m = strlen ( str1 ) ; int n = strlen ( str2 ) ; isSubSequence ( str1 , str2 , m , n ) ? cout << " Yes ▁ " : cout << " No " ; return 0 ; }
Find a sorted subsequence of size 3 in linear time | C ++ Program for above approach ; Function to find the triplet ; If number of elements < 3 then no triplets are possible ; track best sequence length ( not current sequence length ) ; min number in array ; least max number in best sequence i . e . track arr [ j ] ( e . g . in array { 1 , 5 , 3 } our best sequence would be { 1 , 3 } with arr [ j ] = 3 ) ; save arr [ i ] ; Iterate from 1 to nums . size ( ) ; this condition is only hit when current sequence size is 2 ; update best sequence max number to a smaller value ( i . e . we 've found a smaller value for arr[j]) ; store best sequence start value i . e . arr [ i ] ; Increase best sequence length & save next number in our triplet ; We 've found our arr[k]! Print the output ; No triplet found ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find3Numbers ( vector < int > & nums ) { if ( nums . size ( ) < 3 ) { cout << " No ▁ such ▁ triplet ▁ found " ; return ; } int seq = 1 ; int min_num = nums [ 0 ] ; int max_seq = INT_MIN ; int store_min = min_num ; for ( int i = 1 ; i < nums . size ( ) ; i ++ ) { if ( nums [ i ] == min_num ) continue ; else if ( nums [ i ] < min_num ) { min_num = nums [ i ] ; continue ; } else if ( nums [ i ] < max_seq ) { max_seq = nums [ i ] ; store_min = min_num ; } else if ( nums [ i ] > max_seq ) { seq ++ ; if ( seq == 3 ) { cout << " Triplet : ▁ " << store_min << " , ▁ " << max_seq << " , ▁ " << nums [ i ] << endl ; return ; } max_seq = nums [ i ] ; } } cout << " No ▁ such ▁ triplet ▁ found " ; } int main ( ) { vector < int > nums { 1 , 2 , -1 , 7 , 5 } ; find3Numbers ( nums ) ; }
Maximum Product Subarray | C ++ program to find Maximum Product Subarray ; Returns the product of max product subarray . ; Initializing result ; traversing in current subarray ; updating result every time to keep an eye over the maximum product ; updating the result for ( n - 1 ) th index . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSubarrayProduct ( int arr [ ] , int n ) { int result = arr [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { int mul = arr [ i ] ; for ( int j = i + 1 ; j < n ; j ++ ) { result = max ( result , mul ) ; mul *= arr [ j ] ; } result = max ( result , mul ) ; } return result ; } int main ( ) { int arr [ ] = { 1 , -2 , -3 , 0 , 7 , -8 , -2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ Sub ▁ array ▁ product ▁ is ▁ " << maxSubarrayProduct ( arr , n ) ; return 0 ; }
Replace every element with the greatest element on right side | C ++ Program to replace every element with the greatest element on right side ; Function to replace every element with the next greatest element ; Initialize the next greatest element ; The next greatest element for the rightmost element is always - 1 ; Replace all other elements with the next greatest ; Store the current element ( needed later for updating the next greatest element ) ; Replace current element with the next greatest ; Update the greatest element , if needed ; A utility Function that prints an array ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nextGreatest ( int arr [ ] , int size ) { int max_from_right = arr [ size - 1 ] ; arr [ size - 1 ] = -1 ; for ( int i = size - 2 ; i >= 0 ; i -- ) { int temp = arr [ i ] ; arr [ i ] = max_from_right ; if ( max_from_right < temp ) max_from_right = temp ; } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } int main ( ) { int arr [ ] = { 16 , 17 , 4 , 3 , 5 , 2 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; nextGreatest ( arr , size ) ; cout << " The ▁ modified ▁ array ▁ is : ▁ STRNEWLINE " ; printArray ( arr , size ) ; return ( 0 ) ; }
Maximum circular subarray sum | C ++ program for maximum contiguous circular sum problem ; The function returns maximum circular contiguous sum in a [ ] ; Corner Case ; Initialize sum variable which store total sum of the array . ; Initialize every variable with first value of array . ; Concept of Kadane 's Algorithm ; Kadane 's Algorithm to find Maximum subarray sum. ; Kadane 's Algorithm to find Minimum subarray sum. ; returning the maximum value ; Driver program to test maxCircularSum ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCircularSum ( int a [ ] , int n ) { if ( n == 1 ) return a [ 0 ] ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } int curr_max = a [ 0 ] , max_so_far = a [ 0 ] , curr_min = a [ 0 ] , min_so_far = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { curr_max = max ( curr_max + a [ i ] , a [ i ] ) ; max_so_far = max ( max_so_far , curr_max ) ; curr_min = min ( curr_min + a [ i ] , a [ i ] ) ; min_so_far = min ( min_so_far , curr_min ) ; } if ( min_so_far == sum ) return max_so_far ; return max ( max_so_far , sum - min_so_far ) ; } int main ( ) { int a [ ] = { 11 , 10 , -20 , 5 , -3 , -5 , 8 , -13 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << " Maximum ▁ circular ▁ sum ▁ is ▁ " << maxCircularSum ( a , n ) << endl ; return 0 ; }
Construction of Longest Increasing Subsequence ( N log N ) | C ++ implementation to find longest increasing subsequence in O ( n Log n ) time . ; Binary search ; Add boundary case , when array n is zero Depend on smart pointers ; initialized with - 1 ; it will always point to empty location ; new smallest value ; arr [ i ] wants to extend largest subsequence ; arr [ i ] wants to be a potential condidate of future subsequence It will replace ceil value in tailIndices ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int GetCeilIndex ( int arr [ ] , vector < int > & T , int l , int r , int key ) { while ( r - l > 1 ) { int m = l + ( r - l ) / 2 ; if ( arr [ T [ m ] ] >= key ) r = m ; else l = m ; } return r ; } int LongestIncreasingSubsequence ( int arr [ ] , int n ) { vector < int > tailIndices ( n , 0 ) ; vector < int > prevIndices ( n , -1 ) ; int len = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ tailIndices [ 0 ] ] ) { tailIndices [ 0 ] = i ; } else if ( arr [ i ] > arr [ tailIndices [ len - 1 ] ] ) { prevIndices [ i ] = tailIndices [ len - 1 ] ; tailIndices [ len ++ ] = i ; } else { int pos = GetCeilIndex ( arr , tailIndices , -1 , len - 1 , arr [ i ] ) ; prevIndices [ i ] = tailIndices [ pos - 1 ] ; tailIndices [ pos ] = i ; } } cout << " LIS ▁ of ▁ given ▁ input " << endl ; for ( int i = tailIndices [ len - 1 ] ; i >= 0 ; i = prevIndices [ i ] ) cout << arr [ i ] << " ▁ " ; cout << endl ; return len ; } int main ( ) { int arr [ ] = { 2 , 5 , 3 , 7 , 11 , 8 , 10 , 13 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " LIS ▁ size ▁ % d STRNEWLINE " , LongestIncreasingSubsequence ( arr , n ) ) ; return 0 ; }
Maximize sum of consecutive differences in a circular array | C ++ program to maximize the sum of difference between consecutive elements in circular array ; Return the maximum Sum of difference between consecutive elements . ; Sorting the array . ; Subtracting a1 , a2 , a3 , ... . . , a ( n / 2 ) - 1 , an / 2 twice and adding a ( n / 2 ) + 1 , a ( n / 2 ) + 2 , a ( n / 2 ) + 3 , . ... . , an - 1 , an twice . ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int n ) { int sum = 0 ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n / 2 ; i ++ ) { sum -= ( 2 * arr [ i ] ) ; sum += ( 2 * arr [ n - i - 1 ] ) ; } return sum ; } int main ( ) { int arr [ ] = { 4 , 2 , 1 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSum ( arr , n ) << endl ; return 0 ; }
Three way partitioning of an array around a given range | C ++ program to implement three way partitioning around a given range . ; Partitions arr [ 0. . n - 1 ] around [ lowVal . . highVal ] ; Initialize ext available positions for smaller ( than range ) and greater lements ; Traverse elements from left ; If current element is smaller than range , put it on next available smaller position . ; If current element is greater than range , put it on next available greater position . ; Driver code
#include <iostream> NEW_LINE using namespace std ; void threeWayPartition ( int arr [ ] , int n , int lowVal , int highVal ) { int start = 0 , end = n - 1 ; for ( int i = 0 ; i <= end ; ) { if ( arr [ i ] < lowVal ) swap ( arr [ i ++ ] , arr [ start ++ ] ) ; else if ( arr [ i ] > highVal ) swap ( arr [ i ] , arr [ end -- ] ) ; else i ++ ; } } int main ( ) { int arr [ ] = { 1 , 14 , 5 , 20 , 4 , 2 , 54 , 20 , 87 , 98 , 3 , 1 , 32 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; threeWayPartition ( arr , n , 10 , 20 ) ; cout << " Modified ▁ array ▁ STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; }
Generate all possible sorted arrays from alternate elements of two given sorted arrays | ; Function to generates and prints all sorted arrays from alternate elements of ' A [ i . . m - 1 ] ' and ' B [ j . . n - 1 ] ' If ' flag ' is true , then current element is to be included from A otherwise from B . ' len ' is the index in output array C [ ] . We print output array each time before including a character from A only if length of output array is greater than 0. We try than all possible combinations ; Include valid element from A ; Print output if there is at least one ' B ' in output array ' C ' ; Recur for all elements of A after current index ; this block works for the very first call to include the first element in the output array ; don 't increment lem as B is included yet ; include valid element from A and recur ; Include valid element from B and recur ; Wrapper function ; output array ; A utility function to print an array ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) ; void generateUtil ( int A [ ] , int B [ ] , int C [ ] , int i , int j , int m , int n , int len , bool flag ) { if ( flag ) { if ( len ) printArr ( C , len + 1 ) ; for ( int k = i ; k < m ; k ++ ) { if ( ! len ) { C [ len ] = A [ k ] ; generateUtil ( A , B , C , k + 1 , j , m , n , len , ! flag ) ; } else { if ( A [ k ] > C [ len ] ) { C [ len + 1 ] = A [ k ] ; generateUtil ( A , B , C , k + 1 , j , m , n , len + 1 , ! flag ) ; } } } } else { for ( int l = j ; l < n ; l ++ ) { if ( B [ l ] > C [ len ] ) { C [ len + 1 ] = B [ l ] ; generateUtil ( A , B , C , i , l + 1 , m , n , len + 1 , ! flag ) ; } } } } void generate ( int A [ ] , int B [ ] , int m , int n ) { int C [ m + n ] ; generateUtil ( A , B , C , 0 , 0 , m , n , 0 , true ) ; } void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } int main ( ) { int A [ ] = { 10 , 15 , 25 } ; int B [ ] = { 5 , 20 , 30 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int m = sizeof ( B ) / sizeof ( B [ 0 ] ) ; generate ( A , B , n , m ) ; return 0 ; }
Minimum number of swaps required for arranging pairs adjacent to each other | C ++ program to find minimum number of swaps required so that all pairs become adjacent . ; This function updates indexes of elements ' a ' and ' b ' ; This function returns minimum number of swaps required to arrange all elements of arr [ i . . n ] become arranged ; If all pairs procesed so no swapping needed return 0 ; If current pair is valid so DO NOT DISTURB this pair and move ahead . ; Swap pair of arr [ i ] with arr [ i + 1 ] and recursively compute minimum swap required if this move is made . ; Backtrack to previous configuration . Also restore the previous indices , of one and two ; Now swap arr [ i ] with pair of arr [ i + 1 ] and recursively compute minimum swaps required for the subproblem after this move ; Backtrack to previous configuration . Also restore the previous indices , of one and two ; Return minimum of two cases ; Returns minimum swaps required ; To store indices of array elements ; Store index of each element in array index ; Call the recursive function ; Driver program ; For simplicity , it is assumed that arr [ 0 ] is not used . The elements from index 1 to n are only valid elements ; if ( a , b ) is pair than we have assigned elements in array such that pairs [ a ] = b and pairs [ b ] = a ; Number of pairs n is half of total elements ; If there are n elements in array , then there are n pairs
#include <bits/stdc++.h> NEW_LINE using namespace std ; void updateindex ( int index [ ] , int a , int ai , int b , int bi ) { index [ a ] = ai ; index [ b ] = bi ; } int minSwapsUtil ( int arr [ ] , int pairs [ ] , int index [ ] , int i , int n ) { if ( i > n ) return 0 ; if ( pairs [ arr [ i ] ] == arr [ i + 1 ] ) return minSwapsUtil ( arr , pairs , index , i + 2 , n ) ; int one = arr [ i + 1 ] ; int indextwo = i + 1 ; int indexone = index [ pairs [ arr [ i ] ] ] ; int two = arr [ index [ pairs [ arr [ i ] ] ] ] ; swap ( arr [ i + 1 ] , arr [ indexone ] ) ; updateindex ( index , one , indexone , two , indextwo ) ; int a = minSwapsUtil ( arr , pairs , index , i + 2 , n ) ; swap ( arr [ i + 1 ] , arr [ indexone ] ) ; updateindex ( index , one , indextwo , two , indexone ) ; one = arr [ i ] , indexone = index [ pairs [ arr [ i + 1 ] ] ] ; two = arr [ index [ pairs [ arr [ i + 1 ] ] ] ] , indextwo = i ; swap ( arr [ i ] , arr [ indexone ] ) ; updateindex ( index , one , indexone , two , indextwo ) ; int b = minSwapsUtil ( arr , pairs , index , i + 2 , n ) ; swap ( arr [ i ] , arr [ indexone ] ) ; updateindex ( index , one , indextwo , two , indexone ) ; return 1 + min ( a , b ) ; } int minSwaps ( int n , int pairs [ ] , int arr [ ] ) { int index [ 2 * n + 1 ] ; for ( int i = 1 ; i <= 2 * n ; i ++ ) index [ arr [ i ] ] = i ; return minSwapsUtil ( arr , pairs , index , 1 , 2 * n ) ; } int main ( ) { int arr [ ] = { 0 , 3 , 5 , 6 , 4 , 1 , 2 } ; int pairs [ ] = { 0 , 3 , 6 , 1 , 5 , 4 , 2 } ; int m = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int n = m / 2 ; cout << " Min ▁ swaps ▁ required ▁ is ▁ " << minSwaps ( n , pairs , arr ) ; return 0 ; }
Replace two consecutive equal values with one greater | C ++ program to replace two elements with equal values with one greater . ; Function to replace consecutive equal elements ; Index in result ; to print new array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void replace_elements ( int arr [ ] , int n ) { int pos = 0 ; for ( int i = 0 ; i < n ; i ++ ) { arr [ pos ++ ] = arr [ i ] ; while ( pos > 1 && arr [ pos - 2 ] == arr [ pos - 1 ] ) { pos -- ; arr [ pos - 1 ] ++ ; } } for ( int i = 0 ; i < pos ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 6 , 4 , 3 , 4 , 3 , 3 , 5 } ; int n = sizeof ( arr ) / sizeof ( int ) ; replace_elements ( arr , n ) ; return 0 ; }
Rearrange a binary string as alternate x and y occurrences | C ++ program to arrange given string ; Function which arrange the given string ; Counting number of 0 ' s ▁ and ▁ 1' s in the given string . ; Printing first all 0 ' s ▁ x - times ▁ ▁ and ▁ decrement ▁ count ▁ of ▁ 0' s x - times and do the similar task with '1' ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void arrangeString ( string str , int x , int y ) { int count_0 = 0 ; int count_1 = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '0' ) count_0 ++ ; else count_1 ++ ; } while ( count_0 > 0 count_1 > 0 ) { for ( int j = 0 ; j < x && count_0 > 0 ; j ++ ) { if ( count_0 > 0 ) { cout << "0" ; count_0 -- ; } } for ( int j = 0 ; j < y && count_1 > 0 ; j ++ ) { if ( count_1 > 0 ) { cout << "1" ; count_1 -- ; } } } } int main ( ) { string str = "01101101101101101000000" ; int x = 1 ; int y = 2 ; arrangeString ( str , x , y ) ; return 0 ; }
Shuffle 2 n integers as a1 | C ++ program to shuffle an array in the form of a1 , b1 , a2 , b2 , ... ; function to rearrange the array ; if size is null or odd return because it is not possible to rearrange ; start from the middle index ; each time we will set two elements from the start to the valid position by swapping ; Driver Program
#include <iostream> NEW_LINE using namespace std ; void rearrange ( int arr [ ] , int n ) { if ( arr == NULL n % 2 == 1 ) return ; int currIdx = ( n - 1 ) / 2 ; while ( currIdx > 0 ) { int count = currIdx , swapIdx = currIdx ; while ( count -- > 0 ) { int temp = arr [ swapIdx + 1 ] ; arr [ swapIdx + 1 ] = arr [ swapIdx ] ; arr [ swapIdx ] = temp ; swapIdx ++ ; } currIdx -- ; } } int main ( ) { int arr [ ] = { 1 , 3 , 5 , 2 , 4 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; rearrange ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << " ▁ " << arr [ i ] ; }
Maximum difference between two elements such that larger element appears after the smaller number | C ++ program to find Maximum difference between two elements such that larger element appears after the smaller number ; The function assumes that there are at least two elements in array . The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal ; Driver program to test above function ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDiff ( int arr [ ] , int arr_size ) { int max_diff = arr [ 1 ] - arr [ 0 ] ; for ( int i = 0 ; i < arr_size ; i ++ ) { for ( int j = i + 1 ; j < arr_size ; j ++ ) { if ( arr [ j ] - arr [ i ] > max_diff ) max_diff = arr [ j ] - arr [ i ] ; } } return max_diff ; } int main ( ) { int arr [ ] = { 1 , 2 , 90 , 10 , 110 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ difference ▁ is ▁ " << maxDiff ( arr , n ) ; return 0 ; }
Maximum difference between two elements such that larger element appears after the smaller number | C ++ program to find Maximum difference between two elements such that larger element appears after the smaller number ; The function assumes that there are at least two elements in array . The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal ; Initialize Result ; Initialize max element from right side ; Driver program to test above function ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDiff ( int arr [ ] , int n ) { int maxDiff = -1 ; int maxRight = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > maxRight ) maxRight = arr [ i ] ; else { int diff = maxRight - arr [ i ] ; if ( diff > maxDiff ) { maxDiff = diff ; } } } return maxDiff ; } int main ( ) { int arr [ ] = { 1 , 2 , 90 , 10 , 110 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ difference ▁ is ▁ " << maxDiff ( arr , n ) ; return 0 ; }
Maximum difference between two elements such that larger element appears after the smaller number | C ++ program to find Maximum difference between two elements such that larger element appears after the smaller number ; The function assumes that there are at least two elements in array . The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal ; Initialize diff , current sum and max sum ; Calculate current diff ; Calculate current sum ; Update max sum , if needed ; Driver program to test above function ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDiff ( int arr [ ] , int n ) { int diff = arr [ 1 ] - arr [ 0 ] ; int curr_sum = diff ; int max_sum = curr_sum ; for ( int i = 1 ; i < n - 1 ; i ++ ) { diff = arr [ i + 1 ] - arr [ i ] ; if ( curr_sum > 0 ) curr_sum += diff ; else curr_sum = diff ; if ( curr_sum > max_sum ) max_sum = curr_sum ; } return max_sum ; } int main ( ) { int arr [ ] = { 80 , 2 , 6 , 3 , 100 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ difference ▁ is ▁ " << maxDiff ( arr , n ) ; return 0 ; }
Find the maximum element in an array which is first increasing and then decreasing | C ++ program to find maximum element ; function to find the maximum element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximum ( int arr [ ] , int low , int high ) { int max = arr [ low ] ; int i ; for ( i = low + 1 ; i <= high ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; else break ; } return max ; } int main ( ) { int arr [ ] = { 1 , 30 , 40 , 50 , 60 , 70 , 23 , 20 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The ▁ maximum ▁ element ▁ is ▁ " << findMaximum ( arr , 0 , n - 1 ) ; return 0 ; }
Find the maximum element in an array which is first increasing and then decreasing | ; Base Case : Only one element is present in arr [ low . . high ] ; If there are two elements and first is greater then the first element is maximum ; If there are two elements and second is greater then the second element is maximum ; If we reach a point where arr [ mid ] is greater than both of its adjacent elements arr [ mid - 1 ] and arr [ mid + 1 ] , then arr [ mid ] is the maximum element ; If arr [ mid ] is greater than the next element and smaller than the previous element then maximum lies on left side of mid ; when arr [ mid ] is greater than arr [ mid - 1 ] and smaller than arr [ mid + 1 ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaximum ( int arr [ ] , int low , int high ) { if ( low == high ) return arr [ low ] ; if ( ( high == low + 1 ) && arr [ low ] >= arr [ high ] ) return arr [ low ] ; if ( ( high == low + 1 ) && arr [ low ] < arr [ high ] ) return arr [ high ] ; int mid = ( low + high ) / 2 ; if ( arr [ mid ] > arr [ mid + 1 ] && arr [ mid ] > arr [ mid - 1 ] ) return arr [ mid ] ; if ( arr [ mid ] > arr [ mid + 1 ] && arr [ mid ] < arr [ mid - 1 ] ) return findMaximum ( arr , low , mid - 1 ) ; else return findMaximum ( arr , mid + 1 , high ) ; } int main ( ) { int arr [ ] = { 1 , 3 , 50 , 10 , 9 , 7 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The ▁ maximum ▁ element ▁ is ▁ " << findMaximum ( arr , 0 , n - 1 ) ; return 0 ; }
Count smaller elements on right side | ; Initialize all the counts in countSmaller array as 0 ; Utility function that prints out an array on a line ; Driver code
#include <iostream> NEW_LINE using namespace std ; void constructLowerArray ( int arr [ ] , int * countSmaller , int n ) { int i , j ; for ( i = 0 ; i < n ; i ++ ) countSmaller [ i ] = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] < arr [ i ] ) countSmaller [ i ] ++ ; } } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 12 , 10 , 5 , 4 , 2 , 20 , 6 , 1 , 0 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * low = ( int * ) malloc ( sizeof ( int ) * n ) ; constructLowerArray ( arr , low , n ) ; printArray ( low , n ) ; return 0 ; }
Count smaller elements on right side | ; An AVL tree node ; size of the tree rooted with this node ; A utility function to get maximum of two integers ; A utility function to get height of the tree rooted with N ; A utility function to size of the tree of rooted with N ; A utility function to get maximum of two integers ; Helper function that allocates a new node with the given key and NULL left and right pointers . ; New node is initially added at leaf ; A utility function to right rotate subtree rooted with y ; Perform rotation ; Update heights ; Update sizes ; Return new root ; A utility function to left rotate subtree rooted with x ; Perform rotation ; Update heights ; Update sizes ; Return new root ; Get Balance factor of node N ; Inserts a new key to the tree rotted with node . Also , updates * count to contain count of smaller elements for the new key ; 1. Perform the normal BST rotation ; UPDATE COUNT OF SMALLER ELEMENTS FOR KEY ; 2. Update height and size of this ancestor node ; 3. Get the balance factor of this ancestor node to check whether this node became unbalanced ; Left Left Case ; Right Right Case ; Left Right Case ; Right Left Case ; Return the ( unchanged ) node pointer ; The following function updates the countSmaller array to contain count of smaller elements on right side . ; Initialize all the counts in countSmaller array as 0 ; Starting from rightmost element , insert all elements one by one in an AVL tree and get the count of smaller elements ; Utility function that prints out an array on a line ; Driver code
#include <iostream> NEW_LINE using namespace std ; #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE struct node { int key ; struct node * left ; struct node * right ; int height ; int size ; } ; int max ( int a , int b ) ; int height ( struct node * N ) { if ( N == NULL ) return 0 ; return N -> height ; } int size ( struct node * N ) { if ( N == NULL ) return 0 ; return N -> size ; } int max ( int a , int b ) { return ( a > b ) ? a : b ; } struct node * newNode ( int key ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> key = key ; node -> left = NULL ; node -> right = NULL ; node -> height = 1 ; node -> size = 1 ; return ( node ) ; } struct node * rightRotate ( struct node * y ) { struct node * x = y -> left ; struct node * T2 = x -> right ; x -> right = y ; y -> left = T2 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; y -> size = size ( y -> left ) + size ( y -> right ) + 1 ; x -> size = size ( x -> left ) + size ( x -> right ) + 1 ; return x ; } struct node * leftRotate ( struct node * x ) { struct node * y = x -> right ; struct node * T2 = y -> left ; y -> left = x ; x -> right = T2 ; x -> height = max ( height ( x -> left ) , height ( x -> right ) ) + 1 ; y -> height = max ( height ( y -> left ) , height ( y -> right ) ) + 1 ; x -> size = size ( x -> left ) + size ( x -> right ) + 1 ; y -> size = size ( y -> left ) + size ( y -> right ) + 1 ; return y ; } int getBalance ( struct node * N ) { if ( N == NULL ) return 0 ; return height ( N -> left ) - height ( N -> right ) ; } struct node * insert ( struct node * node , int key , int * count ) { if ( node == NULL ) return ( newNode ( key ) ) ; if ( key < node -> key ) node -> left = insert ( node -> left , key , count ) ; else { node -> right = insert ( node -> right , key , count ) ; * count = * count + size ( node -> left ) + 1 ; } node -> height = max ( height ( node -> left ) , height ( node -> right ) ) + 1 ; node -> size = size ( node -> left ) + size ( node -> right ) + 1 ; int balance = getBalance ( node ) ; if ( balance > 1 && key < node -> left -> key ) return rightRotate ( node ) ; if ( balance < -1 && key > node -> right -> key ) return leftRotate ( node ) ; if ( balance > 1 && key > node -> left -> key ) { node -> left = leftRotate ( node -> left ) ; return rightRotate ( node ) ; } if ( balance < -1 && key < node -> right -> key ) { node -> right = rightRotate ( node -> right ) ; return leftRotate ( node ) ; } return node ; } void constructLowerArray ( int arr [ ] , int countSmaller [ ] , int n ) { int i , j ; struct node * root = NULL ; for ( i = 0 ; i < n ; i ++ ) countSmaller [ i ] = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { root = insert ( root , arr [ i ] , & countSmaller [ i ] ) ; } } void printArray ( int arr [ ] , int size ) { int i ; cout << " STRNEWLINE " ; for ( i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 10 , 6 , 15 , 20 , 30 , 5 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * low = ( int * ) malloc ( sizeof ( int ) * n ) ; constructLowerArray ( arr , low , n ) ; cout << " Following ▁ is ▁ the ▁ constructed ▁ smaller ▁ count ▁ array " ; printArray ( low , n ) ; return 0 ; }
Find the smallest positive number missing from an unsorted array | Set 1 | C ++ program to find the smallest positive missing number ; Utility to swap to integers ; Utility function that puts all non - positive ( 0 and negative ) numbers on left side of arr [ ] and return count of such numbers ; increment count of non - positive integers ; Find the smallest positive missing number in an array that contains all positive integers ; Mark arr [ i ] as visited by making arr [ arr [ i ] - 1 ] negative . Note that 1 is subtracted because index start from 0 and positive numbers start from 1 ; Return the first index value at which is positive ; 1 is added because indexes start from 0 ; Find the smallest positive missing number in an array that contains both positive and negative integers ; First separate positive and negative numbers ; Shift the array and call findMissingPositive for positive part ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( int * a , int * b ) { int temp ; temp = * a ; * a = * b ; * b = temp ; } int segregate ( int arr [ ] , int size ) { int j = 0 , i ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ i ] <= 0 ) { swap ( & arr [ i ] , & arr [ j ] ) ; j ++ ; } } return j ; } int findMissingPositive ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) { if ( abs ( arr [ i ] ) - 1 < size && arr [ abs ( arr [ i ] ) - 1 ] > 0 ) arr [ abs ( arr [ i ] ) - 1 ] = - arr [ abs ( arr [ i ] ) - 1 ] ; } for ( i = 0 ; i < size ; i ++ ) if ( arr [ i ] > 0 ) return i + 1 ; return size + 1 ; } int findMissing ( int arr [ ] , int size ) { int shift = segregate ( arr , size ) ; return findMissingPositive ( arr + shift , size - shift ) ; } int main ( ) { int arr [ ] = { 0 , 10 , 2 , -10 , -20 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int missing = findMissing ( arr , arr_size ) ; cout << " The ▁ smallest ▁ positive ▁ missing ▁ number ▁ is ▁ " << missing ; return 0 ; }
Find the smallest positive number missing from an unsorted array | Set 1 | C ++ program for the above approach ; Function for finding the first missing positive number ; Loop to traverse the whole array ; Loop to check boundary condition and for swapping ; Checking any element which is not equal to i + 1 ; Nothing is present return last index ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int firstMissingPositive ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { while ( arr [ i ] >= 1 && arr [ i ] <= n && arr [ i ] != arr [ arr [ i ] - 1 ] ) { swap ( arr [ i ] , arr [ arr [ i ] - 1 ] ) ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] != i + 1 ) { return i + 1 ; } } return n + 1 ; } int main ( ) { int arr [ ] = { 2 , 3 , -7 , 6 , 8 , 1 , -10 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int ans = firstMissingPositive ( arr , n ) ; cout << ans ; return 0 ; }
Given an array of size n and a number k , find all elements that appear more than n / k times | C ++ implementation ; Function to find the number of array elements with frequency more than n / k times ; Calculating n / k ; Counting frequency of every element using Counter ; Traverse the map and print all the elements with occurrence more than n / k times ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printElements ( int arr [ ] , int n , int k ) { int x = n / k ; map < int , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ arr [ i ] ] += 1 ; for ( int it = 0 ; it < mp . size ( ) ; it ++ ) { if ( mp [ it ] > x ) cout << ( it ) << endl ; } } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 3 , 5 , 4 , 2 , 2 , 3 , 1 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 4 ; printElements ( arr , n , k ) ; }
Maximum Sum Path in Two Arrays | C ++ program to find maximum sum path ; Utility function to find maximum of two integers ; This function returns the sum of elements on maximum path from beginning to end ; initialize indexes for ar1 [ ] and ar2 [ ] ; Initialize result and current sum through ar1 [ ] and ar2 [ ] . ; Below 3 loops are similar to merge in merge sort ; Add elements of ar1 [ ] to sum1 ; Add elements of ar2 [ ] to sum2 ; we reached a common point ; Take the maximum of two sums and add to result Also add the common element of array , once ; Update sum1 and sum2 for elements after this intersection point ; update i and j to move to next element of each array ; Add remaining elements of ar1 [ ] ; Add remaining elements of ar2 [ ] ; Add maximum of two sums of remaining elements ; Driver code ; Function call
#include <iostream> NEW_LINE using namespace std ; int max ( int x , int y ) { return ( x > y ) ? x : y ; } int maxPathSum ( int ar1 [ ] , int ar2 [ ] , int m , int n ) { int i = 0 , j = 0 ; int result = 0 , sum1 = 0 , sum2 = 0 ; while ( i < m && j < n ) { if ( ar1 [ i ] < ar2 [ j ] ) sum1 += ar1 [ i ++ ] ; else if ( ar1 [ i ] > ar2 [ j ] ) sum2 += ar2 [ j ++ ] ; else { result += max ( sum1 , sum2 ) + ar1 [ i ] ; sum1 = 0 ; sum2 = 0 ; i ++ ; j ++ ; } } while ( i < m ) sum1 += ar1 [ i ++ ] ; while ( j < n ) sum2 += ar2 [ j ++ ] ; result += max ( sum1 , sum2 ) ; return result ; } int main ( ) { int ar1 [ ] = { 2 , 3 , 7 , 10 , 12 , 15 , 30 , 34 } ; int ar2 [ ] = { 1 , 5 , 7 , 8 , 10 , 15 , 16 , 19 } ; int m = sizeof ( ar1 ) / sizeof ( ar1 [ 0 ] ) ; int n = sizeof ( ar2 ) / sizeof ( ar2 [ 0 ] ) ; cout << " Maximum ▁ sum ▁ path ▁ is ▁ " << maxPathSum ( ar1 , ar2 , m , n ) ; return 0 ; }
Smallest greater elements in whole array | Simple C ++ program to find smallest greater element in whole array for every element . ; Find the closest greater element for arr [ j ] in the entire array . ; Check if arr [ i ] is largest ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void smallestGreater ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int diff = INT_MAX , closest = -1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( arr [ i ] < arr [ j ] && arr [ j ] - arr [ i ] < diff ) { diff = arr [ j ] - arr [ i ] ; closest = j ; } } ( closest == -1 ) ? cout << " _ ▁ " : cout << arr [ closest ] << " ▁ " ; } } int main ( ) { int ar [ ] = { 6 , 3 , 9 , 8 , 10 , 2 , 1 , 15 , 7 } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; smallestGreater ( ar , n ) ; return 0 ; }
Smallest greater elements in whole array | Efficient C ++ program to find smallest greater element in whole array for every element . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void smallestGreater ( int arr [ ] , int n ) { set < int > s ; for ( int i = 0 ; i < n ; i ++ ) s . insert ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { auto it = s . find ( arr [ i ] ) ; it ++ ; if ( it != s . end ( ) ) cout << * it << " ▁ " ; else cout << " _ ▁ " ; } } int main ( ) { int ar [ ] = { 6 , 3 , 9 , 8 , 10 , 2 , 1 , 15 , 7 } ; int n = sizeof ( ar ) / sizeof ( ar [ 0 ] ) ; smallestGreater ( ar , n ) ; return 0 ; }
Online algorithm for checking palindrome in a stream | C program for online algorithm for palindrome checking ; d is the number of characters in input alphabet ; q is a prime number used for evaluating Rabin Karp 's Rolling hash ; Length of input string ; A single character is always a palindrome ; Return if string has only one character ; Initialize first half reverse and second half for as firstr and second characters ; Now check for palindromes from second character onward ; If the hash values of ' firstr ' and ' second ' match , then only check individual characters ; Check if str [ 0. . i ] is palindrome using simple character by character match ; Calculate hash values for next iteration . Don 't calculate hash for next characters if this is the last character of string ; If i is even ( next i is odd ) ; Add next character after first half at beginning of ' firstr ' ; Add next character after second half at the end of second half . ; If next i is odd ( next i is even ) then we need not to change firstr , we need to remove first character of second and append a character to it . ; Driver program to test above function
#include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #define d 256 NEW_LINE #define q 103 NEW_LINE void checkPalindromes ( char str [ ] ) { int N = strlen ( str ) ; printf ( " % c ▁ Yes STRNEWLINE " , str [ 0 ] ) ; if ( N == 1 ) return ; int firstr = str [ 0 ] % q ; int second = str [ 1 ] % q ; int h = 1 , i , j ; for ( i = 1 ; i < N ; i ++ ) { if ( firstr == second ) { for ( j = 0 ; j < i / 2 ; j ++ ) { if ( str [ j ] != str [ i - j ] ) break ; } ( j == i / 2 ) ? printf ( " % c ▁ Yes STRNEWLINE " , str [ i ] ) : printf ( " % c ▁ No STRNEWLINE " , str [ i ] ) ; } else printf ( " % c ▁ No STRNEWLINE " , str [ i ] ) ; if ( i != N - 1 ) { if ( i % 2 == 0 ) { h = ( h * d ) % q ; firstr = ( firstr + h * str [ i / 2 ] ) % q ; second = ( second * d + str [ i + 1 ] ) % q ; } else { second = ( d * ( second + q - str [ ( i + 1 ) / 2 ] * h ) % q + str [ i + 1 ] ) % q ; } } } } int main ( ) { char * txt = " aabaacaabaa " ; checkPalindromes ( txt ) ; getchar ( ) ; return 0 ; }
Find zeroes to be flipped so that number of consecutive 1 's is maximized | C ++ program to find positions of zeroes flipping which produces maximum number of xonsecutive 1 's ; m is maximum of number zeroes allowed to flip n is size of array ; Left and right indexes of current window ; Left index and size of the widest window ; Count of zeroes in current window ; While right boundary of current window doesn 't cross right end ; If zero count of current window is less than m , widen the window toward right ; If zero count of current window is more than m , reduce the window from left ; Updqate widest window if this window size is more ; Print positions of zeroes in the widest window ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findZeroes ( int arr [ ] , int n , int m ) { int wL = 0 , wR = 0 ; int bestL = 0 , bestWindow = 0 ; int zeroCount = 0 ; while ( wR < n ) { if ( zeroCount <= m ) { if ( arr [ wR ] == 0 ) zeroCount ++ ; wR ++ ; } if ( zeroCount > m ) { if ( arr [ wL ] == 0 ) zeroCount -- ; wL ++ ; } if ( ( wR - wL > bestWindow ) && ( zeroCount <= m ) ) { bestWindow = wR - wL ; bestL = wL ; } } for ( int i = 0 ; i < bestWindow ; i ++ ) { if ( arr [ bestL + i ] == 0 ) cout << bestL + i << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 1 } ; int m = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Indexes ▁ of ▁ zeroes ▁ to ▁ be ▁ flipped ▁ are ▁ " ; findZeroes ( arr , n , m ) ; return 0 ; }
Count Strictly Increasing Subarrays | C ++ program to count number of strictly increasing subarrays ; Initialize count of subarrays as 0 ; Pick starting point ; Pick ending point ; If subarray arr [ i . . j ] is not strictly increasing , then subarrays after it , i . e . , arr [ i . . j + 1 ] , arr [ i . . j + 2 ] , ... . cannot be strictly increasing ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countIncreasing ( int arr [ ] , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] > arr [ j - 1 ] ) cnt ++ ; else break ; } } return cnt ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Count ▁ of ▁ strictly ▁ increasing ▁ subarrays ▁ is ▁ " << countIncreasing ( arr , n ) ; return 0 ; }
Count Strictly Increasing Subarrays | C ++ program to count number of strictly increasing subarrays in O ( n ) time . ; Initialize result ; Initialize length of current increasing subarray ; Traverse through the array ; If arr [ i + 1 ] is greater than arr [ i ] , then increment length ; Else Update count and reset length ; If last length is more than 1 ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countIncreasing ( int arr [ ] , int n ) { int cnt = 0 ; int len = 1 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( arr [ i + 1 ] > arr [ i ] ) len ++ ; else { cnt += ( ( ( len - 1 ) * len ) / 2 ) ; len = 1 ; } } if ( len > 1 ) cnt += ( ( ( len - 1 ) * len ) / 2 ) ; return cnt ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Count ▁ of ▁ strictly ▁ increasing ▁ subarrays ▁ is ▁ " << countIncreasing ( arr , n ) ; return 0 ; }
Maximum difference between group of k | CPP to find maximum group difference ; utility function for array sum ; function for finding maximum group difference of array ; sort the array ; find array sum ; difference for k - smallest diff1 = ( arraysum - k_smallest ) - k_smallest ; reverse array for finding sum 0f 1 st k - largest ; difference for k - largest diff2 = ( arraysum - k_largest ) - k_largest ; return maximum difference value ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int arraySum ( int arr [ ] , int n ) { long long int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum = sum + arr [ i ] ; return sum ; } long long int maxDiff ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; long long int arraysum = arraySum ( arr , n ) ; long long int diff1 = abs ( arraysum - 2 * arraySum ( arr , k ) ) ; reverse ( arr , arr + n ) ; long long int diff2 = abs ( arraysum - 2 * arraySum ( arr , k ) ) ; return ( max ( diff1 , diff2 ) ) ; } int main ( ) { int arr [ ] = { 1 , 7 , 4 , 8 , -1 , 5 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; cout << " Maximum ▁ Difference ▁ = ▁ " << maxDiff ( arr , n , k ) ; return 0 ; }
Minimum number of elements to add to make median equals x | C ++ program to find minimum number of elements needs to add to the array so that its median equals x . ; Returns count of elements to be added to make median x . This function assumes that a [ ] has enough extra space . ; to sort the array in increasing order . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minNumber ( int a [ ] , int n , int x ) { sort ( a , a + n ) ; int k ; for ( k = 0 ; a [ ( n - 1 ) / 2 ] != x ; k ++ ) { a [ n ++ ] = x ; sort ( a , a + n ) ; } return k ; } int main ( ) { int x = 10 ; int a [ 6 ] = { 10 , 20 , 30 } ; int n = 3 ; cout << minNumber ( a , n , x ) << endl ; return 0 ; }
Minimum number of elements to add to make median equals x | C ++ program to find minimum number of elements to add so that its median equals x . ; no . of elements equals to x , that is , e . ; no . of elements greater than x , that is , h . ; no . of elements smaller than x , that is , l . ; subtract the no . of elements that are equal to x . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minNumber ( int a [ ] , int n , int x ) { int l = 0 , h = 0 , e = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == x ) e ++ ; else if ( a [ i ] > x ) h ++ ; else if ( a [ i ] < x ) l ++ ; } int ans = 0 ; if ( l > h ) ans = l - h ; else if ( l < h ) ans = h - l - 1 ; return ans + 1 - e ; } int main ( ) { int x = 10 ; int a [ ] = { 10 , 20 , 30 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << minNumber ( a , n , x ) << endl ; return 0 ; }
Find whether a subarray is in form of a mountain or not | C ++ program to check whether a subarray is in mountain form or not ; Utility method to construct left and right array ; Initialize first left index as that index only ; if current value is greater than previous , update last increasing ; Initialize last right index as that index only ; if current value is greater than next , update first decreasing ; Method returns true if arr [ L . . R ] is in mountain form ; return true only if right at starting range is greater than left at ending range ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int preprocess ( int arr [ ] , int N , int left [ ] , int right [ ] ) { left [ 0 ] = 0 ; int lastIncr = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) lastIncr = i ; left [ i ] = lastIncr ; } right [ N - 1 ] = N - 1 ; int firstDecr = N - 1 ; for ( int i = N - 2 ; i >= 0 ; i -- ) { if ( arr [ i ] > arr [ i + 1 ] ) firstDecr = i ; right [ i ] = firstDecr ; } } bool isSubarrayMountainForm ( int arr [ ] , int left [ ] , int right [ ] , int L , int R ) { return ( right [ L ] >= left [ R ] ) ; } int main ( ) { int arr [ ] = { 2 , 3 , 2 , 4 , 4 , 6 , 3 , 2 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int left [ N ] , right [ N ] ; preprocess ( arr , N , left , right ) ; int L = 0 ; int R = 2 ; if ( isSubarrayMountainForm ( arr , left , right , L , R ) ) cout << " Subarray ▁ is ▁ in ▁ mountain ▁ form STRNEWLINE " ; else cout << " Subarray ▁ is ▁ not ▁ in ▁ mountain ▁ form STRNEWLINE " ; L = 1 ; R = 3 ; if ( isSubarrayMountainForm ( arr , left , right , L , R ) ) cout << " Subarray ▁ is ▁ in ▁ mountain ▁ form STRNEWLINE " ; else cout << " Subarray ▁ is ▁ not ▁ in ▁ mountain ▁ form STRNEWLINE " ; return 0 ; }
Range sum queries without updates | CPP program to find sum between two indexes when there is no update . ; Returns sum of elements in arr [ i . . j ] It is assumed that i <= j ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void preCompute ( int arr [ ] , int n , int pre [ ] ) { pre [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) pre [ i ] = arr [ i ] + pre [ i - 1 ] ; } int rangeSum ( int i , int j , int pre [ ] ) { if ( i == 0 ) return pre [ j ] ; return pre [ j ] - pre [ i - 1 ] ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int pre [ n ] ; preCompute ( arr , n , pre ) ; cout << rangeSum ( 1 , 3 , pre ) << endl ; cout << rangeSum ( 2 , 4 , pre ) << endl ; return 0 ; }
Number of primes in a subarray ( with updates ) | C ++ program to find number of prime numbers in a subarray and performing updates ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; A utility function to get the middle index from corner indexes . ; A recursive function to get the number of primes in a given range of array indexes . The following are parameters for this function . st -- > Pointer to segment tree index -- > Index of current node in the segment tree . Initially 0 is passed as root is always at index 0 ss & se -- > Starting and ending indexes of the segment represented by current node , i . e . , st [ index ] qs & qe -- > Starting and ending indexes of query range ; If segment of this node is a part of given range , then return the number of primes in the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps with the given range ; A recursive function to update the nodes which have the given index in their range . The following are parameters st , si , ss and se are same as getSumUtil ( ) i -- > index of the element to be updated . This index is in input array . diff -- > Value to be added to all nodes which have i in range ; Base Case : If the input index lies outside the range of this segment ; If the input index is in range of this node , then update the value of the node and its children ; The function to update a value in input array and segment tree . It uses updateValueUtil ( ) to update the value in segment tree ; Check for erroneous input index ; Update the value in array ; Case 1 : Old and new values both are primes ; Case 2 : Old and new values both non primes ; Case 3 : Old value was prime , new value is non prime ; Case 4 : Old value was non prime , new_val is prime ; Update the values of nodes in segment tree ; Return number of primes in range from index qs ( query start ) to qe ( query end ) . It mainly uses queryPrimesUtil ( ) ; A recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st ; If there is one element in array , check if it is prime then store 1 in the segment tree else store 0 and return ; if arr [ ss ] is prime ; If there are more than one elements , then recur for left and right subtrees and store the sum of the two values in this node ; Function to construct segment tree from given array . This function allocates memory for segment tree and calls constructSTUtil ( ) to fill the allocated memory ; Height of segment tree ; Maximum size of segment tree ; Fill the allocated memory st ; Return the constructed segment tree ; Driver program to test above functions ; Preprocess all primes till MAX . Create a boolean array " isPrime [ 0 . . MAX ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Build segment tree from given array ; Query 1 : Query ( start = 0 , end = 4 ) ; Query 2 : Update ( i = 3 , x = 6 ) , i . e Update a [ i ] to x ; Query 3 : Query ( start = 0 , end = 4 )
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE void sieveOfEratosthenes ( bool isPrime [ ] ) { isPrime [ 1 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( isPrime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) isPrime [ i ] = false ; } } } int getMid ( int s , int e ) { return s + ( e - s ) / 2 ; } int queryPrimesUtil ( int * st , int ss , int se , int qs , int qe , int index ) { if ( qs <= ss && qe >= se ) return st [ index ] ; if ( se < qs ss > qe ) return 0 ; int mid = getMid ( ss , se ) ; return queryPrimesUtil ( st , ss , mid , qs , qe , 2 * index + 1 ) + queryPrimesUtil ( st , mid + 1 , se , qs , qe , 2 * index + 2 ) ; } void updateValueUtil ( int * st , int ss , int se , int i , int diff , int si ) { if ( i < ss i > se ) return ; st [ si ] = st [ si ] + diff ; if ( se != ss ) { int mid = getMid ( ss , se ) ; updateValueUtil ( st , ss , mid , i , diff , 2 * si + 1 ) ; updateValueUtil ( st , mid + 1 , se , i , diff , 2 * si + 2 ) ; } } void updateValue ( int arr [ ] , int * st , int n , int i , int new_val , bool isPrime [ ] ) { if ( i < 0 i > n - 1 ) { printf ( " Invalid ▁ Input " ) ; return ; } int diff , oldValue ; oldValue = arr [ i ] ; arr [ i ] = new_val ; if ( isPrime [ oldValue ] && isPrime [ new_val ] ) return ; if ( ( ! isPrime [ oldValue ] ) && ( ! isPrime [ new_val ] ) ) return ; if ( isPrime [ oldValue ] && ! isPrime [ new_val ] ) { diff = -1 ; } if ( ! isPrime [ oldValue ] && isPrime [ new_val ] ) { diff = 1 ; } updateValueUtil ( st , 0 , n - 1 , i , diff , 0 ) ; } void queryPrimes ( int * st , int n , int qs , int qe ) { int primesInRange = queryPrimesUtil ( st , 0 , n - 1 , qs , qe , 0 ) ; cout << " Number ▁ of ▁ Primes ▁ in ▁ subarray ▁ from ▁ " << qs << " ▁ to ▁ " << qe << " ▁ = ▁ " << primesInRange << " STRNEWLINE " ; } int constructSTUtil ( int arr [ ] , int ss , int se , int * st , int si , bool isPrime [ ] ) { if ( ss == se ) { if ( isPrime [ arr [ ss ] ] ) st [ si ] = 1 ; else st [ si ] = 0 ; return st [ si ] ; } int mid = getMid ( ss , se ) ; st [ si ] = constructSTUtil ( arr , ss , mid , st , si * 2 + 1 , isPrime ) + constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 , isPrime ) ; return st [ si ] ; } int * constructST ( int arr [ ] , int n , bool isPrime [ ] ) { int x = ( int ) ( ceil ( log2 ( n ) ) ) ; int max_size = 2 * ( int ) pow ( 2 , x ) - 1 ; int * st = new int [ max_size ] ; constructSTUtil ( arr , 0 , n - 1 , st , 0 , isPrime ) ; return st ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 5 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; bool isPrime [ MAX + 1 ] ; memset ( isPrime , true , sizeof isPrime ) ; sieveOfEratosthenes ( isPrime ) ; int * st = constructST ( arr , n , isPrime ) ; int start = 0 ; int end = 4 ; queryPrimes ( st , n , start , end ) ; int i = 3 ; int x = 6 ; updateValue ( arr , st , n , i , x , isPrime ) ; start = 0 ; end = 4 ; queryPrimes ( st , n , start , end ) ; return 0 ; }
Check in binary array the number represented by a subarray is odd or even | C ++ program to find if a subarray is even or odd . ; prints if subarray is even or odd ; if arr [ r ] = 1 print odd ; if arr [ r ] = 0 print even ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkEVENodd ( int arr [ ] , int n , int l , int r ) { if ( arr [ r ] == 1 ) cout << " odd " << endl ; else cout << " even " << endl ; } int main ( ) { int arr [ ] = { 1 , 1 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkEVENodd ( arr , n , 1 , 3 ) ; return 0 ; }
Array Queries for multiply , replacements and product | C ++ program to solve three types of queries . ; vector of 1000 elements , all set to 0 ; vector of 1000 elements , all set to 0 ; Function to check number of trailing zeros in multiple of 2 ; Function to check number of trailing zeros in multiple of 5 ; Function to solve the queries received ; If the query is of type 1. ; Counting the number of zeros in the given value of x ; The value x has been multiplied to their respective indices ; The value obtained above has been added to their respective vectors ; If the query is of type 2. ; Counting the number of zero in the given value of x ; The value y has been replaced to their respective indices ; The value obtained above has been added to their respective vectors ; If the query is of type 2 ; as the number of trailing zeros for each case has been found for each array element then we simply add those to the respective index to a variable ; Compare the number of zeros obtained in the multiples of five and two consider the minimum of them and add them ; Driver code ; Input the Size of array and number of queries ; Running the while loop for m number of queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > twos ( 1000 , 0 ) ; vector < int > fives ( 1000 , 0 ) ; int sum = 0 ; int returnTwos ( int val ) { int count = 0 ; while ( val % 2 == 0 && val != 0 ) { val = val / 2 ; count ++ ; } return count ; } int returnFives ( int val ) { int count = 0 ; while ( val % 5 == 0 && val != 0 ) { val = val / 5 ; count ++ ; } return count ; } void solve_queries ( int arr [ ] , int n ) { int type , ql , qr , x , y ; cin >> type ; if ( type == 1 ) { cin >> ql >> qr >> x ; int temp = returnTwos ( x ) ; int temp1 = returnFives ( x ) ; for ( int i = ql - 1 ; i < qr ; i ++ ) { arr [ i ] = arr [ i ] * x ; twos [ i ] += temp ; fives [ i ] += temp1 ; } } if ( type == 2 ) { cin >> ql >> qr >> y ; int temp = returnTwos ( y ) ; int temp1 = returnFives ( y ) ; for ( int i = ql - 1 ; i < qr ; i ++ ) { arr [ i ] = ( i - ql + 2 ) * y ; twos [ i ] = returnTwos ( i - ql + 2 ) + temp ; fives [ i ] = returnFives ( i - ql + 2 ) + temp1 ; } } if ( type == 3 ) { cin >> ql >> qr ; int sumtwos = 0 ; int sumfives = 0 ; for ( int i = ql - 1 ; i < qr ; i ++ ) { sumtwos += twos [ i ] ; sumfives += fives [ i ] ; } sum += min ( sumtwos , sumfives ) ; } } int main ( ) { int n , m ; cin >> n >> m ; int arr [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { cin >> arr [ i ] ; twos [ i ] = returnTwos ( arr [ i ] ) ; fives [ i ] = returnFives ( arr [ i ] ) ; } while ( m -- ) { solve_queries ( arr , n ) ; } cout << sum << endl ; return 0 ; }
Mean of range in array | CPP program to find floor value of mean in range l to r ; To find mean of range in l to r ; Both sum and count are initialize to 0 ; To calculate sum and number of elements in range l to r ; Calculate floor value of mean ; Returns mean of array in range l to r ; Driver program to test findMean ( )
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMean ( int arr [ ] , int l , int r ) { int sum = 0 , count = 0 ; for ( int i = l ; i <= r ; i ++ ) { sum += arr [ i ] ; count ++ ; } int mean = floor ( sum / count ) ; return mean ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; cout << findMean ( arr , 0 , 2 ) << endl ; cout << findMean ( arr , 1 , 3 ) << endl ; cout << findMean ( arr , 0 , 4 ) << endl ; return 0 ; }
Mean of range in array | CPP program to find floor value of mean in range l to r ; To calculate prefixSum of array ; Calculate prefix sum of array ; To return floor of mean in range l to r ; Sum of elements in range l to r is prefixSum [ r ] - prefixSum [ l - 1 ] Number of elements in range l to r is r - l + 1 ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE #define MAX 1000005 NEW_LINE using namespace std ; int prefixSum [ MAX ] ; void calculatePrefixSum ( int arr [ ] , int n ) { prefixSum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefixSum [ i ] = prefixSum [ i - 1 ] + arr [ i ] ; } int findMean ( int l , int r ) { if ( l == 0 ) return floor ( prefixSum [ r ] / ( r + 1 ) ) ; return floor ( ( prefixSum [ r ] - prefixSum [ l - 1 ] ) / ( r - l + 1 ) ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; calculatePrefixSum ( arr , n ) ; cout << findMean ( 0 , 2 ) << endl ; cout << findMean ( 1 , 3 ) << endl ; cout << findMean ( 0 , 4 ) << endl ; return 0 ; }
Print modified array after executing the commands of addition and subtraction | C ++ program to find modified array after executing m commands / queries ; Update function for every command ; If q == 0 , add ' k ' and ' - k ' to ' l - 1' and ' r ' index ; If q == 1 , add ' - k ' and ' k ' to ' l - 1' and ' r ' index ; Function to generate the final array after executing all commands ; Generate final array with the help of DP concept ; Driver program ; Generate final array ; Printing the final modified array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void updateQuery ( int arr [ ] , int n , int q , int l , int r , int k ) { if ( q == 0 ) { arr [ l - 1 ] += k ; arr [ r ] += - k ; } else { arr [ l - 1 ] += - k ; arr [ r ] += k ; } return ; } void generateArray ( int arr [ ] , int n ) { for ( int i = 1 ; i < n ; ++ i ) arr [ i ] += arr [ i - 1 ] ; return ; } int main ( ) { int n = 5 ; int arr [ n + 1 ] ; memset ( arr , 0 , sizeof ( arr ) ) ; int q = 0 , l = 1 , r = 3 , k = 2 ; updateQuery ( arr , n , q , l , r , k ) ; q = 1 , l = 3 , r = 5 , k = 3 ; updateQuery ( arr , n , q , l , r , k ) ; q = 0 , l = 2 , r = 5 , k = 1 ; updateQuery ( arr , n , q , l , r , k ) ; generateArray ( arr , n ) ; for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Products of ranges in an array | Product in range Queries in O ( N ) ; Function to calculate Product in the given range . ; As our array is 0 based as and L and R are given as 1 based index . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateProduct ( int A [ ] , int L , int R , int P ) { L = L - 1 ; R = R - 1 ; int ans = 1 ; for ( int i = L ; i <= R ; i ++ ) { ans = ans * A [ i ] ; ans = ans % P ; } return ans ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int P = 229 ; int L = 2 , R = 5 ; cout << calculateProduct ( A , L , R , P ) << endl ; L = 1 , R = 3 ; cout << calculateProduct ( A , L , R , P ) << endl ; return 0 ; }
Products of ranges in an array | Product in range Queries in O ( 1 ) ; Returns modulo inverse of a with respect to m using extended Euclid Algorithm Assumption : a and m are coprimes , i . e . , gcd ( a , m ) = 1 ; q is quotient ; m is remainder now , process same as Euclid 's algo ; Make x1 positive ; calculating pre_product array ; Cacluating inverse_product array . ; Function to calculate Product in the given range . ; As our array is 0 based as and L and R are given as 1 based index . ; Driver Code ; Array ; Prime P ; Calculating PreProduct and InverseProduct ; Range [ L , R ] in 1 base index
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE int pre_product [ MAX ] ; int inverse_product [ MAX ] ; int modInverse ( 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 ; } void calculate_Pre_Product ( int A [ ] , int N , int P ) { pre_product [ 0 ] = A [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { pre_product [ i ] = pre_product [ i - 1 ] * A [ i ] ; pre_product [ i ] = pre_product [ i ] % P ; } } void calculate_inverse_product ( int A [ ] , int N , int P ) { inverse_product [ 0 ] = modInverse ( pre_product [ 0 ] , P ) ; for ( int i = 1 ; i < N ; i ++ ) inverse_product [ i ] = modInverse ( pre_product [ i ] , P ) ; } int calculateProduct ( int A [ ] , int L , int R , int P ) { L = L - 1 ; R = R - 1 ; int ans ; if ( L == 0 ) ans = pre_product [ R ] ; else ans = pre_product [ R ] * inverse_product [ L - 1 ] ; return ans ; } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 5 , 6 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int P = 113 ; calculate_Pre_Product ( A , N , P ) ; calculate_inverse_product ( A , N , P ) ; int L = 2 , R = 5 ; cout << calculateProduct ( A , L , R , P ) << endl ; L = 1 , R = 3 ; cout << calculateProduct ( A , L , R , P ) << endl ; return 0 ; }
Count Primes in Ranges | CPP program to answer queries for count of primes in given range . ; prefix [ i ] is going to store count of primes till i ( including i ) . ; Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Build prefix array ; Returns count of primes in range from L to R ( both inclusive ) . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 10000 ; int prefix [ MAX + 1 ] ; void buildPrefix ( ) { bool prime [ MAX + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } prefix [ 0 ] = prefix [ 1 ] = 0 ; for ( int p = 2 ; p <= MAX ; p ++ ) { prefix [ p ] = prefix [ p - 1 ] ; if ( prime [ p ] ) prefix [ p ] ++ ; } } int query ( int L , int R ) { return prefix [ R ] - prefix [ L - 1 ] ; } int main ( ) { buildPrefix ( ) ; int L = 5 , R = 10 ; cout << query ( L , R ) << endl ; L = 1 , R = 10 ; cout << query ( L , R ) << endl ; return 0 ; }
Binary array after M range toggle operations | CPP program to find modified array after m range toggle operations . ; function for toggle ; function for final processing of array ; function for printing result ; driver program ; function call for toggle ; process array ; print result
#include <bits/stdc++.h> NEW_LINE using namespace std ; void command ( bool arr [ ] , int a , int b ) { arr [ a ] ^= 1 ; arr [ b + 1 ] ^= 1 ; } void process ( bool arr [ ] , int n ) { for ( int k = 1 ; k <= n ; k ++ ) arr [ k ] ^= arr [ k - 1 ] ; } void result ( bool arr [ ] , int n ) { for ( int k = 1 ; k <= n ; k ++ ) cout << arr [ k ] << " ▁ " ; } int main ( ) { int n = 5 , m = 3 ; bool arr [ n + 2 ] = { 0 } ; command ( arr , 1 , 5 ) ; command ( arr , 2 , 5 ) ; command ( arr , 3 , 5 ) ; process ( arr , n ) ; result ( arr , n ) ; return 0 ; }
Check if any two intervals intersects among a given set of intervals | A C ++ program to check if any two intervals overlap ; An interval has start time and end time ; Compares two intervals according to their staring time . This is needed for sorting the intervals using library goo . gl / iGspV function std :: sort ( ) . See http : ; Function to check if any two intervals overlap ; Sort intervals in increasing order of start time ; In the sorted array , if start time of an interval is less than end of previous interval , then there is an overlap ; If we reach here , then no overlap ; Driver program
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; struct Interval { int start ; int end ; } ; bool compareInterval ( Interval i1 , Interval i2 ) { return ( i1 . start < i2 . start ) ? true : false ; } bool isIntersect ( Interval arr [ ] , int n ) { sort ( arr , arr + n , compareInterval ) ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i - 1 ] . end > arr [ i ] . start ) return true ; return false ; } int main ( ) { Interval arr1 [ ] = { { 1 , 3 } , { 7 , 9 } , { 4 , 6 } , { 10 , 13 } } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; isIntersect ( arr1 , n1 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; Interval arr2 [ ] = { { 6 , 8 } , { 1 , 3 } , { 2 , 4 } , { 4 , 7 } } ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; isIntersect ( arr2 , n2 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; }
Check if any two intervals intersects among a given set of intervals | A C ++ program to check if any two intervals overlap ; An interval has start time and end time ; Function to check if any two intervals overlap ; Find the overall maximum element ; Initialize an array of size max_ele ; starting point of the interval ; end point of the interval ; Calculating the prefix Sum ; Overlap ; If we reach here , then no Overlap ; Driver program
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; struct Interval { int start ; int end ; } ; bool isIntersect ( Interval arr [ ] , int n ) { int max_ele = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( max_ele < arr [ i ] . end ) max_ele = arr [ i ] . end ; } int aux [ max_ele + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int x = arr [ i ] . start ; int y = arr [ i ] . end ; aux [ x ] ++ , aux [ y + 1 ] -- ; } for ( int i = 1 ; i <= max_ele ; i ++ ) { aux [ i ] += aux [ i - 1 ] ; if ( aux [ i ] > 1 ) return true ; } return false ; } int main ( ) { Interval arr1 [ ] = { { 1 , 3 } , { 7 , 9 } , { 4 , 6 } , { 10 , 13 } } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; isIntersect ( arr1 , n1 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; Interval arr2 [ ] = { { 6 , 8 } , { 1 , 3 } , { 2 , 4 } , { 4 , 7 } } ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; isIntersect ( arr2 , n2 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; }
Print modified array after multiple array range increment operations | C ++ implementation to increment values in the given range by a value d for multiple queries ; structure to store the ( start , end ) index pair for each query ; function to increment values in the given range by a value d for multiple queries ; for each ( start , end ) index pair perform the following operations on ' sum [ ] ' ; increment the value at index ' start ' by the given value ' d ' in ' sum [ ] ' ; if the index ' ( end + 1 ) ' exists then decrement the value at index ' ( end + 1 ) ' by the given value ' d ' in ' sum [ ] ' ; Now , perform the following operations : accumulate values in the ' sum [ ] ' array and then add them to the corresponding indexes in ' arr [ ] ' ; function to print the elements of the given array ; Driver program to test above ; modifying the array for multiple queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct query { int start , end ; } ; void incrementByD ( int arr [ ] , struct query q_arr [ ] , int n , int m , int d ) { int sum [ n ] ; memset ( sum , 0 , sizeof ( sum ) ) ; for ( int i = 0 ; i < m ; i ++ ) { sum [ q_arr [ i ] . start ] += d ; if ( ( q_arr [ i ] . end + 1 ) < n ) sum [ q_arr [ i ] . end + 1 ] -= d ; } arr [ 0 ] += sum [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { sum [ i ] += sum [ i - 1 ] ; arr [ i ] += sum [ i ] ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 3 , 5 , 4 , 8 , 6 , 1 } ; struct query q_arr [ ] = { { 0 , 3 } , { 4 , 5 } , { 1 , 4 } , { 0 , 1 } , { 2 , 5 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int m = sizeof ( q_arr ) / sizeof ( q_arr [ 0 ] ) ; int d = 2 ; cout << " Original ▁ Array : STRNEWLINE " ; printArray ( arr , n ) ; incrementByD ( arr , q_arr , n , m , d ) ; cout << " Modified Array : " printArray ( arr , n ) ; return 0 ; }
Queries for number of distinct elements in a subarray | C ++ code to find number of distinct numbers in a subarray ; structure to store queries ; cmp function to sort queries according to r ; updating the bit array ; querying the bit array ; initialising bit array ; holds the rightmost index of any number as numbers of a [ i ] are less than or equal to 10 ^ 6 ; answer for each query ; If last visit is not - 1 update - 1 at the idx equal to last_visit [ arr [ i ] ] ; Setting last_visit [ arr [ i ] ] as i and updating the bit array accordingly ; If i is equal to r of any query store answer for that query in ans [ ] ; print answer for each query ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000001 ; struct Query { int l , r , idx ; } ; bool cmp ( Query x , Query y ) { return x . r < y . r ; } void update ( int idx , int val , int bit [ ] , int n ) { for ( ; idx <= n ; idx += idx & - idx ) bit [ idx ] += val ; } int query ( int idx , int bit [ ] , int n ) { int sum = 0 ; for ( ; idx > 0 ; idx -= idx & - idx ) sum += bit [ idx ] ; return sum ; } void answeringQueries ( int arr [ ] , int n , Query queries [ ] , int q ) { int bit [ n + 1 ] ; memset ( bit , 0 , sizeof ( bit ) ) ; int last_visit [ MAX ] ; memset ( last_visit , -1 , sizeof ( last_visit ) ) ; int ans [ q ] ; int query_counter = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( last_visit [ arr [ i ] ] != -1 ) update ( last_visit [ arr [ i ] ] + 1 , -1 , bit , n ) ; last_visit [ arr [ i ] ] = i ; update ( i + 1 , 1 , bit , n ) ; while ( query_counter < q && queries [ query_counter ] . r == i ) { ans [ queries [ query_counter ] . idx ] = query ( queries [ query_counter ] . r + 1 , bit , n ) - query ( queries [ query_counter ] . l , bit , n ) ; query_counter ++ ; } } for ( int i = 0 ; i < q ; i ++ ) cout << ans [ i ] << endl ; } int main ( ) { int a [ ] = { 1 , 1 , 2 , 1 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; Query queries [ 3 ] ; queries [ 0 ] . l = 0 ; queries [ 0 ] . r = 4 ; queries [ 0 ] . idx = 0 ; queries [ 1 ] . l = 1 ; queries [ 1 ] . r = 3 ; queries [ 1 ] . idx = 1 ; queries [ 2 ] . l = 2 ; queries [ 2 ] . r = 4 ; queries [ 2 ] . idx = 2 ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; sort ( queries , queries + q , cmp ) ; answeringQueries ( a , n , queries , q ) ; return 0 ; }
Count and Toggle Queries on a Binary Array | C ++ program to implement toggle and count queries on a binary array . ; segment tree to store count of 1 's within range ; bool type tree to collect the updates for toggling the values of 1 and 0 in given range ; function for collecting updates of toggling node -- > index of current node in segment tree st -- > starting index of current node en -- > ending index of current node us -- > starting index of range update query ue -- > ending index of range update query ; If lazy value is non - zero for current node of segment tree , then there are some pending updates . So we need to make sure that the pending updates are done before making new updates . Because this value may be used by parent after recursive calls ( See last line of this function ) ; Make pending updates using value stored in lazy nodes ; checking if it is not leaf node because if it is leaf node then we cannot go further ; We can postpone updating children we don ' t ▁ ▁ need ▁ their ▁ new ▁ values ▁ now . ▁ ▁ Since ▁ we ▁ are ▁ not ▁ yet ▁ updating ▁ children ▁ of ▁ ' node ', we need to set lazy flags for the children ; out of range ; Current segment is fully in range ; Add the difference to current node ; same logic for checking leaf node or not ; This is where we store values in lazy nodes , rather than updating the segment tree itelf Since we don 't need these updated values now we postpone updates by storing values in lazy[] ; If not completely in rang , but overlaps , recur for children , ; And use the result of children calls to update this node ; function to count number of 1 's within given range ; current node is out of range ; If lazy flag is set for current node of segment tree , then there are some pending updates . So we need to make sure that the pending updates are done before processing the sub sum query ; Make pending updates to this node . Note that this node represents sum of elements in arr [ st . . en ] and all these elements must be increased by lazy [ node ] ; checking if it is not leaf node because if it is leaf node then we cannot go further ; Since we are not yet updating children os si , we need to set lazy values for the children ; At this point we are sure that pending lazy updates are done for current node . So we can return value If this segment lies in range ; If a part of this segment overlaps with the given range ; Driver program to run the case ; Toggle 1 2 ; Toggle 2 4 ; Count 2 3 ; Toggle 2 4 ; Count 1 4
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 100000 ; int tree [ MAX ] = { 0 } ; bool lazy [ MAX ] = { false } ; void toggle ( int node , int st , int en , int us , int ue ) { if ( lazy [ node ] ) { lazy [ node ] = false ; tree [ node ] = en - st + 1 - tree [ node ] ; if ( st < en ) { lazy [ node << 1 ] = ! lazy [ node << 1 ] ; lazy [ 1 + ( node << 1 ) ] = ! lazy [ 1 + ( node << 1 ) ] ; } } if ( st > en us > en ue < st ) return ; if ( us <= st && en <= ue ) { tree [ node ] = en - st + 1 - tree [ node ] ; if ( st < en ) { lazy [ node << 1 ] = ! lazy [ node << 1 ] ; lazy [ 1 + ( node << 1 ) ] = ! lazy [ 1 + ( node << 1 ) ] ; } return ; } int mid = ( st + en ) / 2 ; toggle ( ( node << 1 ) , st , mid , us , ue ) ; toggle ( ( node << 1 ) + 1 , mid + 1 , en , us , ue ) ; if ( st < en ) tree [ node ] = tree [ node << 1 ] + tree [ ( node << 1 ) + 1 ] ; } int countQuery ( int node , int st , int en , int qs , int qe ) { if ( st > en qs > en qe < st ) return 0 ; if ( lazy [ node ] ) { lazy [ node ] = false ; tree [ node ] = en - st + 1 - tree [ node ] ; if ( st < en ) { lazy [ node << 1 ] = ! lazy [ node << 1 ] ; lazy [ ( node << 1 ) + 1 ] = ! lazy [ ( node << 1 ) + 1 ] ; } } if ( qs <= st && en <= qe ) return tree [ node ] ; int mid = ( st + en ) / 2 ; return countQuery ( ( node << 1 ) , st , mid , qs , qe ) + countQuery ( ( node << 1 ) + 1 , mid + 1 , en , qs , qe ) ; } int main ( ) { int n = 5 ; toggle ( 1 , 0 , n - 1 , 1 , 2 ) ; toggle ( 1 , 0 , n - 1 , 2 , 4 ) ; cout << countQuery ( 1 , 0 , n - 1 , 2 , 3 ) << endl ; toggle ( 1 , 0 , n - 1 , 2 , 4 ) ; cout << countQuery ( 1 , 0 , n - 1 , 1 , 4 ) << endl ; return 0 ; }
No of pairs ( a [ j ] >= a [ i ] ) with k numbers in range ( a [ i ] , a [ j ] ) that are divisible by x | C ++ program to calculate the number pairs satisfying th condition ; function to calculate the number of pairs ; traverse through all elements ; current number 's divisor ; use binary search to find the element after k multiples of x ; use binary search to find the element after k + 1 multiples of x so that we get the answer bu subtracting ; the difference of index will be the answer ; driver code to check the above function ; function call to get the number of pairs
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int a [ ] , int n , int x , int k ) { sort ( a , a + n ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int d = ( a [ i ] - 1 ) / x ; int it1 = lower_bound ( a , a + n , max ( ( d + k ) * x , a [ i ] ) ) - a ; int it2 = lower_bound ( a , a + n , max ( ( d + k + 1 ) * x , a [ i ] ) ) - a ; ans += it2 - it1 ; } return ans ; } int main ( ) { int a [ ] = { 1 , 3 , 5 , 7 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int x = 2 , k = 1 ; cout << countPairs ( a , n , x , k ) ; return 0 ; }
Probability of a random pair being the maximum weighted pair | ; Function to return probability ; Count occurrences of maximum element in A [ ] ; Count occurrences of maximum element in B [ ] ; Returning probability ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double probability ( int a [ ] , int b [ ] , int size1 , int size2 ) { int max1 = INT_MIN , count1 = 0 ; for ( int i = 0 ; i < size1 ; i ++ ) { if ( a [ i ] > max1 ) { max1 = a [ i ] ; count1 = 1 ; } else if ( a [ i ] == max1 ) { count1 ++ ; } } int max2 = INT_MIN , count2 = 0 ; for ( int i = 0 ; i < size2 ; i ++ ) { if ( b [ i ] > max2 ) { max2 = b [ i ] ; count2 = 1 ; } else if ( b [ i ] == max2 ) { count2 ++ ; } } return ( double ) ( count1 * count2 ) / ( size1 * size2 ) ; } int main ( ) { int a [ ] = { 1 , 2 , 3 } ; int b [ ] = { 1 , 3 , 3 } ; int size1 = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int size2 = sizeof ( b ) / sizeof ( b [ 0 ] ) ; cout << probability ( a , b , size1 , size2 ) ; return 0 ; }
Minimum De | CPP for counting minimum de - arrangements present in an array . ; function to count Dearrangement ; create a copy of original array ; sort the array ; traverse sorted array for counting mismatches ; reverse the sorted array ; traverse reverse sorted array for counting mismatches ; return minimum mismatch count ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDe ( int arr [ ] , int n ) { vector < int > v ( arr , arr + n ) ; sort ( arr , arr + n ) ; int count1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != v [ i ] ) count1 ++ ; reverse ( arr , arr + n ) ; int count2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != v [ i ] ) count2 ++ ; return ( min ( count1 , count2 ) ) ; } int main ( ) { int arr [ ] = { 5 , 9 , 21 , 17 , 13 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ Dearrangement ▁ = ▁ " << countDe ( arr , n ) ; return 0 ; }
Divide an array into k segments to maximize maximum of segment minimums | CPP Program to find maximum value of maximum of minimums of k segments . ; function to calculate the max of all the minimum segments ; if we have to divide it into 1 segment then the min will be the answer ; If k >= 3 , return maximum of all elements . ; driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxOfSegmentMins ( int a [ ] , int n , int k ) { if ( k == 1 ) return * min_element ( a , a + n ) ; if ( k == 2 ) return max ( a [ 0 ] , a [ n - 1 ] ) ; return * max_element ( a , a + n ) ; } int main ( ) { int a [ ] = { -10 , -9 , -8 , 2 , 7 , -6 , -5 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 2 ; cout << maxOfSegmentMins ( a , n , k ) ; }
Minimum product pair an array of positive Integers | C ++ program to calculate minimum product of a pair ; Function to calculate minimum product of pair ; Initialize first and second minimums . It is assumed that the array has at least two elements . ; Traverse remaining array and keep track of two minimum elements ( Note that the two minimum elements may be same if minimum element appears more than once ) more than once ) ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int printMinimumProduct ( int arr [ ] , int n ) { int first_min = min ( arr [ 0 ] , arr [ 1 ] ) ; int second_min = max ( arr [ 0 ] , arr [ 1 ] ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] < first_min ) { second_min = first_min ; first_min = arr [ i ] ; } else if ( arr [ i ] < second_min ) second_min = arr [ i ] ; } return first_min * second_min ; } int main ( ) { int a [ ] = { 11 , 8 , 5 , 7 , 5 , 100 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << printMinimumProduct ( a , n ) ; return 0 ; }
Count ways to form minimum product triplets | CPP program to count number of ways we can form triplets with minimum product . ; function to calculate number of triples ; Sort the array ; Count occurrences of third element ; If all three elements are same ( minimum element appears at least 3 times ) . Answer is nC3 . ; If minimum element appears once . Answer is nC2 . ; Minimum two elements are distinct . Answer is nC1 . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long noOfTriples ( long long arr [ ] , int n ) { sort ( arr , arr + n ) ; long long count = 0 ; for ( long long i = 0 ; i < n ; i ++ ) if ( arr [ i ] == arr [ 2 ] ) count ++ ; if ( arr [ 0 ] == arr [ 2 ] ) return ( count - 2 ) * ( count - 1 ) * ( count ) / 6 ; else if ( arr [ 1 ] == arr [ 2 ] ) return ( count - 1 ) * ( count ) / 2 ; return count ; } int main ( ) { long long arr [ ] = { 1 , 3 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << noOfTriples ( arr , n ) ; return 0 ; }
Check if reversing a sub array make the array sorted | C ++ program to check whether reversing a sub array make the array sorted or not ; Return true , if reversing the subarray will sort the array , else return false . ; Copying the array . ; Sort the copied array . ; Finding the first mismatch . ; Finding the last mismatch . ; If whole array is sorted ; Checking subarray is decreasing or not . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkReverse ( int arr [ ] , int n ) { int temp [ n ] ; for ( int i = 0 ; i < n ; i ++ ) temp [ i ] = arr [ i ] ; sort ( temp , temp + n ) ; int front ; for ( front = 0 ; front < n ; front ++ ) if ( temp [ front ] != arr [ front ] ) break ; int back ; for ( back = n - 1 ; back >= 0 ; back -- ) if ( temp [ back ] != arr [ back ] ) break ; if ( front >= back ) return true ; do { front ++ ; if ( arr [ front - 1 ] < arr [ front ] ) return false ; } while ( front != back ) ; return true ; } int main ( ) { int arr [ ] = { 1 , 2 , 5 , 4 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkReverse ( arr , n ) ? ( cout << " Yes " << endl ) : ( cout << " No " << endl ) ; return 0 ; }
Check if reversing a sub array make the array sorted | C ++ program to check whether reversing a sub array make the array sorted or not ; Return true , if reversing the subarray will sort t he array , else return false . ; Find first increasing part ; Find reversed part ; Find last increasing part ; To handle cases like { 1 , 2 , 3 , 4 , 20 , 9 , 16 , 17 } ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkReverse ( int arr [ ] , int n ) { if ( n == 1 ) return true ; int i ; for ( i = 1 ; i < n && arr [ i - 1 ] < arr [ i ] ; i ++ ) ; if ( i == n ) return true ; int j = i ; while ( j < n && arr [ j ] < arr [ j - 1 ] ) { if ( i > 1 && arr [ j ] < arr [ i - 2 ] ) return false ; j ++ ; } if ( j == n ) return true ; int k = j ; if ( arr [ k ] < arr [ i - 1 ] ) return false ; while ( k > 1 && k < n ) { if ( arr [ k ] < arr [ k - 1 ] ) return false ; k ++ ; } return true ; } int main ( ) { int arr [ ] = { 1 , 3 , 4 , 10 , 9 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkReverse ( arr , n ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Making elements of two arrays same with minimum increment / decrement | CPP program to find minimum increment / decrement operations to make array elements same . ; sorting both arrays in ascending order ; variable to store the final result ; After sorting both arrays Now each array is in non - decreasing order . Thus , we will now compare each element of the array and do the increment or decrement operation depending upon the value of array b [ ] . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinOperation ( int a [ ] , int b [ ] , int n ) { sort ( a , a + n ) ; sort ( b , b + n ) ; int result = 0 ; for ( int i = 0 ; i < n ; ++ i ) { result = result + abs ( a [ i ] - b [ i ] ) ; } return result ; } int main ( ) { int a [ ] = { 3 , 1 , 1 } ; int b [ ] = { 1 , 2 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << MinOperation ( a , b , n ) ; return 0 ; }
Sorting array except elements in a subarray | CPP program to sort all elements except given subarray . ; Sort whole array a [ ] except elements in range a [ l . . r ] ; Copy all those element that need to be sorted to an auxiliary array b [ ] ; sort the array b ; Copy sorted elements back to a [ ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortExceptUandL ( int a [ ] , int l , int u , int n ) { int b [ n - ( u - l + 1 ) ] ; for ( int i = 0 ; i < l ; i ++ ) b [ i ] = a [ i ] ; for ( int i = u + 1 ; i < n ; i ++ ) b [ l + ( i - ( u + 1 ) ) ] = a [ i ] ; sort ( b , b + n - ( u - l + 1 ) ) ; for ( int i = 0 ; i < l ; i ++ ) a [ i ] = b [ i ] ; for ( int i = u + 1 ; i < n ; i ++ ) a [ i ] = b [ l + ( i - ( u + 1 ) ) ] ; } int main ( ) { int a [ ] = { 5 , 4 , 3 , 12 , 14 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int l = 2 , u = 4 ; sortExceptUandL ( a , l , u , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " ▁ " ; }
Sorting all array elements except one | CPP program to sort all elements except element at index k . ; Move k - th element to end ; Sort all elements except last ; Store last element ( originally k - th ) ; Move all elements from k - th to one position ahead . ; Restore k - th element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sortExceptK ( int arr [ ] , int k , int n ) { swap ( arr [ k ] , arr [ n - 1 ] ) ; sort ( arr , arr + n - 1 ) ; int last = arr [ n - 1 ] ; for ( int i = n - 1 ; i > k ; i -- ) arr [ i ] = arr [ i - 1 ] ; arr [ k ] = last ; } int main ( ) { int a [ ] = { 10 , 4 , 11 , 7 , 6 , 20 } ; int k = 2 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; sortExceptK ( a , k , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " ▁ " ; }
Sort the linked list in the order of elements appearing in the array | Efficient CPP program to sort given list in order elements are appearing in an array ; Linked list node ; function prototype for printing the list ; Function to insert a node at the beginning of the linked list ; function to print the linked list ; Function that sort list in order of apperaing elements in an array ; Store frequencies of elements in a hash table . ; One by one put elements in lis according to their appearance in array ; Update ' frequency ' nodes with value equal to arr [ i ] ; Modify list data as element appear in an array ; Driver Code ; creating the linked list ; Function call to sort the list in order elements are apperaing in an array ; print the modified linked list
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void printList ( struct Node * ) ; void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = * head_ref ; * head_ref = new_node ; } void printList ( struct Node * head ) { while ( head != NULL ) { cout << head -> data << " ▁ - > ▁ " ; head = head -> next ; } } void sortlist ( int arr [ ] , int N , struct Node * head ) { unordered_map < int , int > hash ; struct Node * temp = head ; while ( temp ) { hash [ temp -> data ] ++ ; temp = temp -> next ; } temp = head ; for ( int i = 0 ; i < N ; i ++ ) { int frequency = hash [ arr [ i ] ] ; while ( frequency -- ) { temp -> data = arr [ i ] ; temp = temp -> next ; } } } int main ( ) { struct Node * head = NULL ; int arr [ ] = { 5 , 1 , 3 , 2 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; push ( & head , 3 ) ; push ( & head , 2 ) ; push ( & head , 5 ) ; push ( & head , 8 ) ; push ( & head , 5 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; sortlist ( arr , N , head ) ; cout << " Sorted ▁ List : " << endl ; printList ( head ) ; return 0 ; }
Maximum number of partitions that can be sorted individually to make sorted | CPP program to find Maximum number of partitions such that we can get a sorted array . ; Function to find maximum partitions . ; Find maximum in prefix arr [ 0. . i ] ; If maximum so far is equal to index , we can make a new partition ending at index i . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxPartitions ( int arr [ ] , int n ) { int ans = 0 , max_so_far = 0 ; for ( int i = 0 ; i < n ; ++ i ) { max_so_far = max ( max_so_far , arr [ i ] ) ; if ( max_so_far == i ) ans ++ ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 0 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxPartitions ( arr , n ) ; return 0 ; }
Ropes left after every removal of smallest | C ++ program to print how many Ropes are Left After Every Cut ; Function print how many Ropes are Left AfterEvery Cutting operation ; sort all Ropes in increase of there length ; min length rope ; now traverse through the given Ropes in increase order of length ; After cutting if current rope length is greater than '0' that mean all ropes to it 's right side are also greater than 0 ; now current rope become min length rope ; After first operation all ropes length become zero ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void cuttringRopes ( int Ropes [ ] , int n ) { sort ( Ropes , Ropes + n ) ; int singleOperation = 0 ; int cuttingLenght = Ropes [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( Ropes [ i ] - cuttingLenght > 0 ) { cout << ( n - i ) << " ▁ " ; cuttingLenght = Ropes [ i ] ; singleOperation ++ ; } } if ( singleOperation == 0 ) cout << "0 ▁ " ; } int main ( ) { int Ropes [ ] = { 5 , 1 , 1 , 2 , 3 , 5 } ; int n = sizeof ( Ropes ) / sizeof ( Ropes [ 0 ] ) ; cuttringRopes ( Ropes , n ) ; return 0 ; }
Rank of all elements in an array | CPP Code to find rank of elements ; Function to find rank ; Rank Vector ; Sweep through all elements in A for each element count the number of less than and equal elements separately in r and s . ; Use formula to obtain rank ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rankify ( int * A , int n ) { float R [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int r = 1 , s = 1 ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != i && A [ j ] < A [ i ] ) r += 1 ; if ( j != i && A [ j ] == A [ i ] ) s += 1 ; } R [ i ] = r + ( float ) ( s - 1 ) / ( float ) 2 ; } for ( int i = 0 ; i < n ; i ++ ) cout << R [ i ] << ' ▁ ' ; } int main ( ) { int A [ ] = { 1 , 2 , 5 , 2 , 1 , 25 , 2 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; for ( int i = 0 ; i < n ; i ++ ) cout << A [ i ] << ' ▁ ' ; cout << ' ' ; rankify ( A , n ) ; return 0 ; }
Minimum number of subtract operation to make an array decreasing | CPP program to make an array decreasing ; Function to count minimum no of operation ; Count how many times we have to subtract . ; Check an additional subtraction is required or not . ; Modify the value of arr [ i ] . ; Count total no of operation / subtraction . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int min_noOf_operation ( int arr [ ] , int n , int k ) { int noOfSubtraction ; int res = 0 ; for ( int i = 1 ; i < n ; i ++ ) { noOfSubtraction = 0 ; if ( arr [ i ] > arr [ i - 1 ] ) { noOfSubtraction = ( arr [ i ] - arr [ i - 1 ] ) / k ; if ( ( arr [ i ] - arr [ i - 1 ] ) % k != 0 ) noOfSubtraction ++ ; arr [ i ] = arr [ i ] - k * noOfSubtraction ; } res = res + noOfSubtraction ; } return res ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 5 ; cout << min_noOf_operation ( arr , N , k ) << endl ; return 0 ; }
Maximize the sum of arr [ i ] * i | CPP program to find the maximum value of i * arr [ i ] ; Sort the array ; Finding the sum of arr [ i ] * i ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += ( arr [ i ] * i ) ; return sum ; } int main ( ) { int arr [ ] = { 3 , 5 , 6 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxSum ( arr , n ) << endl ; return 0 ; }
Pairs with Difference less than K | CPP code to find count of Pairs with difference less than K . ; Function to count pairs ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int a [ ] , int n , int k ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( abs ( a [ j ] - a [ i ] ) < k ) res ++ ; return res ; } int main ( ) { int a [ ] = { 1 , 10 , 4 , 2 } ; int k = 3 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countPairs ( a , n , k ) << endl ; return 0 ; }