Q.) REMOVE THE DUPLICATES FROM A STRING WITH O(N).
SOLUTION---
SOLUTION---
#include#include int main() { char str[400]; scanf("%s",str); int arr[128]; int i,d,len; for(i=0;i<128;i++) arr[i]=0; len=strlen(str); for(i=0;i<len;i++) { d=str[i]; arr[d]+=1; } for(i=0;i<len;i++) { d=str[i]; if(arr[d]!=0) { printf("%c",str[i]); arr[d]=0; } } return 0; }
if you have better solution post ur code with ur name in comment after that ur correct solution will updated on this blog with ur name.
5 comments:
Is there any reason that you set arr[d] to "0" in the second for loop?
for e.g
string is banana
then arr[97]=3
because there is three 'a'char in string
while traversibg the string from position i=0 to i=length(string)
when i=1 it print char 'a'
and set arr[97]=0
after that again at i=3 and i=5
we get char 'a' and checking arr[97]
but now its zero arr[97]=0 as we did in second loop if not then code print char 'a' three time as well as 2 times char 'b' .so for removing repeated char there is arr[d]=0 in second loop.
#include
int main()
{ char str[] = "sandeep jeevan";
int cnt=strlen(str),i=0,j=0;
for(i =0 ;i<cnt;i++)
{
for(j=i+1;j<cnt;j++)
{
if(str[i] == str[j])
{
while(j<cnt)
{
str[j] = str[j+1];
j++;
}
str[j] = "\0";
}
}
}
printf("STR:- %s\n",str);
}
Isn't what Sandy has gives o(n2)(order of n square) ??
yes @aash !!
Post a Comment