Find sub | Java program to find substring with given power ; Function to print indexes of substring with power as given power . ; Create an empty map ; Maintains sum of powers of characters so far . ; Add current character power to curr_power . ; If curr_power is equal to target power we found a substring starting from index 0 and ending at index i . ; If curr_power - power already exists in map then we have found a subarray with target power . ; If we reach here , then no substring exists . ; Driver Code
import java . util . * ; class GFG { static void findSubstring ( String str , int power ) { HashMap < Integer , Integer > map = new HashMap < > ( ) ; int curr_power = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { curr_power = curr_power + ( str . charAt ( i ) - ' a ' + 1 ) ; if ( curr_power == power ) { System . out . println ( " Substring ▁ from ▁ index ▁ 0" + " ▁ to ▁ " + i + " ▁ has ▁ power ▁ " + power ) ; return ; } if ( map . containsKey ( curr_power - power ) ) { System . out . println ( " Substring ▁ from ▁ index ▁ " + ( map . get ( curr_power - power ) + 1 ) + " ▁ to ▁ " + i + " ▁ has ▁ power ▁ " + power ) ; return ; } map . put ( curr_power , i ) ; } System . out . println ( " No ▁ substring ▁ with ▁ given ▁ power ▁ exists . " ) ; } public static void main ( String [ ] args ) { String str = " geeksforgeeks " ; int power = 36 ; findSubstring ( str , power ) ; } }