text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Position of rightmost common bit in two numbers | C ++ implementation to find the position of rightmost same bit ; Function to find the position of rightmost same bit in the binary representations of ' m ' and ' n ' ; Initialize loop counter ; Check whether the value ' m ' is odd ; Check whether the value ' n ' is odd ; Below ' if ' checks for both values to be odd or even ; Right shift value of m ; Right shift value of n ; When no common set is found ; Driver code
#include <iostream> NEW_LINE using namespace std ; static int posOfRightMostSameBit ( int m , int n ) { int loopCounter = 1 ; while ( m > 0 n > 0 ) { bool a = m % 2 == 1 ; bool b = n % 2 == 1 ; if ( ! ( a ^ b ) ) { return loopCounter ; } m = m >> 1 ; n = n >> 1 ; loopCounter ++ ; } return -1 ; } int main ( ) { int m = 16 , n = 7 ; cout << " Position ▁ = ▁ " << posOfRightMostSameBit ( m , n ) ; }
Check whether all the bits are set in the given range | C ++ implementation to check whether all the bits are set in the given range or not ; function to check whether all the bits are set in the given range or not ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; new number which will only have one or more set bits in the range l to r and nowhere else ; if both are equal , then all bits are set in the given range ; else all bits are not set ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; string allBitsSetInTheGivenRange ( unsigned int n , unsigned int l , unsigned int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; int new_num = n & num ; if ( num == new_num ) return " Yes " ; return " No " ; } int main ( ) { unsigned int n = 22 ; unsigned int l = 2 , r = 3 ; cout << allBitsSetInTheGivenRange ( n , l , r ) ; return 0 ; }
1 to n bit numbers with no consecutive 1 s in binary representation | Print all numbers upto n bits with no consecutive set bits . ; Let us first compute 2 raised to power n . ; loop 1 to n to check all the numbers ; A number i doesn ' t ▁ contain ▁ ▁ consecutive ▁ set ▁ bits ▁ if ▁ ▁ bitwise ▁ and ▁ of ▁ i ▁ and ▁ left ▁ ▁ shifted ▁ i ▁ do ' t contain a commons set bit . ; Driver code
#include <iostream> NEW_LINE using namespace std ; void printNonConsecutive ( int n ) { int p = ( 1 << n ) ; for ( int i = 1 ; i < p ; i ++ ) if ( ( i & ( i << 1 ) ) == 0 ) cout << i << " ▁ " ; } int main ( ) { int n = 3 ; printNonConsecutive ( n ) ; return 0 ; }
Find the n | Efficient C ++ program to find n - th palindrome ; Construct the nth binary palindrome with the given group number , aux_number and operation type ; No need to insert any bit in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Insert bit 0 in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Insert bit 1 in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Convert the number to decimal from binary ; Will return the nth binary palindrome number ; Add number of elements in all the groups , until the group of the nth number is found ; Total number of elements until this group ; Element 's offset position in the group ; Finding which bit to be placed in the middle and finding the number , which we will fill from the middle in both directions ; No need to put extra bit in middle ; We need to fill this auxiliary number in binary form the middle in both directions ; Need to Insert 0 at middle ; Need to Insert 1 at middle ; Driver code ; Function Call
#include <iostream> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; int constructNthNumber ( int group_no , int aux_num , int op ) { int INT_SIZE = 32 ; int a [ INT_SIZE ] = { 0 } ; int num = 0 , len_f ; int i = 0 ; if ( op == 2 ) { len_f = 2 * group_no ; a [ len_f - 1 ] = a [ 0 ] = 1 ; while ( aux_num ) { a [ group_no + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } else if ( op == 0 ) { len_f = 2 * group_no + 1 ; a [ len_f - 1 ] = a [ 0 ] = 1 ; a [ group_no ] = 0 ; while ( aux_num ) { a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } else { len_f = 2 * group_no + 1 ; a [ len_f - 1 ] = a [ 0 ] = 1 ; a [ group_no ] = 1 ; while ( aux_num ) { a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 ; aux_num = aux_num >> 1 ; i ++ ; } } for ( i = 0 ; i < len_f ; i ++ ) num += ( 1 << i ) * a [ i ] ; return num ; } int getNthNumber ( int n ) { int group_no = 0 , group_offset ; int count_upto_group = 0 , count_temp = 1 ; int op , aux_num ; while ( count_temp < n ) { group_no ++ ; count_upto_group = count_temp ; count_temp += 3 * ( 1 << ( group_no - 1 ) ) ; } group_offset = n - count_upto_group - 1 ; if ( ( group_offset + 1 ) <= ( 1 << ( group_no - 1 ) ) ) { op = 2 ; aux_num = group_offset ; } else { if ( ( ( group_offset + 1 ) - ( 1 << ( group_no - 1 ) ) ) % 2 ) op = 0 ; else op = 1 ; aux_num = ( ( group_offset ) - ( 1 << ( group_no - 1 ) ) ) / 2 ; } return constructNthNumber ( group_no , aux_num , op ) ; } int main ( ) { int n = 9 ; cout << getNthNumber ( n ) ; return 0 ; }
Shuffle a pack of cards and answer the query | C ++ program to find the card at given index after N shuffles ; function to find card at given index ; Answer will be reversal of N bits from MSB ; Calculating the reverse binary representation ; Printing the result ; driver code ; No . of Shuffle Steps ; Key position
#include <bits/stdc++.h> NEW_LINE using namespace std ; void shuffle ( int N , int key ) { unsigned int NO_OF_BITS = N ; unsigned int reverse_num = 0 , temp ; for ( int i = 0 ; i < NO_OF_BITS ; i ++ ) { temp = ( key & ( 1 << i ) ) ; if ( temp ) reverse_num |= ( 1 << ( ( NO_OF_BITS - 1 ) - i ) ) ; } cout << reverse_num ; } int main ( ) { int N = 3 ; unsigned int key = 3 ; shuffle ( N , key ) ; return 0 ; }
Sum of numbers with exactly 2 bits set | CPP program to find sum of numbers upto n whose 2 bits are set ; To count number of set bits ; To calculate sum of numbers ; To count sum of number whose 2 bit are set ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int n ) { int count = 0 ; while ( n ) { n &= ( n - 1 ) ; count ++ ; } return count ; } int findSum ( int n ) { int sum = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( countSetBits ( i ) == 2 ) sum += i ; return sum ; } int main ( ) { int n = 10 ; cout << findSum ( n ) ; return 0 ; }
Toggle the last m bits | C ++ implementation to toggle the last m bits ; function to toggle the last m bits ; calculating a number ' num ' having ' m ' bits and all are set . ; toggle the last m bits and return the number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int toggleLastMBits ( unsigned int n , unsigned int m ) { unsigned int num = ( 1 << m ) - 1 ; return ( n ^ num ) ; } int main ( ) { unsigned int n = 107 ; unsigned int m = 4 ; cout << toggleLastMBits ( n , m ) ; return 0 ; }
Set the rightmost unset bit | C ++ implementation to set the rightmost unset bit ; function to find the position of rightmost set bit ; if n = 0 , return 1 ; if all bits of ' n ' are set ; position of rightmost unset bit in ' n ' passing ~ n as argument ; set the bit at position ' pos ' ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getPosOfRightmostSetBit ( int n ) { return log2 ( n & - n ) + 1 ; } int setRightmostUnsetBit ( int n ) { if ( n == 0 ) return 1 ; if ( ( n & ( n + 1 ) ) == 0 ) return n ; int pos = getPosOfRightmostSetBit ( ~ n ) ; return ( ( 1 << ( pos - 1 ) ) n ) ; } int main ( ) { int n = 21 ; cout << setRightmostUnsetBit ( n ) ; return 0 ; }
Previous smaller integer having one less number of set bits | C ++ implementation to find the previous smaller integer with one less number of set bits ; function to find the position of rightmost set bit . ; function to find the previous smaller integer ; position of rightmost set bit of n ; turn off or unset the bit at position ' pos ' ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getFirstSetBitPos ( int n ) { return log2 ( n & - n ) + 1 ; } int previousSmallerInteger ( int n ) { int pos = getFirstSetBitPos ( n ) ; return ( n & ~ ( 1 << ( pos - 1 ) ) ) ; } int main ( ) { int n = 25 ; cout << previousSmallerInteger ( n ) ; return 0 ; }
Convert a binary number to octal | C ++ implementation to convert a binary number to octal number ; function to create map between binary number and its equivalent octal ; Function to find octal equivalent of binary ; length of string before ' . ' ; add min 0 's in the beginning to make left substring length divisible by 3 ; if decimal point exists ; length of string after ' . ' ; add min 0 's in the end to make right substring length divisible by 3 ; create map between binary and its equivalent octal code ; one by one extract from left , substring of size 3 and add its octal code ; if ' . ' is encountered add it to result ; required octal number ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; void createMap ( unordered_map < string , char > * um ) { ( * um ) [ "000" ] = '0' ; ( * um ) [ "001" ] = '1' ; ( * um ) [ "010" ] = '2' ; ( * um ) [ "011" ] = '3' ; ( * um ) [ "100" ] = '4' ; ( * um ) [ "101" ] = '5' ; ( * um ) [ "110" ] = '6' ; ( * um ) [ "111" ] = '7' ; } string convertBinToOct ( string bin ) { int l = bin . size ( ) ; int t = bin . find_first_of ( ' . ' ) ; int len_left = t != -1 ? t : l ; for ( int i = 1 ; i <= ( 3 - len_left % 3 ) % 3 ; i ++ ) bin = '0' + bin ; if ( t != -1 ) { int len_right = l - len_left - 1 ; for ( int i = 1 ; i <= ( 3 - len_right % 3 ) % 3 ; i ++ ) bin = bin + '0' ; } unordered_map < string , char > bin_oct_map ; createMap ( & bin_oct_map ) ; int i = 0 ; string octal = " " ; while ( 1 ) { octal += bin_oct_map [ bin . substr ( i , 3 ) ] ; i += 3 ; if ( i == bin . size ( ) ) break ; if ( bin . at ( i ) == ' . ' ) { octal += ' . ' ; i ++ ; } } return octal ; } int main ( ) { string bin = "1111001010010100001.010110110011011" ; cout << " Octal ▁ number ▁ = ▁ " << convertBinToOct ( bin ) ; return 0 ; }
Check if all bits of a number are set | C ++ implementation to check whether every digit in the binary representation of the given number is set or not ; function to check if all the bits are set or not in the binary representation of ' n ' ; all bits are not set ; loop till n becomes '0' ; if the last bit is not set ; right shift ' n ' by 1 ; all bits are set ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; string areAllBitsSet ( int n ) { if ( n == 0 ) return " No " ; while ( n > 0 ) { if ( ( n & 1 ) == 0 ) return " No " ; n = n >> 1 ; } return " Yes " ; } int main ( ) { int n = 7 ; cout << areAllBitsSet ( n ) ; return 0 ; }
Check if all bits of a number are set | C ++ implementation to check whether every digit in the binary representation of the given number is set or not ; function to check if all the bits are set or not in the binary representation of ' n ' ; all bits are not set ; if true , then all bits are set ; else all bits are not set ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; string areAllBitsSet ( int n ) { if ( n == 0 ) return " No " ; if ( ( ( n + 1 ) & n ) == 0 ) return " Yes " ; return " No " ; } int main ( ) { int n = 7 ; cout << areAllBitsSet ( n ) ; return 0 ; }
Next greater integer having one more number of set bits | C ++ implementation to find the next greater integer with one more number of set bits ; function to find the position of rightmost set bit . Returns - 1 if there are no set bits ; function to find the next greater integer ; position of rightmost unset bit of n by passing ~ n as argument ; if n consists of unset bits , then set the rightmost unset bit ; n does not consists of unset bits ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getFirstSetBitPos ( int n ) { return ( log2 ( n & - n ) + 1 ) - 1 ; } int nextGreaterWithOneMoreSetBit ( int n ) { int pos = getFirstSetBitPos ( ~ n ) ; if ( pos > -1 ) return ( 1 << pos ) | n ; return ( ( n << 1 ) + 1 ) ; } int main ( ) { int n = 10 ; cout << " Next ▁ greater ▁ integer ▁ = ▁ " << nextGreaterWithOneMoreSetBit ( n ) ; return 0 ; }
Toggle all the bits of a number except k | C ++ program to toggle all bits except kth bit ; Returns a number with all bit toggled in n except k - th bit ; 1 ) Toggle k - th bit by doing n ^ ( 1 << k ) 2 ) Toggle all bits of the modified number ; Driver code
#include <iostream> NEW_LINE using namespace std ; unsigned int toggleAllExceptK ( unsigned int n , unsigned int k ) { return ~ ( n ^ ( 1 << k ) ) ; } int main ( ) { unsigned int n = 4294967295 ; unsigned int k = 0 ; cout << toggleAllExceptK ( n , k ) ; return 0 ; }
Count numbers whose sum with x is equal to XOR with x | C ++ program to count numbers whose bitwise XOR and sum with x are equal ; Function to find total 0 bit in a number ; Function to find Count of non - negative numbers less than or equal to x , whose bitwise XOR and SUM with x are equal . ; count number of zero bit in x ; power of 2 to count ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long CountZeroBit ( long x ) { unsigned int count = 0 ; while ( x ) { if ( ! ( x & 1LL ) ) count ++ ; x >>= 1LL ; } return count ; } long CountXORandSumEqual ( long x ) { long count = CountZeroBit ( x ) ; return ( 1LL << count ) ; } int main ( ) { long x = 10 ; cout << CountXORandSumEqual ( x ) ; return 0 ; }
Find missing number in another array which is shuffled copy | C ++ implementation to find the missing number in shuffled array C ++ implementation to find the missing number in shuffled array ; Returns the missing number Size of arr2 [ ] is n - 1 ; Missing number ' mnum ' ; 1 st array is of size ' n ' ; 2 nd array is of size ' n ▁ - ▁ 1' ; Required missing number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int missingNumber ( int arr1 [ ] , int arr2 [ ] , int n ) { int mnum = 0 ; for ( int i = 0 ; i < n ; i ++ ) mnum = mnum ^ arr1 [ i ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) mnum = mnum ^ arr2 [ i ] ; return mnum ; } int main ( ) { int arr1 [ ] = { 4 , 8 , 1 , 3 , 7 } ; int arr2 [ ] = { 7 , 4 , 3 , 1 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << " Missing ▁ number ▁ = ▁ " << missingNumber ( arr1 , arr2 , n ) ; return 0 ; }
Find Duplicates of array using bit array | C ++ program to print all Duplicates in array ; A class to represent an array of bits using array of integers ; Constructor ; Divide by 32. To store n bits , we need n / 32 + 1 integers ( Assuming int is stored using 32 bits ) ; Get value of a bit at given position ; Divide by 32 to find position of integer . ; Now find bit number in arr [ index ] ; Find value of given bit number in arr [ index ] ; Sets a bit at given position ; Find index of bit position ; Set bit number in arr [ index ] ; Main function to print all Duplicates ; create a bit with 32000 bits ; Traverse array elements ; Index in bit array ; If num is already present in bit array ; Else insert num ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class BitArray { int * arr ; public : BitArray ( ) { } BitArray ( int n ) { arr = new int [ ( n >> 5 ) + 1 ] ; } bool get ( int pos ) { int index = ( pos >> 5 ) ; int bitNo = ( pos & 0x1F ) ; return ( arr [ index ] & ( 1 << bitNo ) ) != 0 ; } void set ( int pos ) { int index = ( pos >> 5 ) ; int bitNo = ( pos & 0x1F ) ; arr [ index ] |= ( 1 << bitNo ) ; } void checkDuplicates ( int arr [ ] , int n ) { BitArray ba = BitArray ( 320000 ) ; for ( int i = 0 ; i < n ; i ++ ) { int num = arr [ i ] ; if ( ba . get ( num ) ) cout << num << " ▁ " ; else ba . set ( num ) ; } } } ; int main ( ) { int arr [ ] = { 1 , 5 , 1 , 10 , 12 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; BitArray obj = BitArray ( ) ; obj . checkDuplicates ( arr , n ) ; return 0 ; }
Change bits to make specific OR value | C ++ program to change least bits to get desired OR value ; Returns max of three numbers ; Returns count of bits in N ; Returns bit at ' pos ' position ; Utility method to toggle bit at ' pos ' position ; method returns minimum number of bit flip to get T as OR value of A and B ; Loop over maximum number of bits among A , B and T ; T 's bit is set, try to toggle bit of B, if not already ; if A 's bit is set, flip that ; if B 's bit is set, flip that ; if K is less than 0 then we can make A | B == T ; Loop over bits one more time to minimise A further ; If both bit are set , then Unset A 's bit to minimise it ; If A ' s ▁ bit ▁ is ▁ 1 ▁ and ▁ B ' s bit is 0 , toggle both ; Output changed value of A and B ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b , int c ) { return max ( a , max ( b , c ) ) ; } int bitCount ( int N ) { int cnt = 0 ; while ( N ) { cnt ++ ; N >>= 1 ; } return cnt ; } bool at_position ( int num , int pos ) { bool bit = num & ( 1 << pos ) ; return bit ; } void toggle ( int & num , int pos ) { num ^= ( 1 << pos ) ; } void minChangeToReachTaregetOR ( int A , int B , int K , int T ) { int maxlen = max ( bitCount ( A ) , bitCount ( B ) , bitCount ( T ) ) ; for ( int i = maxlen - 1 ; i >= 0 ; i -- ) { bool bitA = at_position ( A , i ) ; bool bitB = at_position ( B , i ) ; bool bitT = at_position ( T , i ) ; if ( bitT ) { if ( ! bitA && ! bitB ) { toggle ( B , i ) ; K -- ; } } else { if ( bitA ) { toggle ( A , i ) ; K -- ; } if ( bitB ) { toggle ( B , i ) ; K -- ; } } } if ( K < 0 ) { cout << " Not ▁ possible STRNEWLINE " ; return ; } for ( int i = maxlen - 1 ; K > 0 && i >= 0 ; -- i ) { bool bitA = at_position ( A , i ) ; bool bitB = at_position ( B , i ) ; bool bitT = at_position ( T , i ) ; if ( bitT ) { if ( bitA && bitB ) { toggle ( A , i ) ; K -- ; } } if ( bitA && ! bitB && K >= 2 ) { toggle ( A , i ) ; toggle ( B , i ) ; K -= 2 ; } } cout << A << " ▁ " << B << endl ; } int main ( ) { int A = 175 , B = 66 , K = 5 , T = 100 ; minChangeToReachTaregetOR ( A , B , K , T ) ; return 0 ; }
Count smaller values whose XOR with x is greater than x | C ++ program to find count of values whose XOR with x is greater than x and values are smaller than x ; Initialize result ; Traversing through all bits of x ; If current last bit of x is set then increment count by n . Here n is a power of 2 corresponding to position of bit ; Simultaneously calculate the 2 ^ n ; Replace x with x / 2 ; ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countValues ( int x ) { int count = 0 , n = 1 ; while ( x != 0 ) { if ( x % 2 == 0 ) count += n ; n *= 2 ; x /= 2 ; } return count ; } int main ( ) { int x = 10 ; cout << countValues ( x ) ; return 0 ; }
Construct an array from XOR of all elements of array except element at same index | C ++ program to construct array from XOR of elements of given array ; function to construct new array ; calculate xor of array ; update array ; Driver code ; print result
#include <bits/stdc++.h> NEW_LINE using namespace std ; void constructXOR ( int A [ ] , int n ) { int XOR = 0 ; for ( int i = 0 ; i < n ; i ++ ) XOR ^= A [ i ] ; for ( int i = 0 ; i < n ; i ++ ) A [ i ] = XOR ^ A [ i ] ; } int main ( ) { int A [ ] = { 2 , 4 , 1 , 3 , 5 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; constructXOR ( A , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << A [ i ] << " ▁ " ; return 0 ; }
Count all pairs of an array which differ in K bits | C ++ program to count all pairs with bit difference as k ; Utility function to count total ones in a number ; Function to count pairs of K different bits ; long long ans = 0 ; initialize final answer ; Check for K differ bit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bitCount ( int n ) { int count = 0 ; while ( n ) { if ( n & 1 ) ++ count ; n >>= 1 ; } return count ; } long long countPairsWithKDiff ( int arr [ ] , int n , int k ) { for ( int i = 0 ; i < n - 1 ; ++ i ) { for ( int j = i + 1 ; j < n ; ++ j ) { int xoredNum = arr [ i ] ^ arr [ j ] ; if ( k == bitCount ( xoredNum ) ) ++ ans ; } } return ans ; } int main ( ) { int k = 2 ; int arr [ ] = { 2 , 4 , 1 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Total ▁ pairs ▁ for ▁ k ▁ = ▁ " << k << " ▁ are ▁ " << countPairsWithKDiff ( arr , n , k ) << " STRNEWLINE " ; return 0 ; }
Count all pairs of an array which differ in K bits | Below is C ++ approach of finding total k bit difference pairs ; Function to calculate K bit different pairs in array ; Get the maximum value among all array elemensts ; Set the count array to 0 , count [ ] stores the total frequency of array elements ; Initialize result ; For 0 bit answer will be total count of same number ; if count [ i ] is 0 , skip the next loop as it will not contribute the answer ; Update answer if k differ bit found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long kBitDifferencePairs ( int arr [ ] , int n , int k ) { int MAX = * max_element ( arr , arr + n ) ; long long count [ MAX + 1 ] ; memset ( count , 0 , sizeof ( count ) ) ; for ( int i = 0 ; i < n ; ++ i ) ++ count [ arr [ i ] ] ; long long ans = 0 ; if ( k == 0 ) { for ( int i = 0 ; i <= MAX ; ++ i ) ans += ( count [ i ] * ( count [ i ] - 1 ) ) / 2 ; return ans ; } for ( int i = 0 ; i <= MAX ; ++ i ) { if ( ! count [ i ] ) continue ; for ( int j = i + 1 ; j <= MAX ; ++ j ) { if ( __builtin_popcount ( i ^ j ) == k ) ans += count [ i ] * count [ j ] ; } } return ans ; } int main ( ) { int k = 2 ; int arr [ ] = { 2 , 4 , 1 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Total ▁ pairs ▁ for ▁ k ▁ = ▁ " << k << " ▁ are ▁ = ▁ " << kBitDifferencePairs ( arr , n , k ) << " STRNEWLINE " ; k = 3 ; cout << " Total ▁ pairs ▁ for ▁ k ▁ = ▁ " << k << " ▁ are ▁ = ▁ " << kBitDifferencePairs ( arr , n , k ) ; return 0 ; }
Ways to represent a number as a sum of 1 ' s ▁ and ▁ 2' s | C ++ program to find number of ways to representing a number as a sum of 1 ' s ▁ and ▁ 2' s ; Function to multiply matrix . ; Power function in log n ; function that returns ( n + 1 ) th Fibonacci number Or number of ways to represent n as sum of 1 ' s ▁ ▁ 2' s ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void multiply ( int F [ 2 ] [ 2 ] , int M [ 2 ] [ 2 ] ) { int x = F [ 0 ] [ 0 ] * M [ 0 ] [ 0 ] + F [ 0 ] [ 1 ] * M [ 1 ] [ 0 ] ; int y = F [ 0 ] [ 0 ] * M [ 0 ] [ 1 ] + F [ 0 ] [ 1 ] * M [ 1 ] [ 1 ] ; int z = F [ 1 ] [ 0 ] * M [ 0 ] [ 0 ] + F [ 1 ] [ 1 ] * M [ 1 ] [ 0 ] ; int w = F [ 1 ] [ 0 ] * M [ 0 ] [ 1 ] + F [ 1 ] [ 1 ] * M [ 1 ] [ 1 ] ; F [ 0 ] [ 0 ] = x ; F [ 0 ] [ 1 ] = y ; F [ 1 ] [ 0 ] = z ; F [ 1 ] [ 1 ] = w ; } void power ( int F [ 2 ] [ 2 ] , int n ) { if ( n == 0 n == 1 ) return ; int M [ 2 ] [ 2 ] = { { 1 , 1 } , { 1 , 0 } } ; power ( F , n / 2 ) ; multiply ( F , F ) ; if ( n % 2 != 0 ) multiply ( F , M ) ; } int countWays ( int n ) { int F [ 2 ] [ 2 ] = { { 1 , 1 } , { 1 , 0 } } ; if ( n == 0 ) return 0 ; power ( F , n ) ; return F [ 0 ] [ 0 ] ; } int main ( ) { int n = 5 ; cout << countWays ( n ) << endl ; return 0 ; }
Multiplication of two numbers with shift operator | CPP program to find multiplication of two number without use of multiplication operator ; Function for multiplication ; check for set bit and left shift n , count times ; increment of place value ( count ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int multiply ( int n , int m ) { int ans = 0 , count = 0 ; while ( m ) { if ( m % 2 == 1 ) ans += n << count ; count ++ ; m /= 2 ; } return ans ; } int main ( ) { int n = 20 , m = 13 ; cout << multiply ( n , m ) ; return 0 ; }
Compare two integers without using any Comparison operator | C ++ program to compare two integers without any comparison operator . ; function return true if A ^ B > 0 else false ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool EqualNumber ( int A , int B ) { return ( A ^ B ) ; } int main ( ) { int A = 5 , B = 6 ; cout << ! EqualNumber ( A , B ) << endl ; return 0 ; }
Check if bits of a number has count of consecutive set bits in increasing order | C ++ program to find if bit - pattern of a number has increasing value of continuous - 1 or not . ; Returns true if n has increasing count of continuous - 1 else false ; store the bit - pattern of n into bit bitset - bp ; set prev_count = 0 and curr_count = 0. ; increment current count of continuous - 1 ; traverse all continuous - 0 ; check prev_count and curr_count on encounter of first zero after continuous - 1 s ; check for last sequence of continuous - 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findContinuous1 ( int n ) { const int bits = 8 * sizeof ( int ) ; string bp = bitset < bits > ( n ) . to_string ( ) ; int prev_count = 0 , curr_count = 0 ; int i = 0 ; while ( i < bits ) { if ( bp [ i ] == '1' ) { curr_count ++ ; i ++ ; } else if ( bp [ i - 1 ] == '0' ) { i ++ ; curr_count = 0 ; continue ; } else { if ( curr_count < prev_count ) return 0 ; i ++ ; prev_count = curr_count ; curr_count = 0 ; } } if ( prev_count > curr_count && ( curr_count != 0 ) ) return 0 ; return 1 ; } int main ( ) { int n = 179 ; if ( findContinuous1 ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check if bits of a number has count of consecutive set bits in increasing order | C ++ program to check if counts of consecutive 1 s are increasing order . ; Returns true if n has counts of consecutive 1 's are increasing order. ; Initialize previous count ; We traverse bits from right to left and check if counts are decreasing order . ; Ignore 0 s until we reach a set bit . ; Count current set bits ; Compare current with previous and update previous . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool areSetBitsIncreasing ( int n ) { int prev_count = INT_MAX ; while ( n > 0 ) { while ( n > 0 && n % 2 == 0 ) n = n / 2 ; int curr_count = 1 ; while ( n > 0 && n % 2 == 1 ) { n = n / 2 ; curr_count ++ ; } if ( curr_count >= prev_count ) return false ; prev_count = curr_count ; } return true ; } int main ( ) { int n = 10 ; if ( areSetBitsIncreasing ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check if a number has bits in alternate pattern | Set 1 | C ++ program to find if a number has alternate bit pattern ; Returns true if n has alternate bit pattern else false ; Store last bit ; Traverse through remaining bits ; If current bit is same as previous ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findPattern ( int n ) { int prev = n % 2 ; n = n / 2 ; while ( n > 0 ) { int curr = n % 2 ; if ( curr == prev ) return false ; prev = curr ; n = n / 2 ; } return true ; } int main ( ) { int n = 10 ; if ( findPattern ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
XOR counts of 0 s and 1 s in binary representation | C ++ program to find XOR of counts 0 s and 1 s in binary representation of n . ; Returns XOR of counts 0 s and 1 s in binary representation of n . ; calculating count of zeros and ones ; Driver Program
#include <iostream> NEW_LINE using namespace std ; int countXOR ( int n ) { int count0 = 0 , count1 = 0 ; while ( n ) { ( n % 2 == 0 ) ? count0 ++ : count1 ++ ; n /= 2 ; } return ( count0 ^ count1 ) ; } int main ( ) { int n = 31 ; cout << countXOR ( n ) ; return 0 ; }
Count all pairs with given XOR | C ++ program to Count all pair with given XOR value x ; Returns count of pairs in arr [ 0. . n - 1 ] with XOR value equals to x . ; create empty map that stores counts of individual elements of array . ; If there exist an element in map m with XOR equals to x ^ arr [ i ] , that means there exist an element such that the XOR of element with arr [ i ] is equal to x , then increment count . ; Increment count of current element ; return total count of pairs with XOR equal to x ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int xorPairCount ( int arr [ ] , int n , int x ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) { int curr_xor = x ^ arr [ i ] ; if ( m . find ( curr_xor ) != m . end ( ) ) result += m [ curr_xor ] ; m [ arr [ i ] ] ++ ; } return result ; } int main ( ) { int arr [ ] = { 2 , 5 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 0 ; cout << " Count ▁ of ▁ pairs ▁ with ▁ given ▁ XOR ▁ = ▁ " << xorPairCount ( arr , n , x ) ; return 0 ; }
Bitwise and ( or & ) of a range | An efficient C ++ program to find bit - wise & of all numbers from x to y . ; Find position of MSB in n . For example if n = 17 , then position of MSB is 4. If n = 7 , value of MSB is 3 ; Function to find Bit - wise & of all numbers from x to y . ; ll res = 0 ; Initialize result ; Find positions of MSB in x and y ; If positions are not same , return ; Add 2 ^ msb_p1 to result ; subtract 2 ^ msb_p1 from x and y . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long int ll ; int msbPos ( ll n ) { int msb_p = -1 ; while ( n ) { n = n >> 1 ; msb_p ++ ; } return msb_p ; } ll andOperator ( ll x , ll y ) { while ( x && y ) { int msb_p1 = msbPos ( x ) ; int msb_p2 = msbPos ( y ) ; if ( msb_p1 != msb_p2 ) break ; ll msb_val = ( 1 << msb_p1 ) ; res = res + msb_val ; x = x - msb_val ; y = y - msb_val ; } return res ; } int main ( ) { ll x = 10 , y = 15 ; cout << andOperator ( x , y ) ; return 0 ; }
Multiply a number with 10 without using multiplication operator | C ++ program to multiply a number with 10 using bitwise operators ; Function to find multiplication of n with 10 without using multiplication operator ; Driver program to run the case
#include <bits/stdc++.h> NEW_LINE using namespace std ; int multiplyTen ( int n ) { return ( n << 1 ) + ( n << 3 ) ; } int main ( ) { int n = 50 ; cout << multiplyTen ( n ) ; return 0 ; }
Equal Sum and XOR | C ++ program to print count of values such that n + i = n ^ i ; function to count number of values less than equal to n that satisfy the given condition ; Traverse all numbers from 0 to n and increment result only when given condition is satisfied . ; Driver program
#include <iostream> NEW_LINE using namespace std ; int countValues ( int n ) { int countV = 0 ; for ( int i = 0 ; i <= n ; i ++ ) if ( ( n + i ) == ( n ^ i ) ) countV ++ ; return countV ; } int main ( ) { int n = 12 ; cout << countValues ( n ) ; return 0 ; }
Equal Sum and XOR | c ++ program to print count of values such that n + i = n ^ i ; function to count number of values less than equal to n that satisfy the given condition ; unset_bits keeps track of count of un - set bits in binary representation of n ; Return 2 ^ unset_bits ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countValues ( int n ) { int unset_bits = 0 ; while ( n ) { if ( ( n & 1 ) == 0 ) unset_bits ++ ; n = n >> 1 ; } return 1 << unset_bits ; } int main ( ) { int n = 12 ; cout << countValues ( n ) ; return 0 ; }
Find profession in a special family | C ++ program to find profession of a person at given level and position . ; Returns ' e ' if profession of node at given level and position is engineer . Else doctor . The function assumes that given position and level have valid values . ; Base case ; Recursively find parent 's profession. If parent is a Doctor, this node will be a Doctor if it is at odd position and an engineer if at even position ; If parent is an engineer , then current node will be an engineer if at add position and doctor if even position . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char findProffesion ( int level , int pos ) { if ( level == 1 ) return ' e ' ; if ( findProffesion ( level - 1 , ( pos + 1 ) / 2 ) == ' d ' ) return ( pos % 2 ) ? ' d ' : ' e ' ; return ( pos % 2 ) ? ' e ' : ' d ' ; } int main ( void ) { int level = 4 , pos = 2 ; ( findProffesion ( level , pos ) == ' e ' ) ? cout << " Engineer " : cout << " Doctor " ; return 0 ; }
Print first n numbers with exactly two set bits | C ++ program to print first n numbers with exactly two set bits ; Prints first n numbers with two set bits ; Initialize higher of two sets bits ; Keep reducing n for every number with two set bits . ; Consider all lower set bits for current higher set bit ; Print current number ; If we have found n numbers ; Consider next lower bit for current higher bit . ; Increment higher set bit ; Driver code
#include <iostream> NEW_LINE using namespace std ; void printTwoSetBitNums ( int n ) { int x = 1 ; while ( n > 0 ) { int y = 0 ; while ( y < x ) { cout << ( 1 << x ) + ( 1 << y ) << " ▁ " ; n -- ; if ( n == 0 ) return ; y ++ ; } x ++ ; } } int main ( ) { printTwoSetBitNums ( 4 ) ; return 0 ; }
Generate 0 and 1 with 25 % and 75 % probability | Program to print 1 with 75 % probability and 0 with 25 % probability ; Random Function to that returns 0 or 1 with equal probability ; rand ( ) function will generate odd or even number with equal probability . If rand ( ) generates odd number , the function will return 1 else it will return 0. ; Random Function to that returns 1 with 75 % probability and 0 with 25 % probability using Bitwise OR ; Driver code to test above functions ; Initialize random number generator
#include <iostream> NEW_LINE using namespace std ; int rand50 ( ) { return rand ( ) & 1 ; } bool rand75 ( ) { return rand50 ( ) | rand50 ( ) ; } int main ( ) { srand ( time ( NULL ) ) ; for ( int i = 0 ; i < 50 ; i ++ ) cout << rand75 ( ) ; return 0 ; }
Find even occurring elements in an array of limited range | C ++ Program to find the even occurring elements in given array ; Function to find the even occurring elements in given array ; do for each element of array ; left - shift 1 by value of current element ; Toggle the bit everytime element gets repeated ; Traverse array again and use _xor to find even occurring elements ; left - shift 1 by value of current element ; Each 0 in _xor represents an even occurrence ; print the even occurring numbers ; set bit as 1 to avoid printing duplicates ; Driver code
#include <iostream> NEW_LINE using namespace std ; void printRepeatingEven ( int arr [ ] , int n ) { long long _xor = 0L ; long long pos ; for ( int i = 0 ; i < n ; ++ i ) { pos = 1 << arr [ i ] ; _xor ^= pos ; } for ( int i = 0 ; i < n ; ++ i ) { pos = 1 << arr [ i ] ; if ( ! ( pos & _xor ) ) { cout << arr [ i ] << " ▁ " ; _xor ^= pos ; } } } int main ( ) { int arr [ ] = { 9 , 12 , 23 , 10 , 12 , 12 , 15 , 23 , 14 , 12 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printRepeatingEven ( arr , n ) ; return 0 ; }
Cyclic Redundancy Check and Modulo | Returns XOR of ' a ' and ' b ' ( both of same length ) ; Initialize result ; Traverse all bits , if bits are same , then XOR is 0 , else 1 ; Performs Modulo - 2 division ; Number of bits to be XORed at a time . ; Slicing the divident to appropriate length for particular step ; Replace the divident by the result of XOR and pull 1 bit down ; If leftmost bit is '0' . If the leftmost bit of the dividend ( or the part used in each step ) is 0 , the step cannot use the regular divisor ; we need to use an all - 0 s divisor . ; Increment pick to move further ; For the last n bits , we have to carry it out normally as increased value of pick will cause Index Out of Bounds . ; Function used at the sender side to encode data by appending remainder of modular division at the end of data . ; Appends n - 1 zeroes at end of data ; Append remainder in the original data ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string xor1 ( string a , string b ) { string result = " " ; int n = b . length ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] == b [ i ] ) result += "0" ; else result += "1" ; } return result ; } string mod2div ( string divident , string divisor ) { int pick = divisor . length ( ) ; string tmp = divident . substr ( 0 , pick ) ; int n = divident . length ( ) ; while ( pick < n ) { if ( tmp [ 0 ] == '1' ) tmp = xor1 ( divisor , tmp ) + divident [ pick ] ; else tmp = xor1 ( std :: string ( pick , '0' ) , tmp ) + divident [ pick ] ; pick += 1 ; } if ( tmp [ 0 ] == '1' ) tmp = xor1 ( divisor , tmp ) ; else tmp = xor1 ( std :: string ( pick , '0' ) , tmp ) ; return tmp ; } void encodeData ( string data , string key ) { int l_key = key . length ( ) ; string appended_data = ( data + std :: string ( l_key - 1 , '0' ) ) ; string remainder = mod2div ( appended_data , key ) ; string codeword = data + remainder ; cout << " Remainder ▁ : ▁ " << remainder << " STRNEWLINE " ; cout << " Encoded ▁ Data ▁ ( Data ▁ + ▁ Remainder ) ▁ : " << codeword << " STRNEWLINE " ; } int main ( ) { string data = "100100" ; string key = "1101" ; encodeData ( data , key ) ; return 0 ; }
Check if a number is Bleak | A simple C ++ program to check Bleak Number ; Function to get no of set bits in binary representation of passed binary no . ; Returns true if n is Bleak ; Check for all numbers ' x ' smaller than n . If x + countSetBits ( x ) becomes n , then n can 't be Bleak ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSetBits ( int x ) { unsigned int count = 0 ; while ( x ) { x &= ( x - 1 ) ; count ++ ; } return count ; } bool isBleak ( int n ) { for ( int x = 1 ; x < n ; x ++ ) if ( x + countSetBits ( x ) == n ) return false ; return true ; } int main ( ) { isBleak ( 3 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; isBleak ( 4 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; }
Check if a number is Bleak | C ++ program to demonstrate __builtin_popcount ( )
#include <iostream> NEW_LINE using namespace std ; int main ( ) { cout << __builtin_popcount ( 4 ) << endl ; cout << __builtin_popcount ( 15 ) ; return 0 ; }
Find the maximum subset XOR of a given set | C ++ program to find maximum XOR subset ; Number of bits to represent int ; Function to return maximum XOR subset in set [ ] ; Initialize index of chosen elements ; Traverse through all bits of integer starting from the most significant bit ( MSB ) ; Initialize index of maximum element and the maximum element ; If i 'th bit of set[j] is set and set[j] is greater than max so far. ; If there was no element with i 'th bit set, move to smaller i ; Put maximum element with i ' th ▁ bit ▁ set ▁ ▁ at ▁ index ▁ ' index ' ; Update maxInd and increment index ; Do XOR of set [ maxIndex ] with all numbers having i 'th bit as set. ; XOR set [ maxInd ] those numbers which have the i 'th bit set ; Increment index of chosen elements ; Final result is XOR of all elements ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define INT_BITS 32 NEW_LINE int maxSubarrayXOR ( int set [ ] , int n ) { int index = 0 ; for ( int i = INT_BITS - 1 ; i >= 0 ; i -- ) { int maxInd = index ; int maxEle = INT_MIN ; for ( int j = index ; j < n ; j ++ ) { if ( ( set [ j ] & ( 1 << i ) ) != 0 && set [ j ] > maxEle ) maxEle = set [ j ] , maxInd = j ; } if ( maxEle == INT_MIN ) continue ; swap ( set [ index ] , set [ maxInd ] ) ; maxInd = index ; for ( int j = 0 ; j < n ; j ++ ) { if ( j != maxInd && ( set [ j ] & ( 1 << i ) ) != 0 ) set [ j ] = set [ j ] ^ set [ maxInd ] ; } index ++ ; } int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) res ^= set [ i ] ; return res ; } int main ( ) { int set [ ] = { 9 , 8 , 5 } ; int n = sizeof ( set ) / sizeof ( set [ 0 ] ) ; cout << " Max ▁ subset ▁ XOR ▁ is ▁ " ; cout << maxSubarrayXOR ( set , n ) ; return 0 ; }
Given a set , find XOR of the XOR 's of all subsets. | C ++ program to find XOR of XOR 's of all subsets ; Returns XOR of all XOR 's of given subset ; XOR is 1 only when n is 1 , else 0 ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findXOR ( int Set [ ] , int n ) { if ( n == 1 ) return Set [ 0 ] ; else return 0 ; } int main ( ) { int Set [ ] = { 1 , 2 , 3 } ; int n = sizeof ( Set ) / sizeof ( Set [ 0 ] ) ; cout << " XOR ▁ of ▁ XOR ' s ▁ of ▁ all ▁ subsets ▁ is ▁ " << findXOR ( Set , n ) ; return 0 ; }
Find XOR of two number without using XOR operator | C ++ program to find XOR without using ^ ; Returns XOR of x and y ; Assuming 32 - bit Integer ; Find current bits in x and y ; If both are 1 then 0 else xor is same as OR ; Update result ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int myXOR ( int x , int y ) { for ( int i = 31 ; i >= 0 ; i -- ) { bool b1 = x & ( 1 << i ) ; bool b2 = y & ( 1 << i ) ; bool xoredBit = ( b1 & b2 ) ? 0 : ( b1 b2 ) ; res <<= 1 ; res |= xoredBit ; } return res ; } int main ( ) { int x = 3 , y = 5 ; cout << " XOR ▁ is ▁ " << myXOR ( x , y ) ; return 0 ; }
Find XOR of two number without using XOR operator | C ++ program to find XOR without using ^ ; Returns XOR of x and y ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int myXOR ( int x , int y ) { return ( x y ) & ( ~ x ~ y ) ; } int main ( ) { int x = 3 , y = 5 ; cout << " XOR ▁ is ▁ " << myXOR ( x , y ) ; return 0 ; }
Operators in C | Set 2 ( Relational and Logical Operators ) | C ++ program to demonstrate working of logical operators ; greater than example ; greater than equal to ; less than example ; lesser than equal to ; equal to ; not equal to
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int a = 10 , b = 4 ; if ( a > b ) cout << " a ▁ is ▁ greater ▁ than ▁ b STRNEWLINE " ; else cout << " a ▁ is ▁ less ▁ than ▁ or ▁ equal ▁ to ▁ b STRNEWLINE " ; if ( a >= b ) cout << " a ▁ is ▁ greater ▁ than ▁ or ▁ equal ▁ to ▁ b STRNEWLINE " ; else cout << " a ▁ is ▁ lesser ▁ than ▁ b STRNEWLINE " ; if ( a < b ) cout << " a ▁ is ▁ less ▁ than ▁ b STRNEWLINE " ; else cout << " a ▁ is ▁ greater ▁ than ▁ or ▁ equal ▁ to ▁ b STRNEWLINE " ; if ( a <= b ) cout << " a ▁ is ▁ lesser ▁ than ▁ or ▁ equal ▁ to ▁ b STRNEWLINE " ; else cout << " a ▁ is ▁ greater ▁ than ▁ b STRNEWLINE " ; if ( a == b ) cout << " a ▁ is ▁ equal ▁ to ▁ b STRNEWLINE " ; else cout << " a ▁ and ▁ b ▁ are ▁ not ▁ equal STRNEWLINE " ; if ( a != b ) cout << " a ▁ is ▁ not ▁ equal ▁ to ▁ b STRNEWLINE " ; else cout << " a ▁ is ▁ equal ▁ b STRNEWLINE " ; return 0 ; }
Operators in C | Set 2 ( Relational and Logical Operators ) | C ++ program to demonstrate working of logical operators ; logical AND example ; logical OR example ; logical NOT example
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int a = 10 , b = 4 , c = 10 , d = 20 ; if ( a > b && c == d ) cout << " a ▁ is ▁ greater ▁ than ▁ b ▁ AND ▁ c ▁ is ▁ equal ▁ to ▁ d STRNEWLINE " ; else cout << " AND ▁ condition ▁ not ▁ satisfied STRNEWLINE " ; if ( a > b c == d ) cout << " a ▁ is ▁ greater ▁ than ▁ b ▁ OR ▁ c ▁ is ▁ equal ▁ to ▁ d STRNEWLINE " ; else cout << " Neither ▁ a ▁ is ▁ greater ▁ than ▁ b ▁ nor ▁ c ▁ is ▁ equal ▁ " " ▁ to ▁ d STRNEWLINE " ; if ( ! a ) cout << " a ▁ is ▁ zero STRNEWLINE " ; else cout << " a ▁ is ▁ not ▁ zero " ; return 0 ; }
Operators in C | Set 2 ( Relational and Logical Operators ) |
#include <stdbool.h> NEW_LINE #include <stdio.h> NEW_LINE int main ( ) { int a = 10 , b = 4 ; bool res = ( ( a != b ) cout << " GeeksQuiz " ) ; return 0 ; }
How to swap two bits in a given integer ? | C ++ program to swap bits in an integer ; This function swaps bit at positions p1 and p2 in an integer n ; Move p1 'th to rightmost side ; Move p2 'th to rightmost side ; XOR the two bits ; Put the xor bit back to their original positions ; XOR ' x ' with the original number so that the two sets are swapped ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int swapBits ( unsigned int n , unsigned int p1 , unsigned int p2 ) { unsigned int bit1 = ( n >> p1 ) & 1 ; unsigned int bit2 = ( n >> p2 ) & 1 ; unsigned int x = ( bit1 ^ bit2 ) ; x = ( x << p1 ) | ( x << p2 ) ; unsigned int result = n ^ x ; } int main ( ) { int res = swapBits ( 28 , 0 , 3 ) ; cout << " Result ▁ = ▁ " << res << " ▁ " ; return 0 ; }
Bitwise Operators in C / C ++ | ; Function to return the only odd occurring element ; Driver Method
#include <iostream> NEW_LINE using namespace std ; int findOdd ( int arr [ ] , int n ) { int res = 0 , i ; for ( i = 0 ; i < n ; i ++ ) res ^= arr [ i ] ; return res ; } int main ( void ) { int arr [ ] = { 12 , 12 , 14 , 90 , 14 , 14 , 14 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The ▁ odd ▁ occurring ▁ element ▁ is ▁ " << findOdd ( arr , n ) ; return 0 ; }
Bitwise Operators in C / C ++ |
#include <iostream> NEW_LINE using namespace std ; int main ( ) { int x = 2 , y = 5 ; ( x & y ) ? cout << " True ▁ " : cout << " False ▁ " ; ( x && y ) ? cout << " True ▁ " : cout << " False ▁ " ; return 0 ; }
Maximum length sub | C ++ implementation of the approach ; Function to return the maximum length of the required sub - array ; For the first consecutive pair of elements ; While a consecutive pair can be selected ; If current pair forms a valid sub - array ; 2 is the length of the current sub - array ; To extend the sub - array both ways ; While elements at indices l and r are part of a valid sub - array ; Update the maximum length so far ; Select the next consecutive pair ; Return the maximum length ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( int arr [ ] , int n ) { int maxLen = 0 ; int i = 0 ; int j = i + 1 ; while ( j < n ) { if ( arr [ i ] != arr [ j ] ) { maxLen = max ( maxLen , 2 ) ; int l = i - 1 ; int r = j + 1 ; while ( l >= 0 && r < n && arr [ l ] == arr [ i ] && arr [ r ] == arr [ j ] ) { l -- ; r ++ ; } maxLen = max ( maxLen , 2 * ( r - j ) ) ; } i ++ ; j = i + 1 ; } return maxLen ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 0 , 0 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxLength ( arr , n ) ; return 0 ; }
FreivaldΓ’ €ℒ s Algorithm to check if a matrix is product of two | CPP code to implement FreivaldaTMs Algorithm ; Function to check if ABx = Cx ; Generate a random vector ; Now comput B * r for evaluating expression A * ( B * r ) - ( C * r ) ; Now comput C * r for evaluating expression A * ( B * r ) - ( C * r ) ; Now comput A * ( B * r ) for evaluating expression A * ( B * r ) - ( C * r ) ; Finally check if value of expression A * ( B * r ) - ( C * r ) is 0 or not ; Runs k iterations Freivald . The value of k determines accuracy . Higher value means higher accuracy . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 2 NEW_LINE int freivald ( int a [ ] [ N ] , int b [ ] [ N ] , int c [ ] [ N ] ) { bool r [ N ] ; for ( int i = 0 ; i < N ; i ++ ) r [ i ] = random ( ) % 2 ; int br [ N ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) br [ i ] = br [ i ] + b [ i ] [ j ] * r [ j ] ; int cr [ N ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) cr [ i ] = cr [ i ] + c [ i ] [ j ] * r [ j ] ; int axbr [ N ] = { 0 } ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < N ; j ++ ) axbr [ i ] = axbr [ i ] + a [ i ] [ j ] * br [ j ] ; for ( int i = 0 ; i < N ; i ++ ) if ( axbr [ i ] - cr [ i ] != 0 ) false ; return true ; } bool isProduct ( int a [ ] [ N ] , int b [ ] [ N ] , int c [ ] [ N ] , int k ) { for ( int i = 0 ; i < k ; i ++ ) if ( freivald ( a , b , c ) == false ) return false ; return true ; } int main ( ) { int a [ N ] [ N ] = { { 1 , 1 } , { 1 , 1 } } ; int b [ N ] [ N ] = { { 1 , 1 } , { 1 , 1 } } ; int c [ N ] [ N ] = { { 2 , 2 } , { 2 , 2 } } ; int k = 2 ; if ( isProduct ( a , b , c , k ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }
Expectation or expected value of an array | CPP code to calculate expected value of an array ; Function to calculate expectation ; variable prb is for probability of each element which is same for each element ; calculating expectation overall ; returning expectation as sum ; Driver program ; Function for calculating expectation ; Display expectation of given array
#include <bits/stdc++.h> NEW_LINE using namespace std ; float calc_Expectation ( float a [ ] , float n ) { float prb = ( 1 / n ) ; float sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += a [ i ] * prb ; return sum ; } int main ( ) { float expect , n = 6.0 ; float a [ 6 ] = { 1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 } ; expect = calc_Expectation ( a , n ) ; cout << " Expectation ▁ of ▁ array ▁ E ( X ) ▁ is ▁ : ▁ " << expect << " STRNEWLINE " ; return 0 ; }
Program to generate CAPTCHA and verify user | C ++ program to automatically generate CAPTCHA and verify user ; Returns true if given two strings are same ; Generates a CAPTCHA of given length ; Characters to be included ; Generate n characters from above set and add these characters to captcha . ; Driver code ; Generate a random CAPTCHA ; Ask user to enter a CAPTCHA ; Notify user about matching status
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkCaptcha ( string & captcha , string & user_captcha ) { return captcha . compare ( user_captcha ) == 0 ; } string generateCaptcha ( int n ) { time_t t ; srand ( ( unsigned ) time ( & t ) ) ; char * chrs = " abcdefghijklmnopqrstuvwxyzABCDEFGHI " " JKLMNOPQRSTUVWXYZ0123456789" ; string captcha = " " ; while ( n -- ) captcha . push_back ( chrs [ rand ( ) % 62 ] ) ; return captcha ; } int main ( ) { string captcha = generateCaptcha ( 9 ) ; cout << captcha ; string usr_captcha ; cout << " Enter above CAPTCHA : " ; cin >> usr_captcha ; if ( checkCaptcha ( captcha , usr_captcha ) ) printf ( " CAPTCHA Matched " else printf ( " CAPTCHA Not Matched " return 0 ; }
Sum of N | C ++ implementation to illustrate the program ; Function to calculate the sum recursively ; Base cases ; If n is odd ; If n is even ; Function to print the value of Sum ; Driver Code ; First element ; Common difference ; Number of elements ; Mod value
#include <iostream> NEW_LINE using namespace std ; int SumGPUtil ( long long int r , long long int n , long long int m ) { if ( n == 0 ) return 1 ; if ( n == 1 ) return ( 1 + r ) % m ; long long int ans ; if ( n % 2 == 1 ) { ans = ( 1 + r ) * SumGPUtil ( ( r * r ) % m , ( n - 1 ) / 2 , m ) ; } else { ans = 1 + ( r * ( 1 + r ) * SumGPUtil ( ( r * r ) % m , ( n / 2 ) - 1 , m ) ) ; } return ( ans % m ) ; } void SumGP ( long long int a , long long int r , long long int N , long long int M ) { long long int answer ; answer = a * SumGPUtil ( r , N , M ) ; answer = answer % M ; cout << answer << endl ; } int main ( ) { long long int a = 1 ; long long int r = 4 ; long long int N = 10000 ; long long int M = 100000 ; SumGP ( a , r , N , M ) ; return 0 ; }
Length of longest subarray in which elements greater than K are more than elements not greater than K | C ++ implementation of above approach ; Function to find the length of a longest subarray in which elements greater than K are more than elements not greater than K ; Create a new array in which we store 1 if a [ i ] > k otherwise we store - 1. ; Taking prefix sum over it ; len will store maximum length of subarray ; This indicate there is at least one subarray of length mid that has sum > 0 ; Check every subarray of length mid if it has sum > 0 or not if sum > 0 then it will satisfy our required condition ; x will store the sum of subarray of length mid ; Satisfy our given condition ; Check for higher length as we get length mid ; Check for lower length as we did not get length mid ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int LongestSubarray ( int a [ ] , int n , int k ) { int pre [ n ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > k ) pre [ i ] = 1 ; else pre [ i ] = -1 ; } for ( int i = 1 ; i < n ; i ++ ) pre [ i ] = pre [ i - 1 ] + pre [ i ] ; int len = 0 ; int lo = 1 , hi = n ; while ( lo <= hi ) { int mid = ( lo + hi ) / 2 ; bool ok = false ; for ( int i = mid - 1 ; i < n ; i ++ ) { int x = pre [ i ] ; if ( i - mid >= 0 ) x -= pre [ i - mid ] ; if ( x > 0 ) { ok = true ; break ; } } if ( ok == true ) { len = mid ; lo = mid + 1 ; } else hi = mid - 1 ; } return len ; } int main ( ) { int a [ ] = { 2 , 3 , 4 , 5 , 3 , 7 } ; int k = 3 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << LongestSubarray ( a , n , k ) ; return 0 ; }
Choose points from two ranges such that no point lies in both the ranges | C ++ implementation of the approach ; Function to find the required points ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findPoints ( int l1 , int r1 , int l2 , int r2 ) { int x = ( l1 != l2 ) ? min ( l1 , l2 ) : -1 ; int y = ( r1 != r2 ) ? max ( r1 , r2 ) : -1 ; cout << x << " ▁ " << y ; } int main ( ) { int l1 = 5 , r1 = 10 , l2 = 1 , r2 = 7 ; findPoints ( l1 , r1 , l2 , r2 ) ; }
Tail Recursion | A NON - tail - recursive function . The function is not tail recursive because the value returned by fact ( n - 1 ) is used in fact ( n ) and call to fact ( n - 1 ) is not the last thing done by fact ( n ) ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; unsigned int fact ( unsigned int n ) { if ( n == 0 ) return 1 ; return n * fact ( n - 1 ) ; } int main ( ) { cout << fact ( 5 ) ; return 0 ; }
Minimum number of working days required to achieve each of the given scores | C ++ program for the above approach ; Function to find the lower bound of N using binary search ; Stores the lower bound ; Stores the upper bound ; Stores the minimum index having value is at least N ; Iterater while i <= j ; Stores the mid index of the range [ i , j ] ; If P [ mid ] is at least N ; Update the value of mid to index ; Update the value of j ; Update the value of i ; Return the resultant index ; Function to find the minimum number of days required to work to at least arr [ i ] points for every array element ; Traverse the array P [ ] ; Find the prefix sum ; Traverse the array arr [ ] ; Find the minimum index of the array having value at least arr [ i ] ; If the index is not - 1 ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySeach ( vector < int > P , int N ) { int i = 0 ; int j = P . size ( ) - 1 ; int index = -1 ; while ( i <= j ) { int mid = i + ( j - i ) / 2 ; if ( P [ mid ] >= N ) { index = mid ; j = mid - 1 ; } else { i = mid + 1 ; } } return index ; } void minDays ( vector < int > P , vector < int > arr ) { for ( int i = 1 ; i < P . size ( ) ; i ++ ) { P [ i ] += P [ i ] + P [ i - 1 ] ; } for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { int index = binarySeach ( P , arr [ i ] ) ; if ( index != -1 ) { cout << index + 1 << " ▁ " ; } else { cout << -1 << " ▁ " ; } } } int main ( ) { vector < int > arr = { 400 , 200 , 700 , 900 , 1400 } ; vector < int > P = { 100 , 300 , 400 , 500 , 600 } ; minDays ( P , arr ) ; return 0 ; }
Maximize profit that can be earned by selling an item among N buyers | C ++ program for the above approach ; Function to find the maximum profit earned by selling an item among N buyers ; Stores the maximum profit ; Stores the price of the item ; Sort the array ; Traverse the array ; Count of buyers with budget >= arr [ i ] ; Update the maximum profit ; Return the maximum possible price ; Driver code
#include <iostream> NEW_LINE #include <climits> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; int maximumProfit ( int arr [ ] , int N ) { int ans = INT_MIN ; int price = 0 ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { int count = ( N - i ) ; if ( ans < count * arr [ i ] ) { price = arr [ i ] ; ans = count * arr [ i ] ; } } return price ; } int main ( ) { int arr [ ] = { 22 , 87 , 9 , 50 , 56 , 43 } ; cout << maximumProfit ( arr , 6 ) ; return 0 ; }
Maximum length palindromic substring for every index such that it starts and ends at that index | C ++ program for the above approach ; Function to return true if S [ i ... j ] is a palindrome ; Iterate until i < j ; If unequal character encountered ; Otherwise ; Function to find for every index , longest palindromic substrings starting or ending at that index ; Stores the maximum palindromic substring length for each index ; Traverse the string ; Stores the maximum length of palindromic substring ; Consider that palindromic substring ends at index i ; If current character is a valid starting index ; If S [ i , j ] is palindrome , ; Update the length of the longest palindrome ; Consider that palindromic substring starts at index i ; If current character is a valid ending index ; If str [ i , j ] is palindrome ; Update the length of the longest palindrome ; Update length of the longest palindromic substring for index i ; Print the length of the longest palindromic substring ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string S , int i , int j ) { while ( i < j ) { if ( S [ i ] != S [ j ] ) return false ; i ++ ; j -- ; } return true ; } void printLongestPalindrome ( string S , int N ) { int palLength [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { int maxlength = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( S [ j ] == S [ i ] ) { if ( isPalindrome ( S , j , i ) ) { maxlength = i - j + 1 ; break ; } } } for ( int j = N - 1 ; j > i ; j -- ) { if ( S [ j ] == S [ i ] ) { if ( isPalindrome ( S , i , j ) ) { maxlength = max ( j - i + 1 , maxlength ) ; break ; } } } palLength [ i ] = maxlength ; } for ( int i = 0 ; i < N ; i ++ ) { cout << palLength [ i ] << " ▁ " ; } } int main ( ) { string S = " bababa " ; int N = S . length ( ) ; printLongestPalindrome ( S , N ) ; return 0 ; }
Sum of array elements which are multiples of a given number | C ++ program for the above approach ; Function to find the sum of array elements which are multiples of N ; Stores the sum ; Traverse the given array ; If current element is a multiple of N ; Print total sum ; Driver Code ; Given arr [ ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; void mulsum ( int arr [ ] , int n , int N ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % N == 0 ) { sum = sum + arr [ i ] ; } } cout << sum ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int N = 3 ; mulsum ( arr , n , N ) ; return 0 ; }
Lexicographically largest string possible consisting of at most K consecutive similar characters | C ++ program for the above approach ; Function to return nearest lower character ; Traverse charset from start - 1 ; If no character can be appended ; Function to find largest string ; Stores the frequency of characters ; Traverse the string ; Append larger character ; Decrease count in charset ; Increase count ; Check if count reached to charLimit ; Find nearest lower char ; If no character can be appended ; Append nearest lower character ; Reset count for next calculation ; Return new largest string ; Driver code ; Given string s
#include <bits/stdc++.h> NEW_LINE using namespace std ; char nextAvailableChar ( vector < int > charset , int start ) { for ( int i = start - 1 ; i >= 0 ; i -- ) { if ( charset [ i ] > 0 ) { charset [ i ] -- ; return char ( i + ' a ' ) ; } } return ' \0' ; } string newString ( string originalLabel , int limit ) { int n = originalLabel . length ( ) ; vector < int > charset ( 26 , 0 ) ; string newStrings = " " ; for ( char i : originalLabel ) charset [ i - ' a ' ] ++ ; for ( int i = 25 ; i >= 0 ; i -- ) { int count = 0 ; while ( charset [ i ] > 0 ) { newStrings += char ( i + ' a ' ) ; charset [ i ] -- ; count ++ ; if ( charset [ i ] > 0 && count == limit ) { char next = nextAvailableChar ( charset , i ) ; if ( next == ' \0' ) return newStrings ; newStrings += next ; count = 0 ; } } } return newStrings ; } int main ( ) { string S = " ccbbb " ; int K = 2 ; cout << ( newString ( S , K ) ) ; }
Rearrange array by interchanging positions of even and odd elements in the given array | C ++ program for the above approach ; Function to replace odd elements with even elements and vice versa ; Traverse the given array ; If arr [ i ] is visited ; Find the next odd element ; Find next even element ; Mark them visited ; Swap them ; Print the final array ; Driver Code ; Given array arr [ ] ; Length of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 3 NEW_LINE #define M 4 NEW_LINE void swapEvenOdd ( int arr [ ] , int n ) { int o = -1 , e = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) continue ; int r = -1 ; if ( arr [ i ] % 2 == 0 ) { o ++ ; while ( arr [ o ] % 2 == 0 arr [ o ] < 0 ) o ++ ; r = o ; } else { e ++ ; while ( arr [ e ] % 2 == 1 arr [ e ] < 0 ) e ++ ; r = e ; } arr [ i ] *= -1 ; arr [ r ] *= -1 ; int tmp = arr [ i ] ; arr [ i ] = arr [ r ] ; arr [ r ] = tmp ; } for ( int i = 0 ; i < n ; i ++ ) { cout << ( -1 * arr [ i ] ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; swapEvenOdd ( arr , n ) ; }
Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings | C ++ program to implement the above approach ; iterate through the length if we could find a [ i ] = = b [ j ] we could increment I and decrement j ; else we could just break the loop as its not a palindrome type sequence ; we could concatenate the a ' s ▁ left ▁ part ▁ + b ' s right part in a variable a and a ' s ▁ right ▁ part + b ' s left in the variable b ; we would check for the palindrome condition if yes we print True else False ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string rev ( string str ) { int st = 0 ; int ed = str . length ( ) - 1 ; string s = str ; while ( st < ed ) { swap ( s [ st ] , s [ ed ] ) ; st ++ ; ed -- ; } return s ; } bool check ( string a , string b , int n ) { int i = 0 ; int j = n - 1 ; while ( i < n ) { if ( a [ i ] != b [ j ] ) break ; i += 1 ; j -= 1 ; string xa = a . substr ( i , j + 1 - i ) ; string xb = b . substr ( i , j + 1 - i ) ; if ( ( xa == rev ( xa ) ) or ( xb == rev ( xb ) ) ) return true ; } return false ; } int main ( ) { string a = " xbdef " ; string b = " cabex " ; if ( check ( a , b , a . length ( ) ) == true or check ( b , a , a . length ( ) ) == true ) cout << " True " ; else cout << " False " ; }
Maximize length of subarray having equal elements by adding at most K | C ++ 14 program for above approach ; Function to check if a subarray of length len consisting of equal elements can be obtained or not ; Sliding window ; Last element of the sliding window will be having the max size in the current window ; The current number of element in all indices of the current sliding window ; If the current number of the window , added to k exceeds totalNumbers ; Function to find the maximum number of indices having equal elements after adding at most k numbers ; Sort the array in ascending order ; Make prefix sum array ; Initialize variables ; Update mid ; Check if any subarray can be obtained of length mid having equal elements ; Decrease max to mid ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( vector < int > pSum , int len , int k , vector < int > a ) { int i = 0 ; int j = len ; while ( j <= a . size ( ) ) { int maxSize = a [ j - 1 ] ; int totalNumbers = maxSize * len ; int currNumbers = pSum [ j ] - pSum [ i ] ; if ( currNumbers + k >= totalNumbers ) { return true ; } else { i ++ ; j ++ ; } } return false ; } int maxEqualIdx ( vector < int > arr , int k ) { sort ( arr . begin ( ) , arr . end ( ) ) ; vector < int > prefixSum ( arr . size ( ) ) ; prefixSum [ 1 ] = arr [ 0 ] ; for ( int i = 1 ; i < prefixSum . size ( ) - 1 ; ++ i ) { prefixSum [ i + 1 ] = prefixSum [ i ] + arr [ i ] ; } int max = arr . size ( ) ; int min = 1 ; int ans = 1 ; while ( min <= max ) { int mid = ( max + min ) / 2 ; if ( check ( prefixSum , mid , k , arr ) ) { ans = mid ; min = mid + 1 ; } else { max = mid - 1 ; } } return ans ; } int main ( ) { vector < int > arr = { 1 , 1 , 1 } ; int k = 7 ; cout << ( maxEqualIdx ( arr , k ) ) ; }
Sum of product of all pairs of a Binary Array | C ++ program to implement the above approach ; Function to print the sum of product of all pairs of the given array ; Stores count of one in the given array ; If current element is 1 ; Increase count ; Return the sum of product of all pairs ; Driver Code ; Stores the size of the given array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int productSum ( int arr [ ] , int N ) { int cntOne = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == 1 ) cntOne ++ ; } return cntOne * ( cntOne - 1 ) / 2 ; } int main ( ) { int arr [ ] = { 0 , 1 , 1 , 0 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << productSum ( arr , n ) << endl ; }
Minimum value of X that can be added to N to minimize sum of the digits to Γƒ Β’ Γ’ €°€ K | C ++ program for the above approach ; Function to find the minimum number needed to be added so that the sum of the digits does not exceed K ; Find the number of digits ; Calculate sum of the digits ; Add the digits of num2 ; If the sum of the digits of N is less than or equal to K ; No number needs to be added ; Otherwise ; Calculate the sum of digits from least significant digit ; If sum exceeds K ; Increase previous digit by 1 ; Add zeros to the end ; Calculate difference between the result and N ; Return the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDigits ( int N , int K ) { int digits_num = floor ( log10 ( N ) + 1 ) ; int temp_sum = 0 ; int temp = digits_num ; int result ; int X , var ; int sum = 0 ; int num2 = N ; while ( num2 != 0 ) { sum += num2 % 10 ; num2 /= 10 ; } if ( sum <= K ) { X = 0 ; } else { while ( temp > 0 ) { var = ( N / ( pow ( 10 , temp - 1 ) ) ) ; temp_sum += var % 10 ; if ( temp_sum >= K ) { var /= 10 ; var ++ ; result = var * pow ( 10 , temp ) ; break ; } temp -- ; } X = result - N ; return X ; } } int main ( ) { int N = 11 , K = 1 ; cout << minDigits ( N , K ) ; return 0 ; }
Count of Ways to obtain given Sum from the given Array elements | C ++ Program to implement the above approach ; Function to perform the DFS to calculate the number of ways ; Base case : Reached the end of array ; If current sum is obtained ; Otherwise ; If previously calculated subproblem occurred ; Check if the required sum can be obtained by adding current element or by subtracting the current index element ; Store the count of ways ; Function to call dfs to calculate the number of ways ; Iterate till the length of array ; Initialize the memorization table ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dfs ( vector < vector < int > > memo , int nums [ ] , int S , int curr_sum , int index , int sum , int N ) { if ( index == N ) { if ( S == curr_sum ) return 1 ; else return 0 ; } if ( memo [ index ] [ curr_sum + sum ] != INT_MIN ) { return memo [ index ] [ curr_sum + sum ] ; } int ans = dfs ( memo , nums , index + 1 , curr_sum + nums [ index ] , S , sum , N ) + dfs ( memo , nums , index + 1 , curr_sum - nums [ index ] , S , sum , N ) ; memo [ index ] [ curr_sum + sum ] = ans ; return ans ; } int findWays ( int nums [ ] , int S , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += nums [ i ] ; vector < vector < int > > memo ( N + 1 , vector < int > ( 2 * sum + 1 , INT_MIN ) ) ; return dfs ( memo , nums , S , 0 , 0 , sum , N ) ; } int main ( ) { int S = 3 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int answer = findWays ( arr , S , N ) ; cout << answer << endl ; return 0 ; }
Longest subarray with sum not divisible by X | C ++ Program to implement the above approach ; Function to print the longest subarray with sum of elements not divisible by X ; Pref [ ] stores the prefix sum Suff [ ] stores the suffix sum ; If array element is divisibile by x ; Increase count ; If all the array elements are divisible by x ; No subarray possible ; Reverse v to calculate the suffix sum ; Calculate the suffix sum ; Reverse to original form ; Reverse the suffix sum array ; Calculate the prefix sum ; Stores the starting index of required subarray ; Stores the ending index of required subarray ; If suffix sum till i - th index is not divisible by x ; Update the answer ; If prefix sum till i - th index is not divisible by x ; Update the answer ; Print the longest subarray ; Driver Code
#include <iostream> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; void max_length ( int N , int x , vector < int > & v ) { int i , a ; vector < int > preff , suff ; int ct = 0 ; for ( i = 0 ; i < N ; i ++ ) { a = v [ i ] ; if ( a % x == 0 ) { ct += 1 ; } } if ( ct == N ) { cout << -1 << endl ; return ; } reverse ( v . begin ( ) , v . end ( ) ) ; suff . push_back ( v [ 0 ] ) ; for ( i = 1 ; i < N ; i ++ ) { suff . push_back ( v [ i ] + suff [ i - 1 ] ) ; } reverse ( v . begin ( ) , v . end ( ) ) ; reverse ( suff . begin ( ) , suff . end ( ) ) ; preff . push_back ( v [ 0 ] ) ; for ( i = 1 ; i < N ; i ++ ) { preff . push_back ( v [ i ] + preff [ i - 1 ] ) ; } int ans = 0 ; int lp = 0 ; int rp = N - 1 ; for ( i = 0 ; i < N ; i ++ ) { if ( suff [ i ] % x != 0 && ( ans < ( N - 1 ) ) ) { lp = i ; rp = N - 1 ; ans = max ( ans , N - i ) ; } if ( preff [ i ] % x != 0 && ( ans < ( i + 1 ) ) ) { lp = 0 ; rp = i ; ans = max ( ans , i + 1 ) ; } } for ( i = lp ; i <= rp ; i ++ ) { cout << v [ i ] << " ▁ " ; } } int main ( ) { int x = 3 ; vector < int > v = { D2 : V21 , 3 , 2 , 6 } ; int N = v . size ( ) ; max_length ( N , x , v ) ; return 0 ; }
Number of times Maximum and minimum value updated during traversal of array | C ++ implementation to find the number of times minimum and maximum value updated during the traversal of the array ; Function to find the number of times minimum and maximum value updated during the traversal of the given array ; Increment i if new highest value occurs Increment j if new lowest value occurs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxUpdated ( vector < int > arr ) { int h_score = arr [ 0 ] ; int l_score = arr [ 0 ] ; int i = 1 , j = 1 ; for ( auto n : arr ) { if ( h_score < n ) { h_score = n ; i ++ ; } if ( l_score > n ) { l_score = n ; j ++ ; } } cout << " Number ▁ of ▁ times ▁ maximum ▁ value ▁ " ; cout << " updated ▁ = ▁ " << i << endl ; cout << " Number ▁ of ▁ times ▁ minimum ▁ value ▁ " ; cout << " updated ▁ = ▁ " << j << endl ; } int main ( ) { vector < int > arr ( { 10 , 5 , 20 , 22 } ) ; maxUpdated ( arr ) ; }
Find the farthest smaller number in the right side | C ++ implementation of the approach ; Function to find the farthest smaller number in the right side ; To store minimum element in the range i to n ; If current element in the suffix_min is less than a [ i ] then move right ; Print the required answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void farthest_min ( int a [ ] , int n ) { int suffix_min [ n ] ; suffix_min [ n - 1 ] = a [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) { suffix_min [ i ] = min ( suffix_min [ i + 1 ] , a [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { int low = i + 1 , high = n - 1 , ans = -1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( suffix_min [ mid ] < a [ i ] ) { ans = mid ; low = mid + 1 ; } else high = mid - 1 ; } cout << ans << " ▁ " ; } } int main ( ) { int a [ ] = { 3 , 1 , 5 , 2 , 4 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; farthest_min ( a , n ) ; return 0 ; }
Print numbers in descending order along with their frequencies | C ++ program to print the elements in descending along with their frequencies ; Function to print the elements in descending along with their frequencies ; Sorts the element in decreasing order ; traverse the array elements ; Prints the number and count ; Prints the last step ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printElements ( int a [ ] , int n ) { sort ( a , a + n , greater < int > ( ) ) ; int cnt = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( a [ i ] != a [ i + 1 ] ) { cout << a [ i ] << " ▁ occurs ▁ " << cnt << " ▁ times STRNEWLINE " ; cnt = 1 ; } else cnt += 1 ; } cout << a [ n - 1 ] << " ▁ occurs ▁ " << cnt << " ▁ times STRNEWLINE " ; } int main ( ) { int a [ ] = { 1 , 1 , 1 , 2 , 3 , 4 , 9 , 9 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printElements ( a , n ) ; return 0 ; }
Find element position in given monotonic sequence | C ++ implementation of the approach ; Function to return the value of f ( n ) for given values of a , b , c , n ; if c is 0 , then value of n can be in order of 10 ^ 15. if c != 0 , then n ^ 3 value has to be in order of 10 ^ 18 so maximum value of n can be 10 ^ 6. ; for efficient searching , use binary search . ; Driver code
#include <iostream> NEW_LINE #include <math.h> NEW_LINE #define SMALL_N 1000000 NEW_LINE #define LARGE_N 1000000000000000 NEW_LINE using namespace std ; long long func ( long long a , long long b , long long c , long long n ) { long long res = a * n ; long long logVlaue = floor ( log2 ( n ) ) ; res += b * n * logVlaue ; res += c * ( n * n * n ) ; return res ; } long long getPositionInSeries ( long long a , long long b , long long c , long long k ) { long long start = 1 , end = SMALL_N ; if ( c == 0 ) { end = LARGE_N ; } long long ans = 0 ; while ( start <= end ) { long long mid = ( start + end ) / 2 ; long long val = func ( a , b , c , mid ) ; if ( val == k ) { ans = mid ; break ; } else if ( val > k ) { end = mid - 1 ; } else { start = mid + 1 ; } } return ans ; } int main ( ) { long long a = 2 , b = 1 , c = 1 ; long long k = 12168587437017 ; cout << getPositionInSeries ( a , b , c , k ) ; return 0 ; }
Check if array can be sorted with one swap | CPP program to check if an array can be sorted with at - most one swap ; Create a sorted copy of original array ; Check if 0 or 1 swap required to get the sorted array ; Driver Program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkSorted ( int n , int arr [ ] ) { int b [ n ] ; for ( int i = 0 ; i < n ; i ++ ) b [ i ] = arr [ i ] ; sort ( b , b + n ) ; int ct = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] != b [ i ] ) ct ++ ; if ( ct == 0 ct == 2 ) return true ; else return false ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 4 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkSorted ( n , arr ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check whether ( i , j ) exists such that arr [ i ] != arr [ j ] and arr [ arr [ i ] ] is equal to arr [ arr [ j ] ] | C ++ implementation of the above approach ; Function that will tell whether such Indices present or Not . ; Checking 1 st condition i . e whether Arr [ i ] equal to Arr [ j ] or not ; Checking 2 nd condition i . e whether Arr [ Arr [ i ] ] equal to Arr [ Arr [ j ] ] or not . ; Driver Code ; Calling function .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkIndices ( int Arr [ ] , int N ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { if ( Arr [ i ] != Arr [ j ] ) { if ( Arr [ Arr [ i ] - 1 ] == Arr [ Arr [ j ] - 1 ] ) return true ; } } } return false ; } int main ( ) { int Arr [ ] = { 3 , 2 , 1 , 1 , 4 } ; int N = sizeof ( Arr ) / sizeof ( Arr [ 0 ] ) ; checkIndices ( Arr , N ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Find two non | C ++ programs to find two non - overlapping pairs having equal sum in an Array ; Function to find two non - overlapping with same sum in an array ; first create an empty map key -> which is sum of a pair of elements in the array value -> vector storing index of every pair having that sum ; consider every pair ( arr [ i ] , arr [ j ] ) and where ( j > i ) ; calculate sum of current pair ; if sum is already present in the map ; check every pair having equal sum ; if pairs don 't overlap, print them and return ; Insert current pair into the map ; If no such pair found ; Driver Code
#include <iostream> NEW_LINE #include <unordered_map> NEW_LINE #include <vector> NEW_LINE using namespace std ; typedef pair < int , int > Pair ; void findPairs ( int arr [ ] , int n ) { unordered_map < int , vector < Pair > > map ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int sum = arr [ i ] + arr [ j ] ; if ( map . find ( sum ) != map . end ( ) ) { for ( auto pair : map . find ( sum ) -> second ) { int m = pair . first , n = pair . second ; if ( ( m != i && m != j ) && ( n != i && n != j ) ) { cout << " Pair ▁ First ( " << arr [ i ] << " , ▁ " << arr [ j ] << " Pair Second ( " ▁ < < ▁ arr [ m ] ▁ < < ▁ " , " ▁ < < ▁ arr [ n ] ▁ < < ▁ " ) " return ; } } } map [ sum ] . push_back ( { i , j } ) ; } } cout << " No ▁ such ▁ non - overlapping ▁ pairs ▁ present " ; } int main ( ) { int arr [ ] = { 8 , 4 , 7 , 8 , 4 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findPairs ( arr , size ) ; return 0 ; }
Print all pairs with given sum | C ++ implementation of simple method to find print pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Consider all possible pairs and check their sums ; Driver function to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int printPairs ( int arr [ ] , int n , int sum ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] + arr [ j ] == sum ) cout << " ( " << arr [ i ] << " , ▁ " << arr [ j ] << " ) " << endl ; } int main ( ) { int arr [ ] = { 1 , 5 , 7 , -1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int sum = 6 ; printPairs ( arr , n , sum ) ; return 0 ; }
Ways to choose three points with distance between the most distant points <= L | C ++ program to count ways to choose triplets such that the distance between the farthest points <= L ; Returns the number of triplets with the distance between farthest points <= L ; sort the array ; find index of element greater than arr [ i ] + L ; find Number of elements between the ith index and indexGreater since the Numbers are sorted and the elements are distinct from the points btw these indices represent points within range ( a [ i ] + 1 and a [ i ] + L ) both inclusive ; if there are at least two elements in between i and indexGreater find the Number of ways to select two points out of these ; Driver Code ; set of n points on the X axis
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTripletsLessThanL ( int n , int L , int * arr ) { sort ( arr , arr + n ) ; int ways = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int indexGreater = upper_bound ( arr , arr + n , arr [ i ] + L ) - arr ; int numberOfElements = indexGreater - ( i + 1 ) ; if ( numberOfElements >= 2 ) { ways += ( numberOfElements * ( numberOfElements - 1 ) / 2 ) ; } } return ways ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int L = 4 ; int ans = countTripletsLessThanL ( n , L , arr ) ; cout << " Total ▁ Number ▁ of ▁ ways ▁ = ▁ " << ans << " STRNEWLINE " ; return 0 ; }
Making elements distinct in a sorted array by minimum increments | CPP program to make sorted array elements distinct by incrementing elements and keeping sum to minimum . ; To find minimum sum of unique elements . ; While current element is same as previous or has become smaller than previous . ; Driver code
#include <iostream> NEW_LINE using namespace std ; int minSum ( int arr [ ] , int n ) { int sum = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) { int j = i ; while ( j < n && arr [ j ] <= arr [ j - 1 ] ) { arr [ j ] = arr [ j ] + 1 ; j ++ ; } } sum = sum + arr [ i ] ; } return sum ; } int main ( ) { int arr [ ] = { 2 , 2 , 3 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minSum ( arr , n ) << endl ; return 0 ; }
Making elements distinct in a sorted array by minimum increments | Efficient CPP program to make sorted array elements distinct by incrementing elements and keeping sum to minimum . ; To find minimum sum of unique elements . ; If violation happens , make current value as 1 plus previous value and add to sum . ; No violation . ; Drivers code
#include <iostream> NEW_LINE using namespace std ; int minSum ( int arr [ ] , int n ) { int sum = arr [ 0 ] , prev = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] <= prev ) { prev = prev + 1 ; sum = sum + prev ; } else { sum = sum + arr [ i ] ; prev = arr [ i ] ; } } return sum ; } int main ( ) { int arr [ ] = { 2 , 2 , 3 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minSum ( arr , n ) << endl ; return 0 ; }
Randomized Binary Search Algorithm | C ++ program to implement recursive randomized algorithm . ; To generate random number between x and y ie . . [ x , y ] ; A recursive randomized binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; Here we have defined middle as random index between l and r ie . . [ l , r ] ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver code
#include <iostream> NEW_LINE #include <ctime> NEW_LINE using namespace std ; int getRandom ( int x , int y ) { srand ( time ( NULL ) ) ; return ( x + rand ( ) % ( y - x + 1 ) ) ; } int randomizedBinarySearch ( int arr [ ] , int l , int r , int x ) { if ( r >= l ) { int mid = getRandom ( l , r ) ; if ( arr [ mid ] == x ) return mid ; if ( arr [ mid ] > x ) return randomizedBinarySearch ( arr , l , mid - 1 , x ) ; return randomizedBinarySearch ( arr , mid + 1 , r , x ) ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 10 ; int result = randomizedBinarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? printf ( " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ) : printf ( " Element ▁ is ▁ present ▁ at ▁ index ▁ % d " , result ) ; return 0 ; }
Program to remove vowels from a String | C ++ program to remove vowels from a String ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string remVowel ( string str ) { vector < char > vowels = { ' a ' , ' e ' , ' i ' , ' o ' , ' u ' , ' A ' , ' E ' , ' I ' , ' O ' , ' U ' } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( find ( vowels . begin ( ) , vowels . end ( ) , str [ i ] ) != vowels . end ( ) ) { str = str . replace ( i , 1 , " " ) ; i -= 1 ; } } return str ; } int main ( ) { string str = " GeeeksforGeeks ▁ - ▁ A ▁ Computer " " ▁ Science ▁ Portal ▁ for ▁ Geeks " ; cout << remVowel ( str ) << endl ; return 0 ; }
Make all array elements equal with minimum cost | This function assumes that a [ ] is sorted . If a [ ] is not sorted , we need to sort it first . ; If there are odd elements , we choose middle element ; If there are even elements , then we choose the average of middle two . ; After deciding the final value , find the result . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCostToMakeElementEqual ( int a [ ] , int n ) { int y ; if ( n % 2 == 1 ) y = a [ n / 2 ] ; else y = ( a [ n / 2 ] + a [ ( n - 2 ) / 2 ] ) / 2 ; int s = 0 ; for ( int i = 0 ; i < n ; i ++ ) s += abs ( a [ i ] - y ) ; return s ; } int main ( ) { int a [ ] = { 1 , 100 , 101 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << ( minCostToMakeElementEqual ( a , n ) ) ; }
Check if an array can be sorted by rearranging odd and even | Function to check if array can be sorted or not ; Function to check if given array can be sorted or not ; Traverse the array ; Traverse remaining elements at indices separated by 2 ; If current element is the minimum ; If any smaller minimum exists ; Swap with current element ; If array is sorted ; Otherwise ; Driver Code ; Given array
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSorted ( int arr [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } bool sortPoss ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int idx = -1 ; int minVar = arr [ i ] ; int j = i ; while ( j < n ) { if ( arr [ j ] < minVar ) { minVar = arr [ j ] ; idx = j ; } j = j + 2 ; } if ( idx != -1 ) { swap ( arr [ i ] , arr [ idx ] ) ; } } if ( isSorted ( arr , n ) ) return true ; else return false ; } int main ( ) { int arr [ ] = { 3 , 5 , 1 , 2 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( sortPoss ( arr , n ) ) cout << " True " ; else cout << " False " ; return 0 ; }
Print all array elements appearing more than N / K times | C ++ program to implement the above approach ; Function to + find the upper_bound of an array element ; Stores minimum index in which K lies ; Stores maximum index in which K lies ; Calculate the upper bound of K ; Stores mid element of l and r ; If arr [ mid ] is less than or equal to K ; Right subarray ; Left subarray ; Function to print all array elements whose frequency is greater than N / K ; Sort the array arr [ ] ; Stores index of an array element ; Traverse the array ; Stores upper bound of arr [ i ] ; If frequency of arr [ i ] is greater than N / 4 ; Update i ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int upperBound ( int arr [ ] , int N , int K ) { int l = 0 ; int r = N ; while ( l < r ) { int mid = ( l + r ) / 2 ; if ( arr [ mid ] <= K ) { l = mid + 1 ; } else { r = mid ; } } return l ; } void NDivKWithFreq ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; int i = 0 ; while ( i < N ) { int X = upperBound ( arr , N , arr [ i ] ) ; if ( ( X - i ) > N / 4 ) { cout << arr [ i ] << " ▁ " ; } i = X ; } } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 4 ; NDivKWithFreq ( arr , N , K ) ; return 0 ; }
Maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1 | C ++ program for the above approach ; Function to find maximum possible sum after changing the array elements as per the given constraints ; Stores the frequency of elements in given array ; Update frequency ; Stores the previously selected integer ; Stores the maximum possible sum ; Traverse over array count [ ] ; Run loop for each k ; Update ans ; Return maximum possible sum ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
#include <iostream> NEW_LINE using namespace std ; long maxSum ( int a [ ] , int n ) { int count [ n + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ min ( a [ i ] , n ) ] ++ ; int size = 0 ; long ans = 0 ; for ( int k = 1 ; k <= n ; k ++ ) { while ( count [ k ] > 0 && size < k ) { size ++ ; ans += size ; count [ k ] -- ; } ans += k * count [ k ] ; } return ans ; } int main ( ) { int arr [ ] = { 3 , 5 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( maxSum ( arr , n ) ) ; return 0 ; }
Find sum of product of every number and its frequency in given range | C ++ implementation to find sum of product of every number and square of its frequency in the given range ; Function to solve queries ; Calculating answer for every query ; The end points of the ith query ; map for storing frequency ; Incrementing the frequency ; Iterating over map to find answer ; adding the contribution of ith number ; print answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void answerQueries ( int arr [ ] , int n , vector < pair < int , int > > & queries ) { for ( int i = 0 ; i < queries . size ( ) ; i ++ ) { int ans = 0 ; int l = queries [ i ] . first - 1 ; int r = queries [ i ] . second - 1 ; map < int , int > freq ; for ( int j = l ; j <= r ; j ++ ) { freq [ arr [ j ] ] ++ ; } for ( auto & i : freq ) { ans += ( i . first * i . second ) ; } cout << ans << endl ; } } int main ( ) { int arr [ ] = { 1 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < pair < int , int > > queries = { { 1 , 2 } , { 1 , 3 } } ; answerQueries ( arr , n , queries ) ; }
Longest subsequence with first and last element greater than all other elements | C ++ implementation of the above approach ; Comparison functions ; Function to update the value in Fenwick tree ; Function to return the query result ; Function to return the length of subsequence ; Store the value in struct Array ; If less than 2 elements are present return that element . ; Set the left and right pointers to extreme ; Calculate left and right pointer index . ; Store the queries from [ L + 1 , R - 1 ] . ; Sort array and queries for fenwick updates ; For each query calculate maxx for the answer and store it in ans array . ; Mx will be mx + 2 as while calculating mx , we excluded element at index left and right ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Query { int l , r , x , index ; } ; struct Arrays { int val , index ; } ; bool cmp1 ( Query q1 , Query q2 ) { return q1 . x < q2 . x ; } bool cmp2 ( Arrays x , Arrays y ) { return x . val < y . val ; } void update ( int * Fenwick , int index , int val , int n ) { while ( index <= n ) { Fenwick [ index ] += val ; index += index & ( - index ) ; } } int query ( int * Fenwick , int index , int n ) { int sum = 0 ; while ( index > 0 ) { sum = sum + Fenwick [ index ] ; index -= index & ( - index ) ; } return sum ; } int maxLength ( int n , vector < int > & v ) { int where [ n + 2 ] ; memset ( where , 0 , sizeof where ) ; Arrays arr [ n ] ; for ( int i = 1 ; i <= n ; ++ i ) { v [ i - 1 ] = v [ i - 1 ] - 1 ; int x = v [ i - 1 ] ; where [ x ] = i - 1 ; arr [ i - 1 ] . val = x ; arr [ i - 1 ] . index = i - 1 ; } if ( n <= 2 ) { cout << n << endl ; return 0 ; } int left = n , right = 0 , mx = 0 ; Query queries [ 4 * n ] ; int j = 0 ; for ( int i = n - 1 ; i >= 0 ; -- i ) { left = min ( left , where [ i ] ) ; right = max ( right , where [ i ] ) ; int diff = right - left ; if ( diff == 0 diff == 1 ) { continue ; } int val1 = v [ left ] ; int val2 = v [ right ] ; int minn = min ( val1 , val2 ) ; queries [ j ] . l = left + 1 ; queries [ j ] . r = right - 1 ; queries [ j ] . x = minn ; queries [ j ] . index = j ; ++ j ; } int Fenwick [ n + 1 ] ; memset ( Fenwick , 0 , sizeof Fenwick ) ; int q = j - 1 ; sort ( arr , arr + n + 1 , cmp2 ) ; sort ( queries , queries + q + 1 , cmp1 ) ; int curr = 0 ; int ans [ q ] ; memset ( ans , 0 , sizeof ans ) ; for ( int i = 0 ; i <= q ; ++ i ) { while ( arr [ curr ] . val <= queries [ i ] . x and curr < n ) { update ( Fenwick , arr [ curr ] . index + 1 , 1 , n ) ; curr ++ ; } ans [ queries [ i ] . index ] = query ( Fenwick , queries [ i ] . r + 1 , n ) - query ( Fenwick , queries [ i ] . l , n ) ; } for ( int i = 0 ; i <= q ; ++ i ) { mx = max ( mx , ans [ i ] ) ; } mx = mx + 2 ; return mx ; } int main ( ) { int n = 6 ; vector < int > v = { 4 , 2 , 6 , 5 , 3 , 1 } ; cout << maxLength ( n , v ) << endl ; return 0 ; }
Pandigital Product | C ++ code to check the number is Pandigital Product or not ; To check the string formed from multiplicand , multiplier and product is pandigital ; calculate the multiplicand , multiplier , and product eligible for pandigital ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPandigital ( string str ) { if ( str . length ( ) != 9 ) return false ; char ch [ str . length ( ) ] ; strcpy ( ch , str . c_str ( ) ) ; sort ( ch , ch + str . length ( ) ) ; string s = ch ; if ( s . compare ( "123456789" ) == 0 ) return true ; else return true ; } bool PandigitalProduct_1_9 ( int n ) { for ( int i = 1 ; i * i <= n ; i ++ ) if ( n % i == 0 && isPandigital ( to_string ( n ) + to_string ( i ) + to_string ( n / i ) ) ) return true ; return false ; } int main ( ) { int n = 6952 ; if ( PandigitalProduct_1_9 ( n ) == true ) cout << " yes " ; else cout << " no " ; return 0 ; }
Median and Mode using Counting Sort | C ++ Program for Mode and Median using Counting Sort technique ; function that sort input array a [ ] and calculate mode and median using counting sort . ; The output array b [ ] will have sorted array ; variable to store max of input array which will to have size of count array ; auxiliary ( count ) array to store count . Initialize count array as 0. Size of count array will be equal to ( max + 1 ) . ; Store count of each element of input array ; mode is the index with maximum count ; Update count [ ] array with sum ; Sorted output array b [ ] to calculate median ; Median according to odd and even array size respectively . ; Output the result ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printModeMedian ( int a [ ] , int n ) { int b [ n ] ; int max = * max_element ( a , a + n ) ; int t = max + 1 ; int count [ t ] ; for ( int i = 0 ; i < t ; i ++ ) count [ i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) count [ a [ i ] ] ++ ; int mode = 0 ; int k = count [ 0 ] ; for ( int i = 1 ; i < t ; i ++ ) { if ( count [ i ] > k ) { k = count [ i ] ; mode = i ; } } for ( int i = 1 ; i < t ; i ++ ) count [ i ] = count [ i ] + count [ i - 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { b [ count [ a [ i ] ] - 1 ] = a [ i ] ; count [ a [ i ] ] -- ; } float median ; if ( n % 2 != 0 ) median = b [ n / 2 ] ; else median = ( b [ ( n - 1 ) / 2 ] + b [ ( n / 2 ) ] ) / 2.0 ; cout << " median ▁ = ▁ " << median << endl ; cout << " mode ▁ = ▁ " << mode ; } int main ( ) { int a [ ] = { 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printModeMedian ( a , n ) ; return 0 ; }
Check if both halves of the string have at least one different character | C ++ implementation to check if both halves of the string have at least one different character ; Function which break string into two halves Counts frequency of characters in each half Compares the two counter array and returns true if these counter arrays differ ; Declaration and initialization of counter array ; Driver function
#include <cstring> NEW_LINE #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; # define MAX 26 NEW_LINE bool function ( string str ) { int l = str . length ( ) ; int counter1 [ MAX ] ; int counter2 [ MAX ] ; memset ( counter1 , 0 , sizeof ( counter1 ) ) ; memset ( counter2 , 0 , sizeof ( counter2 ) ) ; for ( int i = 0 ; i < l / 2 ; i ++ ) counter1 [ str [ i ] - ' a ' ] ++ ; for ( int i = l / 2 ; i < l ; i ++ ) counter2 [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < MAX ; i ++ ) if ( counter2 [ i ] != counter1 [ i ] ) return true ; return false ; } int main ( ) { string str = " abcasdsabcae " ; if ( function ( str ) ) cout << " Yes , ▁ both ▁ halves ▁ differ " << " ▁ by ▁ at ▁ least ▁ one ▁ character " ; else cout << " No , ▁ both ▁ halves ▁ do ▁ " << " not ▁ differ ▁ at ▁ all " ; return 0 ; }
Check if both halves of the string have at least one different character | C ++ implementation to check if both halves of the string have at least one different character ; Function which break string into two halves Increments frequency of characters for first half Decrements frequency of characters for second half true if any index has non - zero value ; Declaration and initialization of counter array ; Driver function
#include <cstring> NEW_LINE #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; # define MAX 26 NEW_LINE bool function ( string str ) { int l = str . length ( ) ; int counter [ MAX ] ; memset ( counter , 0 , sizeof ( counter ) ) ; for ( int i = 0 ; i < l / 2 ; i ++ ) counter [ str [ i ] - ' a ' ] ++ ; for ( int i = l / 2 ; i < l ; i ++ ) counter [ str [ i ] - ' a ' ] -- ; for ( int i = 0 ; i < MAX ; i ++ ) if ( counter [ i ] != 0 ) return true ; return false ; } int main ( ) { string str = " abcasdsabcae " ; if ( function ( str ) ) cout << " Yes , ▁ both ▁ halves ▁ differ " << " ▁ by ▁ at ▁ least ▁ one ▁ character " ; else cout << " No , ▁ both ▁ halves ▁ do " << " ▁ not ▁ differ ▁ at ▁ all " ; return 0 ; }
Sort elements on the basis of number of factors | C ++ implementation to sort numbers on the basis of factors ; structure of each element having its index in the input array and number of factors ; function to count factors for a given number n ; if the number is a perfect square ; count all other factors ; if i is a factor then n / i will be another factor . So increment by 2 ; comparison function for the elements of the structure ; if two elements have the same number of factors then sort them in increasing order of their index in the input array ; sort in decreasing order of number of factors ; function to print numbers after sorting them in decreasing order of number of factors ; for each element of input array create a structure element to store its index and factors count ; sort the array of structures as defined ; access index from the structure element and corresponding to that index access the element from arr ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct element { int index , no_of_fact ; } ; int countFactors ( int n ) { int count = 0 ; int sq = sqrt ( n ) ; if ( sq * sq == n ) count ++ ; for ( int i = 1 ; i < sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) count += 2 ; } return count ; } bool compare ( struct element e1 , struct element e2 ) { if ( e1 . no_of_fact == e2 . no_of_fact ) return e1 . index < e2 . index ; return e1 . no_of_fact > e2 . no_of_fact ; } void printOnBasisOfFactors ( int arr [ ] , int n ) { struct element num [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { num [ i ] . index = i ; num [ i ] . no_of_fact = countFactors ( arr [ i ] ) ; } sort ( num , num + n , compare ) ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ num [ i ] . index ] << " ▁ " ; } int main ( ) { int arr [ ] = { 5 , 11 , 10 , 20 , 9 , 16 , 23 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printOnBasisOfFactors ( arr , n ) ; return 0 ; }
Minimum difference between max and min of all K | C ++ program to find minimum difference between max and min of all subset of K size ; returns min difference between max and min of any K - size subset ; sort the array so that close elements come together . ; initialize result by a big integer number ; loop over first ( N - K ) elements of the array only ; get difference between max and min of current K - sized segment ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minDifferenceAmongMaxMin ( int arr [ ] , int N , int K ) { sort ( arr , arr + N ) ; int res = INT_MAX ; for ( int i = 0 ; i <= ( N - K ) ; i ++ ) { int curSeqDiff = arr [ i + K - 1 ] - arr [ i ] ; res = min ( res , curSeqDiff ) ; } return res ; } int main ( ) { int arr [ ] = { 10 , 20 , 30 , 100 , 101 , 102 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 3 ; cout << minDifferenceAmongMaxMin ( arr , N , K ) ; return 0 ; }
Position of an element after stable sort | C ++ program to get index of array element in sorted array ; Method returns the position of arr [ idx ] after performing stable - sort on array ; Count of elements smaller than current element plus the equal element occurring before given index ; If element is smaller then increase the smaller count ; If element is equal then increase count only if it occurs before ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getIndexInSortedArray ( int arr [ ] , int n , int idx ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < arr [ idx ] ) result ++ ; if ( arr [ i ] == arr [ idx ] && i < idx ) result ++ ; } return result ; } int main ( ) { int arr [ ] = { 3 , 4 , 3 , 5 , 2 , 3 , 4 , 3 , 1 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int idxOfEle = 5 ; cout << getIndexInSortedArray ( arr , n , idxOfEle ) ; return 0 ; }
Find permutation of numbers upto N with a specific sum in a specific range | C ++ program for the above approach ; Function to check if sum is possible with remaining numbers ; Stores the minimum sum possible with x numbers ; Stores the maximum sum possible with x numbers ; If S lies in the range [ minSum , maxSum ] ; Function to find the resultant permutation ; Stores the count of numbers in the given segment ; If the sum is not possible with numbers in the segment ; Output - 1 ; Stores the numbers present within the given segment ; Iterate over the numbers from 1 to N ; If ( S - i ) is a positive non - zero sum and if it is possible to obtain ( S - i ) remaining numbers ; Update sum S ; Update required numbers in the segement ; Push i in vector v ; If sum has been obtained ; Break from the loop ; If sum is not obtained ; Output - 1 ; Stores the numbers which are not present in given segment ; Loop to check the numbers not present in the segment ; Pointer to check if i is present in vector v or not ; If i is not present in v ; Push i in vector v1 ; Point to the first elements of v1 and v respectively ; Print the required permutation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool possible ( int x , int S , int N ) { int minSum = ( x * ( x + 1 ) ) / 2 ; int maxSum = ( x * ( ( 2 * N ) - x + 1 ) ) / 2 ; if ( S < minSum S > maxSum ) { return false ; } return true ; } void findPermutation ( int N , int L , int R , int S ) { int x = R - L + 1 ; if ( ! possible ( x , S , N ) ) { cout << -1 ; return ; } else { vector < int > v ; for ( int i = N ; i >= 1 ; -- i ) { if ( ( S - i ) >= 0 && possible ( x - 1 , S - i , i - 1 ) ) { S = S - i ; x -- ; v . push_back ( i ) ; } if ( S == 0 ) { break ; } } if ( S != 0 ) { cout << -1 ; return ; } vector < int > v1 ; for ( int i = 1 ; i <= N ; ++ i ) { vector < int > :: iterator it = find ( v . begin ( ) , v . end ( ) , i ) ; if ( it == v . end ( ) ) { v1 . push_back ( i ) ; } } int j = 0 , f = 0 ; for ( int i = 1 ; i < L ; ++ i ) { cout << v1 [ j ] << " ▁ " ; j ++ ; } for ( int i = L ; i <= R ; ++ i ) { cout << v [ f ] << " ▁ " ; f ++ ; } for ( int i = R + 1 ; i <= N ; ++ i ) { cout << v1 [ j ] << " ▁ " ; j ++ ; } } return ; } int main ( ) { int N = 6 , L = 3 , R = 5 , S = 8 ; findPermutation ( N , L , R , S ) ; return 0 ; }
Minimum count of indices to be skipped for every index of Array to keep sum till that index at most T | C ++ approach for above approach ; Function to calculate minimum indices to be skipped so that sum till i remains smaller than T ; Store the sum of all indices before i ; Store the elements that can be skipped ; Traverse the array , A [ ] ; Store the total sum of elements that needs to be skipped ; Store the number of elements need to be removed ; Traverse from the back of map so as to take bigger elements first ; Update sum ; Update map with the current element ; Driver code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void skipIndices ( int N , int T , int arr [ ] ) { int sum = 0 ; map < int , int > count ; for ( int i = 0 ; i < N ; i ++ ) { int d = sum + arr [ i ] - T ; int k = 0 ; if ( d > 0 ) { for ( auto u = count . rbegin ( ) ; u != count . rend ( ) ; u ++ ) { int j = u -> first ; int x = j * count [ j ] ; if ( d <= x ) { k += ( d + j - 1 ) / j ; break ; } k += count [ j ] ; d -= x ; } } sum += arr [ i ] ; count [ arr [ i ] ] ++ ; cout << k << " ▁ " ; } } int main ( ) { int N = 7 ; int T = 15 ; int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; skipIndices ( N , T , arr ) ; return 0 ; }
Count triplets ( a , b , c ) such that a + b , b + c and a + c are all divisible by K | Set 2 | C ++ program for the above approach ; Function to count the number of triplets from the range [ 1 , N - 1 ] having sum of all pairs divisible by K ; If K is even ; Otherwise ; Driver Code
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int countTriplets ( int N , int K ) { if ( K % 2 == 0 ) { long long int x = N / K ; long long int y = ( N + ( K / 2 ) ) / K ; return x * x * x + y * y * y ; } else { long long int x = N / K ; return x * x * x ; } } int main ( ) { int N = 2 , K = 2 ; cout << countTriplets ( N , K ) ; return 0 ; }