Muennighoff/xP3x-sample huggingface dataset:
inputs: "Check if the given string is shuffled substring of another string | This function returns true if contents of arr1 [ ] and arr2 [ ] are same , otherwise false . ; This function search for all permutations of pat [ ] in txt [ ] ; countP [ ] : Store count of all characters of pattern countTW [ ] : Store count of current window of text ; Traverse through remaining characters of pattern ; Compare counts of current window of text with counts of pattern [ ] ; Add current character to current window ; Remove the first character of previous window ; Check for the last window in text ; Driver code"
How can the above be solved in JS?
targets: function compare ( arr1 , arr2 ) { for ( let i = 0 ; i < 256 ; i ++ ) if ( arr1 [ i ] != arr2 [ i ] ) return false ; return true ; } function search ( pat , txt ) { let M = pat . length ; let N = txt . length ; let countP = new Array ( 256 ) ; let countTW = new Array ( 256 ) ; for ( let i = 0 ; i < 256 ; i ++ ) { countP [ i ] = 0 ; countTW [ i ] = 0 ; } for ( let i = 0 ; i < 256 ; i ++ ) { countP [ i ] = 0 ; countTW [ i ] = 0 ; } for ( let i = 0 ; i < M ; i ++ ) { ( countP [ pat [ i ] . charCodeAt ( 0 ) ] ) ++ ; ( countTW [ txt [ i ] . charCodeAt ( 0 ) ] ) ++ ; } for ( let i = M ; i < N ; i ++ ) { if ( compare ( countP , countTW ) ) return true ; ( countTW [ txt [ i ] . charCodeAt ( 0 ) ] ) ++ ; countTW [ txt [ i - M ] . charCodeAt ( 0 ) ] -- ; } if ( compare ( countP , countTW ) ) return true ; return false ; } let txt = " " ; let pat = " " ; if ( search ( pat , txt ) ) document . write ( " " ) ; else document . write ( " " ) ;
inputs: Activity Selection Problem | Greedy Algo | C program for activity selection problem . The following implementation assumes that the activities are already sorted according to their finish time ; Prints a maximum set of activities that can be done by a single person , one at a time . n -- > Total number of activities s [ ] -- > An array that contains start time of all activities f [ ] -- > An array that contains finish time of all activities ; The first activity always gets selected ; Consider rest of the activities ; If this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; driver program to test above function
How can the above be solved in C?
targets: #include <stdio.h>
void printMaxActivities ( int s [ ] , int f [ ] , int n ) { int i , j ; printf ( " Following ▁ activities ▁ are ▁ selected ▁ n " ) ; i = 0 ; printf ( " % d ▁ " , i ) ; for ( j = 1 ; j < n ; j ++ ) { if ( s [ j ] >= f [ i ] ) { printf ( " % d ▁ " , j ) ; i = j ; } } } int main ( ) { int s [ ] = { 1 , 3 , 0 , 5 , 8 , 5 } ; int f [ ] = { 2 , 4 , 6 , 7 , 9 , 9 } ; int n = sizeof ( s ) / sizeof ( s [ 0 ] ) ; printMaxActivities ( s , f , n ) ; return 0 ; }
inputs: "Length of the longest substring with every character appearing even number of times | Function to find length of the longest substring with each element occurring even number of times ; Initialize unordered_map ; Stores the length of the longest required substring ; Traverse the string ; Stores the value of the digit present at current index ; Bitwise XOR of the mask with 1 left - shifted by val ; Check if the value of mask is already present in ind or not ; Update the final answer ; Otherwise ; Return the answer ; Given string ; Length of the given string ; Function Call"
Solution in Javascript:
targets: function lenOfLongestReqSubstr ( s , N ) { var ind = new Map ( ) ; var mask = 0 ; ind [ 0 ] = - 1 ; var ans = 0 ; for ( var i = 0 ; i < N ; i ++ ) { var val = s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; mask ^= ( 1 << val ) ; if ( ind . has ( mask ) ) { ans = Math . max ( ans , i - ind . get ( mask ) ) ; } else ind . set ( mask , i ) ; } return ans ; } var s = " " ; var N = s . length ; document . write ( lenOfLongestReqSubstr ( s , N ) ) ;
inputs: "Coin Change | DP | Dynamic Programming PHP implementation of Coin Change problem ; table [ i ] will be storing the number of solutions for value i . We need n + 1 rows as the table is constructed in bottom up manner using the base case ( n = 0 ) ; Base case ( If given value is 0 ) ; Pick all coins one by one and update the table [ ] values after the index greater than or equal to the value of the picked coin ; Driver Code"
Solution in php:
targets: < ? php function count_1 ( & $ S , $ m , $ n ) { $ table = array_fill ( 0 , $ n + 1 , NULl ) ; $ table [ 0 ] = 1 ; for ( $ i = 0 ; $ i < $ m ; $ i ++ ) for ( $ j = $ S [ $ i ] ; $ j <= $ n ; $ j ++ ) $ table [ $ j ] += $ table [ $ j - $ S [ $ i ] ] ; return $ table [ $ n ] ; } $ arr = array ( 1 , 2 , 3 ) ; $ m = sizeof ( $ arr ) ; $ n = 4 ; $ x = count_1 ( $ arr , $ m , $ n ) ; echo $ x ; ? >
inputs: "Find two numbers from their sum and XOR | Set 2 | C ++ program for the above approach ; Function to find the value of A and B whose sum is X and xor is Y ; Initialize the two numbers ; Case 1 : X < Y ; Case 2 : X - Y is odd ; Case 3 : If both Sum and XOR are equal ; Case 4 : If above cases fails ; Update the value of A ; Check if A & Y value is 0 ; If true , update B ; Otherwise assign - 1 to A , - 1 to B ; Print the numbers A and B ; Driver Code ; Given Sum and XOR of 2 numbers ; Function Call"
How can the above be solved in C++?
targets: #include <bits/stdc++.h>
using namespace std ; void findNums ( int X , int Y ) { int A , B ; if ( X < Y ) { A = -1 ; B = -1 ; } else if ( abs ( X - Y ) & 1 ) { A = -1 ; B = -1 ; } else if ( X == Y ) { A = 0 ; B = Y ; } else { A = ( X - Y ) / 2 ; if ( ( A & Y ) == 0 ) { B = ( A + Y ) ; } else { A = -1 ; B = -1 ; } } cout << A << " ▁ " << B ; } int main ( ) { int X = 17 , Y = 13 ; findNums ( X , Y ) ; return 0 ; }
inputs: "Minimize the sum of the array according the given condition | C # implementation of the above approach ; Function to return the minimum sum ; sort the array to find the minimum element ; finding the number to divide ; Checking to what instance the sum has decreased ; getting the max difference ; Driver Code"
How can the above be solved in C-Sharp?
targets: using System ; class GFG { static void findMin ( int [ ] arr , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; Array . Sort ( arr ) ; int min = arr [ 0 ] ; int max = 0 ; for ( int i = n - 1 ; i >= 1 ; i -- ) { int num = arr [ i ] ; int total = num + min ; int j ; for ( j = 2 ; j <= num ; j ++ ) { if ( num % j == 0 ) { int d = j ; int now = ( num / d ) + ( min * d ) ; int reduce = total - now ; if ( reduce > max ) max = reduce ; } } } Console . WriteLine ( sum - max ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 } ; int n = arr . Length ; findMin ( arr , n ) ; } }
inputs: "Program to print Arithmetic Progression series | PHP Program to print an arithmetic progression series ; Printing AP by simply adding d to previous term . ; starting number ; Common difference ; N th term to be find"
Solution in php:
targets: < ? php function printAP ( $ a , $ d , $ n ) { $ curr_term ; $ curr_term = a ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) { echo ( $ curr_term . " " ) ; $ curr_term += $ d ; } } $ a = 2 ; $ d = 1 ; $ n = 5 ; printAP ( $ a , $ d , $ n ) ; ? >
inputs: "Subtract two numbers without using arithmetic operators | C # Program to subtract two Number without using arithmetic operator Recursive implementation . ; Driver program"
Solution in C#:
targets: using System ; class GFG { static int subtract ( int x , int y ) { if ( y == 0 ) return x ; return subtract ( x ^ y , ( ~ x & y ) << 1 ) ; } public static void Main ( ) { int x = 29 , y = 13 ; Console . WriteLine ( " x ▁ - ▁ y ▁ is ▁ " + subtract ( x , y ) ) ; } }
inputs: Smallest power of 2 greater than or equal to n |  ; Finds next power of two for n . If n itself is a power of two then returns n ; Driver Code
How can the above be solved in C?
targets: #include <stdio.h>
unsigned int nextPowerOf2 ( unsigned int n ) { n -- ; n |= n >> 1 ; n |= n >> 2 ; n |= n >> 4 ; n |= n >> 8 ; n |= n >> 16 ; n ++ ; return n ; } int main ( ) { unsigned int n = 5 ; printf ( " % d " , nextPowerOf2 ( n ) ) ; return 0 ; }
inputs: "Number of substrings with each character occurring even times | C # program for the above approach ; Function to count substrings having even frequency of each character ; Stores the total count of substrings ; Traverse the range [ 0 , N ] : ; Traverse the range [ i + 1 , N ] ; Stores the substring over the range of indices [ i , len ] ; Stores the frequency of characters ; Count frequency of each character ; Traverse the dictionary ; If any of the keys have odd count ; Otherwise ; Return count ; Driver Code"
Solution in C#:
targets: using System ; using System . Collections . Generic ; public class GFG { static int subString ( string s , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int len = i + 1 ; len <= n ; len ++ ) { string test_str = s . Substring ( i , len - i ) ; Dictionary < char , int > res = new Dictionary < char , int > ( ) ; foreach ( char keys in test_str . ToCharArray ( ) ) { if ( ! res . ContainsKey ( keys ) ) res . Add ( keys , 0 ) ; res [ keys ] ++ ; } int flag = 0 ; foreach ( KeyValuePair < char , int > keys in res ) { if ( keys . Value % 2 != 0 ) { flag = 1 ; break ; } } if ( flag == 0 ) count += 1 ; } } return count ; } static public void Main ( ) { string S = " abbaa " ; int N = S . Length ; Console . WriteLine ( subString ( S , N ) ) ; } }
inputs: "Count subarrays having a single distinct element that can be obtained from a given array | Java program for the above approach ; Function to count subarrays of single distinct element into which given array can be split ; Stores the count ; Stores frequency of array elements ; Traverse the array ; Traverse the map ; Increase count of subarrays by ( frequency - 1 ) ; Driver Code"
Solution in Java:
targets: import java . io . * ; import java . util . * ; class GFG { static void divisionalArrays ( int arr [ ] , int N ) { int sum = N ; HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } for ( Map . Entry x : mp . entrySet ( ) ) { if ( ( int ) x . getValue ( ) > 1 ) { sum += ( int ) x . getValue ( ) - 1 ; } } System . out . println ( sum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 3 } ; int N = arr . length ; divisionalArrays ( arr , N ) ; } }
inputs: "Sorted order printing of a given array that represents a BST | C Code for Sorted order printing of a given array that represents a BST ; print left subtree ; print root ; print right subtree ; driver program to test above function"
Solution in C:
targets: #include <stdio.h>
void printSorted ( int arr [ ] , int start , int end ) { if ( start > end ) return ; printSorted ( arr , start * 2 + 1 , end ) ; printf ( " % d ▁ " , arr [ start ] ) ; printSorted ( arr , start * 2 + 2 , end ) ; } int main ( ) { int arr [ ] = { 4 , 2 , 5 , 1 , 3 } ; int arr_size = sizeof ( arr ) / sizeof ( int ) ; printSorted ( arr , 0 , arr_size - 1 ) ; getchar ( ) ; return 0 ; }
inputs: "Hexacontatetragon numbers | Function to find the nth Hexacontatetragon number ; Driver code"
How can the above be solved in JS?
targets: function HexacontatetragonNum ( n ) { return ( 62 * n * n - 60 * n ) / 2 ; } let n = 3 ; document . write ( HexacontatetragonNum ( n ) ) ;
inputs: "Print prime numbers from 1 to N in reverse order | Javascript program to print all primes between 1 to N in reverse order using Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Print all prime numbers in reverse order ; static input ; to display"
Solution in Javascript:
targets: function Reverseorder ( n ) { let prime = new Array ( n + 1 ) ; for ( let i = 0 ; i < n ; i ++ ) prime [ i ] = true ; for ( let p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( let i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } for ( let p = n ; p >= 2 ; p -- ) if ( prime [ p ] ) document . write ( p + " " ) ; } let N = 25 ; document . write ( " " + " " ) ; if ( N == 1 ) document . write ( " " ) ; else
inputs: "Ways to Remove Edges from a Complete Graph to make Odd Edges | C # implementation of the approach ; Function to return the number of ways to remove edges from the graph so that odd number of edges are left in the graph ; Total number of edges ; Driver code"
How can the above be solved in C-Sharp?
targets: using System ; public class GFG { static int countWays ( int N ) { int E = ( N * ( N - 1 ) ) / 2 ; if ( N == 1 ) return 0 ; return ( int ) Math . Pow ( 2 , E - 1 ) ; } static public void Main ( ) { int N = 4 ; Console . WriteLine ( countWays ( N ) ) ; } }
inputs: "Multiply two integers without using multiplication , division and bitwise operators , and no loops |  ; function to multiply two numbers x and y ; 0 multiplied with anything gives 0 ; Add x one by one ; the case where y is negative ; Driver Code"
Solution in C:
targets: #include <stdio.h>
int multiply ( int x , int y ) { if ( y == 0 ) return 0 ; if ( y > 0 ) return ( x + multiply ( x , y - 1 ) ) ; if ( y < 0 ) return - multiply ( x , - y ) ; } int main ( ) { printf ( " % d " , multiply ( 5 , -11 ) ) ; getchar ( ) ; return 0 ; }
inputs: "Reduce a given number to form a key by the given operations | C # program of the above approach ; Function to find the key of the given number ; Convert the integer to String ; Iterate the num - string to get the result ; Check if digit is even or odd ; Iterate until odd sum is obtained by adding consecutive digits ; Check if sum becomes odd ; Add the result in ans ; Assign the digit index to num string ; If the number is odd ; Iterate until odd sum is obtained by adding consecutive digits ; Check if sum becomes even ; Add the result in ans ; assign the digit index to main numstring ; Check if all digits are visited or not ; Driver Code"
Solution in C#:
targets: using System ; class GFG { static int key ( int N ) { String num = " " + N ; int ans = 0 ; int j = 0 ; for ( j = 0 ; j < num . Length ; j ++ ) { if ( ( num [ j ] - 48 ) % 2 == 0 ) { int add = 0 ; int i ; for ( i = j ; j < num . Length ; j ++ ) { add += num [ j ] - 48 ; if ( add % 2 == 1 ) break ; } if ( add == 0 ) { ans *= 10 ; } else { int digit = ( int ) Math . Floor ( Math . Log10 ( add ) + 1 ) ; ans *= ( int ) ( Math . Pow ( 10 , digit ) ) ; ans += add ; } i = j ; } else { int add = 0 ; int i ; for ( i = j ; j < num . Length ; j ++ ) { add += num [ j ] - 48 ; if ( add % 2 == 0 ) { break ; } } if ( add == 0 ) { ans *= 10 ; } else { int digit = ( int ) Math . Floor ( Math . Log10 ( add ) + 1 ) ; ans *= ( int ) ( Math . Pow ( 10 , digit ) ) ; ans += add ; } i = j ; } } if ( j + 1 >= num . Length ) { return ans ; } else { return ans += num [ num . Length - 1 ] - 48 ; } } public static void Main ( String [ ] args ) { int N = 1667848271 ; Console . Write ( key ( N ) ) ; } }
inputs: "Min steps to convert N | C # program for the above problem ; Adjacency list for numbers till 100001 ; Visited array ; To store distance of every vertex from A ; Function to check if number is a prime ; Function to check if numbers differ by only a single - digit ; Check the last digit of both numbers and increase count if different ; Generate all N digit primes ; For every prime number i check if an edge can be made . ; For every prime number i check if an edge can be made from i to j . ; If edge is possible then insert in the adjacency list ; Function to count distance ; If unvisited push onto queue and mark visited as 1 and add the distance of curr + 1. ; Driver code ; Call bfs traversal with root as node A ; Indicates not possible"
Solution in C#:
targets: using System ; using System . Collections . Generic ; class GFG { static List < List < int > > lis = new List < List < int > > ( ) ; static List < int > primes = new List < int > ( ) ; static int [ ] vis = new int [ 100001 ] ; static int [ ] dis = new int [ 100001 ] ; static bool isPrime ( int n ) { int i = 2 ; while ( i * i <= n ) { if ( n % i == 0 ) return false ; i += 1 ; } return true ; } static bool valid ( int a , int b ) { int c = 0 ; while ( a > 0 ) { if ( ( a % 10 ) != ( b % 10 ) ) c += 1 ; a = a / 10 ; b = b / 10 ; } if ( c == 1 ) return true ; else return false ; } static void makePrimes ( int N ) { int L = ( int ) Math . Pow ( 10 , N - 1 ) ; int R = ( int ) Math . Pow ( 10 , N ) - 1 ; for ( int i = L ; i < R + 1 ; i ++ ) { if ( isPrime ( i ) ) primes . Add ( i ) ; } for ( int i = 0 ; i < primes . Count ; i ++ ) { for ( int j = i + 1 ; j < primes . Count ; j ++ ) { int a = primes [ i ] ; int b = primes [ j ] ; if ( valid ( a , b ) ) { lis [ a ] . Add ( b ) ; lis [ b ] . Add ( a ) ; } } } } static void bfs ( int src ) { List < int > q = new List < int > ( ) ; q . Add ( src ) ; vis [ src ] = 1 ; dis [ src ] = 0 ; while ( q . Count != 0 ) { int curr = q [ 0 ] ; q . RemoveAt ( 0 ) ; foreach ( int x in lis [ curr ] ) { if ( vis [ x ] == 0 ) { vis [ x ] = 1 ; q . Add ( x ) ; dis [ x ] = dis [ curr ] + 1 ; } } } } static void Main ( ) { for ( int i = 0 ; i < 100001 ; i ++ ) { lis . Add ( new List < int > ( ) ) ; } int N = 4 ; makePrimes ( N ) ; int A = 1033 ; int B = 8179 ; bfs ( A ) ; if ( dis [ B ] == - 1 ) { Console . Write ( - 1 ) ; } else { Console . Write ( dis [ B ] ) ; } } }
inputs: "Check whether the given string is a valid identifier | Function that returns true if str1 is a valid identifier ; If first character is invalid ; Traverse the for the rest of the characters ; is a valid identifier ; Driver code"
Solution in Python:
targets: def isValid ( str1 , n ) :
	if ( ( ( ord ( str1 [ 0 ] ) >= ord ( ' a ' ) and ord ( str1 [ 0 ] ) <= ord ( ' z ' ) ) or ( ord ( str1 [ 0 ] ) >= ord ( ' A ' ) and ord ( str1 [ 0 ] ) <= ord ( ' Z ' ) ) or ord ( str1 [ 0 ] ) == ord ( ' _ ' ) ) == False ) :
		return False
	for i in range ( 1 , len ( str1 ) ) :
		if ( ( ( ord ( str1 [ i ] ) >= ord ( ' a ' ) and ord ( str1 [ i ] ) <= ord ( ' z ' ) ) or ( ord ( str1 [ i ] ) >= ord ( ' A ' ) and ord ( str1 [ i ] ) <= ord ( ' Z ' ) ) or ( ord ( str1 [ i ] ) >= ord ( '0' ) and ord ( str1 [ i ] ) <= ord ( '9' ) ) or ord ( str1 [ i ] ) == ord ( ' _ ' ) ) == False ) :
			return False
	return True
str1 = " _ geeks123"
n = len ( str1 )
if ( isValid ( str1 , n ) ) :
	print ( " Valid " )
else :
	print ( " Invalid " )
inputs: "Maximum Sum possible by selecting X elements from a Matrix based on given conditions | C # program to implement the above approach ; Function to calculate the maximum possible sum by selecting X elements from the Matrix ; Generate prefix sum of the matrix ; Initialize [ , ] dp ; Maximum possible sum by selecting 0 elements from the first i rows ; If a single row is present ; If elements from the current row is not selected ; Iterate over all possible selections from current row ; Return maximum possible sum ; Driver Code"
Solution in C#:
targets: using System ; class GFG { static int n , m , X ; public static int maxSum ( int [ , ] grid ) { int [ , ] prefsum = new int [ n , m ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int x = 0 ; x < m ; x ++ ) { if ( x == 0 ) prefsum [ i , x ] = grid [ i , x ] ; else prefsum [ i , x ] = prefsum [ i , x - 1 ] + grid [ i , x ] ; } } int [ , ] dp = new int [ n , X + 1 ] ; for ( int i = 1 ; i < n ; i ++ ) for ( int j = 1 ; j <= X ; ++ j ) dp [ i , j ] = int . MinValue ; for ( int i = 0 ; i < n ; i ++ ) dp [ i , 0 ] = 0 ; for ( int i = 1 ; i <= Math . Min ( m , X ) ; ++ i ) { dp [ 0 , i ] = dp [ 0 , i - 1 ] + grid [ 0 , i - 1 ] ; } for ( int i = 1 ; i < n ; ++ i ) { for ( int j = 1 ; j <= X ; ++ j ) { dp [ i , j ] = dp [ i - 1 , j ] ; for ( int x = 1 ; x <= Math . Min ( j , m ) ; x ++ ) { dp [ i , j ] = Math . Max ( dp [ i , j ] , dp [ i - 1 , j - x ] + prefsum [ i , x - 1 ] ) ; } } } return dp [ n - 1 , X ] ; } public static void Main ( String [ ] args ) { n = 4 ; m = 4 ; X = 6 ; int [ , ] grid = { { 3 , 2 , 6 , 1 } , { 1 , 9 , 2 , 4 } , { 4 , 1 , 3 , 9 } , { 3 , 8 , 2 , 1 } } ; int ans = maxSum ( grid ) ; Console . WriteLine ( ans ) ; } }
inputs: "Position of rightmost set bit | Python 3 implementation of above approach ; counting the position of first set bit ; Driver code"
Solution in Python:
targets: INT_SIZE = 32
def Right_most_setbit ( num ) :
	pos = 1
	for i in range ( INT_SIZE ) :
		if not ( num & ( 1 << i ) ) :
			pos += 1
		else :
			break
	return pos
