codeparrot/xlcost-text-to-code huggingface dataset:
LCA for general or n | Program to find LCA of n1 and n2 using one DFS on the Tree ; Maximum number of nodes is 100000 and nodes are numbered from 1 to 100000 ; storing root to node path ; storing the path from root to node ; pushing current node into the path ; node found ; terminating the path ; This Function compares the path from root to ' a ' & root to ' b ' and returns LCA of a and b . Time Complexity : O ( n ) ; trivial case ; setting root to be first element in path ; calculating path from root to a ; calculating path from root to b ; runs till path 1 & path 2 mathches ; returns the last matching node in the paths ; Driver code ; Number of nodes
import java . util . * ; class GFG { static final int MAXN = 100001 ; static Vector < Integer > [ ] tree = new Vector [ MAXN ] ; static int [ ] [ ] path = new int [ 3 ] [ MAXN ] ; static boolean flag ; static void dfs ( int cur , int prev , int pathNumber , int ptr , int node ) { for ( int i = 0 ; i < tree [ cur ] . size ( ) ; i ++ ) { if ( tree [ cur ] . get ( i ) != prev && ! flag ) { path [ pathNumber ] [ ptr ] = tree [ cur ] . get ( i ) ; if ( tree [ cur ] . get ( i ) == node ) { flag = true ; path [ pathNumber ] [ ptr + 1 ] = - 1 ; return ; } dfs ( tree [ cur ] . get ( i ) , cur , pathNumber , ptr + 1 , node ) ; } } } static int LCA ( int a , int b ) { if ( a == b ) return a ; path [ 1 ] [ 0 ] = path [ 2 ] [ 0 ] = 1 ; flag = false ; dfs ( 1 , 0 , 1 , 1 , a ) ; flag = false ; dfs ( 1 , 0 , 2 , 1 , b ) ; int i = 0 ; while ( i < MAXN && path [ 1 ] [ i ] == path [ 2 ] [ i ] ) i ++ ; return path [ 1 ] [ i - 1 ] ; } static void addEdge ( int a , int b ) { tree [ a ] . add ( b ) ; tree [ b ] . add ( a ) ; } public static void main ( String [ ] args ) { for ( int i = 0 ; i < MAXN ; i ++ ) tree [ i ] = new Vector < Integer > ( ) ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 2 , 4 ) ; addEdge ( 2 , 5 ) ; addEdge ( 2 , 6 ) ; addEdge ( 3 , 7 ) ; addEdge ( 3 , 8 ) ; System . out . print ( " LCA ( 4 , ▁ 7 ) ▁ = ▁ " + LCA ( 4 , 7 ) + "NEW_LINE"); System . out . print ( " LCA ( 4 , ▁ 6 ) ▁ = ▁ " + LCA ( 4 , 6 ) + "NEW_LINE"); } }
LCA for general or n | Sparse Matrix DP approach to find LCA of two nodes ; pre - compute the depth for each node and their first parent ( 2 ^ 0 th parent ) time complexity : O ( n ) ; Dynamic Programming Sparse Matrix Approach populating 2 ^ i parent for each node Time complexity : O ( nlogn ) ; Returning the LCA of u and v Time complexity : O ( log n ) ; Step 1 of the pseudocode ; now depth [ u ] = = depth [ v ] ; Step 2 of the pseudocode ; driver function ; running dfs and precalculating depth of each node . ; Precomputing the 2 ^ i th ancestor for evey node ; calling the LCA function
import java . util . * ; class GFG { static final int MAXN = 100000 ; static final int level = 18 ; @ SuppressWarnings ( " unchecked " ) static Vector < Integer > [ ] tree = new Vector [ MAXN ] ; static int [ ] depth = new int [ MAXN ] ; static int [ ] [ ] parent = new int [ MAXN ] [ level ] ; static void dfs ( int cur , int prev ) { depth [ cur ] = depth [ prev ] + 1 ; parent [ cur ] [ 0 ] = prev ; for ( int i = 0 ; i < tree [ cur ] . size ( ) ; i ++ ) { if ( tree [ cur ] . get ( i ) != prev ) dfs ( tree [ cur ] . get ( i ) , cur ) ; } } static void precomputeSparseMatrix ( int n ) { for ( int i = 1 ; i < level ; i ++ ) { for ( int node = 1 ; node <= n ; node ++ ) { if ( parent [ node ] [ i - 1 ] != - 1 ) parent [ node ] [ i ] = parent [ parent [ node ] [ i - 1 ] ] [ i - 1 ] ; } } } static int lca ( int u , int v ) { if ( depth [ v ] < depth [ u ] ) { u = u + v ; v = u - v ; u = u - v ; } int diff = depth [ v ] - depth [ u ] ; for ( int i = 0 ; i < level ; i ++ ) if ( ( ( diff >> i ) & 1 ) == 1 ) v = parent [ v ] [ i ] ; if ( u == v ) return u ; for ( int i = level - 1 ; i >= 0 ; i -- ) if ( parent [ u ] [ i ] != parent [ v ] [ i ] ) { u = parent [ u ] [ i ] ; v = parent [ v ] [ i ] ; } return parent [ u ] [ 0 ] ; } static void addEdge ( int u , int v ) { tree [ u ] . add ( v ) ; tree [ v ] . add ( u ) ; } static void memset ( int value ) { for ( int i = 0 ; i < MAXN ; i ++ ) { for ( int j = 0 ; j < level ; j ++ ) { parent [ i ] [ j ] = - 1 ; } } } public static void main ( String [ ] args ) { memset ( - 1 ) ; for ( int i = 0 ; i < MAXN ; i ++ ) tree [ i ] = new Vector < Integer > ( ) ; int n = 8 ; addEdge ( 1 , 2 ) ; addEdge ( 1 , 3 ) ; addEdge ( 2 , 4 ) ; addEdge ( 2 , 5 ) ; addEdge ( 2 , 6 ) ; addEdge ( 3 , 7 ) ; addEdge ( 3 , 8 ) ; depth [ 0 ] = 0 ; dfs ( 1 , 0 ) ; precomputeSparseMatrix ( n ) ; System . out . print ( " LCA ( 4 , ▁ 7 ) ▁ = ▁ " + lca ( 4 , 7 ) + "NEW_LINE"); System . out . print ( " LCA ( 4 , ▁ 6 ) ▁ = ▁ " + lca ( 4 , 6 ) + "NEW_LINE"); } }
Longest Common Extension / LCE | Set 1 ( Introduction and Naive Method ) | A Java Program to find the length of longest common extension using Naive Method ; Structure to represent a query of form ( L , R ) ; A utility function to find longest common extension from index - L and index - R ; A function to answer queries of longest common extension ; Driver code ; LCA Queries to answer
import java . util . * ; class GFG { static class Query { int L , R ; Query ( int L , int R ) { this . L = L ; this . R = R ; } } ; static int LCE ( String str , int n , int L , int R ) { int length = 0 ; while ( R + length < n && str . charAt ( L + length ) == str . charAt ( R + length ) ) length ++ ; return ( length ) ; } static void LCEQueries ( String str , int n , Query q [ ] , int m ) { for ( int i = 0 ; i < m ; i ++ ) { int L = q [ i ] . L ; int R = q [ i ] . R ; System . out . printf ( "LCE (%d, %d) = %dNEW_LINE", L, R, LCE ( str , n , L , R ) ) ; } return ; } public static void main ( String [ ] args ) { String str = " abbababba " ; int n = str . length ( ) ; Query q [ ] = new Query [ 3 ] ; q [ 0 ] = new Query ( 1 , 2 ) ; q [ 1 ] = new Query ( 1 , 6 ) ; q [ 2 ] = new Query ( 0 , 5 ) ; int m = q . length ; LCEQueries ( str , n , q , m ) ; } }
Time Complexity and Space Complexity | Java program for the above approach ; Function to find a pair in the given array whose sum is equal to z ; Iterate through all the pairs ; Check if the sum of the pair ( a [ i ] , a [ j ] ) is equal to z ; Driver code ; Given Input ; Function Call
import java . lang . * ; import java . util . * ; class GFG { static boolean findPair ( int a [ ] , int n , int z ) { for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < n ; j ++ ) if ( i != j && a [ i ] + a [ j ] == z ) return true ; return false ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , - 2 , 1 , 0 , 5 } ; int z = 0 ; int n = a . length ; if ( findPair ( a , n , z ) ) System . out . println ( " True " ) ; else System . out . println ( " False " ) ; } }
Analysis of Algorithms | Big | Java program for the above approach ; Function to print all possible pairs ; Driver code ; Given array ; Store the size of the array ; Function Call
import java . lang . * ; import java . util . * ; class GFG { static void print ( int a [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { if ( i != j ) System . out . println ( a [ i ] + " ▁ " + a [ j ] ) ; } } } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 3 } ; int n = a . length ; print ( a , n ) ; } }
Maximum sum obtained by dividing Array into several subarrays as per given conditions | Java program for the above approach ; Function to find the required answer ; Stores maximum sum ; Adding the difference of elements at ends of increasing subarray to the answer ; Driver Code ; Input ; Function calling
import java . io . * ; class GFG { public static int maximumSum ( int arr [ ] , int N ) { int Sum = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] > arr [ i - 1 ] ) Sum += ( arr [ i ] - arr [ i - 1 ] ) ; } return Sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 3 } ; int N = arr . length ; System . out . println ( maximumSum ( arr , N ) ) ; } }
Maximum count of X that can be inserted with no 3 adjacent characters are X | Java program for the above approach ; Utility function to find maximum count of X that are to be inserted into str such that no three consecutive characters are equal to X ; Stores count of consecutive X ; Stores count of characters which is not equal to X ; Iterate over characters of string , str ; If current character is X ; Update countX ; If countX is less than 3 ; Update countNotX ; Update countX ; If countX is greater than or equal to 3 ; Function to find maximum count of X that are to be inserted into str such that no three consecutive characters are equal to X ; Print the answer ; Driver Code ; Given string ; Function Call
import java . util . * ; public class Main { static int maxNumberOfXAddedUtil ( String str , char X ) { int countX = 0 ; int countNotX = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) == X ) { countX ++ ; } else if ( countX < 3 ) { countNotX ++ ; countX = 0 ; } } if ( countX >= 3 ) return - 1 ; else return 2 * ( countNotX + 1 ) - ( str . length ( ) - countNotX ) ; } static void maxNumberOfXAdded ( String str , char X ) { int ans = maxNumberOfXAddedUtil ( str , X ) ; System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String str = " xxyxy " ; char X = X ; maxNumberOfXAdded ( str , X ) ; } }
Examples of Big | Java program to illustrate time complexity for single for - loop ; Driver Code ; This loop runs for N time ; This loop runs for M time
class GFG { public static void main ( String [ ] args ) { int a = 0 , b = 0 ; int N = 4 , M = 4 ; for ( int i = 0 ; i < N ; i ++ ) { a = a + 10 ; } for ( int i = 0 ; i < M ; i ++ ) { b = b + 40 ; } System . out . print ( a + " ▁ " + b ) ; } }
The Slowest Sorting Algorithms | Java program for the stooge sort ; Function to implement stooge sort ; Base Case ; If first element is smaller than last element , swap them ; If there are more than 2 elements in the array ; Recursively sort the first 2 / 3 elements ; Recursively sort the last 2 / 3 elements ; Recursively sort the first 2 / 3 elements again ; Driver Code ; Function Call ; Display the sorted array
class GFG { static void stoogesort ( int arr [ ] , int l , int h ) { if ( l >= h ) return ; if ( arr [ l ] > arr [ h ] ) { int temp = arr [ l ] ; arr [ l ] = arr [ h ] ; arr [ h ] = temp ; } if ( h - l + 1 > 2 ) { int t = ( h - l + 1 ) / 3 ; stoogesort ( arr , l , h - t ) ; stoogesort ( arr , l + t , h ) ; stoogesort ( arr , l , h - t ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 5 , 3 , 1 } ; int N = arr . length ; stoogesort ( arr , 0 , N - 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } }
Time | Java program to find Nth Fibonacci number using recursion ; Function to find Nth Fibonacci term ; Base Case ; Recursively computing the term using recurrence relation ; Driver Code ; Function Call
class GFG { static int Fibonacci ( int N ) { if ( N < 2 ) return N ; return Fibonacci ( N - 1 ) + Fibonacci ( N - 2 ) ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . print ( Fibonacci ( N ) ) ; } }
Determine winner of the Game by arranging balls in a row | Java program for the above approach ; Function to find the winner of the Game by arranging the balls in a row ; Check if small balls are greater or equal to the large ones ; X can place balls therefore scores n - 1 ; Condition if large balls are greater than small ; X can have m - 1 as a score since greater number of balls can only be adjacent ; Compare the score ; Driver Code ; Given number of small balls ( N ) and number of large balls ( M ) ; Function call
class GFG { static void findWinner ( int n , int m ) { int X = 0 ; int Y = 0 ; if ( n >= m ) { X = n - 1 ; Y = m ; } else { X = m - 1 ; Y = n ; } if ( X > Y ) System . out . print ( " X " ) ; else if ( Y > X ) System . out . print ( " Y " ) ; else System . out . print ( " - 1" ) ; } public static void main ( String [ ] args ) { int n = 3 , m = 1 ; findWinner ( n , m ) ; } }
Check if Pascal 's Triangle is possible with a complete layer by using numbers upto N | Java program for the above approach ; Function to check if Pascaltriangle can be made by N integers ; Find X ; If x is integer ; Driver Code ; Given number N ; Function call
class GFG { static void checkPascaltriangle ( int N ) { double x = ( Math . sqrt ( 8 * N + 1 ) - 1 ) / 2 ; if ( Math . ceil ( x ) - x == 0 ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } public static void main ( String [ ] args ) { int N = 10 ; checkPascaltriangle ( N ) ; } }
Count subarrays having sum of elements at even and odd positions equal | Java program for the above approach ; Function to count subarrays in which sum of elements at even and odd positions are equal ; Initialize variables ; Iterate over the array ; Check if position is even then add to sum then add it to sum ; else subtract it to sum ; Increment the count if the sum equals 0 ; Print the count of subarrays ; Driver Code ; Given array arr [ ] ; Size of the array ; Function call
import java . util . * ; class GFG { static void countSubarrays ( int arr [ ] , int n ) { int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int sum = 0 ; for ( int j = i ; j < n ; j ++ ) { if ( ( j - i ) % 2 == 0 ) sum += arr [ j ] ; else sum -= arr [ j ] ; if ( sum == 0 ) count ++ ; } } System . out . println ( count ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 6 , 4 , 2 } ; int n = arr . length ; countSubarrays ( arr , n ) ; } }
Find position of non | Java implementation to find count of placing non - attacking rooks on the N x N chessboard ; Function to find the count of placing non - attacking rooks on the N x N chessboard ; Count of the Non - attacking rooks ; Printing lexographically smallest configuration ; Driver Code ; Function Call
import java . util . Scanner ; public class P2Placerooks { static void findCountRooks ( int row [ ] , int col [ ] , int n , int k ) { int res = n - k ; System . out . println ( res + " ▁ " ) ; int ri = 0 , ci = 0 ; while ( res -- > 0 ) { while ( ri < k && row [ ri ] == 1 ) { ri ++ ; } while ( ci < k && col [ ci ] == 1 ) { ci ++ ; } System . out . println ( ( ri + 1 ) + " ▁ " + ( ci + 1 ) + " ▁ " ) ; ri ++ ; ci ++ ; } } public static void main ( String [ ] args ) { int n = 4 ; int k = 2 ; int row [ ] = { 1 , 2 } ; int col [ ] = { 4 , 2 } ; findCountRooks ( row , col , n , k ) ; } }
Check if a large number is divisible by a number which is a power of 2 | Java program for the above approach ; Function to check divisibility ; Calculate the number of digits in num ; Check if the length of the string is less than the powerOf2 then return false ; Check if the powerOf2 is 0 that means the given number is 1 and as every number is divisible by 1 so return true ; Find the number which is formed by the last n digits of the string where n = powerOf2 ; Check if the number formed is divisible by input num or not ; Driver Code ; Given number ; Function call
class GFG { static boolean checkIfDivisible ( String str , long num ) { long powerOf2 = ( int ) ( Math . log ( num ) / Math . log ( 2 ) ) ; if ( str . length ( ) < powerOf2 ) return false ; if ( powerOf2 == 0 ) return true ; long i , number = 0 ; int len = str . length ( ) ; for ( i = len - powerOf2 ; i < len ; i ++ ) { number += ( str . charAt ( ( int ) i ) - '0' ) * Math . pow ( 10 , powerOf2 - 1 ) ; powerOf2 -- ; } if ( number % num != 0 ) return false ; else return true ; } public static void main ( String [ ] args ) { String str = "213467756564" ; long num = 4 ; if ( checkIfDivisible ( str , num ) ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }
Check if given permutation of 1 to N can be counted in clockwise or anticlockwise direction | Java program to check clockwise or counterclockwise order in an array ; Comparing the first and last value of array ; If the Count is greater than 1 then it can 't be  represented in required order ; Driver code
class GFG { static boolean check_order ( int [ ] arr ) { int cnt = 0 ; for ( int i = 0 ; i < arr . length - 1 ; i ++ ) { if ( Math . abs ( arr [ i + 1 ] - arr [ i ] ) > 1 ) cnt ++ ; } if ( Math . abs ( arr [ 0 ] - arr [ arr . length - 1 ] ) > 1 ) cnt ++ ; if ( cnt > 1 ) return false ; return true ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 4 , 5 , 1 } ; if ( check_order ( arr ) ) System . out . print ( " YES " ) ; else System . out . print ( " NO " ) ; } }
Largest number M less than N such that XOR of M and N is even | Java program for the above problem . ; Function to find the maximum possible value of M ; Edge case ; M = N - 2 is maximum possible value ; Driver code
import java . util . * ; class GFG { static int getM ( int n ) { if ( n == 1 ) return - 1 ; else return n - 2 ; } public static void main ( String [ ] args ) { int n = 10 ; System . out . print ( getM ( n ) ) ; } }
Maximize profit in buying and selling stocks with Rest condition | Java program for the above problem ; If there is only one day for buying and selling no profit can be made ; Array to store Maxprofit by resting on given day ; Array to store Maxprofit by buying or resting on the given day ; Array to store Maxprofit by selling on given day ; Initially there will 0 profit ; Buying on 1 st day results in negative profit ; Zero profit since selling before buying isn 't possible ; max of profit on ( i - 1 ) th day by resting and profit on ( i - 1 ) th day by selling . ; max of profit by resting on ith day and buying on ith day . ; max of profit by selling on ith day ; maxprofit ; Driver Code
class GFG { static int maxProfit ( int prices [ ] , int n ) { if ( n <= 1 ) return 0 ; int rest [ ] = new int [ n ] ; int hold [ ] = new int [ 9 ] ; int sold [ ] = new int [ 9 ] ; rest [ 0 ] = 0 ; hold [ 0 ] = - prices [ 0 ] ; sold [ 0 ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { rest [ i ] = Math . max ( rest [ i - 1 ] , sold [ i - 1 ] ) ; hold [ i ] = Math . max ( hold [ i - 1 ] , rest [ i - 1 ] - prices [ i ] ) ; sold [ i ] = hold [ i - 1 ] + prices [ i ] ; } return Math . max ( rest [ n - 1 ] , sold [ n - 1 ] ) ; } public static void main ( String [ ] args ) { int price [ ] = { 2 , 4 , 5 , 0 , 2 } ; int n = price . length ; System . out . print ( maxProfit ( price , n ) + "NEW_LINE"); } }
Count of subarrays of size K having at least one pair with absolute difference divisible by K | Java implementation of the above approach ; Function to return the required number of subarrays ; Return number of possible subarrays of length K ; Driver Code
class GFG { static int findSubarrays ( int arr [ ] , int N , int K ) { return N - K + 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 3 , 2 , 17 , 18 } ; int K = 4 ; int N = arr . length ; System . out . print ( findSubarrays ( arr , N , K ) ) ; } }
Maximum length of subarray such that all elements are equal in the subarray | Java program for the above approach ; Function to find the longest subarray with same element ; Check if the elements are same then we can increment the length ; Reinitialize j ; Compare the maximum length e with j ; Return max length ; Driver Code ; Given array arr [ ] ; Function Call
import java . util . * ; class GFG { static int longest_subarray ( int arr [ ] , int d ) { int i = 0 , j = 1 , e = 0 ; for ( i = 0 ; i < d - 1 ; i ++ ) { if ( arr [ i ] == arr [ i + 1 ] ) { j = j + 1 ; } else { j = 1 ; } if ( e < j ) { e = j ; } } return e ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 } ; int N = arr . length ; System . out . print ( longest_subarray ( arr , N ) ) ; } }
Print all Strong numbers less than or equal to N | Java program for the above approach ; Store the factorial of all the digits from [ 0 , 9 ] ; Function to return true if number is strong or not ; Converting N to String so that can easily access all it 's digit ; sum will store summation of factorial of all digits of a number N ; Returns true of N is strong number ; Function to print all strong number till N ; Iterating from 1 to N ; Checking if a number is strong then print it ; Driver Code ; Given Number ; Function Call
class GFG { static int [ ] factorial = { 1 , 1 , 2 , 6 , 24 , 120 , 720 , 5040 , 40320 , 362880 } ; public static boolean isStrong ( int N ) { String num = Integer . toString ( N ) ; int sum = 0 ; for ( int i = 0 ; i < num . length ( ) ; i ++ ) { sum += factorial [ Integer . parseInt ( num . charAt ( i ) + " " ) ] ; } return sum == N ; } public static void printStrongNumbers ( int N ) { for ( int i = 1 ; i <= N ; i ++ ) { if ( isStrong ( i ) ) { System . out . print ( i + " ▁ " ) ; } } } public static void main ( String [ ] args ) throws java . lang . Exception { int N = 1000 ; printStrongNumbers ( N ) ; } }
Count of pairs in a given range with sum of their product and sum equal to their concatenated number | Java program to count all the possible pairs with X * Y + ( X + Y ) equal to number formed by concatenating X and Y ; Function for counting pairs ; Count possible values of Y ; Driver Code
import java . util . * ; class GFG { static int countPairs ( int A , int B ) { int countY = 0 , countX = ( B - A ) + 1 , next_val = 9 ; while ( next_val <= B ) { if ( next_val >= A ) { countY += 1 ; } next_val = next_val * 10 + 9 ; } return ( countX * countY ) ; } public static void main ( String args [ ] ) { int A = 1 ; int B = 16 ; System . out . print ( countPairs ( A , B ) ) ; } }
Minimum sprinklers required to water a rectangular park | Java program to find minimum number sprinklers required to cover the park ; Function to find the minimum number sprinklers required to water the park . ; General requirements of sprinklers ; If M is odd then add one additional sprinklers ; Driver code
class GFG { public static int solve ( int n , int m ) { int ans = n * ( m / 2 ) ; if ( m % 2 == 1 ) { ans += ( n + 1 ) / 2 ; } return ans ; } public static void main ( String args [ ] ) { int N = 5 ; int M = 3 ; System . out . println ( solve ( N , M ) ) ; } }
Queries to find frequencies of a string within specified substrings | Java program to find frequency of a string K in a substring [ L , R ] in S ; Store the frequency of string for each index ; Compute and store frequencies for every index ; Driver code
class GFG { static int max_len = 100005 ; static int cnt [ ] = new int [ max_len ] ; public static void precompute ( String s , String K ) { int n = s . length ( ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { cnt [ i + 1 ] = cnt [ i ] ; if ( s . substring ( i , i + K . length ( ) ) . equals ( K ) ) { cnt [ i + 1 ] += 1 ; } } cnt [ n - 2 + 1 ] = cnt [ n - 2 ] ; } public static void main ( String [ ] args ) { String s = " ABCABCABABC " ; String K = " ABC " ; precompute ( s , K ) ; int Q [ ] [ ] = { { 1 , 6 } , { 5 , 11 } } ; for ( int it = 0 ; it < Q . length ; it ++ ) { System . out . println ( cnt [ Q [ it ] [ 1 ] - 1 ] - cnt [ Q [ it ] [ 0 ] - 1 ] ) ; } } }