-1

In one of my recent interviews I was given a question as follows -

Divide the string into substrings with repeating characters, such that

Example 1

Input : ababccdecfg
Output : [abab, ccdec, f, g]

Example 2

Input : bbbb
Output : [bbbb]

Example 3

Input : abcd
Output : [a, b, c, d]

Signature of the function was

std::vector<std::string> Split(std::string str)
{ //write code here }

Initially, I tried to approach it using sliding window and then using recursion. The more I thought about it, it got more complicated and I eventually gave up.

I am looking for suggestions on how to approach it. Any help is appreciated. Thank you.

  • I might understand why `abab` is taken as a whole, but what about `ccdec`? The `c` is repeating, but the other 3 letters are not. I think you need to clarify. – Enlico May 12 '21 at 10:12
  • 1
    This question is basically asking that find the smallest substring which contains all the occurrences of the characters present in it. So you just need to find the last occurrence of every character and keep appending in the current substring – risingStark May 12 '21 at 11:53
  • 1
    @Enlico ccdec is included because c appears once more, thus including "de" in it. For example, ```abac``` would split into [aba, c]. – Aditya Sahu May 12 '21 at 17:13
  • @risingStark That's what I thought at first too. Lost track of how I would check for the letters in "temp". And couldn't come up with a possible solution. Thanks a lot for this, much appreciated. – Aditya Sahu May 12 '21 at 17:27

1 Answers1

0
std::vector<std::string> Split(std::string str){
    std::vector<std::string> ans;
    std::vector<int> freq(26, 0);
    int i=0, n = (int)str.size();
    for(int i=0;i<n;i++){
        freq[str[i]-'a']=i;
    }
    while(i<n){
        std::string temp = "";
        int m = freq[str[i]-'a'];
        temp.push_back(str[i]);
        i++;
        while(i<=m){
            temp.push_back(str[i]);
            m=max(m, freq[str[i]-'a']);
            i++;
        }
        ans.push_back(temp);
    }
    return ans;
}
risingStark
  • 1,153
  • 10
  • 17