Find sub | C ++ 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 . ; Drivers code
#include <bits/stdc++.h> NEW_LINE #define ll  long long int NEW_LINE using namespace std ; void findSubstring ( string str , ll power ) { ll i ; unordered_map < ll , ll > map ; int curr_power = 0 ; int len = str . length ( ) ; for ( i = 0 ; i < len ; i ++ ) { curr_power = curr_power + ( str [ i ] - ' a ' + 1 ) ; if ( curr_power == power ) { cout << " Substring ▁ from ▁ index ▁ " << 0 << " ▁ to ▁ " << i << " ▁ has ▁ power ▁ " << power << endl ; return ; } if ( map . find ( curr_power - power ) != map . end ( ) ) { cout << " Substring ▁ from ▁ index ▁ " << map [ curr_power - power ] + 1 << " ▁ to ▁ " << i << " ▁ has ▁ power ▁ " << power << endl ; return ; } map [ curr_power ] = i ; } cout << " No ▁ substring ▁ with ▁ given ▁ power ▁ exists . " ; } int main ( ) { string str = " geeksforgeeks " ; ll power = 36 ; findSubstring ( str , power ) ; return 0 ; }