if __name__ == " _ _ main _ _ " :
	num = 18
	pos = Right_most_setbit ( num )
	print ( pos )
inputs: "Counting Sort | C Program for counting sort ; The main function that sort the given string arr [ ] in alphabatical order ; The output character array that will have sorted arr ; Create a count array to store count of inidividul characters and initialize count array as 0 ; Store count of each character ; Change count [ i ] so that count [ i ] now contains actual position of this character in output array ; Build the output character array ; Copy the output array to arr , so that arr now contains sorted characters ; Driver program to test above function"
Solution in C:
targets: #include <stdio.h>
#include <string.h>
#define RANGE  255
void countSort ( char arr [ ] ) { char output [ strlen ( arr ) ] ; int count [ RANGE + 1 ] , i ; memset ( count , 0 , sizeof ( count ) ) ; for ( i = 0 ; arr [ i ] ; ++ i ) ++ count [ arr [ i ] ] ; for ( i = 1 ; i <= RANGE ; ++ i ) count [ i ] += count [ i - 1 ] ; for ( i = 0 ; arr [ i ] ; ++ i ) { output [ count [ arr [ i ] ] - 1 ] = arr [ i ] ; -- count [ arr [ i ] ] ; } for ( i = 0 ; arr [ i ] ; ++ i ) arr [ i ] = output [ i ] ; } int main ( ) { char arr [ ] = " geeksforgeeks " ; countSort ( arr ) ; printf ( " Sorted ▁ character ▁ array ▁ is ▁ % sn " , arr ) ; return 0 ; }
inputs: "Number of subsets with a given OR value | Java implementation of the approach ; To store states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code"
Solution in Java:
targets: import java . util . * ; class GFG { static int maxN = 20 ; static int maxM = 64 ; static int [ ] [ ] dp = new int [ maxN ] [ maxM ] ; static boolean [ ] [ ] v = new boolean [ maxN ] [ maxM ] ; static int findCnt ( int [ ] arr , int i , int curr , int n , int m ) { if ( i == n ) { return ( curr == m ? 1 : 0 ) ; } if ( v [ i ] [ curr ] ) return dp [ i ] [ curr ] ; v [ i ] [ curr ] = true ; dp [ i ] [ curr ] = findCnt ( arr , i + 1 , curr , n , m ) + findCnt ( arr , i + 1 , ( curr arr [ i ] ) , n , m ) ; return dp [ i ] [ curr ] ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 2 } ; int n = arr . length ; int m = 3 ; System . out . println ( findCnt ( arr , 0 , 0 , n , m ) ) ; } }
inputs: "Minimum number of bracket reversals needed to make an expression balanced | Set | Returns count of minimum reversals for making expr balanced . Returns - 1 if expr cannot be balanced . ; length of expression must be even to make it balanced by using reversals . ; To store number of reversals required . ; To store number of unbalanced opening brackets . ; To store number of unbalanced closing brackets . ; If current bracket is open then increment open count . ; If current bracket is close , check if it balances opening bracket . If yes then decrement count of unbalanced opening bracket else increment count of closing bracket . ; For the case : " " or when one closing and one opening bracket remains for pairing , then both need to be reversed . ; Driver Code"
How can the above be solved in Python?
targets: def countMinReversals ( expr ) :
	length = len ( expr )
	if length % 2 :
		return - 1
	ans = 0
	open = 0
	close = 0
	for i in range ( 0 , length ) :
		if expr [ i ] == " " :
			open += 1
		else :
			if not open :
				close += 1
			else :
				open -= 1
	ans = ( close // 2 ) + ( open // 2 )
	close %= 2
	open %= 2
	if close > 0 :
		ans += 2
	return ans
if __name__ == " _ _ main _ _ " :
	expr = " } } { { "
	print ( countMinReversals ( expr ) )
inputs: "Maximum width of an N | C # program to implement the above approach ; Function to find the maximum width of the tree using level order traversal ; Store the edges of the tree ; Stores maximum width of the tree ; Stores the nodes of each level ; Insert root node ; Perform level order traversal on the tree ; Stores the size of the queue ; Update maximum width ; Push the nodes of the next level and pop the elements of the current level ; Get element from the front the Queue ; Push all nodes of the next level . ; Return the result . ; Driver Code ; Constructed tree is : 1 / | \ 2 - 1 3 / \ \ 4 5 8 / / | \ 2 6 12 7"
How can the above be solved in C-Sharp?
targets: using System ; using System . Collections . Generic ; class GFG { static int maxWidth ( int N , int M , List < int > cost , List < List < int > > s ) { List < List < int > > adj = new List < List < int > > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { adj . Add ( new List < int > ( ) ) ; } for ( int i = 0 ; i < M ; i ++ ) { adj [ s [ i ] [ 0 ] ] . Add ( s [ i ] [ 1 ] ) ; } int result = 0 ; Queue < int > q = new Queue < int > ( ) ; q . Enqueue ( 0 ) ; while ( q . Count != 0 ) { int count = q . Count ; result = Math . Max ( count , result ) ; while ( count -- > 0 ) { int temp = q . Dequeue ( ) ; for ( int i = 0 ; i < adj [ temp ] . Count ; i ++ ) { q . Enqueue ( adj [ temp ] [ i ] ) ; } } } return result ; } static public void Main ( ) { int N = 11 , M = 10 ; List < List < int > > edges = new List < List < int > > ( ) ; edges . Add ( new List < int > ( ) { 0 , 1 } ) ; edges . Add ( new List < int > ( ) { 0 , 2 } ) ; edges . Add ( new List < int > ( ) { 0 , 3 } ) ; edges . Add ( new List < int > ( ) { 1 , 4 } ) ; edges . Add ( new List < int > ( ) { 1 , 5 } ) ; edges . Add ( new List < int > ( ) { 3 , 6 } ) ; edges . Add ( new List < int > ( ) { 4 , 7 } ) ; edges . Add ( new List < int > ( ) { 6 , 10 } ) ; edges . Add ( new List < int > ( ) { 6 , 8 } ) ; edges . Add ( new List < int > ( ) { 6 , 9 } ) ; List < int > cost = new List < int > ( ) { 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 2 , 6 , 12 , 7 } ; Console . WriteLine ( maxWidth ( N , M , cost , edges ) ) ; } }
inputs: "Print modified array after executing the commands of addition and subtraction | Update function for every command ; If q == 0 , add ' k ' and ' - k ' to ' l - 1' and ' r ' index ; If q == 1 , add ' - k ' and ' k ' to ' l - 1' and ' r ' index ; Function to generate the final array after executing all commands ; Generate final array with the help of DP concept ; Driver code ; Generate final array ; Printing the final modified array"
How can the above be solved in JS?
targets: function updateQuery ( arr , n , q , l , r , k ) { if ( q == 0 ) { arr [ l - 1 ] += k ; arr [ r ] += - k ; } else { arr [ l - 1 ] += - k ; arr [ r ] += k ; } return ; } function generateArray ( arr , n ) { for ( i = 1 ; i < n ; ++ i ) arr [ i ] += arr [ i - 1 ] ; } var n = 5 ; var arr = Array ( n + 1 ) . fill ( 0 ) ; var q = 0 , l = 1 , r = 3 , k = 2 ; updateQuery ( arr , n , q , l , r , k ) ; q = 1 ; l = 3 ; r = 5 ; k = 3 ; updateQuery ( arr , n , q , l , r , k ) ; q = 0 ; l = 2 ; r = 5 ; k = 1 ; updateQuery ( arr , n , q , l , r , k ) ; generateArray ( arr , n ) ; for ( i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ;
inputs: "Find the Kth position element of the given sequence | Java implementation of the approach ; Function to return the kth number from the required sequence ; Count of odd integers in the sequence ; kth number is even ; It is odd ; Driver code"
How can the above be solved in Java?
targets: class GFG { static int kthNum ( int n , int k ) { int a = ( n + 1 ) / 2 ; if ( k > a ) return ( 2 * ( k - a ) ) ; return ( 2 * k - 1 ) ; } public static void main ( String [ ] args ) { int n = 7 , k = 7 ; System . out . println ( kthNum ( n , k ) ) ; } }
inputs: "Minimum cost of purchasing at least X chocolates | Function to calculate minimum cost of buying least X chocolates ; Base Case ; Include the i - th box ; Exclude the i - th box ; Return the minimum of the above two cases ; Driver Code ; Given array and value of X ; Store the size of the array ; Print answer"
How can the above be solved in Python?
targets: def findMinCost ( arr , X , n , i = 0 ) :
	if ( X <= 0 ) :
		return 0
	if ( i >= n ) :
		return 10 ** 8
	inc = findMinCost ( arr , X - arr [ i ] [ 0 ] , n , i + 1 )
	if ( inc != 10 ** 8 ) :
		inc += arr [ i ] [ 1 ]
	exc = findMinCost ( arr , X , n , i + 1 )
	return min ( inc , exc )
if __name__ == ' _ _ main _ _ ' :
	arr = [ [ 4 , 3 ] , [ 3 , 2 ] , [ 2 , 4 ] , [ 1 , 3 ] , [ 4 , 2 ] ]
	X = 7
	n = len ( arr )
	ans = findMinCost ( arr , X , n )
	if ( ans != 10 ** 8 ) :
		print ( ans )
	else :
		print ( - 1 )
inputs: "Majority Element | Set |  ; function to print the majority Number ; Driver code"
Solution in C++:
targets: #include <bits/stdc++.h>
using namespace std ; #define ll  long long int
int majorityNumber ( int arr [ ] , int n ) { int ans = -1 ; unordered_map < int , int > freq ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; if ( freq [ arr [ i ] ] > n / 2 ) ans = arr [ i ] ; } return ans ; } int main ( ) { int a [ ] = { 2 , 2 , 1 , 1 , 1 , 2 , 2 } ; int n = sizeof ( a ) / sizeof ( int ) ; cout << majorityNumber ( a , n ) ; return 0 ; }
inputs: "Maximum in an array that can make another array sorted | C # program to make array sorted ; Function to check whether there is any swappable element present to make the first array sorted ; wrongIdx is the index of the element which is making the first array unsorted ; Find the maximum element which satisfies the above mentioned neighboring conditions ; if res is true then swap the element and make the first array sorted ; Function to print the sorted array if elements are swapped . ; Driver Code"
How can the above be solved in C-Sharp?
targets: using System ; class GFG { static bool swapElement ( int [ ] arr1 , int [ ] arr2 , int n ) { int wrongIdx = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr1 [ i ] < arr1 [ i - 1 ] ) { wrongIdx = i ; } } int maximum = int . MinValue ; int maxIdx = - 1 ; bool res = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr2 [ i ] > maximum && arr2 [ i ] >= arr1 [ wrongIdx - 1 ] ) { if ( wrongIdx + 1 <= n - 1 && arr2 [ i ] <= arr1 [ wrongIdx + 1 ] ) { maximum = arr2 [ i ] ; maxIdx = i ; res = true ; } } } if ( res ) { swap ( arr1 , wrongIdx , arr2 , maxIdx ) ; } return res ; } static void swap ( int [ ] a , int wrongIdx , int [ ] b , int maxIdx ) { int c = a [ wrongIdx ] ; a [ wrongIdx ] = b [ maxIdx ] ; b [ maxIdx ] = c ; } static void getSortedArray ( int [ ] arr1 , int [ ] arr2 , int n ) { if ( swapElement ( arr1 , arr2 , n ) ) { for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( arr1 [ i ] + " ▁ " ) ; } } else { Console . Write ( " Not ▁ Possible " ) ; } } public static void Main ( ) { int [ ] arr1 = { 1 , 3 , 7 , 4 , 10 } ; int [ ] arr2 = { 2 , 1 , 6 , 8 , 9 } ; int n = arr1 . Length ; getSortedArray ( arr1 , arr2 , n ) ; } }
inputs: "Minimum gcd operations to make all array elements one | __gcd function ; Function to count number of moves . ; Counting Number of ones . ; If there is a one ; Find smallest subarray with GCD equals to one . ; to calculate GCD ; Not Possible ; Final answer ; Driver code"
Solution in php:
targets: < ? php function __gcd ( $ a , $ b ) { if ( $ a == 0 ) return $ b ; return __gcd ( $ b % $ a , $ a ) ; } function minimumMoves ( $ A , $ N ) { $ one = 0 ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) if ( $ A [ $ i ] == 1 ) $ one ++ ; if ( $ one != 0 ) return $ N - $ one ; $ minimum = PHP_INT_MAX ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) { $ g = $ A [ $ i ] ; for ( $ j = $ i + 1 ; $ j < $ N ; $ j ++ ) { $ g = __gcd ( $ A [ $ j ] , $ g ) ; if ( $ g == 1 ) { $ minimum = min ( $ minimum , $ j - $ i ) ; break ; } } } if ( $ minimum == PHP_INT_MAX ) return -1 ; else return $ N + $ minimum - 1 ; } $ A = array ( 2 , 4 , 3 , 9 ) ; $ N = sizeof ( $ A ) ; echo ( minimumMoves ( $ A , $ N ) ) ; ? >
inputs: "Program to print binomial expansion series | function to print the series ; Calculating and printing first term ; Computing and printing remaining terms ; Find current term using previous terms We increment power of X by 1 , decrement power of A by 1 and compute nCi using previous term by multiplying previous term with ( n - i + 1 ) / i ; Driver Code"
How can the above be solved in PHP?
targets: < ? php function series ( $ A , $ X , $ n ) { $ term = pow ( $ A , $ n ) ; echo $ term , " " ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) { $ term = $ term * $ X * ( $ n - $ i + 1 ) / ( $ i * $ A ) ; echo $ term , " " ; } } $ A = 3 ; $ X = 4 ; $ n = 5 ; series ( $ A , $ X , $ n ) ; ? >
inputs: "Smallest N digit number divisible by all possible prime digits | C # implementation of the above approach ; Function to find the minimum number of n digits divisible by all prime digits ; Driver code"
Solution in C#:
targets: using System ; class GFG { static void minNum ( int n ) { if ( n < 3 ) Console . WriteLine ( - 1 ) ; else Console . WriteLine ( 210 * ( ( int ) ( Math . Pow ( 10 , n - 1 ) / 210 ) + 1 ) ) ; } public static void Main ( String [ ] args ) { int n = 5 ; minNum ( n ) ; } }
inputs: "Find all divisors of a natural number | Set 2 | A O ( sqrt ( n ) ) java program that prints all divisors in sorted order ; Method to print the divisors ; List to store half of the divisors ; Check if divisors are equal ; Otherwise print both ; The list will be printed in reverse ; Driver method"
How can the above be solved in Python?
targets: import math
def printDivisors ( n ) :
	list = [ ]
	for i in range ( 1 , int ( math . sqrt ( n ) + 1 ) ) :
		if ( n % i == 0 ) :
			if ( n / i == i ) :
				print ( i , end = " ▁ " )
			else :
				print ( i , end = " ▁ " )
				list . append ( int ( n / i ) )
	for i in list [ : : - 1 ] :
		print ( i , end = " ▁ " )
