Muennighoff/xP3x-sample huggingface dataset:
inputs: "Rearrange array by interchanging positions of even and odd elements in the given array | Function to replace each even element by odd and vice - versa in a given array ; Stores length of array ; Traverse array ; If current element is even then swap it with odd ; Perform Swap ; Change the sign ; If current element is odd then swap it with even ; Perform Swap ; Change the sign ; Marked element positive ; Prlet final array ; Given array arr [ ] ; Function Call"
How can the above be solved in JS?
targets: function replace ( arr ) { let n = arr . length ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = i + 1 ; j < n ; j ++ ) { if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 == 0 && arr [ j ] % 2 != 0 ) { let tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } else if ( arr [ i ] >= 0 && arr [ j ] >= 0 && arr [ i ] % 2 != 0 && arr [ j ] % 2 == 0 ) { let tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; arr [ j ] = - arr [ j ] ; break ; } } } for ( let i = 0 ; i < n ; i ++ ) arr [ i ] = Math . abs ( arr [ i ] ) ; for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } let arr = [ 1 , 3 , 2 , 4 ] ; replace ( arr ) ;
inputs: "Write a program to calculate pow ( x , n ) |  ; Function to calculate x raised to the power y ; Program to test function power"
Solution in C:
targets: #include <stdio.h>
int power ( int x , unsigned int y ) { if ( y == 0 ) return 1 ; else if ( y % 2 == 0 ) return power ( x , y / 2 ) * power ( x , y / 2 ) ; else return x * power ( x , y / 2 ) * power ( x , y / 2 ) ; } int main ( ) { int x = 2 ; unsigned int y = 3 ; printf ( " % d " , power ( x , y ) ) ; return 0 ; }
inputs: Calculate 7 n / 8 without using division and multiplication operators | C program to evaluate ceil ( 7 n / 8 ) without using * and / ; Note the inner bracket here . This is needed because precedence of ' - ' operator is higher than ' < < ' ; Driver program to test above function
How can the above be solved in C?
targets: #include <stdio.h>
int multiplyBySevenByEight ( unsigned int n ) { return ( n - ( n >> 3 ) ) ; } int main ( ) { unsigned int n = 9 ; printf ( " % d " , multiplyBySevenByEight ( n ) ) ; return 0 ; }
inputs: "Find k ordered pairs in array with minimum difference d | Java implementation of the approach ; Function to find the required pairs ; There has to be atleast 2 * k elements ; To store the pairs ; Sort the given array ; For every possible pair ; If the current pair is valid ; Insert it into the pair vector ; If k pairs are not possible ; Print the pairs ; Driver code"
Solution in Java:
targets: import java . util . * ; class GFG { static class pair { int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void findPairs ( int arr [ ] , int n , int k , int d ) { if ( n < 2 * k ) { System . out . print ( - 1 ) ; return ; } Vector < pair > pairs = new Vector < pair > ( ) ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < k ; i ++ ) { if ( arr [ n - k + i ] - arr [ i ] >= d ) { pair p = new pair ( arr [ i ] , arr [ n - k + i ] ) ; pairs . add ( p ) ; } } if ( pairs . size ( ) < k ) { System . out . print ( - 1 ) ; return ; } for ( pair v : pairs ) { System . out . println ( " ( " + v . first + " , ▁ " + v . second + " ) " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 6 , 10 , 23 , 14 , 7 , 2 , 20 , 9 } ; int n = arr . length ; int k = 4 , d = 3 ; findPairs ( arr , n , k , d ) ; } }
inputs: "Probability that a random pair chosen from an array ( a [ i ] , a [ j ] ) has the maximum sum | Java implementation of the approach ; Function to return the probability of getting the maximum pair sum when a random pair is chosen from the given array ; Initialize the maximum sum , its count and the count of total pairs ; For every single pair ; Get the sum of the current pair ; If the sum is equal to the current maximum sum so far ; Increment its count ; If the sum is greater than the current maximum ; Update the current maximum and re - initialize the count to 1 ; Find the required probability ; Driver code"
Solution in Java:
targets: import java . util . * ; class GFG { static float findProb ( int arr [ ] , int n ) { long maxSum = Integer . MIN_VALUE , maxCount = 0 , totalPairs = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int sum = arr [ i ] + arr [ j ] ; if ( sum == maxSum ) { maxCount ++ ; } else if ( sum > maxSum ) { maxSum = sum ; maxCount = 1 ; } totalPairs ++ ; } } float prob = ( float ) maxCount / ( float ) totalPairs ; return prob ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 1 , 1 , 2 , 2 , 2 } ; int n = arr . length ; System . out . println ( findProb ( arr , n ) ) ; } }
inputs: "Find if it is possible to choose subarray that it contains exactly K even integers | Function to check if it is possible to choose a subarray that contains exactly K even integers ; Variable to store the count of even numbers ; If we have to select 0 even numbers but there is all odd numbers in the array ; If the count of even numbers is greater than or equal to K then we can select a subarray with exactly K even integers ; If the count of even numbers is less than K then we cannot select any subarray with exactly K even integers ; Driver code"
How can the above be solved in JS?
targets: function isPossible ( A , n , k ) { var countOfTwo = 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( A [ i ] % 2 == 0 ) { countOfTwo ++ ; } } if ( k == 0 && countOfTwo == n ) document . write ( " " ) ; else if ( countOfTwo >= k ) { document . write ( " " ) ; } else document . write ( " " ) ; } var arr = [ 1 , 2 , 4 , 5 ] ; var K = 2 ; var N = arr . length ; isPossible ( arr , N , K ) ;
inputs: "Maximum number of pair reductions possible on a given triplet | C # program for the above approach ; Function to count the maximum number of pair reductions possible on a given triplet ; Convert them into an array ; Stores count of operations ; Sort the array ; If the first two array elements reduce to 0 ; Apply the operations ; Increment count ; Print the maximum count ; Driver Code ; Given triplet"
Solution in C#:
targets: using System ; class GFG { static void maxOps ( int a , int b , int c ) { int [ ] arr = { a , b , c } ; int count = 0 ; while ( 1 != 0 ) { Array . Sort ( arr ) ; if ( arr [ 0 ] == 0 && arr [ 1 ] == 0 ) break ; arr [ 1 ] -= 1 ; arr [ 2 ] -= 1 ; count += 1 ; } Console . WriteLine ( count ) ; } public static void Main ( String [ ] args ) { int a = 4 , b = 3 , c = 2 ; maxOps ( a , b , c ) ; } }
inputs: "Find the day number in the current year for the given date | Java implementation of the approach ; Function to return the day number of the year for the given date ; Extract the year , month and the day from the date string ; If current year is a leap year and the date given is after the 28 th of February then it must include the 29 th February ; Add the days in the previous months ; Driver code"
How can the above be solved in Java?
targets: class GFG { static int days [ ] = { 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 } ; static int dayOfYear ( String date ) { int year = Integer . parseInt ( date . substring ( 0 , 4 ) ) ; int month = Integer . parseInt ( date . substring ( 5 , 7 ) ) ; int day = Integer . parseInt ( date . substring ( 8 ) ) ; if ( month > 2 && year % 4 == 0 && ( year % 100 != 0 year % 400 == 0 ) ) { ++ day ; } while ( -- month > 0 ) { day = day + days [ month - 1 ] ; } return day ; } public static void main ( String [ ] args ) { String date = "2019-01-09" ; System . out . println ( dayOfYear ( date ) ) ; } }
inputs: "Lexicographically largest permutation possible by a swap that is smaller than a given array | C # program for the above approach ; Function to lexicographic largest permutation possible by a swap that is smaller than given array ; Find the index of first element such that arr [ i ] > arr [ i + 1 ] ; If the array is sorted in increasing order ; Find the index of first element which is smaller than arr [ i ] ; If arr [ j ] = = arr [ j - 1 ] ; Decrement j ; Swap the element ; Print the array arr [ ] ; Driver Code"
How can the above be solved in C-Sharp?
targets: using System ; class GFG { static void findPermutation ( int [ ] arr ) { int N = arr . Length ; int i = N - 2 ; while ( i >= 0 && arr [ i ] <= arr [ i + 1 ] ) i -- ; if ( i == - 1 ) { Console . Write ( " - 1" ) ; return ; } int j = N - 1 ; while ( j > i && arr [ j ] >= arr [ i ] ) j -- ; while ( j > i && arr [ j ] == arr [ j - 1 ] ) { j -- ; } int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; foreach ( int it in arr ) { Console . Write ( it + " ▁ " ) ; } } public static void Main ( ) { int [ ] arr = { 1 , 2 , 5 , 3 , 4 , 6 } ; findPermutation ( arr ) ; } }
inputs: "k | C # program to find k - th element in the Odd - Even sequence . ; insert all the odd numbers from 1 to n . ; insert all the even numbers from 1 to n . ; Driver code"
How can the above be solved in C-Sharp?
targets: using System ; using System . Collections ; class GFG { static int findK ( int n , int k ) { ArrayList a = new ArrayList ( n ) ; for ( int i = 1 ; i < n ; i ++ ) if ( i % 2 == 1 ) a . Add ( i ) ; for ( int i = 1 ; i < n ; i ++ ) if ( i % 2 == 0 ) a . Add ( i ) ; return ( int ) ( a [ k - 1 ] ) ; } static void Main ( ) { int n = 10 , k = 3 ; Console . WriteLine ( findK ( n , k ) ) ; } }
inputs: "Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1 | Java Program to split a given String into K segments such that the sum of product of occurence of characters in them is minimized ; Function to return the minimum sum of products of occurences of 0 and 1 in each segments ; Store the length of the String ; Not possible to generate subsets greater than the length of String ; If the number of subsets equals the length ; Precompute the sum of products for all index ; Calculate the minimum sum of products for K subsets ; Driver code"
How can the above be solved in Java?
targets: import java . util . * ; class GFG { static int minSumProd ( String S , int K ) { int len = S . length ( ) ; if ( K > len ) return - 1 ; if ( K == len ) return 0 ; int [ ] dp = new int [ len ] ; int count_zero = 0 , count_one = 0 ; for ( int j = 0 ; j < len ; j ++ ) { if ( S . charAt ( j ) == '0' ) count_zero ++ ; else count_one ++ ; dp [ j ] = count_zero * count_one ; } for ( int i = 1 ; i < K ; i ++ ) { for ( int j = len - 1 ; j >= i ; j -- ) { count_zero = 0 ; count_one = 0 ; dp [ j ] = Integer . MAX_VALUE ; for ( int k = j ; k >= i ; k -- ) { if ( S . charAt ( k ) == '0' ) count_zero ++ ; else count_one ++ ; dp [ j ] = Math . min ( dp [ j ] , count_zero * count_one + dp [ k - 1 ] ) ; } } } return dp [ len - 1 ] ; } public static void main ( String [ ] args ) { String S = "1011000110110100" ; int K = 5 ; System . out . print ( minSumProd ( S , K ) ) ; } }
inputs: "Pascal 's Triangle | A O ( n ^ 2 ) time and O ( n ^ 2 ) extra space method for Pascal 's Triangle ; An auxiliary array to store generated pscal triangle values ; Iterate through every line and print integer ( s ) in it ; Every line has number of integers equal to line number ; First and last values in every row are 1 ; Other values are sum of values just above and left of above ; Driver code"
How can the above be solved in PHP?
targets: < ? php function printPascal ( $ n ) { $ arr = array ( array ( ) ) ; for ( $ line = 0 ; $ line < $ n ; $ line ++ ) { for ( $ i = 0 ; $ i <= $ line ; $ i ++ ) { if ( $ line == $ i $ i == 0 ) $ arr [ $ line ] [ $ i ] = 1 ; else $ arr [ $ line ] [ $ i ] = $ arr [ $ line - 1 ] [ $ i - 1 ] + $ arr [ $ line - 1 ] [ $ i ] ; echo $ arr [ $ line ] [ $ i ] . " " ; } echo " 
 " ; } } $ n = 5 ; printPascal ( $ n ) ; ? >
inputs: "Find the two numbers with odd occurrences in an unsorted array | Program to find the two odd occurring elements ; Prints two numbers that occur odd number of times . The function assumes that the array size is at least 2 and there are exactly two numbers occurring odd number of times . ; Will hold XOR of two odd occurring elements ; Will have only single set bit of xor2 ; Get the xor of all elements in arr [ ] . The xor will basically be xor of two odd occurring elements ; Get one set bit in the xor2 . We get rightmost set bit in the following line as it is easy to get ; Now divide elements in two sets : 1 ) The elements having the corresponding bit as 1. 2 ) The elements having the corresponding bit as 0. ; XOR of first set is finally going to hold one odd occurring number x ; XOR of second set is finally going to hold the other odd occurring number y ; Driver program to test above function"
Solution in C:
targets: #include <stdio.h>
void printTwoOdd ( int arr [ ] , int size ) { int xor2 = arr [ 0 ] ; int set_bit_no ; int i ; int n = size - 2 ; int x = 0 , y = 0 ; for ( i = 1 ; i < size ; i ++ ) xor2 = xor2 ^ arr [ i ] ; set_bit_no = xor2 & ~ ( xor2 - 1 ) ; for ( i = 0 ; i < size ; i ++ ) { if ( arr [ i ] & set_bit_no ) x = x ^ arr [ i ] ; else y = y ^ arr [ i ] ; } printf ( " The two ODD elements are % d & % d " , x , y ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 4 , 5 , 2 , 3 , 3 , 1 } ; int arr_size = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printTwoOdd ( arr , arr_size ) ; getchar ( ) ; return 0 ; }
inputs: Compute the minimum or maximum of two integers without branching |  ; Function to find minimum of x and y ; Function to find maximum of x and y ; Driver program to test above functions
How can the above be solved in C?
targets: #include <stdio.h>
#define CHAR_BIT  8
int min ( int x , int y ) { return y + ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHAR_BIT - 1 ) ) ) ; } int max ( int x , int y ) { return x - ( ( x - y ) & ( ( x - y ) >> ( sizeof ( int ) * CHAR_BIT - 1 ) ) ) ; } int main ( ) { int x = 15 ; int y = 6 ; printf ( " Minimum ▁ of ▁ % d ▁ and ▁ % d ▁ is ▁ " , x , y ) ; printf ( " % d " , min ( x , y ) ) ; printf ( " Maximum of % d and % d is " printf ( " % d " , max ( x , y ) ) ; getchar ( ) ; }
inputs: "Check if a number has an odd count of odd divisors and even count of even divisors | Java implementation of the above approach ; Function to find the count of even and odd factors of N ; Loop runs till square root ; Condition to check if the even factors of the number N is is even and count of odd factors is odd ; Driver Code"
How can the above be solved in Java?
targets: import java . util . * ; class GFG { static void checkFactors ( long N ) { long ev_count = 0 , od_count = 0 ; for ( long i = 1 ; i <= Math . sqrt ( N ) + 1 ; i ++ ) { if ( N % i == 0 ) { if ( i == N / i ) { if ( i % 2 == 0 ) ev_count += 1 ; else od_count += 1 ; } else { if ( i % 2 == 0 ) ev_count += 1 ; else od_count += 1 ; if ( ( N / i ) % 2 == 0 ) ev_count += 1 ; else od_count += 1 ; } } } if ( ev_count % 2 == 0 && od_count % 2 == 1 ) System . out . print ( " Yes " + "
"); else System . out . print ( " No " + "
"); } public static void main ( String [ ] args ) { long N = 36 ; checkFactors ( N ) ; } }
inputs: "Find minimum steps required to reach the end of a matrix | Set 2 | C ++ implementation of the approach ; 2d array to store states of dp ; Array to determine whether a state has been solved before ; Function to return the minimum steps required ; Base cases ; If a state has been solved before it won 't be evaluated again ; Recurrence relation ; Driver code"
Solution in C++:
targets: #include <bits/stdc++.h>
#define n  3
using namespace std ; int dp [ n ] [ n ] ; int v [ n ] [ n ] ; int minSteps ( int i , int j , int arr [ ] [ n ] ) { if ( i == n - 1 and j == n - 1 ) return 0 ; if ( i > n - 1 j > n - 1 ) return 9999999 ; if ( v [ i ] [ j ] ) return dp [ i ] [ j ] ; v [ i ] [ j ] = 1 ; dp [ i ] [ j ] = 9999999 ; for ( int k = max ( 0 , arr [ i ] [ j ] + j - n + 1 ) ; k <= min ( n - i - 1 , arr [ i ] [ j ] ) ; k ++ ) { dp [ i ] [ j ] = min ( dp [ i ] [ j ] , minSteps ( i + k , j + arr [ i ] [ j ] - k , arr ) ) ; } dp [ i ] [ j ] ++ ; return dp [ i ] [ j ] ; } int main ( ) { int arr [ n ] [ n ] = { { 4 , 1 , 2 } , { 1 , 1 , 1 } , { 2 , 1 , 1 } } ; int ans = minSteps ( 0 , 0 , arr ) ; if ( ans >= 9999999 ) cout << -1 ; else cout << ans ; return 0 ; }
inputs: "Compositorial of a number | Function to check if a number is composite . ; Corner cases ; This is checked so that we can skip the middle five numbers in the below loop ; This function stores all Composite numbers less than N ; Function to calculate the Compositorial of n ; Multiply first n composite number ; Driver code ; Vector to store all the composite less than N"
How can the above be solved in Python?
targets: def isComposite ( n ) :
	if ( n <= 3 ) :
		return False
	if ( n % 2 == 0 or n % 3 == 0 ) :
		return True
	i = 5
	while ( i * i <= n ) :
		if ( n % i == 0 or n % ( i + 2 ) == 0 ) :
			return True
		i = i + 6
	return False
def Compositorial_list ( n ) :
	l = 0
	for i in range ( 4 , 10 ** 6 ) :
		if l < n :
			if isComposite ( i ) :
				compo . append ( i )
				l += 1
def calculateCompositorial ( n ) :
	result = 1
	for i in range ( n ) :
		result = result * compo [ i ]
	return result
if __name__ == " _ _ main _ _ " :
	n = 5
	compo = [ ]
	Compositorial_list ( n )
	print ( calculateCompositorial ( n ) )
inputs: "Sum of all odd length subarrays | C # program for the above approach ; Function to calculate the sum of all odd length subarrays ; Stores the sum ; Size of array ; Traverse the array ; Generate all subarray of odd length ; Add the element to sum ; Return the final sum ; Driver Code ; Given array arr [ ] ; Function call"
Solution in C#:
targets: using System ; class GFG { static int OddLengthSum ( int [ ] arr ) { int sum = 0 ; int l = arr . Length ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = i ; j < l ; j += 2 ) { for ( int k = i ; k <= j ; k ++ ) { sum += arr [ k ] ; } } } return sum ; } public static void Main ( ) { int [ ] arr = { 1 , 5 , 3 , 1 , 2 } ; Console . Write ( OddLengthSum ( arr ) ) ; } }
inputs: "Rearrange array to maximize sum of GCD of array elements with their respective indices | C # program to implement the above approach ; Function to find the maximum sum of GCD ( arr [ i ] , i ) by rearranging the array ; Sort the array in ascending order ; Stores maximum sum of GCD ( arr [ i ] , i ) by rearranging the array elements ; Generate all possible permutations of the array ; Stores sum of GCD ( arr [ i ] , i ) ; Traverse the array ; Update sum ; Update res ; Driver Code"
Solution in C#:
targets: using System ; class GFG { static int findMaxValByRearrArr ( int [ ] arr , int N ) { Array . Sort ( arr ) ; int res = 0 ; do { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += __gcd ( i + 1 , arr [ i ] ) ; } res = Math . Max ( res , sum ) ; } while ( next_permutation ( arr ) ) ; return res ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } static bool next_permutation ( int [ ] p ) { for ( int a = p . Length - 2 ; a >= 0 ; -- a ) if ( p [ a ] < p [ a + 1 ] ) for ( int b = p . Length - 1 ; ; -- b ) if ( p [ b ] > p [ a ] ) { int t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; for ( ++ a , b = p . Length - 1 ; a < b ; ++ a , -- b ) { t = p [ a ] ; p [ a ] = p [ b ] ; p [ b ] = t ; } return true ; } return false ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 1 } ; int N = arr . Length ; Console . Write ( findMaxValByRearrArr ( arr , N ) ) ; } }
inputs: "Count all prefixes of the given binary array which are divisible by x | Function to return the count of total binary prefix which are divisible by x ; Initialize with zero ; Convert all prefixes to decimal ; If number is divisible by x then increase count ; Driver code"
Solution in php:
targets: < ? php function CntDivbyX ( $ arr , $ n , $ x ) { $ number = 0 ; $ count = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ number = $ number * 2 + $ arr [ $ i ] ; if ( ( $ number % $ x == 0 ) ) $ count += 1 ; } return $ count ; } $ arr = array ( 1 , 0 , 1 , 0 , 1 , 1 , 0 ) ; $ n = sizeof ( $ arr ) ; $ x = 2 ; echo CntDivbyX ( $ arr , $ n , $ x ) ;
inputs: "Longest Increasing Subsequence | DP | lis ( ) returns the length of the longest increasing subsequence in arr [ ] of size n ; Initialize LIS values for all indexes ; Compute optimized LIS values in bottom up manner ; Pick maximum of all LIS values ; Driver code"
How can the above be solved in JS?
targets: function lis ( arr , n ) { let lis = Array ( n ) . fill ( 0 ) ; let i , j , max = 0 ; for ( i = 0 ; i < n ; i ++ ) lis [ i ] = 1 ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; for ( i = 0 ; i < n ; i ++ ) if ( max < lis [ i ] ) max = lis [ i ] ; return max ; } let arr = [ 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 ] ; let n = arr . length ; document . write ( " " + lis ( arr , n ) + " " ) ;
inputs: "Majority Element | Program for finding out majority element in an array ; Function to find the candidate for Majority ; Function to check if the candidate occurs more than n / 2 * times ; Function to print Majority Element ; Find the candidate for Majority ; Print the candidate if it is Majority ; Driver code ; Function call"
Solution in C:
targets: #include <stdio.h>
#define bool  int
int findCandidate ( int * , int ) ; bool isMajority ( int * , int , int ) ; int findCandidate ( int a [ ] , int size ) { int maj_index = 0 , count = 1 ; int i ; for ( i = 1 ; i < size ; i ++ ) { if ( a [ maj_index ] == a [ i ] ) count ++ ; else count -- ; if ( count == 0 ) { maj_index = i ; count = 1 ; } } return a [ maj_index ] ; } bool isMajority ( int a [ ] , int size , int cand ) { int i , count = 0 ; for ( i = 0 ; i < size ; i ++ ) if ( a [ i ] == cand ) count ++ ; if ( count > size / 2 ) return 1 ; else return 0 ; } void printMajority ( int a [ ] , int size ) { int cand = findCandidate ( a , size ) ; if ( isMajority ( a , size , cand ) ) printf ( " ▁ % d ▁ " , cand ) ; else printf ( " No ▁ Majority ▁ Element " ) ; } int main ( ) { int a [ ] = { 1 , 3 , 3 , 1 , 2 } ; int size = ( sizeof ( a ) ) / sizeof ( a [ 0 ] ) ; printMajority ( a , size ) ; getchar ( ) ; return 0 ; }
inputs: "Binomial Random Variables | function to calculate nCr i . e . , number of ways to choose r out of n objects ; Since nCr is same as nC ( n - r ) To decrease number of iterations ; function to calculate binomial r . v . probability ; Driver code"
Solution in php:
targets: < ? php function nCr ( $ n , $ r ) { if ( $ r > $ n / 2 ) $ r = $ n - $ r ; $ answer = 1 ; for ( $ i = 1 ; $ i <= $ r ; $ i ++ ) { $ answer *= ( $ n - $ r + $ i ) ; $ answer /= $ i ; } return $ answer ; } function binomialProbability ( $ n , $ k , $ p ) { return nCr ( $ n , $ k ) * pow ( $ p , $ k ) * pow ( 1 - $ p , $ n - $ k ) ; } $ n = 10 ; $ k = 5 ; $ p = 1.0 / 3 ; $ probability = binomialProbability ( $ n , $ k , $ p ) ; echo " Probability ▁ of ▁ " . $ k ; echo " ▁ heads ▁ when ▁ a ▁ coin ▁ is ▁ tossed ▁ " . $ n ; echo " ▁ times ▁ where ▁ probability ▁ of ▁ " . " each ▁ head ▁ is ▁ " . $ p ; echo " is = " ? >
inputs: "Number of permutation with K inversions | Set 2 | C # program for the above approach ; Function to count permutations with K inversions ; Store number of permutations with K inversions ; If N = 1 only 1 permutation with no inversion ; For K = 0 only 1 permutation with no inversion ; Otherwise Update each dp state as per the reccurrance relation formed ; Print final count ; Driver Code ; Given N and K ; Function Call"
How can the above be solved in C-Sharp?
targets: using System ; class GFG { static void numberOfPermWithKInversion ( int N , int K ) { int [ , ] dp = new int [ 2 , K + 1 ] ; int mod = 1000000007 ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 0 ; j <= K ; j ++ ) { if ( i == 1 ) { dp [ i % 2 , j ] = ( j == 0 ) ? 1 : 0 ; } else if ( j == 0 ) dp [ i % 2 , j ] = 1 ; else dp [ i % 2 , j ] = ( dp [ i % 2 , j - 1 ] % mod + ( dp [ 1 - i % 2 , j ] - ( ( Math . Max ( j - ( i - 1 ) , 0 ) == 0 ) ? 0 : dp [ 1 - i % 2 , Math . Max ( j - ( i - 1 ) , 0 ) - 1 ] ) + mod ) % mod ) % mod ; } } Console . WriteLine ( dp [ N % 2 , K ] ) ; } public static void Main ( ) { int N = 3 , K = 2 ; numberOfPermWithKInversion ( N , K ) ; } }
inputs: "Largest lexicographic triplet from a given Array that forms a triangle | C # program to implement the the above approach ; Function to find lexicographically largest triplet that forms a triangle in the given array ; Sort the array ; Iterate from the end of the array ; If the triplet forms a triangle ; If triplet found ; Print the triplet ; Otherwise ; Driver Code"
How can the above be solved in C-Sharp?
targets: using System ; class GFG { static void findTriplet ( int [ ] arr , int N ) { Array . Sort ( arr ) ; int flag = 0 , i ; for ( i = N - 1 ; i - 2 >= 0 ; i -- ) { if ( arr [ i - 2 ] + arr [ i - 1 ] > arr [ i ] ) { flag = 1 ; break ; } } if ( flag != 0 ) { Console . Write ( arr [ i - 2 ] + " ▁ " + arr [ i - 1 ] + " ▁ " + arr [ i ] ) ; } else { Console . Write ( - 1 ) ; } } public static void Main ( string [ ] args ) { int [ ] arr = { 4 , 2 , 10 , 3 , 5 } ; int N = arr . Length ; findTriplet ( arr , N ) ; } }
inputs: "Smallest character in a string having minimum sum of distances between consecutive repetitions | Python3 program for the above approach ; Function to find the character repeats with minimum distance ; Stores the first and last index ; Intialize with - 1 ; Get the values of last and first occurence ; Update the first index ; Update the last index ; Intialize the min ; Get the minimum ; Values must not be same ; Update the minimum distance ; return ans ; Driver Code ; Function call"
How can the above be solved in Python?
targets: import sys
def minDistChar ( s ) :
	n = len ( s )
	first = [ ]
	last = [ ]
	for i in range ( 26 ) :
		first . append ( - 1 )
		last . append ( - 1 )
	for i in range ( n ) :
		if ( first [ ord ( s [ i ] ) - ord ( ' a ' ) ] == - 1 ) :
			first [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i
		last [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i
	min = sys . maxsize
	ans = '1'
	for i in range ( 26 ) :
		if ( last [ i ] == first [ i ] ) :
			continue
		if ( min > last [ i ] - first [ i ] ) :
			min = last [ i ] - first [ i ]
			ans = i + ord ( ' a ' )
	return chr ( ans )
if __name__ == " _ _ main _ _ " :
	str = " geeksforgeeks "
	print ( minDistChar ( str ) )
inputs: "Cutting a Rod | DP | A Dynamic Programming solution for Rod cutting problem ; Returns the best obtainable price for a rod of length n and price [ ] as prices of different pieces ; Build the table val [ ] in bottom up manner and return the last entry from the table ; Driver Code"
How can the above be solved in C-Sharp?
targets: using System ; class GFG { static int cutRod ( int [ ] price , int n ) { int [ ] val = new int [ n + 1 ] ; val [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { int max_val = int . MinValue ; for ( int j = 0 ; j < i ; j ++ ) max_val = Math . Max ( max_val , price [ j ] + val [ i - j - 1 ] ) ; val [ i ] = max_val ; } return val [ n ] ; } public static void Main ( ) { int [ ] arr = new int [ ] { 1 , 5 , 8 , 9 , 10 , 17 , 17 , 20 } ; int size = arr . Length ; Console . WriteLine ( " Maximum ▁ Obtainable ▁ Value ▁ is ▁ " + cutRod ( arr , size ) ) ; } }
inputs: "Find minimum steps required to reach the end of a matrix | Set | Java program to implement above approach ; 2d array to store states of dp ; array to determine whether a state has been solved before ; Function to find the minimum number of steps to reach the end of matrix ; base cases ; if a state has been solved before it won 't be evaluated again. ; recurrence relation ; Driver Code"
How can the above be solved in Java?
targets: class GFG { static int n = 3 ; static int dp [ ] [ ] = new int [ n ] [ n ] ; static int [ ] [ ] v = new int [ n ] [ n ] ; static int minSteps ( int i , int j , int arr [ ] [ ] ) { if ( i == n - 1 && j == n - 1 ) { return 0 ; } if ( i > n - 1 j > n - 1 ) { return 9999999 ; } if ( v [ i ] [ j ] == 1 ) { return dp [ i ] [ j ] ; } v [ i ] [ j ] = 1 ; dp [ i ] [ j ] = 1 + Math . min ( minSteps ( i + arr [ i ] [ j ] , j , arr ) , minSteps ( i , j + arr [ i ] [ j ] , arr ) ) ; return dp [ i ] [ j ] ; } public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 2 , 1 , 2 } , { 1 , 1 , 1 } , { 1 , 1 , 1 } } ; int ans = minSteps ( 0 , 0 , arr ) ; if ( ans >= 9999999 ) { System . out . println ( - 1 ) ; } else { System . out . println ( ans ) ; } } }
inputs: "Find most significant set bit of a number | CPP program to find MSB number for given n . ; To find the position of the most significant set bit ; To return the the value of the number with set bit at k - th position ; Driver code"
How can the above be solved in C++?
targets: #include <bits/stdc++.h>
using namespace std ; int setBitNumber ( int n ) { int k = ( int ) ( log2 ( n ) ) ; return 1 << k ; } int main ( ) { int n = 273 ; cout << setBitNumber ( n ) ; return 0 ; }
inputs: "Maximum sum such that no two elements are adjacent |  ; Function to return max sum such that no two elements are adjacent ; current max excluding i ; current max including i ; return max of incl and excl ; Driver program to test above function"
Solution in C:
targets: #include <stdio.h>
int FindMaxSum ( int arr [ ] , int n ) { int incl = arr [ 0 ] ; int excl = 0 ; int excl_new ; int i ; for ( i = 1 ; i < n ; i ++ ) { excl_new = ( incl > excl ) ? incl : excl ; incl = excl + arr [ i ] ; excl = excl_new ; } return ( ( incl > excl ) ? incl : excl ) ; } int main ( ) { int arr [ ] = { 5 , 5 , 10 , 100 , 10 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " % d ▁ n " , FindMaxSum ( arr , n ) ) ; return 0 ; }
inputs: "Secretary Problem ( A Optimal Stopping Problem ) | PHP Program to test 1 / e law for Secretary Problem : ; To find closest integer of num . ; Finds best candidate using n / e rule . candidate [ ] represents talents of n candidates . ; Calculating sample size for benchmarking . ; Finding best candidate in sample size ; Finding the first best candidate that is better than benchmark set . ; Driver code ; n = 8 candidates and candidate array contains talents of n candidate where the largest number means highest talented candidate . ; generating random numbers between 1 to 8 for talent of candidate"
Solution in php:
targets: < ? php $ e = 2.71828 ; function roundNo ( $ num ) { return $ num < 0 ? $ num - 0.5 : $ num + 0.5 ; } function printBestCandidate ( $ candidate , $ n ) { global $ e ; $ sample_size = roundNo ( $ n / $ e ) ; echo " Sample size is " floor ( $ sample_size ) . " 
 " ; $ best = 0 ; for ( $ i = 1 ; $ i < $ sample_size ; $ i ++ ) if ( $ candidate [ $ i ] > $ candidate [ $ best ] ) $ best = $ i ; for ( $ i = $ sample_size ; $ i < $ n ; $ i ++ ) if ( $ candidate [ $ i ] >= $ candidate [ $ best ] ) { $ best = $ i ; break ; } if ( $ best >= $ sample_size ) echo " Best candidate found is " . floor ( $ best + 1 ) . " ▁ with ▁ talent ▁ " . floor ( $ candidate [ $ best ] ) . " 
 " ; else echo " Couldn ' t ▁ find ▁ a ▁ best ▁ candidate 
 " ; } $ n = 8 ; $ candidate = array_fill ( 0 , $ n , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ candidate [ $ i ] = 1 + rand ( 1 , 8 ) ; echo " Candidate ▁ : ▁ " ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo ( $ i + 1 ) . " ▁ " ; echo " Talents : " ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) echo $ candidate [ $ i ] . " ▁ " ; printBestCandidate ( $ candidate , $ n ) ; ? >
inputs: "Maximum length of consecutive 1 s or 0 s after flipping at most K characters | C # program for the above approach ; Function to find the maximum length continuos segment of character c after flipping at most K characters ; Stores the maximum length ; Stores the count of char ' c ' ; Start of window ; Remove the extra ' c ' from left ; Increment the value of the left ; Update the resultant maximum length of character ch ; Function to find the maximum length of consecutive 0 s or 1 s by flipping at most K characters of the string ; Print the maximum of the maximum length of 0 s or 1 s ; Driver code"
How can the above be solved in C-Sharp?
targets: using System ; public class GFG { static int maxLength ( String str , int n , char c , int k ) { int ans = - 1 ; int cnt = 0 ; int left = 0 ; for ( int right = 0 ; right < n ; right ++ ) { if ( str [ right ] == c ) { cnt ++ ; } while ( cnt > k ) { if ( str [ left ] == c ) { cnt -- ; } left ++ ; } ans = Math . Max ( ans , right - left + 1 ) ; } return ans ; } static int maxConsecutiveSegment ( String S , int K ) { int N = S . Length ; return Math . Max ( maxLength ( S , N , '0' , K ) , maxLength ( S , N , '1' , K ) ) ; } public static void Main ( ) { String S = "1001" ; int K = 1 ; Console . WriteLine ( maxConsecutiveSegment ( S , K ) ) ; } }
inputs: "Print all possible combinations of r elements in a given array of size n | Program to print all combination of size r in an array of size n ; The main function that prints all combinations of size r in arr [ ] of size n . This function mainly uses combinationUtil ( ) ; A temporary array to store all combination one by one ; Print all combination using temprary array ' data [ ] ' ; arr [ ] -- -> Input Array n -- -> Size of input array r -- -> Size of a combination to be printed index -- -> Current index in data [ ] data [ ] -- -> Temporary array to store current combination i -- -> index of current element in arr [ ] ; Current cobination is ready , print it ; When no more elements are there to put in data [ ] ; current is included , put next at next location ; current is excluded , replace it with next ( Note that i + 1 is passed , but index is not changed ) ; Driver program to test above functions"
Solution in C:
targets: #include <stdio.h>
void combinationUtil ( int arr [ ] , int n , int r , int index , int data [ ] , int i ) ; void printCombination ( int arr [ ] , int n , int r ) { int data [ r ] ; combinationUtil ( arr , n , r , 0 , data , 0 ) ; } void combinationUtil ( int arr [ ] , int n , int r , int index , int data [ ] , int i ) { if ( index == r ) { for ( int j = 0 ; j < r ; j ++ ) printf ( " % d ▁ " , data [ j ] ) ; printf ( " 
 " ) ; return ; } if ( i >= n ) return ; data [ index ] = arr [ i ] ; combinationUtil ( arr , n , r , index + 1 , data , i + 1 ) ; combinationUtil ( arr , n , r , index , data , i + 1 ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int r = 3 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printCombination ( arr , n , r ) ; return 0 ; }
inputs: Distance between two parallel Planes in 3 | C program to find the Distance between two parallel Planes in 3 D . ; Function to find distance ; Driver Code
How can the above be solved in C?
targets: #include <stdio.h>
#include <math.h>
void distance ( float a1 , float b1 , float c1 , float d1 , float a2 , float b2 , float c2 , float d2 ) { float x1 , y1 , z1 , d ; if ( a1 / a2 == b1 / b2 && b1 / b2 == c1 / c2 ) { x1 = y1 = 0 ; z1 = - d1 / c1 ; d = fabs ( ( c2 * z1 + d2 ) ) / ( sqrt ( a2 * a2 + b2 * b2 + c2 * c2 ) ) ; printf ( " Perpendicular ▁ distance ▁ is ▁ % f 
 " , d ) ; } else printf ( " Planes ▁ are ▁ not ▁ parallel " ) ; return ; } int main ( ) { float a1 = 1 ; float b1 = 2 ; float c1 = -1 ; float d1 = 1 ; float a2 = 3 ; float b2 = 6 ; float c2 = -3 ; float d2 = -4 ; distance ( a1 , b1 , c1 , d1 , a2 , b2 , c2 , d2 ) ; return 0 ; }
inputs: "Modify array of strings by replacing characters repeating in the same or remaining strings | Function to remove duplicate characters across the strings ; Stores distinct characters ; Size of the array ; Stores the list of modified strings ; Traverse the array ; Stores the modified string ; Iterate over the characters of the modified string ; If character is already present ; Insert character into the Set ; Print the list of modified strings ; Print each string ; Given array of strings ; Function Call to modify the given array of strings"
How can the above be solved in JS?
targets: function removeDuplicateCharacters ( arr ) { var cset = new Set ( ) ; var n = arr . length ; var out = [ ] ; arr . forEach ( str => { var out_curr = " " ; str . split ( ' ' ) . forEach ( ch => { if ( ! cset . has ( ch ) ) { out_curr += ch ; cset . add ( ch ) ; } } ) ; if ( out_curr . size != 0 ) out . push ( out_curr ) ; } ) ; for ( var i = 0 ; i < out . length ; i ++ ) { document . write ( out [ i ] + " " ) ; } } var arr = [ " " , " " , " " , " " ] ; removeDuplicateCharacters ( arr ) ;
inputs: "Hyperfactorial of a number | function to calculate the value of hyperfactorial ; initialise the val to 1 ; returns the hyperfactorial of a number ; Driver code"
Solution in Java:
targets: class GFG { static long boost_hyperfactorial ( long num ) { long val = 1 ; for ( int i = 1 ; i <= num ; i ++ ) { val = val * ( long ) Math . pow ( i , i ) ; } return val ; } public static void main ( String args [ ] ) { int num = 5 ; System . out . println ( boost_hyperfactorial ( num ) ) ; } }
inputs: "Count of minimum reductions required to get the required sum K | Python3 program to find the count of minimum reductions required to get the required sum K ; Function to return the count of minimum reductions ; If the sum is already less than K ; Sort in non - increasing order of difference ; Driver Code ; Function Call"
Solution in Python:
targets: from typing import Any , List
def countReductions ( v : List [ Any ] , K : int ) -> int :
	sum = 0
	for i in v :
		sum += i [ 0 ]
	if ( sum <= K ) :
		return 0
	v . sort ( key = lambda a : a [ 0 ] - a [ 1 ] )
	i = 0
	while ( sum > K and i < len ( v ) ) :
		sum -= ( v [ i ] [ 0 ] - v [ i ] [ 1 ] )
		i += 1
	if ( sum <= K ) :
		return i
	return - 1
if __name__ == " _ _ main _ _ " :
	N = 4
	K = 25
	v = [ [ 0 , 0 ] for _ in range ( N ) ]
	v [ 0 ] = [ 10 , 5 ]
	v [ 1 ] = [ 20 , 9 ]
	v [ 2 ] = [ 12 , 10 ]
	v [ 3 ] = [ 4 , 2 ]
	print ( countReductions ( v , K ) )
inputs: "Count all possible groups of size 2 or 3 that have sum as multiple of 3 | C ++ Program to count all possible groups of size 2 or 3 that have sum as multiple of 3 ; Returns count of all possible groups that can be formed from elements of a [ ] . ; Create an array C [ 3 ] to store counts of elements with remainder 0 , 1 and 2. c [ i ] would store count of elements with remainder i ; To store the result ; Count elements with remainder 0 , 1 and 2 ; Case 3. a : Count groups of size 2 from 0 remainder elements ; Case 3. b : Count groups of size 2 with one element with 1 remainder and other with 2 remainder ; Case 4. a : Count groups of size 3 with all 0 remainder elements ; Case 4. b : Count groups of size 3 with all 1 remainder elements ; Case 4. c : Count groups of size 3 with all 2 remainder elements ; Case 4. c : Count groups of size 3 with different remainders ; Return total count stored in res ; Driver Code"
Solution in C++:
targets: #include <bits/stdc++.h>
using namespace std ; int findgroups ( int arr [ ] , int n ) { int c [ 3 ] = { 0 } , i ; int res = 0 ; for ( i = 0 ; i < n ; i ++ ) c [ arr [ i ] % 3 ] ++ ; res += ( ( c [ 0 ] * ( c [ 0 ] - 1 ) ) >> 1 ) ; res += c [ 1 ] * c [ 2 ] ; res += ( c [ 0 ] * ( c [ 0 ] - 1 ) * ( c [ 0 ] - 2 ) ) / 6 ; res += ( c [ 1 ] * ( c [ 1 ] - 1 ) * ( c [ 1 ] - 2 ) ) / 6 ; res += ( ( c [ 2 ] * ( c [ 2 ] - 1 ) * ( c [ 2 ] - 2 ) ) / 6 ) ; res += c [ 0 ] * c [ 1 ] * c [ 2 ] ; return res ; } int main ( ) { int arr [ ] = { 3 , 6 , 7 , 2 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Required ▁ number ▁ of ▁ groups ▁ are ▁ " << findgroups ( arr , n ) << endl ; return 0 ; }
inputs: "Subarrays whose sum is a perfect square | Function to print the start and end indices of all subarrays whose sum is a perfect square ; Stores the current subarray sum ; Update current subarray sum ; Stores the square root of currSubSum ; Check if currSubSum is a perfect square or not ; Driver Code"
How can the above be solved in JS?
targets: function PrintIndexes ( arr , N ) { for ( let i = 0 ; i < N ; i ++ ) { let currSubSum = 0 ; for ( let j = i ; j < N ; j ++ ) { currSubSum += arr [ j ] ; let sq = Math . floor ( Math . sqrt ( currSubSum ) ) ; if ( sq * sq == currSubSum ) { document . write ( " " + i + " " + j + " " + " " ) ; } } } } let arr = [ 65 , 79 , 81 ] ; PrintIndexes ( arr , arr . length ) ;
inputs: "Minimum removals required to make frequency of each array element equal to its value | Java program to implement the above approach ; Function to find the minimum count of elements required to be removed such that frequency of arr [ i ] equal to arr [ i ] ; Stores frequency of each element of the array ; Traverse the array ; Update frequency of arr [ i ] ; Stores minimum count of removals ; Traverse the map ; Stores key value of the map ; If frequency of i is less than i ; Update cntMinRem ; If frequency of i is greater than i ; Update cntMinRem ; Driver Code"
Solution in Java:
targets: import java . util . * ; class GFG { public static int min_elements ( int arr [ ] , int N ) { Map < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { mp . put ( arr [ i ] , mp . getOrDefault ( arr [ i ] , 0 ) + 1 ) ; } int cntMinRem = 0 ; for ( int key : mp . keySet ( ) ) { int i = key ; int val = mp . get ( i ) ; if ( val < i ) { cntMinRem += val ; } else if ( val > i ) { cntMinRem += ( val - i ) ; } } return cntMinRem ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 1 , 4 , 2 } ; System . out . println ( min_elements ( arr , arr . length ) ) ; } }
inputs: "Sort an Array which contain 1 to N values in O ( N ) using Cycle Sort | C ++ program for the above approach ; Function to swap two a & b value ; Function to print array element ; Traverse the array ; Function to sort the array in O ( N ) ; Traverse the array ; If the current element is at correct position ; Else swap the current element with it 's correct position ; Driver Code ; Function call to sort the array ; Function call to print the array"
Solution in C++:
targets: #include " bits / stdc + + . h "
using namespace std ; void swap ( int * a , int * b ) { int temp = * a ; * a = * b ; * b = temp ; } void printArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << ' ▁ ' ; } } void sortArray ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; ) { if ( arr [ i ] == i + 1 ) { i ++ ; } else { swap ( & arr [ i ] , & arr [ arr [ i ] - 1 ] ) ; } } } int main ( ) { int arr [ ] = { 2 , 1 , 5 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortArray ( arr , N ) ; printArray ( arr , N ) ; return 0 ; }
inputs: "Find most significant set bit of a number | Simple PhP program to find MSB number for given n . ; Driver code"
Solution in php:
targets: < ? php function setBitNumber ( $ n ) { if ( $ n == 0 ) return 0 ; $ msb = 0 ; $ n = $ n / 2 ; while ( $ n != 0 ) { $ n = $ n / 2 ; $ msb ++ ; } return ( 1 << $ msb ) ; } $ n = 0 ; echo setBitNumber ( $ n ) ; ? >
inputs: "Partition problem | DP | Returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; calculate sum of all elements ; initialize top row as true ; initialize leftmost column , except part [ 0 ] [ 0 ] , as 0 ; fill the partition table in bottom up manner ; uncomment this part to print table ; Driver Code ; Function call"
How can the above be solved in Python?
targets: def findPartition ( arr , n ) :
	sum = 0
	i , j = 0 , 0
	for i in range ( n ) :
		sum += arr [ i ]
	if sum % 2 != 0 :
		return false
	part = [ [ True for i in range ( n + 1 ) ] for j in range ( sum // 2 + 1 ) ]
	for i in range ( 0 , n + 1 ) :
		part [ 0 ] [ i ] = True
	for i in range ( 1 , sum // 2 + 1 ) :
		part [ i ] [ 0 ] = False
	for i in range ( 1 , sum // 2 + 1 ) :
		for j in range ( 1 , n + 1 ) :
			part [ i ] [ j ] = part [ i ] [ j - 1 ]
			if i >= arr [ j - 1 ] :
				part [ i ] [ j ] = ( part [ i ] [ j ] or part [ i - arr [ j - 1 ] ] [ j - 1 ] )
	return part [ sum // 2 ] [ n ]
arr = [ 3 , 1 , 1 , 2 , 2 , 1 ]
n = len ( arr )
if findPartition ( arr , n ) == True :
	print ( " Can ▁ be ▁ divided ▁ into ▁ two " , " subsets ▁ of ▁ equal ▁ sum " )
else :
	print ( " Can ▁ not ▁ be ▁ divided ▁ into ▁ " , " two ▁ subsets ▁ of ▁ equal ▁ sum " )
inputs: "Count number of substrings of a string consisting of same characters | Function to return the number of substrings of same characters ; Size of the string ; Initialize count to 1 ; Initialize left to 0 and right to 1 to traverse the string ; Checking if consecutive characters are same and increment the count ; When we encounter a different characters ; Increment the result ; To repeat the whole process set left equals right and count variable to 1 ; Store the final value of result ; Driver code"
Solution in Javascript:
targets: function findNumbers ( s ) { var n = s . length ; var count = 1 ; var result = 0 ; var left = 0 ; var right = 1 ; while ( right < n ) { if ( s [ left ] == s [ right ] ) { count ++ ; } else { result += parseInt ( count * ( count + 1 ) / 2 ) ; left = right ; count = 1 ; } right ++ ; } result += parseInt ( count * ( count + 1 ) / 2 ) ; document . write ( result ) ; } var s = " " ; findNumbers ( s ) ;
inputs: "Count numbers from range whose prime factors are only 2 and 3 | Function to count the number within a range whose prime factors are only 2 and 3 ; Start with 2 so that 1 doesn 't get counted ; While num is divisible by 2 , divide it by 2 ; While num is divisible by 3 , divide it by 3 ; If num got reduced to 1 then it has only 2 and 3 as prime factors ; Driver code"
How can the above be solved in PHP?
targets: < ? php function findTwoThreePrime ( $ l , $ r ) { if ( $ l == 1 ) $ l ++ ; $ count = 0 ; for ( $ i = $ l ; $ i <= $ r ; $ i ++ ) { $ num = $ i ; while ( $ num % 2 == 0 ) $ num /= 2 ; while ( $ num % 3 == 0 ) $ num /= 3 ; if ( $ num == 1 ) $ count ++ ; } return $ count ; } $ l = 1 ; $ r = 10 ; echo findTwoThreePrime ( $ l , $ r ) ; ? >
inputs: "Find the smallest missing number | function that returns smallest elements missing in a sorted array . ; Left half has all elements from 0 to mid ; Driver Code"
Solution in Javascript:
targets: function findFirstMissing ( array , start , end ) { if ( start > end ) return end + 1 ; if ( start != array [ start ] ) return start ; let mid = parseInt ( ( start + end ) / 2 , 10 ) ; if ( array [ mid ] == mid ) return findFirstMissing ( array , mid + 1 , end ) ; return findFirstMissing ( array , start , mid ) ; } let arr = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 10 ] ; let n = arr . length ; document . write ( " " + findFirstMissing ( arr , 0 , n - 1 ) ) ;
inputs: "Count ways to reach the nth stair using step 1 , 2 or 3 | A recursive function used by countWays ; declaring three variables and holding the ways for first three stairs ; d = 0 fourth variable ; starting from 4 as already counted for 3 stairs ; Driver program to test above functions"
Solution in Python:
targets: def countWays ( n ) :
	a = 1
	b = 2
	c = 4
	if ( n == 0 or n == 1 or n == 2 ) :
		return n
	if ( n == 3 ) :
		return c
	for i in range ( 4 , n + 1 ) :
		d = c + b + a
		a = b
		b = c
		c = d
	return d
n = 4
print ( countWays ( n ) )
inputs: "Smallest number exceeding N whose Kth bit is set | Function to find the number greater than n whose Kth bit is set ; Iterate from N + 1 ; Check if Kth bit is set or not ; Increment M for next number ; Return the minimum value ; Driver Code ; Given N and K ; Function Call"
Solution in Python:
targets: def find_next ( n , k ) :
	M = n + 1 ;
	while ( True ) :
		if ( ( M & ( 1 << k ) ) > 0 ) :
			break ;
		M += 1 ;
	return M ;
if __name__ == ' _ _ main _ _ ' :
	N = 15 ; K = 2 ;
	print ( find_next ( N , K ) ) ;
inputs: 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
How can the above be solved in C?
targets: #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 ; }