Tuesday 31 October 2017

Super Reduced String Hacker Rank Solution in C/C++


Write a c program a string consisting of lowercase English alphabetic letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation. To do this, he will repeat the above operation as many times as it can be performed and to find & print’s non-reducible form. Note: If the final string is empty, print Empty String.
Input: aaabccddd
Output: abd
Input: baab
Output: Empty String

Solution in C:

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int main() 
{
    char* s = (char *)malloc(512000 * sizeof(char));
    scanf("%s", s);
    int l,i=0,flag;
   l=strlen(s);
   do    
   {
       flag=0;
       for(i=0;i<l-1;)
      {
           if(s[i]==s[i+1])
           {
                flag=1;
                for(int j=i;j<l-2;j++)
                     s[j]=s[j+2];
                 l=l-2;
            }
            else
                  i++;
       }
        s[l]='\0';
} while(flag==1&&l>0);
if(l!=0)
    printf("%s",s);
else  
    printf("Empty String");
    return 0;
}

Solution in C++

#include <iostream>
#include <string>
using namespace std;

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    string s;
    cin>>s;
    for(int i=1;i<s.length();i++)
    {
        if(s[i] == s[i-1])
        {
            s.erase(i-1,2);
            i=0;
        }
    }
    if(s.length() == 0)
        cout<<"Empty String";
    else
        cout<<s;
    return 0;
}

8 comments:

  1. In the above program, what does erase(i-1,2); do? explain about the arguments passed please.

    ReplyDelete
    Replies
    1. erase(i-1,2) - removes the two elements starting from index (i-1)

      Delete
  2. why is i again declared as 0

    ReplyDelete
  3. Because whenever we delete few characters of the string, the size of the string is changing, and also the indexes assigned for each remaining characters change. So after every deletion it is important to point our index to the beginning of the string.

    ReplyDelete
  4. how this code work if string is not sorted

    ReplyDelete
  5. can someone explain why i is declared as 0 inside the loop??

    ReplyDelete
    Replies
    1. Because whenever we delete few characters of the string, the size of the string is changing, and also the indexes assigned for each remaining characters change. So after every deletion it is important to point our index to the beginning of the string.

      Delete
  6. For traversing the string again from 0th index

    ReplyDelete