Find time taken for signal to reach all positions in a string - C++


In this tutorial, we are going to write a program that computes the time taken for a signal to reach all positions in a string. Let me explain it with an example.

We will have a string that contains only s and p characters. s is a signal and p is a position in the string. A signal starts at s and travels in both left and right directions. We are assuming it takes one unit of time to travel to the next position in the string. Our task is to compute the time needed to convert all positions into signals.

Let's see some examples.

Input − pppppspss

Output − 5

Input − pspspsps

Output − 1

Input − ssssss

Output − 0

Let's see steps involved in solving the problem.

  • Initialize a string and a time (0)

  • Iterate over the string.

    • Count the continuous pcharacters and store the count in a variable.

    • If the current character is s and p count is greater than previous time then check whether s is present in the left side or not.

    • If s present in both sides, then divide the count into two halves as s can travel in both directions.

    • Reset the count of p.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int timeToConvertToSignalString(string sample_string, int string_len) {
   int p_count = 0, time = 0;
   for (int i = 0; i <= string_len; i++) {
      if (sample_string[i] == 'p') {
         p_count++;
      }
      else {
         if (p_count > time) {
            bool is_present_left_side = false;
            if (((i - p_count) > 0) && (sample_string[i - p_count - 1] == 's')) {
               is_present_left_side = 1;
            }
            if (is_present_left_side) {
               p_count = ceil((double)p_count / 2);
            }
            time = max(time, p_count);
         }
         p_count = 0;
      }
   }
   return time;
}
int main() {
   string sample_string = "pppppspss";
   int n = sample_string.size();
   cout << timeToConvertToSignalString(sample_string, n) << endl;
   return 0;
}

Output

If you execute the above program, then you will get the following result.

5

Try to run the program with a different case and check it.

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 29-Dec-2020

60 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements