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 ( isz...
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 ...
```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...
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 ; Fun...
```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 ( ) {...
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 s...
```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 ; } retur...
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...
```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...
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 digit...
```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 )...
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...
```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 <=...
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...
```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 pri...
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 a...
```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 = ...
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 ; Dr...
```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 equat...
```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 > ( ...
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 e...
```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 / facto...
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 ...
```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 ( ) { s...
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 e...
```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...
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 so...
```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 )...
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 signific...
```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 ( ...
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 ; ...
```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_MA...
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 pr...
```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 , len...
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 ; D...
```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 ; r...
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 ; Star...
```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...
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 ...
```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 ) ; co...
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 m...
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 ; ...
```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 ] ; } maxRat...
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 ; Follow...
```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 <=...
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 [...
```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 ) ( $ car...
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"...
```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 ...
```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 ; } ...
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...
```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 ...
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 s...
```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...
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 elem...
```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 +...
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 NUL...
```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 (...
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 ▁ inequali...
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 ...
```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 ' ]...
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 an...
```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 ] ...
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 ...
```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 < vect...
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...
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 functi...
```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 + " ...
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 GC...
```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...
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 position...
```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_...
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 [...
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 ; Ini...
```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_bac...
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 ...
```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 )...
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 ; ...
```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...
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 ...
```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 ) ...
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...
```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 ...
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...
```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 ( struc...
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 i...
```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 ...
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 ) ...
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 charac...
```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...
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...
```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 + ( ...
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 C...
```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 ; ...
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...
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 righ...
```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 sumTruncatabl...
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 n...
```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 ; } } ...
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 ;...
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 eleme...
```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 ...
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 ...
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 l...
```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...
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 tr...
```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 ...
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 , ...
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 ...
```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...