Find sub-string with given power in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string str and an integer pow. Our task is to find a sub-string with given power.

We need to return the substring whose power is equal to pow.

Power of string is the sum of powers of its characters.

Power of character : a -> 1, b -> 2, c -> 3,...

Let's take an example to understand the problem,

Input : string = "programming" power = 49
Output : 'pro'

Explanation

Power of matrix : pro,
power(p) = 16
power(p) = 18
power(p) = 15
Total = 16 + 18 + 15 = 49

Solution Approach

A simple solution to the problem is using nested loops. We will loop through the string and using an inner loop, we will find substring. For each substring, we will calculate the power. And then check if it is equal to 'pow', return true if yes, otherwise return false.

An efficient approach to solve the problem is using the map to store power. We will calculate the power of substring and store it on the map. Check if a value exists in the map that can make the power equal to the required power. If yes, return true. Return false when all characters of the string are traversed and no value matching power is found.

Algorithm

  • Step 1 − Traverse the string and find the power (currPow).

  • Step 2 − If the value, (currPow - pow) exists in the map or not.

    • Step 2.1 − if yes, print -> substring.

  • Step 3 − Insert the value of currPow in the map.

  • Step 4 − If all characters of the string are traversed, print -> ‘not possible’.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
void findSubStringWithPower(string str, int power) {
   int i;
   unordered_map<int , int > powerSS;
   int currPower = 0;
   int N = str.length();
   for (i = 0; i < N; i++) {
      currPower = currPower + (str[i] - 'a' + 1);
      if (currPower == power) {
         cout<<"Substring : "<<str.substr((0), i+1)<<" has power "<<power;
         return;
      }
      if (powerSS.find(currPower - power) != powerSS.end()) {
         cout<<"Substring from index "<<str.substr((powerSS[currPower-power] + 1),(i - (powerSS[currPower - power] + 1)) + 1);
         cout<<" has power "<<power; return;
      }
      powerSS[currPower] = i;
   }
   cout<<"No substring found!";
}
int main() {
   string str = "programming";
   int power = 49;
   findSubStringWithPower(str, power);
   return 0;
}

Output

Substring : pro has power 49
raja
Updated on 25-Jan-2022 12:06:06

Advertisements