config
stringclasses 2
values | instruction
stringlengths 48
2.07k
| response
stringlengths 44
2.06k
|
---|---|---|
xp3x | "Zygodrome Number | C ++ implementation to check if N is an zygodrome number ; Function to check if N is an zygodrome number ; convert N to string ; Adding a space at the beginning and end of the string ; Traverse the string ; If any character is not same as prev and next then return false ; Driver code"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; bool iszygodromeNum ( int N ) { string s = to_string ( N ) ; s = ' β ' + s + ' β ' ; for ( int i = 1 ; i < s . size ( ) - 1 ; i ++ ) { if ( s [ i ] != s [ i - 1 ] && s [ i ] != s [ i + 1 ] ) { return false ; } } return true ; } int main ( ) { int n = 1122 ; if ( iszygodromeNum ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
``` |
xp3x | "Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree | Java implementation of the approach ; Function to solve queries of the maximum xor value between the nodes in a given level L of a perfect binary tree and a given value X ; Initialize result ; Initialize array to store bits ; Initialize a copy of X and size of array ; Storing the bits of X in the array a [ ] ; Filling the array b [ ] ; Initializing variable which gives maximum xor ; Getting the maximum xor value ; Return the result ; Driver code ; Perform queries"
How can the above be solved in Java? | ```java
class GFG { static int MAXN = 60 ; static int solveQuery ( int L , int X ) { int res ; int [ ] a = new int [ MAXN ] ; int [ ] b = new int [ L ] ; int refer = X , size_a = 0 ; while ( refer > 0 ) { a [ size_a ] = refer % 2 ; refer /= 2 ; size_a ++ ; } for ( int i = 0 ; i < Math . min ( size_a , L ) ; i ++ ) { if ( a [ i ] == 1 ) b [ i ] = 0 ; else b [ i ] = 1 ; } for ( int i = Math . min ( size_a , L ) ; i < L ; i ++ ) b [ i ] = 1 ; b [ L - 1 ] = 1 ; int temp = 0 , p = 1 ; for ( int i = 0 ; i < L ; i ++ ) { temp += b [ i ] * p ; p *= 2 ; } res = temp ^ X ; return res ; } static public void main ( String args [ ] ) { int [ ] [ ] queries = { { 2 , 5 } , { 3 , 15 } } ; int q = queries . length ; for ( int i = 0 ; i < q ; i ++ ) System . out . println ( solveQuery ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) ; } }
``` |
xp3x | "Count number of binary strings of length N having only 0 ' s β and β 1' s | C ++ implementation of the approach ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; Function to count the number of binary strings of length N having only 0 ' s β and β 1' s ; Driver code"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; #define ll long long
#define mod (ll)(1e9 + 7)
ll power ( ll x , ll y , ll p ) { while ( y > 0 ) { if ( y & 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } ll findCount ( ll N ) { int count = power ( 2 , N , mod ) ; return count ; } int main ( ) { ll N = 25 ; cout << findCount ( N ) ; return 0 ; }
``` |
xp3x | "Integers from the range that are composed of a single distinct digit | C ++ implementation of the approach ; Boolean function to check distinct digits of a number ; Take last digit ; Check if all other digits are same as last digit ; Remove last digit ; Function to return the count of integers that are composed of a single distinct digit only ; If i has single distinct digit ; Driver code"
How can the above be solved in C++? | ```cpp
#include <bits/stdc++.h>
using namespace std ; bool checkDistinct ( int x ) { int last = x % 10 ; while ( x ) { if ( x % 10 != last ) return false ; x = x / 10 ; } return true ; } int findCount ( int L , int R ) { int count = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( checkDistinct ( i ) ) count += 1 ; } return count ; } int main ( ) { int L = 10 , R = 50 ; cout << findCount ( L , R ) ; return 0 ; }
``` |
xp3x | "Divide given numeric string into at most two increasing subsequences which form an increasing string upon concatenation | C ++ program for the above approach ; Function to check for valid subsequences ; Stores which element belongs to which subsequence ; Check for each pos if a possible subsequence exist or not ; Last member of 1 subsequence ; Last Member of 2 nd subsequence ; Check if current element can go to 2 nd subsequence ; Check if the current elements belongs to first subsequence ; If the current element does not belong to any subsequence ; Check if last digit of first subsequence is greater than pos ; If a subsequence is found , find the subsequences ; Stores the resulting subsequences ; Print the subsequence ; If no subsequence found , print - 1 ; Driver Code"
How can the above be solved in C++? | ```cpp
#include <bits/stdc++.h>
using namespace std ; void findSubsequence ( string str ) { int n = str . size ( ) ; char res [ n ] ; for ( int i = 0 ; i < n ; i ++ ) res [ i ] = 0 ; for ( int pos = 0 ; pos <= 9 ; pos ++ ) { char lst1 = '0' ; bool flag = 1 ; char lst2 = pos + '0' ; for ( int i = 0 ; i < n ; i ++ ) { if ( lst2 <= str [ i ] ) { res [ i ] = '2' ; lst2 = str [ i ] ; } else if ( lst1 <= str [ i ] ) { res [ i ] = '1' ; lst1 = str [ i ] ; } else flag = 0 ; } if ( lst1 > pos + '0' ) flag = 0 ; if ( flag ) { string S1 = " " ; string S2 = " " ; for ( int i = 0 ; i < n ; i ++ ) { if ( res [ i ] == '1' ) { S1 += str [ i ] ; } else { S2 += str [ i ] ; } } cout << S1 << ' β ' << S2 << endl ; return ; } } cout << " - 1" ; } int main ( ) { string S = "040425524644" ; findSubsequence ( S ) ; S = "123456789" ; findSubsequence ( S ) ; return 0 ; }
``` |
xp3x | "Sum of all substrings of a string representing a number | Set 1 | C # program to print sum of all substring of a number represented as a string ; Utility method to convert character digit to integer digit ; Returns sum of all subString of num ; Storing prev value ; SubStrings sum upto current index loop over all digits of String ; Update each sumofdigit from previous value ; Add current value to the result ; Update previous ; Driver code to test above methods"
How can the above be solved in C-Sharp? | ```csharp
using System ; class GFG { static int toDigit ( char ch ) { return ( ch - '0' ) ; } static int sumOfSubStrings ( string num ) { int n = num . Length ; int prev = toDigit ( num [ 0 ] ) ; int res = prev ; int current = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int numi = toDigit ( num [ i ] ) ; current = ( i + 1 ) * numi + 10 * prev ; res += current ; prev = current ; } return res ; } static void Main ( ) { string num = "1234" ; Console . WriteLine ( sumOfSubStrings ( num ) ) ; } }
``` |
xp3x | "Find cubic root of a number | Returns the absolute value of n - mid * mid * mid ; Returns cube root of a no n ; Set start and end for binary search ; Set precision ; If error is less than e then mid is our answer so return mid ; If mid * mid * mid is greater than n set end = mid ; If mid * mid * mid is less than n set start = mid ; Driver Code"
How can the above be solved in JS? | ```javascript
function diff ( n , mid ) { if ( n > ( mid * mid * mid ) ) return ( n - ( mid * mid * mid ) ) ; else return ( ( mid * mid * mid ) - n ) ; } function cubicRoot ( n ) { let start = 0 , end = n ; let e = 0.0000001 ; while ( true ) { let mid = ( start + end ) / 2 ; let error = diff ( n , mid ) ; if ( error <= e ) return mid ; if ( ( mid * mid * mid ) > n ) end = mid ; else start = mid ; } } let n = 3 ; document . write ( " " + n + " " + cubicRoot ( n ) ) ;
``` |
xp3x | "Count occurrences of an element in a matrix of size N * N generated such that each element is equal to product of its indices | Set | C # program for the above approach ; Function to count the occurrences of X in the generated square matrix ; Store the required result ; Iterate over the range [ 1 , N ] ; Check if x is a multiple of i or not ; Check if the other multiple exists in the range or not ; Print the result ; Driver Code"
How can the above be solved in C-Sharp? | ```csharp
using System ; class GFG { static void countOccurrences ( int n , int x ) { int count = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( x % i == 0 ) { if ( x / i <= n ) count ++ ; } } Console . WriteLine ( count ) ; } public static void Main ( String [ ] args ) { int N = 7 , X = 12 ; countOccurrences ( N , X ) ; } }
``` |
xp3x | "Count smaller elements on right side | ; Initialize all the counts in countSmaller array as 0 ; Utility function that prints out an array on a line ; Driver code"
Solution in C++: | ```cpp
#include <iostream>
using namespace std ; void constructLowerArray ( int arr [ ] , int * countSmaller , int n ) { int i , j ; for ( i = 0 ; i < n ; i ++ ) countSmaller [ i ] = 0 ; for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] < arr [ i ] ) countSmaller [ i ] ++ ; } } } void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " β " ; cout << "
" ; } int main ( ) { int arr [ ] = { 12 , 10 , 5 , 4 , 2 , 20 , 6 , 1 , 0 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int * low = ( int * ) malloc ( sizeof ( int ) * n ) ; constructLowerArray ( arr , low , n ) ; printArray ( low , n ) ; return 0 ; }
``` |
xp3x | "Count all increasing subsequences | Function To Count all the sub - sequences possible in which digit is greater than all previous digits arr [ ] is array of n digits ; count [ ] array is used to store all sub - sequences possible using that digit count [ ] array covers all the digit from 0 to 9 ; scan each digit in arr [ ] ; count all possible sub - sequences by the digits less than arr [ i ] digit ; store sum of all sub - sequences plus 1 in count [ ] array ; Now sum up the all sequences possible in count [ ] array ; Driver Code"
How can the above be solved in Python? | ```python
def countSub ( arr , n ) :
count = [ 0 for i in range ( 10 ) ]
for i in range ( n ) :
for j in range ( arr [ i ] - 1 , - 1 , - 1 ) :
count [ arr [ i ] ] += count [ j ]
count [ arr [ i ] ] += 1
result = 0
for i in range ( 10 ) :
result += count [ i ]
return result
arr = [ 3 , 2 , 4 , 5 , 4 ]
n = len ( arr )
print ( countSub ( arr , n ) )
``` |
xp3x | "Number of times the largest perfect square number can be subtracted from N | C # implementation of the approach ; Function to return the count of steps ; Variable to store the count of steps ; Iterate while N > 0 ; Get the largest perfect square and subtract it from N ; Increment steps ; Return the required count ; Driver code"
Solution in C#: | ```csharp
using System ; class GfG { static int countSteps ( int n ) { int steps = 0 ; while ( n > 0 ) { int largest = ( int ) Math . Sqrt ( n ) ; n -= ( largest * largest ) ; steps ++ ; } return steps ; } public static void Main ( ) { int n = 85 ; Console . WriteLine ( countSteps ( n ) ) ; } }
``` |
xp3x | "Number of integral solutions for equation x = b * ( sumofdigits ( x ) ^ a ) + c | C # program to find the numbers of values that satisfy the equation ; This function returns the sum of the digits of a number ; This function creates the array of valid numbers ; this computes s ( x ) ^ a ; this gives the result of equation ; checking if the sum same as i ; counter to keep track of numbers ; resultant array ; prints the number ; Driver Code ; calculate which value of x are possible"
How can the above be solved in C-Sharp? | ```csharp
using System ; using System . Collections . Generic ; class GFG { static int getsum ( int a ) { int r = 0 , sum = 0 ; while ( a > 0 ) { r = a % 10 ; sum = sum + r ; a = a / 10 ; } return sum ; } static void value ( int a , int b , int c ) { int no , x = 0 , q = 0 , w = 0 ; List < int > v = new List < int > ( ) ; for ( int i = 1 ; i < 82 ; i ++ ) { no = ( int ) Math . Pow ( i , a ) ; no = b * no + c ; if ( no > 0 && no < 1000000000 ) { x = getsum ( no ) ; if ( x == i ) { q ++ ; v . Add ( no ) ; w ++ ; } } } for ( int i = 0 ; i < v . Count ; i ++ ) { Console . Write ( v [ i ] + " β " ) ; } } public static void Main ( String [ ] args ) { int a = 2 , b = 2 , c = - 1 ; value ( a , b , c ) ; } }
``` |
xp3x | "Check if a number is an Achilles number or not | Program to check if the given number is an Achilles Number ; function to check if the number is powerful number ; First divide the number repeatedly by 2 ; If only 2 ^ 1 divides n ( not higher powers ) , then return false ; if n is not a power of 2 then this loop will execute repeat above process ; Find highest power of " factor " that divides n ; If only factor ^ 1 divides n ( not higher powers ) , then return false ; n must be 1 now if it is not a prime number . Since prime numbers are not powerful , we return false if n is not 1. ; Utility function to check if number is a perfect power or not ; Function to check Achilles Number ; Driver Program"
How can the above be solved in C++? | ```cpp
#include <bits/stdc++.h>
using namespace std ; bool isPowerful ( int n ) { while ( n % 2 == 0 ) { int power = 0 ; while ( n % 2 == 0 ) { n /= 2 ; power ++ ; } if ( power == 1 ) return false ; } for ( int factor = 3 ; factor <= sqrt ( n ) ; factor += 2 ) { int power = 0 ; while ( n % factor == 0 ) { n = n / factor ; power ++ ; } if ( power == 1 ) return false ; } return ( n == 1 ) ; } bool isPower ( int a ) { if ( a == 1 ) return true ; for ( int i = 2 ; i * i <= a ; i ++ ) { double val = log ( a ) / log ( i ) ; if ( ( val - ( int ) val ) < 0.00000001 ) return true ; } return false ; } bool isAchillesNumber ( int n ) { if ( isPowerful ( n ) && ! isPower ( n ) ) return true ; else return false ; } int main ( ) { int n = 72 ; if ( isAchillesNumber ( n ) ) cout << " YES " << endl ; else cout << " NO " << endl ; n = 36 ; if ( isAchillesNumber ( n ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; }
``` |
xp3x | "Check if a string is concatenation of another given string | C ++ program to implement the above approach ; Function to check if a string is concatenation of another string ; Stores the length of str2 ; Stores the length of str1 ; If M is not multiple of N ; Traverse both the strings ; If str1 is not concatenation of str2 ; Driver Code"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; bool checkConcat ( string str1 , string str2 ) { int N = str1 . length ( ) ; int M = str2 . length ( ) ; if ( N % M != 0 ) { return false ; } for ( int i = 0 ; i < N ; i ++ ) { if ( str1 [ i ] != str2 [ i % M ] ) { return false ; } } return true ; } int main ( ) { string str1 = " abcabcabc " ; string str2 = " abc " ; if ( checkConcat ( str1 , str2 ) ) { cout << " Yes " ; } else { cout << " No " ; } }
``` |
xp3x | "Count of Arrays of size N having absolute difference between adjacent elements at most 1 | Function to find the count of possible arrays such that the absolute difference between any adjacent elements is atmost 1 ; Stores the dp states where dp [ i ] [ j ] represents count of arrays of length i + 1 having their last element as j ; Case where 1 st array element is missing ; All integers in range [ 1 , M ] are reachable ; Only reachable integer is arr [ 0 ] ; Iterate through all values of i ; If arr [ i ] is not missing ; Only valid value of j is arr [ i ] ; If arr [ i ] is missing ; Iterate through all possible values of j in range [ 1 , M ] ; Stores the count of valid arrays ; Calculate the total count of valid arrays ; Return answer ; Driver Code ; Function Call"
How can the above be solved in JS? | ```javascript
function countArray ( arr , N , M ) { let dp = new Array ( N ) ; for ( let i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( M + 2 ) . fill ( 0 ) ; } if ( arr [ 0 ] == - 1 ) { for ( let j = 1 ; j <= M ; j ++ ) { dp [ 0 ] [ j ] = 1 ; } } else { dp [ 0 ] [ arr [ 0 ] ] = 1 ; } for ( let i = 1 ; i < N ; i ++ ) { if ( arr [ i ] != - 1 ) { let j = arr [ i ] ; dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j + 1 ] ; } if ( arr [ i ] == - 1 ) { for ( let j = 1 ; j <= M ; j ++ ) { dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j + 1 ] ; } } } let arrCount = 0 ; for ( let j = 1 ; j <= M ; j ++ ) { arrCount += dp [ N - 1 ] [ j ] ; } return arrCount ; } let arr = [ 4 , - 1 , 2 , 1 , - 1 , - 1 ] ; let N = arr . length ; let M = 10 ; document . write ( countArray ( arr , N , M ) ) ;
``` |
xp3x | "Print all the sum pairs which occur maximum number of times | Function to find the sum pairs that occur the most ; Hash - table ; Keep a count of sum pairs ; Variables to store maximum occurrence ; Iterate in the hash table ; Print all sum pair which occur maximum number of times ; Driver code"
How can the above be solved in JS? | ```javascript
function findSumPairs ( a , n ) { let mpp = new Map ( ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) { for ( let j = i + 1 ; j < n ; j ++ ) { if ( mpp [ a [ i ] + a [ j ] ] ) mpp [ a [ i ] + a [ j ] ] ++ ; else mpp [ a [ i ] + a [ j ] ] = 1 ; } } let occur = 0 ; for ( var it in mpp ) { if ( mpp [ it ] > occur ) { occur = mpp [ it ] ; } } for ( var it in mpp ) { if ( mpp [ it ] == occur ) document . write ( it , ' ' ) ; } } let a = [ 1 , 8 , 3 , 11 , 4 , 9 , 2 , 7 ] ; let len = a . length ; findSumPairs ( a , len ) ;
``` |
xp3x | "Program to toggle K | C program to toggle K - th bit of a number N ; Function to toggle the kth bit of n ; Driver code"
Solution in C: | ```c
#include <stdio.h>
int toggleBit ( int n , int k ) { return ( n ^ ( 1 << ( k - 1 ) ) ) ; } int main ( ) { int n = 5 , k = 2 ; printf ( " % d
" , toggleBit ( n , k ) ) ; return 0 ; }
``` |
xp3x | Count numbers that don 't contain 3 | ; returns count of numbers which are in range from 1 to n and don 't contain 3 as a digit ; Base cases ( Assuming n is not negative ) ; Calculate 10 ^ ( d - 1 ) ( 10 raise to the power d - 1 ) where d is number of digits in n . po will be 100 for n = 578 ; find the most significant digit ( msd is 5 for 578 ) ; For 578 , total will be 4 * count ( 10 ^ 2 - 1 ) + 4 + count ( 78 ) ; For 35 , total will be equal to count ( 29 ) ; Driver program to test above function
How can the above be solved in C? | ```c
#include <stdio.h>
int count ( int n ) { if ( n < 3 ) return n ; if ( n >= 3 && n < 10 ) return n - 1 ; int po = 1 ; while ( n / po > 9 ) po = po * 10 ; int msd = n / po ; if ( msd != 3 ) return count ( msd ) * count ( po - 1 ) + count ( msd ) + count ( n % po ) ; else return count ( msd * po - 1 ) ; } int main ( ) { printf ( " % d β " , count ( 578 ) ) ; return 0 ; }
``` |
xp3x | "Fibbinary Numbers ( No consecutive 1 s in binary ) | function to check if binary representation of an integer has consecutive 1 s ; stores the previous last bit initially as 0 ; if current last bit and previous last bit is 1 ; stores the last bit ; right shift the number ; Driver code"
Solution in php: | ```php
< ? php function checkFibinnary ( $ n ) { $ prev_last = 0 ; while ( $ n ) { if ( ( $ n & 1 ) && $ prev_last ) return false ; $ prev_last = $ n & 1 ; $ n >>= 1 ; } return true ; } $ n = 10 ; if ( checkFibinnary ( $ n ) ) echo " YES " ; else echo " NO " ; ? >
``` |
xp3x | "Trimorphic Number | Functions to find nth Trimorphic number ; Comparing the digits ; Return false , if any digit of num doesn ' t β match β with β β its β cube ' s digits from last ; Reduce num and cube ; Check in max int size ; check number is Trimorphic or not ; if counter is equal to the n then return nth number ; Driver code"
How can the above be solved in PHP? | ```php
< ? php function checkTrimorphic ( $ num ) { $ cube = $ num * $ num * $ num ; while ( $ num > 0 ) { if ( $ num % 10 != $ cube % 10 ) return false ; $ num = ( int ) ( $ num / 10 ) ; $ cube = ( int ) ( $ cube / 10 ) ; } return true ; } function nthTrimorphic ( $ n ) { $ count = 0 ; for ( $ i = 0 ; $ i < PHP_INT_MAX ; $ i ++ ) { if ( checkTrimorphic ( $ i ) ) $ count ++ ; if ( $ count == $ n ) return $ i ; } } $ n = 9 ; echo nthTrimorphic ( $ n ) ; ? >
``` |
xp3x | "Count digit groupings of a number with given constraints | Function to find the subgroups ; Terminating Condition ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as previous sum ; Total number of subgroups till current position ; Driver Code"
How can the above be solved in JS? | ```javascript
function countGroups ( position , previous_sum , length , num ) { if ( position == length ) return 1 ; let res = 0 ; let sum = 0 ; for ( let i = position ; i < length ; i ++ ) { sum += ( num [ i ] . charCodeAt ( ) - ' ' . charCodeAt ( ) ) ; if ( sum >= previous_sum ) res += countGroups ( i + 1 , sum , length , num ) ; } return res ; } let num = " " ; let len = num . length ; document . write ( countGroups ( 0 , 0 , len , num ) ) ;
``` |
xp3x | "Set all even bits of a number | return msb set number ; set all bits ; return msb increment n by 1 and shift by 1 ; return even seted number ; get msb here ; generate even bits like 101010. . ; if bits is odd then shift by 1 ; return even set bits number ; set all even bits here ; take or with even set bits number ; Driver code"
How can the above be solved in PHP? | ```php
< ? php function getmsb ( $ n ) { $ n |= $ n >> 1 ; $ n |= $ n >> 2 ; $ n |= $ n >> 4 ; $ n |= $ n >> 8 ; $ n |= $ n >> 16 ; return ( $ n + 1 ) >> 1 ; } function getevenbits ( $ n ) { $ n = getmsb ( $ n ) ; $ n |= $ n >> 2 ; $ n |= $ n >> 4 ; $ n |= $ n >> 8 ; $ n |= $ n >> 16 ; if ( $ n & 1 ) $ n = $ n >> 1 ; return $ n ; } function setallevenbits ( $ n ) { return $ n | getevenbits ( $ n ) ; } $ n = 10 ; echo setallevenbits ( $ n ) ; ? >
``` |
xp3x | "Maximum occurring character in a linked list | C # program to count the maximum occurring character in linked list ; Link list node ; counting the frequency of current element p . data ; if current counting is greater than max ; Push a node to linked list . Note that this function changes the head ; Driver code ; Start with the empty list ; this will create a linked list of character " geeksforgeeks ""
How can the above be solved in C-Sharp? | ```csharp
using System ; class GFG { class Node { public char data ; public Node next ; } ; static Node head_ref ; static char maxChar ( Node head ) { Node p = head ; int max = - 1 ; char res = '0' ; while ( p != null ) { Node q = p . next ; int count = 1 ; while ( q != null ) { if ( p . data == q . data ) count ++ ; q = q . next ; } if ( max < count ) { res = p . data ; max = count ; } p = p . next ; } return res ; } static void push ( char new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; } public static void Main ( string [ ] args ) { head_ref = null ; string str = " skeegforskeeg " ; char [ ] st = str . ToCharArray ( ) ; int i ; for ( i = 0 ; i < st . Length ; i ++ ) push ( st [ i ] ) ; Console . Write ( maxChar ( head_ref ) ) ; } }
``` |
xp3x | "Tree Traversals ( Inorder , Preorder and Postorder ) | C ++ program for different tree traversals ; A binary tree node has data , pointer to left child and a pointer to right child ; Given a binary tree , print its nodes according to the " bottom - up " postorder traversal . ; first recur on left subtree ; then recur on right subtree ; now deal with the node ; Given a binary tree , print its nodes in inorder ; first recur on left child ; then print the data of node ; now recur on right child ; Given a binary tree , print its nodes in preorder ; first print data of node ; then recur on left sutree ; now recur on right subtree ; Driver program to test above functions"
Solution in C++: | ```cpp
#include <iostream>
using namespace std ; struct Node { int data ; struct Node * left , * right ; Node ( int data ) { this -> data = data ; left = right = NULL ; } } ; void printPostorder ( struct Node * node ) { if ( node == NULL ) return ; printPostorder ( node -> left ) ; printPostorder ( node -> right ) ; cout << node -> data << " β " ; } void printInorder ( struct Node * node ) { if ( node == NULL ) return ; printInorder ( node -> left ) ; cout << node -> data << " β " ; printInorder ( node -> right ) ; } void printPreorder ( struct Node * node ) { if ( node == NULL ) return ; cout << node -> data << " β " ; printPreorder ( node -> left ) ; printPreorder ( node -> right ) ; } int main ( ) { struct Node * root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; root -> left -> left = new Node ( 4 ) ; root -> left -> right = new Node ( 5 ) ; cout << " Preorder traversal of binary tree is " ; printPreorder ( root ) ; cout << " Inorder traversal of binary tree is " ; printInorder ( root ) ; cout << " Postorder traversal of binary tree is " ; printPostorder ( root ) ; return 0 ; }
``` |
xp3x | "Radii of the three tangent circles of equal radius which are inscribed within a circle of given radius | Python3 program to find the radii of the three tangent circles of equal radius when the radius of the circumscribed circle is given ; Driver code"
How can the above be solved in Python? | ```python
def threetangcircle ( R ) :
print ( " The β radii β of β the β tangent " , " circles β is β " , end = " " ) ;
print ( 0.4645 * R ) ;
R = 4 ;
threetangcircle ( R ) ;
``` |
xp3x | Modular exponentiation ( Recursive ) | Recursive C program to compute modular power ; Base cases ; If B is even ; If B is odd ; Driver program to test above functions
How can the above be solved in C? | ```c
#include <stdio.h>
int exponentMod ( int A , int B , int C ) { if ( A == 0 ) return 0 ; if ( B == 0 ) return 1 ; long y ; if ( B % 2 == 0 ) { y = exponentMod ( A , B / 2 , C ) ; y = ( y * y ) % C ; } else { y = A % C ; y = ( y * exponentMod ( A , B - 1 , C ) % C ) % C ; } return ( int ) ( ( y + C ) % C ) ; } int main ( ) { int A = 2 , B = 5 , C = 13 ; printf ( " Power β is β % d " , exponentMod ( A , B , C ) ) ; return 0 ; }
``` |
xp3x | "Largest Ratio Contiguous subarray | Function to return maximum of two double values ; Check if a is greater than b then return a ; Function that returns the Ratio of max Ratio subarray ; Variable to store the maximum ratio ; Compute the product while traversing for subarrays ; Calculate the ratio ; Update max ratio ; Print the answer ; Driver code"
Solution in Javascript: | ```javascript
function maximum ( a , b ) { if ( a > b ) return a ; return b ; } function maxSubarrayRatio ( arr , n ) { var maxRatio = - 1000000000 ; for ( var i = 0 ; i < n ; i ++ ) { for ( var j = i ; j < n ; j ++ ) { var ratio = arr [ i ] ; for ( var k = i + 1 ; k <= j ; k ++ ) { ratio = ratio / arr [ k ] ; } maxRatio = maximum ( maxRatio , ratio ) ; } } return maxRatio ; } var arr = [ 2 , 2 , 4 , - 0.2 , - 1 ] ; var n = arr . length ; document . write ( maxSubarrayRatio ( arr , n ) ) ;
``` |
xp3x | "Length of longest common subsequence containing vowels | Java implementation to find the length of longest common subsequence which contains all vowel characters ; function to check whether ' ch ' is a vowel or not ; function to find the length of longest common subsequence which contains all vowel characters ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] which contains all vowel characters ; Driver Code"
How can the above be solved in Java? | ```java
class GFG { static boolean isVowel ( char ch ) { if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) return true ; return false ; } static int lcs ( String X , String Y , int m , int n ) { int L [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= m ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( ( X . charAt ( i - 1 ) == Y . charAt ( j - 1 ) ) && isVowel ( X . charAt ( i - 1 ) ) ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = Math . max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } public static void main ( String [ ] args ) { String X = " aieef " ; String Y = " klaief " ; int m = X . length ( ) ; int n = Y . length ( ) ; System . out . println ( " Length β of β LCS β = β " + lcs ( X , Y , m , n ) ) ; } }
``` |
xp3x | "Centered decagonal number | Centered decagonal number function ; Formula to calculate nth centered decagonal number & return it into main function . ; Driver Code"
How can the above be solved in Python? | ```python
def centereddecagonalnum ( n ) :
return ( 5 * n * n + 5 * n + 1 )
if __name__ == ' _ _ main _ _ ' :
n = 5
print ( n , " th β centered β decagonal β " + " number β : β " , centereddecagonalnum ( n ) )
n = 9
print ( n , " th β centered β decagonal β " + " number β : β " , centereddecagonalnum ( n ) )
``` |
xp3x | "Find sum of digits in factorial of a number | Function to multiply x with large number stored in vector v . Result is stored in v . ; Calculate res + prev carry ; updation at ith position ; Returns sum of digits in n ! ; One by one multiply i to current vector and update the vector . ; Find sum of digits in vector v [ ] ; Driver code"
How can the above be solved in PHP? | ```php
< ? php function multiply ( & $ v , $ x ) { $ carry = 0 ; $ size = count ( $ v ) ; for ( $ i = 0 ; $ i < $ size ; $ i ++ ) { $ res = $ carry + $ v [ $ i ] * $ x ; $ v [ $ i ] = $ res % 10 ; $ carry = ( int ) ( $ res / 10 ) ; } while ( $ carry != 0 ) { array_push ( $ v , $ carry % 10 ) ; $ carry = ( int ) ( $ carry / 10 ) ; } } function findSumOfDigits ( $ n ) { for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) multiply ( $ v , $ i ) ; $ sum = 0 ; $ size = count ( $ v ) ; for ( $ i = 0 ; $ i < $ size ; $ i ++ ) $ sum += $ v [ $ i ] ; return $ sum ; } $ n = 1000 ; print ( findSumOfDigits ( $ n ) ) ; ? >
``` |
xp3x | "Given a number n , count all multiples of 3 and / or 5 in set { 1 , 2 , 3 , ... n } | python program to find count of multiples of 3 and 5 in { 1 , 2 , 3 , . . n } ; Add multiples of 3 and 5. Since common multiples are counted twice in n / 3 + n / 15 , subtract common multiples ; Driver program to test above function"
How can the above be solved in Python? | ```python
def countOfMultiples ( n ) :
return ( int ( n / 3 ) + int ( n / 5 ) - int ( n / 15 ) ) ;
print ( countOfMultiples ( 6 ) )
print ( countOfMultiples ( 16 ) )
``` |
xp3x | "Check if both halves of the string have at least one different character | Java implementation to check if both halves of the string have at least one different character ; Function which break string into two halves Sorts the two halves separately Compares the two halves return true if any index has non - zero value ; Declaration and initialization of counter array ; Driver code"
How can the above be solved in Java? | ```java
import java . io . * ; import java . util . * ; class GFG { static Boolean function ( char str [ ] ) { int l = str . length ; Arrays . sort ( str , 0 , ( l / 2 ) ) ; Arrays . sort ( str , ( l / 2 ) , l ) ; for ( int i = 0 ; i < l / 2 ; i ++ ) if ( str [ i ] != str [ l / 2 + i ] ) return true ; return false ; } public static void main ( String [ ] args ) { char str [ ] = ( " abcasdsabcae " ) . toCharArray ( ) ; if ( function ( str ) ) System . out . println ( " Yes , β both β halves β differ " + " β by β at β least β one β character " ) ; else System . out . println ( " No , β both β halves β do " + " β not β differ β at β all " ) ; } }
``` |
xp3x | "Find a pair of overlapping intervals from a given Set | Function to find a pair ( i , j ) such that i - th interval lies within the j - th interval ; Store interval and index of the interval in the form of { { l , r } , index } ; Traverse the array , arr [ ] [ ] ; Stores l - value of the interval ; Stores r - value of the interval ; Push current interval and index into tup ; Sort the vector based on l - value of the intervals ; Stores r - value of current interval ; Stores index of current interval ; Traverse the vector , tup [ ] ; Stores l - value of previous interval ; Stores l - value of current interval ; If Q and R equal ; If Y value of immediate previous interval is less than Y value of current interval ; Print the index of interval ; Stores r - value of current interval ; T is less than or equal to curr ; Update curr ; Update currPos ; If such intervals found ; Driver Code Given l - value of segments ; Given r - value of segments ; Given size ; Function Call"
How can the above be solved in JS? | ```javascript
function findOverlapSegement ( N , a , b ) { var tup = [ ] ; for ( var i = 0 ; i < N ; i ++ ) { var x , y ; x = a [ i ] ; y = b [ i ] ; tup . push ( [ [ x , y ] , i ] ) ; } tup . sort ( ( a , b ) => { if ( a [ 0 ] [ 0 ] == b [ 0 ] [ 0 ] ) { return a [ 0 ] [ 1 ] - b [ 0 ] [ 1 ] ; } var tmp = ( a [ 0 ] [ 0 ] - b [ 0 ] [ 0 ] ) ; console . log ( tmp ) ; return ( a [ 0 ] [ 0 ] - b [ 0 ] [ 0 ] ) } ) ; var curr = tup [ 0 ] [ 0 ] [ 1 ] ; var currPos = tup [ 0 ] [ 1 ] ; for ( var i = 1 ; i < N ; i ++ ) { var Q = tup [ i - 1 ] [ 0 ] [ 0 ] ; var R = tup [ i ] [ 0 ] [ 0 ] ; if ( Q == R ) { if ( tup [ i - 1 ] [ 0 ] [ 1 ] < tup [ i ] [ 0 ] [ 1 ] ) { document . write ( tup [ i - 1 ] [ 1 ] + " " + tup [ i ] [ 1 ] ) ; return ; } else { document . write ( tup [ i ] [ 1 ] + " " + tup [ i - 1 ] [ 1 ] ) ; return ; } } var T = tup [ i ] [ 0 ] [ 1 ] ; if ( T <= curr ) { document . write ( tup [ i ] [ 1 ] + " " + currPos ) ; return ; } else { curr = T ; currPos = tup [ i ] [ 1 ] ; } } document . write ( " " ) ; } let a = [ 1 , 2 , 3 , 2 , 2 ] ; let b = [ 5 , 10 , 10 , 2 , 15 ] ; let N = a . length ; findOverlapSegement ( N , a , b ) ;
``` |
xp3x | Area of Circumcircle of a Right Angled Triangle | C program to find the area of Cicumscribed circle of right angled triangle ; Function to find area of circumscribed circle ; Driver code
How can the above be solved in C? | ```c
#include <stdio.h>
#define PI 3.14159265
float area_circumscribed ( float c ) { return ( c * c * ( PI / 4 ) ) ; } int main ( ) { float c = 8 ; printf ( " % f " , area_circumscribed ( c ) ) ; return 0 ; }
``` |
xp3x | Detect loop in a linked list | C program to detect loop in a linked list ; Link list node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Driver program to test above function ; Start with the empty list ; Create a loop for testing
How can the above be solved in C? | ```c
#include <stdio.h>
#include <stdlib.h>
struct Node { int data ; struct Node * next ; } ; 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 detectLoop ( struct Node * list ) { struct Node * slow_p = list , * fast_p = list ; while ( slow_p && fast_p && fast_p -> next ) { slow_p = slow_p -> next ; fast_p = fast_p -> next -> next ; if ( slow_p == fast_p ) { return 1 ; } } return 0 ; } int main ( ) { struct Node * head = NULL ; push ( & head , 20 ) ; push ( & head , 4 ) ; push ( & head , 15 ) ; push ( & head , 10 ) ; head -> next -> next -> next -> next = head ; if ( detectLoop ( head ) ) printf ( " Loop β found " ) ; else printf ( " No β Loop " ) ; return 0 ; }
``` |
xp3x | "Queries for elements greater than K in the given index range using Segment Tree | C ++ implementation of the approach ; Merge procedure to merge two vectors into a single vector ; Final vector to return after merging ; Loop continues until it reaches the end of one of the vectors ; Here , simply add the remaining elements to the vector v ; Procedure to build the segment tree ; Reached the leaf node of the segment tree ; Recursively call the buildTree on both the nodes of the tree ; Storing the final vector after merging the two of its sorted child vector ; Query procedure to get the answer for each query l and r are query range ; out of bound or no overlap ; Complete overlap Query range completely lies in the segment tree node range ; binary search to find index of k ; Partially overlap Query range partially lies in the segment tree node range ; Function to perform the queries ; Driver code ; 1 - based indexing ; Number of queries"
How can the above be solved in C++? | ```cpp
#include <bits/stdc++.h>
using namespace std ; vector < int > merge ( vector < int > & v1 , vector < int > & v2 ) { int i = 0 , j = 0 ; vector < int > v ; while ( i < v1 . size ( ) && j < v2 . size ( ) ) { if ( v1 [ i ] <= v2 [ j ] ) { v . push_back ( v1 [ i ] ) ; i ++ ; } else { v . push_back ( v2 [ j ] ) ; j ++ ; } } for ( int k = i ; k < v1 . size ( ) ; k ++ ) v . push_back ( v1 [ k ] ) ; for ( int k = j ; k < v2 . size ( ) ; k ++ ) v . push_back ( v2 [ k ] ) ; return v ; } void buildTree ( vector < int > * tree , int * arr , int index , int s , int e ) { if ( s == e ) { tree [ index ] . push_back ( arr [ s ] ) ; return ; } int mid = ( s + e ) / 2 ; buildTree ( tree , arr , 2 * index , s , mid ) ; buildTree ( tree , arr , 2 * index + 1 , mid + 1 , e ) ; tree [ index ] = merge ( tree [ 2 * index ] , tree [ 2 * index + 1 ] ) ; } int query ( vector < int > * tree , int index , int s , int e , int l , int r , int k ) { if ( r < s l > e ) return 0 ; if ( s >= l && e <= r ) { return ( tree [ index ] . size ( ) - ( lower_bound ( tree [ index ] . begin ( ) , tree [ index ] . end ( ) , k ) - tree [ index ] . begin ( ) ) ) ; } int mid = ( s + e ) / 2 ; return ( query ( tree , 2 * index , s , mid , l , r , k ) + query ( tree , 2 * index + 1 , mid + 1 , e , l , r , k ) ) ; } void performQueries ( int L [ ] , int R [ ] , int K [ ] , int n , int q , vector < int > tree [ ] ) { for ( int i = 0 ; i < q ; i ++ ) { cout << query ( tree , 1 , 0 , n - 1 , L [ i ] - 1 , R [ i ] - 1 , K [ i ] ) << endl ; } } int main ( ) { int arr [ ] = { 7 , 3 , 9 , 13 , 5 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; vector < int > tree [ 4 * n + 1 ] ; buildTree ( tree , arr , 1 , 0 , n - 1 ) ; int L [ ] = { 1 , 2 } ; int R [ ] = { 4 , 6 } ; int K [ ] = { 6 , 8 } ; int q = sizeof ( L ) / sizeof ( L [ 0 ] ) ; performQueries ( L , R , K , n , q , tree ) ; return 0 ; }
``` |
xp3x | "How to swap two numbers without using a temporary variable ? | C Program to swap two numbers without using temporary variable ; Code to swap ' x ' and ' y ' x now becomes 50 ; y becomes 10 ; x becomes 5"
Solution in C: | ```c
#include <stdio.h>
int main ( ) { int x = 10 , y = 5 ; x = x * y ; y = x / y ; x = x / y ; printf ( " After β Swapping : β x β = β % d , β y β = β % d " , x , y ) ; return 0 ; }
``` |
xp3x | "Largest triangle that can be inscribed in a semicircle | Function to find the area of the triangle ; the radius cannot be negative ; area of the triangle ; Driver Code"
How can the above be solved in Python? | ```python
def trianglearea ( r ) :
if r < 0 :
return - 1
return r * r
if __name__ == " _ _ main _ _ " :
r = 5
print ( trianglearea ( r ) )
``` |
xp3x | "Program to count leaf nodes in a binary tree | C implementation to find leaf count of a given Binary tree ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to get the count of leaf nodes in a binary tree ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver program to test above functions ; create a tree ; get leaf count of the above created tree"
Solution in C: | ```c
#include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left ; struct node * right ; } ; unsigned int getLeafCount ( struct node * node ) { if ( node == NULL ) return 0 ; if ( node -> left == NULL && node -> right == NULL ) return 1 ; else return getLeafCount ( node -> left ) + getLeafCount ( node -> right ) ; } struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = NULL ; node -> right = NULL ; return ( node ) ; } int main ( ) { struct node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; printf ( " Leaf β count β of β the β tree β is β % d " , getLeafCount ( root ) ) ; getchar ( ) ; return 0 ; }
``` |
xp3x | "Nesbitt 's Inequality | PHP code to verify Nesbitt 's Inequality ; 3 parts of the inequality sum ; Driver Code"
How can the above be solved in PHP? | ```php
< ? php function isValidNesbitt ( $ a , $ b , $ c ) { $ A = $ a / ( $ b + $ c ) ; $ B = $ b / ( $ a + $ c ) ; $ C = $ c / ( $ a + $ b ) ; $ inequality = $ A + $ B + $ C ; return ( $ inequality >= 1.5 ) ; } $ a = 1.0 ; $ b = 2.0 ; $ c = 3.0 ; if ( isValidNesbitt ( $ a , $ b , $ c ) ) echo " Nesbitt ' s β inequality β satisfied . " , " for β real β numbers β " , $ a , " , β " , $ b , " , β " , $ c , "
" ; else cout << " Not β satisfied " ; ? >
``` |
xp3x | "Find Minimum Depth of a Binary Tree | A Binary Tree node ; Iterative method to find minimum depth of Binary Tree ; Corner Case ; Create an empty queue for level order traversal ; Enqueue root and initialize depth as 1 ; Do level order traversal ; Remove the front queue item ; Get details of the removed item ; If this is the first leaf node seen so far then return its depth as answer ; If left subtree is not None , add it to queue ; if right subtree is not None , add it to queue ; Lets construct a binary tree shown in above diagram"
How can the above be solved in Python? | ```python
class Node :
def __init__ ( self , data ) :
self . data = data
self . left = None
self . right = None
def minDepth ( root ) :
if root is None :
return 0
q = [ ]
q . append ( { ' node ' : root , ' depth ' : 1 } )
while ( len ( q ) > 0 ) :
queueItem = q . pop ( 0 )
node = queueItem [ ' node ' ]
depth = queueItem [ ' depth ' ]
if node . left is None and node . right is None :
return depth
if node . left is not None :
q . append ( { ' node ' : node . left , ' depth ' : depth + 1 } )
if node . right is not None :
q . append ( { ' node ' : node . right , ' depth ' : depth + 1 } )
root = Node ( 1 )
root . left = Node ( 2 )
root . right = Node ( 3 )
root . left . left = Node ( 4 )
root . left . right = Node ( 5 )
print minDepth ( root )
``` |
xp3x | Print alternate elements of an array | C program to implement the above approach ; Function to print Alternate elements of the given array ; Print elements at odd positions ; Print elements of array ; Driver Code
How can the above be solved in C? | ```c
#include <stdio.h>
void printAlter ( int arr [ ] , int N ) { for ( int currIndex = 0 ; currIndex < N ; currIndex += 2 ) { printf ( " % d β " , arr [ currIndex ] ) ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printAlter ( arr , N ) ; }
``` |
xp3x | "Count positions in Binary Matrix having equal count of set bits in corresponding row and column | Java Program to implement above approach ; Function to return the count of indices in from the given binary matrix having equal count of set bits in its row and column ; Stores count of set bits in corresponding column and row ; Traverse matrix ; Since 1 contains a set bit ; Update count of set bits for current row and col ; Stores the count of required indices ; Traverse matrix ; If current row and column has equal count of set bits ; Return count of required position ; Driver Code"
How can the above be solved in Java? | ```java
import java . util . * ; import java . lang . * ; class GFG { static int countPosition ( int [ ] [ ] mat ) { int n = mat . length ; int m = mat [ 0 ] . length ; int [ ] row = new int [ n ] ; int [ ] col = new int [ m ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( mat [ i ] [ j ] == 1 ) { col [ j ] ++ ; row [ i ] ++ ; } } } int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( row [ i ] == col [ j ] ) { count ++ ; } } } return count ; } public static void main ( String [ ] args ) { int mat [ ] [ ] = { { 0 , 1 } , { 1 , 1 } } ; System . out . println ( countPosition ( mat ) ) ; } }
``` |
xp3x | "Count of Nodes at distance K from S in its subtree for Q queries | C ++ program for the above approach ; Function to add edges ; Function to perform Depth First Search ; Stores the entry time of a node ; Stores the entering time of a node at depth d ; Iterate over the children of node ; Stores the Exit time of a node ; Function to find number of nodes at distance K from node S in the subtree of S ; Distance from root node ; Index of node with greater tin value then tin [ S ] ; Index of node with greater tout value then tout [ S ] ; Answer to the Query ; Function for performing DFS and answer to queries ; DFS function call ; Traverse the array Q [ ] ; Driver Code ; Input ; Function call"
How can the above be solved in C++? | ```cpp
#include <bits/stdc++.h>
using namespace std ; int tin [ 100 ] , tout [ 100 ] , depth [ 100 ] ; int t = 0 ; void Add_edge ( int parent , int child , vector < vector < int > > & adj ) { adj [ parent ] . push_back ( child ) ; adj [ child ] . push_back ( parent ) ; } void dfs ( int node , int parent , vector < vector < int > > & adj , vector < vector < int > > & levels , int d ) { tin [ node ] = t ++ ; levels [ d ] . push_back ( tin [ node ] ) ; depth [ node ] = d ; for ( auto x : adj [ node ] ) { if ( x != parent ) dfs ( x , node , adj , levels , d + 1 ) ; } tout [ node ] = t ++ ; } void numberOfNodes ( int node , int dist , vector < vector < int > > & levels ) { dist += depth [ node ] ; int start = lower_bound ( levels [ dist ] . begin ( ) , levels [ dist ] . end ( ) , tin [ node ] ) - levels [ dist ] . begin ( ) ; int ed = lower_bound ( levels [ dist ] . begin ( ) , levels [ dist ] . end ( ) , tout [ node ] ) - levels [ dist ] . begin ( ) ; cout << ed - start << endl ; } void numberOfNodesUtil ( pair < int , int > Q [ ] , int M , int N ) { vector < vector < int > > adj ( N + 5 ) , levels ( N + 5 ) ; Add_edge ( 1 , 2 , adj ) ; Add_edge ( 1 , 3 , adj ) ; Add_edge ( 2 , 4 , adj ) ; Add_edge ( 2 , 5 , adj ) ; Add_edge ( 2 , 6 , adj ) ; t = 1 ; dfs ( 1 , 1 , adj , levels , 0 ) ; for ( int i = 0 ; i < M ; ++ i ) { numberOfNodes ( Q [ i ] . first , Q [ i ] . second , levels ) ; } } int main ( ) { int N = 6 ; pair < int , int > Q [ ] = { { 2 , 1 } , { 1 , 1 } } ; int M = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; numberOfNodesUtil ( Q , M , N ) ; }
``` |
xp3x | "Sum of LCM ( 1 , n ) , LCM ( 2 , n ) , LCM ( 3 , n ) , ... , LCM ( n , n ) | PHP implementation of the approach ; Euler totient Function ; Function to return the required LCM sum ; Summation of d * ETF ( d ) where d belongs to set of divisors of n ; Driver code"
Solution in php: | ```php
< ? php $ n = 10002 ; $ phi = array_fill ( 0 , $ n + 2 , 0 ) ; $ ans = array_fill ( 0 , $ n + 2 , 0 ) ; function ETF ( ) { global $ phi , $ n ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) { $ phi [ $ i ] = $ i ; } for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) { if ( $ phi [ $ i ] == $ i ) { $ phi [ $ i ] = $ i - 1 ; for ( $ j = 2 * $ i ; $ j <= $ n ; $ j += $ i ) { $ phi [ $ j ] = ( int ) ( ( $ phi [ $ j ] * ( $ i - 1 ) ) / $ i ) ; } } } } function LcmSum ( $ m ) { ETF ( ) ; global $ ans , $ n , $ phi ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) { for ( $ j = $ i ; $ j <= $ n ; $ j += $ i ) { $ ans [ $ j ] += ( $ i * $ phi [ $ i ] ) ; } } $ answer = $ ans [ $ m ] ; $ answer = ( $ answer + 1 ) * $ m ; $ answer = ( int ) ( $ answer / 2 ) ; return $ answer ; } $ m = 5 ; echo LcmSum ( $ m ) ; ? >
``` |
xp3x | "Program to find last two digits of 2 ^ n | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; x = x % p ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 ; y = y / 2 ; JavaScript function to calculate number of digits in x ; JavaScript function to prlet last 2 digits of 2 ^ n ; Generating 10 ^ 2 ; Calling modular exponentiation ; Printing leftmost zeros . Since ( 2 ^ n ) % 2 can have digits less then 2. In that case we need to prlet zeros ; If temp is not zero then print temp . If temp is zero then already prleted ; driver program"
How can the above be solved in JS? | ```javascript
function power ( x , y , p ) { while ( y > 0 ) { let r = y & 1 ; if ( r == 1 ) res = ( res * x ) % p ; x = ( x * x ) % p ; } return res ; } function numberOfDigits ( x ) { let i = 0 ; while ( x != 0 ) { x /= 10 ; i ++ ; } return i ; } function LastTwoDigit ( n ) { document . write ( " " + 2 + " " + 2 + " " ) ; document . write ( n + " " ) ; let temp = 1 ; for ( let i = 1 ; i <= 2 ; i ++ ) temp *= 10 ; temp = power ( 2 , n , temp ) ; for ( let i = 0 ; i < ( 2 - numberOfDigits ( temp ) ) ; i ++ ) document . write ( 0 + " " ) ; if ( temp != 0 ) document . write ( temp ) ; } let n = 72 ; LastTwoDigit ( n ) ;
``` |
xp3x | "Program to find Greatest Common Divisor ( GCD ) of N strings | Function that finds gcd of 2 strings ; If str1 length is less than that of str2 then recur with gcd ( str2 , str1 ) ; If str1 is not the concatenation of str2 ; GCD string is found ; Cut off the common prefix part of str1 & then recur ; Function to find GCD of array of strings ; Return the GCD of strings ; Given array of strings ; Function Call"
How can the above be solved in Python? | ```python
def gcd ( str1 , str2 ) :
if ( len ( str1 ) < len ( str2 ) ) :
return gcd ( str2 , str1 )
elif ( not str1 . startswith ( str2 ) ) :
return " "
elif ( len ( str2 ) == 0 ) :
return str1
else :
return gcd ( str1 [ len ( str2 ) : ] , str2 )
def findGCD ( arr , n ) :
result = arr [ 0 ]
for i in range ( 1 , n ) :
result = gcd ( result , arr [ i ] )
return result
arr = [ " GFGGFG " , " GFGGFG " , " GFGGFGGFGGFG " ]
n = len ( arr )
print ( findGCD ( arr , n ) )
``` |
xp3x | "Minimum swaps required to make a binary string alternating | C ++ implementation of the above approach ; function to count minimum swaps required to make binary string alternating ; stores total number of ones ; stores total number of zeroes ; checking impossible condition ; odd length string ; number of even positions ; stores number of zeroes and ones at even positions ; even length string ; stores number of ones at odd and even position respectively ; Driver code"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; int countMinSwaps ( string s ) { int N = s . size ( ) ; int one = 0 ; int zero = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) one ++ ; else zero ++ ; } if ( one > zero + 1 zero > one + 1 ) return -1 ; if ( N % 2 ) { int num = ( N + 1 ) / 2 ; int one_even = 0 , zero_even = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i % 2 == 0 ) { if ( s [ i ] == '1' ) one_even ++ ; else zero_even ++ ; } } if ( one > zero ) return num - one_even ; else return num - zero_even ; } else { int one_odd = 0 , one_even = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == '1' ) { if ( i % 2 ) one_odd ++ ; else one_even ++ ; } } return min ( N / 2 - one_odd , N / 2 - one_even ) ; } } int main ( ) { string s = "111000" ; cout << countMinSwaps ( s ) ; return 0 ; }
``` |
xp3x | "Sum of width ( max and min diff ) of all Subsequences | CPP implementation of above approach ; Function to return sum of width of all subsets ; Sort the array ; Driver program"
How can the above be solved in C++? | ```cpp
#include <bits/stdc++.h>
using namespace std ; #define MOD 1000000007
int SubseqWidths ( int A [ ] , int n ) { sort ( A , A + n ) ; int pow2 [ n ] ; pow2 [ 0 ] = 1 ; for ( int i = 1 ; i < n ; ++ i ) pow2 [ i ] = ( pow2 [ i - 1 ] * 2 ) % MOD ; int ans = 0 ; for ( int i = 0 ; i < n ; ++ i ) ans = ( ans + ( pow2 [ i ] - pow2 [ n - 1 - i ] ) * A [ i ] ) % MOD ; return ans ; } int main ( ) { int A [ ] = { 5 , 6 , 4 , 3 , 8 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << SubseqWidths ( A , n ) ; return 0 ; }
``` |
xp3x | "Minimum length paths between 1 to N including each node | C ++ program for the above approach ; Function to calculate the distances from node 1 to N ; Vector to store our edges ; Storing the edgees in the Vector ; Initialize queue ; BFS from first node using queue ; Pop from queue ; Traversing its adjacency list ; Initialize queue ; BFS from last node using queue ; Pop from queue ; Traversing its adjacency list ; Printing the minimum distance including node i ; If not reachable ; Path exists ; Driver Code ; Given Input ; Function Call"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; #define ll long long int
void minDisIncludingNode ( int n , int m , int edges [ ] [ 2 ] ) { vector < ll > g [ 10005 ] ; for ( int i = 0 ; i < m ; i ++ ) { int a = edges [ i ] [ 0 ] - 1 ; int b = edges [ i ] [ 1 ] - 1 ; g [ a ] . push_back ( b ) ; g [ b ] . push_back ( a ) ; } queue < pair < ll , ll > > q ; q . push ( { 0 , 0 } ) ; vector < int > dist ( n , 1e9 ) ; dist [ 0 ] = 0 ; while ( ! q . empty ( ) ) { auto up = q . front ( ) ; q . pop ( ) ; int x = up . first ; int lev = up . second ; if ( lev > dist [ x ] ) continue ; if ( x == n - 1 ) continue ; for ( ll y : g [ x ] ) { if ( dist [ y ] > lev + 1 ) { dist [ y ] = lev + 1 ; q . push ( { y , lev + 1 } ) ; } } } queue < pair < ll , ll > > q1 ; q1 . push ( { n - 1 , 0 } ) ; vector < int > dist1 ( n , 1e9 ) ; dist1 [ n - 1 ] = 0 ; while ( ! q1 . empty ( ) ) { auto up = q1 . front ( ) ; q1 . pop ( ) ; int x = up . first ; int lev = up . second ; if ( lev > dist1 [ x ] ) continue ; if ( x == 0 ) continue ; for ( ll y : g [ x ] ) { if ( dist1 [ y ] > lev + 1 ) { dist1 [ y ] = lev + 1 ; q1 . push ( { y , lev + 1 } ) ; } } } for ( int i = 0 ; i < n ; i ++ ) { if ( dist [ i ] + dist1 [ i ] > 1e9 ) cout << -1 << " β " ; else cout << dist [ i ] + dist1 [ i ] << " β " ; } } int main ( ) { int n = 5 ; int m = 7 ; int edges [ m ] [ 2 ] = { { 1 , 2 } , { 1 , 4 } , { 2 , 3 } , { 2 , 5 } , { 4 , 3 } , { 4 , 5 } , { 1 , 5 } } ; minDisIncludingNode ( n , m , edges ) ; return 0 ; }
``` |
xp3x | "Find sum of all nodes of the given perfect binary tree | ; function to find sum of all of the nodes of given perfect binary tree ; no of leaf nodes ; list of vector to store nodes of all of the levels ; store the nodes of last level i . e . , the leaf nodes ; store nodes of rest of the level by moving in bottom - up manner ; loop to calculate values of parent nodes from the children nodes of lower level ; store the value of parent node as sum of children nodes ; traverse the list of vector and calculate the sum ; Driver Code"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; int sumNodes ( int l ) { int leafNodeCount = pow ( 2 , l - 1 ) ; vector < int > vec [ l ] ; for ( int i = 1 ; i <= leafNodeCount ; i ++ ) vec [ l - 1 ] . push_back ( i ) ; for ( int i = l - 2 ; i >= 0 ; i -- ) { int k = 0 ; while ( k < vec [ i + 1 ] . size ( ) - 1 ) { vec [ i ] . push_back ( vec [ i + 1 ] [ k ] + vec [ i + 1 ] [ k + 1 ] ) ; k += 2 ; } } int sum = 0 ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = 0 ; j < vec [ i ] . size ( ) ; j ++ ) sum += vec [ i ] [ j ] ; } return sum ; } int main ( ) { int l = 3 ; cout << sumNodes ( l ) ; return 0 ; }
``` |
xp3x | "Elements of Array which can be expressed as power of prime numbers | C # program to print all elements of Array which can be expressed as power of prime numbers ; Function to mark all the exponent of prime numbers ; If number is prime then marking all of its exponent true ; Function to display all required elements ; Function to print the required numbers ; To find the largest number ; Function call to mark all the Exponential prime nos . ; Function call ; Driver code"
How can the above be solved in C-Sharp? | ```csharp
using System ; class GFG { static void ModifiedSieveOfEratosthenes ( int N , bool [ ] Expo_Prime ) { bool [ ] primes = new bool [ N ] ; for ( int i = 0 ; i < N ; i ++ ) primes [ i ] = true ; for ( int i = 2 ; i < N ; i ++ ) { if ( primes [ i ] ) { int no = i ; while ( no <= N ) { Expo_Prime [ no ] = true ; no *= i ; } for ( int j = i * i ; j < N ; j += i ) primes [ j ] = false ; } } } static void Display ( int [ ] arr , bool [ ] Expo_Prime , int n ) { for ( int i = 0 ; i < n ; i ++ ) if ( Expo_Prime [ arr [ i ] ] ) Console . Write ( arr [ i ] + " β " ) ; } static void FindExpoPrime ( int [ ] arr , int n ) { int max = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( max < arr [ i ] ) max = arr [ i ] ; } bool [ ] Expo_Prime = new bool [ max + 1 ] ; ModifiedSieveOfEratosthenes ( max + 1 , Expo_Prime ) ; Display ( arr , Expo_Prime , n ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 6 , 9 , 16 , 1 , 3 , 12 , 36 , 625 , 1000 } ; int n = arr . Length ; FindExpoPrime ( arr , n ) ; } }
``` |
xp3x | "Split array into two subsequences having minimum count of pairs with sum equal to X | Java program for the above approach ; Function to split the array into two subsequences ; Stores the two subsequences ; Flag to set / reset to split arrays elements alternately into two arrays ; Traverse the given array ; If 2 * arr [ i ] is less than X ; Push element into the first array ; If 2 * arr [ i ] is greater than X ; Push element into the second array ; If 2 * arr [ i ] is equal to X ; Alternatively place the elements into the two arrays ; Print both the arrays ; Driver Code ; Size of the array ; Function Call"
How can the above be solved in Java? | ```java
import java . util . * ; class GFG { static void solve ( int arr [ ] , int N , int X ) { Vector < Integer > A = new Vector < Integer > ( ) , B = new Vector < Integer > ( ) ; int c = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( ( 2 * arr [ i ] ) < X ) { A . add ( arr [ i ] ) ; } else if ( ( 2 * arr [ i ] ) > X ) { B . add ( arr [ i ] ) ; } else { if ( c % 2 == 0 ) { A . add ( arr [ i ] ) ; } else { B . add ( arr [ i ] ) ; } c ++ ; } } System . out . print ( " The β First β Array β is β - β " ) ; for ( int i = 0 ; i < A . size ( ) ; i ++ ) { System . out . print ( A . get ( i ) + " β " ) ; } System . out . println ( ) ; System . out . print ( " The β Second β Array β is β - β " ) ; for ( int i = 0 ; i < B . size ( ) ; i ++ ) { System . out . print ( B . get ( i ) + " β " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 4 , 3 , 6 , 2 , 4 , 3 } ; int X = 7 ; int N = arr . length ; solve ( arr , N , X ) ; } }
``` |
xp3x | "Find middle point segment from given segment lengths | C / C ++ implementation of the approach ; Function that returns the segment for the middle point ; the middle point ; stores the segment index ; increment sum by length of the segment ; if the middle is in between two segments ; if sum is greater than middle point ; Driver code"
How can the above be solved in C++? | ```cpp
#include <iostream>
using namespace std ; int findSegment ( int n , int m , int segment_length [ ] ) { double meet_point = ( 1.0 * n ) / 2.0 ; int sum = 0 ; int segment_number = 0 ; for ( int i = 0 ; i < m ; i ++ ) { sum += segment_length [ i ] ; if ( ( double ) sum == meet_point ) { segment_number = -1 ; break ; } if ( sum > meet_point ) { segment_number = i + 1 ; break ; } } return segment_number ; } int main ( ) { int n = 13 ; int m = 3 ; int segment_length [ ] = { 3 , 2 , 8 } ; int ans = findSegment ( n , m , segment_length ) ; cout << ( ans ) ; return 0 ; }
``` |
xp3x | "Difference between sums of odd level and even level nodes of a Binary Tree | A recursive program to find difference between sum of nodes at odd level and sum at even level ; Binary Tree node ; A utility function to allocate a new tree node with given data ; The main function that return difference between odd and even level nodes ; Base case ; Difference for root is root 's data - difference for left subtree - difference for right subtree ; Driver program to test above functions"
Solution in C: | ```c
#include <stdio.h>
#include <stdlib.h>
struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int data ) { struct node * node = ( struct node * ) malloc ( sizeof ( struct node ) ) ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int getLevelDiff ( struct node * root ) { if ( root == NULL ) return 0 ; return root -> data - getLevelDiff ( root -> left ) - getLevelDiff ( root -> right ) ; } int main ( ) { struct node * root = newNode ( 5 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 6 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 4 ) ; root -> left -> right -> left = newNode ( 3 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 7 ) ; printf ( " % d β is β the β required β difference
" , getLevelDiff ( root ) ) ; getchar ( ) ; return 0 ; }
``` |
xp3x | "Perimeter and Area of Varignon 's Parallelogram | C program to find the perimeter and area ; Function to find the perimeter ; Function to find the area ; Driver code"
Solution in C: | ```c
#include <stdio.h>
float per ( float a , float b ) { return ( a + b ) ; } float area ( float s ) { return ( s / 2 ) ; } int main ( ) { float a = 7 , b = 8 , s = 10 ; printf ( " % f
" , per ( a , b ) ) ; printf ( " % f " , area ( s ) ) ; return 0 ; }
``` |
xp3x | "Practice questions for Linked List and Recursion |"
Solution in C: | ```c
void fun1 ( struct Node * head ) { if ( head == NULL ) return ; fun1 ( head -> next ) ; printf ( " % d β " , head -> data ) ; }
``` |
xp3x | "Sorting array with reverse around middle | Javascript program to find possibility to sort by multiple subarray reverse operation ; making the copy of the original array ; sorting the copied array ; checking mirror image of elements of sorted copy array and equivalent element of original array ; driver code"
Solution in Javascript: | ```javascript
function ifPossible ( arr , n ) { let copy = arr ; copy . sort ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( ! ( arr [ i ] == copy [ i ] ) && ! ( arr [ n - 1 - i ] == copy [ i ] ) ) return false ; } return true ; } let arr = [ 1 , 7 , 6 , 4 , 5 , 3 , 2 , 8 ] ; let n = arr . length ; if ( ifPossible ( arr , n ) ) document . write ( " " ) ; else document . write ( " " ) ; ;
``` |
xp3x | "Minimum sum of two numbers formed from digits of an array | Returns sum of two numbers formed from all digits in a [ ] ; sort the elements ; Driver code"
How can the above be solved in PHP? | ```php
< ? php function minSum ( $ a , $ n ) { sort ( $ a ) ; $ num1 = 0 ; $ num2 = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ i % 2 == 0 ) $ num1 = $ num1 * 10 + $ a [ $ i ] ; else $ num2 = $ num2 * 10 + $ a [ $ i ] ; } return ( $ num2 + $ num1 ) ; } $ arr = array ( 5 , 3 , 0 , 7 , 4 ) ; $ n = sizeof ( $ arr ) ; echo " The β required β sum β is β " , minSum ( $ arr , $ n ) , "
" ; ? >
``` |
xp3x | "Minimum steps to delete a string by deleting substring comprising of same characters | Java implementation of the approach ; Function to return the minimum number of delete operations ; When a single character is deleted ; When a group of consecutive characters are deleted if any of them matches ; When both the characters are same then delete the letters in between them ; Memoize ; Driver code"
How can the above be solved in Java? | ```java
class GFG { static int N = 10 ; static int findMinimumDeletion ( int l , int r , int dp [ ] [ ] , String s ) { if ( l > r ) { return 0 ; } if ( l == r ) { return 1 ; } if ( dp [ l ] [ r ] != - 1 ) { return dp [ l ] [ r ] ; } int res = 1 + findMinimumDeletion ( l + 1 , r , dp , s ) ; for ( int i = l + 1 ; i <= r ; ++ i ) { if ( s . charAt ( l ) == s . charAt ( i ) ) { res = Math . min ( res , findMinimumDeletion ( l + 1 , i - 1 , dp , s ) + findMinimumDeletion ( i , r , dp , s ) ) ; } } return dp [ l ] [ r ] = res ; } public static void main ( String [ ] args ) { String s = " abcddcba " ; int n = s . length ( ) ; int dp [ ] [ ] = new int [ N ] [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } System . out . println ( findMinimumDeletion ( 0 , n - 1 , dp , s ) ) ; } }
``` |
xp3x | "Minimize Nth term of an Arithmetic progression ( AP ) | C ++ program to implement the above approach ; Function to find the smallest Nth term of an AP possible ; Stores the smallest Nth term ; Check if common difference of AP is an integer ; Store the common difference ; Store the First Term of that AP ; Store the Nth term of that AP ; Check if all elements of an AP are positive ; Return the least Nth term obtained ; Driver Code"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; int smallestNth ( int A , int B , int N ) { int res = INT_MAX ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = N ; j > i ; j -- ) { if ( ( B - A ) % ( j - i ) == 0 ) { int D = ( B - A ) / ( j - i ) ; int FirstTerm = A - ( i - 1 ) * D ; int NthTerm = FirstTerm + ( N - 1 ) * D ; if ( FirstTerm > 0 ) res = min ( res , NthTerm ) ; } } } return res ; } int main ( ) { int N = 3 ; int A = 1 ; int B = 6 ; cout << smallestNth ( A , B , N ) ; }
``` |
xp3x | "Calculate the Sum of GCD over all subarrays | C # program to find Sum of GCD over all subarrays . ; Utility function to calculate sum of gcd of all sub - arrays . ; Fixing the starting index of a subarray ; Fixing the ending index of a subarray ; Finding the GCD of this subarray ; Adding this GCD in our sum ; Driver Code"
How can the above be solved in C-Sharp? | ```csharp
using System ; class GFG { static int findGCDSum ( int n , int [ ] a ) { int GCDSum = 0 ; int tempGCD = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { tempGCD = 0 ; for ( int k = i ; k <= j ; k ++ ) { tempGCD = __gcd ( tempGCD , a [ k ] ) ; } GCDSum += tempGCD ; } } return GCDSum ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void Main ( String [ ] args ) { int n = 5 ; int [ ] a = { 1 , 2 , 3 , 4 , 5 } ; int totalSum = findGCDSum ( n , a ) ; Console . Write ( totalSum + "
" ) ; } }
``` |
xp3x | "Find the element that appears once in an array where every other element appears twice | C ++ program to find element that appears once ; function which find number ; applying the formula . ; Driver code"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; int singleNumber ( int nums [ ] , int n ) { map < int , int > m ; long sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( m [ nums [ i ] ] == 0 ) { sum1 += nums [ i ] ; m [ nums [ i ] ] ++ ; } sum2 += nums [ i ] ; } return 2 * ( sum1 ) - sum2 ; } int main ( ) { int a [ ] = { 2 , 3 , 5 , 4 , 5 , 3 , 4 } ; int n = 7 ; cout << singleNumber ( a , n ) << "
" ; int b [ ] = { 15 , 18 , 16 , 18 , 16 , 15 , 89 } ; cout << singleNumber ( b , n ) ; return 0 ; }
``` |
xp3x | "Find the sum of all Truncatable primes below N | PHP implementation of the approach ; To check if a number is prime or not ; Sieve of Eratosthenes function to find all prime numbers ; Function to return the sum of all truncatable primes below n ; To store the required sum ; Check every number below n ; Check from right to left ; If number is not prime at any stage ; Check from left to right ; If number is not prime at any stage ; If flag is still true ; Return the required sum ; Driver code"
How can the above be solved in PHP? | ```php
< ? php $ N = 10005 ; $ prime = array_fill ( 0 , $ N , true ) ; function sieve ( ) { global $ prime , $ N ; $ prime [ 1 ] = false ; $ prime [ 0 ] = false ; for ( $ i = 2 ; $ i < $ N ; $ i ++ ) if ( $ prime [ $ i ] ) for ( $ j = $ i * 2 ; $ j < $ N ; $ j += $ i ) $ prime [ $ j ] = false ; } function sumTruncatablePrimes ( $ n ) { global $ prime , $ N ; $ sum = 0 ; for ( $ i = 2 ; $ i < $ n ; $ i ++ ) { $ num = $ i ; $ flag = true ; while ( $ num ) { if ( ! $ prime [ $ num ] ) { $ flag = false ; break ; } $ num = ( int ) ( $ num / 10 ) ; } $ num = $ i ; $ power = 10 ; while ( ( int ) ( $ num / $ power ) ) { if ( ! $ prime [ $ num % $ power ] ) { $ flag = false ; break ; } $ power *= 10 ; } if ( $ flag ) $ sum += $ i ; } return $ sum ; } $ n = 25 ; sieve ( ) ; echo sumTruncatablePrimes ( $ n ) ; ? >
``` |
xp3x | "Minimize swaps required to make all prime | Function to pre - calculate the prime [ ] prime [ i ] denotes whether i is prime or not ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to count minimum number of swaps required ; To count the minimum number of swaps required to convert the array into perfectly prime ; To count total number of prime indexes in the array ; To count the total number of prime numbers in the array ; Check whether index is prime or not ; Element is not prime ; If the total number of prime numbers is greater than or equal to the total number of prime indices , then it is possible to convert the array into perfectly prime ; Driver Code ; Pre - calculate prime [ ]"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; const int mxn = 1e4 + 1 ; bool prime [ mxn + 1 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; for ( int p = 2 ; p * p <= mxn ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= mxn ; i += p ) prime [ i ] = false ; } } } int countMin ( int arr [ ] , int n ) { int cMinSwaps = 0 ; int cPrimeIndices = 0 ; int cPrimeNos = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ i + 1 ] ) { cPrimeIndices ++ ; if ( ! prime [ arr [ i ] ] ) cMinSwaps ++ ; else cPrimeNos ++ ; } else if ( prime [ arr [ i ] ] ) { cPrimeNos ++ ; } } if ( cPrimeNos >= cPrimeIndices ) return cMinSwaps ; else return -1 ; } int main ( ) { SieveOfEratosthenes ( ) ; int n = 5 ; int arr [ 5 ] = { 2 , 7 , 8 , 5 , 13 } ; cout << countMin ( arr , n ) ; return 0 ; }
``` |
xp3x | Program to Convert Hexadecimal Number to Binary | C program to convert Hexadecimal number to Binary ; function to convert Hexadecimal to Binary Number ; driver code ; Get the Hexadecimal number ; Convert HexaDecimal to Binary
How can the above be solved in C? | ```c
#include <stdio.h>
void HexToBin ( char * hexdec ) { long int i = 0 ; while ( hexdec [ i ] ) { switch ( hexdec [ i ] ) { case '0' : printf ( "0000" ) ; break ; case '1' : printf ( "0001" ) ; break ; case '2' : printf ( "0010" ) ; break ; case '3' : printf ( "0011" ) ; break ; case '4' : printf ( "0100" ) ; break ; case '5' : printf ( "0101" ) ; break ; case '6' : printf ( "0110" ) ; break ; case '7' : printf ( "0111" ) ; break ; case '8' : printf ( "1000" ) ; break ; case '9' : printf ( "1001" ) ; break ; case ' A ' : case ' a ' : printf ( "1010" ) ; break ; case ' B ' : case ' b ' : printf ( "1011" ) ; break ; case ' C ' : case ' c ' : printf ( "1100" ) ; break ; case ' D ' : case ' d ' : printf ( "1101" ) ; break ; case ' E ' : case ' e ' : printf ( "1110" ) ; break ; case ' F ' : case ' f ' : printf ( "1111" ) ; break ; default : printf ( " Invalid hexadecimal digit % c " , hexdec [ i ] ) ; } i ++ ; } } int main ( ) { char hexdec [ 100 ] = "1AC5" ; printf ( " Equivalent Binary value is : " HexToBin ( hexdec ) ; }
``` |
xp3x | "Maximum length of Strictly Increasing Sub | Function to return the maximum length of strictly increasing subarray after removing atmost one element ; Create two arrays pre and pos ; Find out the contribution of the current element in array [ 0 , i ] and update pre [ i ] ; Find out the contribution of the current element in array [ N - 1 , i ] and update pos [ i ] ; Calculate the maximum length of the stricly increasing subarray without removing any element ; Calculate the maximum length of the strictly increasing subarray after removing the current element ; Driver code"
How can the above be solved in Python? | ```python
def maxIncSubarr ( a , n ) :
pre = [ 0 ] * n ;
pos = [ 0 ] * n ;
pre [ 0 ] = 1 ;
pos [ n - 1 ] = 1 ;
l = 0 ;
for i in range ( 1 , n ) :
if ( a [ i ] > a [ i - 1 ] ) :
pre [ i ] = pre [ i - 1 ] + 1 ;
else :
pre [ i ] = 1 ;
l = 1 ;
for i in range ( n - 2 , - 1 , - 1 ) :
if ( a [ i ] < a [ i + 1 ] ) :
pos [ i ] = pos [ i + 1 ] + 1 ;
else :
pos [ i ] = 1 ;
ans = 0 ;
l = 1 ;
for i in range ( 1 , n ) :
if ( a [ i ] > a [ i - 1 ] ) :
l += 1 ;
else :
l = 1 ;
ans = max ( ans , l ) ;
for i in range ( 1 , n - 1 ) :
if ( a [ i - 1 ] < a [ i + 1 ] ) :
ans = max ( pre [ i - 1 ] + pos [ i + 1 ] , ans ) ;
return ans ;
if __name__ == ' _ _ main _ _ ' :
arr = [ 1 , 2 ] ;
n = len ( arr ) ;
print ( maxIncSubarr ( arr , n ) ) ;
``` |
xp3x | "Program to Interchange Diagonals of Matrix | C program to interchange the diagonals of matrix ; Function to interchange diagonals ; swap elements of diagonal ; Driver Code"
Solution in C: | ```c
#include <bits/stdc++.h>
using namespace std ; #define N 3
void interchangeDiagonals ( int array [ ] [ N ] ) { for ( int i = 0 ; i < N ; ++ i ) if ( i != N / 2 ) swap ( array [ i ] [ i ] , array [ i ] [ N - i - 1 ] ) ; for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < N ; ++ j ) printf ( " β % d " , array [ i ] [ j ] ) ; printf ( "
" ) ; } } int main ( ) { int array [ N ] [ N ] = { 4 , 5 , 6 , 1 , 2 , 3 , 7 , 8 , 9 } ; interchangeDiagonals ( array ) ; return 0 ; }
``` |
xp3x | "Numbers having Unique ( or Distinct ) digits | C ++ implementation to find unique digit numbers in a range ; Function to print unique digit numbers in range from l to r . ; Start traversing the numbers ; Find digits and maintain its hash ; if a digit occurs more than 1 time then break ; num will be 0 only when above loop doesn 't get break that means the number is unique so print it. ; Driver code"
Solution in C++: | ```cpp
#include <bits/stdc++.h>
using namespace std ; void printUnique ( int l , int r ) { for ( int i = l ; i <= r ; i ++ ) { int num = i ; bool visited [ 10 ] = { false } ; while ( num ) { if ( visited [ num % 10 ] ) break ; visited [ num % 10 ] = true ; num = num / 10 ; } if ( num == 0 ) cout << i << " β " ; } } int main ( ) { int l = 1 , r = 20 ; printUnique ( l , r ) ; return 0 ; }
``` |
xp3x | "Check if two nodes are cousins in a Binary Tree | C program to check if two Nodes in a binary tree are cousins ; A Binary Tree Node ; A utility function to create a new Binary Tree Node ; Recursive function to check if two Nodes are siblings ; Base case ; Recursive function to find level of Node ' ptr ' in a binary tree ; base cases ; Return level if Node is present in left subtree ; Else search in right subtree ; Returns 1 if a and b are cousins , otherwise 0 ; 1. The two Nodes should be on the same level in the binary tree . 2. The two Nodes should not be siblings ( means that they should not have the same parent Node ) . ; Driver Program to test above functions"
Solution in C: | ```c
#include <stdio.h>
#include <stdlib.h>
struct Node { int data ; struct Node * left , * right ; } ; struct Node * newNode ( int item ) { struct Node * temp = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; temp -> data = item ; temp -> left = temp -> right = NULL ; return temp ; } int isSibling ( struct Node * root , struct Node * a , struct Node * b ) { if ( root == NULL ) return 0 ; return ( ( root -> left == a && root -> right == b ) || ( root -> left == b && root -> right == a ) || isSibling ( root -> left , a , b ) || isSibling ( root -> right , a , b ) ) ; } int level ( struct Node * root , struct Node * ptr , int lev ) { if ( root == NULL ) return 0 ; if ( root == ptr ) return lev ; int l = level ( root -> left , ptr , lev + 1 ) ; if ( l != 0 ) return l ; return level ( root -> right , ptr , lev + 1 ) ; } int isCousin ( struct Node * root , struct Node * a , struct Node * b ) { if ( ( level ( root , a , 1 ) == level ( root , b , 1 ) ) && ! ( isSibling ( root , a , b ) ) ) return 1 ; else return 0 ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> left -> right -> right = newNode ( 15 ) ; root -> right -> left = newNode ( 6 ) ; root -> right -> right = newNode ( 7 ) ; root -> right -> left -> right = newNode ( 8 ) ; struct Node * Node1 , * Node2 ; Node1 = root -> left -> left ; Node2 = root -> right -> right ; isCousin ( root , Node1 , Node2 ) ? puts ( " Yes " ) : puts ( " No " ) ; return 0 ; }
``` |
xp3x | "Gould 's Sequence | Function to generate gould 's Sequence ; loop to generate each row of pascal 's Triangle up to nth row ; Loop to generate each element of ith row ; if c is odd increment count ; print count of odd elements ; Get n ; Function call"
How can the above be solved in PHP? | ```php
< ? php function gouldSequence ( $ n ) { for ( $ row_num = 1 ; $ row_num <= $ n ; $ row_num ++ ) { $ count = 1 ; $ c = 1 ; for ( $ i = 1 ; $ i <= $ row_num ; $ i ++ ) { $ c = $ c * ( $ row_num - $ i ) / $ i ; if ( $ c % 2 == 1 ) $ count ++ ; } echo $ count , " " ; } } $ n = 16 ; gouldSequence ( $ n ) ; ? >
``` |
xp3x | Program to find sum of series 1 + 1 / 2 + 1 / 3 + 1 / 4 + . . + 1 / n | C program to find sum of series ; Function to return sum of 1 / 1 + 1 / 2 + 1 / 3 + . . + 1 / n ; Driver code
How can the above be solved in C? | ```c
#include <stdio.h>
double sum ( int n ) { double i , s = 0.0 ; for ( i = 1 ; i <= n ; i ++ ) s = s + 1 / i ; return s ; } int main ( ) { int n = 5 ; printf ( " Sum β is β % f " , sum ( n ) ) ; return 0 ; }
``` |
xp3x | "Equally divide into two sets such that one set has maximum distinct elements | Java program to equally divide n elements into two sets such that second set has maximum distinct elements . ; Driver code"
Solution in Java: | ```java
import java . util . * ; class Geeks { static int distribution ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int count = 1 ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > arr [ i - 1 ] ) count ++ ; return Math . min ( count , n / 2 ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 1 , 2 , 1 , 3 , 4 } ; int n = arr . length ; System . out . println ( distribution ( arr , n ) ) ; } }
``` |
xp3x | "Index Mapping ( or Trivial Hashing ) with negatives allowed | Java program to implement direct index mapping with negative values allowed . ; Since array is global , it is initialized as 0. ; searching if X is Present in the given array or not . ; if X is negative take the absolute value of X . ; Driver code"
How can the above be solved in Java? | ```java
class GFG { final static int MAX = 1000 ; static boolean [ ] [ ] has = new boolean [ MAX + 1 ] [ 2 ] ; static boolean search ( int X ) { if ( X >= 0 ) { if ( has [ X ] [ 0 ] == true ) { return true ; } else { return false ; } } X = Math . abs ( X ) ; if ( has [ X ] [ 1 ] == true ) { return true ; } return false ; } static void insert ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) { has [ a [ i ] ] [ 0 ] = true ; } else { has [ Math . abs ( a [ i ] ) ] [ 1 ] = true ; } } } public static void main ( String args [ ] ) { int a [ ] = { - 1 , 9 , - 5 , - 8 , - 5 , - 2 } ; int n = a . length ; insert ( a , n ) ; int X = - 5 ; if ( search ( X ) == true ) { System . out . println ( " Present " ) ; } else { System . out . println ( " Not β Present " ) ; } } }
``` |