My Programming I class assigned an exercise in which we have to implement a function that counts the number of occurrences of a non-consecutive subsequence in a string. This is what we're asked to do:
To begin with, you have to implement a function such that, given a string s and three different characters c1, c2, c3 as parameters, returns how many times c1c2c3 occurs in s as (non-consecutive) subsequence. In other words, it returns the number of triples of indexes (i1,i2,i3) holding i1<i2<i3 and s[i1]=c1, s[i2]=c2, s[i3]=c3.
And this is the code I implemented:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int numberSubsequences(const string &s, char c1, char c2, char c3) {
int count = 0;
int lengthSequence = s.length();
for ( int i = 0; i < lengthSequence - 2; ++i ) {
if ( s[i] == c1 ) {
for ( int j = i + 1; j < lengthSequence - 1; ++j ) {
if ( s[j] == c2 ) {
for ( int k = j + 1; k < lengthSequence; ++k ) {
if ( s[k] == c3 ) {
count = count + 1;
}
}
}
}
}
}
return count;
}
The problem is that I submitted this code and the submission program we use said that I exceeded the time limit for some private cases. Is there a way to simplify this function so that it passes all cases? Any help is appreciated. :)
In order to avoid entirely doing your homework for you, here is a version which handles the case of two characters rather than three:
The main idea is to scan the input string only once, which is the best "big O" possible for this problem. At each position, we know how many times we have seen
c1, and if we seec2we accumulate the count ofc1which came before it.Extending this to three or more characters is an exercise for the reader.