text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Sort 3 numbers | C ++ program to sort an array of size 3 ; Insert arr [ 1 ] ; Insert arr [ 2 ] ; Driver Code
#include <algorithm> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int sort3 ( int arr [ ] ) { if ( arr [ 1 ] < arr [ 0 ] ) swap ( arr [ 0 ] , arr [ 1 ] ) ; if ( arr [ 2 ] < arr [ 1 ] ) { swap ( arr [ 1 ] , arr [ 2 ] ) ; if ( arr [ 1 ] < arr [ 0 ] ) swap ( arr [ 1 ] , arr [ 0 ] ) ; } } int main ( ) { int a [ ] = { 10 , 12 , 5 } ; sort3 ( a ) ; for ( int i = 0 ; i < 3 ; i ++ ) cout << a [ i ] << " ▁ " ; return 0 ; }
Merge Sort with O ( 1 ) extra space merge and O ( n lg n ) time [ Unsigned Integers Only ] | C ++ program to sort an array using merge sort such that merge operation takes O ( 1 ) extra space . ; Obtaining actual values ; Recursive merge sort with extra parameter , naxele ; This functions finds max element and calls recursive merge sort . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void merge ( int arr [ ] , int beg , int mid , int end , int maxele ) { int i = beg ; int j = mid + 1 ; int k = beg ; while ( i <= mid && j <= end ) { if ( arr [ i ] % maxele <= arr [ j ] % maxele ) { arr [ k ] = arr [ k ] + ( arr [ i ] % maxele ) * maxele ; k ++ ; i ++ ; } else { arr [ k ] = arr [ k ] + ( arr [ j ] % maxele ) * maxele ; k ++ ; j ++ ; } } while ( i <= mid ) { arr [ k ] = arr [ k ] + ( arr [ i ] % maxele ) * maxele ; k ++ ; i ++ ; } while ( j <= end ) { arr [ k ] = arr [ k ] + ( arr [ j ] % maxele ) * maxele ; k ++ ; j ++ ; } for ( int i = beg ; i <= end ; i ++ ) arr [ i ] = arr [ i ] / maxele ; } void mergeSortRec ( int arr [ ] , int beg , int end , int maxele ) { if ( beg < end ) { int mid = ( beg + end ) / 2 ; mergeSortRec ( arr , beg , mid , maxele ) ; mergeSortRec ( arr , mid + 1 , end , maxele ) ; merge ( arr , beg , mid , end , maxele ) ; } } void mergeSort ( int arr [ ] , int n ) { int maxele = * max_element ( arr , arr + n ) + 1 ; mergeSortRec ( arr , 0 , n - 1 , maxele ) ; } int main ( ) { int arr [ ] = { 999 , 612 , 589 , 856 , 56 , 945 , 243 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; mergeSort ( arr , n ) ; cout << " Sorted ▁ array ▁ STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Print triplets with sum less than k | C ++ program to print triplets with sum smaller than a given value ; Sort input array ; Every iteration of loop counts triplet with first element as arr [ i ] . ; Initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; Use Meet in the Middle concept ; If sum of current triplet is more or equal , move right corner to look for smaller values ; Else move left corner ; This is important . For current i and j , there are total k - j third elements . ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int printTriplets ( int arr [ ] , int n , int sum ) { sort ( arr , arr + n ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { int j = i + 1 , k = n - 1 ; while ( j < k ) { if ( arr [ i ] + arr [ j ] + arr [ k ] >= sum ) k -- ; else { for ( int x = j + 1 ; x <= k ; x ++ ) cout << arr [ i ] << " , ▁ " << arr [ j ] << " , ▁ " << arr [ x ] << endl ; j ++ ; } } } } int main ( ) { int arr [ ] = { 5 , 1 , 3 , 4 , 7 } ; int n = sizeof arr / sizeof arr [ 0 ] ; int sum = 12 ; printTriplets ( arr , n , sum ) ; return 0 ; }
Sort string of characters using Stack | C ++ program to sort string of characters using stack ; Function to print the characters in sorted order ; Primary stack ; Secondary stack ; Append first character ; Iterate for all character in string ; i - th character ASCII ; stack 's top element ASCII ; If greater or equal to top element then push to stack ; If smaller , then push all element to the temporary stack ; Push all greater elements ; Push operation ; Push till the stack is not - empty ; Push the i - th character ; Push the tempstack back to stack ; Print the stack in reverse order ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSorted ( string s , int l ) { stack < char > Stack ; stack < char > tempstack ; Stack . push ( s [ 0 ] ) ; for ( int i = 1 ; i < l ; i ++ ) { int a = s [ i ] ; int b = Stack . top ( ) ; if ( ( a - b ) >= 1 or ( a == b ) ) Stack . push ( s [ i ] ) ; else if ( ( b - a ) >= 1 ) { while ( ( b - a ) >= 1 ) { tempstack . push ( Stack . top ( ) ) ; Stack . pop ( ) ; if ( Stack . size ( ) > 0 ) b = Stack . top ( ) ; else break ; } Stack . push ( s [ i ] ) ; while ( tempstack . size ( ) > 0 ) { Stack . push ( tempstack . top ( ) ) ; tempstack . pop ( ) ; } } } string answer ; while ( Stack . size ( ) > 0 ) { answer = Stack . top ( ) + answer ; Stack . pop ( ) ; } cout << answer << endl ; } int main ( ) { string s = " geeksforgeeks " ; int l = s . length ( ) ; printSorted ( s , l ) ; return 0 ; }
Check whether an array can be fit into another array rearranging the elements in the array | C ++ Program to check whether an array can be fit into another array with given condition . ; Returns true if the array A can be fit into array B , otherwise false ; Sort both the arrays ; Iterate over the loop and check whether every array element of A is less than or equal to its corresponding array element of B ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkFittingArrays ( int A [ ] , int B [ ] , int N ) { sort ( A , A + N ) ; sort ( B , B + N ) ; for ( int i = 0 ; i < N ; i ++ ) if ( A [ i ] > B [ i ] ) return false ; return true ; } int main ( ) { int A [ ] = { 7 , 5 , 3 , 2 } ; int B [ ] = { 5 , 4 , 8 , 7 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( checkFittingArrays ( A , B , N ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Maximise the number of toys that can be purchased with amount K | C ++ Program to maximize the number of toys with K amount ; This functions returns the required number of toys ; sort the cost array ; Check if we can buy ith toy or not ; Increment count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximum_toys ( int cost [ ] , int N , int K ) { int count = 0 , sum = 0 ; sort ( cost , cost + N ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( sum + cost [ i ] <= K ) { sum = sum + cost [ i ] ; count ++ ; } } return count ; } int main ( ) { int K = 50 ; int cost [ ] = { 1 , 12 , 5 , 111 , 200 , 1000 , 10 , 9 , 12 , 15 } ; int N = sizeof ( cost ) / sizeof ( cost [ 0 ] ) ; cout << maximum_toys ( cost , N , K ) << endl ; return 0 ; }
Find if k bookings possible with given arrival and departure times | C ++ code implementation of the above approach ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string areBookingsPossible ( int A [ ] , int B [ ] , int K , int N ) { sort ( A , A + N ) ; sort ( B , B + N ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( i + K < N && A [ i + K ] < B [ i ] ) { return " No " ; } } return " Yes " ; } int main ( ) { int arrival [ ] = { 1 , 2 , 3 } ; int departure [ ] = { 2 , 3 , 4 } ; int N = sizeof ( arrival ) / sizeof ( arrival [ 0 ] ) ; int K = 1 ; cout << ( areBookingsPossible ( arrival , departure , K , N ) ) ; return 0 ; }
Insertion Sort by Swapping Elements | Recursive CPP program to sort an array by swapping elements ; Utility function to print a Vector ; Function to perform Insertion Sort recursively ; General Case Sort V till second last element and then insert last element into V ; Insertion step ; Insert V [ i ] into list 0. . i - 1 ; Swap V [ j ] and V [ j - 1 ] ; Decrement j ; Driver Code
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; using Vector = vector < int > ; void printVector ( const Vector & V ) { for ( auto e : V ) { cout << e << " ▁ " ; } cout << endl ; } void insertionSortRecursive ( Vector & V , int N ) { if ( N <= 1 ) return ; insertionSortRecursive ( V , N - 1 ) ; int j = N - 1 ; while ( j > 0 and V [ j ] < V [ j - 1 ] ) { swap ( V [ j ] , V [ j - 1 ] ) ; j -= 1 ; } } int main ( ) { Vector A = { 9 , 8 , 7 , 5 , 2 , 1 , 2 , 3 } ; cout << " Array : ▁ " << endl ; printVector ( A ) ; cout << " After ▁ Sorting ▁ : " << endl ; insertionSortRecursive ( A , A . size ( ) ) ; printVector ( A ) ; return 0 ; }
Check if given array is almost sorted ( elements are at | CPP program to find whether given array almost sorted or not ; function for checking almost sort ; One by one compare adjacents . ; check whether resultant is sorted or not ; is resultant is sorted return true ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool almostSort ( int A [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { swap ( A [ i ] , A [ i + 1 ] ) ; i ++ ; } } for ( int i = 0 ; i < n - 1 ; i ++ ) if ( A [ i ] > A [ i + 1 ] ) return false ; return true ; } int main ( ) { int A [ ] = { 1 , 3 , 2 , 4 , 6 , 5 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; if ( almostSort ( A , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Efficiently merging two sorted arrays with O ( 1 ) extra space | Merging two sorted arrays with O ( 1 ) extra space ; Function to find next gap . ; comparing elements in the first array . ; comparing elements in both arrays . ; comparing elements in the second array . ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nextGap ( int gap ) { if ( gap <= 1 ) return 0 ; return ( gap / 2 ) + ( gap % 2 ) ; } void merge ( int * arr1 , int * arr2 , int n , int m ) { int i , j , gap = n + m ; for ( gap = nextGap ( gap ) ; gap > 0 ; gap = nextGap ( gap ) ) { for ( i = 0 ; i + gap < n ; i ++ ) if ( arr1 [ i ] > arr1 [ i + gap ] ) swap ( arr1 [ i ] , arr1 [ i + gap ] ) ; for ( j = gap > n ? gap - n : 0 ; i < n && j < m ; i ++ , j ++ ) if ( arr1 [ i ] > arr2 [ j ] ) swap ( arr1 [ i ] , arr2 [ j ] ) ; if ( j < m ) { for ( j = 0 ; j + gap < m ; j ++ ) if ( arr2 [ j ] > arr2 [ j + gap ] ) swap ( arr2 [ j ] , arr2 [ j + gap ] ) ; } } } int main ( ) { int a1 [ ] = { 10 , 27 , 38 , 43 , 82 } ; int a2 [ ] = { 3 , 9 } ; int n = sizeof ( a1 ) / sizeof ( int ) ; int m = sizeof ( a2 ) / sizeof ( int ) ; merge ( a1 , a2 , n , m ) ; printf ( " First ▁ Array : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) printf ( " % d ▁ " , a1 [ i ] ) ; printf ( " Second Array : " for ( int i = 0 ; i < m ; i ++ ) printf ( " % d ▁ " , a2 [ i ] ) ; printf ( " STRNEWLINE " ) ; return 0 ; }
Merge two sorted arrays | C ++ program to merge two sorted arrays / ; Merge arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] into arr3 [ 0. . n1 + n2 - 1 ] ; Traverse both array ; Check if current element of first array is smaller than current element of second array . If yes , store first array element and increment first array index . Otherwise do same with second array ; Store remaining elements of first array ; Store remaining elements of second array ; Driver code
#include <iostream> NEW_LINE using namespace std ; void mergeArrays ( int arr1 [ ] , int arr2 [ ] , int n1 , int n2 , int arr3 [ ] ) { int i = 0 , j = 0 , k = 0 ; while ( i < n1 && j < n2 ) { if ( arr1 [ i ] < arr2 [ j ] ) arr3 [ k ++ ] = arr1 [ i ++ ] ; else arr3 [ k ++ ] = arr2 [ j ++ ] ; } while ( i < n1 ) arr3 [ k ++ ] = arr1 [ i ++ ] ; while ( j < n2 ) arr3 [ k ++ ] = arr2 [ j ++ ] ; } int main ( ) { int arr1 [ ] = { 1 , 3 , 5 , 7 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int arr2 [ ] = { 2 , 4 , 6 , 8 } ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int arr3 [ n1 + n2 ] ; mergeArrays ( arr1 , arr2 , n1 , n2 , arr3 ) ; cout << " Array ▁ after ▁ merging " << endl ; for ( int i = 0 ; i < n1 + n2 ; i ++ ) cout << arr3 [ i ] << " ▁ " ; return 0 ; }
Sort array after converting elements to their squares | C ++ program to Sort square of the numbers of the array ; Function to sort an square array ; First convert each array elements into its square ; Sort an array using " sort ▁ STL ▁ function ▁ " ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortSquares ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = arr [ i ] * arr [ i ] ; sort ( arr , arr + n ) ; } int main ( ) { int arr [ ] = { -6 , -3 , -1 , 2 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Before ▁ sort ▁ " << endl ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; sortSquares ( arr , n ) ; cout << " After Sort " for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Sort an array when two halves are sorted | C ++ program to Merge Two Sorted Halves Of Array Into Single Sorted Array ; Merge two sorted halves of Array into single sorted array ; Temp Array store sorted resultant array ; First Find the point where array is divide into two half ; If Given array is all - ready sorted ; Merge two sorted arrays in single sorted array ; Copy the remaining elements of A [ i to half_ ! ] ; Copy the remaining elements of A [ half_ ! to n ] ; Driver code ; Print sorted Array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void mergeTwoHalf ( int A [ ] , int n ) { int temp [ n ] ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { half_i = i + 1 ; break ; } } if ( half_i == 0 ) return ; int i = 0 , j = half_i , k = 0 ; while ( i < half_i && j < n ) { if ( A [ i ] < A [ j ] ) temp [ k ++ ] = A [ i ++ ] ; else temp [ k ++ ] = A [ j ++ ] ; } while ( i < half_i ) temp [ k ++ ] = A [ i ++ ] ; while ( j < n ) temp [ k ++ ] = A [ j ++ ] ; for ( int i = 0 ; i < n ; i ++ ) A [ i ] = temp [ i ] ; } int main ( ) { int A [ ] = { 2 , 3 , 8 , -1 , 7 , 10 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; mergeTwoHalf ( A , n ) ; for ( int i = 0 ; i < n ; i ++ ) cout << A [ i ] << " ▁ " ; return 0 ; }
Chocolate Distribution Problem | C ++ program to solve chocolate distribution problem ; arr [ 0. . n - 1 ] represents sizes of packets m is number of students . Returns minimum difference between maximum and minimum values of distribution . ; if there are no chocolates or number of students is 0 ; Sort the given packets ; Number of students cannot be more than number of packets ; Largest number of chocolates ; Find the subarray of size m such that difference between last ( maximum in case of sorted ) and first ( minimum in case of sorted ) elements of subarray is minimum . ; Driver program to test above function ; int m = 7 ; Number of students
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinDiff ( int arr [ ] , int n , int m ) { if ( m == 0 n == 0 ) return 0 ; sort ( arr , arr + n ) ; if ( n < m ) return -1 ; int min_diff = INT_MAX ; for ( int i = 0 ; i + m - 1 < n ; i ++ ) { int diff = arr [ i + m - 1 ] - arr [ i ] ; if ( diff < min_diff ) min_diff = diff ; } return min_diff ; } int main ( ) { int arr [ ] = { 12 , 4 , 7 , 9 , 2 , 23 , 25 , 41 , 30 , 40 , 28 , 42 , 30 , 44 , 48 , 43 , 50 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ difference ▁ is ▁ " << findMinDiff ( arr , n , m ) ; return 0 ; }
Absolute distinct count in a sorted array | C ++ program to find absolute distinct count of an array in O ( n ) time . ; The function returns number of distinct absolute values among the elements of the array ; Note that set keeps only one copy even if we try to insert multiple values ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctCount ( int arr [ ] , int n ) { unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) s . insert ( abs ( arr [ i ] ) ) ; return s . size ( ) ; } int main ( ) { int arr [ ] = { -2 , -1 , 0 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Count ▁ of ▁ absolute ▁ distinct ▁ values ▁ : ▁ " << distinctCount ( arr , n ) ; return 0 ; }
Absolute distinct count in a sorted array | C ++ program to find absolute distinct count of an array using O ( 1 ) space . ; The function returns return number of distinct absolute values among the elements of the array ; initialize count as number of elements ; Remove duplicate elements from the left of the current window ( i , j ) and also decrease the count ; Remove duplicate elements from the right of the current window ( i , j ) and also decrease the count ; break if only one element is left ; Now look for the zero sum pair in current window ( i , j ) ; decrease the count if ( positive , negative ) pair is encountered ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctCount ( int arr [ ] , int n ) { int count = n ; int i = 0 , j = n - 1 , sum = 0 ; while ( i < j ) { while ( i != j && arr [ i ] == arr [ i + 1 ] ) count -- , i ++ ; while ( i != j && arr [ j ] == arr [ j - 1 ] ) count -- , j -- ; if ( i == j ) break ; sum = arr [ i ] + arr [ j ] ; if ( sum == 0 ) { count -- ; i ++ , j -- ; } else if ( sum < 0 ) i ++ ; else j -- ; } return count ; } int main ( ) { int arr [ ] = { -2 , -1 , 0 , 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Count ▁ of ▁ absolute ▁ distinct ▁ values ▁ : ▁ " << distinctCount ( arr , n ) ; return 0 ; }
Sorting Strings using Bubble Sort | C ++ implementation ; Sorting strings using bubble sort ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE void sortStrings ( char arr [ ] [ MAX ] , int n ) { char temp [ MAX ] ; for ( int j = 0 ; j < n - 1 ; j ++ ) { for ( int i = j + 1 ; i < n ; i ++ ) { if ( strcmp ( arr [ j ] , arr [ i ] ) > 0 ) { strcpy ( temp , arr [ j ] ) ; strcpy ( arr [ j ] , arr [ i ] ) ; strcpy ( arr [ i ] , temp ) ; } } } } int main ( ) { char arr [ ] [ MAX ] = { " GeeksforGeeks " , " Quiz " , " Practice " , " Gblogs " , " Coding " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortStrings ( arr , n ) ; printf ( " Strings ▁ in ▁ sorted ▁ order ▁ are ▁ : ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) printf ( " String % d is % s " , i + 1 , arr [ i ] ) ; return 0 ; }
Sort an almost sorted array where only two elements are swapped | C ++ program to sort using one swap ; This function sorts an array that can be sorted by single swap ; Traverse the given array from rightmost side ; Check if arr [ i ] is not in order ; Find the other element to be swapped with arr [ i ] ; Swap the pair ; A utility function to print an array of size n ; Driver program to test insertion sort
#include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; void sortByOneSwap ( int arr [ ] , int n ) { for ( int i = n - 1 ; i > 0 ; i -- ) { if ( arr [ i ] < arr [ i - 1 ] ) { int j = i - 1 ; while ( j >= 0 && arr [ i ] < arr [ j ] ) j -- ; swap ( arr [ i ] , arr [ j + 1 ] ) ; break ; } } } void printArray ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; cout << endl ; } int main ( ) { int arr [ ] = { 10 , 30 , 20 , 40 , 50 , 60 , 70 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Given ▁ array ▁ is ▁ STRNEWLINE " ; printArray ( arr , n ) ; sortByOneSwap ( arr , n ) ; cout << " Sorted ▁ array ▁ is ▁ STRNEWLINE " ; printArray ( arr , n ) ; return 0 ; }
Pancake sorting | C ++ program to sort array using pancake sort ; Reverses arr [ 0. . i ] ; Returns index of the maximum element in arr [ 0. . n - 1 ] ; The main function that sorts given array using flip operations ; Start from the complete array and one by one reduce current size by one ; Find index of the maximum element in arr [ 0. . curr_size - 1 ] ; Move the maximum element to end of current array if it 's not already at the end ; To move at the end , first move maximum number to beginning ; Now move the maximum number to end by reversing current array ; A utility function to print n array of size n ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void flip ( int arr [ ] , int i ) { int temp , start = 0 ; while ( start < i ) { temp = arr [ start ] ; arr [ start ] = arr [ i ] ; arr [ i ] = temp ; start ++ ; i -- ; } } int findMax ( int arr [ ] , int n ) { int mi , i ; for ( mi = 0 , i = 0 ; i < n ; ++ i ) if ( arr [ i ] > arr [ mi ] ) mi = i ; return mi ; } void pancakeSort ( int * arr , int n ) { for ( int curr_size = n ; curr_size > 1 ; -- curr_size ) { int mi = findMax ( arr , curr_size ) ; if ( mi != curr_size - 1 ) { flip ( arr , mi ) ; flip ( arr , curr_size - 1 ) ; } } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 23 , 10 , 20 , 11 , 12 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pancakeSort ( arr , n ) ; cout << " Sorted ▁ Array ▁ " << endl ; printArray ( arr , n ) ; return 0 ; }
Lexicographically smallest numeric string having odd digit counts | C ++ program for the above approach ; Function to construct lexicographically smallest numeric string having an odd count of each characters ; Stores the resultant string ; If N is even ; Otherwise ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string genString ( int N ) { string ans = " " ; if ( N % 2 == 0 ) { ans = string ( N - 1 , '1' ) + '2' ; } else { ans = string ( N , '1' ) ; } return ans ; } int main ( ) { int N = 5 ; cout << genString ( N ) ; return 0 ; }
Modify given string such that odd and even indices is lexicographically largest and smallest | C ++ program for the above approach ; Function to modify the given string satisfying the given criteria ; Traverse the string S ; If i is even ; If the S [ i ] is ' a ' , then change S [ i ] to ' b ' ; Otherwise , change S [ i ] to ' a ' ; If S [ i ] is ' z ' , then change S [ i ] to ' y ' ; Otherwise , change S [ i ] to ' z ' ; Return the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string performOperation ( string S , int N ) { for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { if ( S [ i ] == ' a ' ) { S [ i ] = ' b ' ; } else { S [ i ] = ' a ' ; } } else { if ( S [ i ] == ' z ' ) { S [ i ] = ' y ' ; } else { S [ i ] = ' z ' ; } } } return S ; } int main ( ) { string S = " giad " ; int N = S . size ( ) ; cout << performOperation ( S , N ) ; return 0 ; }
Count of values chosen for X such that N is reduced to 0 after given operations | C ++ program for the above approach ; Function to check if the value of X reduces N to 0 or not ; Update the value of N as N - x ; Check if x is a single digit integer ; Function to find the number of values X such that N can be reduced to 0 after performing the given operations ; Number of digits in N ; Stores the count of value of X ; Iterate over all possible value of X ; Check if x follow the conditions ; Return total count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int x , int N ) { while ( 1 ) { N -= x ; if ( x < 10 ) break ; int temp2 = 0 ; while ( x ) { temp2 *= 10 ; temp2 += ( x % 10 ) ; x /= 10 ; } x = temp2 ; } if ( ( x < 10 ) && ( N == 0 ) ) { return 1 ; } return 0 ; } int countNoOfsuchX ( int N ) { int k = ceil ( log10 ( N ) ) ; int count = 1 ; for ( int x = ( N - ( k * ( k + 1 ) * 5 ) ) ; x < N ; x ++ ) { if ( check ( x , N ) ) { count += 1 ; } } return count ; } int main ( ) { int N = 9399 ; cout << countNoOfsuchX ( N ) ; return 0 ; }
Maximize subarrays count containing the maximum and minimum Array element after deleting at most one element | C ++ program for the above approach ; Returns the count of subarrays which contains both the maximum and minimum elements in the given vector ; Initialize the low and high of array ; If current element is less than least element ; If current element is more than highest element ; If current element is equal to low or high then update the pointers ; Update number of subarrays ; Return the result ; Function to find the maximum count of subarrays ; Iterate the array to find the maximum and minimum element ; Vector after removing the minimum element ; Using assignment operator to copy one vector to other ; Vector after removing the maximum element ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long proc ( vector < int > & v ) { long long int n = v . size ( ) ; int low = v [ n - 1 ] , high = v [ n - 1 ] ; long long int p1 = n , p2 = n ; long long ans = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { int x = v [ i ] ; if ( x < low ) { low = x ; ans = 0 ; } else if ( x > high ) { high = x ; ans = 0 ; } if ( x == low ) p1 = i ; if ( x == high ) p2 = i ; ans += n - max ( p1 , p2 ) ; } return ans ; } long long subarray ( vector < int > & v ) { long long int n = v . size ( ) ; if ( n <= 1 ) return n ; long long ans = proc ( v ) ; int low = v [ 0 ] , pos_low = 0 , high = v [ 0 ] , pos_high = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int x = v [ i ] ; if ( x < low ) { low = x ; pos_low = i ; } else if ( x > high ) { high = x ; pos_high = i ; } } vector < int > u ; u = v ; u . erase ( u . begin ( ) + pos_low ) ; ans = max ( ans , proc ( u ) ) ; vector < int > w ; w = v ; w . erase ( w . begin ( ) + pos_high ) ; return max ( ans , proc ( w ) ) ; } int main ( ) { vector < int > v ; v . push_back ( 7 ) ; v . push_back ( 2 ) ; v . push_back ( 5 ) ; v . push_back ( 4 ) ; v . push_back ( 3 ) ; v . push_back ( 1 ) ; cout << subarray ( v ) << endl ; return 0 ; }
Minimize moves required to make array elements equal by incrementing and decrementing pairs | Set 2 | Function to find the minimum number of increment and decrement of pairs required to make all array elements equal ; Stores the sum of the array ; If sum is not divisible by N ; Update sum ; Store the minimum number of operations ; Iterate while i is less than N ; Add absolute difference of current element with k to ans ; Increase i bye 1 ; Return the value in ans2 ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( vector < int > arr , int N ) { int Sum = 0 ; for ( auto i : arr ) Sum += i ; if ( Sum % N ) return -1 ; int k = Sum / N ; int ans = 0 ; int i = 0 ; while ( i < N ) { ans = ans + abs ( k - arr [ i ] ) ; i += 1 ; } return ans / 2 ; } int main ( ) { vector < int > arr = { 5 , 4 , 1 , 10 } ; int N = arr . size ( ) ; cout << ( find ( arr , N ) ) ; }
Convert A into B by incrementing or decrementing 1 , 2 , or 5 any number of times | C ++ program for the above approach ; Function to find minimum number of moves required to convert A into B ; Stores the minimum number of moves required ; Stores the absolute difference ; FInd the number of moves ; Return cnt ; Driver Code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumSteps ( int a , int b ) { int cnt = 0 ; a = abs ( a - b ) ; cnt = ( a / 5 ) + ( a % 5 ) / 2 + ( a % 5 ) % 2 ; return cnt ; } int main ( ) { int A = 3 , B = 9 ; cout << minimumSteps ( A , B ) ; return 0 ; }
Minimum distance between duplicates in a String | C ++ Program to find the minimum distance between two repeating characters in a string using two pointers technique ; This function is used to find minimum distance between any two repeating characters using two - pointers and hashing technique ; hash array to store character 's last index ; Traverse through the string ; If the character is present in visited array find if its forming minimum distance ; update current character 's last index ; Return minimum distance found , else - 1 ; Driver code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int shortestDistance ( string s , int n ) { vector < int > visited ( 128 , -1 ) ; int ans = INT_MAX ; for ( int right = 0 ; right < n ; right ++ ) { char c = s [ right ] ; int left = visited ; if ( left != -1 ) ans = min ( ans , right - left - 1 ) ; visited = right ; } return ans == INT_MAX ? -1 : ans ; } int main ( ) { string s = " geeksforgeeks " ; int n = 13 ; cout << ( shortestDistance ( s , n ) ) ; }
Lexicographically smallest string which is not a subsequence of given string | C ++ program for the above approach ; Function to find lexicographically smallest string that is not a subsequence of S ; variable to store frequency of ' a ' ; calculate frequency of ' a ' ; Initialize string consisting of freq number of ' a ' ; change the last digit to ' b ' ; add another ' a ' to the string ; return tha answer string ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string smallestNonSubsequence ( string S , int N ) { int freq = 0 ; for ( int i = 0 ; i < N ; i ++ ) if ( S [ i ] == ' a ' ) freq ++ ; string ans ( freq , ' a ' ) ; if ( freq == N ) ans [ freq - 1 ] = ' b ' ; else ans += ' a ' ; return ans ; } int main ( ) { string S = " abcdefghijklmnopqrstuvwxyz " ; int N = S . length ( ) ; cout << smallestNonSubsequence ( S , N ) << endl ; return 0 ; }
Print all numbers that can be obtained by adding A or B to N exactly M times | C ++ program for the above approach ; Function to find all possible numbers that can be obtained by adding A or B to N exactly M times ; For maintaining increasing order ; Smallest number that can be obtained ; If A and B are equal , then only one number can be obtained , i . e . N + M * A ; For finding others numbers , subtract A from number once and add B to number once ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void possibleNumbers ( int N , int M , int A , int B ) { if ( A > B ) { swap ( A , B ) ; } int number = N + M * A ; cout << number << " ▁ " ; if ( A != B ) { for ( int i = 0 ; i < M ; i ++ ) { number = number - A + B ; cout << number << " ▁ " ; } } } int main ( ) { int N = 5 , M = 3 , A = 4 , B = 6 ; possibleNumbers ( N , M , A , B ) ; return 0 ; }
Maximize number of circular buildings that can be covered by L length wire | C ++ program for the above approach ; Function to find the maximum number of buildings covered ; Store the current sum ; Traverse the array ; Add the length of wire required for current building to cur_sum ; Add extra unit distance 1 ; If curr_sum <= length of wire increment count by 1 ; If curr_sum > length of wire increment start by 1 and decrement count by 1 and update the new curr_sum ; Update the max_count ; Return the max_count ; Driver Code ; Given Input ; Size of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const double Pi = 3.141592 ; int MaxBuildingsCovered ( int arr [ ] , int N , int L ) { double curr_sum = 0 ; int start = 0 , curr_count = 0 , max_count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { curr_sum = curr_sum + ( ( double ) arr [ i ] * Pi ) ; if ( i != 0 ) curr_sum += 1 ; if ( curr_sum <= L ) { curr_count ++ ; } else if ( curr_sum > L ) { curr_sum = curr_sum - ( ( double ) arr [ start ] * Pi ) ; curr_sum -= 1 ; start ++ ; curr_count -- ; } max_count = max ( curr_count , max_count ) ; } return max_count ; } int main ( ) { int arr [ ] = { 4 , 1 , 6 , 2 } ; int L = 24 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << MaxBuildingsCovered ( arr , N , L ) ; return 0 ; }
Count numbers less than N whose Bitwise AND with N is zero | C ++ program for the above approach ; Function to count number of unset bits in the integer N ; Stores the number of unset bits in N ; Check if N is even ; Increment the value of c ; Right shift N by 1 ; Return the value of count of unset bits ; Function to count numbers whose Bitwise AND with N equal to 0 ; Stores the number of unset bits in N ; Print the value of 2 to the power of unsetBits ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countUnsetBits ( int N ) { int c = 0 ; while ( N ) { if ( N % 2 == 0 ) { c += 1 ; } N = N >> 1 ; } return c ; } void countBitwiseZero ( int N ) { int unsetBits = countUnsetBits ( N ) ; cout << ( 1 << unsetBits ) ; } int main ( ) { int N = 9 ; countBitwiseZero ( N ) ; return 0 ; }
Check if a Binary String can be split into disjoint subsequences which are equal to "010" | C ++ program for the above approach ; Function to check if the given string can be partitioned into a number of subsequences all of which are equal to "010" ; Store the size of the string ; Store the count of 0 s and 1 s ; Traverse the given string in the forward direction ; If the character is '0' , increment count_0 by 1 ; If the character is '1' increment count_1 by 1 ; If at any point , count_1 > count_0 , return false ; If count_0 is not equal to twice count_1 , return false ; Reset the value of count_0 and count_1 ; Traverse the string in the reverse direction ; If the character is '0' increment count_0 ; If the character is '1' increment count_1 ; If count_1 > count_0 , return false ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( string s ) { int n = s . size ( ) ; int count_0 = 0 , count_1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '0' ) ++ count_0 ; else ++ count_1 ; if ( count_1 > count_0 ) return false ; } if ( count_0 != ( 2 * count_1 ) ) return false ; count_0 = 0 , count_1 = 0 ; for ( int i = n - 1 ; i >= 0 ; -- i ) { if ( s [ i ] == '0' ) ++ count_0 ; else ++ count_1 ; if ( count_1 > count_0 ) return false ; } return true ; } int main ( ) { string s = "010100" ; if ( isPossible ( s ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Minimum number of bricks that can be intersected | C ++ program for the above approach ; Function to find a line across a wall such that it intersects minimum number of bricks ; Declare a hashmap ; Store the maximum number of brick ending a point on x - axis ; Iterate over all the rows ; Initialize width as 0 ; Iterate over individual bricks ; Add the width of the current brick to the total width ; Increment number of bricks ending at this width position ; Update the variable , res ; Print the answer ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void leastBricks ( vector < vector < int > > wall ) { unordered_map < int , int > map ; int res = 0 ; for ( vector < int > list : wall ) { int width = 0 ; for ( int i = 0 ; i < list . size ( ) - 1 ; i ++ ) { width += list [ i ] ; map [ width ] ++ ; res = max ( res , map [ width ] ) ; } } cout << wall . size ( ) - res ; } int main ( ) { vector < vector < int > > arr { { 1 , 2 , 2 , 1 } , { 3 , 1 , 2 } , { 1 , 3 , 2 } , { 2 , 4 } , { 3 , 1 , 2 } , { 1 , 3 , 1 , 1 } } ; leastBricks ( arr ) ; return 0 ; }
Find an N | C ++ implementation of the above approach ; Function to print the required permutation ; Driver code
#include <iostream> NEW_LINE using namespace std ; void findPermutation ( int N ) { for ( int i = 1 ; i <= N ; i ++ ) cout << i << " ▁ " ; cout << endl ; } int main ( ) { int N = 5 ; findPermutation ( N ) ; return 0 ; }
Maximize count of distinct profits possible by N transactions | C ++ program for the above approach ; Function to count distinct profits possible ; Stores the minimum total profit ; Stores the maximum total profit ; Return count of distinct profits ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfWays ( int N , int X , int Y ) { int S1 = ( N - 1 ) * X + Y ; int S2 = ( N - 1 ) * Y + X ; return ( S2 - S1 + 1 ) ; } int main ( ) { int N = 3 ; int X = 13 ; int Y = 15 ; cout << numberOfWays ( N , X , Y ) ; return 0 ; }
Minimum number of operations required to make a permutation of first N natural numbers equal | C ++ program for the above approach ; Function to find the minimum number of operations required to make all array elements equal ; Store the count of operations required ; Increment by K - 1 , as the last element will be used again for the next K consecutive elements ; Increment count by 1 ; Return the result ; Driver Code ; Given Input
#include <bits/stdc++.h> NEW_LINE using namespace std ; int MinimumOperations ( int A [ ] , int N , int K ) { int Count = 0 ; int i = 0 ; while ( i < N - 1 ) { i = i + K - 1 ; Count ++ ; } return Count ; } int main ( ) { int A [ ] = { 5 , 4 , 3 , 1 , 2 } ; int K = 3 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << MinimumOperations ( A , N , K ) << endl ; return 0 ; }
Consecutive Prime numbers greater than equal to given number . | C ++ program for the above approach ; Function to check prime . ; It means it is not a prime ; No factor other than 1 therefore prime number ; Function to find out the required consecutive primes . ; Finding first prime just less than sqrt ( n ) . ; Finding prime just greater than sqrt ( n ) . ; Product of both prime is greater than n then print it ; Finding prime greater than second ; Driver Program
#include <bits/stdc++.h> NEW_LINE #define endl " NEW_LINE " #define ll long long NEW_LINE using namespace std ; bool is_prime ( ll n ) { if ( n == 1 ) { return false ; } for ( ll i = 2 ; i <= sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) { return false ; } } return true ; } void consecutive_primes ( int n ) { ll first = -1 , second = -1 ; for ( ll i = sqrt ( n ) ; i >= 2 ; i -- ) { if ( is_prime ( i ) ) { first = i ; break ; } } for ( ll i = sqrt ( n ) + 1 ; i <= n / 2 ; i ++ ) { if ( is_prime ( i ) ) { second = i ; break ; } } if ( first * second >= n ) { cout << first << " ▁ " << second << endl ; } else { for ( ll i = second + 1 ; i <= n ; i ++ ) { if ( is_prime ( i ) ) { cout << second << " ▁ " << i << endl ; return ; } } } } int main ( ) { ll n = 14 ; consecutive_primes ( n ) ; return 0 ; }
Minimum decrements required to make all pairs of adjacent matrix elements distinct | C ++ program for the above approach ; Function to count minimum number of operations required ; Case 1 : ; Case 2 : ; Print the minimum number of operations required ; Driver Code ; The given matrix ; Function Call to count the minimum number of decrements required
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int n = 3 ; const int m = 3 ; void countDecrements ( long long arr [ ] [ m ] ) { int count_1 = 0 ; int count_2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( ( i + j ) % 2 == arr [ i ] [ j ] % 2 ) count_1 ++ ; if ( 1 - ( i + j ) % 2 == arr [ i ] [ j ] % 2 ) count_2 ++ ; } } cout << min ( count_1 , count_2 ) ; } int main ( ) { long long arr [ ] [ m ] = { { 1 , 2 , 3 } , { 1 , 2 , 3 } , { 1 , 2 , 3 } } ; countDecrements ( arr ) ; return 0 ; }
Check if X can be converted to Y by converting to 3 * ( X / 2 ) or X | C ++ program for the above approach ; Function to check if X can be made equal to Y by converting X to ( 3 * X / 2 ) or ( X - 1 ) ; Conditions for possible conversion ; Otherwise , conversion is not possible ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void check ( int X , int Y ) { if ( X > 3 ) { cout << " Yes " ; } else if ( X == 1 and Y == 1 ) { cout << " Yes " ; } else if ( X == 2 and Y <= 3 ) { cout << " Yes " ; } else if ( X == 3 and Y <= 3 ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { int X = 6 , Y = 8 ; check ( X , Y ) ; return 0 ; }
Count distinct sum of pairs possible from a given range | C ++ program for the above approach ; Function to count distinct sum of pairs possible from the range [ L , R ] ; Return the count of distinct sum of pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distIntegers ( int L , int R ) { return 2 * R - 2 * L + 1 ; } int main ( ) { int L = 3 , R = 8 ; cout << distIntegers ( L , R ) ; return 0 ; }
Count subarrays having even Bitwise XOR | C ++ program for the above approach ; Function to count subarrays having even Bitwise XOR ; Store the required result ; Stores count of subarrays with even and odd XOR values ; Stores Bitwise XOR of current subarray ; Traverse the array ; Update current Xor ; If XOR is even ; Update ans ; Increment count of subarrays with even XOR ; Otherwise , increment count of subarrays with odd XOR ; Print the result ; Driver Code ; Given array ; Stores the size of the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; void evenXorSubarray ( int arr [ ] , int n ) { int ans = 0 ; int freq [ ] = { 0 , 0 } ; int XOR = 0 ; for ( int i = 0 ; i < n ; i ++ ) { XOR = XOR ^ arr [ i ] ; if ( XOR % 2 == 0 ) { ans += freq [ 0 ] + 1 ; freq [ 0 ] ++ ; } else { ans += freq [ 1 ] ; freq [ 1 ] ++ ; } } cout << ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; evenXorSubarray ( arr , N ) ; return 0 ; }
Count occurrences of an element in a matrix of size N * N generated such that each element is equal to product of its indices | C ++ program for the above approach ; Function to count the occurrences of X in the generated square matrix ; Stores the required result ; Iterate upto square root of X ; Check if i divides X ; Store the quotient obtained on dividing X by i ; If both the numbers fall in the range , update count ; Return the result ; Driver code ; Given N and X ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOccurrences ( int N , int X ) { int count = 0 ; for ( int i = 1 ; i < sqrt ( X ) ; i ++ ) { if ( X % i == 0 ) { int a = i ; int b = X / i ; if ( a <= N && b <= N ) { if ( a == b ) count += 1 ; else count += 2 ; } } } return count ; } int main ( ) { int N = 7 ; int X = 12 ; cout << countOccurrences ( N , X ) ; return 0 ; }
Maximize array product by changing any array element arr [ i ] to ( | C ++ program for the above approach ; Function to find array with maximum product by changing array elements to ( - 1 ) arr [ i ] - 1 ; Traverse the array ; Applying the operation on all the positive elements ; Stores maximum element in array ; Stores index of maximum element ; Check if current element is greater than the maximum element ; Find index of the maximum element ; Perform the operation on the maximum element ; Print the elements of the array ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findArrayWithMaxProduct ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) if ( arr [ i ] >= 0 ) { arr [ i ] = - arr [ i ] - 1 ; } if ( N % 2 == 1 ) { int max_element = -1 ; int index = -1 ; for ( int i = 0 ; i < N ; i ++ ) if ( abs ( arr [ i ] ) > max_element ) { max_element = abs ( arr [ i ] ) ; index = i ; } arr [ index ] = - arr [ index ] - 1 ; } for ( int i = 0 ; i < N ; i ++ ) printf ( " % d ▁ " , arr [ i ] ) ; } int main ( ) { int arr [ ] = { -3 , 0 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findArrayWithMaxProduct ( arr , N ) ; return 0 ; }
Lexicographically smallest permutation of first N natural numbers having K perfect indices | C ++ program for the above approach ; Function to print the lexicographically smallest permutation with K perfect indices ; Iterator to traverse the array ; Traverse first K array indices ; Traverse remaining indices ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void findPerfectIndex ( int N , int K ) { int i = 0 ; for ( ; i < K ; i ++ ) { cout << ( N - K + 1 ) + i << " ▁ " ; } for ( ; i < N ; i ++ ) { cout << i - K + 1 << " ▁ " ; } } int main ( ) { int N = 10 , K = 3 ; findPerfectIndex ( N , K ) ; return 0 ; }
Count pairs having distinct sum from a given range | C ++ program for the above approach ; Function to count pairs made up of elements from the range [ L , R ] having distinct sum ; Stores the least sum which can be formed by the pairs ; Stores the highest sum which can be formed by the pairs ; Stores the count of pairs having distinct sum ; Print the count of pairs ; Driver Code ; Function call to count the number of pairs having distinct sum in the range [ L , R ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; long countPairs ( long L , long R ) { long firstNum = 2 * L ; long lastNum = 2 * R ; long Cntpairs = lastNum - firstNum + 1 ; cout << Cntpairs ; } int main ( ) { long L = 2 , R = 3 ; countPairs ( L , R ) ; return 0 ; }
Count pairs from an array whose Bitwise OR is greater than Bitwise AND | C ++ program for the above approach ; Function to count the number of pairs ( i , j ) their Bitwise OR is greater than Bitwise AND ; Total number of pairs possible from the array ; Stores frequency of each array element ; Traverse the array A [ ] ; Increment ump [ A [ i ] ] by 1 ; Traverse the Hashmap ump ; Subtract those pairs ( i , j ) from count which has the same element on index i and j ( i < j ) ; Print the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countPairs ( int A [ ] , int n ) { long long count = ( n * ( n - 1 ) ) / 2 ; unordered_map < long long , long long > ump ; for ( int i = 0 ; i < n ; i ++ ) { ump [ A [ i ] ] ++ ; } for ( auto it = ump . begin ( ) ; it != ump . end ( ) ; ++ it ) { long long c = it -> second ; count = count - ( c * ( c - 1 ) ) / 2 ; } cout << count ; } int main ( ) { int A [ ] = { 1 , 4 , 7 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; countPairs ( A , N ) ; return 0 ; }
Construct a K | C ++ program for the above approach ; To construct the required binary string ; Function to construct binary string according to the given conditions ; Initialize with 1 ; Traverse the array ; To check if the i - th integer needs to be considered or not ; Print the binary string ; Driver Code ; Given array ; Size of the array ; Given K
#include <bits/stdc++.h> NEW_LINE using namespace std ; bitset < 100003 > bit ; void constructBinaryString ( int arr [ ] , int N , int K ) { bit [ 0 ] = 1 ; for ( int i = 0 ; i < N ; i ++ ) { bit |= bit << arr [ i ] ; } for ( int i = 1 ; i <= K ; i ++ ) { cout << bit [ i ] ; } } int main ( ) { int arr [ ] = { 1 , 6 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 8 ; constructBinaryString ( arr , N , K ) ; }
Check if a Rook can reach the given destination in a single move | C ++ program to implement for the above approach ; Function to check if it is possible to reach destination in a single move by a rook ; Driver Code ; Given arrays
#include <bits/stdc++.h> NEW_LINE using namespace std ; string check ( int current_row , int current_col , int destination_row , int destination_col ) { if ( current_row == destination_row ) return " POSSIBLE " ; else if ( current_col == destination_col ) return " POSSIBLE " ; else return " NOT ▁ POSSIBLE " ; } int main ( ) { int current_row = 8 ; int current_col = 8 ; int destination_row = 8 ; int destination_col = 4 ; string output = check ( current_row , current_col , destination_row , destination_col ) ; cout << output ; return 0 ; }
Append X digits to the end of N to make it divisible by M | C ++ program to implement the above approach ; Function to check if the value of N by appending X digits on right side of N is divisible by M or not ; Base Case ; If N is divisible by M ; Update res ; Iterate over the range [ 0 , 9 ] ; If N is divisible by M by appending X digits ; Driver Code ; Stores the number by appending X digits on the right side of N
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDiv ( int N , int X , int M , int & res ) { if ( X == 0 ) { if ( N % M == 0 ) { res = N ; return true ; } return false ; } for ( int i = 0 ; i <= 9 ; i ++ ) { if ( isDiv ( N * 10 + i , X - 1 , M , res ) ) { return true ; } } } int main ( ) { int N = 4 , M = 50 , X = 2 ; int res = -1 ; isDiv ( N , X , M , res ) ; cout << res ; }
Minimum increments to modify array such that value of any array element can be splitted to make all remaining elements equal | C ++ program for the above approach ; Function to count minimum moves ; Stores sum of given array ; Stores maximum array element ; Base Case ; If N is 2 , the answer will always be 0 ; Traverse the array ; Calculate sum of the array ; Finding maximum element ; Calculate ceil ( sum / N - 1 ) ; If k is smaller than maxelement ; Final sum - original sum ; Print the minimum number of increments required ; Driver Code ; Given array ; Size of given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumMoves ( int arr [ ] , int N ) { int sum = 0 ; int maxelement = -1 ; if ( N == 2 ) { cout << 0 ; } for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; maxelement = max ( maxelement , arr [ i ] ) ; } int K = ( sum + N - 2 ) / ( N - 1 ) ; K = max ( maxelement , K ) ; int ans = K * ( N - 1 ) - sum ; cout << ans ; } int main ( ) { int arr [ ] = { 2 , 3 , 7 } ; int N = 3 ; minimumMoves ( arr , N ) ; return 0 ; }
Split first N natural numbers into two subsequences with non | C ++ program for the above approach ; Function to split 1 to N into two subsequences with non - coprime sums ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void printSubsequence ( int N ) { cout << " { ▁ " ; for ( int i = 1 ; i < N - 1 ; i ++ ) { cout << i << " , ▁ " ; } cout << N - 1 << " ▁ } STRNEWLINE " ; cout << " { ▁ " << N << " ▁ } " ; } int main ( ) { int N = 8 ; printSubsequence ( N ) ; return 0 ; }
Generate an array with product of all subarrays of length exceeding one divisible by K | C ++ program for the above approach ; Function to check if the required array can be generated or not ; To check if divisor exists ; To store divisiors of K ; Check if K is prime or not ; If array can be generated ; Print d1 and d2 alternatively ; No such array can be generated ; Driver Code ; Given N and K ; Function Call
#include <iostream> NEW_LINE using namespace std ; void array_divisbleby_k ( int N , int K ) { bool flag = false ; int d1 , d2 ; for ( int i = 2 ; i * i <= K ; i ++ ) { if ( K % i == 0 ) { flag = true ; d1 = i ; d2 = K / i ; break ; } } if ( flag ) { for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 1 ) { cout << d2 << " ▁ " ; } else { cout << d1 << " ▁ " ; } } } else { cout << -1 ; } } int main ( ) { int N = 5 , K = 21 ; array_divisbleby_k ( N , K ) ; return 0 ; }
Minimum characters to be replaced to make a string concatenation of a K | C ++ program for the above approach ; Function to add an edge to graph ; Function to perform DFS traversal on the graph recursively from a given vertex u ; Visit the current vertex ; Total number of nodes in this component ; Increment the frequency of u ; Function for finding the minimum number changes required in given string ; Form the edges according to the given conditions ; Find minimum number of operations ; Frequency array for finding the most frequent character ; Frequency array for finding the most frequent character ; Finding most frequent character ; Change rest of the characters to most frequent one ; Print total number of changes ; Driver Code ; Function Call
#include " bits / stdc + + . h " NEW_LINE using namespace std ; void addEdge ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } void DFS ( int u , vector < int > adj [ ] , int & cnt , vector < bool > & visited , int fre [ ] , string S ) { visited [ u ] = true ; cnt ++ ; fre [ S [ u ] - ' a ' ] ++ ; for ( int i = 0 ; i < adj [ u ] . size ( ) ; i ++ ) { if ( ! visited [ adj [ u ] [ i ] ] ) { DFS ( adj [ u ] [ i ] , adj , cnt , visited , fre , S ) ; } } } int minimumOperations ( string & S , int m ) { int V = 100 ; vector < int > adj [ V ] ; int total = 0 , N = S . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { addEdge ( adj , i , N - i - 1 ) ; addEdge ( adj , N - i - 1 , i ) ; } for ( int i = 0 ; i < N - m ; i ++ ) { addEdge ( adj , i , i + m ) ; addEdge ( adj , i + m , i ) ; } vector < bool > visited ( V , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! visited [ i ] ) { int fre [ 26 ] = { 0 } ; int cnt = 0 , maxx = -1 ; DFS ( i , adj , cnt , visited , fre , S ) ; for ( int j = 0 ; j < 26 ; j ++ ) maxx = max ( maxx , fre [ j ] ) ; total += cnt - maxx ; } } cout << total ; } int main ( ) { string S = " abaaba " ; int K = 2 ; minimumOperations ( S , K ) ; return 0 ; }
Replace specified matrix elements such that no two adjacent elements are equal | C ++ program for the above approach ; Function to display the valid matrix ; Traverse the matrix ; If the current cell is a free space and is even - indexed ; If the current cell is a free space and is odd - indexed ; Print the matrix ; Driver Code ; Given N and M ; Given matrix ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void print ( vector < vector < char > > arr , int n , int m ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { char a = arr [ i ] [ j ] ; if ( ( i + j ) % 2 == 0 && a == ' F ' ) { arr [ i ] [ j ] = '1' ; } else if ( a == ' F ' ) { arr [ i ] [ j ] = '2' ; } } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { cout << arr [ i ] [ j ] ; } cout << endl ; } } int main ( ) { int n = 4 , m = 4 ; vector < vector < char > > arr = { { ' F ' , ' F ' , ' F ' , ' F ' } , { ' F ' , ' O ' , ' F ' , ' F ' } , { ' F ' , ' F ' , ' O ' , ' F ' } , { ' F ' , ' F ' , ' F ' , ' F ' } , } ; print ( arr , n , m ) ; return 0 ; }
Lexicographically smallest string formed by removing duplicates | C ++ program for the above approach ; Function that finds lexicographically smallest string after removing the duplicates from the given string ; Stores the frequency of characters ; Mark visited characters ; Stores count of each character ; Stores the resultant string ; Decrease the count of current character ; If character is not already in answer ; Last character > S [ i ] and its count > 0 ; Mark letter unvisited ; Add s [ i ] in res and mark it visited ; Return the resultant string ; Driver Code ; Given string S ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeDuplicateLetters ( string s ) { int cnt [ 26 ] = { 0 } ; int vis [ 26 ] = { 0 } ; int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) cnt [ s [ i ] - ' a ' ] ++ ; string res = " " ; for ( int i = 0 ; i < n ; i ++ ) { cnt [ s [ i ] - ' a ' ] -- ; if ( ! vis [ s [ i ] - ' a ' ] ) { while ( res . size ( ) > 0 && res . back ( ) > s [ i ] && cnt [ res . back ( ) - ' a ' ] > 0 ) { vis [ res . back ( ) - ' a ' ] = 0 ; res . pop_back ( ) ; } res += s [ i ] ; vis [ s [ i ] - ' a ' ] = 1 ; } } return res ; } int main ( ) { string S = " acbc " ; cout << removeDuplicateLetters ( S ) ; return 0 ; }
Number of pairs whose product is a power of 2 | C ++ program for the above approach ; Function to count pairs having product equal to a power of 2 ; Stores count of array elements which are power of 2 ; If array element contains only one set bit ; Increase count of powers of 2 ; Count required number of pairs ; Print the required number of pairs ; Driver Code ; Given array ; Size of the array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int N ) { int countPowerof2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( __builtin_popcount ( arr [ i ] ) == 1 ) countPowerof2 ++ ; } int desiredPairs = ( countPowerof2 * ( countPowerof2 - 1 ) ) / 2 ; cout << desiredPairs << ' ▁ ' ; } int main ( ) { int arr [ 4 ] = { 2 , 4 , 7 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countPairs ( arr , N ) ; return 0 ; }
Count ways to split N ! into two distinct co | C ++ Program for the above approach ; Maximum value of N ; Stores at each indices if given number is prime or not ; Stores count_of_primes ; Function to generate primes using Sieve of Eratsothenes ; Assume all odds are primes ; If a prime is encountered ; Mark all its multiples as non - prime ; Count primes <= MAXN ; Function to calculate ( x ^ y ) % p in O ( log y ) ; Utility function to count the number of ways N ! can be split into co - prime factors ; Driver Code ; Calling sieve function ; Given N ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAXN 1000000 NEW_LINE int is_prime [ MAXN ] = { 0 } ; int count_of_primes [ MAXN ] = { 0 } ; void sieve ( ) { for ( int i = 3 ; i < MAXN ; i += 2 ) { is_prime [ i ] = 1 ; } for ( int i = 3 ; i * i < MAXN ; i += 2 ) { if ( is_prime [ i ] ) for ( int j = i * i ; j < MAXN ; j += i ) { is_prime [ j ] = 0 ; } } is_prime [ 2 ] = 1 ; for ( int i = 1 ; i < MAXN ; i ++ ) count_of_primes [ i ] = count_of_primes [ i - 1 ] + is_prime [ i ] ; } long long int power ( long long int x , long long int y , long long int p ) { long long result = 1 ; while ( y > 0 ) { if ( y & 1 == 1 ) result = ( result * x ) % p ; x = ( x * x ) % p ; y >>= 1 ; } return result ; } void numberOfWays ( int N ) { long long int count = count_of_primes [ N ] - 1 ; long long int mod = 1000000007 ; long long int answer = power ( 2 , count , mod ) ; if ( N == 1 ) answer = 0 ; cout << answer ; } int main ( ) { sieve ( ) ; int N = 7 ; numberOfWays ( N ) ; return 0 ; }
Maximum possible sum of squares of stack elements satisfying the given properties | C ++ Program to implement the above approach ; Function to find the maximum sum of squares of stack elements ; Stores the sum ofsquares of stack elements ; Check if sum is valid ; Initialize all stack elements with 1 ; Stores the count the number of stack elements not equal to 1 ; Add the sum of squares of stack elements not equal to 1 ; Add 1 * 1 to res as the remaining stack elements are 1 ; Print the result ; Driver Code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSumOfSquares ( int N , int S ) { int res = 0 ; if ( S < N S > 9 * N ) { cout << ( -1 ) ; return ; } S = S - N ; int c = 0 ; while ( S > 0 ) { c ++ ; if ( S / 8 > 0 ) { res += 9 * 9 ; S -= 8 ; } else { res += ( S + 1 ) * ( S + 1 ) ; break ; } } res = res + ( N - c ) ; cout << ( res ) ; } int main ( ) { int N = 3 ; int S = 12 ; maxSumOfSquares ( N , S ) ; }
Unset least significant K bits of a given number | C ++ program for the above approach ; Function to return the value after unsetting K LSBs ; Create a mask ; Bitwise AND operation with the number and the mask ; Driver Code ; Given N and K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int clearLastBit ( int N , int K ) { int mask = ( -1 << K + 1 ) ; return N = N & mask ; } int main ( ) { int N = 730 , K = 3 ; cout << clearLastBit ( N , K ) ; return 0 ; }
Check if quantities of 3 distinct colors can be converted to a single color by given merge | C ++ program for the above approach ; Function to check whether it is possible to do the operation or not ; Calculate modulo 3 of all the colors ; Check for any equal pair ; Otherwise ; Driver Code ; Given colors ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int r , int b , int g ) { r = r % 3 ; b = b % 3 ; g = g % 3 ; if ( r == b b == g g == r ) { return true ; } else { return false ; } } int main ( ) { int R = 1 , B = 3 , G = 6 ; if ( isPossible ( R , B , G ) ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } return 0 ; }
Minimize steps required to make all array elements same by adding 1 , 2 or 5 | C ++ program for the above approach ; Function to calculate the minimum number of steps ; count stores number of operations required to make all elements equal to minimum value ; Remark , the array should remain unchanged for further calculations with different minimum ; Storing the current value of arr [ i ] in val ; Finds how much extra amount is to be removed ; Subtract the maximum number of 5 and stores remaining ; Subtract the maximum number of 2 and stores remaining ; Restores the actual value of arr [ i ] ; Return the count ; Function to find the minimum number of steps to make array elements same ; Sort the array in descending order ; Stores the minimum array element ; Stores the operations required to make array elements equal to minimum ; Stores the operations required to make array elements equal to minimum - 1 ; Stores the operations required to make array elements equal to minimum - 2 ; Return minimum of the three counts ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate_steps ( int arr [ ] , int n , int minimum ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int val = arr [ i ] ; if ( arr [ i ] > minimum ) { arr [ i ] = arr [ i ] - minimum ; count += arr [ i ] / 5 ; arr [ i ] = arr [ i ] % 5 ; count += arr [ i ] / 2 ; arr [ i ] = arr [ i ] % 2 ; if ( arr [ i ] ) { count ++ ; } } arr [ i ] = val ; } return count ; } int solve ( int arr [ ] , int n ) { sort ( arr , arr + n , greater < int > ( ) ) ; int minimum = arr [ n - 1 ] ; int count1 = 0 , count2 = 0 , count3 = 0 ; count1 = calculate_steps ( arr , n , minimum ) ; count2 = calculate_steps ( arr , n , minimum - 1 ) ; count3 = calculate_steps ( arr , n , minimum - 2 ) ; return min ( count1 , min ( count2 , count3 ) ) ; } int main ( ) { int arr [ ] = { 3 , 6 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << solve ( arr , N ) ; }
Largest palindromic string possible from given strings by rearranging the characters | C ++ program for the above approach ; Function to find largest palindrome possible from S and P after rearranging characters to make palindromic string T ; Using unordered_map to store frequency of elements mapT will have freq of elements of T ; Size of both the strings ; Take all character in mapT which occur even number of times in respective strings & simultaneously update number of characters left in map ; Check if a unique character is present in both string S and P ; Making string T in two halves half1 - first half half2 - second half ; Reverse the half2 to attach with half1 to make palindrome T ; If same unique element is present in both S and P , then taking that only which is already taken through mapT ; If same unique element is not present in S and P , then take characters that make string T lexicographically smallest ; If no unique element is present in both string S and P ; Driver Code ; Given two strings S and P ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string mergePalindromes ( string S , string P ) { unordered_map < char , int > mapS , mapP , mapT ; int n = S . size ( ) , m = P . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mapS [ S [ i ] ] ++ ; } for ( int i = 0 ; i < m ; i ++ ) { mapP [ P [ i ] ] ++ ; } for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { if ( mapS [ i ] % 2 == 0 ) { mapT [ i ] += mapS [ i ] ; mapS [ i ] = 0 ; } else { mapT [ i ] += mapS [ i ] - 1 ; mapS [ i ] = 1 ; } if ( mapP [ i ] % 2 == 0 ) { mapT [ i ] += mapP [ i ] ; mapP [ i ] = 0 ; } else { mapT [ i ] += mapP [ i ] - 1 ; mapP [ i ] = 1 ; } } int check = 0 ; for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { if ( mapS [ i ] > 0 && mapP [ i ] > 0 ) { mapT [ i ] += 2 ; check = 1 ; break ; } } string half1 = " " , half2 = " " ; for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { for ( int j = 0 ; ( 2 * j ) < mapT [ i ] ; j ++ ) { half1 += i ; half2 += i ; } } reverse ( half2 . begin ( ) , half2 . end ( ) ) ; if ( check ) { return half1 + half2 ; } for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { if ( mapS [ i ] > 0 mapP [ i ] > 0 ) { half1 += i ; return half1 + half2 ; } } return half1 + half2 ; } int main ( ) { string S = " aeabb " ; string P = " dfedf " ; cout << mergePalindromes ( S , P ) ; return 0 ; }
Count of subarrays having sum equal to its length | C ++ program for the above approach ; Function that counts the subarrays with sum of its elements as its length ; Decrementing all the elements of the array by 1 ; Making prefix sum array ; Declare map to store count of elements upto current element ; To count all the subarrays whose prefix sum is 0 ; Iterate the array ; Increment answer by count of current element of prefix array ; Return the answer ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfSubarray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) arr [ i ] -- ; int pref [ N ] ; pref [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) pref [ i ] = pref [ i - 1 ] + arr [ i ] ; map < int , int > mp ; int answer = 0 ; mp [ 0 ] ++ ; for ( int i = 0 ; i < N ; i ++ ) { answer += mp [ pref [ i ] ] ; mp [ pref [ i ] ] ++ ; } return answer ; } int main ( ) { int arr [ ] = { 1 , 1 , 0 } ; int N = sizeof arr / sizeof arr [ 0 ] ; cout << countOfSubarray ( arr , N ) ; return 0 ; }
Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum | C ++ program to print subset at the nth position ordered by the sum of the elements ; Function to print the elements of the subset at pos n ; Initialize count = 0 and x = 0 ; create a vector for storing the elements of subsets ; doing until all the set bits of n are used ; this part is executed only when the last bit is set ; right shift the bit by one position ; increasing the count each time by one ; printing the values os elements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printsubset ( int n , int k ) { int count = 0 , x = 0 ; vector < int > vec ; while ( n ) { x = n & 1 ; if ( x ) { vec . push_back ( pow ( k , count ) ) ; } n = n >> 1 ; count ++ ; } for ( int i = 0 ; i < vec . size ( ) ; i ++ ) cout << vec [ i ] << " ▁ " ; } int main ( ) { int n = 7 , k = 4 ; printsubset ( n , k ) ; return 0 ; }
Minimum digits to be removed to make either all digits or alternating digits same | C ++ program for the above approach ; Function to find longest possible subsequence of s beginning with x and y ; Iterate over the string ; Increment count ; Swap the positions ; Return the result ; Function that finds all the possible pairs ; Update count ; Return the answer ; Driver Code ; Given string s ; Find the size of the string ; Function Call ; This value is the count of minimum element to be removed
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( string s , int x , int y ) { int res = 0 ; for ( auto c : s ) { if ( c - '0' == x ) { res ++ ; swap ( x , y ) ; } } if ( x != y && res % 2 == 1 ) -- res ; return res ; } int find_min ( string s ) { int count = 0 ; for ( int i = 0 ; i < 10 ; i ++ ) { for ( int j = 0 ; j < 10 ; j ++ ) { count = max ( count , solve ( s , i , j ) ) ; } } return count ; } int main ( ) { string s = "100120013" ; int n = s . size ( ) ; int answer = find_min ( s ) ; cout << ( n - answer ) ; return 0 ; }
Count total set bits in all numbers from range L to R | C ++ program for the above approach ; Function to count set bits in x ; Base Case ; Recursive Call ; Function that returns count of set bits present in all numbers from 1 to N ; Initialize the result ; Return the setbit count ; Driver Code ; Given L and R ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int countSetBitsUtil ( unsigned int x ) { if ( x <= 0 ) return 0 ; return ( ( x % 2 == 0 ? 0 : 1 ) + countSetBitsUtil ( x / 2 ) ) ; } unsigned int countSetBits ( unsigned int L , unsigned int R ) { int bitCount = 0 ; for ( int i = L ; i <= R ; i ++ ) { bitCount += countSetBitsUtil ( i ) ; } return bitCount ; } int main ( ) { int L = 3 , R = 5 ; printf ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ % d " , countSetBits ( L , R ) ) ; return 0 ; }
Possible values of Q such that , for any value of R , their product is equal to X times their sum | C ++ program for the above approach ; Function to find all possible values of Q ; Vector initialization to store all numbers satisfying the given condition ; Iterate for all the values of X ; Check if condition satisfied then push the number ; Possible value of Q ; Print all the numbers ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void values_of_Q ( int X ) { vector < int > val_Q ; for ( int i = 1 ; i <= X ; i ++ ) { if ( ( ( ( X + i ) * X ) ) % i == 0 ) { val_Q . push_back ( X + i ) ; } } cout << val_Q . size ( ) << endl ; for ( int i = 0 ; i < val_Q . size ( ) ; i ++ ) { cout << val_Q [ i ] << " ▁ " ; } } int main ( ) { int X = 3 ; values_of_Q ( X ) ; return 0 ; }
Program to find Greatest Common Divisor ( GCD ) of N strings | C ++ program for the above approach ; Function that finds gcd of 2 strings ; If str1 length is less than that of str2 then recur with gcd ( str2 , str1 ) ; If str1 is not the concatenation of str2 ; GCD string is found ; Cut off the common prefix part of str1 & then recur ; Function to find GCD of array of strings ; Return the GCD of strings ; Driver Code ; Given array of strings ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string gcd ( string str1 , string str2 ) { if ( str1 . length ( ) < str2 . length ( ) ) { return gcd ( str2 , str1 ) ; } else if ( str1 . find ( str2 ) != 0 ) { return " " ; } else if ( str2 == " " ) { return str1 ; } else { return gcd ( str1 . substr ( str2 . length ( ) ) , str2 ) ; } } string findGCD ( string arr [ ] , int n ) { string result = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { result = gcd ( result , arr [ i ] ) ; } return result ; } int main ( ) { string arr [ ] = { " GFGGFG " , " GFGGFG " , " GFGGFGGFGGFG " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findGCD ( arr , n ) ; }
Check whether the given Matrix is balanced or not | C ++ program for the above approach ; Define size of matrix ; Function to check given matrix balanced or unbalanced ; Flag for check matrix is balanced or unbalanced ; Iterate row until condition is true ; Iterate cols until condition is true ; Check for corner edge elements ; Check for border elements ; Check for the middle ones ; Return balanced or not ; Driver Code ; Given Matrix mat [ ] [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE #define M 4 NEW_LINE string balancedMatrix ( int mat [ ] [ M ] ) { bool is_balanced = true ; for ( int i = 0 ; i < N && is_balanced ; i ++ ) { for ( int j = 0 ; j < M && is_balanced ; j ++ ) { if ( ( i == 0 i == N - 1 ) && ( j == 0 j == M - 1 ) ) { if ( mat [ i ] [ j ] >= 2 ) is_balanced = false ; } else if ( i == 0 i == N - 1 j == 0 j == M - 1 ) { if ( mat [ i ] [ j ] >= 3 ) is_balanced = false ; } else { if ( mat [ i ] [ j ] >= 4 ) is_balanced = false ; } } } if ( is_balanced ) return " Balanced " ; else return " Unbalanced " ; } int main ( ) { int mat [ N ] [ M ] = { { 1 , 2 , 3 , 4 } , { 3 , 5 , 2 , 6 } , { 5 , 3 , 6 , 1 } , { 9 , 5 , 6 , 0 } } ; cout << balancedMatrix ( mat ) ; return 0 ; }
Convert Unix timestamp to DD / MM / YYYY HH : MM : SS format | Unix time is in seconds and Humar Readable Format : DATE : MONTH : YEAR : HOUR : MINUTES : SECONDS , Start of unix time : 01 Jan 1970 , 00 : 00 : 00 ; Function to convert unix time to Human readable format ; Save the time in Human readable format ; Number of days in month in normal year ; Calculate total days unix time T ; Calculating current year ; Updating extradays because it will give days till previous day and we have include current day ; Calculating MONTH and DATE ; Current Month ; Calculating HH : MM : YYYY ; Return the time ; Driver Code ; Given unix time ; Function call to convert unix time to human read able ; Print time in format DD : MM : YYYY : HH : MM : SS
#include <bits/stdc++.h> NEW_LINE using namespace std ; string unixTimeToHumanReadable ( long int seconds ) { string ans = " " ; int daysOfMonth [ ] = { 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } ; long int currYear , daysTillNow , extraTime , extraDays , index , date , month , hours , minutes , secondss , flag = 0 ; daysTillNow = seconds / ( 24 * 60 * 60 ) ; extraTime = seconds % ( 24 * 60 * 60 ) ; currYear = 1970 ; while ( daysTillNow >= 365 ) { if ( currYear % 400 == 0 || ( currYear % 4 == 0 && currYear % 100 != 0 ) ) { daysTillNow -= 366 ; } else { daysTillNow -= 365 ; } currYear += 1 ; } extraDays = daysTillNow + 1 ; if ( currYear % 400 == 0 || ( currYear % 4 == 0 && currYear % 100 != 0 ) ) flag = 1 ; month = 0 , index = 0 ; if ( flag == 1 ) { while ( true ) { if ( index == 1 ) { if ( extraDays - 29 < 0 ) break ; month += 1 ; extraDays -= 29 ; } else { if ( extraDays - daysOfMonth [ index ] < 0 ) { break ; } month += 1 ; extraDays -= daysOfMonth [ index ] ; } index += 1 ; } } else { while ( true ) { if ( extraDays - daysOfMonth [ index ] < 0 ) { break ; } month += 1 ; extraDays -= daysOfMonth [ index ] ; index += 1 ; } } if ( extraDays > 0 ) { month += 1 ; date = extraDays ; } else { if ( month == 2 && flag == 1 ) date = 29 ; else { date = daysOfMonth [ month - 1 ] ; } } hours = extraTime / 3600 ; minutes = ( extraTime % 3600 ) / 60 ; secondss = ( extraTime % 3600 ) % 60 ; ans += to_string ( date ) ; ans += " / " ; ans += to_string ( month ) ; ans += " / " ; ans += to_string ( currYear ) ; ans += " ▁ " ; ans += to_string ( hours ) ; ans += " : " ; ans += to_string ( minutes ) ; ans += " : " ; ans += to_string ( secondss ) ; return ans ; } int main ( ) { long int T = 1595497956 ; string ans = unixTimeToHumanReadable ( T ) ; cout << ans << " STRNEWLINE " ; return 0 ; }
Maximum area of a Rectangle that can be circumscribed about a given Rectangle of size LxW | C ++ program for the above approach ; Function to find area of rectangle inscribed another rectangle of length L and width W ; Area of rectangle ; Return the area ; Driver Code ; Given dimensions ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; double AreaofRectangle ( int L , int W ) { double area = ( W + L ) * ( W + L ) / 2 ; return area ; } int main ( ) { int L = 18 ; int W = 12 ; cout << AreaofRectangle ( L , W ) ; return 0 ; }
Minimum number of operations required to reduce N to 0 | C ++ Program to implement the above approach ; Function to count the minimum steps required to reduce n ; Base case ; Allocate memory for storing intermediate results ; Store base values ; Stores square root of each number ; Compute square root ; Use rule 1 to find optimized answer ; Check if it perfectly divides n ; Use of rule 2 to find the optimized answer ; Store computed value ; Return answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int downToZero ( int n ) { if ( n <= 3 ) return n ; vector < int > dp ( n + 1 , -1 ) ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; dp [ 2 ] = 2 ; dp [ 3 ] = 3 ; int sqr ; for ( int i = 4 ; i <= n ; i ++ ) { sqr = sqrt ( i ) ; int best = INT_MAX ; while ( sqr > 1 ) { if ( i % sqr == 0 ) { best = min ( best , 1 + dp [ sqr ] ) ; } sqr -- ; } best = min ( best , 1 + dp [ i - 1 ] ) ; dp [ i ] = best ; } return dp [ n ] ; } int main ( ) { int n = 4 ; cout << downToZero ( n ) ; return 0 ; }
Minimum number of operations required to reduce N to 0 | C ++ Program to implement the above approach ; Function to find the minimum steps required to reduce n ; Base case ; Return answer based on parity of n ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int downToZero ( int n ) { if ( n <= 3 ) return n ; return n % 2 == 0 ? 3 : 4 ; } int main ( ) { int n = 4 ; cout << downToZero ( n ) ; return 0 ; }
Minimum count of elements required to obtain the given Array by repeated mirror operations | C ++ Program to implement the above approach ; Function to find minimum number of elements required to form A [ ] by performing mirroring operation ; Initialize K ; Odd length array cannot be formed by mirror operation ; Check if prefix of length K is palindrome ; Check if not a palindrome ; If found to be palindrome ; Otherwise ; Return the final answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumrequired ( int A [ ] , int N ) { int K = N ; int ans ; while ( K > 0 ) { if ( K % 2 == 1 ) { ans = K ; break ; } bool ispalindrome = 1 ; for ( int i = 0 ; i < K / 2 ; i ++ ) { if ( A [ i ] != A [ K - 1 - i ] ) ispalindrome = 0 ; } if ( ispalindrome ) { ans = K / 2 ; K /= 2 ; } else { ans = K ; break ; } } return ans ; } int main ( ) { int a [ ] = { 1 , 2 , 2 , 1 , 1 , 2 , 2 , 1 } ; int N = sizeof a / sizeof a [ 0 ] ; cout << minimumrequired ( a , N ) ; return 0 ; }
Sum of product of all integers upto N with their count of divisors | C ++ program for the above approach ; Function to find the sum of the product of all the integers and their positive divisors up to N ; Iterate for every number between 1 and N ; Find the first multiple of i between 1 and N ; Find the last multiple of i between 1 and N ; Find the total count of multiple of in [ 1 , N ] ; Compute the contribution of i using the formula ; Add the contribution of i to the answer ; Return the result ; Driver code ; Given N ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long sumOfFactors ( int N ) { long long ans = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { long long first = i ; long long last = ( N / i ) * i ; long long factors = ( last - first ) / i + 1 ; long long totalContribution = ( ( ( factors ) * ( factors + 1 ) ) / 2 ) * i ; ans += totalContribution ; } return ans ; } int main ( ) { int N = 3 ; cout << sumOfFactors ( N ) ; }
Find a number M < N such that difference between their XOR and AND is maximum | C ++ program for the above approach ; Function to return M < N such that N ^ M - N & M is maximum ; Initialize variables ; Iterate for all values < N ; Find the difference between Bitwise XOR and AND ; Check if new difference is greater than previous maximum ; Update variables ; Return the answer ; Driver Code ; Given Number N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxDifference ( int N ) { int M = -1 ; int maxDiff = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int diff = ( N ^ i ) - ( N & i ) ; if ( diff >= maxDiff ) { maxDiff = diff ; M = i ; } } return M ; } int main ( ) { int N = 6 ; cout << getMaxDifference ( N ) ; return 0 ; }
Find a number M < N such that difference between their XOR and AND is maximum | C ++ program for the above approach ; Function to flip all bits of N ; Finding most significant bit of N ; Calculating required number ; Return the answer ; Driver Code ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findM ( int N ) { int M = 0 ; int MSB = ( int ) log2 ( N ) ; for ( int i = 0 ; i < MSB ; i ++ ) { if ( ! ( N & ( 1 << i ) ) ) M += ( 1 << i ) ; } return M ; } int main ( ) { int N = 6 ; cout << findM ( N ) ; return 0 ; }
Number of containers that can be filled in the given time | C ++ program for the above problem ; matrix of containers ; function to find the number of containers that will be filled in X seconds ; container on top level ; if container gets filled ; dividing the liquid equally in two halves ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; double cont [ 1000 ] [ 1000 ] ; void num_of_containers ( int n , double x ) { int count = 0 ; cont [ 1 ] [ 1 ] = x ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= i ; j ++ ) { if ( cont [ i ] [ j ] >= ( double ) 1 ) { count ++ ; cont [ i + 1 ] [ j ] += ( cont [ i ] [ j ] - ( double ) 1 ) / ( double ) 2 ; cont [ i + 1 ] [ j + 1 ] += ( cont [ i ] [ j ] - ( double ) 1 ) / ( double ) 2 ; } } } cout << count ; } int main ( ) { int n = 3 ; double x = 5 ; num_of_containers ( n , x ) ; return 0 ; }
Check whether there exists a triplet ( i , j , k ) such that arr [ i ] < arr [ k ] < arr [ j ] for i < j < k | C ++ program for the above approach ; Function to check if there exist triplet in the array such that i < j < k and arr [ i ] < arr [ k ] < arr [ j ] ; Initialize the heights of h1 and h2 to INT_MAX and INT_MIN respectively ; Store the current element as h1 ; If the element at top of stack is less than the current element then pop the stack top and keep updating the value of h3 ; Push the current element on the stack ; If current element is less than h3 , then we found such triplet and return true ; No triplet found , hence return false ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findTriplet ( vector < int > & arr ) { int n = arr . size ( ) ; stack < int > st ; int h3 = INT_MIN , h1 = INT_MAX ; for ( int i = n - 1 ; i >= 0 ; i -- ) { h1 = arr [ i ] ; while ( ! st . empty ( ) && st . top ( ) < arr [ i ] ) { h3 = st . top ( ) ; st . pop ( ) ; } st . push ( arr [ i ] ) ; if ( h1 < h3 ) { return true ; } } return false ; } int main ( ) { vector < int > arr = { 4 , 7 , 5 , 6 } ; if ( findTriplet ( arr ) ) { cout << " ▁ Yes " << ' ' ; } else { cout << " ▁ No " << ' ' ; } return 0 ; }
Minimum number of distinct elements after removing M items | Set 2 | C ++ program for the above approach ; Function to return minimum distinct character after M removals ; Count the occurences of number and store in count ; Count the occurences of the frequencies ; Take answer as total unique numbers and remove the frequency and subtract the answer ; Remove the minimum number of times ; Return the answer ; Driver Code ; Initialize array ; Size of array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int distinctNumbers ( int arr [ ] , int m , int n ) { unordered_map < int , int > count ; for ( int i = 0 ; i < n ; i ++ ) count [ arr [ i ] ] ++ ; vector < int > fre_arr ( n + 1 , 0 ) ; for ( auto it : count ) { fre_arr [ it . second ] ++ ; } int ans = count . size ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { int temp = fre_arr [ i ] ; if ( temp == 0 ) continue ; int t = min ( temp , m / i ) ; ans -= t ; m -= i * t ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 4 , 1 , 5 , 3 , 5 , 1 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int m = 2 ; cout << distinctNumbers ( arr , m , n ) ; return 0 ; }
Find minimum moves to bring all elements in one cell of a matrix | C ++ implementation to find the minimum number of moves to bring all non - zero element in one cell of the matrix ; Function to find the minimum number of moves to bring all elements in one cell of matrix ; Moves variable to store the sum of number of moves ; Loop to count the number of the moves ; Condition to check that the current cell is a non - zero element ; Driver Code ; Coordinates of given cell ; Given Matrix ; Element to be moved ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 4 ; const int N = 5 ; void no_of_moves ( int Matrix [ M ] [ N ] , int x , int y ) { int moves = 0 ; for ( int i = 0 ; i < M ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { if ( Matrix [ i ] [ j ] != 0 ) { moves += abs ( x - i ) ; moves += abs ( y - j ) ; } } } cout << moves << " STRNEWLINE " ; } int main ( ) { int x = 3 ; int y = 2 ; int Matrix [ M ] [ N ] = { { 1 , 0 , 1 , 1 , 0 } , { 0 , 1 , 1 , 0 , 1 } , { 0 , 0 , 1 , 1 , 0 } , { 1 , 1 , 1 , 0 , 0 } } ; int num = 1 ; no_of_moves ( Matrix , x , y ) ; return 0 ; }
Check if all array elements can be removed by the given operations | C ++ program to implement the above approach ; Function to check if it is possible to remove all array elements ; Condition if we can remove all elements from the array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void removeAll ( int arr [ ] , int n ) { if ( arr [ 0 ] < arr [ n - 1 ] ) cout << " YES " ; else cout << " NO " ; } int main ( ) { int Arr [ ] = { 10 , 4 , 7 , 1 , 3 , 6 } ; int size = sizeof ( Arr ) / sizeof ( Arr [ 0 ] ) ; removeAll ( Arr , size ) ; return 0 ; }
Smallest subarray having an element with frequency greater than that of other elements | C ++ program for the above approach ; Function to find subarray ; If the array has only one element , then there is no answer . ; Array to store the last occurrences of the elements of the array . ; To maintain the length ; Variables to store start and end indices ; Check if element is occurring for the second time in the array ; Find distance between last and current index of the element . ; If the current distance is less then len update len and set ' start ' and ' end ' ; Set the last occurrence of current element to be ' i ' . ; If flag is equal to 0 , it means there is no answer . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void FindSubarray ( int arr [ ] , int n ) { if ( n == 1 ) { cout << " No ▁ such ▁ subarray ! " << endl ; } int vis [ n + 1 ] ; memset ( vis , -1 , sizeof ( vis ) ) ; vis [ arr [ 0 ] ] = 0 ; int len = INT_MAX , flag = 0 ; int start , end ; for ( int i = 1 ; i < n ; i ++ ) { int t = arr [ i ] ; if ( vis [ t ] != -1 ) { int distance = i - vis [ t ] + 1 ; if ( distance < len ) { len = distance ; start = vis [ t ] ; end = i ; } flag = 1 ; } vis [ t ] = i ; } if ( flag == 0 ) cout << " No ▁ such ▁ subarray ! " << endl ; else { for ( int i = start ; i <= end ; i ++ ) cout << arr [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 2 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; FindSubarray ( arr , n ) ; return 0 ; }
Count substring of Binary string such that each character belongs to a palindrome of size greater than 1 | C ++ implementation to find the substrings in binary string such that every character belongs to a palindrome ; Function to to find the substrings in binary string such that every character belongs to a palindrome ; Total substrings ; Loop to store the count of continious characters in the given string ; Subtract non special strings from answer ; Driver Code ; Given string s ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string s ) { int n = s . length ( ) ; int answer = ( n * ( n - 1 ) ) / 2 ; int cnt = 1 ; vector < int > v ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) cnt ++ ; else { v . push_back ( cnt ) ; cnt = 1 ; } } if ( cnt > 0 ) v . push_back ( cnt ) ; for ( int i = 0 ; i < v . size ( ) - 1 ; i ++ ) { answer -= ( v [ i ] + v [ i + 1 ] - 1 ) ; } return answer ; } int main ( ) { string s = "00111" ; cout << countSubstrings ( s ) ; return 0 ; }
Minimum minutes needed to make the time palindromic | C ++ program for the above approach ; Function to get the required minutes ; Storing hour and minute value in integral form ; Keep iterating till first digit hour becomes equal to second digit of minute and second digit of hour becomes equal to first digit of minute ; If mins is 60 , increase hour , and reinitilialized to 0 ; If hours is 60 , reinitialized to 0 ; Return the required time ; Driver Code ; Given Time as a string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int get_palindrome_time ( string str ) { int hh , mm ; hh = ( str [ 0 ] - 48 ) * 10 + ( str [ 1 ] - 48 ) ; mm = ( str [ 3 ] - 48 ) * 10 + ( str [ 4 ] - 48 ) ; int requiredTime = 0 ; while ( hh % 10 != mm / 10 hh / 10 != mm % 10 ) { ++ mm ; if ( mm == 60 ) { mm = 0 ; ++ hh ; } if ( hh == 24 ) hh = 0 ; ++ requiredTime ; } return requiredTime ; } int main ( ) { string str = "05:39" ; cout << get_palindrome_time ( str ) << endl ; }
Maximum sum of values in a given range of an Array for Q queries when shuffling is allowed | C ++ implementation to find the maximum sum of K subarrays when shuffling is allowed ; Function to find the maximum sum of all subarrays ; Initialize maxsum and prefixArray ; Find the frequency using prefix Array ; Perform prefix sum ; Sort both arrays to get a greedy result ; Finally multiply largest frequency with largest array element . ; Return the answer ; Driver Code ; Initial Array ; Subarrays ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSubarraySum ( int a [ ] , int n , vector < pair < int , int > > & subarrays ) { int i , maxsum = 0 ; int prefixArray [ n ] = { 0 } ; for ( i = 0 ; i < subarrays . size ( ) ; ++ i ) { prefixArray [ subarrays [ i ] . first - 1 ] ++ ; prefixArray [ subarrays [ i ] . second ] -- ; } for ( i = 1 ; i < n ; i ++ ) { prefixArray [ i ] += prefixArray [ i - 1 ] ; } sort ( prefixArray , prefixArray + n , greater < int > ( ) ) ; sort ( a , a + n , greater < int > ( ) ) ; for ( i = 0 ; i < n ; i ++ ) maxsum += a [ i ] * prefixArray [ i ] ; return maxsum ; } int main ( ) { int n = 6 ; int a [ ] = { 4 , 1 , 2 , 1 , 9 , 2 } ; vector < pair < int , int > > subarrays ; subarrays . push_back ( { 1 , 2 } ) ; subarrays . push_back ( { 1 , 3 } ) ; subarrays . push_back ( { 1 , 4 } ) ; subarrays . push_back ( { 3 , 4 } ) ; cout << maximumSubarraySum ( a , n , subarrays ) ; }
Maximum profit such that total stolen value is less than K to get bonus | C ++ implementation to find the maximum stolen value such that total stolen value is less than K ; Function to find the maximum profit from the given values ; Iterating over every possible permutation ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxProfit ( vector < int > value , int N , int K ) { sort ( value . begin ( ) , value . end ( ) ) ; int maxval = value [ N - 1 ] ; int maxProfit = 0 ; int curr_val ; do { curr_val = 0 ; for ( int i = 0 ; i < N ; i ++ ) { curr_val += value [ i ] ; if ( curr_val <= K ) { maxProfit = max ( curr_val + maxval * ( i + 1 ) , maxProfit ) ; } } } while ( next_permutation ( value . begin ( ) , value . end ( ) ) ) ; return maxProfit ; } int main ( ) { int N = 4 , K = 6 ; vector < int > values { 5 , 2 , 7 , 3 } ; cout << maxProfit ( values , N , K ) ; }
Min operations to reduce N by multiplying by any number or taking square root | C ++ program for above approach ; Function to reduce N to its minimum possible value by the given operations ; Keep replacing n until is an integer ; Keep replacing n until n is divisible by i * i ; Print the answer ; Driver Code ; Given N ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minValue ( int n ) { while ( int ( sqrt ( n ) ) == sqrt ( n ) && n > 1 ) { n = sqrt ( n ) ; } for ( int i = sqrt ( n ) ; i > 1 ; i -- ) { while ( n % ( i * i ) == 0 ) n /= i ; } cout << n ; } int main ( ) { int N = 20 ; minValue ( N ) ; }
Count of ways to split given string into two non | C ++ Program to implement the above approach ; Function to check whether the substring from l to r is palindrome or not ; If characters at l and r differ ; Not a palindrome ; If the string is a palindrome ; Function to count and return the number of possible splits ; Stores the count of splits ; Check if the two substrings after the split are palindromic or not ; If both are palindromes ; Print the final count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( int l , int r , string & s ) { while ( l <= r ) { if ( s [ l ] != s [ r ] ) return false ; l ++ ; r -- ; } return true ; } int numWays ( string & s ) { int n = s . length ( ) ; int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( isPalindrome ( 0 , i , s ) && isPalindrome ( i + 1 , n - 1 , s ) ) { ans ++ ; } } return ans ; } int main ( ) { string S = " aaaaa " ; cout << numWays ( S ) ; return 0 ; }
Final direction after visiting every cell of Matrix starting from ( 0 , 0 ) | C ++ program to find the direction when stopped moving ; Function to find the direction when stopped moving ; Driver Code ; Given size of NxM grid ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findDirection ( int n , int m ) { if ( n > m ) { if ( m % 2 == 0 ) printf ( " Up STRNEWLINE " ) ; else printf ( " Down STRNEWLINE " ) ; } else { if ( n % 2 == 0 ) printf ( " Left STRNEWLINE " ) ; else printf ( " Right STRNEWLINE " ) ; } } int main ( ) { int n = 3 , m = 3 ; findDirection ( n , m ) ; return 0 ; }
Maximize the sum of modulus with every Array element | C ++ program to find the maximum sum of modulus with every array element ; Function to return the maximum sum of modulus with every array element ; Sum of array elements ; Return the answer ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxModulosum ( int a [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } return sum - n ; } int main ( ) { int a [ ] = { 3 , 4 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxModulosum ( a , n ) ; return 0 ; }
Minimum jumps required to group all 1 s together in a given Binary string | C ++ Program to find the minimum number of jumps required to group all ones together in the binary string ; Function to get the minimum jump value ; Store all indices of ones ; Populating one 's indices ; Calculate median ; Jumps required for 1 's to the left of median ; Jumps required for 1 's to the right of median ; Return the final answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinJumps ( string s ) { vector < int > ones ; int jumps = 0 , median = 0 , ind = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '1' ) ones . push_back ( i ) ; } if ( ones . size ( ) == 0 ) return jumps ; median = ones [ ones . size ( ) / 2 ] ; ind = median ; for ( int i = ind ; i >= 0 ; i -- ) { if ( s [ i ] == '1' ) { jumps += ind - i ; ind -- ; } } ind = median ; for ( int i = ind ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '1' ) { jumps += i - ind ; ind ++ ; } } return jumps ; } int main ( ) { string S = "00100000010011" ; cout << getMinJumps ( S ) << ' ' ; return 0 ; }
Find GCD of each subtree of a given node in an N | C ++ program to find GCD of each subtree for a given node by Q queries ; Maximum Number of nodes ; Tree represented as adjacency list ; for storing value associates with node ; for storing GCD of every subarray ; number of nodes ; Function to find GCD of two numbers using Euclidean algo ; if b == 0 then simply return a ; DFS function to traverse the tree ; initializing answer with GCD of this node . ; iterate over each child of current node ; skipping the parent ; call DFS for each child ; taking GCD of the answer of the child to find node 's GCD ; Calling DFS from the root ( 1 ) for precomputing answers ; Function to find and print GCD for Q queries ; doing preprocessing ; iterate over each given query ; Driver code ; Tree : 1 ( 2 ) / \ 2 ( 3 ) 3 ( 4 ) / \ 4 ( 8 ) 5 ( 16 ) ; making a undirected tree ; values associated with nodes ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int N = 1e5 + 5 ; vector < vector < int > > v ( N ) ; vector < int > val ( N ) ; vector < int > answer ( N ) ; int n ; int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } void DFS ( int node , int parent ) { answer [ node ] = val [ node ] ; for ( int child : v [ node ] ) { if ( child == parent ) continue ; DFS ( child , node ) ; answer [ node ] = gcd ( answer [ node ] , answer [ child ] ) ; } } void preprocess ( ) { DFS ( 1 , -1 ) ; } void findGCD ( int queries [ ] , int q ) { preprocess ( ) ; for ( int i = 0 ; i < q ; i ++ ) { int GCD = answer [ queries [ i ] ] ; cout << " For ▁ subtree ▁ of ▁ " << queries [ i ] << " , ▁ GCD ▁ = ▁ " << GCD << endl ; } } int main ( ) { n = 5 ; v [ 1 ] . push_back ( 2 ) ; v [ 2 ] . push_back ( 1 ) ; v [ 1 ] . push_back ( 3 ) ; v [ 3 ] . push_back ( 1 ) ; v [ 3 ] . push_back ( 4 ) ; v [ 4 ] . push_back ( 3 ) ; v [ 3 ] . push_back ( 5 ) ; v [ 5 ] . push_back ( 3 ) ; val [ 1 ] = 2 ; val [ 2 ] = 3 ; val [ 3 ] = 4 ; val [ 4 ] = 8 ; val [ 5 ] = 16 ; int queries [ ] = { 2 , 3 , 1 } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; findGCD ( queries , q ) ; return 0 ; }
Minimize cost to convert given two integers to zero using given operations | C ++ implementation to find the minimum cost to make the two integers equal to zero using given operations ; Function to find out the minimum cost to make two number X and Y equal to zero ; If x is greater than y then swap ; Cost of making y equal to x ; Cost if we choose 1 st operation ; Cost if we choose 2 nd operation ; Total cost ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int makeZero ( int x , int y , int a , int b ) { if ( x > y ) x = y , y = x ; int tot_cost = ( y - x ) * a ; int cost1 = 2 * x * a ; int cost2 = x * b ; tot_cost += min ( cost1 , cost2 ) ; cout << tot_cost ; } int main ( ) { int X = 1 , Y = 3 ; int cost1 = 391 , cost2 = 555 ; makeZero ( X , Y , cost1 , cost2 ) ; }
Find N fractions that sum upto a given fraction N / D | C ++ implementation to split the fraction into N parts ; Function to split the fraction into the N parts ; Loop to find the N - 1 fraction ; Loop to print the Fractions ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void splitFraction ( int n , int d ) { int ar [ n ] ; int first = d + n - 1 ; ar [ 0 ] = first ; for ( int i = 1 ; i < n ; i ++ ) { int temp = -- first ; first ++ ; ar [ i ] = first * temp ; -- first ; } for ( int i = 0 ; i < n ; i ++ ) { if ( ar [ i ] % n == 0 ) { cout << "1 / " << ar [ i ] / n << " , ▁ " ; } else { cout << n << " / " << ar [ i ] << " , ▁ " ; } } } int main ( ) { int N = 4 ; int D = 2 ; splitFraction ( N , D ) ; }
Count of pairs ( i , j ) in the array such that arr [ i ] is a factor of arr [ j ] | C ++ Program to find the number of pairs ( i , j ) such that arr [ i ] is a factor of arr [ j ] ; Function to return the count of Pairs ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numPairs ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] % arr [ i ] == 0 ) ans ++ ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 3 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << numPairs ( arr , n ) << endl ; return 0 ; }
Check if array can be converted into strictly decreasing sequence | C ++ implementation to check that array can be converted into a strictly decreasing sequence ; Function to check that array can be converted into a strictly decreasing sequence ; Loop to check that each element is greater than the ( N - index ) ; If element is less than ( N - index ) ; If array can be converted ; Driver Code ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int * arr , int n ) { bool flag = true ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < n - i ) { flag = false ; } } if ( flag ) { return true ; } else { return false ; } } int main ( ) { int arr1 [ ] = { 11 , 11 , 11 , 11 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; if ( check ( arr1 , n1 ) ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } }
Maximum Balanced String Partitions | C ++ program to find a maximum number X , such that a given string can be partitioned into X substrings that are each balanced ; Function to find a maximum number X , such that a given string can be partitioned into X substrings that are each balanced ; If the size of the string is 0 , then answer is zero ; variable that represents the number of ' R ' s and ' L ' s ; To store maximum number of possible partitions ; increment the variable r if the character in the string is ' R ' ; increment the variable l if the character in the string is ' L ' ; if r and l are equal , then increment ans ; Return the required answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int BalancedPartition ( string str , int n ) { if ( n == 0 ) return 0 ; int r = 0 , l = 0 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' R ' ) { r ++ ; } else if ( str [ i ] = ' L ' ) { l ++ ; } if ( r == l ) { ans ++ ; } } return ans ; } int main ( ) { string str = " LLRRRLLRRL " ; int n = str . size ( ) ; cout << BalancedPartition ( str , n ) << endl ; return 0 ; }
Minimize the non | C ++ implementation to minimize the non - zero elements in the array ; Function to minimize the non - zero elements in the given array ; To store the min pos needed ; Loop to iterate over the elements of the given array ; If current position A [ i ] is occupied the we can place A [ i ] , A [ i + 1 ] and A [ i + 2 ] elements together at A [ i + 1 ] if exists . ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOccupiedPosition ( int A [ ] , int n ) { int minPos = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( A [ i ] > 0 ) { ++ minPos ; i += 2 ; } } return minPos ; } int main ( ) { int A [ ] = { 8 , 0 , 7 , 0 , 0 , 6 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minOccupiedPosition ( A , n ) ; return 0 ; }
Find minimum number K such that sum of array after multiplication by K exceed S | C ++ implementation of the approach ; Function to return the minimum value of k that satisfies the given condition ; store sum of array elements ; Calculate the sum after ; return minimum possible K ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimumK ( int a [ ] , int n , int S ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } return ceil ( ( ( S + 1 ) * 1.0 ) / ( sum * 1.0 ) ) ; } int main ( ) { int a [ ] = { 10 , 7 , 8 , 10 , 12 , 19 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int S = 200 ; cout << findMinimumK ( a , n , S ) ; return 0 ; }
Find the largest number smaller than integer N with maximum number of set bits | C ++ implementation to Find the largest number smaller than integer N with maximum number of set bits ; Function to return the largest number less than N ; Iterate through all possible values ; Multiply the number by 2 i times ; Return the final result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNum ( int n ) { int num = 0 ; for ( int i = 0 ; i <= 32 ; i ++ ) { int x = ( 1 << i ) ; if ( ( x - 1 ) <= n ) num = ( 1 << i ) - 1 ; else break ; } return num ; } int main ( ) { int N = 345 ; cout << largestNum ( N ) ; return 0 ; }