print ( " The ▁ divisors ▁ of ▁ 100 ▁ are : ▁ " )
printDivisors ( 100 )
inputs: "Minimum increment and decrement by K of each pair elements required to make all array elements equal | C # program for the above approach ; Function to check if its possible to make all array elements equal or not ; Stores the sum of the array ; Traverse the array ; If sum is divisible by N ; Otherwise , not possible to make all array elements equal ; Driver Code ; Given array ; Size of the array"
Solution in C#:
targets: using System ; using System . Collections . Generic ; public class GFG { static void arrayElementEqual ( int [ ] arr , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; } if ( sum % N == 0 ) { Console . WriteLine ( " Yes " ) ; } else { Console . Write ( " No " + " 
 " ) ; } } static public void Main ( ) { int [ ] arr = { 1 , 5 , 6 , 4 } ; int N = arr . Length ; arrayElementEqual ( arr , N ) ; } }
inputs: "Count numbers from a given range that are not divisible by any of the array elements | Java program for the above approach ; Function to find the non - multiples till k ; Stores all unique multiples ; Iterate the array ; For finding duplicates only once ; Inserting all multiples into the set ; Returning only the count of numbers that are not divisible by any of the array elements ; Function to count the total values in the range [ L , R ] ; Count all values in the range using exclusion principle ; Driver code ; Function Call"
How can the above be solved in Java?
targets: import java . io . * ; import java . util . * ; class GFG { public static int findNonMultiples ( int [ ] arr , int n , int k ) { Set < Integer > multiples = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( ! multiples . contains ( arr [ i ] ) ) { for ( int j = 1 ; j <= k / arr [ i ] ; j ++ ) { multiples . add ( arr [ i ] * j ) ; } } } return k - multiples . size ( ) ; } public static int countValues ( int [ ] arr , int N , int L , int R ) { return findNonMultiples ( arr , N , R ) - findNonMultiples ( arr , N , L - 1 ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 4 , 5 , 6 } ; int N = arr . length ; int L = 1 ; int R = 20 ; System . out . println ( countValues ( arr , N , L , R ) ) ; } }
inputs: "Check whether triangle is valid or not if sides are given | function to check if three sider form a triangle or not ; check condition ; Driver Code ; function calling and print output"
Solution in php:
targets: < ? php function checkValidity ( $ a , $ b , $ c ) { if ( $ a + $ b <= $ c $ a + $ c <= $ b $ b + $ c <= $ a ) return false ; else return true ; } $ a = 7 ; $ b = 10 ; $ c = 5 ; if ( checkValidity ( $ a , $ b , $ c ) ) echo " Valid " ; else echo " Invalid " ; ? >
inputs: "Reduce N to 1 with minimum number of given operations | Java implementation of the approach ; Function to return the minimum number of given operations required to reduce n to 1 ; To store the count of operations ; To store the digit ; If n is already then no operation is required ; Extract all the digits except the first digit ; Store the maximum of that digits ; for each digit ; First digit ; Add the value to count ; Driver code"
How can the above be solved in Java?
targets: class GFG { static long minOperations ( long n ) { long count = 0 ; long d = 0 ; if ( n == 1 ) return 0 ; while ( n > 9 ) { d = Math . max ( n % 10 , d ) ; n /= 10 ; count += 10 ; } d = Math . max ( d , n - 1 ) ; count += Math . abs ( d ) ; return count - 1 ; } public static void main ( String [ ] args ) { long n = 240 ; System . out . println ( minOperations ( n ) ) ; } }
inputs: "Permute two arrays such that sum of every pair is greater or equal to K | Check whether any permutation exists which satisfy the condition . ; Sort the array a [ ] in decreasing order . ; Sort the array b [ ] in increasing order . ; Checking condition on each index . ; Driven Program"
How can the above be solved in PHP?
targets: < ? php function isPossible ( $ a , $ b , $ n , $ k ) { sort ( $ a ) ; rsort ( $ b ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( $ a [ $ i ] + $ b [ $ i ] < $ k ) return false ; return true ; } $ a = array ( 2 , 1 , 3 ) ; $ b = array ( 7 , 8 , 9 ) ; $ k = 10 ; $ n = count ( $ a ) ; if ( isPossible ( $ a , $ b , $ n , $ k ) ) echo " Yes " ; else echo " No " ; ? >
inputs: "Naive algorithm for Pattern Searching | PHP program for Naive Pattern Searching algorithm ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver Code"
How can the above be solved in PHP?
targets: < ? php function search ( $ pat , $ txt ) { $ M = strlen ( $ pat ) ; $ N = strlen ( $ txt ) ; for ( $ i = 0 ; $ i <= $ N - $ M ; $ i ++ ) { for ( $ j = 0 ; $ j < $ M ; $ j ++ ) if ( $ txt [ $ i + $ j ] != $ pat [ $ j ] ) break ; if ( $ j == $ M ) echo " Pattern ▁ found ▁ at ▁ index ▁ " , $ i . " 
 " ; } } $ txt = " AABAACAADAABAAABAA " ; $ pat = " AABA " ; search ( $ pat , $ txt ) ; ? >
inputs: "Minimum steps to reduce N to 0 by given operations | C ++ program for the above approach ; Function to find the minimum number to steps to reduce N to 0 ; Dictionary for storing the precomputed sum ; Bases Cases ; Check if n is not in dp then only call the function so as to reduce no of recursive calls ; Return the answer ; Driver Code ; Given number N ; Function call"
How can the above be solved in C++?
targets: #include <bits/stdc++.h>
using namespace std ; int count ( int n ) { map < int , int > dp ; dp [ 0 ] = 0 ; dp [ 1 ] = 1 ; if ( ( dp . find ( n ) == dp . end ( ) ) ) dp [ n ] = 1 + min ( n % 2 + count ( n / 2 ) , n % 3 + count ( n / 3 ) ) ; return dp [ n ] ; } int main ( ) { int N = 6 ; cout << count ( N ) ; }
inputs: "Level order traversal with direction change after every two levels | A Binary Tree Node ; Function to prthe level order of given binary tree . Direction of printing level order traversal of binary tree changes after every two levels ; For null root ; Maintain a queue for normal level order traversal ; Maintain a stack for printing nodes in reverse order after they are popped out from queue . ; sz is used for storing the count of nodes in a level ; Used for changing the direction of level order traversal ; Used for changing the direction of level order traversal ; Push root node to the queue ; Run this while loop till queue got empty ; Do a normal level order traversal ; For printing nodes from left to right , simply prthe nodes in the order in which they are being popped out from the queue . ; For printing nodes from right to left , push the nodes to stack instead of printing them . ; for printing the nodes in order from right to left ; Change the direction of printing nodes after every two levels . ; Driver program to test above functions ; Let us create binary tree"
How can the above be solved in Python?
targets: from collections import deque
class Node :
	def __init__ ( self , x ) :
		self . data = x
		self . left = None
		self . right = None
def modifiedLevelOrder ( node ) :
	if ( node == None ) :
		return
	if ( node . left == None and node . right == None ) :
		print ( node . data , end = " ▁ " )
		return
	myQueue = deque ( )
	myStack = [ ]
	temp = None
	sz = 0
	ct = 0
	rightToLeft = False
	myQueue . append ( node )
	while ( len ( myQueue ) > 0 ) :
		ct += 1
		sz = len ( myQueue )
		for i in range ( sz ) :
			temp = myQueue . popleft ( )
			if ( rightToLeft == False ) :
				print ( temp . data , end = " ▁ " )
			else :
				myStack . append ( temp )
			if ( temp . left ) :
				myQueue . append ( temp . left )
			if ( temp . right ) :
				myQueue . append ( temp . right )
		if ( rightToLeft == True ) :
			while ( len ( myStack ) > 0 ) :
				temp = myStack [ - 1 ]
				del myStack [ - 1 ]
				print ( temp . data , end = " ▁ " )
		if ( ct == 2 ) :
			rightToLeft = not rightToLeft
			ct = 0
		print ( )
if __name__ == ' _ _ main _ _ ' :
	root = Node ( 1 )
	root . left = Node ( 2 )
	root . right = Node ( 3 )
	root . left . left = Node ( 4 )
	root . left . right = Node ( 5 )
	root . right . left = Node ( 6 )
	root . right . right = Node ( 7 )
	root . left . left . left = Node ( 8 )
	root . left . left . right = Node ( 9 )
	root . left . right . left = Node ( 3 )
	root . left . right . right = Node ( 1 )
	root . right . left . left = Node ( 4 )
	root . right . left . right = Node ( 2 )
	root . right . right . left = Node ( 7 )
	root . right . right . right = Node ( 2 )
	root . left . right . left . left = Node ( 16 )
	root . left . right . left . right = Node ( 17 )
	root . right . left . right . left = Node ( 18 )
	root . right . right . left . right = Node ( 19 )
	modifiedLevelOrder ( root )
inputs: Find the smallest missing number | C program to find the smallest elements missing in a sorted array . ; function that returns smallest elements missing in a sorted array . ; Left half has all elements from 0 to mid ; driver program to test above function
How can the above be solved in C?
targets: #include <stdio.h>
int findFirstMissing ( int array [ ] , int start , int end ) { if ( start > end ) return end + 1 ; if ( start != array [ start ] ) return start ; int mid = ( start + end ) / 2 ; if ( array [ mid ] == mid ) return findFirstMissing ( array , mid + 1 , end ) ; return findFirstMissing ( array , start , mid ) ; } int main ( ) { int arr [ ] = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Smallest ▁ missing ▁ element ▁ is ▁ % d " , findFirstMissing ( arr , 0 , n - 1 ) ) ; return 0 ; }
inputs: "Count of valid arrays of size P with elements in range [ 1 , N ] having duplicates at least M distance apart | Java program for the above approach ; Function to calculate the total number of arrays ; If the size of the array is P ; Check if all elements are used atlease once ; Check if this state is already calculated ; Initialize the result ; Use a number from the list of unused numbers ; There are ' unused ' number of favourable choices ; Use a number from already present number atlease M distance back ; There are ' used ▁ - ▁ M ' number of favourable choices ; Store the result ; Function to solve the problem ; Initialize DP table : dp [ i ] [ j ] [ j ] i : current position / index j : number of used elements k : number of unused elements ; Driver Code"
Solution in Java:
targets: import java . io . * ; class GFG { static int calculate ( int position , int used , int unused , int P , int M , int dp [ ] [ ] [ ] ) { if ( position == P ) { return unused == 0 ? 1 : 0 ; } if ( dp [ position ] [ used ] [ unused ] != - 1 ) return dp [ position ] [ used ] [ unused ] ; int result = 0 ; if ( unused > 0 ) { result += calculate ( position + 1 , used + 1 , unused - 1 , P , M , dp ) * unused ; } if ( used > M ) { result += calculate ( position + 1 , used , unused , P , M , dp ) * ( used - M ) ; } return dp [ position ] [ used ] [ unused ] = result ; } static int solve ( int N , int P , int M ) { int [ ] [ ] [ ] dp = new int [ 101 ] [ 101 ] [ 101 ] ; for ( int i = 0 ; i < 101 ; i ++ ) { for ( int j = 0 ; j < 101 ; j ++ ) for ( int k = 0 ; k < 101 ; k ++ ) dp [ i ] [ j ] [ k ] = - 1 ; } return calculate ( 0 , 0 , N , P , M , dp ) ; } public static void main ( String [ ] args ) { int N = 2 , M = 0 , P = 3 ; System . out . println ( solve ( N , P , M ) ) ; } }
inputs: "Find Nth item distributed from infinite items of infinite types based on given conditions | C ++ program for the above approach ; Function to find the type of the item given out according to the given rules ; Stores the count of item given out at each step ; Iterate over the days from 1 ; Iterate over type of item on that day ; Count of items given out should exceed n ; Driver Code"
How can the above be solved in C++?
targets: #include <bits/stdc++.h>
using namespace std ; int itemType ( int n ) { int count = 0 ; for ( int day = 1 ; ; day ++ ) { for ( int type = day ; type > 0 ; type -- ) { count += type ; if ( count >= n ) return type ; } } } int main ( ) { int N = 10 ; cout << itemType ( N ) ; return 0 ; }
inputs: "Program to find the sum of a Series 1 + 1 / 2 ^ 2 + 1 / 3 ^ 3 + â €¦ . . + 1 / n ^ n | C program to calculate the following series ; Function to calculate the following series ; Driver Code"
Solution in C:
targets: #include <math.h>
#include <stdio.h>
double Series ( int n ) { int i ; double sums = 0.0 , ser ; for ( i = 1 ; i <= n ; ++ i ) { ser = 1 / pow ( i , i ) ; sums += ser ; } return sums ; } int main ( ) { int n = 3 ; double res = Series ( n ) ; printf ( " % .5f " , res ) ; return 0 ; }
inputs: "Program to find whether a no is power of two | Function to check if x is power of 2 ; Driver Code"
How can the above be solved in JS?
targets: function isPowerOfTwo ( n ) { if ( n == 0 ) return false ; return parseInt ( ( Math . ceil ( ( Math . log ( n ) / Math . log ( 2 ) ) ) ) ) == parseInt ( ( Math . floor ( ( ( Math . log ( n ) / Math . log ( 2 ) ) ) ) ) ) ; } if ( isPowerOfTwo ( 31 ) ) document . write ( " " ) ; else document . write ( " " ) ; if ( isPowerOfTwo ( 64 ) ) document . write ( " " ) ; else document . write ( " " ) ;
inputs: "Check if a given integer is the product of K consecutive integers | Function to check if N can be expressed as the product of K consecutive integers ; Stores the K - th root of N ; Stores the product of K consecutive integers ; Traverse over the range [ 1 , K ] ; Update the product ; If product is N , then return " Yes " ; Otherwise , traverse over the range [ 2 , Kthroot ] ; Update the value of product ; If product is equal to N ; Otherwise , return " No " ; Driver Code"
Solution in Python:
targets: def checkPro ( n , k ) :
	KthRoot = int ( n ** ( 1 / k ) )
	product = 1
	for i in range ( 1 , k + 1 ) :
		product = product * i
	print ( product )
	if ( product == N ) :
		return ( " Yes " )
	for i in range ( 2 , KthRoot + 1 ) :
		product = product * ( i + k - 1 )
		product = product / ( i - 1 )
		print ( product )
		if ( product == N ) :
			return ( " Yes " )
	return ( " No " )
N = 210
K = 3
print ( checkPro ( N , K ) )