text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Pairs with Difference less than K | C ++ code to find count of Pairs with difference less than K . ; to sort the array . ; Keep incrementing result while subsequent elements are within limits . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int a [ ] , int n , int k ) { sort ( a , a + n ) ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int j = i + 1 ; while ( j < n && a [ j ] - a [ i ] < k ) { res ++ ; j ++ ; } } return res ; } int main ( ) { int a [ ] = { 1 , 10 , 4 , 2 } ; int k = 3 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countPairs ( a , n , k ) << endl ; return 0 ; }
Merging two unsorted arrays in sorted order | CPP program to merge two unsorted lists in sorted order ; Function to merge array in sorted order ; Sorting a [ ] and b [ ] ; Merge two sorted arrays into res [ ] ; Merging remaining elements of a [ ] ( if any ) ; Merging remaining elements of b [ ] ( if any ) ; Driver code ; Final merge list
#include <bits/stdc++.h> NEW_LINE using namespace std ; void sortedMerge ( int a [ ] , int b [ ] , int res [ ] , int n , int m ) { sort ( a , a + n ) ; sort ( b , b + m ) ; int i = 0 , j = 0 , k = 0 ; while ( i < n && j < m ) { if ( a [ i ] <= b [ j ] ) { res [ k ] = a [ i ] ; i += 1 ; k += 1 ; } else { res [ k ] = b [ j ] ; j += 1 ; k += 1 ; } } while ( i < n ) { res [ k ] = a [ i ] ; i += 1 ; k += 1 ; } while ( j < m ) { res [ k ] = b [ j ] ; j += 1 ; k += 1 ; } } int main ( ) { int a [ ] = { 10 , 5 , 15 } ; int b [ ] = { 20 , 3 , 2 , 12 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; int res [ n + m ] ; sortedMerge ( a , b , res , n , m ) ; cout << " Sorted ▁ merge ▁ list ▁ : " ; for ( int i = 0 ; i < n + m ; i ++ ) cout << " ▁ " << res [ i ] ; cout << " n " ; return 0 ; }
Maximizing Unique Pairs from two arrays | C ++ implementation of above approach ; Returns count of maximum pairs that caan be formed from a [ ] and b [ ] under given constraints . ; Sorting the first array . ; Sorting the second array . ; To keep track of visited elements of b [ ] ; For every element of a [ ] , find a pair for it and break as soon as a pair is found . ; Increasing the count if a pair is formed . ; Making the corresponding flag array element as 1 indicating the element in the second array element has been used . ; We break the loop to make sure an element of a [ ] is used only once . ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll findMaxPairs ( ll a [ ] , ll b [ ] , ll n , ll k ) { sort ( a , a + n ) ; sort ( b , b + n ) ; bool flag [ n ] ; memset ( flag , false , sizeof ( flag ) ) ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( abs ( a [ i ] - b [ j ] ) <= k && flag [ j ] == false ) { result ++ ; flag [ j ] = true ; break ; } } } return result ; } int main ( ) { ll a [ ] = { 10 , 15 , 20 } , b [ ] = { 17 , 12 , 24 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 3 ; cout << findMaxPairs ( a , b , n , k ) ; return 0 ; }
Maximizing Unique Pairs from two arrays | ; Returns count of maximum pairs that caan be formed from a [ ] and b [ ] under given constraints . ; Sorting the first array . ; Sorting the second array . ; Increasing array pointer of both the first and the second array . ; Increasing array pointer of the second array . ; Increasing array pointer of the first array . ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll findMaxPairs ( ll a [ ] , ll b [ ] , ll n , ll k ) { sort ( a , a + n ) ; sort ( b , b + n ) ; int result = 0 ; for ( int i = 0 , j = 0 ; i < n && j < n ; ) { if ( abs ( a [ i ] - b [ j ] ) <= k ) { result ++ ; i ++ ; j ++ ; } else if ( a [ i ] > b [ j ] ) j ++ ; else i ++ ; } return result ; } int main ( ) { ll a [ ] = { 10 , 15 , 20 } ; ll b [ ] = { 17 , 12 , 24 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 3 ; cout << findMaxPairs ( a , b , n , k ) ; return 0 ; }
Sum of minimum absolute difference of each array element | C ++ implementation to find the sum of minimum absolute difference of each array element ; function to find the sum of minimum absolute difference ; sort the given array ; initialize sum ; min absolute difference for the 1 st array element ; min absolute difference for the last array element ; find min absolute difference for rest of the array elements and add them to sum ; required sum ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfMinAbsDifferences ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int sum = 0 ; sum += abs ( arr [ 0 ] - arr [ 1 ] ) ; sum += abs ( arr [ n - 1 ] - arr [ n - 2 ] ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) sum += min ( abs ( arr [ i ] - arr [ i - 1 ] ) , abs ( arr [ i ] - arr [ i + 1 ] ) ) ; return sum ; } int main ( ) { int arr [ ] = { 5 , 10 , 1 , 4 , 8 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Sum ▁ = ▁ " << sumOfMinAbsDifferences ( arr , n ) ; }
Smallest Difference pair of values between two unsorted Arrays | C ++ Code to find Smallest Difference between two Arrays ; function to calculate Small result between two arrays ; Sort both arrays using sort function ; Initialize result as max value ; Scan Both Arrays upto sizeof of the Arrays ; Move Smaller Value ; return final sma result ; Driver Code ; Input given array A ; Input given array B ; Calculate size of Both arrays ; Call function to print smallest result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSmallestDifference ( int A [ ] , int B [ ] , int m , int n ) { sort ( A , A + m ) ; sort ( B , B + n ) ; int a = 0 , b = 0 ; int result = INT_MAX ; while ( a < m && b < n ) { if ( abs ( A [ a ] - B [ b ] ) < result ) result = abs ( A [ a ] - B [ b ] ) ; if ( A [ a ] < B [ b ] ) a ++ ; else b ++ ; } return result ; } int main ( ) { int A [ ] = { 1 , 2 , 11 , 5 } ; int B [ ] = { 4 , 12 , 19 , 23 , 127 , 235 } ; int m = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int n = sizeof ( B ) / sizeof ( B [ 0 ] ) ; cout << findSmallestDifference ( A , B , m , n ) ; return 0 ; }
Find elements larger than half of the elements in an array | C ++ program to find elements that are larger than half of the elements in array ; Prints elements larger than n / 2 element ; Sort the array in ascending order ; Print last ceil ( n / 2 ) elements ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findLarger ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; for ( int i = n - 1 ; i >= n / 2 ; i -- ) cout << arr [ i ] << " ▁ " ; } int main ( ) { int arr [ ] = { 1 , 3 , 6 , 1 , 0 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findLarger ( arr , n ) ; return 0 ; }
Find the element that appears once in an array where every other element appears twice | ; singleelement function ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int singleelement ( int arr [ ] , int n ) { int low = 0 , high = n - 2 ; int mid ; while ( low <= high ) { mid = ( low + high ) / 2 ; if ( arr [ mid ] == arr [ mid ^ 1 ] ) { low = mid + 1 ; } else { high = mid - 1 ; } } return arr [ low ] ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 4 , 5 , 3 , 4 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sort ( arr , arr + size ) ; cout << singleelement ( arr , size ) ; return 0 ; }
Count triplets with sum smaller than a given value | A Simple C ++ program to count triplets with sum smaller than a given value ; Initialize result ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int arr [ ] , int n , int sum ) { int ans = 0 ; for ( int i = 0 ; i < n - 2 ; i ++ ) { for ( int j = i + 1 ; j < n - 1 ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) if ( arr [ i ] + arr [ j ] + arr [ k ] < sum ) ans ++ ; } } return ans ; } int main ( ) { int arr [ ] = { 5 , 1 , 3 , 4 , 7 } ; int n = sizeof arr / sizeof arr [ 0 ] ; int sum = 12 ; cout << countTriplets ( arr , n , sum ) << endl ; return 0 ; }
Count triplets with sum smaller than a given value | C ++ program to count triplets with sum smaller than a given value ; Sort input array ; Initialize result ; 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 can be total k - j third elements . ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int arr [ ] , int n , int sum ) { sort ( arr , arr + n ) ; int ans = 0 ; 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 { ans += ( k - j ) ; j ++ ; } } } return ans ; } int main ( ) { int arr [ ] = { 5 , 1 , 3 , 4 , 7 } ; int n = sizeof arr / sizeof arr [ 0 ] ; int sum = 12 ; cout << countTriplets ( arr , n , sum ) << endl ; return 0 ; }
Number of unique triplets whose XOR is zero | CPP program to count the number of unique triplets whose XOR is 0 ; function to count the number of unique triplets whose xor is 0 ; To store values that are present ; stores the count of unique triplets ; traverse for all i , j pairs such that j > i ; xor of a [ i ] and a [ j ] ; if xr of two numbers is present , then increase the count ; returns answer ; Driver code to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTriplets ( int a [ ] , int n ) { unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) s . insert ( a [ i ] ) ; int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int xr = a [ i ] ^ a [ j ] ; if ( s . find ( xr ) != s . end ( ) && xr != a [ i ] && xr != a [ j ] ) count ++ ; } } return count / 3 ; } int main ( ) { int a [ ] = { 1 , 3 , 5 , 10 , 14 , 15 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << countTriplets ( a , n ) ; return 0 ; }
Find the Missing Number | ; Function to get the missing number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMissingNo ( int a [ ] , int n ) { int total = ( n + 1 ) * ( n + 2 ) / 2 ; for ( int i = 0 ; i < n ; i ++ ) total -= a [ i ] ; return total ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 5 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int miss = getMissingNo ( arr , n ) ; cout << miss ; }
Find the Missing Number | ; a represents the array n : Number of elements in array a ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMissingNo ( int a [ ] , int n ) { int i , total = 1 ; for ( i = 2 ; i <= ( n + 1 ) ; i ++ ) { total += i ; total -= a [ i - 2 ] ; } return total ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 5 } ; cout << getMissingNo ( arr , sizeof ( arr ) / sizeof ( arr [ 0 ] ) ) ; return 0 ; }
Find the Missing Number | C ++ program to find the missing Number ; getMissingNo takes list as argument ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMissingNo ( int a [ ] , int n ) { int n_elements_sum = n * ( n + 1 ) / 2 ; int sum = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) sum += a [ i ] ; return n_elements_sum - sum ; } int main ( ) { int a [ ] = { 1 , 2 , 4 , 5 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) + 1 ; int miss = getMissingNo ( a , n ) ; cout << ( miss ) ; return 0 ; }
Count number of occurrences ( or frequency ) in a sorted array | C ++ program to count occurrences of an element ; Returns number of times x occurs in arr [ 0. . n - 1 ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOccurrences ( int arr [ ] , int n , int x ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( x == arr [ i ] ) res ++ ; return res ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 2 , 2 , 3 , 4 , 7 , 8 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 2 ; cout << countOccurrences ( arr , n , x ) ; return 0 ; }
Count number of occurrences ( or frequency ) in a sorted array | C ++ program to count occurrences of an element ; A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; Returns number of times x occurs in arr [ 0. . n - 1 ] ; If element is not present ; Count elements on left side . ; Count elements on right side . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySearch ( int arr [ ] , int l , int r , int x ) { if ( r < l ) return -1 ; int mid = l + ( r - l ) / 2 ; if ( arr [ mid ] == x ) return mid ; if ( arr [ mid ] > x ) return binarySearch ( arr , l , mid - 1 , x ) ; return binarySearch ( arr , mid + 1 , r , x ) ; } int countOccurrences ( int arr [ ] , int n , int x ) { int ind = binarySearch ( arr , 0 , n - 1 , x ) ; if ( ind == -1 ) return 0 ; int count = 1 ; int left = ind - 1 ; while ( left >= 0 && arr [ left ] == x ) count ++ , left -- ; int right = ind + 1 ; while ( right < n && arr [ right ] == x ) count ++ , right ++ ; return count ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 2 , 2 , 3 , 4 , 7 , 8 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 2 ; cout << countOccurrences ( arr , n , x ) ; return 0 ; }
Given a sorted array and a number x , find the pair in array whose sum is closest to x | Simple C ++ program to find the pair with sum closest to a given no . ; Prints the pair with sum closest to x ; To store indexes of result pair ; Initialize left and right indexes and difference between pair sum and x ; While there are elements between l and r ; Check if this pair is closer than the closest pair so far ; If this pair has more sum , move to smaller values . ; Move to larger values ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printClosest ( int arr [ ] , int n , int x ) { int res_l , res_r ; int l = 0 , r = n - 1 , diff = INT_MAX ; while ( r > l ) { if ( abs ( arr [ l ] + arr [ r ] - x ) < diff ) { res_l = l ; res_r = r ; diff = abs ( arr [ l ] + arr [ r ] - x ) ; } if ( arr [ l ] + arr [ r ] > x ) r -- ; else l ++ ; } cout << " ▁ The ▁ closest ▁ pair ▁ is ▁ " << arr [ res_l ] << " ▁ and ▁ " << arr [ res_r ] ; } int main ( ) { int arr [ ] = { 10 , 22 , 28 , 29 , 30 , 40 } , x = 54 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printClosest ( arr , n , x ) ; return 0 ; }
Count 1 's in a sorted binary array | C ++ program to count one 's in a boolean array ; Returns counts of 1 's in arr[low..high]. The array is assumed to be sorted in non-increasing order ; get the middle index ; check if the element at middle index is last 1 ; If element is not last 1 , recur for right side ; else recur for left side ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOnes ( bool arr [ ] , int low , int high ) { if ( high >= low ) { int mid = low + ( high - low ) / 2 ; if ( ( mid == high arr [ mid + 1 ] == 0 ) && ( arr [ mid ] == 1 ) ) return mid + 1 ; if ( arr [ mid ] == 1 ) return countOnes ( arr , ( mid + 1 ) , high ) ; return countOnes ( arr , low , ( mid - 1 ) ) ; } return 0 ; } int main ( ) { bool arr [ ] = { 1 , 1 , 1 , 1 , 0 , 0 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Count ▁ of ▁ 1 ' s ▁ in ▁ given ▁ array ▁ is ▁ " << countOnes ( arr , 0 , n - 1 ) ; return 0 ; }
Count 1 's in a sorted binary array | ; Returns counts of 1 's in arr[low..high]. The array is assumed to be sorted in non-increasing order ; get the middle index ; else recur for left side ; If element is not last 1 , recur for right side ; check if the element at middle index is last 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOnes ( bool arr [ ] , int n ) { int ans ; int low = 0 , high = n - 1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( arr [ mid ] < 1 ) high = mid - 1 ; else if ( arr [ mid ] > 1 ) low = mid + 1 ; else { if ( mid == n - 1 arr [ mid + 1 ] != 1 ) return mid + 1 ; else low = mid + 1 ; } } } int main ( ) { bool arr [ ] = { 1 , 1 , 1 , 1 , 0 , 0 , 0 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Count ▁ of ▁ 1 ' s ▁ in ▁ given ▁ array ▁ is ▁ " << countOnes ( arr , n ) ; return 0 ; }
Find lost element from a duplicated array | C ++ program to find missing element from same arrays ( except one missing element ) ; Function to find missing element based on binary search approach . arr1 [ ] is of larger size and N is size of it . arr1 [ ] and arr2 [ ] are assumed to be in same order . ; special case , for only element which is missing in second array ; special case , for first element missing ; Initialize current corner points ; loop until lo < hi ; If element at mid indices are equal then go to right subarray ; if lo , hi becomes contiguous , break ; missing element will be at hi index of bigger array ; This function mainly does basic error checking and calls findMissingUtil ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMissingUtil ( int arr1 [ ] , int arr2 [ ] , int N ) { if ( N == 1 ) return arr1 [ 0 ] ; if ( arr1 [ 0 ] != arr2 [ 0 ] ) return arr1 [ 0 ] ; int lo = 0 , hi = N - 1 ; while ( lo < hi ) { int mid = ( lo + hi ) / 2 ; if ( arr1 [ mid ] == arr2 [ mid ] ) lo = mid ; else hi = mid ; if ( lo == hi - 1 ) break ; } return arr1 [ hi ] ; } void findMissing ( int arr1 [ ] , int arr2 [ ] , int M , int N ) { if ( N == M - 1 ) cout << " Missing ▁ Element ▁ is ▁ " << findMissingUtil ( arr1 , arr2 , M ) << endl ; else if ( M == N - 1 ) cout << " Missing ▁ Element ▁ is ▁ " << findMissingUtil ( arr2 , arr1 , N ) << endl ; else cout << " Invalid ▁ Input " ; } int main ( ) { int arr1 [ ] = { 1 , 4 , 5 , 7 , 9 } ; int arr2 [ ] = { 4 , 5 , 7 , 9 } ; int M = sizeof ( arr1 ) / sizeof ( int ) ; int N = sizeof ( arr2 ) / sizeof ( int ) ; findMissing ( arr1 , arr2 , M , N ) ; return 0 ; }
Find lost element from a duplicated array | C ++ program to find missing element from one array such that it has all elements of other array except one . Elements in two arrays can be in any order . ; This function mainly does XOR of all elements of arr1 [ ] and arr2 [ ] ; Do XOR of all element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMissing ( int arr1 [ ] , int arr2 [ ] , int M , int N ) { if ( M != N - 1 && N != M - 1 ) { cout << " Invalid ▁ Input " ; return ; } int res = 0 ; for ( int i = 0 ; i < M ; i ++ ) res = res ^ arr1 [ i ] ; for ( int i = 0 ; i < N ; i ++ ) res = res ^ arr2 [ i ] ; cout << " Missing ▁ element ▁ is ▁ " << res ; } int main ( ) { int arr1 [ ] = { 4 , 1 , 5 , 9 , 7 } ; int arr2 [ ] = { 7 , 5 , 9 , 4 } ; int M = sizeof ( arr1 ) / sizeof ( int ) ; int N = sizeof ( arr2 ) / sizeof ( int ) ; findMissing ( arr1 , arr2 , M , N ) ; return 0 ; }
Find the repeating and the missing | Added 3 new methods | C ++ program to Find the repeating and missing elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printTwoElements ( int arr [ ] , int size ) { int i ; cout << " ▁ The ▁ repeating ▁ element ▁ is ▁ " ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ abs ( arr [ i ] ) - 1 ] > 0 ) arr [ abs ( arr [ i ] ) - 1 ] = - arr [ abs ( arr [ i ] ) - 1 ] ; else cout << abs ( arr [ i ] ) << " STRNEWLINE " ; } cout << " and ▁ the ▁ missing ▁ element ▁ is ▁ " ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ i ] > 0 ) cout << ( i + 1 ) ; } } int main ( ) { int arr [ ] = { 7 , 3 , 4 , 5 , 5 , 6 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printTwoElements ( arr , n ) ; }
Find the repeating and the missing | Added 3 new methods | C ++ program to Find the repeating and missing elements ; The output of this function is stored at * x and * y ; Will hold xor of all elements and numbers from 1 to n ; Will have only single set bit of xor1 ; Get the xor of all array elements ; XOR the previous result with numbers from 1 to n ; Get the rightmost set bit in set_bit_no ; Now divide elements into two sets by comparing a rightmost set bit of xor1 with the bit at the same position in each element . Also , get XORs of two sets . The two XORs are the output elements . The following two for loops serve the purpose ; arr [ i ] belongs to first set ; arr [ i ] belongs to second set ; i belongs to first set ; i belongs to second set ; * x and * y hold the desired output elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void getTwoElements ( int arr [ ] , int n , int * x , int * y ) { int xor1 ; int set_bit_no ; int i ; * x = 0 ; * y = 0 ; xor1 = arr [ 0 ] ; for ( i = 1 ; i < n ; i ++ ) xor1 = xor1 ^ arr [ i ] ; for ( i = 1 ; i <= n ; i ++ ) xor1 = xor1 ^ i ; set_bit_no = xor1 & ~ ( xor1 - 1 ) ; for ( i = 0 ; i < n ; i ++ ) { if ( arr [ i ] & set_bit_no ) * x = * x ^ arr [ i ] ; else * y = * y ^ arr [ i ] ; } for ( i = 1 ; i <= n ; i ++ ) { if ( i & set_bit_no ) * x = * x ^ i ; else * y = * y ^ i ; } } int main ( ) { int arr [ ] = { 1 , 3 , 4 , 5 , 5 , 6 , 2 } ; int * x = ( int * ) malloc ( sizeof ( int ) ) ; int * y = ( int * ) malloc ( sizeof ( int ) ) ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; getTwoElements ( arr , n , x , y ) ; cout << " ▁ The ▁ missing ▁ element ▁ is ▁ " << * x << " ▁ and ▁ the ▁ repeating " << " ▁ number ▁ is ▁ " << * y ; getchar ( ) ; }
Find the repeating and the missing | Added 3 new methods | C ++ program to find the repeating and missing elements using Maps
#include <iostream> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; int main ( ) { int arr [ ] = { 4 , 3 , 6 , 2 , 1 , 1 } ; int n = 6 ; unordered_map < int , bool > numberMap ; for ( int i : arr ) { if ( numberMap . find ( i ) == numberMap . end ( ) ) { numberMap [ i ] = true ; } else { cout << " Repeating ▁ = ▁ " << i ; } } cout << endl ; for ( int i = 1 ; i <= n ; i ++ ) { if ( numberMap . find ( i ) == numberMap . end ( ) ) { cout << " Missing ▁ = ▁ " << i ; } } return 0 ; }
Find four elements that sum to a given value | Set 1 ( n ^ 3 solution ) | C ++ program for naive solution to print all combination of 4 elements in A [ ] with sum equal to X ; A naive solution to print all combination of 4 elements in A [ ] with sum equal to X ; Fix the first element and find other three ; Fix the second element and find other two ; Fix the third element and find the fourth ; find the fourth ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findFourElements ( int A [ ] , int n , int X ) { for ( int i = 0 ; i < n - 3 ; i ++ ) { for ( int j = i + 1 ; j < n - 2 ; j ++ ) { for ( int k = j + 1 ; k < n - 1 ; k ++ ) { for ( int l = k + 1 ; l < n ; l ++ ) if ( A [ i ] + A [ j ] + A [ k ] + A [ l ] == X ) cout << A [ i ] << " , ▁ " << A [ j ] << " , ▁ " << A [ k ] << " , ▁ " << A [ l ] ; } } } } int main ( ) { int A [ ] = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int X = 91 ; findFourElements ( A , n , X ) ; return 0 ; }
Find four elements that sum to a given value | Set 2 | C ++ program to find 4 elements with given sum ; The following structure is needed to store pair sums in aux [ ] ; index ( int A [ ] ) of first element in pair ; index of second element in pair ; sum of the pair ; Following function is needed for library function qsort ( ) ; Function to check if two given pairs have any common element or not ; The function finds four elements with given sum X ; Create an auxiliary array to store all pair sums ; Generate all possible pairs from A [ ] and store sums of all possible pairs in aux [ ] ; Sort the aux [ ] array using library function for sorting ; Now start two index variables from two corners of array and move them toward each other . ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; class pairSum { public : int first ; int sec ; int sum ; } ; int compare ( const void * a , const void * b ) { return ( ( * ( pairSum * ) a ) . sum - ( * ( pairSum * ) b ) . sum ) ; } bool noCommon ( pairSum a , pairSum b ) { if ( a . first == b . first a . first == b . sec a . sec == b . first a . sec == b . sec ) return false ; return true ; } void findFourElements ( int arr [ ] , int n , int X ) { int i , j ; int size = ( n * ( n - 1 ) ) / 2 ; pairSum aux [ size ] ; int k = 0 ; for ( i = 0 ; i < n - 1 ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { aux [ k ] . sum = arr [ i ] + arr [ j ] ; aux [ k ] . first = i ; aux [ k ] . sec = j ; k ++ ; } } qsort ( aux , size , sizeof ( aux [ 0 ] ) , compare ) ; i = 0 ; j = size - 1 ; while ( i < size && j >= 0 ) { if ( ( aux [ i ] . sum + aux [ j ] . sum == X ) && noCommon ( aux [ i ] , aux [ j ] ) ) { cout << arr [ aux [ i ] . first ] << " , ▁ " << arr [ aux [ i ] . sec ] << " , ▁ " << arr [ aux [ j ] . first ] << " , ▁ " << arr [ aux [ j ] . sec ] << endl ; return ; } else if ( aux [ i ] . sum + aux [ j ] . sum < X ) i ++ ; else j -- ; } } int main ( ) { int arr [ ] = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 91 ; findFourElements ( arr , n , X ) ; return 0 ; }
Find four elements that sum to a given value | Set 2 | A hashing based CPP program to find if there are four elements with given sum . ; The function finds four elements with given sum X ; Store sums of all pairs in a hash table ; Traverse through all pairs and search for X - ( current pair sum ) . ; If X - sum is present in hash table , ; Making sure that all elements are distinct array elements and an element is not considered more than once . ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findFourElements ( int arr [ ] , int n , int X ) { unordered_map < int , pair < int , int > > mp ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) mp [ arr [ i ] + arr [ j ] ] = { i , j } ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int sum = arr [ i ] + arr [ j ] ; if ( mp . find ( X - sum ) != mp . end ( ) ) { pair < int , int > p = mp [ X - sum ] ; if ( p . first != i && p . first != j && p . second != i && p . second != j ) { cout << arr [ i ] << " , ▁ " << arr [ j ] << " , ▁ " << arr [ p . first ] << " , ▁ " << arr [ p . second ] ; return ; } } } } } int main ( ) { int arr [ ] = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 91 ; findFourElements ( arr , n , X ) ; return 0 ; }
Find four elements that sum to a given value | Set 2 | C ++ program to find four elements with the given sum ; Function to find 4 elements that add up to given sum ; Iterate from 0 to temp . length ; Iterate from 0 to arr . length ; Iterate from i + 1 to arr . length ; Store curr_sum = arr [ i ] + arr [ j ] ; Check if X - curr_sum if present in map ; Store pair having map value X - curr_sum ; Print the output ; Program for two Sum ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void fourSum ( int X , int arr [ ] , map < int , pair < int , int > > Map , int N ) { int temp [ N ] ; for ( int i = 0 ; i < N ; i ++ ) temp [ i ] = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { int curr_sum = arr [ i ] + arr [ j ] ; if ( Map . find ( X - curr_sum ) != Map . end ( ) ) { pair < int , int > p = Map [ X - curr_sum ] ; if ( p . first != i && p . second != i && p . first != j && p . second != j && temp [ p . first ] == 0 && temp [ p . second ] == 0 && temp [ i ] == 0 && temp [ j ] == 0 ) { cout << arr [ i ] << " , " << arr [ j ] << " , " << arr [ p . first ] << " , " << arr [ p . second ] ; temp [ p . second ] = 1 ; temp [ i ] = 1 ; temp [ j ] = 1 ; break ; } } } } } map < int , pair < int , int > > twoSum ( int nums [ ] , int N ) { map < int , pair < int , int > > Map ; for ( int i = 0 ; i < N - 1 ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { Map [ nums [ i ] + nums [ j ] ] . first = i ; Map [ nums [ i ] + nums [ j ] ] . second = j ; } } return Map ; } int main ( ) { int arr [ ] = { 10 , 20 , 30 , 40 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 91 ; map < int , pair < int , int > > Map = twoSum ( arr , n ) ; fourSum ( X , arr , Map , n ) ; return 0 ; }
Search an element in an array where difference between adjacent elements is 1 | C ++ program to search an element in an array where difference between all elements is 1 ; x is the element to be searched in arr [ 0. . n - 1 ] ; Traverse the given array starting from leftmost element ; If x is found at index i ; Jump the difference between current array element and x ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int search ( int arr [ ] , int n , int x ) { int i = 0 ; while ( i < n ) { if ( arr [ i ] == x ) return i ; i = i + abs ( arr [ i ] - x ) ; } cout << " number ▁ is ▁ not ▁ present ! " ; return -1 ; } int main ( ) { int arr [ ] = { 8 , 7 , 6 , 7 , 6 , 5 , 4 , 3 , 2 , 3 , 4 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 3 ; cout << " Element ▁ " << x << " ▁ is ▁ present ▁ at ▁ index ▁ " << search ( arr , n , 3 ) ; return 0 ; }
Third largest element in an array of distinct elements | C ++ program to find third Largest element in an array of distinct elements ; There should be atleast three elements ; Find first largest element ; Find second largest element ; Find third largest element ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE void thirdLargest ( int arr [ ] , int arr_size ) { if ( arr_size < 3 ) { printf ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } int first = arr [ 0 ] ; for ( int i = 1 ; i < arr_size ; i ++ ) if ( arr [ i ] > first ) first = arr [ i ] ; int second = INT_MIN ; for ( int i = 0 ; i < arr_size ; i ++ ) if ( arr [ i ] > second && arr [ i ] < first ) second = arr [ i ] ; int third = INT_MIN ; for ( int i = 0 ; i < arr_size ; i ++ ) if ( arr [ i ] > third && arr [ i ] < second ) third = arr [ i ] ; printf ( " The ▁ third ▁ Largest ▁ element ▁ is ▁ % d STRNEWLINE " , third ) ; } int main ( ) { int arr [ ] = { 12 , 13 , 1 , 10 , 34 , 16 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; thirdLargest ( arr , n ) ; return 0 ; }
Third largest element in an array of distinct elements | C ++ program to find third Largest element in an array ; There should be atleast three elements ; Initialize first , second and third Largest element ; Traverse array elements to find the third Largest ; If current element is greater than first , then update first , second and third ; If arr [ i ] is in between first and second ; If arr [ i ] is in between second and third ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE void thirdLargest ( int arr [ ] , int arr_size ) { if ( arr_size < 3 ) { printf ( " ▁ Invalid ▁ Input ▁ " ) ; return ; } int first = arr [ 0 ] , second = INT_MIN , third = INT_MIN ; for ( int i = 1 ; i < arr_size ; i ++ ) { if ( arr [ i ] > first ) { third = second ; second = first ; first = arr [ i ] ; } else if ( arr [ i ] > second ) { third = second ; second = arr [ i ] ; } else if ( arr [ i ] > third ) third = arr [ i ] ; } printf ( " The ▁ third ▁ Largest ▁ element ▁ is ▁ % d STRNEWLINE " , third ) ; } int main ( ) { int arr [ ] = { 12 , 13 , 1 , 10 , 34 , 16 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; thirdLargest ( arr , n ) ; return 0 ; }
Check if there exist two elements in an array whose sum is equal to the sum of rest of the array | C ++ program to find whether two elements exist whose sum is equal to sum of rest of the elements . ; Function to check whether two elements exist whose sum is equal to sum of rest of the elements . ; Find sum of whole array ; If sum of array is not even than we can not divide it into two part ; For each element arr [ i ] , see if there is another element with vaalue sum - arr [ i ] ; If element exist than return the pair ; Driver program .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPair ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; if ( sum % 2 != 0 ) return false ; sum = sum / 2 ; unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) { int val = sum - arr [ i ] ; if ( s . find ( val ) != s . end ( ) ) { printf ( " Pair ▁ elements ▁ are ▁ % d ▁ and ▁ % d STRNEWLINE " , arr [ i ] , val ) ; return true ; } s . insert ( arr [ i ] ) ; } return false ; } int main ( ) { int arr [ ] = { 2 , 11 , 5 , 1 , 4 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkPair ( arr , n ) == false ) printf ( " No ▁ pair ▁ found " ) ; return 0 ; }
Search an element in an unsorted array using minimum number of comparisons | C ++ implementation to search an element in the unsorted array using minimum number of comparisons ; function to search an element in minimum number of comparisons ; 1 st comparison ; no termination condition and thus no comparison ; this would be executed at - most n times and therefore at - most n comparisons ; replace arr [ n - 1 ] with its actual element as in original ' arr [ ] ' ; if ' x ' is found before the ' ( n - 1 ) th ' index , then it is present in the array final comparison ; else not present in the array ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; string search ( int arr [ ] , int n , int x ) { if ( arr [ n - 1 ] == x ) return " Found " ; int backup = arr [ n - 1 ] ; arr [ n - 1 ] = x ; for ( int i = 0 ; ; i ++ ) { if ( arr [ i ] == x ) { arr [ n - 1 ] = backup ; if ( i < n - 1 ) return " Found " ; return " Not ▁ Found " ; } } } int main ( ) { int arr [ ] = { 4 , 6 , 1 , 5 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 1 ; cout << search ( arr , n , x ) ; return 0 ; }
Count of only repeated element in a sorted array of consecutive elements | C ++ program to find the only repeated element and number of times it appears ; Assumptions : vector a is sorted , max - difference of two adjacent elements is 1 ; if a [ m ] = m + a [ 0 ] , there is no repeating character in [ s . . m ] ; if a [ m ] < m + a [ 0 ] , there is a repeating character in [ s . . m ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , int > sequence ( const vector < int > & a ) { if ( a . size ( ) == 0 ) return { 0 , 0 } ; int s = 0 ; int e = a . size ( ) - 1 ; while ( s < e ) { int m = ( s + e ) / 2 ; if ( a [ m ] >= m + a [ 0 ] ) s = m + 1 ; else e = m ; } return { a [ s ] , a . size ( ) - ( a [ a . size ( ) - 1 ] - a [ 0 ] ) } ; } int main ( ) { pair < int , int > p = sequence ( { 1 , 2 , 3 , 4 , 4 , 4 , 5 , 6 } ) ; cout << " Repeated ▁ element ▁ is ▁ " << p . first << " , ▁ it ▁ appears ▁ " << p . second << " ▁ times " ; return 0 ; }
Find element in a sorted array whose frequency is greater than or equal to n / 2. | C ++ code to find majority element in a sorted array ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int findMajority ( int arr [ ] , int n ) { return arr [ n / 2 ] ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMajority ( arr , n ) ; return 0 ; }
Minimum absolute difference of adjacent elements in a circular array | C ++ program to find maximum difference between adjacent elements in a circular array . ; Checking normal adjacent elements ; Checking circular link ; driver program to check the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minAdjDifference ( int arr [ ] , int n ) { if ( n < 2 ) return ; int res = abs ( arr [ 1 ] - arr [ 0 ] ) ; for ( int i = 2 ; i < n ; i ++ ) res = min ( res , abs ( arr [ i ] - arr [ i - 1 ] ) ) ; res = min ( res , abs ( arr [ n - 1 ] - arr [ 0 ] ) ) ; cout << " Min ▁ Difference ▁ = ▁ " << res ; } int main ( ) { int a [ ] = { 10 , 12 , 13 , 15 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; minAdjDifference ( a , n ) ; return 0 ; }
Find the first , second and third minimum elements in an array | CPP program to find the first , second and third minimum element in an array ; Check if current element is less than firstmin , then update first , second and third ; Check if current element is less than secmin then update second and third ; Check if current element is less than then update third ; Driver code
#include <bits/stdc++.h> NEW_LINE #define MAX 100000 NEW_LINE using namespace std ; int Print3Smallest ( int array [ ] , int n ) { int firstmin = MAX , secmin = MAX , thirdmin = MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( array [ i ] < firstmin ) { thirdmin = secmin ; secmin = firstmin ; firstmin = array [ i ] ; } else if ( array [ i ] < secmin ) { thirdmin = secmin ; secmin = array [ i ] ; } else if ( array [ i ] < thirdmin ) thirdmin = array [ i ] ; } cout << " First ▁ min ▁ = ▁ " << firstmin << " STRNEWLINE " ; cout << " Second ▁ min ▁ = ▁ " << secmin << " STRNEWLINE " ; cout << " Third ▁ min ▁ = ▁ " << thirdmin << " STRNEWLINE " ; } int main ( ) { int array [ ] = { 4 , 9 , 1 , 32 , 12 } ; int n = sizeof ( array ) / sizeof ( array [ 0 ] ) ; Print3Smallest ( array , n ) ; return 0 ; }
Program to find the minimum ( or maximum ) element of an array | CPP program to find minimum ( or maximum ) element in an array . ; If there is single element , return it . Else return minimum of first element and minimum of remaining array . ; If there is single element , return it . Else return maximum of first element and maximum of remaining array . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMin ( int arr [ ] , int n ) { return ( n == 1 ) ? arr [ 0 ] : min ( arr [ 0 ] , getMin ( arr + 1 , n - 1 ) ) ; } int getMax ( int arr [ ] , int n ) { return ( n == 1 ) ? arr [ 0 ] : max ( arr [ 0 ] , getMax ( arr + 1 , n - 1 ) ) ; } int main ( ) { int arr [ ] = { 12 , 1234 , 45 , 67 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ element ▁ of ▁ array : ▁ " << getMin ( arr , n ) << " STRNEWLINE " ; cout << " Maximum ▁ element ▁ of ▁ array : ▁ " << getMax ( arr , n ) ; return 0 ; }
Program to find the minimum ( or maximum ) element of an array | CPP program to find minimum ( or maximum ) element in an array . ; C ++ program to find minimum ( or maximum ) element in an array . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMin ( int arr [ ] , int n ) { return * min_element ( arr , arr + n ) ; } int getMax ( int arr [ ] , int n ) { return * max_element ( arr , arr + n ) ; } int main ( ) { int arr [ ] = { 12 , 1234 , 45 , 67 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ element ▁ of ▁ array : ▁ " << getMin ( arr , n ) << " STRNEWLINE " ; cout << " Maximum ▁ element ▁ of ▁ array : ▁ " << getMax ( arr , n ) ; return 0 ; }
Closest greater element for every array element from another array | CPP to find result from target array for closest element ; Function for printing resultant array ; change arr [ ] to vector ; sort vector for ease ; iterator for upper_bound ; vector for result ; calculate resultant array ; check upper bound element ; if no element found push - 1 ; Else push the element ; add to resultant ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void closestResult ( int a [ ] , int b [ ] , int n ) { vector < int > vect ( a , a + n ) ; sort ( vect . begin ( ) , vect . end ( ) ) ; vector < int > :: iterator up ; vector < int > c ; for ( int i = 0 ; i < n ; i ++ ) { up = upper_bound ( vect . begin ( ) , vect . end ( ) , b [ i ] ) ; if ( up == vect . end ( ) ) c . push_back ( -1 ) ; else c . push_back ( * up ) ; } cout << " Result ▁ = ▁ " ; for ( auto it = c . begin ( ) ; it != c . end ( ) ; it ++ ) cout << * it << " ▁ " ; } int main ( ) { int a [ ] = { 2 , 5 , 6 , 1 , 8 , 9 } ; int b [ ] = { 2 , 1 , 0 , 5 , 4 , 9 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; closestResult ( a , b , n ) ; return 0 ; }
Count frequencies of all elements in array in O ( 1 ) extra space and O ( n ) time | C ++ program to print frequencies of all array elements in O ( n ) extra space and O ( n ) time ; Function to find counts of all elements present in arr [ 0. . n - 1 ] . The array elements must be range from 1 to n ; Hashmap ; Traverse all array elements ; update the frequency of array [ i ] ; increase the index ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findCounts ( int * arr , int n ) { int hash [ n ] = { 0 } ; int i = 0 ; while ( i < n ) { hash [ arr [ i ] - 1 ] ++ ; i ++ ; } printf ( " Below are counts of all elements " for ( int i = 0 ; i < n ; i ++ ) printf ( " % d ▁ - > ▁ % d STRNEWLINE " , i + 1 , hash [ i ] ) ; } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 2 , 5 } ; findCounts ( arr , sizeof ( arr ) / sizeof ( arr [ 0 ] ) ) ; int arr1 [ ] = { 1 } ; findCounts ( arr1 , sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ) ; int arr3 [ ] = { 4 , 4 , 4 , 4 } ; findCounts ( arr3 , sizeof ( arr3 ) / sizeof ( arr3 [ 0 ] ) ) ; int arr2 [ ] = { 1 , 3 , 5 , 7 , 9 , 1 , 3 , 5 , 7 , 9 , 1 } ; findCounts ( arr2 , sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ) ; int arr4 [ ] = { 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 } ; findCounts ( arr4 , sizeof ( arr4 ) / sizeof ( arr4 [ 0 ] ) ) ; int arr5 [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 } ; findCounts ( arr5 , sizeof ( arr5 ) / sizeof ( arr5 [ 0 ] ) ) ; int arr6 [ ] = { 11 , 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 } ; findCounts ( arr6 , sizeof ( arr6 ) / sizeof ( arr6 [ 0 ] ) ) ; return 0 ; }
Count frequencies of all elements in array in O ( 1 ) extra space and O ( n ) time | C ++ program to print frequencies of all array elements in O ( 1 ) extra space and O ( n ) time ; Function to find counts of all elements present in arr [ 0. . n - 1 ] . The array elements must be range from 1 to n ; Traverse all array elements ; If this element is already processed , then nothing to do ; Find index corresponding to this element For example , index for 5 is 4 ; If the elementIndex has an element that is not processed yet , then first store that element to arr [ i ] so that we don 't lose anything. ; After storing arr [ elementIndex ] , change it to store initial count of ' arr [ i ] ' ; If this is NOT first occurrence of arr [ i ] , then decrement its count . ; And initialize arr [ i ] as 0 means the element ' i + 1' is not seen so far ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findCounts ( int * arr , int n ) { int i = 0 ; while ( i < n ) { if ( arr [ i ] <= 0 ) { i ++ ; continue ; } int elementIndex = arr [ i ] - 1 ; if ( arr [ elementIndex ] > 0 ) { arr [ i ] = arr [ elementIndex ] ; arr [ elementIndex ] = -1 ; } else { arr [ elementIndex ] -- ; arr [ i ] = 0 ; i ++ ; } } printf ( " Below are counts of all elements " for ( int i = 0 ; i < n ; i ++ ) printf ( " % d ▁ - > ▁ % d STRNEWLINE " , i + 1 , abs ( arr [ i ] ) ) ; } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 2 , 5 } ; findCounts ( arr , sizeof ( arr ) / sizeof ( arr [ 0 ] ) ) ; int arr1 [ ] = { 1 } ; findCounts ( arr1 , sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ) ; int arr3 [ ] = { 4 , 4 , 4 , 4 } ; findCounts ( arr3 , sizeof ( arr3 ) / sizeof ( arr3 [ 0 ] ) ) ; int arr2 [ ] = { 1 , 3 , 5 , 7 , 9 , 1 , 3 , 5 , 7 , 9 , 1 } ; findCounts ( arr2 , sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ) ; int arr4 [ ] = { 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 , 3 } ; findCounts ( arr4 , sizeof ( arr4 ) / sizeof ( arr4 [ 0 ] ) ) ; int arr5 [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 } ; findCounts ( arr5 , sizeof ( arr5 ) / sizeof ( arr5 [ 0 ] ) ) ; int arr6 [ ] = { 11 , 10 , 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 } ; findCounts ( arr6 , sizeof ( arr6 ) / sizeof ( arr6 [ 0 ] ) ) ; return 0 ; }
Count frequencies of all elements in array in O ( 1 ) extra space and O ( n ) time | C ++ program to print frequencies of all array elements in O ( 1 ) extra space and O ( n ) time ; Function to find counts of all elements present in arr [ 0. . n - 1 ] . The array elements must be range from 1 to n ; Subtract 1 from every element so that the elements become in range from 0 to n - 1 ; Use every element arr [ i ] as index and add ' n ' to element present at arr [ i ] % n to keep track of count of occurrences of arr [ i ] ; To print counts , simply print the number of times n was added at index corresponding to every element ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printfrequency ( int arr [ ] , int n ) { for ( int j = 0 ; j < n ; j ++ ) arr [ j ] = arr [ j ] - 1 ; for ( int i = 0 ; i < n ; i ++ ) arr [ arr [ i ] % n ] = arr [ arr [ i ] % n ] + n ; for ( int i = 0 ; i < n ; i ++ ) cout << i + 1 << " ▁ - > ▁ " << arr [ i ] / n << endl ; } int main ( ) { int arr [ ] = { 2 , 3 , 3 , 2 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printfrequency ( arr , n ) ; return 0 ; }
Delete an element from array ( Using two traversals and one traversal ) | C ++ program to remove a given element from an array ; This function removes an element x from arr [ ] and returns new size after removal ( size is reduced only when x is present in arr [ ] ; Search x in array ; If x found in array ; reduce size of array and move all elements on space ahead ; Driver program to test above function ; Delete x from arr [ ]
#include <bits/stdc++.h> NEW_LINE using namespace std ; int deleteElement ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n ; i ++ ) if ( arr [ i ] == x ) break ; if ( i < n ) { n = n - 1 ; for ( int j = i ; j < n ; j ++ ) arr [ j ] = arr [ j + 1 ] ; } return n ; } int main ( ) { int arr [ ] = { 11 , 15 , 6 , 8 , 9 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 6 ; n = deleteElement ( arr , n , x ) ; cout << " Modified ▁ array ▁ is ▁ STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Delete an element from array ( Using two traversals and one traversal ) | C ++ program to remove a given element from an array ; This function removes an element x from arr [ ] and returns new size after removal . Returned size is n - 1 when element is present . Otherwise 0 is returned to indicate failure . ; If x is last element , nothing to do ; Start from rightmost element and keep moving elements one position ahead . ; If element was not found ; Else move the next element in place of x ; Driver program to test above function ; Delete x from arr [ ]
#include <iostream> NEW_LINE using namespace std ; int deleteElement ( int arr [ ] , int n , int x ) { if ( arr [ n - 1 ] == x ) return ( n - 1 ) ; int prev = arr [ n - 1 ] , i ; for ( i = n - 2 ; i >= 0 && arr [ i ] != x ; i -- ) { int curr = arr [ i ] ; arr [ i ] = prev ; prev = curr ; } if ( i < 0 ) return 0 ; arr [ i ] = prev ; return ( n - 1 ) ; } int main ( ) { int arr [ ] = { 11 , 15 , 6 , 8 , 9 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 6 ; n = deleteElement ( arr , n , x ) ; cout << " Modified ▁ array ▁ is ▁ STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; return 0 ; }
Count Inversions of size three in a given array | A O ( n ^ 2 ) C ++ program to count inversions of size 3 ; Returns count of inversions of size 3 ; Initialize result ; Count all smaller elements on right of arr [ i ] ; Count all greater elements on left of arr [ i ] ; Update inversion count by adding all inversions that have arr [ i ] as middle of three elements ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getInvCount ( int arr [ ] , int n ) { int invcount = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { int small = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] > arr [ j ] ) small ++ ; int great = 0 ; for ( int j = i - 1 ; j >= 0 ; j -- ) if ( arr [ i ] < arr [ j ] ) great ++ ; invcount += great * small ; } return invcount ; } int main ( ) { int arr [ ] = { 8 , 4 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Inversion ▁ Count ▁ : ▁ " << getInvCount ( arr , n ) ; return 0 ; }
Trapping Rain Water | C ++ implementation of the approach ; Function to return the maximum water that can be stored ; To store the maximum water that can be stored ; For every element of the array ; Find the maximum element on its left ; Find the maximum element on its right ; Update the maximum water ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxWater ( int arr [ ] , int n ) { int res = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { int left = arr [ i ] ; for ( int j = 0 ; j < i ; j ++ ) left = max ( left , arr [ j ] ) ; int right = arr [ i ] ; for ( int j = i + 1 ; j < n ; j ++ ) right = max ( right , arr [ j ] ) ; res = res + ( min ( left , right ) - arr [ i ] ) ; } return res ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxWater ( arr , n ) ; return 0 ; }
Trapping Rain Water | C ++ program to find maximum amount of water that can be trapped within given set of bars . ; Method for maximum amount of water ; left [ i ] contains height of tallest bar to the left of i 'th bar including itself ; Right [ i ] contains height of tallest bar to the right of ith bar including itself ; Initialize result ; Fill left array ; Fill right array ; Calculate the accumulated water element by element consider the amount of water on i 'th bar, the amount of water accumulated on this particular bar will be equal to min(left[i], right[i]) - arr[i] . ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findWater ( int arr [ ] , int n ) { int left [ n ] ; int right [ n ] ; int water = 0 ; left [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) left [ i ] = max ( left [ i - 1 ] , arr [ i ] ) ; right [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) right [ i ] = max ( right [ i + 1 ] , arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) water += min ( left [ i ] , right [ i ] ) - arr [ i ] ; return water ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ water ▁ that ▁ can ▁ be ▁ accumulated ▁ is ▁ " << findWater ( arr , n ) ; return 0 ; }
Trapping Rain Water | C ++ program to find maximum amount of water that can be trapped within given set of bars . Space Complexity : O ( 1 ) ; initialize output ; maximum element on left and right ; indices to traverse the array ; update max in left ; water on curr element = max - curr ; update right maximum ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int findWater ( int arr [ ] , int n ) { int result = 0 ; int left_max = 0 , right_max = 0 ; int lo = 0 , hi = n - 1 ; while ( lo <= hi ) { if ( arr [ lo ] < arr [ hi ] ) { if ( arr [ lo ] > left_max ) left_max = arr [ lo ] ; else result += left_max - arr [ lo ] ; lo ++ ; } else { if ( arr [ hi ] > right_max ) right_max = arr [ hi ] ; else result += right_max - arr [ hi ] ; hi -- ; } } return result ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ water ▁ that ▁ can ▁ be ▁ accumulated ▁ is ▁ " << findWater ( arr , n ) ; }
Trapping Rain Water | C ++ implementation of the approach ; Function to return the maximum water that can be stored ; Let the first element be stored as previous , we shall loop from index 1 ; To store previous wall 's index ; To store the water until a larger wall is found , if there are no larger walls then delete temp value from water ; If the current wall is taller than the previous wall then make current wall as the previous wall and its index as previous wall 's index for the subsequent loops ; Because larger or same height wall is found ; Since current wall is shorter than the previous , we subtract previous wall ' s ▁ height ▁ from ▁ the ▁ current ▁ wall ' s height and add it to the water ; Store the same value in temp as well If we dont find any larger wall then we will subtract temp from water ; If the last wall was larger than or equal to the previous wall then prev_index would be equal to size of the array ( last element ) If we didn 't find a wall greater than or equal to the previous wall from the left then prev_index must be less than the index of the last element ; Temp would 've stored the water collected from previous largest wall till the end of array if no larger wall was found then it has excess water and remove that from water variable ; We start from the end of the array , so previous should be assigned to the last element ; Loop from the end of array up to the previous index which would contain the largest wall from the left ; Right end wall will be definitely smaller than the ' previous ▁ index ' wall ; Return the maximum water ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int maxWater ( int arr [ ] , int n ) { int size = n - 1 ; int prev = arr [ 0 ] ; int prev_index = 0 ; int water = 0 ; int temp = 0 ; for ( int i = 1 ; i <= size ; i ++ ) { if ( arr [ i ] >= prev ) { prev = arr [ i ] ; prev_index = i ; temp = 0 ; } else { water += prev - arr [ i ] ; temp += prev - arr [ i ] ; } } if ( prev_index < size ) { water -= temp ; prev = arr [ size ] ; for ( int i = size ; i >= prev_index ; i -- ) { if ( arr [ i ] >= prev ) { prev = arr [ i ] ; } else { water += prev - arr [ i ] ; } } } return water ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxWater ( arr , n ) ; return 0 ; }
Trapping Rain Water | C ++ implementation of the approach ; Function to return the maximum water that can be stored ; Stores the indices of the bars ; Stores the final result ; Loop through the each bar ; Remove bars from the stack until the condition holds ; Store the height of the top and pop it . ; If the stack does not have any bars or the the popped bar has no left boundary ; Get the distance between the left and right boundary of popped bar ; Calculate the min . height ; If the stack is either empty or height of the current bar is less than or equal to the top bar of stack ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxWater ( int height [ ] , int n ) { stack < int > st ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( ( ! st . empty ( ) ) && ( height [ st . top ( ) ] < height [ i ] ) ) { int pop_height = height [ st . top ( ) ] ; st . pop ( ) ; if ( st . empty ( ) ) break ; int distance = i - st . top ( ) - 1 ; int min_height = min ( height [ st . top ( ) ] , height [ i ] ) - pop_height ; ans += distance * min_height ; } st . push ( i ) ; } return ans ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxWater ( arr , n ) ; return 0 ; }
Trapping Rain Water | C ++ implementation of the approach ; indices to traverse the array ; To store Left max and right max for two pointers left and right ; To store the total amount of rain water trapped ; We need check for minimum of left and right max for each element ; Add the difference between current value and right max at index r ; Update right max ; Update right pointer ; Add the difference between current value and left max at index l ; Update left max ; Update left pointer ; Driver code
#include <iostream> NEW_LINE using namespace std ; int maxWater ( int arr [ ] , int n ) { int left = 0 ; int right = n - 1 ; int l_max = 0 ; int r_max = 0 ; int result = 0 ; while ( left <= right ) { if ( r_max <= l_max ) { result += max ( 0 , r_max - arr [ right ] ) ; r_max = max ( r_max , arr [ right ] ) ; right -= 1 ; } else { result += max ( 0 , l_max - arr [ left ] ) ; l_max = max ( l_max , arr [ left ] ) ; left += 1 ; } } return result ; } int main ( ) { int arr [ ] = { 0 , 1 , 0 , 2 , 1 , 0 , 1 , 3 , 2 , 1 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxWater ( arr , n ) << endl ; return 0 ; }
Median of two sorted arrays with different sizes in O ( log ( min ( n , m ) ) ) | C ++ code for finding median of the given two sorted arrays that exists in the merged array ( ( n + m ) / 2 - 1 position ) ; Function to find median of given two sorted arrays ; if i = n , it means that Elements from a [ ] in the second half is an empty set . If j = 0 , it means that Elements from b [ ] in the first half is an empty set . so it is necessary to check that , because we compare elements from these two groups . searching on right ; if i = 0 , it means that Elements from a [ ] in the first half is an empty set and if j = m , it means that Elements from b [ ] in the second half is an empty set . so it is necessary to check that , because we compare elements from these two groups . searching on left ; we have found the desired halves . ; this condition happens when we don 't have any elements in the first half from a[] so we returning the last element in b[] from the first half. ; and this condition happens when we don 't have any elements in the first half from b[] so we returning the last element in a[] from the first half. ; Function to find maximum ; Driver code ; we need to define the smaller array as the first parameter to make sure that the time complexity will be O ( log ( min ( n , m ) ) )
#include <bits/stdc++.h> NEW_LINE using std :: cout ; int maximum ( int a , int b ) ; int findMedianSortedArrays ( int * a , int n , int * b , int m ) { int min_index = 0 , max_index = n , i , j ; while ( min_index <= max_index ) { i = ( min_index + max_index ) / 2 ; j = ( ( n + m + 1 ) / 2 ) - i ; if ( i < n && j > 0 && b [ j - 1 ] > a [ i ] ) min_index = i + 1 ; else if ( i > 0 && j < m && b [ j ] < a [ i - 1 ] ) max_index = i - 1 ; else { if ( i == 0 ) return b [ j - 1 ] ; if ( j == 0 ) return a [ i - 1 ] ; else return maximum ( a [ i - 1 ] , b [ j - 1 ] ) ; } } cout << " ERROR ! ! ! ▁ " << " returning STRNEWLINE " ; return 0 ; } int maximum ( int a , int b ) { return a > b ? a : b ; } int main ( ) { int a [ ] = { 900 } ; int b [ ] = { 10 , 13 , 14 } ; int n = sizeof ( a ) / sizeof ( int ) ; int m = sizeof ( b ) / sizeof ( int ) ; if ( n < m ) cout << " The ▁ median ▁ is : ▁ " << findMedianSortedArrays ( a , n , b , m ) ; else cout << " The ▁ median ▁ is : ▁ " << findMedianSortedArrays ( b , m , a , n ) ; return 0 ; }
Print uncommon elements from two sorted arrays | C ++ program to find uncommon elements of two sorted arrays ; If not common , print smaller ; Skip common element ; printing remaining elements ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printUncommon ( int arr1 [ ] , int arr2 [ ] , int n1 , int n2 ) { int i = 0 , j = 0 , k = 0 ; while ( i < n1 && j < n2 ) { if ( arr1 [ i ] < arr2 [ j ] ) { cout << arr1 [ i ] << " ▁ " ; i ++ ; k ++ ; } else if ( arr2 [ j ] < arr1 [ i ] ) { cout << arr2 [ j ] << " ▁ " ; k ++ ; j ++ ; } else { i ++ ; j ++ ; } } while ( i < n1 ) { cout << arr1 [ i ] << " ▁ " ; i ++ ; k ++ ; } while ( j < n2 ) { cout << arr2 [ j ] << " ▁ " ; j ++ ; k ++ ; } } int main ( ) { int arr1 [ ] = { 10 , 20 , 30 } ; int arr2 [ ] = { 20 , 25 , 30 , 40 , 50 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; printUncommon ( arr1 , arr2 , n1 , n2 ) ; return 0 ; }
Least frequent element in an array | CPP program to find the least frequent element in an array . ; Sort the array ; find the min frequency using linear traversal ; If last element is least frequent ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int leastFrequent ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int min_count = n + 1 , res = -1 , curr_count = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) curr_count ++ ; else { if ( curr_count < min_count ) { min_count = curr_count ; res = arr [ i - 1 ] ; } curr_count = 1 ; } } if ( curr_count < min_count ) { min_count = curr_count ; res = arr [ n - 1 ] ; } return res ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << leastFrequent ( arr , n ) ; return 0 ; }
Least frequent element in an array | CPP program to find the least frequent element in an array . ; Insert all elements in hash . ; find the min frequency ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int leastFrequent ( int arr [ ] , int n ) { unordered_map < int , int > hash ; for ( int i = 0 ; i < n ; i ++ ) hash [ arr [ i ] ] ++ ; int min_count = n + 1 , res = -1 ; for ( auto i : hash ) { if ( min_count >= i . second ) { res = i . first ; min_count = i . second ; } } return res ; } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 1 , 2 , 2 , 3 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << leastFrequent ( arr , n ) ; return 0 ; }
Maximum sum of increasing order elements from n arrays | CPP program to find maximum sum by selecting a element from n arrays ; To calculate maximum sum by selecting element from each array ; Sort each array ; Store maximum element of last array ; Selecting maximum element from previoulsy selected element ; j = - 1 means no element is found in a [ i ] so return 0 ; Driver program to test maximumSum
#include <bits/stdc++.h> NEW_LINE #define M 4 NEW_LINE using namespace std ; int maximumSum ( int a [ ] [ M ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) sort ( a [ i ] , a [ i ] + M ) ; int sum = a [ n - 1 ] [ M - 1 ] ; int prev = a [ n - 1 ] [ M - 1 ] ; int i , j ; for ( i = n - 2 ; i >= 0 ; i -- ) { for ( j = M - 1 ; j >= 0 ; j -- ) { if ( a [ i ] [ j ] < prev ) { prev = a [ i ] [ j ] ; sum += prev ; break ; } } if ( j == -1 ) return 0 ; } return sum ; } int main ( ) { int arr [ ] [ M ] = { { 1 , 7 , 3 , 4 } , { 4 , 2 , 5 , 1 } , { 9 , 5 , 1 , 8 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumSum ( arr , n ) ; return 0 ; }
Maximum sum of increasing order elements from n arrays | CPP program to find maximum sum by selecting a element from n arrays ; To calculate maximum sum by selecting element from each array ; Store maximum element of last array ; Selecting maximum element from previoulsy selected element ; max_smaller equals to INT_MIN means no element is found in a [ i ] so return 0 ; Driver program to test maximumSum
#include <bits/stdc++.h> NEW_LINE #define M 4 NEW_LINE using namespace std ; int maximumSum ( int a [ ] [ M ] , int n ) { int prev = * max_element ( & a [ n - 1 ] [ 0 ] , & a [ n - 1 ] [ M - 1 ] + 1 ) ; int sum = prev ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int max_smaller = INT_MIN ; for ( int j = M - 1 ; j >= 0 ; j -- ) { if ( a [ i ] [ j ] < prev && a [ i ] [ j ] > max_smaller ) max_smaller = a [ i ] [ j ] ; } if ( max_smaller == INT_MIN ) return 0 ; prev = max_smaller ; sum += max_smaller ; } return sum ; } int main ( ) { int arr [ ] [ M ] = { { 1 , 7 , 3 , 4 } , { 4 , 2 , 5 , 1 } , { 9 , 5 , 1 , 8 } } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumSum ( arr , n ) ; return 0 ; }
Pairs such that one is a power multiple of other | Program to find pairs count ; function to count the required pairs ; sort the given array ; for each A [ i ] traverse rest array ; count Aj such that Ai * k ^ x = Aj ; increase x till Ai * k ^ x <= largest element ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int A [ ] , int n , int k ) { int ans = 0 ; sort ( A , A + n ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int x = 0 ; while ( ( A [ i ] * pow ( k , x ) ) <= A [ j ] ) { if ( ( A [ i ] * pow ( k , x ) ) == A [ j ] ) { ans ++ ; break ; } x ++ ; } } } return ans ; } int main ( ) { int A [ ] = { 3 , 8 , 9 , 12 , 18 , 4 , 24 , 2 , 6 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int k = 3 ; cout << countPairs ( A , n , k ) ; return 0 ; }
Find final value if we double after every successful search in array | CPP program to find value if we double the value after every successful search ; Function to Find the value of k ; Sort the array ; Search for k . After every successful search , double k . ; Driver 's Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findValue ( int a [ ] , int n , int k ) { sort ( a , a + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == k ) k *= 2 ; } return k ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 10 , 8 , 1 } , k = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findValue ( arr , n , k ) ; return 0 ; }
Last duplicate element in a sorted array | To print last duplicate element and its index in a sorted array ; if array is null or size is less than equal to 0 return ; compare elements and return last duplicate and its index ; If we reach here , then no duplicate found . ; Driver Code
#include <bits/stdc++.h> NEW_LINE void dupLastIndex ( int arr [ ] , int n ) { if ( arr == NULL n <= 0 ) return ; for ( int i = n - 1 ; i > 0 ; i -- ) { if ( arr [ i ] == arr [ i - 1 ] ) { printf ( " Last ▁ index : ▁ % d STRNEWLINE Last ▁ " " duplicate ▁ item : ▁ % d STRNEWLINE " , i , arr [ i ] ) ; return ; } } printf ( " no ▁ duplicate ▁ found " ) ; } int main ( ) { int arr [ ] = { 1 , 5 , 5 , 6 , 6 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( int ) ; dupLastIndex ( arr , n ) ; return 0 ; }
Find an array element such that all elements are divisible by it | CPP program to find an array element that divides all numbers in the array using naive approach ; function to find smallest num ; traverse for all elements ; stores the minimum if it divides all ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSmallest ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < n ; j ++ ) if ( a [ j ] % a [ i ] ) break ; if ( j == n ) return a [ i ] ; } return -1 ; } int main ( ) { int a [ ] = { 25 , 20 , 5 , 10 , 100 } ; int n = sizeof ( a ) / sizeof ( int ) ; cout << findSmallest ( a , n ) ; return 0 ; }
Find an array element such that all elements are divisible by it | CPP Program to find the smallest number that divides all numbers in an array ; function to find smallest num ; Find the smallest element ; Check if all array elements are divisible by smallest . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSmallest ( int a [ ] , int n ) { int smallest = * min_element ( a , a + n ) ; for ( int i = 1 ; i < n ; i ++ ) if ( a [ i ] % smallest ) return -1 ; return smallest ; } int main ( ) { int a [ ] = { 25 , 20 , 5 , 10 , 100 } ; int n = sizeof ( a ) / sizeof ( int ) ; cout << findSmallest ( a , n ) ; return 0 ; }
Maximum in array which is at | CPP program for Maximum of the array which is at least twice of other elements of the array . ; Function to find the index of Max element that satisfies the condition ; Finding index of max of the array ; Returns - 1 if the max element is not twice of the i - th element . ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findIndex ( int arr [ ] , int len ) { int maxIndex = 0 ; for ( int i = 0 ; i < len ; ++ i ) if ( arr [ i ] > arr [ maxIndex ] ) maxIndex = i ; for ( int i = 0 ; i < len ; ++ i ) if ( maxIndex != i && arr [ maxIndex ] < 2 * arr [ i ] ) return -1 ; return maxIndex ; } int main ( ) { int arr [ ] = { 3 , 6 , 1 , 0 } ; int len = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( findIndex ( arr , len ) ) ; }
Consecutive steps to roof top | CPP code to find maximum number of consecutive steps . ; Function to count consecutive steps ; count the number of consecutive increasing height building ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_consecutive_steps ( int arr [ ] , int len ) { int count = 0 ; int maximum = 0 ; for ( int index = 1 ; index < len ; index ++ ) { if ( arr [ index ] > arr [ index - 1 ] ) count ++ ; else { maximum = max ( maximum , count ) ; count = 0 ; } } return max ( maximum , count ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int len = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << find_consecutive_steps ( arr , len ) ; }
Maximum difference between groups of size two | CPP program to find minimum difference between groups of highest and lowest sums . ; Sorting the whole array . ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll CalculateMax ( ll arr [ ] , int n ) { sort ( arr , arr + n ) ; int min_sum = arr [ 0 ] + arr [ 1 ] ; int max_sum = arr [ n - 1 ] + arr [ n - 2 ] ; return abs ( max_sum - min_sum ) ; } int main ( ) { ll arr [ ] = { 6 , 7 , 1 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << CalculateMax ( arr , n ) << endl ; return 0 ; }
Minimum difference between groups of size two | CPP program to find minimum difference between groups of highest and lowest sums . ; Sorting the whole array . ; Generating sum groups . ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll calculate ( ll a [ ] , ll n ) { sort ( a , a + n ) ; vector < ll > s ; for ( int i = 0 , j = n - 1 ; i < j ; i ++ , j -- ) s . push_back ( a [ i ] + a [ j ] ) ; ll mini = * min_element ( s . begin ( ) , s . end ( ) ) ; ll maxi = * max_element ( s . begin ( ) , s . end ( ) ) ; return abs ( maxi - mini ) ; } int main ( ) { ll a [ ] = { 2 , 6 , 4 , 3 } ; int n = sizeof ( a ) / ( sizeof ( a [ 0 ] ) ) ; cout << calculate ( a , n ) << endl ; return 0 ; }
Closest numbers from a list of unsorted integers | CPP program to find minimum difference an unsorted array . ; Returns minimum difference between any two pair in arr [ 0. . n - 1 ] ; Sort array elements ; Compare differences of adjacent pairs to find the minimum difference . ; Traverse array again and print all pairs with difference as minDiff . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMinDiffPairs ( int arr [ ] , int n ) { if ( n <= 1 ) return ; sort ( arr , arr + n ) ; int minDiff = arr [ 1 ] - arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) minDiff = min ( minDiff , arr [ i ] - arr [ i - 1 ] ) ; for ( int i = 1 ; i < n ; i ++ ) if ( ( arr [ i ] - arr [ i - 1 ] ) == minDiff ) cout << " ( " << arr [ i - 1 ] << " , ▁ " << arr [ i ] << " ) , ▁ " ; } int main ( ) { int arr [ ] = { 5 , 3 , 2 , 4 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printMinDiffPairs ( arr , n ) ; return 0 ; }
Maximum absolute difference of value and index sums | Brute force C ++ program to calculate the maximum absolute difference of an array . ; Utility function to calculate the value of absolute difference for the pair ( i , j ) . ; Function to return maximum absolute difference in brute force . ; Variable for storing the maximum absolute distance throughout the traversal of loops . ; Iterate through all pairs . ; If the absolute difference of current pair ( i , j ) is greater than the maximum difference calculated till now , update the value of result . ; Driver program to test the above function .
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateDiff ( int i , int j , int arr [ ] ) { return abs ( arr [ i ] - arr [ j ] ) + abs ( i - j ) ; } int maxDistance ( int arr [ ] , int n ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { if ( calculateDiff ( i , j , arr ) > result ) result = calculateDiff ( i , j , arr ) ; } } return result ; } int main ( ) { int arr [ ] = { -70 , -64 , -6 , -56 , 64 , 61 , -57 , 16 , 48 , -98 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxDistance ( arr , n ) << endl ; return 0 ; }
Maximum absolute difference of value and index sums | C ++ program to calculate the maximum absolute difference of an array . ; Function to return maximum absolute difference in linear time . ; max and min variables as described in algorithm . ; Updating max and min variables as described in algorithm . ; Calculating maximum absolute difference . ; Driver program to test the above function .
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistance ( int arr [ ] , int n ) { int max1 = INT_MIN , min1 = INT_MAX ; int max2 = INT_MIN , min2 = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { max1 = max ( max1 , arr [ i ] + i ) ; min1 = min ( min1 , arr [ i ] + i ) ; max2 = max ( max2 , arr [ i ] - i ) ; min2 = min ( min2 , arr [ i ] - i ) ; } return max ( max1 - min1 , max2 - min2 ) ; } int main ( ) { int arr [ ] = { -70 , -64 , -6 , -56 , 64 , 61 , -57 , 16 , 48 , -98 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maxDistance ( arr , n ) << endl ; return 0 ; }
Number of local extrema in an array | CPP to find number of extrema ; function to find local extremum ; start loop from position 1 till n - 1 ; check if a [ i ] is greater than both its neighbours then add 1 to x ; check if a [ i ] is less than both its neighbours , then add 1 to x ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int extrema ( int a [ ] , int n ) { int count = 0 ; for ( int i = 1 ; i < n - 1 ; i ++ ) { count += ( a [ i ] > a [ i - 1 ] && a [ i ] > a [ i + 1 ] ) ; count += ( a [ i ] < a [ i - 1 ] && a [ i ] < a [ i + 1 ] ) ; } return count ; } int main ( ) { int a [ ] = { 1 , 0 , 2 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << extrema ( a , n ) ; return 0 ; }
Find closest number in array | CPP program to find element closet to given target . ; Returns element closest to target in arr [ ] ; Corner cases ; Doing binary search ; If target is less than array element , then search in left ; If target is greater than previous to mid , return closest of two ; Repeat for left half ; If target is greater than mid ; update i ; Only single element left after search ; Method to compare which one is the more close . We find the closest by taking the difference between the target and both values . It assumes that val2 is greater than val1 and target lies between these two . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getClosest ( int , int , int ) ; int findClosest ( int arr [ ] , int n , int target ) { if ( target <= arr [ 0 ] ) return arr [ 0 ] ; if ( target >= arr [ n - 1 ] ) return arr [ n - 1 ] ; int i = 0 , j = n , mid = 0 ; while ( i < j ) { mid = ( i + j ) / 2 ; if ( arr [ mid ] == target ) return arr [ mid ] ; if ( target < arr [ mid ] ) { if ( mid > 0 && target > arr [ mid - 1 ] ) return getClosest ( arr [ mid - 1 ] , arr [ mid ] , target ) ; j = mid ; } else { if ( mid < n - 1 && target < arr [ mid + 1 ] ) return getClosest ( arr [ mid ] , arr [ mid + 1 ] , target ) ; i = mid + 1 ; } } return arr [ mid ] ; } int getClosest ( int val1 , int val2 , int target ) { if ( target - val1 >= val2 - target ) return val2 ; else return val1 ; } int main ( ) { int arr [ ] = { 1 , 2 , 4 , 5 , 6 , 6 , 8 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int target = 11 ; cout << ( findClosest ( arr , n , target ) ) ; }
Number of pairs with maximum sum | CPP program to count pairs with maximum sum . ; function to find the number of maximum pair sums ; traverse through all the pairs ; traverse through all pairs and keep a count of the number of maximum pairs ; driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int a [ ] , int n ) { int maxSum = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) maxSum = max ( maxSum , a [ i ] + a [ j ] ) ; int c = 0 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( a [ i ] + a [ j ] == maxSum ) c ++ ; return c ; } int main ( ) { int array [ ] = { 1 , 1 , 1 , 2 , 2 , 2 } ; int n = sizeof ( array ) / sizeof ( array [ 0 ] ) ; cout << sum ( array , n ) ; return 0 ; }
Number of pairs with maximum sum | CPP program to count pairs with maximum sum . ; function to find the number of maximum pair sums ; Find maximum and second maximum elements . Also find their counts . ; If maximum element appears more than once . ; If maximum element appears only once . ; driver program to test the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int a [ ] , int n ) { int maxVal = a [ 0 ] , maxCount = 1 ; int secondMax = INT_MIN , secondMaxCount ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] == maxVal ) maxCount ++ ; else if ( a [ i ] > maxVal ) { secondMax = maxVal ; secondMaxCount = maxCount ; maxVal = a [ i ] ; maxCount = 1 ; } else if ( a [ i ] == secondMax ) { secondMax = a [ i ] ; secondMaxCount ++ ; } else if ( a [ i ] > secondMax ) { secondMax = a [ i ] ; secondMaxCount = 1 ; } } if ( maxCount > 1 ) return maxCount * ( maxCount - 1 ) / 2 ; return secondMaxCount ; } int main ( ) { int array [ ] = { 1 , 1 , 1 , 2 , 2 , 2 , 3 } ; int n = sizeof ( array ) / sizeof ( array [ 0 ] ) ; cout << sum ( array , n ) ; return 0 ; }
Find first k natural numbers missing in given array | C ++ program to find missing k numbers in an array . ; Prints first k natural numbers in arr [ 0. . n - 1 ] ; Find first positive number ; Now find missing numbers between array elements ; Find missing numbers after maximum . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printKMissing ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; int i = 0 ; while ( i < n && arr [ i ] <= 0 ) i ++ ; int count = 0 , curr = 1 ; while ( count < k && i < n ) { if ( arr [ i ] != curr ) { cout << curr << " ▁ " ; count ++ ; } else i ++ ; curr ++ ; } while ( count < k ) { cout << curr << " ▁ " ; curr ++ ; count ++ ; } } int main ( ) { int arr [ ] = { 2 , 3 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; printKMissing ( arr , n , k ) ; return 0 ; }
Find first k natural numbers missing in given array | C ++ code for the above approach ; Program to print first k missing number ; Creating a hashmap ; Iterate over array ; Iterate to find missing element ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printmissingk ( int arr [ ] , int n , int k ) { map < int , int > d ; for ( int i = 0 ; i < n ; i ++ ) d [ arr [ i ] ] = arr [ i ] ; int cnt = 1 ; int fl = 0 ; for ( int i = 0 ; i < ( n + k ) ; i ++ ) { if ( d . find ( cnt ) == d . end ( ) ) { fl += 1 ; cout << cnt << " ▁ " ; if ( fl == k ) break ; } cnt += 1 ; } } int main ( ) { int arr [ ] = { 1 , 4 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; ; printmissingk ( arr , n , k ) ; }
Noble integers in an array ( count of greater elements is equal to value ) | C ++ program to find Noble elements in an array . ; Returns a Noble integer if present , else returns - 1. ; If count of greater elements is equal to arr [ i ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nobleInteger ( int arr [ ] , int size ) { for ( int i = 0 ; i < size ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < size ; j ++ ) if ( arr [ i ] < arr [ j ] ) count ++ ; if ( count == arr [ i ] ) return arr [ i ] ; } return -1 ; } int main ( ) { int arr [ ] = { 10 , 3 , 20 , 40 , 2 } ; int size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int res = nobleInteger ( arr , size ) ; if ( res != -1 ) cout << " The ▁ noble ▁ integer ▁ is ▁ " << res ; else cout << " No ▁ Noble ▁ Integer ▁ Found " ; }
Noble integers in an array ( count of greater elements is equal to value ) | C ++ program to find Noble elements in an array . ; Returns a Noble integer if present , else returns - 1. ; Return a Noble element if present before last . ; In case of duplicates , we reach last occurrence here . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nobleInteger ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) continue ; if ( arr [ i ] == n - i - 1 ) return arr [ i ] ; } if ( arr [ n - 1 ] == 0 ) return arr [ n - 1 ] ; return -1 ; } int main ( ) { int arr [ ] = { 10 , 3 , 20 , 40 , 2 } ; int res = nobleInteger ( arr , 5 ) ; if ( res != -1 ) cout << " The ▁ noble ▁ integer ▁ is ▁ " << res ; else cout << " No ▁ Noble ▁ Integer ▁ Found " ; return 0 ; }
Noble integers in an array ( count of greater elements is equal to value ) | C ++ program to find Noble elements in an array . ; Declare a countArr which keeps count of all elements greater than or equal to arr [ i ] . Initialize it with zero . ; Iterating through the given array ; If current element is less than zero , it cannot be a solution so we skip it . ; If current element is >= size of input array , if will be greater than all elements which can be considered as our solution , as it cannot be greater than size of array . ; Else we increase the count of elements >= our current array in countArr ; Initially , countArr [ n ] is count of elements greater than all possible solutions ; Iterating through countArr ; If totalGreater = current index , means we found arr [ i ] for which count of elements >= arr [ i ] is equal to arr [ i ] ; If at any point count of elements greater than arr [ i ] becomes more than current index , then it means we can no longer have a solution ; Adding count of elements >= arr [ i ] to totalGreater . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nobleInteger ( int arr [ ] , int n ) { int countArr [ n + 1 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) { continue ; } else if ( arr [ i ] >= n ) { countArr [ n ] ++ ; } else { countArr [ arr [ i ] ] ++ ; } } int totalGreater = countArr [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( totalGreater == i && countArr [ i ] > 0 ) { return i ; } else if ( totalGreater > i ) { return -1 ; } totalGreater += countArr [ i ] ; } return -1 ; } int main ( ) { int arr [ ] = { 10 , 3 , 20 , 40 , 2 } ; int res = nobleInteger ( arr , 5 ) ; if ( res != -1 ) cout << " The ▁ noble ▁ integer ▁ is ▁ " << res ; else cout << " No ▁ Noble ▁ Integer ▁ Found " ; return 0 ; }
Minimum sum of absolute difference of pairs of two arrays | C ++ program to find minimum sum of absolute differences of two arrays . ; Returns minimum possible pairwise absolute difference of two arrays . ; Sort both arrays ; Find sum of absolute differences ; Driver code ; Both a [ ] and b [ ] must be of same size .
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int findMinSum ( long long int a [ ] , long long int b [ ] , int n ) { sort ( a , a + n ) ; sort ( b , b + n ) ; long long int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum = sum + abs ( a [ i ] - b [ i ] ) ; return sum ; } int main ( ) { long long int a [ ] = { 4 , 1 , 8 , 7 } ; long long int b [ ] = { 2 , 3 , 6 , 5 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printf ( " % lld STRNEWLINE " , findMinSum ( a , b , n ) ) ; return 0 ; }
Minimum product subset of an array | CPP program to find maximum product of a subset . ; Find count of negative numbers , count of zeros , maximum valued negative number , minimum valued positive number and product of non - zero numbers ; If number is 0 , we don 't multiply it with product. ; Count negatives and keep track of maximum valued negative . ; Track minimum positive number of array ; If there are all zeros or no negative number present ; If there are all positive ; If there are even number of negative numbers and count_neg not 0 ; Otherwise result is product of all non - zeros divided by maximum valued negative . ; main function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minProductSubset ( int a [ ] , int n ) { if ( n == 1 ) return a [ 0 ] ; int max_neg = INT_MIN ; int min_pos = INT_MAX ; int count_neg = 0 , count_zero = 0 ; int prod = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) { count_zero ++ ; continue ; } if ( a [ i ] < 0 ) { count_neg ++ ; max_neg = max ( max_neg , a [ i ] ) ; } if ( a [ i ] > 0 ) min_pos = min ( min_pos , a [ i ] ) ; prod = prod * a [ i ] ; } if ( count_zero == n || ( count_neg == 0 && count_zero > 0 ) ) return 0 ; if ( count_neg == 0 ) return min_pos ; if ( ! ( count_neg & 1 ) && count_neg != 0 ) { prod = prod / max_neg ; } return prod ; } int main ( ) { int a [ ] = { -1 , -1 , -2 , 4 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << minProductSubset ( a , n ) ; return 0 ; }
Repeatedly search an element by doubling it after every successful search | C ++ program to repeatedly search an element by doubling it after every successful search ; Sort the given array so that binary search can be applied on it ; Maximum array element ; search for the element b present or not in array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findElement ( int a [ ] , int n , int b ) { sort ( a , a + n ) ; int max = a [ n - 1 ] ; while ( b < max ) { if ( binary_search ( a , a + n , b ) ) b *= 2 ; else return b ; } return b ; } int main ( ) { int a [ ] = { 1 , 2 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int b = 1 ; cout << findElement ( a , n , b ) ; return 0 ; }
Maximum sum of pairwise product in an array with negative allowed | C ++ program for above implementation ; Function to find the maximum sum ; Sort the array first ; First multiply negative numbers pairwise and sum up from starting as to get maximum sum . ; Second multiply positive numbers pairwise and summed up from the last as to get maximum sum . ; To handle case if positive and negative numbers both are odd in counts . ; If one of them occurs odd times ; Drivers code
#include <bits/stdc++.h> NEW_LINE #define Mod 1000000007 NEW_LINE using namespace std ; long long int findSum ( int arr [ ] , int n ) { long long int sum = 0 ; sort ( arr , arr + n ) ; int i = 0 ; while ( i < n && arr [ i ] < 0 ) { if ( i != n - 1 && arr [ i + 1 ] <= 0 ) { sum = ( sum + ( arr [ i ] * arr [ i + 1 ] ) % Mod ) % Mod ; i += 2 ; } else break ; } int j = n - 1 ; while ( j >= 0 && arr [ j ] > 0 ) { if ( j != 0 && arr [ j - 1 ] > 0 ) { sum = ( sum + ( arr [ j ] * arr [ j - 1 ] ) % Mod ) % Mod ; j -= 2 ; } else break ; } if ( j > i ) sum = ( sum + ( arr [ i ] * arr [ j ] ) % Mod ) % Mod ; else if ( i == j ) sum = ( sum + arr [ i ] ) % Mod ; return sum ; } int main ( ) { int arr [ ] = { -1 , 9 , 4 , 5 , -4 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSum ( arr , n ) ; return 0 ; }
Search an element in a Linked List ( Iterative and Recursive ) | Recursive C ++ program to search an element in linked list ; Link list node ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; allocate node ; link the old list off the new node ; move the head to point to the new node ; Checks whether the value x is present in linked list ; Base case ; If key is present in current node , return true ; Recur for remaining list ; Driver code ; Start with the empty list ; Use push ( ) to construct below list 14 -> 21 -> 11 -> 30 -> 10
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * next ; } ; void push ( struct Node * * head_ref , int new_key ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> key = new_key ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } bool search ( struct Node * head , int x ) { if ( head == NULL ) return false ; if ( head -> key == x ) return true ; return search ( head -> next , x ) ; } int main ( ) { struct Node * head = NULL ; int x = 21 ; push ( & head , 10 ) ; push ( & head , 30 ) ; push ( & head , 11 ) ; push ( & head , 21 ) ; push ( & head , 14 ) ; search ( head , 21 ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Iteratively Reverse a linked list using only 2 pointers ( An Interesting Method ) | C ++ program to reverse a linked list using two pointers . ; Link list node ; Function to reverse the linked list using 2 pointers ; at last prev points to new head ; This expression evaluates from left to right current -> next = prev , changes the link fron next to prev node prev = current , moves prev to current node for next reversal of node This example of list will clear it more 1 -> 2 -> 3 -> 4 initially prev = 1 , current = 2 Final expression will be current = 1 ^ 2 ^ 3 ^ 2 ^ 1 , as we know that bitwise XOR of two same numbers will always be 0 i . e ; 1 ^ 1 = 2 ^ 2 = 0 After the evaluation of expression current = 3 that means it has been moved by one node from its previous position ; Function to push a node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Function to print linked list ; Driver program to test above function ; Start with the empty list
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef uintptr_t ut ; struct Node { int data ; struct Node * next ; } ; void reverse ( struct Node * * head_ref ) { struct Node * prev = NULL ; struct Node * current = * head_ref ; while ( current != NULL ) { current = ( struct Node * ) ( ( ut ) prev ^ ( ut ) current ^ ( ut ) ( current -> next ) ^ ( ut ) ( current -> next = prev ) ^ ( ut ) ( prev = current ) ) ; } * head_ref = prev ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * head ) { struct Node * temp = head ; while ( temp != NULL ) { printf ( " % d ▁ " , temp -> data ) ; temp = temp -> next ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 20 ) ; push ( & head , 4 ) ; push ( & head , 15 ) ; push ( & head , 85 ) ; printf ( " Given ▁ linked ▁ list STRNEWLINE " ) ; printList ( head ) ; reverse ( & head ) ; printf ( " Reversed Linked list " printList ( head ) ; return 0 ; }
Iteratively Reverse a linked list using only 2 pointers ( An Interesting Method ) | C ++ program to reverse a linked list using two pointers . ; Link list node ; Function to reverse the linked list using 2 pointers ; Function to push a node ; Function to print linked list ; Driver program to test above function ; Start with the empty list
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef uintptr_t ut ; struct Node { int data ; struct Node * next ; } ; void reverse ( struct Node * * head_ref ) { struct Node * current = * head_ref ; struct Node * next ; while ( current -> next != NULL ) { next = current -> next ; current -> next = next -> next ; next -> next = ( * head_ref ) ; * head_ref = next ; } } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = new Node ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * head ) { struct Node * temp = head ; while ( temp != NULL ) { printf ( " % d ▁ " , temp -> data ) ; temp = temp -> next ; } } int main ( ) { struct Node * head = NULL ; push ( & head , 20 ) ; push ( & head , 4 ) ; push ( & head , 15 ) ; push ( & head , 85 ) ; printf ( " Given ▁ linked ▁ list STRNEWLINE " ) ; printList ( head ) ; reverse ( & head ) ; printf ( " Reversed Linked list " printList ( head ) ; return 0 ; }
Delete alternate nodes of a Linked List | deletes alternate nodes of a list starting with head ; Change the next link of head ; free memory allocated for node ; Recursively call for the new next of head
void deleteAlt ( Node * head ) { if ( head == NULL ) return ; Node * node = head -> next ; if ( node == NULL ) return ; head -> next = node -> next ; free ( node ) ; deleteAlt ( head -> next ) ; }
Alternating split of a given Singly Linked List | Set 1 | ; points to the last node in ' a ' ; points to the last node in ' b ' ; add at ' a ' tail ; advance the ' a ' tail
void AlternatingSplit ( Node * source , Node * * aRef , Node * * bRef ) { Node aDummy ; Node * aTail = & aDummy ; Node bDummy ; Node * bTail = & bDummy ; Node * current = source ; aDummy . next = NULL ; bDummy . next = NULL ; while ( current != NULL ) { MoveNode ( & ( aTail -> next ) , t ) ; aTail = aTail -> next ; if ( current != NULL ) { MoveNode ( & ( bTail -> next ) , t ) ; bTail = bTail -> next ; } } * aRef = aDummy . next ; * bRef = bDummy . next ; }
Identical Linked Lists | An iterative C ++ program to check if two linked lists are identical or not ; Structure for a linked list node ; Returns true if linked lists a and b are identical , otherwise false ; If we reach here , then a and b are not NULL and their data is same , so move to next nodes in both lists ; If linked lists are identical , then ' a ' and ' b ' must be NULL at this point . ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the list . ; allocate node put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver Code ; The constructed linked lists are : a : 3 -> 2 -> 1 b : 3 -> 2 -> 1
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; bool areIdentical ( struct Node * a , struct Node * b ) { while ( a != NULL && b != NULL ) { if ( a -> data != b -> data ) return false ; a = a -> next ; b = b -> next ; } return ( a == NULL && b == NULL ) ; } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int main ( ) { struct Node * a = NULL ; struct Node * b = NULL ; push ( & a , 1 ) ; push ( & a , 2 ) ; push ( & a , 3 ) ; push ( & b , 1 ) ; push ( & b , 2 ) ; push ( & b , 3 ) ; if ( areIdentical ( a , b ) ) cout << " Identical " ; else cout << " Not ▁ identical " ; return 0 ; }
Identical Linked Lists | A recursive C ++ function to check if two linked lists are identical or not ; If both lists are empty ; If both lists are not empty , then data of current nodes must match , and same should be recursively true for rest of the nodes . ; If we reach here , then one of the lists is empty and other is not
bool areIdentical ( Node * a , Node * b ) { if ( a == NULL && b == NULL ) return true ; if ( a != NULL && b != NULL ) return ( a -> data == b -> data ) && areIdentical ( a -> next , b -> next ) ; return false ; }
Rotate a Linked List | C ++ program to rotate a linked list counter clock wise ; Link list node ; This function rotates a linked list counter - clockwise and updates the head . The function assumes that k is smaller than size of linked list . ; Let us understand the below code for example k = 4 and list = 10 -> 20 -> 30 -> 40 -> 50 -> 60. ; Traverse till the end . ; traverse the linked list to k - 1 position which will be last element for rotated array . ; update the head_ref and last element pointer to NULL ; Function to push a node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Function to print linked list ; Driver code ; Start with the empty list ; create a list 10 -> 20 -> 30 -> 40 -> 50 -> 60
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void rotate ( Node * * head_ref , int k ) { if ( k == 0 ) return ; Node * current = * head_ref ; while ( current -> next != NULL ) current = current -> next ; current -> next = * head_ref ; current = * head_ref ; for ( int i = 0 ; i < k - 1 ; i ++ ) current = current -> next ; * head_ref = current -> next ; current -> next = NULL ; } void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " ▁ " ; node = node -> next ; } } int main ( void ) { Node * head = NULL ; for ( int i = 60 ; i > 0 ; i -= 10 ) push ( & head , i ) ; cout << " Given ▁ linked ▁ list ▁ STRNEWLINE " ; printList ( head ) ; rotate ( & head , 4 ) ; cout << " Rotated Linked list " ; printList ( head ) ; return ( 0 ) ; }
Sort a linked list of 0 s , 1 s and 2 s | C ++ Program to sort a linked list 0 s , 1 s or 2 s ; Link list node ; Function to sort a linked list of 0 s , 1 s and 2 s ; Initialize count of '0' , '1' and '2' as 0 ; count total number of '0' , '1' and '2' * count [ 0 ] will store total number of '0' s * count [ 1 ] will store total number of '1' s * count [ 2 ] will store total number of '2' s ; Let say count [ 0 ] = n1 , count [ 1 ] = n2 and count [ 2 ] = n3 * now start traversing list from head node , * 1 ) fill the list with 0 , till n1 > 0 * 2 ) fill the list with 1 , till n2 > 0 * 3 ) fill the list with 2 , till n3 > 0 ; Function to push a node ; allocate node put in the data ; link the old list off the new node ; move the head to point to the new node ; Function to print linked list ; Driver code ; Constructed Linked List is 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 8 -> 9 -> null
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void sortList ( Node * head ) { int count [ 3 ] = { 0 , 0 , 0 } ; Node * ptr = head ; while ( ptr != NULL ) { count [ ptr -> data ] += 1 ; ptr = ptr -> next ; } int i = 0 ; ptr = head ; while ( ptr != NULL ) { if ( count [ i ] == 0 ) ++ i ; else { ptr -> data = i ; -- count [ i ] ; ptr = ptr -> next ; } } } void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " ▁ " ; node = node -> next ; } cout << endl ; } int main ( void ) { Node * head = NULL ; push ( & head , 0 ) ; push ( & head , 1 ) ; push ( & head , 0 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; push ( & head , 1 ) ; push ( & head , 2 ) ; push ( & head , 1 ) ; push ( & head , 2 ) ; cout << " Linked ▁ List ▁ Before ▁ Sorting STRNEWLINE " ; printList ( head ) ; sortList ( head ) ; cout << " Linked ▁ List ▁ After ▁ Sorting STRNEWLINE " ; printList ( head ) ; return 0 ; }
Rearrange a linked list such that all even and odd positioned nodes are together | C ++ program to rearrange a linked list in such a way that all odd positioned node are stored before all even positioned nodes ; Linked List Node ; A utility function to create a new node ; Rearranges given linked list such that all even positioned nodes are before odd positioned . Returns new head of linked List . ; Corner case ; Initialize first nodes of even and odd lists ; Remember the first node of even list so that we can connect the even list at the end of odd list . ; If there are no more nodes , then connect first node of even list to the last node of odd list ; Connecting odd nodes ; If there are NO more even nodes after current odd . ; Connecting even nodes ; A utility function to print a linked list ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> data = key ; temp -> next = NULL ; return temp ; } Node * rearrangeEvenOdd ( Node * head ) { if ( head == NULL ) return NULL ; Node * odd = head ; Node * even = head -> next ; Node * evenFirst = even ; while ( 1 ) { if ( ! odd || ! even || ! ( even -> next ) ) { odd -> next = evenFirst ; break ; } odd -> next = even -> next ; odd = even -> next ; if ( odd -> next == NULL ) { even -> next = NULL ; odd -> next = evenFirst ; break ; } even -> next = odd -> next ; even = odd -> next ; } return head ; } void printlist ( Node * node ) { while ( node != NULL ) { cout << node -> data << " - > " ; node = node -> next ; } cout << " NULL " << endl ; } int main ( void ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; cout << " Given ▁ Linked ▁ List STRNEWLINE " ; printlist ( head ) ; head = rearrangeEvenOdd ( head ) ; cout << " Modified ▁ Linked ▁ List STRNEWLINE " ; printlist ( head ) ; return 0 ; }
Add 1 to a number represented as linked list | Recursive C ++ program to add 1 to a linked list ; Linked list node ; Function to create a new node with given data ; Recursively add 1 from end to beginning and returns carry after all nodes are processed . ; If linked list is empty , then return carry ; Add carry returned be next node call ; Update data and return new carry ; This function mainly uses addWithCarry ( ) . ; Add 1 to linked list from end to beginning ; If there is carry after processing all nodes , then we need to add a new node to linked list ; New node becomes head now ; A utility function to print a linked list ; Driver code
#include <bits/stdc++.h> NEW_LINE struct Node { int data ; Node * next ; } ; Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> next = NULL ; return new_node ; } int addWithCarry ( Node * head ) { if ( head == NULL ) return 1 ; int res = head -> data + addWithCarry ( head -> next ) ; head -> data = ( res ) % 10 ; return ( res ) / 10 ; } Node * addOne ( Node * head ) { int carry = addWithCarry ( head ) ; if ( carry ) { Node * newNode = new Node ; newNode -> data = carry ; newNode -> next = head ; return newNode ; } return head ; } void printList ( Node * node ) { while ( node != NULL ) { printf ( " % d " , node -> data ) ; node = node -> next ; } printf ( " STRNEWLINE " ) ; } int main ( void ) { Node * head = newNode ( 1 ) ; head -> next = newNode ( 9 ) ; head -> next -> next = newNode ( 9 ) ; head -> next -> next -> next = newNode ( 9 ) ; printf ( " List ▁ is ▁ " ) ; printList ( head ) ; head = addOne ( head ) ; printf ( " Resultant list is " printList ( head ) ; return 0 ; }
Point arbit pointer to greatest value right side node in a linked list | C ++ program to point arbit pointers to highest value on its right ; Link list node ; Function to reverse the linked list ; This function populates arbit pointer in every node to the greatest value to its right . ; Reverse given linked list ; Initialize pointer to maximum value node ; Traverse the reversed list ; Connect max through arbit pointer ; Update max if required ; Move ahead in reversed list ; Reverse modified linked list and return head . ; Utility function to print result linked list ; Function to create a new node with given data ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next , * arbit ; } ; Node * reverse ( Node * head ) { Node * prev = NULL , * current = head , * next ; while ( current != NULL ) { next = current -> next ; current -> next = prev ; prev = current ; current = next ; } return prev ; } Node * populateArbit ( Node * head ) { head = reverse ( head ) ; Node * max = head ; Node * temp = head -> next ; while ( temp != NULL ) { temp -> arbit = max ; if ( max -> data < temp -> data ) max = temp ; temp = temp -> next ; } return reverse ( head ) ; } void printNextArbitPointers ( Node * node ) { printf ( " Node TABSYMBOL Next ▁ Pointer TABSYMBOL Arbit ▁ Pointer STRNEWLINE " ) ; while ( node != NULL ) { cout << node -> data << " TABSYMBOL TABSYMBOL " ; if ( node -> next ) cout << node -> next -> data << " TABSYMBOL TABSYMBOL " ; else cout << " NULL " << " TABSYMBOL TABSYMBOL " ; if ( node -> arbit ) cout << node -> arbit -> data ; else cout << " NULL " ; cout << endl ; node = node -> next ; } } Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> next = NULL ; return new_node ; } int main ( ) { Node * head = newNode ( 5 ) ; head -> next = newNode ( 10 ) ; head -> next -> next = newNode ( 2 ) ; head -> next -> next -> next = newNode ( 3 ) ; head = populateArbit ( head ) ; printf ( " Resultant ▁ Linked ▁ List ▁ is : ▁ STRNEWLINE " ) ; printNextArbitPointers ( head ) ; return 0 ; }
Point arbit pointer to greatest value right side node in a linked list | C ++ program to point arbit pointers to highest value on its right ; Link list node ; This function populates arbit pointer in every node to the greatest value to its right . ; using static maxNode to keep track of maximum orbit node address on right side ; if head is null simply return the list ; if head -> next is null it means we reached at the last node just update the max and maxNode ; Calling the populateArbit to the next node ; updating the arbit node of the current node with the maximum value on the right side ; if current Node value id greater then the previous right node then update it ; Utility function to print result linked list ; Function to create a new node with given data ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * next , * arbit ; } ; void populateArbit ( Node * head ) { static Node * maxNode ; if ( head == NULL ) return ; if ( head -> next == NULL ) { maxNode = head ; return ; } populateArbit ( head -> next ) ; head -> arbit = maxNode ; if ( head -> data > maxNode -> data ) maxNode = head ; return ; } void printNextArbitPointers ( Node * node ) { printf ( " Node TABSYMBOL Next ▁ Pointer TABSYMBOL Arbit ▁ Pointer STRNEWLINE " ) ; while ( node != NULL ) { cout << node -> data << " TABSYMBOL TABSYMBOL " ; if ( node -> next ) cout << node -> next -> data << " TABSYMBOL TABSYMBOL " ; else cout << " NULL " << " TABSYMBOL TABSYMBOL " ; if ( node -> arbit ) cout << node -> arbit -> data ; else cout << " NULL " ; cout << endl ; node = node -> next ; } } Node * newNode ( int data ) { Node * new_node = new Node ; new_node -> data = data ; new_node -> next = NULL ; return new_node ; } int main ( ) { Node * head = newNode ( 5 ) ; head -> next = newNode ( 10 ) ; head -> next -> next = newNode ( 2 ) ; head -> next -> next -> next = newNode ( 3 ) ; populateArbit ( head ) ; printf ( " Resultant ▁ Linked ▁ List ▁ is : ▁ STRNEWLINE " ) ; printNextArbitPointers ( head ) ; return 0 ; }
Check if a linked list of strings forms a palindrome | Program to check if a given linked list of strings form a palindrome ; Link list node ; A utility function to check if str is palindrome or not ; Match characters from beginning and end . ; Returns true if string formed by linked list is palindrome ; Append all nodes to form a string ; Check if the formed string is palindrome ; A utility function to print a given linked list ; Function to create a new node with given data ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { string data ; Node * next ; } ; bool isPalindromeUtil ( string str ) { int length = str . length ( ) ; for ( int i = 0 ; i < length / 2 ; i ++ ) if ( str [ i ] != str [ length - i - 1 ] ) return false ; return true ; } bool isPalindrome ( Node * node ) { string str = " " ; while ( node != NULL ) { str . append ( node -> data ) ; node = node -> next ; } return isPalindromeUtil ( str ) ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " ▁ - > ▁ " ; node = node -> next ; } printf ( " NULL STRNEWLINE " ) ; } Node * newNode ( const char * str ) { Node * new_node = new Node ; new_node -> data = str ; new_node -> next = NULL ; return new_node ; } int main ( ) { Node * head = newNode ( " a " ) ; head -> next = newNode ( " bc " ) ; head -> next -> next = newNode ( " d " ) ; head -> next -> next -> next = newNode ( " dcb " ) ; head -> next -> next -> next -> next = newNode ( " a " ) ; isPalindrome ( head ) ? printf ( " true STRNEWLINE " ) : printf ( " false STRNEWLINE " ) ; return 0 ; }
Delete last occurrence of an item from linked list | A C ++ program to demonstrate deletion of last Node in singly linked list ; A linked list Node ; Function to delete the last occurrence ; If found key , update ; If the last occurrence is the last node ; If it is not the last node ; Utility function to create a new node with given key ; This function prints contents of linked list starting from the given Node ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; void deleteLast ( struct Node * head , int x ) { struct Node * temp = head , * ptr = NULL ; while ( temp ) { if ( temp -> data == x ) ptr = temp ; temp = temp -> next ; } if ( ptr != NULL && ptr -> next == NULL ) { temp = head ; while ( temp -> next != ptr ) temp = temp -> next ; temp -> next = NULL ; } if ( ptr != NULL && ptr -> next != NULL ) { ptr -> data = ptr -> next -> data ; temp = ptr -> next ; ptr -> next = ptr -> next -> next ; free ( temp ) ; } } struct Node * newNode ( int x ) { Node * node = new Node ; node -> data = x ; node -> next = NULL ; return node ; } void display ( struct Node * head ) { struct Node * temp = head ; if ( head == NULL ) { cout << " NULL STRNEWLINE " ; return ; } while ( temp != NULL ) { cout << " ▁ - - > ▁ " << temp -> data ; temp = temp -> next ; } cout << " NULL STRNEWLINE " ; } int main ( ) { struct Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next = newNode ( 5 ) ; head -> next -> next -> next -> next -> next = newNode ( 4 ) ; head -> next -> next -> next -> next -> next -> next = newNode ( 4 ) ; cout << " Created ▁ Linked ▁ list : ▁ " ; display ( head ) ; deleteLast ( head , 4 ) ; cout << " List ▁ after ▁ deletion ▁ of ▁ 4 : ▁ " ; display ( head ) ; return 0 ; }
Flatten a multi |
Node * flattenList2 ( Node * head ) { Node * headcop = head ; stack < Node * > save ; save . push ( head ) ; Node * prev = NULL ; while ( ! save . empty ( ) ) { Node * temp = save . top ( ) ; save . pop ( ) ; if ( temp -> next ) save . push ( temp -> next ) ; if ( temp -> down ) save . push ( temp -> down ) ; if ( prev != NULL ) prev -> next = temp ; prev = temp ; } return headcop ; }
Partitioning a linked list around a given value and keeping the original order | C ++ program to partition a linked list around a given value . ; Link list Node ; A utility function to create a new node ; Function to make two separate lists and return head after concatenating ; Let us initialize first and last nodes of three linked lists 1 ) Linked list of values smaller than x . 2 ) Linked list of values equal to x . 3 ) Linked list of values greater than x . ; Now iterate original list and connect nodes of appropriate linked lists . ; If current node is equal to x , append it to the list of x values ; If current node is less than X , append it to the list of smaller values ; Append to the list of greater values ; Fix end of greater linked list to NULL if this list has some nodes ; If smaller list is empty ; If smaller list is not empty and equal list is empty ; If both smaller and equal list are non - empty ; Function to print linked list ; Driver program to run the case ; Start with the empty list
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; Node * newNode ( int data ) { struct Node * new_node = new Node ; new_node -> data = data ; new_node -> next = NULL ; return new_node ; } struct Node * partition ( struct Node * head , int x ) { struct Node * smallerHead = NULL , * smallerLast = NULL ; struct Node * greaterLast = NULL , * greaterHead = NULL ; struct Node * equalHead = NULL , * equalLast = NULL ; while ( head != NULL ) { if ( head -> data == x ) { if ( equalHead == NULL ) equalHead = equalLast = head ; else { equalLast -> next = head ; equalLast = equalLast -> next ; } } else if ( head -> data < x ) { if ( smallerHead == NULL ) smallerLast = smallerHead = head ; else { smallerLast -> next = head ; smallerLast = head ; } } else { if ( greaterHead == NULL ) greaterLast = greaterHead = head ; else { greaterLast -> next = head ; greaterLast = head ; } } head = head -> next ; } if ( greaterLast != NULL ) greaterLast -> next = NULL ; if ( smallerHead == NULL ) { if ( equalHead == NULL ) return greaterHead ; equalLast -> next = greaterHead ; return equalHead ; } if ( equalHead == NULL ) { smallerLast -> next = greaterHead ; return smallerHead ; } smallerLast -> next = equalHead ; equalLast -> next = greaterHead ; return smallerHead ; } void printList ( struct Node * head ) { struct Node * temp = head ; while ( temp != NULL ) { printf ( " % d ▁ " , temp -> data ) ; temp = temp -> next ; } } int main ( ) { struct Node * head = newNode ( 10 ) ; head -> next = newNode ( 4 ) ; head -> next -> next = newNode ( 5 ) ; head -> next -> next -> next = newNode ( 30 ) ; head -> next -> next -> next -> next = newNode ( 2 ) ; head -> next -> next -> next -> next -> next = newNode ( 50 ) ; int x = 3 ; head = partition ( head , x ) ; printList ( head ) ; return 0 ; }