config
stringclasses
2 values
instruction
stringlengths
48
2.07k
response
stringlengths
44
2.06k
xp3x
"Find Nth number in a sequence which is not a multiple of a given number | Python3 program for the above approach ; Function to find Nth number not a multiple of A in range [ L , R ] ; Calculate the Nth no ; Check for the edge case ; ; Input parameters ; Function Call" How can the above be solved in Python?
```python import math def countNo ( A , N , L , R ) : ans = L - 1 + N + math . floor ( ( N - 1 ) / ( A - 1 ) ) if ans % A == 0 : ans = ans + 1 ; print ( ans ) / * Driver Code * / A , N , L , R = 5 , 10 , 4 , 20 countNo ( A , N , L , R ) ```
xp3x
"Find maximum product of digits among numbers less than or equal to N | Function that returns the maximum product of digits among numbers less than or equal to N ; Driver code" How can the above be solved in PHP?
```php < ? php function maxProd ( $ N ) { if ( $ N == 0 ) return 1 ; if ( $ N < 10 ) return $ N ; return max ( maxProd ( ( int ) ( $ N / 10 ) ) * ( $ N % 10 ) , maxProd ( ( int ) ( $ N / 10 ) - 1 ) * 9 ) ; } $ N = 390 ; echo maxProd ( $ N ) ; ? > ```
xp3x
"Program to find Nth term of the series 3 , 12 , 29 , 54 , 87 , ... | calculate Nth term of series ; Return Nth term ; declaration of number of terms ; Get the Nth term" How can the above be solved in PHP?
```php < ? php function getNthTerm ( $ N ) { return 4 * pow ( $ N , 2 ) - 3 * $ N + 2 ; } $ N = 10 ; echo getNthTerm ( $ N ) ; ? > ```
xp3x
"Convert given string to another by minimum replacements of subsequences by its smallest character | Java program for the above approach ; Function to return the minimum number of operation ; Storing data ; Initialize both arrays ; Stores the index of character ; Filling str1array , convChar and hashmap convertMap . ; Not possible to convert ; Calculate result Initializing return values ; Iterating the character from the end ; Increment the number of operations ; Not possible to convert ; To check whether the final element has been added in set S or not . ; Check if v1 [ j ] is present in hashmap or not ; Already converted then then continue ; Not possible to convert ; Print the result ; Driver Code ; Given strings ; Function call" How can the above be solved in Java?
```java import java . util . * ; import java . lang . * ; class GFG { static void transformString ( String str1 , String str2 ) { int N = str1 . length ( ) ; ArrayList < ArrayList < Integer > > convChar = new ArrayList < > ( ) ; ArrayList < ArrayList < Integer > > str1array = new ArrayList < > ( ) ; for ( int i = 0 ; i < 26 ; i ++ ) { convChar . add ( new ArrayList < > ( ) ) ; str1array . add ( new ArrayList < > ( ) ) ; } Map < Integer , Character > convertMap = new HashMap < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { str1array . get ( str1 . charAt ( i ) - ' a ' ) . add ( i ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( str1 . charAt ( i ) < str2 . charAt ( i ) ) { System . out . println ( - 1 ) ; return ; } else if ( str1 . charAt ( i ) == str2 . charAt ( i ) ) continue ; else { convChar . get ( str2 . charAt ( i ) - ' a ' ) . add ( i ) ; convertMap . put ( i , str2 . charAt ( i ) ) ; } } int ret = 0 ; ArrayList < ArrayList < Integer > > retv = new ArrayList < > ( ) ; for ( int i = 25 ; i >= 0 ; i -- ) { ArrayList < Integer > v = convChar . get ( i ) ; if ( v . size ( ) == 0 ) continue ; ret ++ ; ArrayList < Integer > v1 = str1array . get ( i ) ; if ( v1 . size ( ) == 0 ) { System . out . println ( - 1 ) ; return ; } boolean isScompleted = false ; for ( int j = 0 ; j < v1 . size ( ) ; j ++ ) { if ( convertMap . containsKey ( v1 . get ( j ) ) ) { char a = convertMap . get ( v1 . get ( j ) ) ; if ( a > i + ' a ' ) continue ; else { v . add ( v1 . get ( j ) ) ; isScompleted = true ; retv . add ( v ) ; break ; } } else { v . add ( v1 . get ( j ) ) ; isScompleted = true ; retv . add ( v ) ; break ; } } if ( ! isScompleted ) { System . out . println ( - 1 ) ; return ; } } System . out . println ( ret ) ; } public static void main ( String [ ] args ) { String A = " abcab " ; String B = " aabab " ; transformString ( A , B ) ; } } ```
xp3x
"Program to find sum of elements in a given array | C ++ Program to find sum of elements in a given array ; Driver code ; calling accumulate function , passing first , last element and initial sum , which is 0 in this case ." Solution in C++:
```cpp #include <bits/stdc++.h> using namespace std ; int main ( ) { int arr [ ] = { 12 , 3 , 4 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Sum ▁ of ▁ given ▁ array ▁ is ▁ " << accumulate ( arr , arr + n , 0 ) ; return 0 ; } ```
xp3x
"Count number of squares in a rectangle | C ++ program to count squares in a rectangle of size m x n ; Returns count of all squares in a rectangle of size m x n ; If n is smaller , swap m and n ; Now n is greater dimension , apply formula ; Driver Code" Solution in C++:
```cpp #include <iostream> using namespace std ; int countSquares ( int m , int n ) { if ( n < m ) { int temp = m ; m = n ; n = temp ; } return n * ( n + 1 ) * ( 3 * m - n + 1 ) / 6 ; } int main ( ) { int m = 4 , n = 3 ; cout << " Count ▁ of ▁ squares ▁ is ▁ " << countSquares ( m , n ) ; } ```
xp3x
"Minimum number of letters needed to make a total of n | C ++ implementation of the approach ; Function to return the minimum letters required to make a total of n ; Driver code" How can the above be solved in C++?
```cpp #include <bits/stdc++.h> using namespace std ; int minLettersNeeded ( int n ) { if ( n % 26 == 0 ) return ( n / 26 ) ; else return ( ( n / 26 ) + 1 ) ; } int main ( ) { int n = 52 ; cout << minLettersNeeded ( n ) ; return 0 ; } ```
xp3x
"Lexicographically smallest permutation of a string that can be reduced to length K by removing K | Java program for the above approach ; Function to count the number of zeroes present in the string ; Traverse the string ; Return the count ; Function to rearrange the string s . t the string can be reduced to a length K as per the given rules ; Distribute the count of 0 s and 1 s in segment of length 2 k ; Store string that are initially have formed lexicographically smallest 2 k length substring ; Store the lexicographically smallest string of length n that satisfy the condition ; Insert temp_str into final_str ( n / 2 k ) times and add ( n % 2 k ) characters of temp_str at end ; Return the final string ; Function to reduce the string to length K that follows the given conditions ; If the string contains either 0 s or 1 s then it always be reduced into a K length string ; If the string contains only 0 s 1 s then it always reduces to a K length string ; If K = 1 ; Check whether the given string is K reducing string or not ; Otherwise recursively find the string ; Driver Code ; Function Call" How can the above be solved in Java?
```java import java . io . * ; class GFG { static int count_zeroes ( int n , String str ) { int cnt = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == '0' ) cnt ++ ; } return cnt ; } static String kReducingStringUtil ( int n , int k , String str , int no_of_zeroes ) { int zeroes_in_2k = ( ( no_of_zeroes ) * ( 2 * k ) ) / n ; int ones_in_2k = 2 * k - zeroes_in_2k ; String temp_str = " " ; for ( int i = 0 ; i < ( zeroes_in_2k ) / 2 ; i ++ ) { temp_str += '0' ; } for ( int i = 0 ; i < ones_in_2k ; i ++ ) { temp_str += '1' ; } for ( int i = 0 ; i < ( zeroes_in_2k ) / 2 ; i ++ ) { temp_str += '0' ; } String final_str = " " ; for ( int i = 0 ; i < n / ( 2 * k ) ; i ++ ) { final_str += ( temp_str ) ; } for ( int i = 0 ; i < n % ( 2 * k ) ; i ++ ) { final_str += temp_str . charAt ( i ) ; } return final_str ; } static String kReducingString ( int n , int k , String str ) { int no_of_zeroes = count_zeroes ( n , str ) ; int no_of_ones = n - no_of_zeroes ; if ( no_of_zeroes == 0 no_of_zeroes == n ) { return str ; } if ( k == 1 ) { if ( no_of_zeroes == 0 no_of_zeroes == n ) { return str ; } else { return " Not ▁ Possible " ; } } boolean check = false ; for ( int i = ( n / k ) ; i < n ; i += ( n / k ) ) { if ( no_of_zeroes == i no_of_ones == i ) { check = true ; break ; } } if ( check == false ) { return " Not ▁ Possible " ; } return kReducingStringUtil ( n , k , str , no_of_zeroes ) ; } public static void main ( String [ ] args ) { String str = "0000100001100001" ; int K = 4 ; int N = str . length ( ) ; System . out . println ( kReducingString ( N , K , str ) ) ; } } ```
xp3x
"Smallest number greater than X which is K | C ++ Program to find the smallest K periodic integer greater than X ; Function to find the smallest K periodic integer greater than X ; Stores the number in a temporary string ; Set X [ i ] = X [ i - k ] for i > k ; Start from the current index ; Loop upto N change X [ j ] to X [ i ] ; Return X if current Value is greater than original value ; Find the first digit not equal to 9 ; Increment X [ i ] ; Set POS to current index ; Change X [ i ] to 0 for all indices from POS + 1 to K ; Set X [ i ] = X [ i - k ] for i > k ; Loop upto N change X [ j ] to X [ i ] ; Return the final string ; Driver Code" How can the above be solved in C++?
```cpp #include <bits/stdc++.h> using namespace std ; string Kperiodicinteger ( string X , int N , int K ) { string temp = X ; for ( int i = 0 ; i < K ; i ++ ) { int j = i ; while ( j < N ) { X [ j ] = X [ i ] ; j += K ; } } if ( X >= temp ) { return X ; } int POS ; for ( int i = K - 1 ; i >= 0 ; i -- ) { if ( X [ i ] != '9' ) { X [ i ] ++ ; POS = i ; break ; } } for ( int i = POS + 1 ; i < K ; i ++ ) { X [ i ] = '0' ; } for ( int i = 0 ; i < K ; i ++ ) { int j = i ; while ( j < N ) { X [ j ] = X [ i ] ; j += K ; } } return X ; } int main ( ) { int N = 4 , K = 2 ; string X = "1215" ; cout << Kperiodicinteger ( X , N , K ) ; return 0 ; } ```
xp3x
"Sort a binary array using one traversal | Javascript Code for Sort a binary array using one traversal ; if number is smaller than 1 then swap it with j - th number ; driver function" How can the above be solved in JS?
```javascript function sortBinaryArray ( a , n ) { let j = - 1 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] < 1 ) { j ++ ; let temp = a [ j ] ; a [ j ] = a [ i ] ; a [ i ] = temp ; } } } let a = [ 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 ] ; let n = a . length ; sortBinaryArray ( a , n ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( a [ i ] + " " ) ; ```
xp3x
"Minimum number of operations required to maximize the Binary String | C # program to implement the above approach ; Function to find the number of operations required ; Swap 0 ' s ▁ and ▁ 1' s ; Return the answer ; Driver code" How can the above be solved in C-Sharp?
```csharp using System ; class GFG { static int minOperation ( String s , int n ) { int ans = 0 ; int i = 0 , j = n - 1 ; while ( i < j ) { if ( s [ i ] == '0' && s [ j ] == '1' ) { ans ++ ; i ++ ; j -- ; continue ; } if ( s [ i ] == '1' ) { i ++ ; } if ( s [ j ] == '0' ) { j -- ; } } return ans ; } public static void Main ( String [ ] args ) { int n = 8 ; String s = "10100101" ; Console . WriteLine ( minOperation ( s , n ) ) ; } } ```
xp3x
"Check whether a number is circular prime or not | Program to check if a number is circular prime or not . ; Function to check if a number is prime or not . ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to check if the number is circular prime or not . ; Count digits . ; Following three lines generate the next circular permutation of a number . We move last digit to first position . ; If all the permutations are checked and we obtain original number exit from loop . ; Driver Program" Solution in C++:
```cpp #include <iostream> #include <cmath> using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } bool checkCircular ( int N ) { int count = 0 , temp = N ; while ( temp ) { count ++ ; temp /= 10 ; } int num = N ; while ( isPrime ( num ) ) { int rem = num % 10 ; int div = num / 10 ; num = ( pow ( 10 , count - 1 ) ) * rem + div ; if ( num == N ) return true ; } return false ; } int main ( ) { int N = 1193 ; if ( checkCircular ( N ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; } ```
xp3x
"Generate an array of size N according to the given rules | Java implementation to generate an array of size N by following the given rules ; Function to search the most recent location of element N If not present in the array it will return - 1 ; Function to generate an array of size N by following the given rules ; Loop to fill the array as per the given rules ; Check for the occurrence of arr [ i - 1 ] ; Driver code" How can the above be solved in Java?
```java class GFG { static int a [ ] ; static int search ( int a [ ] , int k , int x ) { int j ; for ( j = k - 1 ; j > - 1 ; j -- ) { if ( a [ j ] == x ) return j ; } return - 1 ; } static void genArray ( int [ ] arr , int N ) { for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( search ( arr , i , arr [ i ] ) == - 1 ) arr [ i + 1 ] = 0 ; else arr [ i + 1 ] = ( i - search ( arr , i , arr [ i ] ) ) ; } } public static void main ( String [ ] args ) { int N = 5 ; int size = N + 1 ; int a [ ] = new int [ N ] ; genArray ( a , N ) ; for ( int i = 0 ; i < N ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } } ```
xp3x
"Check if Pascal 's Triangle is possible with a complete layer by using numbers upto N | C ++ program for the above approach ; Function to check if Pascaltriangle can be made by N integers ; Find X ; If x is integer ; Driver Code ; Given number N ; Function Call" How can the above be solved in C++?
```cpp #include <bits/stdc++.h> using namespace std ; void checkPascaltriangle ( int N ) { double x = ( sqrt ( 8 * N + 1 ) - 1 ) / 2 ; if ( ceil ( x ) - x == 0 ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int N = 10 ; checkPascaltriangle ( N ) ; return 0 ; } ```
xp3x
"Number of circular tours that visit all petrol pumps | Python 3 Program to find the number of circular tour that visits all petrol pump ; Return the number of pumps from where we can start the journey . ; Making Circular Array . ; for each of the petrol pump . ; If tank is less than 0. ; If starting pump is greater than n , return ans as 0. ; For each of the petrol pump ; Finding the need array ; If need is 0 , increment the count . ; Driver Code" How can the above be solved in Python?
```python N = 100 def count ( n , c , a , b ) : need = [ 0 for i in range ( N ) ] for i in range ( 0 , n , 1 ) : a [ i + n ] = a [ i ] b [ i + n ] = b [ i ] s = 0 tank = 0 for i in range ( 0 , 2 * n , 1 ) : tank += a [ i ] tank = min ( tank , c ) tank -= b [ i ] if ( tank < 0 ) : tank = 0 s = i + 1 if ( s >= n ) : return 0 ans = 1 need [ s + n ] = 0 for i in range ( 1 , n , 1 ) : id = s + n - i need [ id ] = max ( 0 , need [ id + 1 ] + b [ id ] - min ( a [ id ] , c ) ) if ( need [ id ] == 0 ) : ans += 1 return ans if __name__ == ' _ _ main _ _ ' : n = 3 c = 3 a = [ 3 , 1 , 2 , 0 , 0 , 0 ] b = [ 2 , 2 , 2 , 0 , 0 , 0 ] print ( count ( n , c , a , b ) ) ```
xp3x
"Count numbers from a given range having exactly 5 distinct factors | Python3 implementation of the above approach ; Stores all prime numbers up to 2 * 10 ^ 5 ; Function to generate all prime numbers up to 2 * 10 ^ 5 using Sieve of Eratosthenes ; Mark 0 and 1 as non - prime ; If i is prime ; Mark all its factors as non - prime ; If current number is prime ; Store the prime ; Function to count numbers in the range [ L , R ] having exactly 5 factors ; Stores the required count ; Driver Code" How can the above be solved in Python?
```python N = 2 * 100000 prime = [ 0 ] * N def Sieve ( ) : p = [ True ] * ( N + 1 ) p [ 0 ] = p [ 1 ] = False i = 2 while ( i * i <= N ) : if ( p [ i ] == True ) : for j in range ( i * i , N , i ) : p [ j ] = False i += 1 for i in range ( N ) : if ( p [ i ] != False ) : prime . append ( pow ( i , 4 ) ) def countNumbers ( L , R ) : Count = 0 for p in prime : if ( p >= L and p <= R ) : Count += 1 print ( Count ) L = 16 R = 85000 Sieve ( ) countNumbers ( L , R ) ```
xp3x
Reorder an array such that sum of left half is not equal to sum of right half | C program for the above approach ; A comparator function used by qsort ; Function to print the required reordering of array if possible ; Sort the array in increasing order ; If all elements are equal , then it is not possible ; Else print the sorted array arr [ ] ; Driver Code ; Given array ; Function call How can the above be solved in C?
```c #include <stdio.h> #include <stdlib.h> int compare ( const void * a , const void * b ) { return ( * ( int * ) a - * ( int * ) b ) ; } void printArr ( int arr [ ] , int n ) { qsort ( arr , n , sizeof ( int ) , compare ) ; if ( arr [ 0 ] == arr [ n - 1 ] ) { printf ( " No " ) ; } else { printf ( " Yes " ) ; for ( int i = 0 ; i < n ; i ++ ) { printf ( " % d ▁ " , arr [ i ] ) ; } } } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 1 , 3 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printArr ( arr , N ) ; return 0 ; } ```
xp3x
"Maximize median after doing K addition operation on the Array | Java program for the above approach ; Function to check operation can be perform or not ; Number of operation to perform s . t . mid is median ; If mid is median of the array ; Function to find max median of the array ; Lowest possible median ; Highest possible median ; Checking for mid is possible for the median of array after doing at most k operation ; Return the max possible ans ; Driver code ; Given array ; Given number of operation ; Size of array ; Sort the array ; Function call" How can the above be solved in Java?
```java import java . util . * ; class GFG { static boolean possible ( int arr [ ] , int N , int mid , int K ) { int add = 0 ; for ( int i = N / 2 - ( N + 1 ) % 2 ; i < N ; ++ i ) { if ( mid - arr [ i ] > 0 ) { add += ( mid - arr [ i ] ) ; if ( add > K ) return false ; } } if ( add <= K ) return true ; else return false ; } static int findMaxMedian ( int arr [ ] , int N , int K ) { int low = 1 ; int mx = 0 ; for ( int i = 0 ; i < N ; ++ i ) { mx = Math . max ( mx , arr [ i ] ) ; } int high = K + mx ; while ( low <= high ) { int mid = ( high + low ) / 2 ; if ( possible ( arr , N , mid , K ) ) { low = mid + 1 ; } else { high = mid - 1 ; } } if ( N % 2 == 0 ) { if ( low - 1 < arr [ N / 2 ] ) { return ( arr [ N / 2 ] + low - 1 ) / 2 ; } } return low - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 6 } ; int K = 10 ; int N = arr . length ; Arrays . sort ( arr ) ; System . out . println ( findMaxMedian ( arr , N , K ) ) ; } } ```
xp3x
"Sum of minimum and the maximum difference between two given Strings | Function to find the sum of the minimum and the maximum difference between two given strings ; Variables to store the minimum difference and the maximum difference ; Iterate through the length of the string as both the given strings are of the same length ; For the maximum difference , we can replace " + " in both the strings with different char ; For the minimum difference , we can replace " + " in both the strings with the same char ; Driver code" How can the above be solved in JS?
```javascript function solve ( a , b ) { var l = a . length ; var min = 0 , max = 0 ; for ( var i = 0 ; i < l ; i ++ ) { if ( a [ i ] == ' ' b [ i ] == ' ' a [ i ] != b [ i ] ) max ++ ; if ( a [ i ] != ' ' && b [ i ] != ' ' && a [ i ] != b [ i ] ) min ++ ; } document . write ( min + max ) ; } var s1 = " " , s2 = " " ; solve ( s1 , s2 ) ; ```
xp3x
"Longest Geometric Progression | Returns length of the longest GP subset of set [ ] ; Base cases ; Let us sort the set first ; An entry L [ i ] [ j ] in this table stores LLGP with set [ i ] and set [ j ] as first two elements of GP and j > i . ; Initialize result ( A single element is always a GP ) ; Initialize values of last column ; Consider every element as second element of GP ; Search for i and k for j ; Two cases when i , j and k don 't form a GP. ; i , j and k form GP , LLGP with i and j as first two elements is equal to LLGP with j and k as first two elements plus 1. L [ j ] [ k ] must have been filled before as we run the loop from right side ; Update overall LLGP ; Change i and k to fill more L [ i ] [ j ] values for current j ; If the loop was stopped due to k becoming more than n - 1 , set the remaining entries in column j as 1 or 2 based on divisibility of set [ j ] by set [ i ] ; Return result ; Driver code" How can the above be solved in JS?
```javascript function lenOfLongestGP ( set , n ) { if ( n < 2 ) { return n ; } if ( n == 2 ) { return ( set [ 1 ] % set [ 0 ] == 0 ? 2 : 1 ) ; } set . sort ( function ( a , b ) { return a - b } ) ; let L = new Array ( n ) ; for ( let i = 0 ; i < n ; ++ i ) { L [ i ] = new Array ( n ) ; for ( let j = 0 ; j < n ; ++ j ) { L [ i ] [ j ] = 0 ; } } let llgp = 1 ; for ( let i = 0 ; i < n - 1 ; ++ i ) { if ( set [ n - 1 ] % set [ i ] == 0 ) { L [ i ] [ n - 1 ] = 2 ; if ( 2 > llgp ) llgp = 2 ; } else { L [ i ] [ n - 1 ] = 1 ; } } L [ n - 1 ] [ n - 1 ] = 1 ; for ( let j = n - 2 ; j >= 1 ; -- j ) { let i = j - 1 , k = j + 1 ; while ( i >= 0 && k <= n - 1 ) { if ( set [ i ] * set [ k ] < set [ j ] * set [ j ] ) { ++ k ; } else if ( set [ i ] * set [ k ] > set [ j ] * set [ j ] ) { if ( set [ j ] % set [ i ] == 0 ) { L [ i ] [ j ] = 2 ; if ( 2 > llgp ) llgp = 2 ; } else { L [ i ] [ j ] = 1 ; } -- i ; } else { if ( set [ j ] % set [ i ] == 0 ) { L [ i ] [ j ] = L [ j ] [ k ] + 1 ; if ( L [ i ] [ j ] > llgp ) { llgp = L [ i ] [ j ] ; } } else { L [ i ] [ j ] = 1 ; } -- i ; ++ k ; } } while ( i >= 0 ) { if ( set [ j ] % set [ i ] == 0 ) { L [ i ] [ j ] = 2 ; if ( 2 > llgp ) llgp = 2 ; } else { L [ i ] [ j ] = 1 ; } -- i ; } } return llgp ; } let set1 = [ 1 , 3 , 9 , 27 , 81 , 243 ] ; let n1 = set1 . length ; document . write ( lenOfLongestGP ( set1 , n1 ) + " " ) ; let set2 = [ 1 , 3 , 4 , 9 , 7 , 27 ] ; let n2 = set2 . length ; document . write ( lenOfLongestGP ( set2 , n2 ) + " " ) ; let set3 = [ 2 , 3 , 5 , 7 , 11 , 13 ] ; let n3 = set3 . length ; document . write ( lenOfLongestGP ( set3 , n3 ) + " " ) ; ```
xp3x
"Perfect Number | Returns true if n is perfect ; To store sum of divisors ; Find all divisors and add them ; If sum of divisors is equal to n , then n is a perfect number ; Driver program" How can the above be solved in JS?
```javascript function isPerfect ( n ) { sum = 1 ; for ( let i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { if ( i * i != n ) sum = sum + i + n / i ; else sum = sum + i ; } } if ( sum == n && n != 1 ) return true ; return false ; } document . write ( " " + " " ) ; for ( let n = 2 ; n < 10000 ; n ++ ) if ( isPerfect ( n ) ) document . write ( n + " " + " " ) ; ```
xp3x
"Count Balanced Binary Trees of Height h | PHP program to count number of balanced ; base cases ; Driver Code" How can the above be solved in PHP?
```php < ? php $ mod = 1000000007 ; function countBT ( $ h ) { global $ mod ; $ dp [ 0 ] = $ dp [ 1 ] = 1 ; for ( $ i = 2 ; $ i <= $ h ; $ i ++ ) { $ dp [ $ i ] = ( $ dp [ $ i - 1 ] * ( ( 2 * $ dp [ $ i - 2 ] ) % $ mod + $ dp [ $ i - 1 ] ) % $ mod ) % $ mod ; } return $ dp [ $ h ] ; } $ h = 3 ; echo " No . ▁ of ▁ balanced ▁ binary ▁ trees " , " ▁ of ▁ height ▁ h ▁ is : ▁ " , countBT ( $ h ) , " " ; ? > ```
xp3x
"Maximize count of 1 s in an array by repeated division of array elements by 2 at most K times | Python3 program to implement the above approach ; Function to count the maximum number of array elements that can be reduced to 1 by repeatedly dividing array elements by 2 ; Sort the array in ascending order ; Store the count of array elements ; Traverse the array ; Store the number of operations required to reduce arr [ i ] to 1 ; Decrement k by opr ; If k becomes less than 0 , then break out of the loop ; Increment cnt by 1 ; Prthe answer ; Driver Code" How can the above be solved in Python?
```python import math def findMaxNumbers ( arr , n , k ) : arr . sort ( ) cnt = 0 for i in range ( n ) : opr = math . ceil ( math . log2 ( arr [ i ] ) ) k -= opr if ( k < 0 ) : break cnt += 1 print ( cnt ) arr = [ 5 , 8 , 4 , 7 ] N = len ( arr ) K = 5 findMaxNumbers ( arr , N , K ) ```
xp3x
"Count of matchsticks required to represent the given number | C ++ implementation of the approach ; stick [ i ] stores the count of sticks required to represent the digit i ; Function to return the count of matchsticks required to represent the given number ; For every digit of the given number ; Add the count of sticks required to represent the current digit ; Driver code" Solution in C++:
```cpp #include <bits/stdc++.h> using namespace std ; const int sticks [ ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 } ; int countSticks ( string str , int n ) { int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { cnt += ( sticks [ str [ i ] - '0' ] ) ; } return cnt ; } int main ( ) { string str = "56" ; int n = str . length ( ) ; cout << countSticks ( str , n ) ; return 0 ; } ```
xp3x
"Find K elements whose absolute difference with median of array is maximum | C ++ implementation to find first K elements whose difference with the median of array is maximum ; Function for calculating median ; check for even case ; Function to find the K maximum absolute difference with the median of the array ; Sort the array . ; Store median ; Find and store difference ; If diff [ i ] is greater print it Else print diff [ j ] ; Driver Code" How can the above be solved in C++?
```cpp #include <bits/stdc++.h> using namespace std ; double findMedian ( int a [ ] , int n ) { if ( n % 2 != 0 ) return ( double ) a [ n / 2 ] ; return ( double ) ( a [ ( n - 1 ) / 2 ] + a [ n / 2 ] ) / 2.0 ; } void kStrongest ( int arr [ ] , int n , int k ) { sort ( arr , arr + n ) ; double median = findMedian ( arr , n ) ; int diff [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { diff [ i ] = abs ( median - arr [ i ] ) ; } int i = 0 , j = n - 1 ; while ( k > 0 ) { if ( diff [ i ] > diff [ j ] ) { cout << arr [ i ] << " ▁ " ; i ++ ; } else { cout << arr [ j ] << " ▁ " ; j -- ; } k -- ; } } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int k = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; kStrongest ( arr , n , k ) ; return 0 ; } ```
xp3x
"Program to find the Nth term of the series 3 , 7 , 13 , 21 , 31. ... . | Function to calculate sum ; Return Nth term ; driver code ; declaration of number of terms ; Get the Nth term" How can the above be solved in Python?
```python def getNthTerm ( N ) : return ( pow ( N , 2 ) + N + 1 ) if __name__ == ' _ _ main _ _ ' : N = 11 print ( getNthTerm ( N ) ) ```
xp3x
"Binary Search | C program to implement recursive Binary Search ; A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver method to test above" Solution in C:
```c #include <stdio.h> int binarySearch ( int arr [ ] , int l , int r , int x ) { if ( r >= l ) { int mid = l + ( r - l ) / 2 ; if ( arr [ mid ] == x ) return mid ; if ( arr [ mid ] > x ) return binarySearch ( arr , l , mid - 1 , x ) ; return binarySearch ( arr , mid + 1 , r , x ) ; } return -1 ; } int main ( void ) { int arr [ ] = { 2 , 3 , 4 , 10 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int x = 10 ; int result = binarySearch ( arr , 0 , n - 1 , x ) ; ( result == -1 ) ? printf ( " Element ▁ is ▁ not ▁ present ▁ in ▁ array " ) : printf ( " Element ▁ is ▁ present ▁ at ▁ index ▁ % d " , result ) ; return 0 ; } ```
xp3x
"Print steps to make a number in form of 2 ^ X | C ++ program to implement the above approach ; Function to find the leftmost unset bit in a number . ; Function that perform the step ; Find the leftmost unset bit ; If the number has no bit unset , it means it is in form 2 ^ x - 1 ; Count the steps ; Iterate till number is of form 2 ^ x - 1 ; At even step increase by 1 ; Odd step xor with any 2 ^ m - 1 ; Find the leftmost unset bit ; 2 ^ m - 1 ; Perform the step ; Increase the steps ; Driver code" How can the above be solved in C++?
```cpp #include <bits/stdc++.h> using namespace std ; int find_leftmost_unsetbit ( int n ) { int ind = -1 ; int i = 1 ; while ( n ) { if ( ! ( n & 1 ) ) ind = i ; i ++ ; n >>= 1 ; } return ind ; } void perform_steps ( int n ) { int left = find_leftmost_unsetbit ( n ) ; if ( left == -1 ) { cout << " No ▁ steps ▁ required " ; return ; } int step = 1 ; while ( find_leftmost_unsetbit ( n ) != -1 ) { if ( step % 2 == 0 ) { n += 1 ; cout << " Step " << step << " : ▁ Increase ▁ by ▁ 1 " ; } else { int m = find_leftmost_unsetbit ( n ) ; int num = pow ( 2 , m ) - 1 ; n = n ^ num ; cout << " Step " << step << " : ▁ Xor ▁ with ▁ " << num << endl ; } step += 1 ; } } int main ( ) { int n = 39 ; perform_steps ( n ) ; return 0 ; } ```
xp3x
"Palindrome Partitioning | DP | Java Code for Palindrome Partitioning Problem ; Driver code" How can the above be solved in Java?
```java public class GFG { static boolean isPalindrome ( String string , int i , int j ) { while ( i < j ) { if ( string . charAt ( i ) != string . charAt ( j ) ) return false ; i ++ ; j -- ; } return true ; } static int minPalPartion ( String string , int i , int j ) { if ( i >= j || isPalindrome ( string , i , j ) ) return 0 ; int ans = Integer . MAX_VALUE , count ; for ( int k = i ; k < j ; k ++ ) { count = minPalPartion ( string , i , k ) + minPalPartion ( string , k + 1 , j ) + 1 ; ans = Math . min ( ans , count ) ; } return ans ; } public static void main ( String args [ ] ) { String str = " ababbbabbababa " ; System . out . println ( " Min ▁ cuts ▁ needed ▁ for ▁ " + " Palindrome ▁ Partitioning ▁ is ▁ " + minPalPartion ( str , 0 , str . length ( ) - 1 ) ) ; } } ```
xp3x
"Find the Substring with maximum product | C ++ program to find the maximum product substring ; Function to return the value of a character ; Function to find the maximum product substring ; To store substrings ; Check if current product is maximum possible or not ; If product is 0 ; Return the substring with maximum product ; Driver code ; Function call" Solution in C++:
```cpp #include <bits/stdc++.h> using namespace std ; int value ( char x ) { return ( int ) ( x - ' a ' ) ; } string maximumProduct ( string str , int n ) { string answer = " " , curr = " " ; long long maxProduct = 0 , product = 1 ; for ( int i = 0 ; i < n ; i ++ ) { product *= 1LL * value ( str [ i ] ) ; curr += str [ i ] ; if ( product >= maxProduct ) { maxProduct = product ; answer = curr ; } if ( product == 0 ) { product = 1 ; curr = " " ; } } return answer ; } int main ( ) { string str = " sdtfakdhdahdzz " ; int n = str . size ( ) ; cout << maximumProduct ( str , n ) << endl ; return 0 ; } ```
xp3x
"Minimum sum of two integers whose product is strictly greater than N | Java program for the above approach ; Function to find the minimum sum of two integers such that their product is strictly greater than N ; Initialise low as 0 and high as 1e9 ; Iterate to find the first number ; Find the middle value ; If mid ^ 2 is greater than equal to A , then update high to mid ; Otherwise update low ; Store the first number ; Again , set low as 0 and high as 1e9 ; Iterate to find the second number ; Find the middle value ; If first number * mid is greater than N then update high to mid ; Else , update low to mid ; Store the second number ; Print the result ; Driver Code ; Function Call" How can the above be solved in Java?
```java import java . io . * ; class GFG { static void minSum ( int N ) { long low = 0 , high = 1000000000 ; while ( low + 1 < high ) { long mid = low + ( high - low ) / 2 ; if ( mid * mid >= N ) { high = mid ; } else { low = mid ; } } long first = high ; low = 0 ; high = 1000000000 ; while ( low + 1 < high ) { long mid = low + ( high - low ) / 2 ; if ( first * mid > N ) { high = mid ; } else { low = mid ; } } long second = high ; System . out . println ( first + second ) ; } public static void main ( String [ ] args ) { int N = 10 ; minSum ( N ) ; } } ```
xp3x
"Check if given Parentheses expression is balanced or not | C program of the above approach ; Function to check if parentheses are balanced ; Initialising Variables ; Traversing the Expression ; It is a closing parenthesis ; This means there are more Closing parenthesis than opening ones ; If count is not zero , It means there are more opening parenthesis ; Driver code" Solution in C:
```c #include <stdbool.h> #include <stdio.h> bool isBalanced ( char exp [ ] ) { bool flag = true ; int count = 0 ; for ( int i = 0 ; exp [ i ] != ' \0' ; i ++ ) { if ( exp [ i ] == ' ( ' ) { count ++ ; } else { count -- ; } if ( count < 0 ) { flag = false ; break ; } } if ( count != 0 ) { flag = false ; } return flag ; } int main ( ) { char exp1 [ ] = " ( ( ( ) ) ) ( ) ( ) " ; if ( isBalanced ( exp1 ) ) printf ( " Balanced ▁ " ) ; else printf ( " Not ▁ Balanced ▁ " ) ; char exp2 [ ] = " ( ) ) ( ( ( ) ) " ; if ( isBalanced ( exp2 ) ) printf ( " Balanced ▁ " ) ; else printf ( " Not ▁ Balanced ▁ " ) ; return 0 ; } ```
xp3x
How to access elements of a Square Matrix | C Program to read a square matrix and print the elements on secondary diagonal ; Get the square matrix ; Display the matrix ; Print the elements on secondary diagonal ; check for elements on secondary diagonal How can the above be solved in C?
```c #include <stdio.h> int main ( ) { int matrix [ 5 ] [ 5 ] , row_index , column_index , x = 0 , size = 5 ; for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { matrix [ row_index ] [ column_index ] = ++ x ; } } printf ( " The ▁ matrix ▁ is " ) ; for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { printf ( " % d " , matrix [ row_index ] [ column_index ] ) ; } printf ( " " ) ; } printf ( " Elements on Secondary diagonal : " for ( row_index = 0 ; row_index < size ; row_index ++ ) { for ( column_index = 0 ; column_index < size ; column_index ++ ) { if ( ( row_index + column_index ) == size - 1 ) printf ( " % d , ▁ " , matrix [ row_index ] [ column_index ] ) ; } } return 0 ; } ```
xp3x
"Leaders in an array | PHP Function to print leaders in an array ; Rightmost element is always leader ; Driver Code" How can the above be solved in PHP?
```php < ? php function printLeaders ( & $ arr , $ size ) { $ max_from_right = $ arr [ $ size - 1 ] ; echo ( $ max_from_right ) ; echo ( " ▁ " ) ; for ( $ i = $ size - 2 ; $ i >= 0 ; $ i -- ) { if ( $ max_from_right < $ arr [ $ i ] ) { $ max_from_right = $ arr [ $ i ] ; echo ( $ max_from_right ) ; echo ( " ▁ " ) ; } } } $ arr = array ( 16 , 17 , 4 , 3 , 5 , 2 ) ; $ n = sizeof ( $ arr ) ; printLeaders ( $ arr , $ n ) ; ? > ```
xp3x
"Modulo power for large numbers represented as strings | PHP program to find ( a ^ b ) % MOD where a and b may be very large and represented as strings . ; Returns modulo exponentiation for two numbers represented as long long int . It is used by powerStrings ( ) . Its complexity is log ( n ) ; Returns modulo exponentiation for two numbers represented as strings . It is used by powerStrings ( ) ; We convert strings to number ; calculating a % MOD ; calculating b % ( MOD - 1 ) ; Now a and b are long long int . We calculate a ^ b using modulo exponentiation ; As numbers are very large that is it may contains upto 10 ^ 6 digits . So , we use string ." How can the above be solved in PHP?
```php < ? php $ MOD = 1000000007 ; function powerLL ( $ x , $ n ) { global $ MOD ; $ result = 1 ; while ( $ n ) { if ( $ n & 1 ) $ result = $ result * $ x % $ MOD ; $ n = ( int ) $ n / 2 ; $ x = $ x * $ x % $ MOD ; } return $ result ; } function powerStrings ( $ sa , $ sb ) { global $ MOD ; $ a = 0 ; $ b = 0 ; for ( $ i = 0 ; $ i < strlen ( $ sa ) ; $ i ++ ) $ a = ( $ a * 10 + ( $ sa [ $ i ] - '0' ) ) % $ MOD ; for ( $ i = 0 ; $ i < strlen ( $ sb ) ; $ i ++ ) $ b = ( $ b * 10 + ( $ sb [ $ i ] - '0' ) ) % ( $ MOD - 1 ) ; return powerLL ( $ a , $ b ) ; } $ sa = "2" ; $ sb = "3" ; echo powerStrings ( $ sa , $ sb ) ; ? > ```
xp3x
"Check if matrix can be converted to another matrix by transposing square sub | JavaScript implementation of the approach ; Function that returns true if matrix1 can be converted to matrix2 with the given operation ; Traverse all the diagonals starting at first column ; Traverse in diagonal ; Store the diagonal elements ; Move up ; Sort the elements ; Check if they are same ; Traverse all the diagonals starting at last row ; Traverse in the diagonal ; Store diagonal elements ; Sort all elements ; Check for same ; If every element matches ; Driver code" How can the above be solved in JS?
```javascript var n = 3 var m = 3 function check ( a , b ) { for ( var i = 0 ; i < n ; i ++ ) { var v1 = [ ] , v2 = [ ] ; var r = i ; var col = 0 ; while ( r >= 0 && col < m ) { v1 . push ( a [ r ] [ col ] ) ; v2 . push ( b [ r ] [ col ] ) ; r -- ; col ++ ; } v1 . sort ( ) ; v2 . sort ( ) ; for ( var i = 0 ; i < v1 . length ; i ++ ) { if ( v1 [ i ] != v2 [ i ] ) return false ; } } for ( var j = 1 ; j < m ; j ++ ) { var v1 = [ ] , v2 = [ ] ; var r = n - 1 ; var col = j ; while ( r >= 0 && col < m ) { v1 . push ( a [ r ] [ col ] ) ; v2 . push ( b [ r ] [ col ] ) ; r -- ; col ++ ; } v1 . sort ( ) ; v2 . sort ( ) ; for ( var i = 0 ; i < v1 . length ; i ++ ) { if ( v1 [ i ] != v2 [ i ] ) return false ; } } return true ; } var a = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; var b = [ [ 1 , 4 , 7 ] , [ 2 , 5 , 6 ] , [ 3 , 8 , 9 ] ] ; if ( check ( a , b ) ) document . write ( " " ) ; else document . write ( " " ) ; ```
xp3x
"Sum of the series 1.2 . 3 + 2.3 . 4 + ... + n ( n + 1 ) ( n + 2 ) | function to calculate sum of series ; Driver Code" How can the above be solved in PHP?
```php < ? php function sumofseries ( $ n ) { return ( $ n * ( $ n + 1 ) * ( $ n + 2 ) * ( $ n + 3 ) / 4 ) ; } echo sumofseries ( 3 ) ; ? > ```
xp3x
"Find position of the only set bit | C program to find position of only set bit in a given number ; A utility function to check whether n is power of 2 or not ; Returns position of the only set bit in ' n ' ; One by one move the only set bit to right till it reaches end ; increment count of shifts ; Driver program to test above function" Solution in C:
```c #include <stdio.h> int isPowerOfTwo ( unsigned n ) { return n && ( ! ( n & ( n - 1 ) ) ) ; } int findPosition ( unsigned n ) { if ( ! isPowerOfTwo ( n ) ) return -1 ; unsigned count = 0 ; while ( n ) { n = n >> 1 ; ++ count ; } return count ; } int main ( void ) { int n = 0 ; int pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ " , n , pos ) ; n = 12 ; pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ " , n , pos ) ; n = 128 ; pos = findPosition ( n ) ; ( pos == -1 ) ? printf ( " n ▁ = ▁ % d , ▁ Invalid ▁ number " , n ) : printf ( " n ▁ = ▁ % d , ▁ Position ▁ % d ▁ " , n , pos ) ; return 0 ; } ```
xp3x
"Reverse words in a given string | Set 2 | C # program to implement the above approach ; Function to reverse the words of a given String ; Stack to store each word of the String ; Store the whole String in String stream ; Push each word of the String into the stack ; Print the String in reverse order of the words ; Driver Code" Solution in C#:
```csharp using System ; using System . Collections ; class GFG { static void printRev ( string str ) { Stack st = new Stack ( ) ; String [ ] separator = { " ▁ " } ; string [ ] ss = str . Split ( separator , int . MaxValue , StringSplitOptions . RemoveEmptyEntries ) ; foreach ( string temp in ss ) { st . Push ( temp ) ; } while ( st . Count > 0 ) { Console . Write ( st . Peek ( ) + " ▁ " ) ; st . Pop ( ) ; } } public static void Main ( string [ ] args ) { string str ; str = " geeks ▁ quiz ▁ practice ▁ code " ; printRev ( str ) ; } } ```
xp3x
"Range queries for alternatively addition and subtraction on given Array | C # program for the above approach ; Structure to represent a range query ; Function to find the result of alternatively adding and subtracting elements in the range [ L , R ] ; A bool variable flag to alternatively add and subtract ; Iterate from [ L , R ] ; If flag is false , then add & toggle the flag ; If flag is true subtract and toggle the flag ; Return the readonly result ; Function to find the value for each query ; Iterate for each query ; Driver Code ; Given array ; Given Queries ; Function call" How can the above be solved in C-Sharp?
```csharp using System ; class GFG { class Query { public int L , R ; public Query ( int l , int r ) { L = l ; R = r ; } } ; static int findResultUtil ( int [ ] arr , int L , int R ) { int result = 0 ; bool flag = false ; for ( int i = L ; i <= R ; i ++ ) { if ( flag == false ) { result = result + arr [ i ] ; flag = true ; } else { result = result - arr [ i ] ; flag = false ; } } return result ; } static void findResult ( int [ ] arr , int n , Query [ ] q , int m ) { for ( int i = 0 ; i < m ; i ++ ) { Console . Write ( findResultUtil ( arr , q [ i ] . L , q [ i ] . R ) + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 } ; int n = arr . Length ; Query [ ] q = { new Query ( 2 , 5 ) , new Query ( 6 , 8 ) , new Query ( 1 , 7 ) , new Query ( 4 , 8 ) , new Query ( 0 , 5 ) } ; int m = q . Length ; findResult ( arr , n , q , m ) ; } } ```
xp3x
Divide a string in N equal parts | C program to divide a string in n equal parts ; Function to print n equal parts of str ; Check if string can be divided in n equal parts ; Calculate the size of parts to find the division points ; length od string is 28 ; Print 4 equal parts of the string How can the above be solved in C?
```c #include <stdio.h> #include <string.h> void divideString ( char * str , int n ) { int str_size = strlen ( str ) ; int i ; int part_size ; if ( str_size % n != 0 ) { printf ( " Invalid ▁ Input : ▁ String ▁ size " ) ; printf ( " ▁ is ▁ not ▁ divisible ▁ by ▁ n " ) ; return ; } part_size = str_size / n ; for ( i = 0 ; i < str_size ; i ++ ) { if ( i % part_size == 0 ) printf ( " " ) ; printf ( " % c " , str [ i ] ) ; } } int main ( ) { char * str = " a _ simple _ divide _ string _ quest " ; divideString ( str , 4 ) ; getchar ( ) ; return 0 ; } ```
xp3x
"Print all the pairs that contains the positive and negative values of an element | C # program to find pairs of positive and negative values present in an array ; Function to print pairs of positive and negative values present in the array ; Store all the positive elements in the unordered_set ; Start traversing the array ; Check if the positive value of current element exists in the set or not ; Print that pair ; Driver code" How can the above be solved in C-Sharp?
```csharp using System ; using System . Collections . Generic ; class GFG { static void printPairs ( int [ ] arr , int n ) { HashSet < int > pairs = new HashSet < int > ( ) ; bool pair_exists = false ; for ( int i = 0 ; i < n ; i ++ ) if ( arr [ i ] > 0 ) pairs . Add ( arr [ i ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 0 ) if ( pairs . Contains ( - arr [ i ] ) ) { Console . WriteLine ( arr [ i ] + " , ▁ " + - arr [ i ] ) ; pair_exists = true ; } } if ( pair_exists == false ) Console . WriteLine ( " No ▁ such ▁ pair ▁ exists " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 } ; int n = arr . Length ; printPairs ( arr , n ) ; } } ```
xp3x
"Count number of right triangles possible with a given perimeter | Function to return the count ; making a list to store ( a , b ) pairs ; no triangle if p is odd ; make ( a , b ) pair in sorted order ; check to avoid duplicates ; store the new pair ; Driver Code" How can the above be solved in Python?
```python def countTriangles ( p ) : store = [ ] if p % 2 != 0 : return 0 else : count = 0 for b in range ( 1 , p // 2 ) : a = p / 2 * ( ( p - 2 * b ) / ( p - b ) ) inta = int ( a ) if ( a == inta ) : ab = tuple ( sorted ( ( inta , b ) ) ) if ab not in store : count += 1 store . append ( ab ) return count p = 840 print ( " number ▁ of ▁ right ▁ triangles ▁ = ▁ " + str ( countTriangles ( p ) ) ) ```
xp3x
"Number of common base strings for two strings | function for finding common divisor . ; Checking if ' base ' is base string of ' s1' ; Checking if ' base ' is base string of ' s2' ; Driver code" Solution in php:
```php < ? php function isCommonBase ( $ base , $ s1 , $ s2 ) { for ( $ j = 0 ; $ j < strlen ( $ s1 ) ; ++ $ j ) if ( $ base [ $ j % strlen ( $ base ) ] != $ s1 [ $ j ] ) return false ; for ( $ j = 0 ; $ j < strlen ( $ s2 ) ; ++ $ j ) if ( $ base [ $ j % strlen ( $ base ) ] != $ s2 [ $ j ] ) return false ; return true ; } function countCommonBases ( $ s1 , $ s2 ) { $ n1 = strlen ( $ s1 ) ; $ n2 = strlen ( $ s2 ) ; $ count = 0 ; for ( $ i = 1 ; $ i <= min ( $ n1 , $ n2 ) ; $ i ++ ) { $ base = substr ( $ s1 , 0 , $ i ) ; if ( isCommonBase ( $ base , $ s1 , $ s2 ) ) $ count ++ ; } return $ count ; } $ s1 = " pqrspqrs " ; $ s2 = " pqrspqrspqrspqrs " ; echo countCommonBases ( $ s1 , $ s2 ) . " " ; ? > ```
xp3x
"HeapSort | C ++ program for implementation of Heap Sort ; To heapify a subtree rooted with node i which is an index in arr [ ] . n is size of heap ; Initialize largest as root ; left = 2 * i + 1 ; right = 2 * i + 2 ; If left child is larger than root ; If right child is larger than largest so far ; If largest is not root ; Recursively heapify the affected sub - tree ; main function to do heap sort ; Build heap ( rearrange array ) ; One by one extract an element from heap ; Move current root to end ; call max heapify on the reduced heap ; A utility function to print array of size n ; Driver code" How can the above be solved in C++?
```cpp #include <iostream> using namespace std ; void heapify ( int arr [ ] , int n , int i ) { int largest = i ; int l = 2 * i + 1 ; int r = 2 * i + 2 ; if ( l < n && arr [ l ] > arr [ largest ] ) largest = l ; if ( r < n && arr [ r ] > arr [ largest ] ) largest = r ; if ( largest != i ) { swap ( arr [ i ] , arr [ largest ] ) ; heapify ( arr , n , largest ) ; } } void heapSort ( int arr [ ] , int n ) { for ( int i = n / 2 - 1 ; i >= 0 ; i -- ) heapify ( arr , n , i ) ; for ( int i = n - 1 ; i > 0 ; i -- ) { swap ( arr [ 0 ] , arr [ i ] ) ; heapify ( arr , i , 0 ) ; } } void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; ++ i ) cout << arr [ i ] << " ▁ " ; cout << " " ; } int main ( ) { int arr [ ] = { 12 , 11 , 13 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; heapSort ( arr , n ) ; cout << " Sorted ▁ array ▁ is ▁ " ; printArray ( arr , n ) ; } ```
xp3x
Find Array obtained after adding terms of AP for Q queries | C program for the above approach ; Function to find array after performing the given query to the array elements ; Traverse the given query ; Traverse the given array ; Update the value of A [ i ] ; Update the value of curr ; Print the array elements ; Driver Code ; Function Call How can the above be solved in C?
```c #include <stdio.h> void addAP ( int A [ ] , int Q , int operations [ 2 ] [ 4 ] ) { for ( int j = 0 ; j < 2 ; ++ j ) { int L = operations [ j ] [ 0 ] , R = operations [ j ] [ 1 ] , a = operations [ j ] [ 2 ] , d = operations [ j ] [ 3 ] ; int curr = a ; for ( int i = L - 1 ; i < R ; i ++ ) { A [ i ] += curr ; curr += d ; } } for ( int i = 0 ; i < 4 ; ++ i ) printf ( " % d ▁ " , A [ i ] ) ; } int main ( ) { int A [ ] = { 5 , 4 , 2 , 8 } ; int Q = 2 ; int Query [ 2 ] [ 4 ] = { { 1 , 2 , 1 , 3 } , { 1 , 4 , 4 , 1 } } ; addAP ( A , Q , Query ) ; return 0 ; } ```
xp3x
"Minimum number of towers required such that every house is in the range of at least one tower | C ++ implementation of above approach ; Function to count the number of tower ; first we sort the house numbers ; for count number of towers ; for iterate all houses ; count number of towers ; find find the middle location ; traverse till middle location ; this is point to middle house where we insert the tower ; now find the last location ; traverse till last house of the range ; return the number of tower ; Driver code ; given elements ; print number of towers" Solution in C++:
```cpp #include <bits/stdc++.h> using namespace std ; int number_of_tower ( int house [ ] , int range , int n ) { sort ( house , house + n ) ; int numOfTower = 0 ; int i = 0 ; while ( i < n ) { numOfTower ++ ; int loc = house [ i ] + range ; while ( i < n && house [ i ] <= loc ) i ++ ; -- i ; loc = house [ i ] + range ; while ( i < n && house [ i ] <= loc ) i ++ ; } return numOfTower ; } int main ( ) { int house [ ] = { 7 , 2 , 4 , 6 , 5 , 9 , 12 , 11 } ; int range = 2 ; int n = sizeof ( house ) / sizeof ( house [ 0 ] ) ; cout << number_of_tower ( house , range , n ) ; } ```
xp3x
"Count number of rotated strings which have more number of vowels in the first half than second half | C ++ implementation of the approach ; Function to return the count of rotated strings which have more number of vowels in the first half than the second half ; Compute the number of vowels in first - half ; Compute the number of vowels in second - half ; Check if first - half has more vowels ; Check for all possible rotations ; Return the answer ; Driver code ; Function call" Solution in C++:
```cpp #include <bits/stdc++.h> using namespace std ; int cntRotations ( char s [ ] , int n ) { int lh = 0 , rh = 0 , i , ans = 0 ; for ( i = 0 ; i < n / 2 ; ++ i ) if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' i ' s [ i ] == ' o ' s [ i ] == ' u ' ) { lh ++ ; } for ( i = n / 2 ; i < n ; ++ i ) if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' i ' s [ i ] == ' o ' s [ i ] == ' u ' ) { rh ++ ; } if ( lh > rh ) ans ++ ; for ( i = 1 ; i < n ; ++ i ) { if ( s [ i - 1 ] == ' a ' s [ i - 1 ] == ' e ' s [ i - 1 ] == ' i ' s [ i - 1 ] == ' o ' s [ i - 1 ] == ' u ' ) { rh ++ ; lh -- ; } if ( s [ ( i - 1 + n / 2 ) % n ] == ' a ' || s [ ( i - 1 + n / 2 ) % n ] == ' e ' || s [ ( i - 1 + n / 2 ) % n ] == ' i ' || s [ ( i - 1 + n / 2 ) % n ] == ' o ' || s [ ( i - 1 + n / 2 ) % n ] == ' u ' ) { rh -- ; lh ++ ; } if ( lh > rh ) ans ++ ; } return ans ; } int main ( ) { char s [ ] = " abecidft " ; int n = strlen ( s ) ; cout << " ▁ " << cntRotations ( s , n ) ; return 0 ; } ```
xp3x
"Print triplets with sum less than k | PHP program to print triplets with sum smaller than a given value ; Sort input array ; Every iteration of loop counts triplet with first element as arr [ i ] . ; Initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; Use Meet in the Middle concept ; If sum of current triplet is more or equal , move right corner to look for smaller values ; Else move left corner ; This is important . For current i and j , there are total k - j third elements . ; Driver Code" How can the above be solved in PHP?
```php < ? php function printTriplets ( $ arr , $ n , $ sum ) { sort ( $ arr , 0 ) ; for ( $ i = 0 ; $ i < $ n - 2 ; $ i ++ ) { $ j = $ i + 1 ; $ k = $ n - 1 ; while ( $ j < $ k ) { if ( $ arr [ $ i ] + $ arr [ $ j ] + $ arr [ $ k ] >= $ sum ) $ k -- ; else { for ( $ x = $ j + 1 ; $ x <= $ k ; $ x ++ ) echo $ arr [ $ i ] . " , " ▁ . ▁ $ arr [ $ j ] ▁ . " , " ▁ . ▁ $ arr [ $ x ] ▁ . ▁ " " $ j ++ ; } } } } $ arr = array ( 5 , 1 , 3 , 4 , 7 ) ; $ n = sizeof ( $ arr ) ; $ sum = 12 ; printTriplets ( $ arr , $ n , $ sum ) ; ? > ```
xp3x
"Median of all non | Java program to implement the above approach ; Function to calculate the median of all possible subsets by given operations ; Stores sum of elements of arr [ ] ; Traverse the array arr [ ] ; Update sum ; Sort the array ; DP [ i ] [ j ] : Stores total number of ways to form the sum j by either selecting ith element or not selecting ith item . ; Initialize all the DP states ; Base case ; Fill dp [ i ] [ 0 ] ; Base case ; Fill all the DP states based on the mentioned DP relation ; If j is greater than or equal to arr [ i ] ; Update dp [ i ] [ j ] ; Update dp [ i ] [ j ] ; Stores all possible subset sum ; Traverse all possible subset sum ; Stores count of subsets whose sum is j ; Itearate over the range [ 1 , M ] ; Insert j into sumSub ; Stores middle element of sumSub ; Driver Code" Solution in Java:
```java import java . util . * ; class GFG { static int findMedianOfsubSum ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; } Arrays . sort ( arr ) ; int [ ] [ ] dp = new int [ N ] [ sum + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < sum + 1 ; j ++ ) dp [ i ] [ j ] = 0 ; } for ( int i = 0 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = 1 ; } dp [ 0 ] [ arr [ 0 ] ] = 1 ; for ( int i = 1 ; i < N ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { if ( j >= arr [ i ] ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - arr [ i ] ] ; } else { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } } } Vector < Integer > sumSub = new Vector < Integer > ( ) ; for ( int j = 1 ; j <= sum ; j ++ ) { int M = dp [ N - 1 ] [ j ] ; for ( int i = 1 ; i <= M ; i ++ ) { sumSub . add ( j ) ; } } int mid = sumSub . get ( sumSub . size ( ) / 2 ) ; return mid ; } public static void main ( String args [ ] ) { int arr [ ] = { 2 , 3 , 3 } ; int N = arr . length ; System . out . print ( findMedianOfsubSum ( arr , N ) ) ; } } ```
xp3x
"Find two prime numbers with given sum | Generate all prime numbers less than n . ; Initialize all entries of boolean array as true . A value in isPrime [ i ] will finally be false if i is Not a prime , else true bool isPrime [ n + 1 ] ; ; If isPrime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Prints a prime pair with given sum ; Generating primes using Sieve ; Traversing all numbers to find first pair ; Driver Code" How can the above be solved in PHP?
```php < ? php function SieveOfEratosthenes ( $ n , & $ isPrime ) { $ isPrime [ 0 ] = $ isPrime [ 1 ] = false ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) $ isPrime [ $ i ] = true ; for ( $ p = 2 ; $ p * $ p <= $ n ; $ p ++ ) { if ( $ isPrime [ $ p ] == true ) { for ( $ i = $ p * $ p ; $ i <= $ n ; $ i += $ p ) $ isPrime [ $ i ] = false ; } } } function findPrimePair ( $ n ) { $ isPrime = array_fill ( 0 , $ n + 1 , NULL ) ; SieveOfEratosthenes ( $ n , $ isPrime ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ isPrime [ $ i ] && $ isPrime [ $ n - $ i ] ) { echo $ i . " ▁ " . ( $ n - $ i ) ; return ; } } } $ n = 74 ; findPrimePair ( $ n ) ; ? > ```
xp3x
"In | Merge In Place in C ; Both sorted sub - arrays must be adjacent in ' a ' ' an ' is the length of the first sorted section in ' a ' ' bn ' is the length of the second sorted section in ' a ' ; Return right now if we 're done ; Do insertion sort to merge if size of sub - arrays are small enough ; p -- ) Insert Sort A into B ; p ++ ) Insert Sort B into A ; Find the pivot points . Basically this is just finding the point in ' a ' where we can swap in the first part of ' b ' such that after the swap the last element in ' a ' will be less than or equal to the least element in ' b ' ; Swap first part of b with last part of a ; Now merge the two sub - array pairings ; } merge_array_inplace ; Merge Sort Implementation ; Sort first and second halves ; Now merge the two sorted sub - arrays together ; Function to print an array ; Driver program to test sort utiliyy" Solution in C:
```c #include <stddef.h> #include <stdio.h> #define __INSERT_THRESH 5 #define __swap ( x , y ) (t = *(x), *(x) = *(y), *(y) = t) static void merge ( int * a , size_t an , size_t bn ) { int * b = a + an , * e = b + bn , * s , t ; if ( an == 0 || bn == 0 || ! ( * b < * ( b - 1 ) ) ) return ; if ( an < __INSERT_THRESH && an <= bn ) { for ( int * p = b , * v ; p > a ; for ( v = p , s = p - 1 ; v < e && * v < * s ; s = v , v ++ ) __swap ( s , v ) ; return ; } if ( bn < __INSERT_THRESH ) { for ( int * p = b , * v ; p < e ; for ( s = p , v = p - 1 ; s > a && * s < * v ; s = v , v -- ) __swap ( s , v ) ; return ; } int * pa = a , * pb = b ; for ( s = a ; s < b && pb < e ; s ++ ) if ( * pb < * pa ) pb ++ ; else pa ++ ; pa += b - s ; for ( int * la = pa , * fb = b ; la < b ; la ++ , fb ++ ) __swap ( la , fb ) ; merge ( a , pa - a , pb - b ) ; merge ( b , pb - b , e - pb ) ; #undef __swap #undef __INSERT_THRESH void merge_sort ( int * a , size_t n ) { size_t m = ( n + 1 ) / 2 ; if ( m > 1 ) merge_sort ( a , m ) ; if ( n - m > 1 ) merge_sort ( a + m , n - m ) ; merge ( a , m , n - m ) ; } void print_array ( int a [ ] , size_t n ) { if ( n > 0 ) { printf ( " % d " , a [ 0 ] ) ; for ( size_t i = 1 ; i < n ; i ++ ) printf ( " ▁ % d " , a [ i ] ) ; } printf ( " " ) ; } int main ( ) { int a [ ] = { 3 , 16 , 5 , 14 , 8 , 10 , 7 , 15 , 1 , 13 , 4 , 9 , 12 , 11 , 6 , 2 } ; size_t n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; merge_sort ( a , n ) ; print_array ( a , n ) ; return 0 ; } ```
xp3x
"Maximum number of pieces in N cuts | Function for finding maximum pieces with n cuts . ; to maximize number of pieces x is the horizontal cuts ; Now ( x ) is the horizontal cuts and ( n - x ) is vertical cuts , then maximum number of pieces = ( x + 1 ) * ( n - x + 1 ) ; Taking the maximum number of cuts allowed as 3 ; Finding and printing the max number of pieces" Solution in php:
```php < ? php function findMaximumPieces ( $ n ) { $ x = ( int ) ( $ n / 2 ) ; return ( ( $ x + 1 ) * ( $ n - $ x + 1 ) ) ; } $ n = 3 ; echo " Max ▁ number ▁ of ▁ pieces ▁ for ▁ n ▁ = ▁ " . $ n . " ▁ is ▁ " . findMaximumPieces ( 3 ) ; ? > ```
xp3x
Program to find LCM of two numbers | C program to find LCM of two numbers ; Recursive function to return gcd of a and b ; Function to return LCM of two numbers ; Driver program to test above function How can the above be solved in C?
```c #include <stdio.h> int gcd ( int a , int b ) { if ( a == 0 ) return b ; return gcd ( b % a , a ) ; } int lcm ( int a , int b ) { return ( a / gcd ( a , b ) ) * b ; } int main ( ) { int a = 15 , b = 20 ; printf ( " LCM ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ % d ▁ " , a , b , lcm ( a , b ) ) ; return 0 ; } ```
xp3x
"Longest subarray with elements divisible by k | C ++ program of above approach ; function to find longest subarray ; this will contain length of longest subarray found ; Driver code" How can the above be solved in C++?
```cpp #include <bits/stdc++.h> using namespace std ; int longestsubarray ( int arr [ ] , int n , int k ) { int current_count = 0 ; int max_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) current_count ++ ; else current_count = 0 ; max_count = max ( current_count , max_count ) ; } return max_count ; } int main ( ) { int arr [ ] = { 2 , 5 , 11 , 32 , 64 , 88 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 8 ; cout << longestsubarray ( arr , n , k ) ; return 0 ; } ```
xp3x
"Maximum number of groups that can receive fresh donuts distributed in batches of size K | Stores the result of the same recursive calls ; Recursive function to find the maximum number of groups that will receive fresh donuts ; Store the result for the current state ; Store the key and check if it is present in the hashmap ; If already calculated ; If left is 0 ; Traverse the array [ ] arr ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] by 1 ; Otherwise , traverse the given array [ ] arr ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] by 1 ; Memoize the result and return it ; Function to find the maximum number of groups that will receive fresh donuts ; Stores count of remainder by K ; Traverse the array [ ] arr ; Hashmap to memoize the results ; Store the maximum number of groups ; Return the answer ; Driver Code" How can the above be solved in Python?
```python memo = { } def dfs ( V , left , K ) : q = 0 v = [ str ( int ) for int in V ] key = " , " . join ( v ) key += str ( left ) if key in memo : return memo [ key ] elif left == 0 : for i in range ( 1 , K ) : if V [ i ] > 0 : V [ i ] -= 1 q = max ( q , 1 + dfs ( V , K - i , K ) ) V [ i ] += 1 else : for i in range ( 1 , K ) : if V [ i ] > 0 : V [ i ] -= 1 if i <= left : nleft = left - i else : nleft = K + left - i q = max ( q , dfs ( V , nleft , K ) ) V [ i ] += 1 if key in memo : memo [ key ] = q else : memo [ key ] = q return q def maxGroups ( K , arr ) : V = [ 0 ] * ( K ) for x in range ( len ( arr ) ) : V [ arr [ x ] % K ] += 1 memo = { } ans = V [ 0 ] + dfs ( V , 0 , K ) return ans arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] K = 3 print ( maxGroups ( K , arr ) ) ```
xp3x
"Final string after performing given operations | Function to return the modified string ; Count number of ' x ' ; Count number of ' y ' ; min ( x , y ) number of ' x ' and ' y ' will be deleted ; Driver Program to test above function" How can the above be solved in JS?
```javascript function printFinalString ( s ) { var i , n ; n = s . length ; var x = 0 , y = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' ' ) x ++ ; else y ++ ; } var finalString = " " ; if ( x > y ) for ( i = 0 ; i < x - y ; i ++ ) finalString += " " ; else for ( i = 0 ; i < y - x ; i ++ ) finalString += " " ; return finalString ; } var s = " " ; document . write ( printFinalString ( s ) ) ; ```
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" Solution 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
"Sum of multiples of A and B less than N | PHP program to find the sum of all multiples of A and B below N ; Function to find sum of AP series ; Number of terms ; Function to find the sum of all multiples of A and B below N ; Since , we need the sum of multiples less than N ; common factors of A and B ; Driver code" How can the above be solved in PHP?
```php < ? php function __gcd ( $ a , $ b ) { if ( $ b == 0 ) return $ a ; return __gcd ( $ b , $ a % $ b ) ; } function sumAP ( $ n , $ d ) { $ n = ( int ) ( $ n / $ d ) ; return ( $ n ) * ( 1 + $ n ) * $ d / 2 ; } function sumMultiples ( $ A , $ B , $ n ) { $ n -- ; $ common = ( int ) ( ( $ A * $ B ) / __gcd ( $ A , $ B ) ) ; return sumAP ( $ n , $ A ) + sumAP ( $ n , $ B ) - sumAP ( $ n , $ common ) ; } $ n = 100 ; $ A = 5 ; $ B = 10 ; echo " Sum = " ? > ```
xp3x
"Null Cipher | Function to decode the message . ; Store the decoded string ; found variable is used to tell that the encoded encoded character is found in that particular word . ; Set found variable to false whenever we find whitespace , meaning that encoded character for new word is not found ; Driver code" Solution in Python:
```python def decode ( string ) : res = " " found = False for character in string : if character == ' ▁ ' : found = False continue if not found : if character >= ' A ' and character <= ' Z ' or character >= ' a ' and character <= ' z ' : res += character found = True return res . lower ( ) if __name__ == " _ _ main _ _ " : input = " A ▁ Step ▁ by ▁ Step ▁ Guide ▁ for ▁ Placement ▁ Preparation ▁ by ▁ GeeksforGeeks " print ( " Enciphered ▁ Message : " , decode ( input ) ) ```
xp3x
"Minimum increments to convert to an array of consecutive integers | Function that return true if the required array can be generated with m as the last element ; Build the desired array ; Check if the given array can be converted to the desired array with the given operation ; Function to return the minimum number of operations required to convert the given array to an increasing AP series with common difference as 1 ; Apply Binary Search ; If array can be generated with mid as the last element ; Current ans is mid ; Check whether the same can be achieved with even less operations ; Build the desired array ; Calculate the number of operations required ; Return the number of operations required ; Driver code" How can the above be solved in Python?
```python def check ( m , n , arr ) : desired = [ 0 ] * n ; for i in range ( n - 1 , - 1 , - 1 ) : desired [ i ] = m ; m -= 1 ; for i in range ( n ) : if ( arr [ i ] > desired [ i ] or desired [ i ] < 1 ) : return False ; return True def minOperations ( arr , n ) : start = arr [ n - 1 ] ; end = max ( arr ) + n ; max_arr = 0 ; while ( start <= end ) : mid = ( start + end ) // 2 ; if ( check ( mid , n , arr ) ) : max_arr = mid ; end = mid - 1 ; else : start = mid + 1 ; desired = [ 0 ] * n ; for i in range ( n - 1 , - 1 , - 1 ) : desired [ i ] = max_arr ; max_arr -= 1 ; operations = 0 ; for i in range ( n ) : operations += ( desired [ i ] - arr [ i ] ) ; return operations ; if __name__ == " _ _ main _ _ " : arr = [ 4 , 4 , 5 , 5 , 7 ] ; n = len ( arr ) ; print ( minOperations ( arr , n ) ) ; ```
xp3x
"Count all possible values of K less than Y such that GCD ( X , Y ) = GCD ( X + K , Y ) | C # program for the above approach ; Function to find the gcd of a and b ; Function to find the number of Ks ; Find gcd ; Calculating value of totient function for n ; Driver Code ; Given X and Y" How can the above be solved in C-Sharp?
```csharp using System ; class GFG { static int gcd ( int a , int b ) { if ( b == 0 ) return a ; return gcd ( b , a % b ) ; } static int calculateK ( int x , int y ) { int g = gcd ( x , y ) ; int n = y / g ; int res = n ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( n % i == 0 ) { res -= ( res / i ) ; while ( n % i == 0 ) n /= i ; } } if ( n != 1 ) res -= ( res / n ) ; return res ; } public static void Main ( String [ ] args ) { int x = 3 , y = 15 ; Console . Write ( calculateK ( x , y ) + " " ) ; } } ```
xp3x
"Find the maximum sum leaf to root path in a Binary Tree | C program to find maximum sum leaf to root path in Binary Tree ; A tree node structure ; A utility function that prints all nodes on the path from root to target_leaf ; base case ; return true if this node is the target_leaf or target leaf is present in one of its descendants ; This function Sets the target_leaf_ref to refer the leaf node of the maximum path sum . Also , returns the max_sum using max_sum_ref ; Update current sum to hold sum of nodes on path from root to this node ; If this is a leaf node and path to this node has maximum sum so far , then make this node target_leaf ; If this is not a leaf node , then recur down to find the target_leaf ; Returns the maximum sum and prints the nodes on max sum path ; base case ; find the target leaf and maximum sum ; print the path from root to the target leaf ; return maximum sum ; Utility function to create a new Binary Tree node ; Driver function to test above functions" Solution in C:
```c #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> struct node { int data ; struct node * left ; struct node * right ; } ; bool printPath ( struct node * root , struct node * target_leaf ) { if ( root == NULL ) return false ; if ( root == target_leaf || printPath ( root -> left , target_leaf ) || printPath ( root -> right , target_leaf ) ) { printf ( " % d ▁ " , root -> data ) ; return true ; } return false ; } void getTargetLeaf ( struct node * node , int * max_sum_ref , int curr_sum , struct node * * target_leaf_ref ) { if ( node == NULL ) return ; curr_sum = curr_sum + node -> data ; if ( node -> left == NULL && node -> right == NULL ) { if ( curr_sum > * max_sum_ref ) { * max_sum_ref = curr_sum ; * target_leaf_ref = node ; } } getTargetLeaf ( node -> left , max_sum_ref , curr_sum , target_leaf_ref ) ; getTargetLeaf ( node -> right , max_sum_ref , curr_sum , target_leaf_ref ) ; } int maxSumPath ( struct node * node ) { if ( node == NULL ) return 0 ; struct node * target_leaf ; int max_sum = INT_MIN ; getTargetLeaf ( node , & max_sum , 0 , & target_leaf ) ; printPath ( node , target_leaf ) ; return max_sum ; } struct node * newNode ( int data ) { struct node * temp = ( struct node * ) malloc ( sizeof ( struct node ) ) ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int main ( ) { struct node * root = NULL ; root = newNode ( 10 ) ; root -> left = newNode ( -2 ) ; root -> right = newNode ( 7 ) ; root -> left -> left = newNode ( 8 ) ; root -> left -> right = newNode ( -4 ) ; printf ( " Following ▁ are ▁ the ▁ nodes ▁ on ▁ the ▁ maximum ▁ " " sum ▁ path ▁ " ) ; int sum = maxSumPath ( root ) ; printf ( " Sum of the nodes is % d " , sum ) ; getchar ( ) ; return 0 ; } ```
xp3x
"Count N digits numbers with sum divisible by K | JavaScript Program to implement the above approach ; Function to count the N digit numbers whose sum is divisible by K ; Base case ; If already computed subproblem occurred ; Store the count of N digit numbers whose sum is divisible by K ; Check if the number does not contain any leading 0. ; Recurrence relation ; Driver Code ; Stores the values of overlapping subproblems" How can the above be solved in JS?
```javascript var M = 1000 ; function countNum ( N , sum , K , st , dp ) { if ( N == 0 && sum == 0 ) { return 1 ; } if ( N < 0 ) { return 0 ; } if ( dp [ N ] [ sum ] [ st ] != - 1 ) { return dp [ N ] [ sum ] [ st ] ; } var res = 0 ; var start = st == 1 ? 0 : 1 ; for ( var i = start ; i <= 9 ; i ++ ) { res += countNum ( N - 1 , ( sum + i ) % K , K , ( st i > 0 ) , dp ) ; } return dp [ N ] [ sum ] [ st ] = res ; } var N = 2 , K = 7 ; var dp = Array . from ( Array ( M ) , ( ) => Array ( M ) ) ; for ( var i = 0 ; i < M ; i ++ ) for ( var j = 0 ; j < M ; j ++ ) dp [ i ] [ j ] = new Array ( 2 ) . fill ( - 1 ) ; document . write ( countNum ( N , 0 , K , 0 , dp ) ) ; ```
xp3x
"Print all array elements appearing more than N / K times | C # program to implement the above approach ; Function to print all array elements whose frequency is greater than N / K ; Sort the array , arr [ ] ; Traverse the array ; Stores frequency of arr [ i ] ; Traverse array elements which is equal to arr [ i ] ; Update cnt ; Update i ; If frequency of arr [ i ] is greater than ( N / K ) ; Driver Code" Solution in C#:
```csharp using System ; class GFG { static void NDivKWithFreq ( int [ ] arr , int N , int K ) { Array . Sort ( arr ) ; for ( int i = 0 ; i < N ; ) { int cnt = 1 ; while ( ( i + 1 ) < N && arr [ i ] == arr [ i + 1 ] ) { cnt ++ ; i ++ ; } if ( cnt > ( N / K ) ) { Console . Write ( arr [ i ] + " ▁ " ) ; } i ++ ; } } public static void Main ( ) { int [ ] arr = { 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 } ; int N = arr . Length ; int K = 4 ; NDivKWithFreq ( arr , N , K ) ; } } ```
xp3x
"Count of subsequences whose product is a difference of square of two integers | Java implementation to count all the contiguous subsequences whose product is expressed as the square of the difference of two integers ; Function to count all the contiguous subsequences whose product is expressed as the square of the difference of two integers ; Creating vectors to store the remainders and the subsequences ; Iterating through the array ; Finding the remainder when the element is divided by 4 ; Bringing all the elements in the range [ 0 , 3 ] ; If the remainder is 2 , store the index of the ; If the remainder is 2 , store the index of the ; Finding the total number of subsequences ; If there are no numbers which yield the remainder 2 ; Iterating through the vector ; If the element is 2 , find the nearest 2 or 0 and find the number of elements between them ; Returning the count ; Driver code" How can the above be solved in Java?
```java import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static int CntcontSubs ( int a [ ] , int n ) { int prod = 1 ; Vector < pair > vect = new Vector < pair > ( ) ; vect . add ( new pair ( 0 , 2 ) ) ; Vector < Integer > two = new Vector < Integer > ( ) ; Vector < Integer > zero = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { a [ i ] = a [ i ] % 4 ; if ( a [ i ] < 0 ) a [ i ] = a [ i ] + 4 ; if ( a [ i ] == 2 ) two . add ( i + 1 ) ; if ( a [ i ] == 0 ) zero . add ( i + 1 ) ; if ( a [ i ] == 0 a [ i ] == 2 ) vect . add ( new pair ( i + 1 , a [ i ] ) ) ; } vect . add ( new pair ( n + 1 , 2 ) ) ; int total = ( n * ( n + 1 ) ) / 2 ; if ( two . isEmpty ( ) ) return total ; else { int sum = 0 ; int pos1 = - 1 , pos2 = - 1 , pos3 = - 1 ; int sz = vect . size ( ) ; for ( int i = 1 ; i + 1 < sz ; i ++ ) { if ( vect . get ( i ) . second == 2 ) { sum += ( vect . get ( i ) . first - vect . get ( i - 1 ) . first ) * ( vect . get ( i + 1 ) . first - vect . get ( i ) . first ) - 1 ; } } return total - sum - two . size ( ) ; } } public static void main ( String [ ] args ) { int a [ ] = { 5 , 4 , 2 , 9 , 8 } ; int n = a . length ; System . out . print ( CntcontSubs ( a , n ) ) ; } } ```
xp3x
"Split n into maximum composite numbers | C # program to split a number into maximum number of composite numbers . ; function to calculate the maximum number of composite numbers adding upto n ; 4 is the smallest composite number ; stores the remainder when n is divided by 4 ; if remainder is 0 , then it is perfectly divisible by 4. ; if the remainder is 1 ; If the number is less then 9 , that is 5 , then it cannot be expressed as 4 is the only composite number less than 5 ; If the number is greater then 8 , and has a remainder of 1 , then express n as n - 9 a and it is perfectly divisible by 4 and for 9 , count 1. ; When remainder is 2 , just subtract 6 from n , so that n is perfectly divisible by 4 and count 1 for 6 which is subtracted . ; if the number is 7 , 11 which cannot be expressed as sum of any composite numbers ; when the remainder is 3 , then subtract 15 from it and n becomes perfectly divisible by 4 and we add 2 for 9 and 6 , which is getting subtracted to make n perfectly divisible by 4. ; Driver program" Solution in C#:
```csharp using System ; class GFG { static int count ( int n ) { if ( n < 4 ) return - 1 ; int rem = n % 4 ; if ( rem == 0 ) return n / 4 ; if ( rem == 1 ) { if ( n < 9 ) return - 1 ; return ( n - 9 ) / 4 + 1 ; } if ( rem == 2 ) return ( n - 6 ) / 4 + 1 ; if ( rem == 3 ) { if ( n < 15 ) return - 1 ; return ( n - 15 ) / 4 + 2 ; } return 0 ; } public static void Main ( ) { int n = 90 ; Console . WriteLine ( count ( n ) ) ; n = 143 ; Console . WriteLine ( count ( n ) ) ; } } ```
xp3x
"Count N | Java program for the above approach ; Function to count binary strings of length N having substring "11" ; Initialize dp [ ] of size N + 1 ; Base Cases ; Stores the first N powers of 2 ; Generate ; Iterate over the range [ 2 , N ] ; Print total count of substrings ; Driver Code" How can the above be solved in Java?
```java import java . util . * ; class GFG { static void binaryStrings ( int N ) { int [ ] dp = new int [ N + 1 ] ; dp [ 0 ] = 0 ; dp [ 1 ] = 0 ; int [ ] power = new int [ N + 1 ] ; power [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) { power [ i ] = 2 * power [ i - 1 ] ; } for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] + power [ i - 2 ] ; } System . out . println ( dp [ N ] ) ; } public static void main ( String [ ] args ) { int N = 12 ; binaryStrings ( N ) ; } } ```
xp3x
"Lexicographically smallest permutation with no digits at Original Index | Java program to find the smallest permutation ; Function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add EOL and print result ; Driver Code" How can the above be solved in Java?
```java class GFG { static void smallestPermute ( int n ) { char res [ ] = new char [ n + 1 ] ; if ( n % 2 == 0 ) { for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = ( char ) ( 48 + i + 2 ) ; else res [ i ] = ( char ) ( 48 + i ) ; } } else { for ( int i = 0 ; i < n - 2 ; i ++ ) { if ( i % 2 == 0 ) res [ i ] = ( char ) ( 48 + i + 2 ) ; else res [ i ] = ( char ) ( 48 + i ) ; } res [ n - 1 ] = ( char ) ( 48 + n - 2 ) ; res [ n - 2 ] = ( char ) ( 48 + n ) ; res [ n - 3 ] = ( char ) ( 48 + n - 1 ) ; } res [ n ] = ' \0' ; for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( res [ i ] ) ; } } public static void main ( String [ ] args ) { int n = 7 ; smallestPermute ( n ) ; } } ```
xp3x
"Count valid pairs in the array satisfying given conditions | Function to return total valid pairs ; Initialize count of all the elements ; frequency count of all the elements ; Add total valid pairs ; Exclude pairs made with a single element i . e . ( x , x ) ; Driver Code ; Function call to print required answer" How can the above be solved in PHP?
```php < ? php function ValidPairs ( $ arr , $ n ) { $ count = array_fill ( 0 , 121 , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ count [ $ arr [ $ i ] ] += 1 ; $ ans = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( $ arr [ $ i ] < $ arr [ $ j ] ) continue ; if ( abs ( $ arr [ $ i ] - $ arr [ $ j ] ) % 2 == 1 ) continue ; $ ans += $ count [ $ arr [ $ i ] ] * $ count [ $ arr [ $ j ] ] ; if ( $ arr [ $ i ] == $ arr [ $ j ] ) $ ans -= $ count [ $ arr [ $ i ] ] ; } return $ ans ; } $ arr = array ( 16 , 17 , 18 ) ; $ n = count ( $ arr ) ; echo ( ValidPairs ( $ arr , $ n ) ) ; ? > ```
xp3x
"Program to compute log a to any base b ( logb a ) | Java program to find log ( a ) on any base b using Recursion ; Recursive function to compute log a to the base b ; Driver code" How can the above be solved in Java?
```java class GFG { static int log_a_to_base_b ( int a , int b ) { int rslt = ( a > b - 1 ) ? 1 + log_a_to_base_b ( a / b , b ) : 0 ; return rslt ; } public static void main ( String [ ] args ) { int a = 3 ; int b = 2 ; System . out . println ( log_a_to_base_b ( a , b ) ) ; a = 256 ; b = 4 ; System . out . println ( log_a_to_base_b ( a , b ) ) ; } } ```
xp3x
"Maximize the size of array by deleting exactly k sub | Java implementation of the approach ; Sieve of Eratosthenes ; Function to return the size of the maximized array ; Insert the indices of composite numbers ; Compute the number of prime between two consecutive composite ; Sort the diff vector ; Compute the prefix sum of diff vector ; Impossible case ; Delete sub - arrays of length 1 ; Find the number of primes to be deleted when deleting the sub - arrays ; Driver code" How can the above be solved in Java?
```java import java . util . * ; class GFG { static int N = 10000005 ; static int [ ] prime = new int [ N ] ; static void seive ( ) { for ( int i = 2 ; i < N ; i ++ ) { if ( prime [ i ] == 0 ) { for ( int j = i + i ; j < N ; j += i ) { prime [ j ] = 1 ; } } } prime [ 1 ] = 1 ; } static int maxSizeArr ( int arr [ ] , int n , int k ) { ArrayList < Integer > v = new ArrayList < Integer > ( ) ; ArrayList < Integer > diff = new ArrayList < Integer > ( ) ; int num = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] == 1 ) { v . add ( i ) ; } } num = 0 ; for ( int i = 1 ; i < v . size ( ) ; i ++ ) { diff . add ( v . get ( i ) - v . get ( i - 1 ) - 1 ) ; } Collections . sort ( diff ) ; for ( int i = 1 ; i < diff . size ( ) ; i ++ ) { diff . set ( i , diff . get ( i ) + diff . get ( i - 1 ) ) ; } if ( k > n || ( k == 0 && v . size ( ) > 0 ) ) { return - 1 ; } else if ( v . size ( ) <= k ) { return ( n - k ) ; } else if ( v . size ( ) > k ) { int tt = v . size ( ) - k ; int sum = 0 ; sum += diff . get ( tt - 1 ) ; int res = n - ( v . size ( ) + sum ) ; return res ; } return 1 ; } public static void main ( String [ ] args ) { seive ( ) ; int [ ] arr = { 2 , 4 , 2 , 2 , 4 , 2 , 4 , 2 } ; int n = arr . length ; int k = 2 ; System . out . println ( maxSizeArr ( arr , n , k ) ) ; } } ```
xp3x
"K | Returns the sum of first n odd numbers ; Count prime factors of all numbers till B . ; Print all numbers with k prime factors ; Driver code" How can the above be solved in Python?
```python def printKPFNums ( A , B , K ) : prime = [ True ] * ( B + 1 ) p_factors = [ 0 ] * ( B + 1 ) for p in range ( 2 , B + 1 ) : if ( p_factors [ p ] == 0 ) : for i in range ( p , B + 1 , p ) : p_factors [ i ] = p_factors [ i ] + 1 for i in range ( A , B + 1 ) : if ( p_factors [ i ] == K ) : print ( i , end = " ▁ " ) A = 14 B = 18 K = 2 printKPFNums ( A , B , K ) ```
xp3x
"Find the only missing number in a sorted array | CPP program to find the only missing element . ; If this is the first element which is not index + 1 , then missing element is mid + 1 ; if this is not the first missing element search in left side ; if it follows index + 1 property then search in right side ; if no element is missing ; Driver code" How can the above be solved in C++?
```cpp #include <iostream> using namespace std ; int findmissing ( int ar [ ] , int N ) { int l = 0 , r = N - 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( ar [ mid ] != mid + 1 && ar [ mid - 1 ] == mid ) return mid + 1 ; if ( ar [ mid ] != mid + 1 ) r = mid - 1 ; else l = mid + 1 ; } return -1 ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 7 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findmissing ( arr , N ) ; return 0 ; } ```
xp3x
"Minimum multiplications with { 2 , 3 , 7 } to make two numbers equal | Function to find powers of 2 , 3 and 7 in x ; To keep count of each divisor ; To store the result ; Count powers of 2 in x ; Count powers of 3 in x ; Count powers of 7 in x ; Remaining number which is not divisible by 2 , 3 or 7 ; Function to return the minimum number of given operations required to make a and b equal ; a = x * 2 ^ a1 * 3 ^ a2 * 7 ^ a3 va [ 0 ] = a1 va [ 1 ] = a2 va [ 2 ] = a3 va [ 3 ] = x ; Similarly for b ; If a and b cannot be made equal with the given operation . Note that va [ 3 ] and vb [ 3 ] contain remaining numbers after repeated divisions with 2 , 3 and 7. If remaining numbers are not same then we cannot make them equal . ; Minimum number of operations required ; Driver code" How can the above be solved in Python?
```python def Divisors ( x ) : c = 0 v = [ ] while ( x % 2 == 0 ) : c += 1 x /= 2 v . append ( c ) c = 0 while ( x % 3 == 0 ) : c += 1 x /= 3 v . append ( c ) c = 0 while ( x % 7 == 0 ) : c += 1 x /= 7 v . append ( c ) v . append ( x ) return v def MinOperations ( a , b ) : va = Divisors ( a ) vb = Divisors ( b ) if ( va [ 3 ] != vb [ 3 ] ) : return - 1 minOperations = abs ( va [ 0 ] - vb [ 0 ] ) + abs ( va [ 1 ] - vb [ 1 ] ) + abs ( va [ 2 ] - vb [ 2 ] ) return minOperations if __name__ == ' _ _ main _ _ ' : a = 14 b = 28 print ( MinOperations ( a , b ) ) ```
xp3x
"Find number of days between two given dates | Java program two find number of days between two given dates ; A date has day ' d ' , month ' m ' and year ' y ' ; To store number of days in all months from January to Dec . ; This function counts number of leap years before the given date ; Check if the current year needs to be considered for the count of leap years or not ; An year is a leap year if it is a multiple of 4 , multiple of 400 and not a multiple of 100. ; This function returns number of days between two given dates ; initialize count using years and day ; Add days for months in given date ; Since every leap year is of 366 days , Add a day for every leap year ; SIMILARLY , COUNT TOTAL NUMBER OF DAYS BEFORE ' dt2' ; return difference between two counts ; Driver code ; Function call" How can the above be solved in Java?
```java class GFG { static class Date { int d , m , y ; public Date ( int d , int m , int y ) { this . d = d ; this . m = m ; this . y = y ; } } ; static int monthDays [ ] = { 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } ; static int countLeapYears ( Date d ) { int years = d . y ; if ( d . m <= 2 ) { years -- ; } return years / 4 - years / 100 + years / 400 ; } static int getDifference ( Date dt1 , Date dt2 ) { int n1 = dt1 . y * 365 + dt1 . d ; for ( int i = 0 ; i < dt1 . m - 1 ; i ++ ) { n1 += monthDays [ i ] ; } n1 += countLeapYears ( dt1 ) ; int n2 = dt2 . y * 365 + dt2 . d ; for ( int i = 0 ; i < dt2 . m - 1 ; i ++ ) { n2 += monthDays [ i ] ; } n2 += countLeapYears ( dt2 ) ; return ( n2 - n1 ) ; } public static void main ( String [ ] args ) { Date dt1 = new Date ( 1 , 2 , 2000 ) ; Date dt2 = new Date ( 1 , 2 , 2004 ) ; System . out . println ( " Difference ▁ between ▁ two ▁ dates ▁ is ▁ " + getDifference ( dt1 , dt2 ) ) ; } } ```
xp3x
"Maximum and minimum of an array using minimum number of comparisons | ; structure is used to return two values from minMax ( ) ; If array has even number of elements then initialize the first two elements as minimum and maximum ; set the starting index for loop ; If array has odd number of elements then initialize the first element as minimum and maximum ; set the starting index for loop ; In the while loop , pick elements in pair and compare the pair with max and min so far ; Increment the index by 2 as two elements are processed in loop ; Driver program to test above function" Solution in C:
```c #include <stdio.h> struct pair { int min ; int max ; } ; struct pair getMinMax ( int arr [ ] , int n ) { struct pair minmax ; int i ; if ( n % 2 == 0 ) { if ( arr [ 0 ] > arr [ 1 ] ) { minmax . max = arr [ 0 ] ; minmax . min = arr [ 1 ] ; } else { minmax . min = arr [ 0 ] ; minmax . max = arr [ 1 ] ; } i = 2 ; } else { minmax . min = arr [ 0 ] ; minmax . max = arr [ 0 ] ; i = 1 ; } while ( i < n - 1 ) { if ( arr [ i ] > arr [ i + 1 ] ) { if ( arr [ i ] > minmax . max ) minmax . max = arr [ i ] ; if ( arr [ i + 1 ] < minmax . min ) minmax . min = arr [ i + 1 ] ; } else { if ( arr [ i + 1 ] > minmax . max ) minmax . max = arr [ i + 1 ] ; if ( arr [ i ] < minmax . min ) minmax . min = arr [ i ] ; } i += 2 ; } return minmax ; } int main ( ) { int arr [ ] = { 1000 , 11 , 445 , 1 , 330 , 3000 } ; int arr_size = 6 ; struct pair minmax = getMinMax ( arr , arr_size ) ; printf ( " nMinimum ▁ element ▁ is ▁ % d " , minmax . min ) ; printf ( " nMaximum ▁ element ▁ is ▁ % d " , minmax . max ) ; getchar ( ) ; } ```
xp3x
"Sum of maximum of all subarrays by adding even frequent maximum twice | Function to calculate sum of maximum of all subarrays ; Stores the sum of maximums ; Traverse the array ; Store the frequency of the maximum element in subarray ; Finding maximum ; Increment frequency by 1 ; If new maximum is obtained ; If frequency of maximum is even , then add 2 * maxNumber . Otherwise , add maxNumber ; Print the sum obtained ; Driver Code ; Function Call" How can the above be solved in JS?
```javascript function findSum ( a ) { var ans = 0 ; for ( var low = 0 ; low < a . length ; low ++ ) { for ( var high = low ; high < a . length ; high ++ ) { var count = 0 ; var maxNumber = 0 ; for ( var i = low ; i <= high ; i ++ ) { if ( a [ i ] === maxNumber ) count ++ ; else if ( a [ i ] > maxNumber ) { maxNumber = a [ i ] ; count = 1 ; } } ans += maxNumber * ( count % 2 === 0 ? 2 : 1 ) ; } } document . write ( ans ) ; } var arr = [ 2 , 1 , 4 , 4 , 2 ] ; findSum ( arr ) ; ```
xp3x
"Lowest Common Ancestor of the deepest leaves of a Binary Tree | Node of a Binary Tree ; Function to find the depth of the Binary Tree ; If root is not null ; Left recursive subtree ; Right recursive subtree ; Returns the maximum depth ; Function to perform the depth first search on the binary tree ; If root is null ; If curr is equal to depth ; Left recursive subtree ; Right recursive subtree ; If left and right are not null ; Return left , if left is not null Otherwise return right ; Function to find the LCA of the deepest nodes of the binary tree ; If root is null ; Stores the deepest depth of the binary tree ; Return the LCA of the nodes at level depth ; Driver code ; Given Binary Tree" Solution in Java:
```java class Node { Node left = null ; Node right = null ; int data ; Node ( int data ) { this . data = data ; } } class GFG { public static int findDepth ( Node root ) { if ( root == null ) return 0 ; int left = findDepth ( root . left ) ; int right = findDepth ( root . right ) ; return 1 + Math . max ( left , right ) ; } public static Node DFS ( Node root , int curr , int depth ) { if ( root == null ) return null ; if ( curr == depth ) return root ; Node left = DFS ( root . left , curr + 1 , depth ) ; Node right = DFS ( root . right , curr + 1 , depth ) ; if ( left != null && right != null ) return root ; return ( left != null ) ? left : right ; } public static Node lcaOfDeepestLeaves ( Node root ) { if ( root == null ) return null ; int depth = findDepth ( root ) - 1 ; return DFS ( root , 0 , depth ) ; } public static void main ( String [ ] args ) { 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 ) ; root . right . left = new Node ( 6 ) ; root . right . right = new Node ( 7 ) ; root . right . left . left = new Node ( 8 ) ; root . right . left . right = new Node ( 9 ) ; System . out . println ( lcaOfDeepestLeaves ( root ) . data ) ; } } ```
xp3x
"Median of an unsorted array using Quick Select Algorithm | C # program to find median of an array ; Utility function to swapping of element ; Returns the correct position of pivot element ; Picks a random pivot element between l and r and partitions arr [ l . . r ] around the randomly picked element using partition ( ) ; Utility function to find median ; if l < r ; Find the partition index ; If partition index = k , then we found the median of odd number element in [ ] arr ; If index = k - 1 , then we get a & b as middle element of [ ] arr ; If partitionIndex >= k then find the index in first half of the [ ] arr ; If partitionIndex <= k then find the index in second half of the [ ] arr ; Function to find Median ; If n is odd ; If n is even ; Print the Median of [ ] arr ; Driver code" How can the above be solved in C-Sharp?
```csharp using System ; class GFG { static int a , b ; static int [ ] swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } static int Partition ( int [ ] arr , int l , int r ) { int lst = arr [ r ] , i = l , j = l ; while ( j < r ) { if ( arr [ j ] < lst ) { arr = swap ( arr , i , j ) ; i ++ ; } j ++ ; } arr = swap ( arr , i , r ) ; return i ; } static int randomPartition ( int [ ] arr , int l , int r ) { int n = r - l + 1 ; int pivot = ( int ) ( new Random ( ) . Next ( ) % n ) ; arr = swap ( arr , l + pivot , r ) ; return Partition ( arr , l , r ) ; } static int MedianUtil ( int [ ] arr , int l , int r , int k ) { if ( l <= r ) { int partitionIndex = randomPartition ( arr , l , r ) ; if ( partitionIndex == k ) { b = arr [ partitionIndex ] ; if ( a != - 1 ) return int . MinValue ; } else if ( partitionIndex == k - 1 ) { a = arr [ partitionIndex ] ; if ( b != - 1 ) return int . MinValue ; } if ( partitionIndex >= k ) return MedianUtil ( arr , l , partitionIndex - 1 , k ) ; else return MedianUtil ( arr , partitionIndex + 1 , r , k ) ; } return int . MinValue ; } static void findMedian ( int [ ] arr , int n ) { int ans ; a = - 1 ; b = - 1 ; if ( n % 2 == 1 ) { MedianUtil ( arr , 0 , n - 1 , n / 2 ) ; ans = b ; } else { MedianUtil ( arr , 0 , n - 1 , n / 2 ) ; ans = ( a + b ) / 2 ; } Console . Write ( " Median ▁ = ▁ " + ans ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 12 , 3 , 5 , 7 , 4 , 19 , 26 } ; int n = arr . Length ; findMedian ( arr , n ) ; } } ```
xp3x
"Count number of ways to divide a number in 4 parts | A Dynamic Programming based solution to count number of ways to represent n as sum of four numbers ; " parts " is number of parts left , n is the value left " nextPart " is starting point from where we start trying for next part . ; Base cases ; If this subproblem is already solved ; Count number of ways for remaining number n - i remaining parts " parts - 1" , and for all part varying from ' nextPart ' to 'n ; Store computed answer in table and return result ; This function mainly initializes dp table and calls countWaysUtil ( ) ; Driver Code" Solution in Python:
```python dp = [ [ [ - 1 for i in range ( 5 ) ] for i in range ( 501 ) ] for i in range ( 501 ) ] def countWaysUtil ( n , parts , nextPart ) : if ( parts == 0 and n == 0 ) : return 1 if ( n <= 0 or parts <= 0 ) : return 0 if ( dp [ n ] [ nextPart ] [ parts ] != - 1 ) : return dp [ n ] [ nextPart ] [ parts ] ' for i in range ( nextPart , n + 1 ) : ans += countWaysUtil ( n - i , parts - 1 , i ) dp [ n ] [ nextPart ] [ parts ] = ans return ( ans ) def countWays ( n ) : return countWaysUtil ( n , 4 , 1 ) n = 8 print ( countWays ( n ) ) ```
xp3x
"Print all array elements appearing more than N / K times | Function to print all array elements whose frequency is greater than N / K ; Sort the array , arr [ ] ; Traverse the array ; Stores frequency of arr [ i ] ; Traverse array elements which is equal to arr [ i ] ; Update cnt ; Update i ; If frequency of arr [ i ] is greater than ( N / K ) ; Driver Code" Solution in Javascript:
```javascript function NDivKWithFreq ( arr , N , K ) { arr . sort ( ) ; for ( let i = 0 ; i < N ; ) { let cnt = 1 ; while ( ( i + 1 ) < N && arr [ i ] == arr [ i + 1 ] ) { cnt ++ ; i ++ ; } if ( cnt > ( N / K ) ) { document . write ( arr [ i ] + " " ) ; } i ++ ; } } let arr = [ 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 ] ; let N = arr . length ; let K = 4 ; NDivKWithFreq ( arr , N , K ) ; ```
xp3x
"Number of n digit stepping numbers | function that calculates the answer ; if n is 1 then answer will be 10. ; Compute values for count of digits more than 1. ; If ending digit is 0 ; If ending digit is 9 ; For other digits . ; stores the final answer ; Driver Code" How can the above be solved in PHP?
```php < ? php function answer ( $ n ) { if ( $ n == 1 ) return 10 ; for ( $ j = 0 ; $ j <= 9 ; $ j ++ ) $ dp [ 1 ] [ $ j ] = 1 ; for ( $ i = 2 ; $ i <= $ n ; $ i ++ ) { for ( $ j = 0 ; $ j <= 9 ; $ j ++ ) { if ( $ j == 0 ) $ dp [ $ i ] [ $ j ] = $ dp [ $ i - 1 ] [ $ j + 1 ] ; else if ( $ j == 9 ) $ dp [ $ i ] [ $ j ] = $ dp [ $ i - 1 ] [ $ j - 1 ] ; else $ dp [ $ i ] [ $ j ] = $ dp [ $ i - 1 ] [ $ j - 1 ] + $ dp [ $ i - 1 ] [ $ j + 1 ] ; } } $ sum = 0 ; for ( $ j = 1 ; $ j <= 9 ; $ j ++ ) $ sum += $ dp [ $ n ] [ $ j ] ; return $ sum ; } $ n = 2 ; echo answer ( $ n ) ; ? > ```
xp3x
"Lexicographically largest sub | C # implementation of the approach ; Function to return the lexicographically largest sub - sequence of s ; Get the max character from the String ; Use all the occurrences of the current maximum character ; Repeat the steps for the remaining String ; Driver code" How can the above be solved in C-Sharp?
```csharp using System ; class GFG { static String getSubSeq ( String s , int n ) { String res = " " ; int cr = 0 ; while ( cr < n ) { char mx = s [ cr ] ; for ( int i = cr + 1 ; i < n ; i ++ ) { mx = ( char ) Math . Max ( mx , s [ i ] ) ; } int lst = cr ; for ( int i = cr ; i < n ; i ++ ) { if ( s [ i ] == mx ) { res += s [ i ] ; lst = i ; } } cr = lst + 1 ; } return res ; } public static void Main ( String [ ] args ) { String s = " geeksforgeeks " ; int n = s . Length ; Console . WriteLine ( getSubSeq ( s , n ) ) ; } } ```
xp3x
"Count total set bits in all numbers from 1 to n |" Solution in Python:
```python def getSetBitsFromOneToN ( N ) : two = 2 ans = 0 n = N while ( n != 0 ) : ans += int ( N / two ) * ( two >> 1 ) if ( ( N & ( two - 1 ) ) > ( two >> 1 ) - 1 ) : ans += ( N & ( two - 1 ) ) - ( two >> 1 ) + 1 two <<= 1 ; n >>= 1 ; return ans ```
xp3x
"Smallest Special Prime which is greater than or equal to a given number | CPP program to find the Smallest Special Prime which is greater than or equal to a given number ; Function to check whether the number is a special prime or not ; While number is not equal to zero ; If the number is not prime return false . ; Else remove the last digit by dividing the number by 10. ; If the number has become zero then the number is special prime , hence return true ; Function to find the Smallest Special Prime which is greater than or equal to a given number ; Initially all numbers are considered Primes . ; There is always an answer possible ; Checking if the number is a special prime or not ; If yes print the number and break the loop . ; Else increment the number . ; Driver code" How can the above be solved in C++?
```cpp #include <bits/stdc++.h> using namespace std ; bool checkSpecialPrime ( bool * sieve , int num ) { while ( num ) { if ( ! sieve [ num ] ) { return false ; } num /= 10 ; } return true ; } void findSpecialPrime ( int N ) { bool sieve [ N * 10 ] ; memset ( sieve , true , sizeof ( sieve ) ) ; sieve [ 0 ] = sieve [ 1 ] = false ; for ( long long i = 2 ; i <= N * 10 ; i ++ ) { if ( sieve [ i ] ) { for ( long long j = i * i ; j <= N * 10 ; j += i ) { sieve [ j ] = false ; } } } while ( true ) { if ( checkSpecialPrime ( sieve , N ) ) { cout << N << ' ' ; break ; } else N ++ ; } } int main ( ) { int N = 379 ; findSpecialPrime ( N ) ; N = 100 ; findSpecialPrime ( N ) ; return 0 ; } ```
xp3x
"Find a point whose sum of distances from all given points on a line is K | Java program for the above approach ; Function to find the sum of distances of all points from a given point ; Stores sum of distances ; Traverse the array ; Return the sum ; Function to find such a point having sum of distances of all other points from this point equal to K ; If N is odd keep left as arr [ n / 2 ] else keep left as arr [ n / 2 - 1 ] + 1 ; ; Keep right as arr [ N - 1 ] ; Perform binary search in the right half ; Calculate the mid index of the range ; If temp is equal to K ; Print the value of mid ; If the value of K < temp ; Update right to mid - 1 ; If the value of K > temp ; Update left to mid + 1 ; Update the value of left ; Update the value of right ; Perform binary search on the left half ; Calculate the mid index of the range ; If temp is equal to K ; Print mid ; if K > temp ; Update right to mid - 1 ; If K < temp ; Update left to mid + 1 ; If no such point found ; Driver Code" How can the above be solved in Java?
```java import java . lang . * ; class GFG { public static int findSum ( int arr [ ] , int N , int pt ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += Math . abs ( arr [ i ] - pt ) ; } return sum ; } public static void findPoint ( int arr [ ] , int N , int K ) { int left ; if ( N % 2 != 0 ) { left = arr [ N / 2 ] ; } else { left = arr [ N / 2 - 1 ] + 1 ; } int right = arr [ N - 1 ] ; while ( left <= right ) { int mid = ( left + right ) / 2 ; int temp = findSum ( arr , N , mid ) ; if ( temp == K ) { System . out . println ( mid ) ; return ; } else if ( K < temp ) { right = mid - 1 ; } else { left = mid + 1 ; } } left = arr [ 0 ] ; right = arr [ N / 2 ] - 1 ; while ( left <= right ) { int mid = ( left + right ) / 2 ; int temp = findSum ( arr , N , mid ) ; if ( temp == K ) { System . out . println ( mid ) ; return ; } else if ( K > temp ) { right = mid - 1 ; } else { left = mid + 1 ; } } System . out . println ( " - 1" ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 3 , 6 , 7 , 11 } ; int K = 18 ; int N = arr . length ; findPoint ( arr , N , K ) ; } } ```
xp3x
"Largest N digit Octal number which is a Perfect square | C ++ implementation to find the maximum N - digit octal number which is perfect square ; Function to convert decimal number to a octal number ; Array to store octal number ; Counter for octal number array ; Store remainder in octal array ; Print octal number array in reverse order ; Largest n - digit perfect square ; Driver Code" Solution in C++:
```cpp #include <bits/stdc++.h> using namespace std ; void decToOctal ( int n ) { int octalNum [ 100 ] ; int i = 0 ; while ( n != 0 ) { octalNum [ i ] = n % 8 ; n = n / 8 ; i ++ ; } for ( int j = i - 1 ; j >= 0 ; j -- ) cout << octalNum [ j ] ; cout << " " ; } void nDigitPerfectSquares ( int n ) { int decimal = pow ( ceil ( sqrt ( pow ( 8 , n ) ) ) - 1 , 2 ) ; decToOctal ( decimal ) ; } int main ( ) { int n = 2 ; nDigitPerfectSquares ( n ) ; return 0 ; } ```
xp3x
Mobile Numeric Keypad Problem | A Space Optimized C program to count number of possible numbers of given length ; Return count of all possible numbers of length n in a given numeric keyboard ; odd [ i ] , even [ i ] arrays represent count of numbers starting with digit i for any length j ; for j = 1 ; Bottom Up calculation from j = 2 to n ; Here we are explicitly writing lines for each number 0 to 9. But it can always be written as DFS on 4 X3 grid using row , column array valid moves ; Get count of all possible numbers of length " n " starting with digit 0 , 1 , 2 , ... , 9 ; Driver program to test above function How can the above be solved in C?
```c #include <stdio.h> int getCount ( char keypad [ ] [ 3 ] , int n ) { if ( keypad == NULL n <= 0 ) return 0 ; if ( n == 1 ) return 10 ; int odd [ 10 ] , even [ 10 ] ; int i = 0 , j = 0 , useOdd = 0 , totalCount = 0 ; for ( i = 0 ; i <= 9 ; i ++ ) odd [ i ] = 1 ; for ( j = 2 ; j <= n ; j ++ ) { useOdd = 1 - useOdd ; if ( useOdd == 1 ) { even [ 0 ] = odd [ 0 ] + odd [ 8 ] ; even [ 1 ] = odd [ 1 ] + odd [ 2 ] + odd [ 4 ] ; even [ 2 ] = odd [ 2 ] + odd [ 1 ] + odd [ 3 ] + odd [ 5 ] ; even [ 3 ] = odd [ 3 ] + odd [ 2 ] + odd [ 6 ] ; even [ 4 ] = odd [ 4 ] + odd [ 1 ] + odd [ 5 ] + odd [ 7 ] ; even [ 5 ] = odd [ 5 ] + odd [ 2 ] + odd [ 4 ] + odd [ 8 ] + odd [ 6 ] ; even [ 6 ] = odd [ 6 ] + odd [ 3 ] + odd [ 5 ] + odd [ 9 ] ; even [ 7 ] = odd [ 7 ] + odd [ 4 ] + odd [ 8 ] ; even [ 8 ] = odd [ 8 ] + odd [ 0 ] + odd [ 5 ] + odd [ 7 ] + odd [ 9 ] ; even [ 9 ] = odd [ 9 ] + odd [ 6 ] + odd [ 8 ] ; } else { odd [ 0 ] = even [ 0 ] + even [ 8 ] ; odd [ 1 ] = even [ 1 ] + even [ 2 ] + even [ 4 ] ; odd [ 2 ] = even [ 2 ] + even [ 1 ] + even [ 3 ] + even [ 5 ] ; odd [ 3 ] = even [ 3 ] + even [ 2 ] + even [ 6 ] ; odd [ 4 ] = even [ 4 ] + even [ 1 ] + even [ 5 ] + even [ 7 ] ; odd [ 5 ] = even [ 5 ] + even [ 2 ] + even [ 4 ] + even [ 8 ] + even [ 6 ] ; odd [ 6 ] = even [ 6 ] + even [ 3 ] + even [ 5 ] + even [ 9 ] ; odd [ 7 ] = even [ 7 ] + even [ 4 ] + even [ 8 ] ; odd [ 8 ] = even [ 8 ] + even [ 0 ] + even [ 5 ] + even [ 7 ] + even [ 9 ] ; odd [ 9 ] = even [ 9 ] + even [ 6 ] + even [ 8 ] ; } } totalCount = 0 ; if ( useOdd == 1 ) { for ( i = 0 ; i <= 9 ; i ++ ) totalCount += even [ i ] ; } else { for ( i = 0 ; i <= 9 ; i ++ ) totalCount += odd [ i ] ; } return totalCount ; } int main ( ) { char keypad [ 4 ] [ 3 ] = { { '1' , '2' , '3' } , { '4' , '5' , '6' } , { '7' , '8' , '9' } , { ' * ' , '0' , ' # ' } } ; printf ( " Count ▁ for ▁ numbers ▁ of ▁ length ▁ % d : ▁ % dn " , 1 , getCount ( keypad , 1 ) ) ; printf ( " Count ▁ for ▁ numbers ▁ of ▁ length ▁ % d : ▁ % dn " , 2 , getCount ( keypad , 2 ) ) ; printf ( " Count ▁ for ▁... ```
xp3x
"Minimum flip required to make Binary Matrix symmetric | ; Return the minimum flip required to make Binary Matrix symmetric along main diagonal . ; finding the transpose of the matrix ; Finding the number of position where element are not same . ; Driver code" How can the above be solved in JS?
```javascript / *JavaScript Program to find minimum flip required to make Binary Matrix symmetric along main diagonal function minimumflip ( mat , n ) { let transpose = new Array ( n ) ; for ( var i = 0 ; i < transpose . length ; i ++ ) { transpose [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < n ; i ++ ) for ( let j = 0 ; j < n ; j ++ ) transpose [ i ] [ j ] = mat [ j ] [ i ] ; let flip = 0 ; for ( let i = 0 ; i < n ; i ++ ) for ( let j = 0 ; j < n ; j ++ ) if ( transpose [ i ] [ j ] != mat [ i ] [ j ] ) flip ++ ; return flip / 2 ; } let n = 3 ; let mat = [ [ 0 , 0 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 0 , 0 ] ] ; document . write ( minimumflip ( mat , n ) ) ; ```
xp3x
"Finding sum of digits of a number until sum becomes single digit | PHP program to find sum of digits of a number until sum becomes single digit . ; Loop to do sum while sum is not less than or equal to 9 ; Driver Code" Solution in php:
```php < ? php function digSum ( $ n ) { $ sum = 0 ; while ( $ n > 0 $ sum > 9 ) { if ( $ n == 0 ) { $ n = $ sum ; $ sum = 0 ; } $ sum += $ n % 10 ; $ n = ( int ) $ n / 10 ; } return $ sum ; } $ n = 1234 ; echo digSum ( $ n ) ; ? > ```
xp3x
"Sort an almost sorted array where only two elements are swapped | This function sorts an array that can be sorted by single swap ; Traverse the given array from rightmost side ; Check if arr [ i ] is not in order ; Find the other element to be swapped with arr [ i ] ; Swap the pair ; A utility function to print an array of size n ; Driver Code" How can the above be solved in PHP?
```php < ? php function sortByOneSwap ( & $ arr , $ n ) { for ( $ i = $ n - 1 ; $ i > 0 ; $ i -- ) { if ( $ arr [ $ i ] < $ arr [ $ i - 1 ] ) { $ j = $ i - 1 ; while ( $ j >= 0 && $ arr [ $ i ] < $ arr [ $ j ] ) $ j -- ; $ temp = $ arr [ $ i ] ; $ arr [ $ i ] = $ arr [ $ j + 1 ] ; $ arr [ $ j + 1 ] = $ temp ; break ; } } } function printArray ( & $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; echo " " ; } $ arr = array ( 10 , 30 , 20 , 40 , 50 , 60 , 70 ) ; $ n = sizeof ( $ arr ) ; echo " Given ▁ array ▁ is ▁ " . " " ; printArray ( $ arr , $ n ) ; sortByOneSwap ( $ arr , $ n ) ; echo " Sorted ▁ array ▁ is ▁ " . " " ; printArray ( $ arr , $ n ) ; ```
xp3x
"Check if any permutation of a large number is divisible by 8 | Java program to check if any permutation of a large number is divisible by 8 or not ; Function to check if any permutation of a large number is divisible by 8 ; Less than three digit number can be checked directly . ; check for the reverse of a number ; Stores the Frequency of characters in the n . ; Iterates for all three digit numbers divisible by 8 ; stores the frequency of all single digit in three - digit number ; check if the original number has the digit ; when all are checked its not possible ; Driver Code" How can the above be solved in Java?
```java import java . util . * ; class GFG { public static boolean solve ( String n , int l ) { if ( l < 3 ) { if ( Integer . parseInt ( n ) % 8 == 0 ) return true ; n = new String ( ( new StringBuilder ( ) ) . append ( n ) . reverse ( ) ) ; if ( Integer . parseInt ( n ) % 8 == 0 ) return true ; return false ; } int [ ] hash = new int [ 10 ] ; for ( int i = 0 ; i < l ; i ++ ) hash [ n . charAt ( i ) - '0' ] ++ ; for ( int i = 104 ; i < 1000 ; i += 8 ) { int dup = i ; int [ ] freq = new int [ 10 ] ; freq [ dup % 10 ] ++ ; dup = dup / 10 ; freq [ dup % 10 ] ++ ; dup = dup / 10 ; freq [ dup % 10 ] ++ ; dup = i ; if ( freq [ dup % 10 ] > hash [ dup % 10 ] ) continue ; dup = dup / 10 ; if ( freq [ dup % 10 ] > hash [ dup % 10 ] ) continue ; dup = dup / 10 ; if ( freq [ dup % 10 ] > hash [ dup % 10 ] ) continue ; return true ; } return false ; } public static void main ( String [ ] args ) { String number = "31462708" ; int l = number . length ( ) ; if ( solve ( number , l ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } } ```
xp3x
"Minimize Nth term of an Arithmetic progression ( AP ) | 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" How can the above be solved in JS?
```javascript function smallestNth ( A , B , N ) { let res = Number . MAX_VALUE ; for ( let i = 1 ; i < N ; i ++ ) { for ( let j = N ; j > i ; j -- ) { if ( ( B - A ) % ( j - i ) == 0 ) { let D = ( B - A ) / ( j - i ) ; let FirstTerm = A - ( i - 1 ) * D ; let NthTerm = FirstTerm + ( N - 1 ) * D ; if ( FirstTerm > 0 ) res = Math . min ( res , NthTerm ) ; } } } return res ; } let N = 3 ; let A = 1 ; let B = 6 ; document . write ( smallestNth ( A , B , N ) ) ; ```
xp3x
"Long Division Method to find Square root with Examples | Java program to find the square root of a number by using long division method ; Function to find the square root of a number by using long division method ; int i = 0 , udigit , j ; Loop counters ; Dividing the number into segments ; Last index of the array of segments ; Start long division from the last segment ( j = i ) ; Initialising the remainder to the maximum value ; Including the next segment in new dividend ; Loop to check for the perfect square closest to each segment ; This condition is to find the divisor after adding a digit in the range 0 to 9 ; Calculating the remainder ; Updating the units digit of the quotient ; Adding units digit to the quotient ; New divisor is two times quotient ; Including the remainder in new dividend ; Driver code" Solution in Java:
```java import java . util . * ; class GFG { static final int INFINITY_ = 9999999 ; static int sqrtByLongDivision ( int n ) { int cur_divisor = 0 ; int quotient_units_digit = 0 ; int cur_quotient = 0 ; int cur_dividend = 0 ; int cur_remainder = 0 ; int a [ ] = new int [ 10 ] ; while ( n > 0 ) { a [ i ] = n % 100 ; n = n / 100 ; i ++ ; } i -- ; for ( j = i ; j >= 0 ; j -- ) { cur_remainder = INFINITY_ ; cur_dividend = cur_dividend * 100 + a [ j ] ; for ( udigit = 0 ; udigit <= 9 ; udigit ++ ) { if ( cur_remainder >= cur_dividend - ( ( cur_divisor * 10 + udigit ) * udigit ) && cur_dividend - ( ( cur_divisor * 10 + udigit ) * udigit ) >= 0 ) { cur_remainder = cur_dividend - ( ( cur_divisor * 10 + udigit ) * udigit ) ; quotient_units_digit = udigit ; } } cur_quotient = cur_quotient * 10 + quotient_units_digit ; cur_divisor = cur_quotient * 2 ; cur_dividend = cur_remainder ; } return cur_quotient ; } public static void main ( String [ ] args ) { int x = 1225 ; System . out . print ( sqrtByLongDivision ( x ) + " "); } } ```
xp3x
"Sum of an array of large numbers | Function to print the result of the summation of numbers having K - digit ; Reverse the array to obtain the result ; Print every digit of the answer ; Function to calculate the total sum ; Stores the array of large numbers in integer format ; Convert each element from character to integer ; Stores the carry ; Stores the result of summation ; Initialize the sum ; Calculate sum ; Update the sum by adding existing carry ; Store the number of digits ; Increase count of digits ; If the number exceeds 9 , Store the unit digit in carry ; Store the rest of the sum ; Append digit by digit into result array ; Append result until carry is 0 ; Print the result ; Driver Code ; Given N array of large numbers" Solution in Javascript:
```javascript function printResult ( result ) { result . reverse ( ) ; let i = 0 ; while ( i < result . length ) { document . write ( result [ i ] ) ; i ++ ; } } function sumOfLargeNumbers ( v , k , N ) { let x = [ ] ; for ( let i = 0 ; i < k ; i ++ ) x . push ( [ ] ) ; for ( let i = 0 ; i < k ; i ++ ) { for ( let j = 0 ; j < N ; j ++ ) { x [ i ] . push ( v [ i ] [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ; } } let carry = 0 ; let result = [ ] ; for ( let i = N - 1 ; i >= 0 ; i -- ) { let sum = 0 ; for ( let j = 0 ; j < k ; j ++ ) sum += x [ j ] [ i ] ; sum += carry ; let temp = sum ; let count = 0 ; while ( temp > 9 ) { temp = temp % 10 ; count ++ ; } let l = Math . pow ( 10 , count ) ; if ( l != 1 ) carry = Math . floor ( sum / l ) ; sum = sum % 10 ; result . push ( sum ) ; } while ( carry != 0 ) { let a = carry % 10 ; result . push ( a ) ; carry = Math . floor ( carry / 10 ) ; } printResult ( result ) ; } let K = 10 ; let N = 5 ; let arr = [ " " , " " , " " , " " , " " ] ; sumOfLargeNumbers ( arr , N , K ) ; ```
xp3x
"Count of replacements required to make the sum of all Pairs of given type from the Array equal | C ++ Program to implement the above approach ; Function to find the minimum replacements required ; Stores the maximum and minimum values for every pair of the form arr [ i ] , arr [ n - i - 1 ] ; Map for storing frequencies of every sum formed by pairs ; Minimum element in the pair ; Maximum element in the pair ; Incrementing the frequency of sum encountered ; Insert minimum and maximum values ; Sorting the vectors ; Iterate over all possible values of x ; Count of pairs for which x > x + k ; Count of pairs for which x < mn + 1 ; Count of pairs requiring 2 replacements ; Count of pairs requiring no replacements ; Count of pairs requiring 1 replacement ; Update the answer ; Return the answer ; Driver Code" How can the above be solved in C++?
```cpp #include <bits/stdc++.h> #define int long long int using namespace std ; const int inf = 1e18 ; int minimumReplacement ( int * arr , int N , int K ) { int ans = inf ; vector < int > max_values ; vector < int > min_values ; map < int , int > sum_equal_to_x ; for ( int i = 0 ; i < N / 2 ; i ++ ) { int mn = min ( arr [ i ] , arr [ N - i - 1 ] ) ; int mx = max ( arr [ i ] , arr [ N - i - 1 ] ) ; sum_equal_to_x [ arr [ i ] + arr [ N - i - 1 ] ] ++ ; min_values . push_back ( mn ) ; max_values . push_back ( mx ) ; } sort ( max_values . begin ( ) , max_values . end ( ) ) ; sort ( min_values . begin ( ) , min_values . end ( ) ) ; for ( int x = 2 ; x <= 2 * K ; x ++ ) { int mp1 = lower_bound ( max_values . begin ( ) , max_values . end ( ) , x - K ) - max_values . begin ( ) ; int mp2 = lower_bound ( min_values . begin ( ) , min_values . end ( ) , x ) - min_values . begin ( ) ; int rep2 = mp1 + ( N / 2 - mp2 ) ; int rep0 = sum_equal_to_x [ x ] ; int rep1 = ( N / 2 - rep2 - rep0 ) ; ans = min ( ans , rep2 * 2 + rep1 ) ; } return ans ; } int32_t main ( ) { int N = 4 ; int K = 3 ; int arr [ ] = { 1 , 2 , 2 , 1 } ; cout << minimumReplacement ( arr , N , K ) ; return 0 ; } ```
xp3x
"Sum of the series 1.2 . 3 + 2.3 . 4 + ... + n ( n + 1 ) ( n + 2 ) | PHP program to find sum of the series 1.2 . 3 + 2.3 . 4 + 3.4 . 5 + ... ; Driver Code" How can the above be solved in PHP?
```php < ? php function sumofseries ( $ n ) { $ res = 0 ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ res += ( $ i ) * ( $ i + 1 ) * ( $ i + 2 ) ; return $ res ; } echo sumofseries ( 3 ) ; ? > ```
xp3x
"Maximize the sum of modulus with every Array element | C ++ program to find the maximum sum of modulus with every array element ; Function to return the maximum sum of modulus with every array element ; Sum of array elements ; Return the answer ; Driver Program" How can the above be solved in C++?
```cpp #include <bits/stdc++.h> using namespace std ; int maxModulosum ( int a [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += a [ i ] ; } return sum - n ; } int main ( ) { int a [ ] = { 3 , 4 , 6 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxModulosum ( a , n ) ; return 0 ; } ```
xp3x
"Check if a number is divisible by all prime divisors of another number | PHP program to find if all prime factors of y divide x . ; Returns true if all prime factors of y divide x . ; Driver Code" How can the above be solved in PHP?
```php < ? php function gcd ( $ a , $ b ) { return $ b == 0 ? $ a : gcd ( $ b , $ a % $ b ) ; } function isDivisible ( $ x , $ y ) { if ( $ y == 1 ) return true ; $ z = gcd ( $ x , $ y ) ; if ( $ z == 1 ) return false ; return isDivisible ( $ x , $ y / $ z ) ; } $ x = 18 ; $ y = 12 ; if ( isDivisible ( $ x , $ y ) ) echo " Yes " ; else echo " No " ; ? > ```