text
stringlengths 17
3.65k
| code
stringlengths 60
5.26k
|
---|---|
Split array into two subarrays such that difference of their sum is minimum | C # program for the above approach ; Function to return minimum difference between two subarray sums ; To store prefix sums ; Generate prefix sum array ; To store suffix sums ; Generate suffix sum array ; Stores the minimum difference ; Traverse the given array ; Calculate the difference ; Update minDiff ; Return minDiff ; Driver Code ; Given array ; Length of the array
|
using System ; class GFG { static int minDiffSubArray ( int [ ] arr , int n ) { int [ ] prefix_sum = new int [ n ] ; prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] ; int [ ] suffix_sum = new int [ n ] ; suffix_sum [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suffix_sum [ i ] = suffix_sum [ i + 1 ] + arr [ i ] ; int minDiff = int . MaxValue ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int diff = Math . Abs ( prefix_sum [ i ] - suffix_sum [ i + 1 ] ) ; if ( diff < minDiff ) minDiff = diff ; } return minDiff ; } public static void Main ( String [ ] args ) { int [ ] arr = { 7 , 9 , 5 , 10 } ; int n = arr . Length ; Console . WriteLine ( minDiffSubArray ( arr , n ) ) ; } }
|
Count of days remaining for the next day with higher temperature | C # program for the above approach ; Function to determine how many days required to wait for the next warmer temperature ; To store the answer ; Traverse all the temperatures ; Check if current index is the next warmer temperature of any previous indexes ; Pop the element ; Push the current index ; Print waiting days ; Driver Code ; Given temperatures ; Function call
|
using System ; using System . Collections . Generic ; class GFG { static void dailyTemperatures ( int [ ] T ) { int n = T . Length ; int [ ] daysOfWait = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) daysOfWait [ i ] = - 1 ; Stack < int > s = new Stack < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { while ( s . Count != 0 && T [ s . Peek ( ) ] < T [ i ] ) { daysOfWait [ s . Peek ( ) ] = i - s . Peek ( ) ; s . Pop ( ) ; } s . Push ( i ) ; } for ( int i = 0 ; i < n ; i ++ ) { Console . Write ( daysOfWait [ i ] + " β " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 73 , 74 , 75 , 71 , 69 , 72 , 76 , 73 } ; dailyTemperatures ( arr ) ; } }
|
Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U | C # program for the above approach ; To store the time ; Function to perform DFS to store times , distance and parent of each node ; Update the distance of node u ; Update parent of node u ; Increment time timeT ; Discovery time of node u ; Traverse the adjacency list of current node and recursively call DFS for each vertex ; If current node Adj [ u , i ] is unvisited ; Update the finishing time ; Function to add edges between nodes u and v ; Function to find the node U such that path from root to U contains nodes in V [ ] ; Initialise vis , dis , parent , preTime , and postTime ; Store Adjacency List ; Create adjacency List ; Perform DFS Traversal ; Stores the distance of deepest vertex ' u ' ; Update the deepest node by traversing the qu [ ] ; Find deepest vertex ; Replace each vertex with it 's corresponding parent except the root vertex ; Checks if the ancestor with respect to deepest vertex u ; Update ans ; Print the result ; Driver Code ; Total vertices ; Given set of vertices ; Given edges ; Function call
|
using System ; using System . Collections . Generic ; class GFG { static int timeT = 0 ; static void dfs ( int u , int p , int dis , int [ ] vis , int [ ] distance , int [ ] parent , int [ ] preTime , int [ ] postTime , List < List < int > > Adj ) { distance [ u ] = dis ; parent [ u ] = p ; vis [ u ] = 1 ; timeT ++ ; preTime [ u ] = timeT ; for ( int i = 0 ; i < Adj [ u ] . Count ; i ++ ) { if ( vis [ Adj [ u ] [ i ] ] == 0 ) { dfs ( Adj [ u ] [ i ] , u , dis + 1 , vis , distance , parent , preTime , postTime , Adj ) ; } } timeT ++ ; postTime [ u ] = timeT ; } static void addEdge ( List < List < int > > Adj , int u , int v ) { Adj [ u ] . Add ( v ) ; Adj [ v ] . Add ( u ) ; } static void findNodeU ( int N , int V , int [ ] Vertices , int [ , ] Edges ) { int [ ] vis = new int [ N + 1 ] ; int [ ] distance = new int [ N + 1 ] ; int [ ] parent = new int [ N + 1 ] ; int [ ] preTime = new int [ N + 1 ] ; int [ ] postTime = new int [ N + 1 ] ; List < List < int > > Adj = new List < List < int > > ( ) ; for ( int i = 0 ; i < N + 1 ; i ++ ) Adj . Add ( new List < int > ( ) ) ; int u = 0 , v ; for ( int i = 0 ; i < N - 1 ; i ++ ) { addEdge ( Adj , Edges [ i , 0 ] , Edges [ i , 1 ] ) ; } dfs ( 1 , 0 , 0 , vis , distance , parent , preTime , postTime , Adj ) ; int maximumDistance = 0 ; maximumDistance = 0 ; for ( int k = 0 ; k < V ; k ++ ) { if ( maximumDistance < distance [ Vertices [ k ] ] ) { maximumDistance = distance [ Vertices [ k ] ] ; u = Vertices [ k ] ; } if ( parent [ Vertices [ k ] ] != 0 ) { Vertices [ k ] = parent [ Vertices [ k ] ] ; } } bool ans = true ; bool flag ; for ( int k = 0 ; k < V ; k ++ ) { if ( preTime [ Vertices [ k ] ] <= preTime [ u ] && postTime [ Vertices [ k ] ] >= postTime [ u ] ) flag = true ; else flag = false ; ans = ans & flag ; } if ( ans ) Console . WriteLine ( u ) ; else Console . WriteLine ( " NO " ) ; } public static void Main ( String [ ] args ) { int N = 10 ; int V = 5 ; int [ ] Vertices = { 4 , 3 , 8 , 9 , 10 } ; int [ , ] Edges = { { 1 , 2 } , { 1 , 3 } , { 1 , 4 } , { 2 , 5 } , { 2 , 6 } , { 3 , 7 } , { 7 , 8 } , { 7 , 9 } , { 9 , 10 } } ; findNodeU ( N , V , Vertices , Edges ) ; } }
|
Check if an array contains only one distinct element | C # program for the above approach ; Function to find if the array contains only one distinct element ; Create a set ; Traversing the array ; Compare and print the result ; Driver Code ; Function call
|
using System ; using System . Collections . Generic ; class GFG { public static void uniqueElement ( int [ ] arr ) { HashSet < int > set = new HashSet < int > ( ) ; for ( int i = 0 ; i < arr . Length ; i ++ ) { set . Add ( arr [ i ] ) ; } if ( set . Count == 1 ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 9 , 9 , 9 , 9 , 9 , 9 , 9 } ; uniqueElement ( arr ) ; } }
|
Maximum cost of splitting given Binary Tree into two halves | C # program for the above approach ; To store the results and sum of all nodes in the array ; To create adjacency list ; Function to add edges into the adjacency list ; Recursive function that calculate the value of the cost of splitting the tree recursively ; Fetch the child of node - r ; Neglect if cur node is parent ; Add all values of nodes which are decendents of r ; The two trees formed are rooted at ' r ' with its decendents ; Check and replace if current product t1 * t2 is large ; Function to find the maximum cost after splitting the tree in 2 halves ; Find sum of values in all nodes ; Traverse edges to create adjacency list ; Function Call ; Driver Code ; Values in each node ; Given Edges
|
using System ; using System . Collections . Generic ; class GFG { static int ans = 0 , allsum = 0 ; static List < int > [ ] edges = new List < int > [ 100001 ] ; static void addedge ( int a , int b ) { edges [ a ] . Add ( b ) ; edges [ b ] . Add ( a ) ; } static void findCost ( int r , int p , int [ ] arr ) { int i , cur ; for ( i = 0 ; i < edges [ r ] . Count ; i ++ ) { cur = edges [ r ] [ i ] ; if ( cur == p ) continue ; findCost ( cur , r , arr ) ; arr [ r ] += arr [ cur ] ; } int t1 = arr [ r ] ; int t2 = allsum - t1 ; if ( t1 * t2 > ans ) { ans = t1 * t2 ; } } static void maximumCost ( int r , int p , int N , int M , int [ ] arr , int [ , ] Edges ) { for ( int i = 0 ; i < N ; i ++ ) { allsum += arr [ i ] ; } for ( int i = 0 ; i < M ; i ++ ) { addedge ( Edges [ i , 0 ] , Edges [ i , 1 ] ) ; } findCost ( r , p , arr ) ; } public static void Main ( String [ ] args ) { int N = 6 ; int [ ] arr = { 13 , 8 , 7 , 4 , 5 , 9 } ; int M = 5 ; int [ , ] Edges = { { 0 , 1 } , { 1 , 2 } , { 1 , 4 } , { 3 , 4 } , { 4 , 5 } } ; for ( int i = 0 ; i < edges . Length ; i ++ ) edges [ i ] = new List < int > ( ) ; maximumCost ( 1 , - 1 , N , M , arr , Edges ) ; Console . Write ( ans ) ; } }
|
Diameters for each node of Tree after connecting it with given disconnected component | C # Program to implement the above approach ; Keeps track of the farthest end of the diameter ; Keeps track of the length of the diameter ; Stores the nodes which are at ends of the diameter ; Perform DFS on the given tree ; Update diameter and X ; If current node is an end of diameter ; Traverse its neighbors ; Function to call DFS for the required purposes ; DFS from a random node and find the node farthest from it ; DFS from X to calculate diameter ; DFS from farthest_node to find the farthest node ( s ) from it ; DFS from X ( other end of diameter ) and check the farthest node ( s ) from it ; If node i is the end of a diameter ; Increase diameter by 1 ; Otherwise ; Remains unchanged ; Driver Code ; constructed tree is 1 / \ 2 3 7 / | \ / | \ 4 5 6 ; creating undirected edges
|
using System ; using System . Collections . Generic ; class GFG { static int X = 1 ; static int diameter = 0 ; static Dictionary < int , Boolean > mp = new Dictionary < int , Boolean > ( ) ; static void dfs ( int current_node , int prev_node , int len , bool add_to_map , List < int > [ ] adj ) { if ( len > diameter ) { diameter = len ; X = current_node ; } if ( add_to_map && len == diameter ) { mp . Add ( current_node , true ) ; } foreach ( int it in adj [ current_node ] ) { if ( it != prev_node ) dfs ( it , current_node , len + 1 , add_to_map , adj ) ; } } static void dfsUtility ( List < int > [ ] adj ) { dfs ( 1 , - 1 , 0 , false , adj ) ; int farthest_node = X ; dfs ( farthest_node , - 1 , 0 , false , adj ) ; dfs ( farthest_node , - 1 , 0 , true , adj ) ; dfs ( X , - 1 , 0 , true , adj ) ; } static void printDiameters ( List < int > [ ] adj ) { dfsUtility ( adj ) ; for ( int i = 1 ; i <= 6 ; i ++ ) { if ( mp . ContainsKey ( i ) && mp [ i ] == true ) Console . Write ( diameter + 1 + " , β " ) ; else Console . Write ( diameter + " , β " ) ; } } public static void Main ( String [ ] args ) { List < int > [ ] adj = new List < int > [ 7 ] ; for ( int i = 0 ; i < adj . Length ; i ++ ) adj [ i ] = new List < int > ( ) ; adj [ 1 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 1 ) ; adj [ 1 ] . Add ( 3 ) ; adj [ 3 ] . Add ( 1 ) ; adj [ 2 ] . Add ( 4 ) ; adj [ 4 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 5 ) ; adj [ 5 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 6 ) ; adj [ 6 ] . Add ( 2 ) ; printDiameters ( adj ) ; } }
|
Count of replacements required to make the sum of all Pairs of given type from the Array equal | C # program implement the above approach ; Function to find the minimum replacements required ; Stores the maximum and minimum values for every pair of the form arr [ i ] , arr [ n - i - 1 ] ; Map for storing frequencies of every sum formed by pairs ; Minimum element in the pair ; Maximum element in the pair ; Incrementing the frequency of sum encountered ; Insert minimum and maximum values ; Sorting the vectors ; Iterate over all possible values of x ; Count of pairs for which x > x + k ; Count of pairs for which x < mn + 1 ; Count of pairs requiring 2 replacements ; Count of pairs requiring no replacements ; Count of pairs requiring 1 replacement ; Update the answer ; Return the answer ; Driver Code
|
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static int minimumReplacement ( int [ ] arr , int N , int K ) { int ans = int . MaxValue ; ArrayList max_values = new ArrayList ( ) ; ArrayList min_values = new ArrayList ( ) ; Dictionary < int , int > sum_equal_to_x = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N / 2 ; i ++ ) { int mn = Math . Min ( arr [ i ] , arr [ N - i - 1 ] ) ; int mx = Math . Max ( arr [ i ] , arr [ N - i - 1 ] ) ; sum_equal_to_x [ arr [ i ] + arr [ N - i - 1 ] ] = sum_equal_to_x . GetValueOrDefault ( arr [ i ] + arr [ N - i - 1 ] , 0 ) + 1 ; min_values . Add ( mn ) ; max_values . Add ( mx ) ; } max_values . Sort ( ) ; min_values . Sort ( ) ; for ( int x = 2 ; x <= 2 * K ; x ++ ) { int mp1 = max_values . IndexOf ( x - K ) ; int mp2 = min_values . IndexOf ( x ) ; int rep2 = mp1 + ( N / 2 - mp2 ) ; int rep0 = sum_equal_to_x . GetValueOrDefault ( x , - 1 ) ; int rep1 = ( N / 2 - rep2 - rep0 ) ; ans = Math . Min ( ans , rep2 * 2 + rep1 ) ; } return ans ; } public static void Main ( string [ ] args ) { int N = 4 ; int K = 3 ; int [ ] arr = { 1 , 2 , 2 , 1 } ; Console . Write ( minimumReplacement ( arr , N , K ) ) ; } }
|
Print the Forests of a Binary Tree after removal of given Nodes | C # program to implement the above approach ; Stores the nodes to be deleted ; Structure of a Tree node ; Function to create a new node ; Function to check whether the node needs to be deleted or not ; Function to perform tree pruning by performing post order traversal ; If the node needs to be deleted ; Store the its subtree ; Perform Inorder Traversal ; Function to print the forests ; Stores the remaining nodes ; Print the inorder traversal of Forests ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static Dictionary < int , Boolean > mp = new Dictionary < int , Boolean > ( ) ; class Node { public int key ; public Node left , right ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . left = temp . right = null ; return ( temp ) ; } static bool deleteNode ( int nodeVal ) { return mp . ContainsKey ( nodeVal ) ; } static Node treePruning ( Node root , List < Node > result ) { if ( root == null ) return null ; root . left = treePruning ( root . left , result ) ; root . right = treePruning ( root . right , result ) ; if ( deleteNode ( root . key ) ) { if ( root . left != null ) { result . Add ( root . left ) ; } if ( root . right != null ) { result . Add ( root . right ) ; } return null ; } return root ; } static void printInorderTree ( Node root ) { if ( root == null ) return ; printInorderTree ( root . left ) ; Console . Write ( root . key + " β " ) ; printInorderTree ( root . right ) ; } static void printForests ( Node root , int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) { mp . Add ( arr [ i ] , true ) ; } List < Node > result = new List < Node > ( ) ; if ( treePruning ( root , result ) != null ) result . Add ( root ) ; for ( int i = 0 ; i < result . Count ; i ++ ) { printInorderTree ( result [ i ] ) ; Console . WriteLine ( ) ; } } public static void Main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 12 ) ; root . right = newNode ( 13 ) ; root . right . left = newNode ( 14 ) ; root . right . right = newNode ( 15 ) ; root . right . left . left = newNode ( 21 ) ; root . right . left . right = newNode ( 22 ) ; root . right . right . left = newNode ( 23 ) ; root . right . right . right = newNode ( 24 ) ; int [ ] arr = { 14 , 23 , 1 } ; int n = arr . Length ; printForests ( root , arr , n ) ; } }
|
Count of Ways to obtain given Sum from the given Array elements | C # Program to implement the above approach ; Function to call dfs to calculate the number of ways ; If target + sum is odd or S exceeds sum ; No sultion exists ; Return the answer ; Driver Code
|
using System ; class GFG { static int knapSack ( int [ ] nums , int S ) { int sum = 0 ; foreach ( int i in nums ) sum += i ; if ( sum < S || - sum > - S || ( S + sum ) % 2 == 1 ) return 0 ; int [ ] dp = new int [ ( S + sum ) / 2 + 1 ] ; dp [ 0 ] = 1 ; foreach ( int num in nums ) { for ( int i = dp . Length - 1 ; i >= num ; i -- ) { dp [ i ] += dp [ i - num ] ; } } return dp [ dp . Length - 1 ] ; } public static void Main ( String [ ] args ) { int S = 3 ; int [ ] arr = new int [ ] { 1 , 2 , 3 , 4 , 5 } ; int answer = knapSack ( arr , S ) ; Console . WriteLine ( answer ) ; } }
|
Maximum distance between two elements whose absolute difference is K | C # program for the above approach ; Function that find maximum distance between two elements whose absolute difference is K ; To store the first index ; Traverse elements and find maximum distance between 2 elements whose absolute difference is K ; If this is first occurrence of element then insert its index in map ; If next element present in map then update max distance ; If previous element present in map then update max distance ; Return the answer ; Driver Code ; Given array [ ] arr ; Given difference K ; Function call
|
using System ; using System . Collections . Generic ; class GFG { static int maxDistance ( int [ ] arr , int K ) { Dictionary < int , int > map = new Dictionary < int , int > ( ) ; int maxDist = 0 ; for ( int i = 0 ; i < arr . Length ; i ++ ) { if ( ! map . ContainsKey ( arr [ i ] ) ) map . Add ( arr [ i ] , i ) ; if ( map . ContainsKey ( arr [ i ] + K ) ) { maxDist = Math . Max ( maxDist , i - map [ arr [ i ] + K ] ) ; } if ( map . ContainsKey ( arr [ i ] - K ) ) { maxDist = Math . Max ( maxDist , i - map [ arr [ i ] - K ] ) ; } } if ( maxDist == 0 ) return - 1 ; else return maxDist ; } public static void Main ( String [ ] args ) { int [ ] arr = { 11 , 2 , 3 , 8 , 5 , 2 } ; int K = 2 ; Console . WriteLine ( maxDistance ( arr , K ) ) ; } }
|
Count of Substrings with at least K pairwise Distinct Characters having same Frequency | C # program for the above approach ; Function to find the subString with K pairwise distinct characters and with same frequency ; Stores the occurrence of each character in the subString ; Length of the String ; Iterate over the String ; Set all values at each index to zero ; Stores the count of unique characters ; Moving the subString ending at j ; Calculate the index of character in frequency array ; Increment the frequency ; Update the maximum index ; Check for both the conditions ; Return the answer ; Driver Code ; Function call
|
using System ; class GFG { static int no_of_subString ( String s , int N ) { int [ ] fre = new int [ 26 ] ; int str_len ; str_len = ( int ) s . Length ; int count = 0 ; for ( int i = 0 ; i < str_len ; i ++ ) { fre = new int [ 26 ] ; int max_index = 0 ; int dist = 0 ; for ( int j = i ; j < str_len ; j ++ ) { int x = s [ j ] - ' a ' ; if ( fre [ x ] == 0 ) dist ++ ; fre [ x ] ++ ; max_index = Math . Max ( max_index , fre [ x ] ) ; if ( dist >= N && ( ( max_index * dist ) == ( j - i + 1 ) ) ) count ++ ; } } return count ; } public static void Main ( String [ ] args ) { String s = " abhay " ; int N = 3 ; Console . Write ( no_of_subString ( s , N ) ) ; } }
|
Count of Ordered Pairs ( X , Y ) satisfying the Equation 1 / X + 1 / Y = 1 / N | C # program for the above approach ; Function to find number of ordered positive integer pairs ( x , y ) such that they satisfy the equation ; Initialize answer variable ; Iterate over all possible values of y ; For valid x and y , ( n * n ) % ( y - n ) has to be 0 ; Increment count of ordered pairs ; Print the answer ; Driver Code ; Function call
|
using System ; class GFG { static void solve ( int n ) { int ans = 0 ; for ( int y = n + 1 ; y <= n * n + n ; y ++ ) { if ( ( n * n ) % ( y - n ) == 0 ) { ans += 1 ; } } Console . Write ( ans ) ; } public static void Main ( String [ ] args ) { int n = 5 ; solve ( n ) ; } }
|
Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K | C # program to implement the above approach ; Initialize the adjacency list and visited array ; Function to find the number of root to leaf paths that contain atmost m consecutive nodes with value k ; Mark the current node as visited ; If value at current node is k ; Increment counter ; If count is greater than m return from that path ; Path is allowed if size of present node becomes 0 i . e it has no child root and no more than m consecutive 1 's ; Driver Code ; Desigining the tree ; Counter counts no . of consecutive nodes
|
using System ; using System . Collections . Generic ; class GFG { static List < int > [ ] adj = new List < int > [ 100005 ] ; static int [ ] visited = new int [ 100005 ] ; static int ans = 0 ; static void dfs ( int node , int count , int m , int [ ] arr , int k ) { visited [ node ] = 1 ; if ( arr [ node - 1 ] == k ) { count ++ ; } else { count = 0 ; } if ( count > m ) { return ; } if ( adj [ node ] . Count == 1 && node != 1 ) { ans ++ ; } foreach ( int x in adj [ node ] ) { if ( visited [ x ] == 0 ) { dfs ( x , count , m , arr , k ) ; } } } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 3 , 2 , 1 , 2 , 1 } ; int K = 2 , M = 2 ; for ( int i = 0 ; i < adj . Length ; i ++ ) adj [ i ] = new List < int > ( ) ; adj [ 1 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 1 ) ; adj [ 1 ] . Add ( 3 ) ; adj [ 3 ] . Add ( 1 ) ; adj [ 2 ] . Add ( 4 ) ; adj [ 4 ] . Add ( 2 ) ; adj [ 2 ] . Add ( 5 ) ; adj [ 5 ] . Add ( 2 ) ; adj [ 3 ] . Add ( 6 ) ; adj [ 6 ] . Add ( 3 ) ; adj [ 3 ] . Add ( 7 ) ; adj [ 7 ] . Add ( 3 ) ; int counter = 0 ; dfs ( 1 , counter , M , arr , K ) ; Console . Write ( ans + " STRNEWLINE " ) ; } }
|
Count of N | C # program to implement the above approach ; Function to calculate and return the reverse of the number ; Function to calculate the total count of N - digit numbers satisfying the necessary conditions ; Initialize two variables ; Calculate the sum of odd and even positions ; Check for divisibility ; Return the answer ; Driver Code
|
using System ; class GFG { public static long reverse ( long num ) { long rev = 0 ; while ( num > 0 ) { int r = ( int ) ( num % 10 ) ; rev = rev * 10 + r ; num /= 10 ; } return rev ; } public static long count ( int N , int A , int B ) { long l = ( long ) Math . Pow ( 10 , N - 1 ) , r = ( long ) Math . Pow ( 10 , N ) - 1 ; if ( l == 1 ) l = 0 ; long ans = 0 ; for ( long i = l ; i <= r ; i ++ ) { int even_sum = 0 , odd_sum = 0 ; long itr = 0 , num = reverse ( i ) ; while ( num > 0 ) { if ( itr % 2 == 0 ) odd_sum += ( int ) num % 10 ; else even_sum += ( int ) num % 10 ; num /= 10 ; itr ++ ; } if ( even_sum % A == 0 && odd_sum % B == 0 ) ans ++ ; } return ans ; } public static void Main ( String [ ] args ) { int N = 2 , A = 5 , B = 3 ; Console . WriteLine ( count ( N , A , B ) ) ; } }
|
Distance Traveled by Two Trains together in the same Direction | C # program to find the distance traveled together by the two trains ; Function to find the distance traveled together ; Stores distance travelled by A ; Stpres distance travelled by B ; Stores the total distance travelled together ; Sum of distance travelled ; Condition for traveling together ; Driver Code
|
using System ; class GFG { static int calc_distance ( int [ ] A , int [ ] B , int n ) { int distance_traveled_A = 0 ; int distance_traveled_B = 0 ; int answer = 0 ; for ( int i = 0 ; i < 5 ; i ++ ) { distance_traveled_A += A [ i ] ; distance_traveled_B += B [ i ] ; if ( ( distance_traveled_A == distance_traveled_B ) && ( A [ i ] == B [ i ] ) ) { answer += A [ i ] ; } } return answer ; } public static void Main ( string [ ] s ) { int [ ] A = { 1 , 2 , 3 , 2 , 4 } ; int [ ] B = { 2 , 1 , 3 , 1 , 4 } ; int N = A . Length ; Console . Write ( calc_distance ( A , B , N ) ) ; } }
|
Sum of Nodes and respective Neighbors on the path from root to a vertex V | C # program to implement the above approach ; Creating Adjacency list ; Function to perform DFS traversal ; Initializing parent of each node to p ; Iterate over the children ; Function to add values of children to respective parent nodes ; Root node ; Function to return sum of values of each node in path from V to the root ; Path from node V to root node ; Driver Code ; Insert edges into the graph ; Values assigned to each vertex ; Constructing the tree using adjacency list ; Parent array ; store values in the parent array ; Add values of children to the parent ; Find sum of nodes lying in the path ; Add root node since its value is not included yet
|
using System ; using System . Collections . Generic ; class GFG { private static List < List < int > > constructTree ( int n , int [ , ] edges ) { List < List < int > > adjl = new List < List < int > > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { adjl . Add ( new List < int > ( ) ) ; } for ( int i = 0 ; i < edges . GetLength ( 0 ) ; i ++ ) { int u = edges [ i , 0 ] ; int v = edges [ i , 1 ] ; adjl [ u ] . Add ( v ) ; adjl [ v ] . Add ( u ) ; } return adjl ; } private static void DFS ( List < List < int > > adjl , int [ ] parent , int u , int p ) { parent [ u ] = p ; foreach ( int v in adjl [ u ] ) { if ( v != p ) { DFS ( adjl , parent , v , u ) ; } } } private static int [ ] valuesFromChildren ( int [ ] parent , int [ ] values ) { int [ ] valuesChildren = new int [ parent . Length ] ; for ( int i = 0 ; i < parent . Length ; i ++ ) { if ( parent [ i ] == - 1 ) continue ; else { int p = parent [ i ] ; valuesChildren [ p ] += values [ i ] ; } } return valuesChildren ; } private static int findSumOfValues ( int v , int [ ] parent , int [ ] valuesChildren ) { int cur_node = v ; int sum = 0 ; while ( cur_node != - 1 ) { sum += valuesChildren [ cur_node ] ; cur_node = parent [ cur_node ] ; } return sum ; } public static void Main ( string [ ] args ) { int n = 8 ; int [ , ] edges = { { 0 , 1 } , { 0 , 2 } , { 0 , 3 } , { 1 , 4 } , { 1 , 5 } , { 4 , 7 } , { 3 , 6 } } ; int v = 7 ; int [ ] values = new int [ ] { 1 , 2 , 3 , 0 , 0 , 4 , 3 , 6 } ; List < List < int > > adjl = constructTree ( n , edges ) ; int [ ] parent = new int [ n ] ; DFS ( adjl , parent , 0 , - 1 ) ; int [ ] valuesChildren = valuesFromChildren ( parent , values ) ; int sum = findSumOfValues ( v , parent , valuesChildren ) ; sum += values [ 0 ] ; Console . WriteLine ( sum ) ; } }
|
Find a pair in Array with second largest product | C # program for the above approach ; Function to find second largest product pair in arr [ 0. . n - 1 ] ; No pair exits ; Initialize max product pair ; Traverse through every possible pair and keep track of largest product ; If pair is largest ; Second largest ; If pair dose not largest but larger then second largest ; Print the pairs ; Driver Code ; Given array ; Function call
|
using System ; class GFG { static void maxProduct ( int [ ] arr , int N ) { if ( N < 3 ) { return ; } int a = arr [ 0 ] , b = arr [ 1 ] ; int c = 0 , d = 0 ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = i + 1 ; j < N - 1 ; j ++ ) { if ( arr [ i ] * arr [ j ] > a * b ) { c = a ; d = b ; a = arr [ i ] ; b = arr [ j ] ; } if ( arr [ i ] * arr [ j ] < a * b && arr [ i ] * arr [ j ] > c * d ) c = arr [ i ] ; d = arr [ j ] ; } Console . WriteLine ( c + " β " + d ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 5 , 2 , 67 , 45 , 160 , 78 } ; int N = arr . Length ; maxProduct ( arr , N ) ; } }
|
Count of substrings consisting of even number of vowels | C # program to implement the above approach ; Utility function to check if a character is a vowel ; Function to calculate and return the count of substrings with even number of vowels ; Stores the count of substrings ; If the current character is a vowel ; Increase count ; If substring contains even number of vowels ; Increase the answer ; Print the final answer ; Driver Code
|
using System ; class GFG { static bool isVowel ( char c ) { if ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) return true ; return false ; } static void countSubstrings ( String s , int n ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; for ( int j = i ; j < n ; j ++ ) { if ( isVowel ( s [ j ] ) ) { count ++ ; } if ( count % 2 == 0 ) result ++ ; } } Console . WriteLine ( result ) ; } public static void Main ( String [ ] args ) { int n = 5 ; String s = " abcde " ; countSubstrings ( s , n ) ; } }
|
Count of substrings consisting of even number of vowels | C # Program to implement the above approach ; Utility function to check if a character is a vowel ; Function to calculate and return the count of substrings with even number of vowels ; Stores the count of substrings with even and odd number of vowels respectively ; Update count of vowels modulo 2 in sum to obtain even or odd ; Increment even / odd count ; Count substrings with even number of vowels using Handshaking Lemma ; Driver Code
|
using System ; class GFG { static bool isVowel ( char c ) { if ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) return true ; return false ; } static void countSubstrings ( String s , int n ) { int [ ] temp = { 1 , 0 } ; int result = 0 , sum = 0 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { sum += ( isVowel ( s [ i ] ) ? 1 : 0 ) ; sum %= 2 ; temp [ sum ] ++ ; } result += ( ( temp [ 0 ] * ( temp [ 0 ] - 1 ) ) / 2 ) ; result += ( ( temp [ 1 ] * ( temp [ 1 ] - 1 ) ) / 2 ) ; Console . Write ( result ) ; } public static void Main ( string [ ] args ) { int n = 5 ; String s = " abcde " ; countSubstrings ( s , n ) ; } }
|
Find the Level of a Binary Tree with Width K | C # program to implement the above approach ; Structure of binary tree node ; Function to create new node ; Function returns required level of width k , if found else - 1 ; To store the node and the label and perform traversal ; Taking the last label of each level of the tree ; Check width of current level ; If the width is equal to k then return that level ; Taking the first label of each level of the tree ; If any level does not has width equal to k , return - 1 ; Driver code
|
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { class Node { public int data ; public Node left , right ; } ; class pair { public Node first ; public int second ; public pair ( Node first , int second ) { this . first = first ; this . second = second ; } } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } static int findLevel ( Node root , int k , int level ) { Queue qt = new Queue ( ) ; qt . Enqueue ( new pair ( root , 0 ) ) ; int count = 1 , b = 0 , a = 0 ; while ( qt . Count != 0 ) { pair temp = ( pair ) qt . Dequeue ( ) ; if ( count == 1 ) { b = temp . second ; } if ( temp . first . left != null ) { qt . Enqueue ( new pair ( temp . first . left , 2 * temp . second ) ) ; } if ( temp . first . right != null ) { qt . Enqueue ( new pair ( temp . first . right , 2 * temp . second + 1 ) ) ; } count -- ; if ( count == 0 ) { if ( ( b - a + 1 ) == k ) return level ; pair secondLabel = ( pair ) qt . Peek ( ) ; a = secondLabel . second ; level += 1 ; count = qt . Count ; } } return - 1 ; } public static void Main ( string [ ] args ) { Node root = newNode ( 5 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 2 ) ; root . right . right = newNode ( 8 ) ; root . left . left = newNode ( 7 ) ; root . left . left . left = newNode ( 5 ) ; root . left . right = newNode ( 3 ) ; root . left . right . right = newNode ( 4 ) ; int k = 4 ; Console . Write ( findLevel ( root , k , 1 ) ) ; } }
|
Maximize median after doing K addition operation on the Array | C # program for the above approach ; Function to check operation can be perform or not ; Number of operation to perform s . t . mid is median ; If mid is median of the array ; Function to find max median of the array ; Lowest possible median ; Highest possible median ; Checking for mid is possible for the median of array after doing at most k operation ; Return the max possible ans ; Driver code ; Given array ; Given number of operation ; Size of array ; Sort the array ; Function call
|
using System ; class GFG { static bool possible ( int [ ] arr , int N , int mid , int K ) { int add = 0 ; for ( int i = N / 2 - ( N + 1 ) % 2 ; i < N ; ++ i ) { if ( mid - arr [ i ] > 0 ) { add += ( mid - arr [ i ] ) ; if ( add > K ) return false ; } } if ( add <= K ) return true ; else return false ; } static int findMaxMedian ( int [ ] arr , int N , int K ) { int low = 1 ; int mx = 0 ; for ( int i = 0 ; i < N ; ++ i ) { mx = Math . Max ( mx , arr [ i ] ) ; } int high = K + mx ; while ( low <= high ) { int mid = ( high + low ) / 2 ; if ( possible ( arr , N , mid , K ) ) { low = mid + 1 ; } else { high = mid - 1 ; } } if ( N % 2 == 0 ) { if ( low - 1 < arr [ N / 2 ] ) { return ( arr [ N / 2 ] + low - 1 ) / 2 ; } } return low - 1 ; } public static void Main ( string [ ] args ) { int [ ] arr = { 1 , 3 , 6 } ; int K = 10 ; int N = arr . Length ; Array . Sort ( arr ) ; Console . Write ( findMaxMedian ( arr , N , K ) ) ; } }
|
Kth Smallest Element of a Matrix of given dimensions filled with product of indices | C # program to implement the above approach ; Function that returns true if the count of elements is less than mid ; To store count of elements less than mid ; Loop through each row ; Count elements less than mid in the ith row ; Function that returns the Kth smallest element in the NxM Matrix after sorting in an array ; Initialize low and high ; Perform binary search ; Find the mid ; Check if the count of elements is less than mid ; Return Kth smallest element of the matrix ; Driver code
|
using System ; class GFG { public static bool countLessThanMid ( int mid , int N , int M , int K ) { int count = 0 ; for ( int i = 1 ; i <= Math . Min ( N , mid ) ; ++ i ) { count = count + Math . Min ( mid / i , M ) ; } if ( count >= K ) return false ; else return true ; } public static int findKthElement ( int N , int M , int K ) { int low = 1 , high = N * M ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( countLessThanMid ( mid , N , M , K ) ) low = mid + 1 ; else high = mid - 1 ; } return high + 1 ; } public static void Main ( String [ ] args ) { int N = 2 , M = 3 ; int K = 5 ; Console . WriteLine ( findKthElement ( N , M , K ) ) ; } }
|
Count of substrings containing only the given character | C # program for the above approach ; Function that finds the count of substrings containing only character C in the string S ; To store total count of substrings ; To store count of consecutive C 's ; Loop through the string ; Increase the consecutive count of C 's ; Add count of sub - strings from consecutive strings ; Reset the consecutive count of C 's ; Add count of sub - strings from consecutive strings ; Print the count of sub - strings containing only C ; Driver Code
|
using System ; class GFG { static void countSubString ( String S , char C ) { int count = 0 ; int conCount = 0 ; for ( int i = 0 ; i < S . Length ; i ++ ) { char ch = S [ i ] ; if ( ch == C ) conCount ++ ; else { count += ( conCount * ( conCount + 1 ) ) / 2 ; conCount = 0 ; } } count += ( conCount * ( conCount + 1 ) ) / 2 ; Console . Write ( count ) ; } public static void Main ( String [ ] args ) { String S = " geeksforgeeks " ; char C = ' e ' ; countSubString ( S , C ) ; } }
|
Check if both halves of a string are Palindrome or not | C # program to check whether both halves of a string is Palindrome or not ; Function to check and return if both halves of a string are palindromic or not ; Length of string ; Initialize both part as true ; If first half is not palindrome ; If second half is not palindrome ; If both halves are Palindrome ; Driver code
|
using System ; class GFG { public static void checkPalindrome ( String S ) { int N = S . Length ; bool first_half = true ; bool second_half = true ; int cnt = ( N / 2 ) - 1 ; for ( int i = 0 ; i < ( N / 2 ) ; i ++ ) { if ( S [ i ] != S [ cnt ] ) { first_half = false ; break ; } if ( S [ N / 2 + i ] != S [ N / 2 + cnt ] ) { second_half = false ; break ; } cnt -- ; } if ( first_half && second_half ) { Console . Write ( " Yes " ) ; } else { Console . Write ( " No " ) ; } } public static void Main ( ) { String S = " momdad " ; checkPalindrome ( S ) ; } }
|
Kth Smallest element in a Perfect Binary Search Tree | C # program to find K - th smallest element in a perfect BST ; A BST node ; A utility function to create a new BST node ; A utility function to insert a new node with given key in BST ; If the tree is empty ; Recur down the left subtree for smaller values ; Recur down the right subtree for smaller values ; Return the ( unchanged ) node pointer ; Function to find Kth Smallest element in a perfect BST ; Find the median ( division operation is floored ) ; If the element is at the median ; calculate the number of nodes in the right and left sub - trees ( division operation is floored ) ; If median is located higher ; If median is located lower ; Driver Code ; Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 / \ / \ / \ / \ 14 25 35 45 55 65 75 85 ; Function call
|
using System ; class GFG { public class Node { public int key ; public Node left , right ; } ; static int kth_smallest ; public static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . key = item ; temp . left = temp . right = null ; return temp ; } static Node insert ( Node node , int key ) { if ( node == null ) return newNode ( key ) ; if ( key < node . key ) node . left = insert ( node . left , key ) ; else if ( key > node . key ) node . right = insert ( node . right , key ) ; return node ; } static bool KSmallestPerfectBST ( Node root , int k , int treeSize ) { if ( root == null ) return false ; int median_loc = ( treeSize / 2 ) + 1 ; if ( k == median_loc ) { kth_smallest = root . key ; return true ; } int newTreeSize = treeSize / 2 ; if ( k < median_loc ) { return KSmallestPerfectBST ( root . left , k , newTreeSize ) ; } int newK = k - median_loc ; return KSmallestPerfectBST ( root . right , newK , newTreeSize ) ; } public static void Main ( String [ ] args ) { Node root = null ; root = insert ( root , 50 ) ; insert ( root , 30 ) ; insert ( root , 20 ) ; insert ( root , 40 ) ; insert ( root , 70 ) ; insert ( root , 60 ) ; insert ( root , 80 ) ; insert ( root , 14 ) ; insert ( root , 25 ) ; insert ( root , 35 ) ; insert ( root , 45 ) ; insert ( root , 55 ) ; insert ( root , 65 ) ; insert ( root , 75 ) ; insert ( root , 85 ) ; int n = 15 , k = 5 ; if ( KSmallestPerfectBST ( root , k , n ) ) { Console . Write ( kth_smallest + " β " ) ; } } }
|
Check if given Binary string follows then given condition or not | C # program for the above approach ; Function to check if the String follows rules or not ; Check for the first condition ; Check for the third condition ; Check for the second condition ; Driver Code ; Given String str ; Function call
|
using System ; class GFG { static bool checkrules ( String s ) { if ( s . Length == 0 ) return true ; if ( s [ 0 ] != '1' ) return false ; if ( s . Length > 2 ) { if ( s [ 1 ] == '0' && s [ 2 ] == '0' ) return checkrules ( s . Substring ( 3 ) ) ; } return checkrules ( s . Substring ( 1 ) ) ; } public static void Main ( String [ ] args ) { String str = "1111" ; if ( checkrules ( str ) ) { Console . Write ( " Valid β String " ) ; } else { Console . Write ( " Invalid β String " ) ; } } }
|
Length of longest subsequence in an Array having all elements as Nude Numbers | C # program for the above approach ; Function to check if the number is a Nude number ; Variable initialization ; int ' copy ' is converted to a String ; Total digits in the number ; Loop through all digits and check if every digit divides n or not ; flag is used to keep check ; Return true or false as per the condition ; Function to find the longest subsequence which contain all Nude numbers ; Find the length of longest Nude number subsequence ; Driver Code ; Given array [ ] arr ; Function call
|
using System ; class GFG { static bool isNudeNum ( int n ) { int copy , length , flag = 0 ; copy = n ; String temp ; temp = String . Join ( " " , copy ) ; length = temp . Length ; for ( int i = 0 ; i < length ; i ++ ) { int num = temp [ i ] - '0' ; if ( num == 0 n % num != 0 ) { flag = 1 ; } } if ( flag == 1 ) return false ; else return true ; } static int longestNudeSubseq ( int [ ] arr , int n ) { int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isNudeNum ( arr [ i ] ) ) answer ++ ; } return answer ; } public static void Main ( String [ ] args ) { int [ ] arr = { 34 , 34 , 2 , 2 , 3 , 333 , 221 , 32 } ; int n = arr . Length ; Console . Write ( longestNudeSubseq ( arr , n ) + " STRNEWLINE " ) ; } }
|
Longest subarray with difference exactly K between any two distinct values | C # implementation to find the longest subarray consisting of only two values with difference K ; Function to return the length of the longest sub - array ; Initialize set ; Store 1 st element of sub - array into set ; Check absolute difference between two elements ; If the new element is not present in the set ; If the set contains two elements ; Otherwise ; Update the maximum length ; Remove the set elements ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static int longestSubarray ( int [ ] arr , int n , int k ) { int i , j , Max = 1 ; HashSet < int > s = new HashSet < int > ( ) ; for ( i = 0 ; i < n - 1 ; i ++ ) { s . Add ( arr [ i ] ) ; for ( j = i + 1 ; j < n ; j ++ ) { if ( Math . Abs ( arr [ i ] - arr [ j ] ) == 0 || Math . Abs ( arr [ i ] - arr [ j ] ) == k ) { if ( ! s . Contains ( arr [ j ] ) ) { if ( s . Count == 2 ) break ; else s . Add ( arr [ j ] ) ; } } else break ; } if ( s . Count == 2 ) { Max = Math . Max ( Max , j - i ) ; s . Clear ( ) ; } else s . Clear ( ) ; } return Max ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 0 , 2 , 2 , 5 , 5 , 5 } ; int N = arr . Length ; int K = 1 ; int length = longestSubarray ( arr , N , K ) ; if ( length == 1 ) Console . Write ( - 1 ) ; else Console . Write ( length ) ; } }
|
Longest subarray of non | C # program for the above approach ; Function to find the maximum length of a subarray of 1 s after removing at most one 0 ; Stores the count of consecutive 1 's from left ; Stores the count of consecutive 1 's from right ; Traverse left to right ; If cell is non - empty ; Increase count ; If cell is empty ; Store the count of consecutive 1 's till (i - 1)-th index ; Traverse from right to left ; Store the count of consecutive 1 s till ( i + 1 ) - th index ; Stores the length of longest subarray ; Store the maximum ; If array a contains only 1 s return n else return ans ; Driver code
|
using System ; class GFG { public static int longestSubarray ( int [ ] a , int n ) { int [ ] l = new int [ n ] ; int [ ] r = new int [ n ] ; for ( int i = 0 , count = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) count ++ ; else { l [ i ] = count ; count = 0 ; } } for ( int i = n - 1 , count = 0 ; i >= 0 ; i -- ) { if ( a [ i ] == 1 ) count ++ ; else { r [ i ] = count ; count = 0 ; } } int ans = - 1 ; for ( int i = 0 ; i < n ; ++ i ) { if ( a [ i ] == 0 ) ans = Math . Max ( ans , l [ i ] + r [ i ] ) ; } return ans < 0 ? n : ans ; } public static void Main ( ) { int [ ] arr = { 0 , 1 , 1 , 1 , 0 , 1 , 0 , 1 , 1 } ; int n = arr . Length ; Console . Write ( longestSubarray ( arr , n ) ) ; } }
|
Find largest factor of N such that N / F is less than K | C # program for the above approach ; Function to find the value of X ; Loop to check all the numbers divisible by N that yield minimum N / i value ; Print the value of packages ; Driver code ; Given N and K ; Function call
|
using System ; class GFG { static void findMaxValue ( int N , int K ) { int packages ; int maxi = 1 ; for ( int i = 1 ; i <= K ; i ++ ) { if ( N % i == 0 ) maxi = Math . Max ( maxi , i ) ; } packages = N / maxi ; Console . WriteLine ( packages ) ; } public static void Main ( String [ ] args ) { int N = 8 , K = 7 ; findMaxValue ( N , K ) ; } }
|
Largest square which can be formed using given rectangular blocks | C # program for the above approach ; Function to find maximum side length of square ; Sort array in asc order ; Traverse array in desc order ; Driver code ; Given array arr [ ] ; Function Call
|
using System ; class GFG { static void maxSide ( int [ ] a , int n ) { int sideLength = 0 ; Array . Sort ( a ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( a [ i ] > sideLength ) { sideLength ++ ; } else { break ; } } Console . Write ( sideLength ) ; } public static void Main ( ) { int N = 6 ; int [ ] arr = new int [ ] { 3 , 2 , 1 , 5 , 2 , 4 } ; maxSide ( arr , N ) ; } }
|
Minimize difference after changing all odd elements to even | C # program for the above approach ; Function to minimize the difference between two elements of array ; Find all the element which are possible by multiplying 2 to odd numbers ; Sort the array ; Find the minimum difference Iterate and find which adjacent elements have the minimum difference ; Print the minimum difference ; Driver Code ; Given array ; Function call
|
using System ; class GFG { public static void minDiff ( long [ ] a , int n ) { for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 1 ) a [ i ] *= 2 ; } Array . Sort ( a ) ; long mindifference = a [ 1 ] - a [ 0 ] ; for ( int i = 1 ; i < a . Length ; i ++ ) { mindifference = Math . Min ( mindifference , a [ i ] - a [ i - 1 ] ) ; } Console . Write ( mindifference ) ; } public static void Main ( ) { long [ ] arr = { 3 , 8 , 13 , 30 , 50 } ; int n = arr . Length ; minDiff ( arr , n ) ; } }
|
Longest subarray having sum K | Set 2 | C # program for the above approach ; To store the prefix sum array ; Function for searching the lower bound of the subarray ; Iterate until low less than equal to high ; For each mid finding sum of sub array less than or equal to k ; Return the final answer ; Function to find the length of subarray with sum K ; Initialize sum to 0 ; Push the prefix sum of the array [ ] arr in prefix [ ] ; Search r for each i ; Update ans ; Print the length of subarray found in the array ; Driver Code ; Given array [ ] arr ; Given sum K ; Function call
|
using System ; using System . Collections . Generic ; class GFG { static List < int > v = new List < int > ( ) ; static int bin ( int val , int k , int n ) { int lo = 0 ; int hi = n ; int mid ; int ans = - 1 ; while ( lo <= hi ) { mid = lo + ( hi - lo ) / 2 ; if ( v [ mid ] - val <= k ) { lo = mid + 1 ; ans = mid ; } else hi = mid - 1 ; } return ans ; } static void findSubarraySumK ( int [ ] arr , int N , int K ) { int sum = 0 ; v . Add ( 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; v . Add ( sum ) ; } int ans = 0 , r ; for ( int i = 0 ; i < v . Count ; i ++ ) { r = bin ( v [ i ] , K , N ) ; ans = Math . Max ( ans , r - i ) ; } Console . Write ( ans ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 6 , 8 , 14 , 9 , 4 , 11 , 10 } ; int N = arr . Length ; int K = 13 ; findSubarraySumK ( arr , N , K ) ; } }
|
Minimum number of reversals to reach node 0 from every other node | C # program for the above approach ; Function to find minimum reversals ; Add all adjacent nodes to the node in the graph ; Insert edges in the graph ; Insert edges in the reversed graph ; Create array visited to mark all the visited nodes ; Stores the number of edges to be reversed ; BFS Traversal ; Pop the current node from the queue ; mark the current node visited ; Intitialize count of edges need to be reversed to 0 ; Enqueue adjacent nodes in the reversed graph to the queue , if not visited ; Enqueue adjacent nodes in graph to the queue , if not visited count the number of nodes added to the queue ; Update the reverse edge to the final count ; Return the result ; Driver Code ; Given edges to the graph ; Number of nodes ; Function Call
|
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static int minRev ( ArrayList edges , int n ) { Dictionary < int , ArrayList > graph = new Dictionary < int , ArrayList > ( ) ; Dictionary < int , ArrayList > graph_rev = new Dictionary < int , ArrayList > ( ) ; for ( int i = 0 ; i < edges . Count ; i ++ ) { int x = ( int ) ( ( ArrayList ) edges [ i ] ) [ 0 ] ; int y = ( int ) ( ( ArrayList ) edges [ i ] ) [ 1 ] ; if ( ! graph . ContainsKey ( x ) ) { graph [ x ] = new ArrayList ( ) ; } graph [ x ] . Add ( y ) ; if ( ! graph_rev . ContainsKey ( y ) ) { graph_rev [ y ] = new ArrayList ( ) ; } graph_rev [ y ] . Add ( x ) ; } Queue q = new Queue ( ) ; ArrayList visited = new ArrayList ( ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) { visited . Add ( false ) ; } q . Enqueue ( 0 ) ; int ans = 0 ; while ( q . Count != 0 ) { int curr = ( int ) q . Peek ( ) ; visited [ curr ] = true ; int count = 0 ; q . Dequeue ( ) ; if ( graph_rev . ContainsKey ( curr ) ) { for ( int i = 0 ; i < graph_rev [ curr ] . Count ; i ++ ) { if ( ! ( bool ) visited [ ( int ) ( ( ArrayList ) graph_rev [ curr ] ) [ i ] ] ) { q . Enqueue ( ( int ) ( ( ArrayList ) graph_rev [ curr ] ) [ i ] ) ; } } } if ( graph . ContainsKey ( curr ) ) { for ( int i = 0 ; i < ( ( ArrayList ) graph [ curr ] ) . Count ; i ++ ) { if ( ! ( bool ) visited [ ( int ) ( ( ArrayList ) graph [ curr ] ) [ i ] ] ) { q . Enqueue ( ( int ) ( ( ArrayList ) graph [ curr ] ) [ i ] ) ; count ++ ; } } } ans += count ; } return ans ; } public static void Main ( string [ ] args ) { ArrayList edges = new ArrayList ( ) { new ArrayList ( ) { 0 , 1 } , new ArrayList ( ) { 1 , 3 } , new ArrayList ( ) { 2 , 3 } , new ArrayList ( ) { 4 , 0 } , new ArrayList ( ) { 4 , 5 } } ; int n = 6 ; Console . Write ( minRev ( edges , n ) ) ; } }
|
Partition a set into two subsets such that difference between max of one and min of other is minimized | C # program for the above approach ; Function to split the array ; Sort the array in increasing order ; Calculating the max difference between consecutive elements ; Return the final minimum difference ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
|
using System ; class GFG { static int splitArray ( int [ ] arr , int N ) { Array . Sort ( arr ) ; int result = Int32 . MaxValue ; for ( int i = 1 ; i < N ; i ++ ) { result = Math . Min ( result , arr [ i ] - arr [ i - 1 ] ) ; } return result ; } public static void Main ( ) { int [ ] arr = { 3 , 1 , 2 , 6 , 4 } ; int N = arr . Length ; Console . Write ( splitArray ( arr , N ) ) ; } }
|
Find the element at R ' th β row β and β C ' th column in given a 2D pattern | C # implementation to compute the R ' th β row β and β C ' th column of the given pattern ; Function to compute the R ' th β row β and β C ' th column of the given pattern ; First element of a given row ; Element in the given column ; Driver code ; Function call
|
using System ; class GFG { static int findValue ( int R , int C ) { int k = ( R * ( R - 1 ) ) / 2 + 1 ; int diff = R + 1 ; for ( int i = 1 ; i < C ; i ++ ) { k = ( k + diff ) ; diff ++ ; } return k ; } public static void Main ( ) { int R = 4 ; int C = 4 ; int k = findValue ( R , C ) ; Console . Write ( k ) ; } }
|
Maximize number of groups formed with size not smaller than its largest element | C # implementation of above approach ; Function that prints the number of maximum groups ; Store the number of occurrence of elements ; Make all groups of similar elements and store the left numbers ; Condition for finding first leftover element ; Condition for current leftover element ; Condition if group size is equal to or more than current element ; Printing maximum number of groups ; Driver Code
|
using System ; class GFG { static void makeGroups ( int [ ] a , int n ) { int [ ] v = new int [ n + 1 ] ; int i = 0 ; for ( i = 0 ; i < n ; i ++ ) { v [ a [ i ] ] ++ ; } int no_of_groups = 0 ; for ( i = 1 ; i <= n ; i ++ ) { no_of_groups += v [ i ] / i ; v [ i ] = v [ i ] % i ; } i = 1 ; int total = 0 ; for ( i = 1 ; i <= n ; i ++ ) { if ( v [ i ] != 0 ) { total = v [ i ] ; break ; } } i ++ ; while ( i <= n ) { if ( v [ i ] != 0 ) { total += v [ i ] ; if ( total >= i ) { int rem = total - i ; no_of_groups ++ ; total = rem ; } } i ++ ; } Console . Write ( no_of_groups + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 1 , 2 , 2 } ; int size = arr . Length ; makeGroups ( arr , size ) ; } }
|
Leftmost Column with atleast one 1 in a row | C # program to calculate leftmost column having at least 1 ; Function return leftmost column having at least a 1 ; If current element is 1 decrement column by 1 ; If current element is 0 increment row by 1 ; Driver code
|
using System ; class GFG { static readonly int N = 3 ; static readonly int M = 4 ; static int FindColumn ( int [ , ] mat ) { int row = 0 , col = M - 1 ; int flag = 0 ; while ( row < N && col >= 0 ) { if ( mat [ row , col ] == 1 ) { col -- ; flag = 1 ; } else { row ++ ; } } col ++ ; if ( flag != 0 ) return col + 1 ; else return - 1 ; } public static void Main ( String [ ] args ) { int [ , ] mat = { { 0 , 0 , 0 , 1 } , { 0 , 1 , 1 , 1 } , { 0 , 0 , 1 , 1 } } ; Console . Write ( FindColumn ( mat ) ) ; } }
|
Find two numbers made up of a given digit such that their difference is divisible by N | C # implementation of the above approach ; Function to implement the above approach ; To store remainder - length of the number as key - value pairs ; Iterate till N + 1 length ; Search remainder in the map ; If remainder is not already present insert the length for the corresponding remainder ; Keep increasing M ; To keep M in range of integer ; Length of one number is the current Length ; Length of the other number is the length paired with current remainder in map ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static void findNumbers ( int N , int M ) { int m = M ; Dictionary < int , int > remLen = new Dictionary < int , int > ( ) ; int len , remainder = 0 ; for ( len = 1 ; len <= N + 1 ; ++ len ) { remainder = M % N ; if ( ! remLen . ContainsKey ( remainder ) ) { remLen . Add ( remainder , len ) ; } else { break ; } M = M * 10 + m ; M = M % N ; } int LenA = len ; int LenB = remLen [ remainder ] ; for ( int i = 0 ; i < LenB ; ++ i ) Console . Write ( m ) ; Console . Write ( " β " ) ; for ( int i = 0 ; i < LenA ; ++ i ) Console . Write ( m ) ; } public static void Main ( String [ ] args ) { int N = 8 , M = 2 ; findNumbers ( N , M ) ; } }
|
Number of ways to select equal sized subarrays from two arrays having atleast K equal pairs of elements | C # implementation to count the number of ways to select equal sized subarrays such that they have atleast K common elements ; 2D prefix sum for submatrix sum query for matrix ; Function to find the prefix sum of the matrix from i and j ; Function to count the number of ways to select equal sized subarrays such that they have atleast K common elements ; Combining the two arrays ; Calculating the 2D prefix sum ; Iterating through all the elements of matrix and considering them to be the bottom right ; Applying binary search over side length ; If sum of this submatrix >= k then new search space will be [ low , mid ] ; Else new search space will be [ mid + 1 , high ] ; Adding the total submatrices ; Driver Code
|
using System ; class GFG { static int [ , ] prefix_2D = new int [ 2005 , 2005 ] ; static int subMatrixSum ( int i , int j , int len ) { return prefix_2D [ i , j ] - prefix_2D [ i , j - len ] - prefix_2D [ i - len , j ] + prefix_2D [ i - len , j - len ] ; } static int numberOfWays ( int [ ] a , int [ ] b , int n , int m , int k ) { for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { if ( a [ i - 1 ] == b [ j - 1 ] ) prefix_2D [ i , j ] = 1 ; else prefix_2D [ i , j ] = 0 ; } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { prefix_2D [ i , j ] += prefix_2D [ i , j - 1 ] ; } } for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { prefix_2D [ i , j ] += prefix_2D [ i - 1 , j ] ; } } int answer = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { int low = 1 ; int high = Math . Min ( i , j ) ; while ( low < high ) { int mid = ( low + high ) >> 1 ; if ( subMatrixSum ( i , j , mid ) >= k ) { high = mid ; } else { low = mid + 1 ; } } if ( subMatrixSum ( i , j , low ) >= k ) { answer += ( Math . Min ( i , j ) - low + 1 ) ; } } } return answer ; } public static void Main ( String [ ] args ) { int N = 2 , M = 3 ; int [ ] A = { 1 , 2 } ; int [ ] B = { 1 , 2 , 3 } ; int K = 1 ; Console . Write ( numberOfWays ( A , B , N , M , K ) ) ; } }
|
Find lexicographically smallest string in at most one swaps | C # implementation of the above approach ; Function to return the lexicographically smallest String that can be formed by swapping at most one character . The characters might not necessarily be adjacent . ; Store last occurrence of every character ; Set - 1 as default for every character . ; char index to fill in the last occurrence array ; If this is true then this character is being visited for the first time from the last Thus last occurrence of this character is stored in this index ; char to replace ; Find the last occurrence of this character . ; Swap this with the last occurrence ; Driver code
|
using System ; class GFG { static String findSmallest ( char [ ] s ) { int len = s . Length ; int [ ] loccur = new int [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) loccur [ i ] = - 1 ; for ( int i = len - 1 ; i >= 0 ; -- i ) { int chI = s [ i ] - ' a ' ; if ( loccur [ chI ] == - 1 ) { loccur [ chI ] = i ; } } char [ ] sorted_s = s ; Array . Sort ( sorted_s ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( s [ i ] != sorted_s [ i ] ) { int chI = sorted_s [ i ] - ' a ' ; int last_occ = loccur [ chI ] ; char temp = s [ last_occ ] ; s [ last_occ ] = s [ i ] ; s [ i ] = temp ; break ; } } return String . Join ( " " , s ) ; } public static void Main ( String [ ] args ) { String s = " geeks " ; Console . Write ( findSmallest ( s . ToCharArray ( ) ) ) ; } }
|
Maximum size of square such that all submatrices of that size have sum less than K | C # implementation to find the maximum size square submatrix such that their sum is less than K ; Size of matrix ; Function to preprocess the matrix for computing the sum of every possible matrix of the given size ; Loop to copy the first row of the matrix into the aux matrix ; Computing the sum column - wise ; Computing row wise sum ; Function to find the sum of a submatrix with the given indices ; Overall sum from the top to right corner of matrix ; Removing the sum from the top corer of the matrix ; Remove the overlapping sum ; Add the sum of top corner which is subtracted twice ; Function to check whether square sub matrices of size mid satisfy the condition or not ; Iterating throught all possible submatrices of given size ; Function to find the maximum square size possible with the such that every submatrix have sum less than the given sum ; Search space ; Binary search for size ; Check if the mid satisfies the given condition ; Driver Code
|
using System ; class GFG { static readonly int N = 4 ; static readonly int M = 5 ; static void preProcess ( int [ , ] mat , int [ , ] aux ) { for ( int i = 0 ; i < M ; i ++ ) aux [ 0 , i ] = mat [ 0 , i ] ; for ( int i = 1 ; i < N ; i ++ ) for ( int j = 0 ; j < M ; j ++ ) aux [ i , j ] = mat [ i , j ] + aux [ i - 1 , j ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 1 ; j < M ; j ++ ) aux [ i , j ] += aux [ i , j - 1 ] ; } static int sumQuery ( int [ , ] aux , int tli , int tlj , int rbi , int rbj ) { int res = aux [ rbi , rbj ] ; if ( tli > 0 ) res = res - aux [ tli - 1 , rbj ] ; if ( tlj > 0 ) res = res - aux [ rbi , tlj - 1 ] ; if ( tli > 0 && tlj > 0 ) res = res + aux [ tli - 1 , tlj - 1 ] ; return res ; } static bool check ( int mid , int [ , ] aux , int K ) { bool satisfies = true ; for ( int x = 0 ; x < N ; x ++ ) { for ( int y = 0 ; y < M ; y ++ ) { if ( x + mid - 1 <= N - 1 && y + mid - 1 <= M - 1 ) { if ( sumQuery ( aux , x , y , x + mid - 1 , y + mid - 1 ) > K ) satisfies = false ; } } } return ( satisfies == true ) ; } static int maximumSquareSize ( int [ , ] mat , int K ) { int [ , ] aux = new int [ N , M ] ; preProcess ( mat , aux ) ; int low = 1 , high = Math . Min ( N , M ) ; int mid ; while ( high - low > 1 ) { mid = ( low + high ) / 2 ; if ( check ( mid , aux , K ) ) { low = mid ; } else high = mid ; } if ( check ( high , aux , K ) ) return high ; return low ; } public static void Main ( String [ ] args ) { int K = 30 ; int [ , ] mat = { { 1 , 2 , 3 , 4 , 6 } , { 5 , 3 , 8 , 1 , 2 } , { 4 , 6 , 7 , 5 , 5 } , { 2 , 4 , 8 , 9 , 4 } } ; Console . Write ( maximumSquareSize ( mat , K ) ) ; } }
|
Length of Longest Subarray with same elements in atmost K increments | C # program to find the length of longest Subarray with same elements in atmost K increments ; Initialize array for segment tree ; Function that builds the segment tree to return the max element in a range ; update the value in segment tree from given array ; find the middle index ; If there are more than one elements , then recur for left and right subtrees and store the max of values in this node ; Function to return the max element in the given range ; If the range is out of bounds , return - 1 ; Function that returns length of longest subarray with same elements in atmost K increments . ; Initialize the result variable Even though the K is 0 , the required longest subarray , in that case , will also be of length 1 ; Initialize the prefix sum array ; Build the prefix sum array ; Build the segment tree for range max query ; Loop through the array with a starting point as i for the required subarray till the longest subarray is found ; Performing the binary search to find the endpoint for the selected range ; Find the mid for binary search ; Find the max element in the range [ i , mid ] using Segment Tree ; Total sum of subarray after increments ; Actual sum of elements before increments ; Check if such increment is possible If true , then current i is the actual starting point of the required longest subarray ; Now for finding the endpoint for this range Perform the Binary search again with the updated start ; Store max end point for the range to give longest subarray ; If false , it means that the selected range is invalid ; Perform the Binary Search again with the updated end ; Store the length of longest subarray ; Return result ; Driver code
|
using System ; class GFG { static int [ ] segment_tree = new int [ 4 * 1000000 ] ; static int build ( int [ ] A , int start , int end , int node ) { if ( start == end ) segment_tree [ node ] = A [ start ] ; else { int mid = ( start + end ) / 2 ; segment_tree [ node ] = Math . Max ( build ( A , start , mid , 2 * node + 1 ) , build ( A , mid + 1 , end , 2 * node + 2 ) ) ; } return segment_tree [ node ] ; } static int query ( int start , int end , int l , int r , int node ) { if ( start > r end < l ) return - 1 ; if ( start >= l && end <= r ) return segment_tree [ node ] ; int mid = ( start + end ) / 2 ; return Math . Max ( query ( start , mid , l , r , 2 * node + 1 ) , query ( mid + 1 , end , l , r , 2 * node + 2 ) ) ; } static int longestSubArray ( int [ ] A , int N , int K ) { int res = 1 ; int [ ] preSum = new int [ N + 1 ] ; preSum [ 0 ] = A [ 0 ] ; for ( int i = 0 ; i < N ; i ++ ) preSum [ i + 1 ] = preSum [ i ] + A [ i ] ; build ( A , 0 , N - 1 , 0 ) ; for ( int i = 0 ; i < N ; i ++ ) { int start = i , end = N - 1 , mid , max_index = i ; while ( start <= end ) { mid = ( start + end ) / 2 ; int max_element = query ( 0 , N - 1 , i , mid , 0 ) ; int expected_sum = ( mid - i + 1 ) * max_element ; int actual_sum = preSum [ mid + 1 ] - preSum [ i ] ; if ( expected_sum - actual_sum <= K ) { start = mid + 1 ; max_index = Math . Max ( max_index , mid ) ; } else { end = mid - 1 ; } } res = Math . Max ( res , max_index - i + 1 ) ; } return res ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 0 , 4 , 6 , 7 } ; int K = 6 ; int N = arr . Length ; Console . WriteLine ( longestSubArray ( arr , N , K ) ) ; } }
|
Count of numbers from range [ L , R ] that end with any of the given digits | C # implementation of the approach ; Function to return the count of the required numbers ; Last digit of the current number ; If the last digit is equal to any of the given digits ; Driver code
|
using System ; class GFG { static int countNums ( int l , int r ) { int cnt = 0 ; for ( int i = l ; i <= r ; i ++ ) { int lastDigit = ( i % 10 ) ; if ( ( lastDigit % 10 ) == 2 || ( lastDigit % 10 ) == 3 || ( lastDigit % 10 ) == 9 ) { cnt ++ ; } } return cnt ; } public static void Main ( ) { int l = 11 , r = 33 ; Console . Write ( countNums ( l , r ) ) ; } }
|
Minimum K such that sum of array elements after division by K does not exceed S | C # implementation of the approach ; Function to return the minimum value of k that satisfies the given condition ; Find the maximum element ; Lowest answer can be 1 and the highest answer can be ( maximum + 1 ) ; Binary search ; Get the mid element ; Calculate the sum after dividing the array by new K which is mid ; Search in the second half ; First half ; Driver code
|
using System ; class GFG { static int findMinimumK ( int [ ] a , int n , int s ) { int maximum = a [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { maximum = Math . Max ( maximum , a [ i ] ) ; } int low = 1 , high = maximum + 1 ; int ans = high ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += ( int ) ( a [ i ] / mid ) ; } if ( sum > s ) low = mid + 1 ; else { ans = Math . Min ( ans , mid ) ; high = mid - 1 ; } } return ans ; } public static void Main ( ) { int [ ] a = { 10 , 7 , 8 , 10 , 12 , 19 } ; int n = a . Length ; int s = 27 ; Console . WriteLine ( findMinimumK ( a , n , s ) ) ; } }
|
Calculate the Sum of GCD over all subarrays | C # program to find Sum of GCD over all subarrays ; int a [ 100001 ] ; ; Build Sparse Table ; Building the Sparse Table for GCD [ L , R ] Queries ; Utility Function to calculate GCD in range [ L , R ] ; Calculating where the answer is stored in our Sparse Table ; Utility Function to find next - farther position where gcd is same ; BinarySearch for Next Position for EndPointer ; Utility function to calculate sum of gcd ; Initializing all the values ; Finding the next position for endPointer ; Adding the suitable sum to our answer ; Changing prevEndPointer ; Recalculating tempGCD ; Driver code
|
using System ; class GFG { static int [ , ] SparseTable = new int [ 100001 , 51 ] ; static void buildSparseTable ( int [ ] a , int n ) { for ( int i = 0 ; i < n ; i ++ ) { SparseTable [ i , 0 ] = a [ i ] ; } for ( int j = 1 ; j <= 19 ; j ++ ) { for ( int i = 0 ; i <= n - ( 1 << j ) ; i ++ ) { SparseTable [ i , j ] = __gcd ( SparseTable [ i , j - 1 ] , SparseTable [ i + ( 1 << ( j - 1 ) ) , j - 1 ] ) ; } } } static int queryForGCD ( int L , int R ) { int returnValue ; int j = ( int ) ( Math . Log ( R - L + 1 ) ) ; returnValue = __gcd ( SparseTable [ L , j ] , SparseTable [ R - ( 1 << j ) + 1 , j ] ) ; return returnValue ; } static int nextPosition ( int tempGCD , int startPointer , int prevEndPointer , int n ) { int high = n - 1 ; int low = prevEndPointer ; int mid = prevEndPointer ; int nextPos = prevEndPointer ; while ( high >= low ) { mid = ( ( high + low ) >> 1 ) ; if ( queryForGCD ( startPointer , mid ) == tempGCD ) { nextPos = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } return nextPos + 1 ; } static int calculateSum ( int [ ] a , int n ) { buildSparseTable ( a , n ) ; int endPointer , startPointer , prevEndPointer , tempGCD ; int tempAns = 0 ; for ( int i = 0 ; i < n ; i ++ ) { endPointer = i ; startPointer = i ; prevEndPointer = i ; tempGCD = a [ i ] ; while ( endPointer < n ) { endPointer = nextPosition ( tempGCD , startPointer , prevEndPointer , n ) ; tempAns += ( ( endPointer - prevEndPointer ) * tempGCD ) ; prevEndPointer = endPointer ; if ( endPointer < n ) { tempGCD = __gcd ( tempGCD , a [ endPointer ] ) ; } } } return tempAns ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void Main ( String [ ] args ) { int n = 6 ; int [ ] a = { 2 , 2 , 2 , 3 , 5 , 5 } ; Console . WriteLine ( calculateSum ( a , n ) ) ; } }
|
QuickSelect ( A Simple Iterative Implementation ) | C # program for iterative implementation of QuickSelect ; Standard Lomuto partition function ; Implementation of QuickSelect ; Partition a [ left . . right ] around a pivot and find the position of the pivot ; If pivot itself is the k - th smallest element ; If there are more than k - 1 elements on left of pivot , then k - th smallest must be on left side . ; Else k - th smallest is on right side . ; Driver Code
|
using System ; class GFG { static int partition ( int [ ] arr , int low , int high ) { int temp ; int pivot = arr [ high ] ; int i = ( low - 1 ) ; for ( int j = low ; j <= high - 1 ; j ++ ) { if ( arr [ j ] <= pivot ) { i ++ ; temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } temp = arr [ i + 1 ] ; arr [ i + 1 ] = arr [ high ] ; arr [ high ] = temp ; return ( i + 1 ) ; } static int kthSmallest ( int [ ] a , int left , int right , int k ) { while ( left <= right ) { int pivotIndex = partition ( a , left , right ) ; if ( pivotIndex == k - 1 ) return a [ pivotIndex ] ; else if ( pivotIndex > k - 1 ) right = pivotIndex - 1 ; else left = pivotIndex + 1 ; } return - 1 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 4 , 5 , 8 , 11 , 6 , 26 } ; int n = arr . Length ; int k = 5 ; Console . WriteLine ( " K - th β smallest β element β is β " + kthSmallest ( arr , 0 , n - 1 , k ) ) ; } }
|
Pair with largest sum which is less than K in the array | C # program to find pair with largest sum which is less than K in the array ; Function to find pair with largest sum which is less than K in the array ; To store the break point ; Sort the given array ; Find the break point ; No need to look beyond i 'th index ; Find the required pair ; Print the required answer ; Driver code ; Function call
|
using System ; class GFG { static void Max_Sum ( int [ ] arr , int n , int k ) { int p = n ; Array . Sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= k ) { p = i ; break ; } } int maxsum = 0 , a = 0 , b = 0 ; for ( int i = 0 ; i < p ; i ++ ) { for ( int j = i + 1 ; j < p ; j ++ ) { if ( arr [ i ] + arr [ j ] < k && arr [ i ] + arr [ j ] > maxsum ) { maxsum = arr [ i ] + arr [ j ] ; a = arr [ i ] ; b = arr [ j ] ; } } } Console . WriteLine ( a + " β " + b ) ; } public static void Main ( ) { int [ ] arr = { 5 , 20 , 110 , 100 , 10 } ; int k = 85 ; int n = arr . Length ; Max_Sum ( arr , n , k ) ; } }
|
Maximum length palindromic substring such that it starts and ends with given char | C # implementation of the approach ; Function that returns true if str [ i ... j ] is a palindrome ; Function to return the length of the longest palindromic sub - string such that it starts and ends with the character ch ; If current character is a valid starting index ; Instead of finding the ending index from the beginning , find the index from the end This is because if the current sub - string is a palindrome then there is no need to check the sub - strings of smaller length and we can skip to the next iteration of the outer loop ; If current character is a valid ending index ; If str [ i ... j ] is a palindrome then update the length of the maximum palindrome so far ; Driver code
|
using System ; class GFG { static bool isPalindrome ( string str , int i , int j ) { while ( i < j ) { if ( str [ i ] != str [ j ] ) { return false ; } i ++ ; j -- ; } return true ; } static int maxLenPalindrome ( string str , int n , char ch ) { int maxLen = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ch ) { for ( int j = n - 1 ; j >= i ; j -- ) { if ( str [ j ] == ch ) { if ( isPalindrome ( str , i , j ) ) { maxLen = Math . Max ( maxLen , j - i + 1 ) ; break ; } } } } } return maxLen ; } public static void Main ( ) { string str = " lapqooqpqpl " ; int n = str . Length ; char ch = ' p ' ; Console . WriteLine ( maxLenPalindrome ( str , n , ch ) ) ; } }
|
Longest sub | C # implementation of the approach ; Function to find the starting and the ending index of the sub - array with equal number of alphabets and numeric digits ; If its an alphabet ; Else its a number ; Pick a starting point as i ; Consider all sub - arrays starting from i ; If this is a 0 sum sub - array then compare it with maximum size sub - array calculated so far ; If no valid sub - array found ; Driver code
|
using System ; class GFG { static bool isalpha ( int input_char ) { if ( ( input_char >= 65 && input_char <= 90 ) || ( input_char >= 97 && input_char <= 122 ) ) return true ; return false ; } static void findSubArray ( int [ ] arr , int n ) { int sum = 0 ; int maxsize = - 1 , startindex = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isalpha ( arr [ i ] ) ) { arr [ i ] = 0 ; } else { arr [ i ] = 1 ; } } for ( int i = 0 ; i < n - 1 ; i ++ ) { sum = ( arr [ i ] == 0 ) ? - 1 : 1 ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] == 0 ) sum += - 1 ; else sum += 1 ; if ( sum == 0 && maxsize < j - i + 1 ) { maxsize = j - i + 1 ; startindex = i ; } } } if ( maxsize == - 1 ) Console . WriteLine ( maxsize ) ; else Console . WriteLine ( startindex + " β " + ( startindex + maxsize - 1 ) ) ; } public static void Main ( ) { int [ ] arr = { ' A ' , ' B ' , ' X ' , 4 , 6 , ' X ' , ' a ' } ; int size = arr . Length ; findSubArray ( arr , size ) ; } }
|
Check if given string can be formed by two other strings or their permutations | C # implementation of the above approach ; Function to sort the given string using counting sort ; Array to store the count of each character ; Insert characters in the string in increasing order ; Function that returns true if str can be generated from any permutation of the two strings selected from the given vector ; Sort the given string ; Select two strings at a time from given vector ; Get the concatenated string ; Sort the resultant string ; If the resultant string is equal to the given string str ; No valid pair found ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static int MAX = 26 ; static String countingsort ( char [ ] s ) { int [ ] count = new int [ MAX ] ; for ( int i = 0 ; i < s . Length ; i ++ ) { count [ s [ i ] - ' a ' ] ++ ; } int index = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { int j = 0 ; while ( j < count [ i ] ) { s [ index ++ ] = ( char ) ( i + ' a ' ) ; j ++ ; } } return String . Join ( " " , s ) ; } static Boolean isPossible ( List < String > v , String str ) { str = countingsort ( str . ToCharArray ( ) ) ; for ( int i = 0 ; i < v . Count - 1 ; i ++ ) { for ( int j = i + 1 ; j < v . Count ; j ++ ) { String temp = v [ i ] + v [ j ] ; temp = countingsort ( temp . ToCharArray ( ) ) ; if ( temp . Equals ( str ) ) { return true ; } } } return false ; } public static void Main ( String [ ] args ) { String str = " amazon " ; String [ ] arr = { " fds " , " oxq " , " zoa " , " epw " , " amn " } ; List < String > v = new List < String > ( arr ) ; if ( isPossible ( v , str ) ) Console . WriteLine ( " Yes " ) ; else Console . WriteLine ( " No " ) ; } }
|
Queries to find the first non | C # implementation of the approach ; Maximum distinct characters possible ; To store the frequency of the characters ; Function to pre - calculate the frequency array ; Only the first character has frequency 1 till index 0 ; Starting from the second character of the string ; For every possible character ; Current character under consideration ; If it is equal to the character at the current index ; Function to return the frequency of the given character in the sub - string str [ l ... r ] ; Function to return the first non - repeating character in range [ l . . r ] ; Starting from the first character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the sub - string are repeating ; Driver code ; Pre - calculate the frequency array
|
using System ; class GFG { static int MAX = 256 ; static int [ , ] freq ; static void preCalculate ( string str , int n ) { freq [ ( int ) str [ 0 ] , 0 ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { char ch = str [ i ] ; for ( int j = 0 ; j < MAX ; j ++ ) { char charToUpdate = ( char ) j ; if ( charToUpdate == ch ) freq [ j , i ] = freq [ j , i - 1 ] + 1 ; else freq [ j , i ] = freq [ j , i - 1 ] ; } } } static int getFrequency ( char ch , int l , int r ) { if ( l == 0 ) return freq [ ( int ) ch , r ] ; else return ( freq [ ( int ) ch , r ] - freq [ ( int ) ch , l - 1 ] ) ; } static string firstNonRepeating ( string str , int n , int l , int r ) { for ( int i = l ; i < r ; i ++ ) { char ch = str [ i ] ; if ( getFrequency ( ch , l , r ) == 1 ) return ( " " + ch ) ; } return " - 1" ; } public static void Main ( ) { string str = " GeeksForGeeks " ; int n = str . Length ; int [ , ] queries = { { 0 , 3 } , { 2 , 3 } , { 5 , 12 } } ; int q = queries . Length ; freq = new int [ MAX , n ] ; preCalculate ( str , n ) ; for ( int i = 0 ; i < q ; i ++ ) { Console . WriteLine ( firstNonRepeating ( str , n , queries [ i , 0 ] , queries [ i , 1 ] ) ) ; } } }
|
Length of the largest substring which have character with frequency greater than or equal to half of the substring | C # implementation of the above approach ; Function to return the length of the longest sub string having frequency of a character greater than half of the length of the sub string ; for each of the character ' a ' to ' z ' ; finding frequency prefix array of the character ; Finding the r [ ] and l [ ] arrays . ; for each j from 0 to n ; Finding the lower bound of i . ; storing the maximum value of i - j + 1 ; clearing all the vector so that it can be used for other characters . ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static int maxLength ( String s , int n ) { int ans = int . MinValue ; List < int > A = new List < int > ( ) ; List < int > L = new List < int > ( ) ; List < int > R = new List < int > ( ) ; int [ ] freq = new int [ n + 5 ] ; for ( int i = 0 ; i < 26 ; i ++ ) { int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( s [ j ] - ' a ' == i ) count ++ ; freq [ j ] = count ; } for ( int j = 1 ; j < n ; j ++ ) { L . Add ( ( 2 * freq [ j - 1 ] ) - j ) ; R . Add ( ( 2 * freq [ j ] ) - j ) ; } int max_len = int . MinValue ; int min_val = int . MaxValue ; for ( int j = 0 ; j < L . Count ; j ++ ) { min_val = Math . Min ( min_val , L [ j ] ) ; A . Add ( min_val ) ; int l = 0 , r = j ; while ( l <= r ) { int mid = ( l + r ) >> 1 ; if ( A [ mid ] <= R [ j ] ) { max_len = Math . Max ( max_len , j - mid + 1 ) ; r = mid - 1 ; } else { l = mid + 1 ; } } } ans = Math . Max ( ans , max_len ) ; A . Clear ( ) ; R . Clear ( ) ; L . Clear ( ) ; } return ans ; } public static void Main ( String [ ] args ) { String s = " ababbbacbcbcca " ; int n = s . Length ; Console . WriteLine ( maxLength ( s , n ) ) ; } }
|
Repeated Character Whose First Appearance is Leftmost | C # program to find first repeating character ; The function returns index of the first repeating character in a string . If all characters are repeating then returns - 1 ; Mark all characters as not visited ; Traverse from right and update res as soon as we see a visited character . ; Driver Code
|
using System ; class GFG { static int NO_OF_CHARS = 256 ; static int firstRepeating ( String str ) { Boolean [ ] visited = new Boolean [ NO_OF_CHARS ] ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) visited [ i ] = false ; int res = - 1 ; for ( int i = str . Length - 1 ; i >= 0 ; i -- ) { if ( visited [ str [ i ] ] == false ) visited [ str [ i ] ] = true ; else res = i ; } return res ; } public static void Main ( String [ ] args ) { String str = " geeksforgeeks " ; int index = firstRepeating ( str ) ; if ( index == - 1 ) Console . Write ( " Either β all β characters β are β " + " distinct β or β string β is β empty " ) ; else Console . Write ( " First β Repeating β character " + " β is β { 0 } " , str [ index ] ) ; } }
|
Find maximum sum taking every Kth element in the array | C # implementation of the approach ; Function to return the maximum sum for every possible sequence such that a [ i ] + a [ i + k ] + a [ i + 2 k ] + ... + a [ i + qk ] is maximized ; Initialize the maximum with the smallest value ; Initialize the sum array with zero ; Iterate from the right ; Update the sum starting at the current element ; Update the maximum so far ; Driver code
|
using System ; class GFG { static int maxSum ( int [ ] arr , int n , int K ) { int maximum = int . MinValue ; int [ ] sum = new int [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i + K < n ) sum [ i ] = sum [ i + K ] + arr [ i ] ; else sum [ i ] = arr [ i ] ; maximum = Math . Max ( maximum , sum [ i ] ) ; } return maximum ; } public static void Main ( ) { int [ ] arr = { 3 , 6 , 4 , 7 , 2 } ; int n = arr . Length ; int K = 2 ; Console . Write ( maxSum ( arr , n , K ) ) ; } }
|
Count common characters in two strings | C # implementation of the approach ; Function to return the count of valid indices pairs ; To store the frequencies of characters of string s1 and s2 ; To store the count of valid pairs ; Update the frequencies of the characters of string s1 ; Update the frequencies of the characters of string s2 ; Find the count of valid pairs ; Driver code
|
using System ; class GFG { static int countPairs ( string s1 , int n1 , string s2 , int n2 ) { int [ ] freq1 = new int [ 26 ] ; int [ ] freq2 = new int [ 26 ] ; Array . Fill ( freq1 , 0 ) ; Array . Fill ( freq2 , 0 ) ; int i , count = 0 ; for ( i = 0 ; i < n1 ; i ++ ) freq1 [ s1 [ i ] - ' a ' ] ++ ; for ( i = 0 ; i < n2 ; i ++ ) freq2 [ s2 [ i ] - ' a ' ] ++ ; for ( i = 0 ; i < 26 ; i ++ ) count += ( Math . Min ( freq1 [ i ] , freq2 [ i ] ) ) ; return count ; } public static void Main ( ) { string s1 = " geeksforgeeks " , s2 = " platformforgeeks " ; int n1 = s1 . Length , n2 = s2 . Length ; Console . WriteLine ( countPairs ( s1 , n1 , s2 , n2 ) ) ; } }
|
Find a distinct pair ( x , y ) in given range such that x divides y | C # implementation of the approach ; Driver code
|
using System ; class GFG { static void findpair ( int l , int r ) { int c = 0 ; for ( int i = l ; i <= r ; i ++ ) { for ( int j = i + 1 ; j <= r ; j ++ ) { if ( j % i == 0 && j != i ) { Console . Write ( i + " , β " + j ) ; c = 1 ; break ; } } if ( c == 1 ) break ; } } static void Main ( ) { int l = 1 , r = 10 ; findpair ( l , r ) ; } }
|
Check if the given array can be reduced to zeros with the given operation performed given number of times | C # implementation of the approach ; Function that returns true if the array can be reduced to 0 s with the given operation performed given number of times ; Set to store unique elements ; Add every element of the array to the set ; Count of all the unique elements in the array ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { public static bool check ( int [ ] arr , int N , int K ) { HashSet < int > unique = new HashSet < int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { unique . Add ( arr [ i ] ) ; } if ( unique . Count == K ) { return true ; } return false ; } public static void Main ( string [ ] args ) { int [ ] arr = new int [ ] { 1 , 1 , 2 , 3 } ; int N = arr . Length ; int K = 3 ; if ( check ( arr , N , K ) ) { Console . WriteLine ( " Yes " ) ; } else { Console . WriteLine ( " No " ) ; } } }
|
Print all the sum pairs which occur maximum number of times | C # implementation of above approach ; Function to find the sum pairs that occur the most ; Hash - table ; Keep a count of sum pairs ; Variables to store maximum occurrence ; Iterate in the hash table ; Print all sum pair which occur maximum number of times ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static void findSumPairs ( int [ ] a , int n ) { Dictionary < int , int > mpp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( mpp . ContainsKey ( a [ i ] + a [ j ] ) ) { var val = mpp [ a [ i ] + a [ j ] ] ; mpp . Remove ( a [ i ] + a [ j ] ) ; mpp . Add ( a [ i ] + a [ j ] , val + 1 ) ; } else { mpp . Add ( a [ i ] + a [ j ] , 1 ) ; } } } int occur = 0 ; foreach ( KeyValuePair < int , int > entry in mpp ) { if ( entry . Value > occur ) { occur = entry . Value ; } } foreach ( KeyValuePair < int , int > entry in mpp ) { if ( entry . Value == occur ) Console . WriteLine ( entry . Key ) ; } } public static void Main ( String [ ] args ) { int [ ] a = { 1 , 8 , 3 , 11 , 4 , 9 , 2 , 7 } ; int n = a . Length ; findSumPairs ( a , n ) ; } }
|
Minimum index i such that all the elements from index i to given index are equal | C # implementation of the approach ; Function to return the minimum required index ; Start from arr [ pos - 1 ] ; All elements are equal from arr [ i + 1 ] to arr [ pos ] ; Driver code ; Function Call
|
using System ; class GFG { static int minIndex ( int [ ] arr , int n , int pos ) { int num = arr [ pos ] ; int i = pos - 1 ; while ( i >= 0 ) { if ( arr [ i ] != num ) break ; i -- ; } return i + 1 ; } public static void Main ( ) { int [ ] arr = { 2 , 1 , 1 , 1 , 5 , 2 } ; int n = arr . Length ; int pos = 4 ; Console . WriteLine ( minIndex ( arr , n , pos ) ) ; } }
|
Minimum index i such that all the elements from index i to given index are equal | C # implementation of the approach ; Function to return the minimum required index ; Short - circuit more comparisions as found the border point ; For cases were high = low + 1 and arr [ high ] will match with arr [ pos ] but not arr [ low ] or arr [ mid ] . In such iteration the if condition will satisfy and loop will break post that low will be updated . Hence i will not point to the correct index . ; Driver code ; Console . WriteLine ( minIndex ( arr , 2 ) ) ; Should be 1 Console . WriteLine ( minIndex ( arr , 3 ) ) ; Should be 1 Console . WriteLine ( minIndex ( arr , 4 ) ) ; Should be 4
|
using System ; class GFG { static int minIndex ( int [ ] arr , int pos ) { int low = 0 ; int high = pos ; int i = pos ; while ( low < high ) { int mid = ( low + high ) / 2 ; if ( arr [ mid ] != arr [ pos ] ) { low = mid + 1 ; } else { high = mid - 1 ; i = mid ; if ( mid > 0 && arr [ mid - 1 ] != arr [ pos ] ) { break ; } } } return arr [ low ] == arr [ pos ] ? low : i ; } public static void Main ( ) { int [ ] arr = { 2 , 1 , 1 , 1 , 5 , 2 } ; } }
|
Count of strings that become equal to one of the two strings after one removal | C # implementation of the approach ; Function to return the count of the required strings ; Searching index after longest common prefix ends ; Searching index before longest common suffix ends ; If str1 = str2 ; If only 1 character is different in both the strings ; Checking remaining part of string for equality ; Searching in right of string h ( g to h ) ; Driver code
|
using System ; class GFG { static int findAnswer ( string str1 , string str2 , int n ) { int l = 0 , r = 0 ; int ans = 2 ; for ( int i = 0 ; i < n ; ++ i ) { if ( str1 [ i ] != str2 [ i ] ) { l = i ; break ; } } for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( str1 [ i ] != str2 [ i ] ) { r = i ; break ; } } if ( r < l ) return 26 * ( n + 1 ) ; else if ( l == r ) return ans ; else { for ( int i = l + 1 ; i <= r ; i ++ ) { if ( str1 [ i ] != str2 [ i - 1 ] ) { ans -- ; break ; } } for ( int i = l + 1 ; i <= r ; i ++ ) { if ( str1 [ i - 1 ] != str2 [ i ] ) { ans -- ; break ; } } return ans ; } } public static void Main ( ) { String str1 = " toy " , str2 = " try " ; int n = str1 . Length ; Console . WriteLine ( findAnswer ( str1 , str2 , n ) ) ; } }
|
Minimize the maximum minimum difference after one removal from array | C # implementation of the approach ; Function to return the minimum required difference ; Sort the given array ; When minimum element is removed ; When maximum element is removed ; Return the minimum of diff1 and diff2 ; Driver Code
|
using System ; public class GFG { static int findMinDifference ( int [ ] arr , int n ) { Array . Sort ( arr ) ; int diff1 = arr [ n - 1 ] - arr [ 1 ] ; int diff2 = arr [ n - 2 ] - arr [ 0 ] ; return Math . Min ( diff1 , diff2 ) ; } static public void Main ( ) { int [ ] arr = { 1 , 2 , 4 , 3 , 4 } ; int n = arr . Length ; Console . Write ( findMinDifference ( arr , n ) ) ; } }
|
Minimize the maximum minimum difference after one removal from array | C # implementation of the approach ; Function to return the minimum required difference ; If current element is greater than max ; max will become secondMax ; Update the max ; If current element is greater than secondMax but smaller than max ; Update the secondMax ; If current element is smaller than min ; min will become secondMin ; Update the min ; If current element is smaller than secondMin but greater than min ; Update the secondMin ; Minimum of the two possible differences ; Driver code
|
using System ; public class GFG { static int findMinDifference ( int [ ] arr , int n ) { int min , secondMin , max , secondMax ; min = secondMax = ( arr [ 0 ] < arr [ 1 ] ) ? arr [ 0 ] : arr [ 1 ] ; max = secondMin = ( arr [ 0 ] < arr [ 1 ] ) ? arr [ 1 ] : arr [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i ] > max ) { secondMax = max ; max = arr [ i ] ; } else if ( arr [ i ] > secondMax ) { secondMax = arr [ i ] ; } else if ( arr [ i ] < min ) { secondMin = min ; min = arr [ i ] ; } else if ( arr [ i ] < secondMin ) { secondMin = arr [ i ] ; } } int diff = Math . Min ( max - secondMin , secondMax - min ) ; return diff ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 4 , 3 , 4 } ; int n = arr . Length ; Console . WriteLine ( findMinDifference ( arr , n ) ) ; } }
|
Integers from the range that are composed of a single distinct digit | C # implementation of the approach ; Boolean function to check distinct digits of a number ; Take last digit ; Check if all other digits are same as last digit ; Remove last digit ; Function to return the count of integers that are composed of a single distinct digit only ; If i has single distinct digit ; Driver code
|
using System ; class GFG { static Boolean checkDistinct ( int x ) { int last = x % 10 ; while ( x > 0 ) { if ( x % 10 != last ) return false ; x = x / 10 ; } return true ; } static int findCount ( int L , int R ) { int count = 0 ; for ( int i = L ; i <= R ; i ++ ) { if ( checkDistinct ( i ) ) count += 1 ; } return count ; } static public void Main ( String [ ] args ) { int L = 10 , R = 50 ; Console . WriteLine ( findCount ( L , R ) ) ; } }
|
Smallest Pair Sum in an array | C # program to print the sum of the minimum pair ; Function to return the sum of the minimum pair from the array ; If found new minimum ; Minimum now becomes second minimum ; Update minimum ; If current element is > min and < secondMin ; Update secondMin ; Return the sum of the minimum pair ; Driver code
|
using System ; class GFG { static int smallest_pair ( int [ ] a , int n ) { int min = int . MaxValue , secondMin = int . MaxValue ; for ( int j = 0 ; j < n ; j ++ ) { if ( a [ j ] < min ) { secondMin = min ; min = a [ j ] ; } else if ( ( a [ j ] < secondMin ) && a [ j ] != min ) secondMin = a [ j ] ; } return ( secondMin + min ) ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 } ; int n = arr . Length ; Console . Write ( smallest_pair ( arr , n ) ) ; } }
|
Longest subarray with elements divisible by k | C # program of above approach ; function to find longest subarray ; this will contain length of longest subarray found ; Driver code
|
using System ; class GFG { static int longestsubarray ( int [ ] arr , int n , int k ) { int current_count = 0 ; int max_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) current_count ++ ; else current_count = 0 ; max_count = Math . Max ( current_count , max_count ) ; } return max_count ; } public static void Main ( ) { int [ ] arr = { 2 , 5 , 11 , 32 , 64 , 88 } ; int n = arr . Length ; int k = 8 ; Console . Write ( longestsubarray ( arr , n , k ) ) ; } }
|
Remove elements that appear strictly less than k times | C # program to remove the elements which appear strictly less than k times from the array . ; Hash map which will store the frequency of the elements of the array . ; Incrementing the frequency of the element by 1. ; Print the element which appear more than or equal to k times . ; Driver code
|
using System ; using System . Collections . Generic ; class geeks { public static void removeElements ( int [ ] arr , int n , int k ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( ! mp . ContainsKey ( arr [ i ] ) ) mp . Add ( arr [ i ] , 1 ) ; else { int x = mp [ arr [ i ] ] ; mp [ arr [ i ] ] = mp [ arr [ i ] ] + ++ x ; } } for ( int i = 0 ; i < n ; ++ i ) { if ( mp [ arr [ i ] ] >= k ) Console . Write ( arr [ i ] + " β " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 2 , 3 , 2 , 3 , 4 } ; int n = arr . Length ; int k = 2 ; removeElements ( arr , n , k ) ; } }
|
Check if a string contains a palindromic sub | C # program to check if there is a substring palindrome of even length . ; function to check if two consecutive same characters are present ; Driver Code
|
using System ; public class GFG { static bool check ( String s ) { for ( int i = 0 ; i < s . Length - 1 ; i ++ ) if ( s [ i ] == s [ i + 1 ] ) return true ; return false ; } public static void Main ( ) { String s = " xzyyz " ; if ( check ( s ) ) Console . WriteLine ( " YES " ) ; else Console . WriteLine ( " NO " ) ; } }
|
Remove elements from the array which appear more than k times | C # program to remove the elements which appear more than k times from the array . ; Hash map which will store the frequency of the elements of the array . ; Incrementing the frequency of the element by 1. ; Print the element which appear less than or equal to k times . ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static void RemoveElements ( int [ ] arr , int n , int k ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( mp . ContainsKey ( arr [ i ] ) ) mp [ arr [ i ] ] ++ ; else mp [ arr [ i ] ] = 1 ; } for ( int i = 0 ; i < n ; ++ i ) { if ( mp . ContainsKey ( arr [ i ] ) && mp [ arr [ i ] ] <= k ) { Console . Write ( arr [ i ] + " β " ) ; } } } static public void Main ( ) { int [ ] arr = { 1 , 2 , 2 , 3 , 2 , 3 , 4 } ; int n = arr . Length ; int k = 2 ; RemoveElements ( arr , n , k ) ; } }
|
Find the smallest after deleting given elements | C # program to find the smallest number from the array after n deletions ; Returns minimum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; Hash Map of the numbers to be deleted ; Increment the count of del [ i ] ; Initializing the smallestElement ; Search if the element is present ; Decrement its frequency ; If the frequency becomes 0 , erase it from the map ; Else compare it smallestElement ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static int findSmallestAfterDel ( int [ ] arr , int m , int [ ] del , int n ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( mp . ContainsKey ( del [ i ] ) ) { mp [ del [ i ] ] = mp [ del [ i ] ] + 1 ; } else { mp . Add ( del [ i ] , 1 ) ; } } int smallestElement = int . MaxValue ; for ( int i = 0 ; i < m ; ++ i ) { if ( mp . ContainsKey ( arr [ i ] ) ) { mp [ arr [ i ] ] = mp [ arr [ i ] ] - 1 ; if ( mp [ arr [ i ] ] == 0 ) mp . Remove ( arr [ i ] ) ; } else smallestElement = Math . Min ( smallestElement , arr [ i ] ) ; } return smallestElement ; } public static void Main ( String [ ] args ) { int [ ] array = { 5 , 12 , 33 , 4 , 56 , 12 , 20 } ; int m = array . Length ; int [ ] del = { 12 , 4 , 56 , 5 } ; int n = del . Length ; Console . WriteLine ( findSmallestAfterDel ( array , m , del , n ) ) ; } }
|
Find the largest after deleting the given elements | C # program to find the largest number from the array after n deletions ; Returns maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; Hash Map of the numbers to be deleted ; Increment the count of del [ i ] ; Initializing the largestElement ; Search if the element is present ; Decrement its frequency ; If the frequency becomes 0 , erase it from the map ; Else compare it largestElement ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static int findlargestAfterDel ( int [ ] arr , int m , int [ ] del , int n ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( mp . ContainsKey ( del [ i ] ) ) { mp [ arr [ i ] ] = mp [ arr [ i ] ] + 1 ; } else { mp . Add ( del [ i ] , 1 ) ; } } int largestElement = int . MinValue ; for ( int i = 0 ; i < m ; i ++ ) { if ( mp . ContainsKey ( arr [ i ] ) ) { mp [ arr [ i ] ] = mp [ arr [ i ] ] - 1 ; if ( mp [ arr [ i ] ] == 0 ) mp . Remove ( arr [ i ] ) ; } else largestElement = Math . Max ( largestElement , arr [ i ] ) ; } return largestElement ; } public static void Main ( String [ ] args ) { int [ ] array = { 5 , 12 , 33 , 4 , 56 , 12 , 20 } ; int m = array . Length ; int [ ] del = { 12 , 33 , 56 , 5 } ; int n = del . Length ; Console . WriteLine ( findlargestAfterDel ( array , m , del , n ) ) ; } }
|
Number of anomalies in an array | A simple C # solution to count anomalies in an array . ; Driver code
|
using System ; class GFG { static int countAnomalies ( int [ ] arr , int n , int k ) { int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int j ; for ( j = 0 ; j < n ; j ++ ) if ( i != j && Math . Abs ( arr [ i ] - arr [ j ] ) <= k ) break ; if ( j == n ) res ++ ; } return res ; } public static void Main ( ) { int [ ] arr = { 7 , 1 , 8 } ; int k = 5 ; int n = arr . Length ; Console . WriteLine ( countAnomalies ( arr , n , k ) ) ; } }
|
Count majority element in a matrix | C # program to find count of all majority elements in a Matrix ; Function to find count of all majority elements in a Matrix ; Store frequency of elements in matrix ; loop to iteratre through map ; check if frequency is greater than or equal to ( N * M ) / 2 ; Driver Code
|
using System ; using System . Collections . Generic ; class GFG { static int majorityInMatrix ( int [ , ] arr ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { if ( mp . ContainsKey ( arr [ i , j ] ) ) mp [ arr [ i , j ] ] ++ ; else mp [ arr [ i , j ] ] = 1 ; } } int countMajority = 0 ; Dictionary < int , int > . KeyCollection keyColl = mp . Keys ; foreach ( int i in keyColl ) { if ( mp [ i ] >= ( ( N * M ) / 2 ) ) { countMajority ++ ; } } return countMajority ; } public static void Main ( ) { int [ , ] mat = { { 1 , 2 , 2 } , { 1 , 3 , 2 } , { 1 , 2 , 6 } } ; Console . WriteLine ( majorityInMatrix ( mat ) ) ; } }
|
Find pair with maximum difference in any column of a Matrix | C # program to find column with max difference of any pair of elements ; Function to find the column with max difference ; Traverse matrix column wise ; Insert elements of column to vector ; calculating difference between maximum and minimum ; Driver Code
|
using System ; class GFG { static int colMaxDiff ( int [ , ] mat ) { int max_diff = int . MinValue ; for ( int i = 0 ; i < N ; i ++ ) { int max_val = mat [ 0 , i ] , min_val = mat [ 0 , i ] ; for ( int j = 1 ; j < N ; j ++ ) { max_val = Math . Max ( max_val , mat [ j , i ] ) ; min_val = Math . Min ( min_val , mat [ j , i ] ) ; } max_diff = Math . Max ( max_diff , max_val - min_val ) ; } return max_diff ; } public static void Main ( ) { int [ , ] mat = { { 1 , 2 , 3 , 4 , 5 } , { 5 , 3 , 5 , 4 , 0 } , { 5 , 6 , 7 , 8 , 9 } , { 0 , 6 , 3 , 4 , 12 } , { 9 , 7 , 12 , 4 , 3 } } ; Console . WriteLine ( " Max β difference β : β " + colMaxDiff ( mat ) ) ; } }
|
Find the Missing Number in a sorted array | A binary search based program to find the only missing number in a sorted array of distinct elements within limited range . ; Driver Code
|
using System ; class GFG { static int search ( int [ ] ar , int size ) { int a = 0 , b = size - 1 ; int mid = 0 ; while ( ( b - a ) > 1 ) { mid = ( a + b ) / 2 ; if ( ( ar [ a ] - a ) != ( ar [ mid ] - mid ) ) b = mid ; else if ( ( ar [ b ] - b ) != ( ar [ mid ] - mid ) ) a = mid ; } return ( ar [ a ] + 1 ) ; } static public void Main ( String [ ] args ) { int [ ] ar = { 1 , 2 , 3 , 4 , 5 , 6 , 8 } ; int size = ar . Length ; Console . WriteLine ( " Missing β number : β " + search ( ar , size ) ) ; } }
|
Delete array element in given index range [ L | C # code to delete element in given range ; Delete L to R elements ; Return size of Array after delete element ; Driver Code
|
using System ; class GFG { static int deleteElement ( int [ ] A , int L , int R , int N ) { int i , j = 0 ; for ( i = 0 ; i < N ; i ++ ) { if ( i <= L i >= R ) { A [ j ] = A [ i ] ; j ++ ; } } return j ; } public static void Main ( ) { int [ ] A = new int [ ] { 5 , 8 , 11 , 15 , 26 , 14 , 19 , 17 , 10 , 14 } ; int L = 2 , R = 7 ; int n = A . Length ; int res_size = deleteElement ( A , L , R , n ) ; for ( int i = 0 ; i < res_size ; i ++ ) Console . Write ( A [ i ] + " β " ) ; } }
|
Find the only missing number in a sorted array | C # program to find the only missing element . ; If this is the first element which is not index + 1 , then missing element is mid + 1 ; if this is not the first missing element search in left side ; if it follows index + 1 property then search in right side ; if no element is missing ; Driver code
|
using System ; class GFG { static int findmissing ( int [ ] ar , int N ) { int l = 0 , r = N - 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; if ( ar [ mid ] != mid + 1 && ar [ mid - 1 ] == mid ) return ( mid + 1 ) ; if ( ar [ mid ] != mid + 1 ) r = mid - 1 ; else l = mid + 1 ; } return - 1 ; } public static void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 7 , 8 } ; int N = arr . Length ; Console . WriteLine ( findmissing ( arr , N ) ) ; } }
|
Find index of first occurrence when an unsorted array is sorted | C # program to find index of first occurrence of x when array is sorted . ; lower_bound returns iterator pointing to first element that does not compare less to x . ; If x is not present return - 1. ; ; Driver Code
|
using System ; class GFG { static int findFirst ( int [ ] arr , int n , int x ) { Array . Sort ( arr ) ; int ptr = lowerBound ( arr , 0 , n , x ) ; return ( arr [ ptr ] != x ) ? - 1 : ( ptr ) ; } static int lowerBound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } static public void Main ( ) { int x = 20 ; int [ ] arr = { 10 , 30 , 20 , 50 , 20 } ; int n = arr . Length ; Console . Write ( findFirst ( arr , n , x ) ) ; } }
|
Find index of first occurrence when an unsorted array is sorted | C # program to find index of first occurrence of x when array is sorted . ; Driver main
|
using System ; public class GFG { static int findFirst ( int [ ] arr , int n , int x ) { int count = 0 ; bool isX = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == x ) { isX = true ; } else if ( arr [ i ] < x ) { count ++ ; } } return ( isX == false ) ? - 1 : count ; } public static void Main ( ) { int x = 20 ; int [ ] arr = { 10 , 30 , 20 , 50 , 20 } ; int n = arr . Length ; Console . WriteLine ( findFirst ( arr , n , x ) ) ; } }
|
Find duplicate in an array in O ( n ) and by using O ( 1 ) extra space | C # code to find the repeated elements in the array where every other is present once ; Function to find duplicate ; Find the intersection point of the slow and fast . ; Find the " entrance " to the cycle . ; Driver Code
|
using System ; class GFG { public static int findDuplicate ( int [ ] arr ) { int slow = arr [ 0 ] ; int fast = arr [ 0 ] ; do { slow = arr [ slow ] ; fast = arr [ arr [ fast ] ] ; } while ( slow != fast ) ; int ptr1 = arr [ 0 ] ; int ptr2 = slow ; while ( ptr1 != ptr2 ) { ptr1 = arr [ ptr1 ] ; ptr2 = arr [ ptr2 ] ; } return ptr1 ; } public static void Main ( ) { int [ ] arr = { 1 , 3 , 2 , 1 } ; Console . WriteLine ( " " + findDuplicate ( arr ) ) ; } }
|
Number of Larger Elements on right side in a string | C # program to count greater characters on right side of every character . ; Arrays to store result and character counts . ; start from right side of string ; Driver code
|
using System ; class GFG { static int MAX_CHAR = 26 ; static void printGreaterCount ( string str ) { int len = str . Length ; int [ ] ans = new int [ len ] ; int [ ] count = new int [ MAX_CHAR ] ; for ( int i = len - 1 ; i >= 0 ; i -- ) { count [ str [ i ] - ' a ' ] ++ ; for ( int j = str [ i ] - ' a ' + 1 ; j < MAX_CHAR ; j ++ ) { ans [ i ] += count [ j ] ; } } for ( int i = 0 ; i < len ; i ++ ) { Console . Write ( ans [ i ] + " β " ) ; } } static void Main ( ) { string str = " abcd " ; printGreaterCount ( str ) ; } }
|
Print all pairs with given sum | C # implementation of simple method to find count of pairs with given sum . ; Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to ' sum ' ; Store counts of all elements in map m ; Traverse through all elements ; Search if a pair can be formed with arr [ i ] . ; Driver code
|
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static void printPairs ( int [ ] arr , int n , int sum ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int rem = sum - arr [ i ] ; if ( m . ContainsKey ( rem ) ) { int count = m [ rem ] ; for ( int j = 0 ; j < count ; j ++ ) { Console . Write ( " ( " + rem + " , β " + arr [ i ] + " ) " + " STRNEWLINE " ) ; } } if ( m . ContainsKey ( arr [ i ] ) ) { m [ arr [ i ] ] ++ ; } else { m [ arr [ i ] ] = 1 ; } } } public static void Main ( string [ ] args ) { int [ ] arr = { 1 , 5 , 7 , - 1 , 5 } ; int n = arr . Length ; int sum = 6 ; printPairs ( arr , n , sum ) ; } }
|
Maximum product quadruple ( sub | A O ( n ) C # program to find maximum quadruple in an array . ; Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; Initialize Maximum , second maximum , third maximum and fourth maximum element ; Initialize Minimum , second minimum , third minimum and fourth minimum element ; Update Maximum , second maximum , third maximum and fourth maximum element ; Update second maximum , third maximum and fourth maximum element ; Update third maximum and fourth maximum element ; Update fourth maximum element ; Update Minimum , second minimum third minimum and fourth minimum element ; Update second minimum , third minimum and fourth minimum element ; Update third minimum and fourth minimum element ; Update fourth minimum element ; Return the maximum of x , y and z ; Driver Code
|
using System ; class GFG { static int maxProduct ( int [ ] arr , int n ) { if ( n < 4 ) { return - 1 ; } int maxA = int . MinValue , maxB = int . MinValue , maxC = int . MinValue , maxD = int . MinValue ; int minA = int . MaxValue , minB = int . MaxValue , minC = int . MaxValue , minD = int . MaxValue ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > maxA ) { maxD = maxC ; maxC = maxB ; maxB = maxA ; maxA = arr [ i ] ; } else if ( arr [ i ] > maxB ) { maxD = maxC ; maxC = maxB ; maxB = arr [ i ] ; } else if ( arr [ i ] > maxC ) { maxD = maxC ; maxC = arr [ i ] ; } else if ( arr [ i ] > maxD ) { maxD = arr [ i ] ; } if ( arr [ i ] < minA ) { minD = minC ; minC = minB ; minB = minA ; minA = arr [ i ] ; } else if ( arr [ i ] < minB ) { minD = minC ; minC = minB ; minB = arr [ i ] ; } else if ( arr [ i ] < minC ) { minD = minC ; minC = arr [ i ] ; } else if ( arr [ i ] < minD ) { minD = arr [ i ] ; } } int x = maxA * maxB * maxC * maxD ; int y = minA * minB * minC * minD ; int z = minA * minB * maxA * maxB ; return Math . Max ( x , Math . Max ( y , z ) ) ; } public static void Main ( ) { int [ ] arr = { 1 , - 4 , 3 , - 6 , 7 , 0 } ; int n = arr . Length ; int max = maxProduct ( arr , n ) ; if ( max == - 1 ) Console . Write ( " No β Quadruple β Exists " ) ; else Console . Write ( " Maximum β product β is β " + max ) ; } }
|
Ways to choose three points with distance between the most distant points <= L | C # program to count ways to choose triplets such that the distance between the farthest points <= L ; Returns the number of triplets with distance between farthest points <= L ; sort to get ordered triplets so that we can find the distance between farthest points belonging to a triplet ; generate and check for all possible triplets : { arr [ i ] , arr [ j ] , arr [ k ] } ; Since the array is sorted the farthest points will be a [ i ] and a [ k ] ; ; Driver Code ; set of n points on the X axis
|
using System ; class GFG { static int countTripletsLessThanL ( int n , int L , int [ ] arr ) { Array . Sort ( arr ) ; int ways = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { for ( int k = j + 1 ; k < n ; k ++ ) { int mostDistantDistance = arr [ k ] - arr [ i ] ; if ( mostDistantDistance <= L ) { ways ++ ; } } } } return ways ; } static public void Main ( ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . Length ; int L = 3 ; int ans = countTripletsLessThanL ( n , L , arr ) ; Console . WriteLine ( " Total β Number β of β ways β = β " + ans ) ; } }
|
Triplets in array with absolute difference less than k | C # program to count triplets with difference less than k . ; Return the lower bound i . e smallest index of element having value greater or equal to value ; Return the number of triplet indices satisfies the three constraints ; sort the array ; for each element from index 2 to n - 1. ; finding the lower bound of arr [ i ] - k . ; If there are at least two elements between lower bound and current element . ; increment the count by lb - i C 2. ; Driver Code
|
using System ; class GFG { static int binary_lower ( int value , int [ ] arr , int n ) { int start = 0 ; int end = n - 1 ; int ans = - 1 ; int mid ; while ( start <= end ) { mid = ( start + end ) / 2 ; if ( arr [ mid ] >= value ) { end = mid - 1 ; ans = mid ; } else { start = mid + 1 ; } } return ans ; } static int countTriplet ( int [ ] arr , int n , int k ) { int count = 0 ; Array . Sort ( arr ) ; for ( int i = 2 ; i < n ; i ++ ) { int cur = binary_lower ( arr [ i ] - k , arr , n ) ; if ( cur <= i - 2 ) { count += ( ( i - cur ) * ( i - cur - 1 ) ) / 2 ; } } return count ; } public static void Main ( ) { int [ ] arr = { 1 , 1 , 2 , 2 , 3 } ; int k = 1 ; int n = arr . Length ; Console . WriteLine ( countTriplet ( arr , n , k ) ) ; } }
|
Minimize the sum of roots of a given polynomial | C # program to find minimum sum of roots of a given polynomial ; resultant vector ; a vector that store indices of the positive elements ; a vector that store indices of the negative elements ; Case - 1 : ; Case - 2 : ; Case - 3 : ; Case - 4 : ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { static void getMinimumSum ( int [ ] arr , int n ) { List < int > res = new List < int > ( ) ; List < int > pos = new List < int > ( ) ; List < int > neg = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) pos . Add ( i ) ; else if ( arr [ i ] < 0 ) neg . Add ( i ) ; } if ( pos . Count >= 2 && neg . Count >= 2 ) { int posMax = Int32 . MinValue , posMaxIdx = - 1 ; int posMin = Int32 . MaxValue , posMinIdx = - 1 ; int negMax = Int32 . MinValue , negMaxIdx = - 1 ; int negMin = Int32 . MaxValue , negMinIdx = - 1 ; for ( int i = 0 ; i < pos . Count ; i ++ ) { if ( arr [ pos [ i ] ] > posMax ) { posMaxIdx = pos [ i ] ; posMax = arr [ posMaxIdx ] ; } } for ( int i = 0 ; i < pos . Count ; i ++ ) { if ( arr [ pos [ i ] ] < posMin && pos [ i ] != posMaxIdx ) { posMinIdx = pos [ i ] ; posMin = arr [ posMinIdx ] ; } } for ( int i = 0 ; i < neg . Count ; i ++ ) { if ( Math . Abs ( arr [ neg [ i ] ] ) > negMax ) { negMaxIdx = neg [ i ] ; negMax = Math . Abs ( arr [ negMaxIdx ] ) ; } } for ( int i = 0 ; i < neg . Count ; i ++ ) { if ( Math . Abs ( arr [ neg [ i ] ] ) < negMin && neg [ i ] != negMaxIdx ) { negMinIdx = neg [ i ] ; negMin = Math . Abs ( arr [ negMinIdx ] ) ; } } double posVal = - 1.0 * ( double ) posMax / ( double ) posMin ; double negVal = - 1.0 * ( double ) negMax / ( double ) negMin ; if ( posVal < negVal ) { res . Add ( arr [ posMinIdx ] ) ; res . Add ( arr [ posMaxIdx ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i != posMinIdx && i != posMaxIdx ) { res . Add ( arr [ i ] ) ; } } } else { res . Add ( arr [ negMinIdx ] ) ; res . Add ( arr [ negMaxIdx ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i != negMinIdx && i != negMaxIdx ) { res . Add ( arr [ i ] ) ; } } } for ( int i = 0 ; i < res . Count ; i ++ ) { Console . Write ( res [ i ] + " β " ) ; } Console . WriteLine ( ) ; } else if ( pos . Count >= 2 ) { int posMax = Int32 . MinValue , posMaxIdx = - 1 ; int posMin = Int32 . MaxValue , posMinIdx = - 1 ; for ( int i = 0 ; i < pos . Count ; i ++ ) { if ( arr [ pos [ i ] ] > posMax ) { posMaxIdx = pos [ i ] ; posMax = arr [ posMaxIdx ] ; } } for ( int i = 0 ; i < pos . Count ; i ++ ) { if ( arr [ pos [ i ] ] < posMin && pos [ i ] != posMaxIdx ) { posMinIdx = pos [ i ] ; posMin = arr [ posMinIdx ] ; } } res . Add ( arr [ posMinIdx ] ) ; res . Add ( arr [ posMaxIdx ] ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i != posMinIdx && i != posMaxIdx ) { res . Add ( arr [ i ] ) ; } } for ( int i = 0 ; i < res . Count ; i ++ ) { Console . Write ( res [ i ] + " β " ) ; } Console . WriteLine ( ) ; } else if ( neg . Count >= 2 ) { int negMax = Int32 . MinValue , negMaxIdx = - 1 ; int negMin = Int32 . MaxValue , negMinIdx = - 1 ; for ( int i = 0 ; i < neg . Count ; i ++ ) { if ( Math . Abs ( arr [ neg [ i ] ] ) > negMax ) { negMaxIdx = neg [ i ] ; negMax = Math . Abs ( arr [ negMaxIdx ] ) ; } } for ( int i = 0 ; i < neg . Count ; i ++ ) { if ( Math . Abs ( arr [ neg [ i ] ] ) < negMin && neg [ i ] != negMaxIdx ) { negMinIdx = neg [ i ] ; negMin = Math . Abs ( arr [ negMinIdx ] ) ; } } res . Add ( arr [ negMinIdx ] ) ; res . Add ( arr [ negMaxIdx ] ) ; for ( int i = 0 ; i < n ; i ++ ) if ( i != negMinIdx && i != negMaxIdx ) res . Add ( arr [ i ] ) ; for ( int i = 0 ; i < res . Count ; i ++ ) Console . WriteLine ( res [ i ] + " β " ) ; Console . WriteLine ( ) ; } else { Console . WriteLine ( " No β swap β required " ) ; } } static public void Main ( ) { int [ ] arr = { - 4 , 1 , 6 , - 3 , - 2 , - 1 } ; int n = arr . Length ; getMinimumSum ( arr , n ) ; } }
|
Longest Palindromic Substring using Palindromic Tree | Set 3 | C # code for longest Palindromic subString using Palindromic Tree data structure ; store start and end indexes of current Node inclusively ; stores length of subString ; stores insertion Node for all characters a - z ; stores the Maximum Palindromic Suffix Node for the current Node ; two special dummy Nodes as explained above ; stores Node information for constant time access ; Keeps track the current Node while insertion ; Function to insert edge in tree ; Finding X , such that s [ currIndex ] + X + s [ currIndex ] is palindrome . ; Check if s [ currIndex ] + X + s [ currIndex ] is already Present in tree . ; Else Create new node ; ; Setting suffix edge for newly Created Node . ; longest Palindromic suffix for a String of length 1 is a Null String . ; Else ; Driver code ; Imaginary root 's suffix edge points to itself, since for an imaginary String of length = -1 has an imaginary suffix String. Imaginary root. ; null root 's suffix edge points to Imaginary root, since for a String of length = 0 has an imaginary suffix String. ; last will be the index of our last subString
|
using System ; class GFG { static readonly int MAXN = 1000 ; class Node { public int start , end ; public int Length ; public int [ ] insertionEdge = new int [ 26 ] ; public int suffixEdge ; } ; static Node root1 , root2 ; static Node [ ] tree = new Node [ MAXN ] ; static int currNode ; static char [ ] s ; static int ptr ; static void insert ( int currIndex ) { int temp = currNode ; while ( true ) { int currLength = tree [ temp ] . Length ; if ( currIndex - currLength >= 1 && ( s [ currIndex ] == s [ currIndex - currLength - 1 ] ) ) break ; temp = tree [ temp ] . suffixEdge ; } if ( tree [ temp ] . insertionEdge [ s [ currIndex ] - ' a ' ] != 0 ) { currNode = tree [ temp ] . insertionEdge [ s [ currIndex ] - ' a ' ] ; return ; } ptr ++ ; tree [ temp ] . insertionEdge [ s [ currIndex ] - ' a ' ] = ptr ; tree [ ptr ] . end = currIndex ; tree [ ptr ] . Length = tree [ temp ] . Length + 2 ; tree [ ptr ] . start = tree [ ptr ] . end - tree [ ptr ] . Length + 1 ; currNode = ptr ; temp = tree [ temp ] . suffixEdge ; if ( tree [ currNode ] . Length == 1 ) { tree [ currNode ] . suffixEdge = 2 ; return ; } while ( true ) { int currLength = tree [ temp ] . Length ; if ( currIndex - currLength >= 1 && ( s [ currIndex ] == s [ currIndex - currLength - 1 ] ) ) break ; temp = tree [ temp ] . suffixEdge ; } tree [ currNode ] . suffixEdge = tree [ temp ] . insertionEdge [ s [ currIndex ] - ' a ' ] ; } public static void Main ( String [ ] args ) { root1 = new Node ( ) ; root1 . Length = - 1 ; root1 . suffixEdge = 1 ; root2 = new Node ( ) ; root2 . Length = 0 ; root2 . suffixEdge = 1 ; for ( int i = 0 ; i < MAXN ; i ++ ) tree [ i ] = new Node ( ) ; tree [ 1 ] = root1 ; tree [ 2 ] = root2 ; ptr = 2 ; currNode = 1 ; s = " forgeeksskeegfor " . ToCharArray ( ) ; for ( int i = 0 ; i < s . Length ; i ++ ) insert ( i ) ; int last = ptr ; for ( int i = tree [ last ] . start ; i <= tree [ last ] . end ; i ++ ) Console . Write ( s [ i ] ) ; } }
|
Maximum occurring character in a linked list | C # program to count the maximum occurring character in linked list ; Link list node ; counting the frequency of current element p . data ; if current counting is greater than max ; Push a node to linked list . Note that this function changes the head ; Driver code ; Start with the empty list ; this will create a linked list of character " geeksforgeeks "
|
using System ; class GFG { class Node { public char data ; public Node next ; } ; static Node head_ref ; static char maxChar ( Node head ) { Node p = head ; int max = - 1 ; char res = '0' ; while ( p != null ) { Node q = p . next ; int count = 1 ; while ( q != null ) { if ( p . data == q . data ) count ++ ; q = q . next ; } if ( max < count ) { res = p . data ; max = count ; } p = p . next ; } return res ; } static void push ( char new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; } public static void Main ( string [ ] args ) { head_ref = null ; string str = " skeegforskeeg " ; char [ ] st = str . ToCharArray ( ) ; int i ; for ( i = 0 ; i < st . Length ; i ++ ) push ( st [ i ] ) ; Console . Write ( maxChar ( head_ref ) ) ; } }
|
Find the one missing number in range | C # program to find missing number in a range . ; Find the missing number in a range ; here we xor of all the number ; xor last number ; Driver Code
|
using System ; using System . Collections . Generic ; using System . Linq ; class GFG { static int missingNum ( int [ ] arr , int n ) { List < int > list = new List < int > ( arr . Length ) ; foreach ( int i in arr ) { list . Add ( i ) ; } int minvalue = list . Min ( ) ; int xornum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { xornum ^= ( minvalue ) ^ arr [ i ] ; minvalue ++ ; } return xornum ^ minvalue ; } public static void Main ( String [ ] args ) { int [ ] arr = { 13 , 12 , 11 , 15 } ; int n = arr . Length ; Console . WriteLine ( missingNum ( arr , n ) ) ; } }
|
Find last index of a character in a string | C # program to find last index of character x in given string . ; Returns last index of x if it is present Else returns - 1. ; Driver code ; String in which char is to be found ; char whose index is to be found
|
using System ; class GFG { static int findLastIndex ( string str , char x ) { int index = - 1 ; for ( int i = 0 ; i < str . Length ; i ++ ) if ( str [ i ] == x ) index = i ; return index ; } public static void Main ( ) { string str = " geeksforgeeks " ; char x = ' e ' ; int index = findLastIndex ( str , x ) ; if ( index == - 1 ) Console . WriteLine ( " Character β not β found " ) ; else Console . WriteLine ( " Last β index β is β " + index ) ; } }
|
Find last index of a character in a string | C # code to find last index character x in given string . ; Returns last index of x if it is present . Else returns - 1. ; Traverse from right ; Driver code
|
using System ; class GFG { static int findLastIndex ( string str , char x ) { for ( int i = str . Length - 1 ; i >= 0 ; i -- ) if ( str [ i ] == x ) return i ; return - 1 ; } public static void Main ( ) { string str = " geeksforgeeks " ; char x = ' e ' ; int index = findLastIndex ( str , x ) ; if ( index == - 1 ) Console . WriteLine ( " Character β not β found " ) ; else Console . WriteLine ( " Last β index β is β " + index ) ; } }
|
Smallest number whose set bits are maximum in a given range | C # program to find number whose set bits are maximum among ' l ' and ' r ' ; Returns smallest number whose set bits are maximum in given range . ; Driver code
|
using System ; class GFG { static int countMaxSetBits ( int left , int right ) { while ( ( left | ( left + 1 ) ) <= right ) left |= left + 1 ; return left ; } static public void Main ( ) { int l = 1 ; int r = 5 ; Console . WriteLine ( countMaxSetBits ( l , r ) ) ; l = 1 ; r = 10 ; Console . WriteLine ( countMaxSetBits ( l , r ) ) ; } }
|
Largest number less than or equal to N in BST ( Iterative Approach ) | C # code to find the largest value smaller than or equal to N ; To create new BST Node ; To insert a new node in BST ; if tree is empty return new node ; if key is less then or greater then node value then recur down the tree ; return the ( unchanged ) node pointer ; Returns largest value smaller than or equal to key . If key is smaller than the smallest , it returns - 1. ; Driver code
|
using System ; using System . Collections . Generic ; class GFG { public class Node { public int key ; public Node left , right ; } ; static Node newNode ( int item ) { Node temp = new Node ( ) ; temp . key = item ; temp . left = temp . right = null ; return temp ; } static Node insert ( Node node , int key ) { if ( node == null ) return newNode ( key ) ; if ( key < node . key ) node . left = insert ( node . left , key ) ; else if ( key > node . key ) node . right = insert ( node . right , key ) ; return node ; } static int findFloor ( Node root , int key ) { Node curr = root , ans = null ; while ( curr != null ) { if ( curr . key <= key ) { ans = curr ; curr = curr . right ; } else curr = curr . left ; } if ( ans != null ) return ans . key ; return - 1 ; } public static void Main ( String [ ] args ) { int N = 25 ; Node root = new Node ( ) ; insert ( root , 19 ) ; insert ( root , 2 ) ; insert ( root , 1 ) ; insert ( root , 3 ) ; insert ( root , 12 ) ; insert ( root , 9 ) ; insert ( root , 21 ) ; insert ( root , 19 ) ; insert ( root , 25 ) ; Console . Write ( " { 0 } " , findFloor ( root , N ) ) ; } }
|
Find if given number is sum of first n natural numbers | C # program for finding s such that sum from 1 to s equals to n ; Function to find no . of elements to be added to get s ; Apply Binary search ; Find mid ; find sum of 1 to mid natural numbers using formula ; If sum is equal to n return mid ; If greater than n do r = mid - 1 ; else do l = mid + 1 ; If not possible , return - 1 ; Drivers code
|
using System ; public class GFG { static int findS ( int s ) { int l = 1 , r = ( s / 2 ) + 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; int sum = mid * ( mid + 1 ) / 2 ; if ( sum == s ) return mid ; else if ( sum > s ) r = mid - 1 ; else l = mid + 1 ; } return - 1 ; } static public void Main ( ) { int s = 15 ; int n = findS ( s ) ; if ( n == - 1 ) Console . WriteLine ( " - 1" ) ; else Console . WriteLine ( n ) ; } }
|
Check if a Binary String can be sorted in decreasing order by removing non | C # program for the above approach ; Function to sort the given string in decreasing order by removing the non adjacent characters ; Keeps the track whether the string can be sorted or not ; Traverse the given string S ; Check if S [ i ] and S [ i + 1 ] are both '1' ; Traverse the string S from the indices i to 0 ; If S [ j ] and S [ j + 1 ] is equal to 0 ; Mark flag false ; If flag is 0 , then it is not possible to sort the string ; Otherwise ; Driver code
|
using System ; class GFG { static string canSortString ( string S , int N ) { int flag = 1 ; int i , j ; for ( i = N - 2 ; i >= 0 ; i -- ) { if ( S [ i ] == '1' && S [ i + 1 ] == '1' ) { break ; } } for ( j = i ; j >= 0 ; j -- ) { if ( S [ j ] == '0' && S [ j + 1 ] == '0' ) { flag = 0 ; break ; } } if ( flag == 0 ) { return " No " ; } else { return " Yes " ; } } public static void Main ( string [ ] args ) { string S = "10101011011" ; int N = S . Length ; Console . WriteLine ( canSortString ( S , N ) ) ; } }
|
Rearrange array elements to maximize the sum of MEX of all prefix arrays | C # program for the above approach ; Function to find the maximum sum of MEX of prefix arrays for any arrangement of the given array ; Stores the final arrangement ; Sort the array in increasing order ; Iterate over the array arr [ ] ; Iterate over the array , arr [ ] and push the remaining occurrences of the elements into ans [ ] ; Print the array , ans [ ] ; Driver Code ; Given array ; Store the size of the array ; Function Call
|
using System ; class GFG { static void maximumMex ( int [ ] arr , int N ) { int [ ] ans = new int [ 2 * N ] ; Array . Sort ( ans ) ; int j = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( i == 0 arr [ i ] != arr [ i - 1 ] ) { j += 1 ; ans [ j ] = arr [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) { if ( i > 0 && arr [ i ] == arr [ i - 1 ] ) { j += 1 ; ans [ j ] = arr [ i ] ; } } for ( int i = 0 ; i < N ; i ++ ) Console . Write ( ans [ i ] + " β " ) ; } public static void Main ( string [ ] args ) { int [ ] arr = { 1 , 0 , 0 } ; int N = arr . Length ; maximumMex ( arr , N ) ; } }
|
Sort an array using Bubble Sort without using loops | C # program for the above approach ; Function to implement bubble sort without using loops ; Base Case : If array contains a single element ; Base Case : If array contains two elements ; Store the first two elements of the list in variables a and b ; Store remaining elements in the list bs ; Store the list after each recursive call ; If a < b ; Otherwise , if b >= a ; Recursively call for the list less than the last element and and return the newly formed list ; Driver Code ; Print the array
|
using System ; using System . Collections . Generic ; class GFG { static List < int > bubble_sort ( List < int > ar ) { List < int > temp = new List < int > ( ) ; if ( ar . Count <= 1 ) return ar ; if ( ar . Count == 2 ) { if ( ar [ 0 ] < ar [ 1 ] ) return ar ; else { temp . Add ( ar [ 1 ] ) ; temp . Add ( ar [ 0 ] ) ; return temp ; } } int a = ar [ 0 ] ; int b = ar [ 1 ] ; List < int > bs = new List < int > ( ) ; for ( int i = 2 ; i < ar . Count ; i ++ ) bs . Add ( ar [ i ] ) ; List < int > res = new List < int > ( ) ; if ( a < b ) { List < int > temp1 = new List < int > ( ) ; temp1 . Add ( b ) ; for ( int i = 0 ; i < bs . Count ; i ++ ) temp1 . Add ( bs [ i ] ) ; List < int > v = bubble_sort ( temp1 ) ; v . Insert ( 0 , a ) ; res = v ; } else { List < int > temp1 = new List < int > ( ) ; temp1 . Add ( a ) ; for ( int i = 0 ; i < bs . Count ; i ++ ) temp1 . Add ( bs [ i ] ) ; List < int > v = bubble_sort ( temp1 ) ; v . Insert ( 0 , b ) ; res = v ; } List < int > pass = new List < int > ( ) ; for ( int i = 0 ; i < res . Count - 1 ; i ++ ) pass . Add ( res [ i ] ) ; List < int > ans = bubble_sort ( pass ) ; ans . Add ( res [ res . Count - 1 ] ) ; return ans ; } public static void Main ( ) { List < int > arr = new List < int > { 1 , 3 , 4 , 5 , 6 , 2 } ; List < int > res = bubble_sort ( arr ) ; for ( int i = 0 ; i < res . Count ; i ++ ) Console . Write ( res [ i ] + " β " ) ; } }
|
Modify a given matrix by placing sorted boundary elements in clockwise manner | C # program for the above approach ; Function to print the elements of the matrix in row - wise manner ; Function to sort boundary elements of a matrix starting from the outermost to the innermost boundary and place them in a clockwise manner ; k - starting row index m - ending row index l - starting column index n - ending column index i - iterator ; Stores the current boundary elements ; Push the first row ; Push the last column ; Push the last row ; Push the first column ; Sort the boundary elements ; Update the first row ; Update the last column ; Update the last row ; Update the first column ; Print the resultant matrix ; Driver code ; Given matrix
|
using System ; using System . Collections . Generic ; class GFG { static void printMatrix ( List < List < int > > a ) { foreach ( List < int > x in a ) { foreach ( int y in x ) { Console . Write ( y + " β " ) ; } Console . WriteLine ( ) ; } } static void sortBoundaryWise ( List < List < int > > a ) { int i , k = 0 , l = 0 ; int m = a . Count , n = a [ 0 ] . Count ; int n_k = 0 , n_l = 0 , n_m = m , n_n = n ; while ( k < m && l < n ) { List < int > boundary = new List < int > ( ) ; for ( i = l ; i < n ; ++ i ) { boundary . Add ( a [ k ] [ i ] ) ; } k ++ ; for ( i = k ; i < m ; ++ i ) { boundary . Add ( a [ i ] [ n - 1 ] ) ; } n -- ; if ( k < m ) { for ( i = n - 1 ; i >= l ; -- i ) { boundary . Add ( a [ m - 1 ] [ i ] ) ; } m -- ; } if ( l < n ) { for ( i = m - 1 ; i >= k ; -- i ) { boundary . Add ( a [ i ] [ l ] ) ; } l ++ ; } boundary . Sort ( ) ; int ind = 0 ; for ( i = n_l ; i < n_n ; ++ i ) { a [ n_k ] [ i ] = boundary [ ind ++ ] ; } n_k ++ ; for ( i = n_k ; i < n_m ; ++ i ) { a [ i ] [ n_n - 1 ] = boundary [ ind ++ ] ; } n_n -- ; if ( n_k < n_m ) { for ( i = n_n - 1 ; i >= n_l ; -- i ) { a [ n_m - 1 ] [ i ] = boundary [ ind ++ ] ; } n_m -- ; } if ( n_l < n_n ) { for ( i = n_m - 1 ; i >= n_k ; -- i ) { a [ i ] [ n_l ] = boundary [ ind ++ ] ; } n_l ++ ; } } printMatrix ( a ) ; } static void Main ( ) { List < List < int > > matrix = new List < List < int > > ( ) ; matrix . Add ( new List < int > ( new int [ ] { 9 , 7 , 4 , 5 } ) ) ; matrix . Add ( new List < int > ( new int [ ] { 1 , 6 , 2 , - 6 } ) ) ; matrix . Add ( new List < int > ( new int [ ] { 12 , 20 , 2 , 0 } ) ) ; matrix . Add ( new List < int > ( new int [ ] { - 5 , - 6 , 7 , - 2 } ) ) ; sortBoundaryWise ( matrix ) ; } }
|
Minimum sum of absolute differences between pairs of a triplet from an array | C # Program for the above approach ; Function to find minimum sum of absolute differences of pairs of a triplet ; Sort the array ; Stores the minimum sum ; Traverse the array ; Update the minimum sum ; Print the minimum sum ; Driver Code ; Input ; Function call to find minimum sum of absolute differences of pairs in a triplet
|
using System ; using System . Collections . Generic ; class GFG { static int minimum_sum ( int [ ] A , int N ) { Array . Sort ( A ) ; int sum = 2147483647 ; for ( int i = 0 ; i <= N - 3 ; i ++ ) { sum = Math . Min ( sum , Math . Abs ( A [ i ] - A [ i + 1 ] ) + Math . Abs ( A [ i + 1 ] - A [ i + 2 ] ) ) ; } return sum ; } public static void Main ( ) { int [ ] A = { 1 , 1 , 2 , 3 } ; int N = A . Length ; Console . WriteLine ( minimum_sum ( A , N ) ) ; } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.