Wednesday, July 19, 2006

Group Characters Together in Order

/**
Input will be a string. We need to o/p a string with the order of characters same as the input but with same characters grouped together.
I/P: abcdacde
O/P: aabccdde

I/P: kapilrajadurga
O/P: kaaaapilrrjdug

I/P: 1232
O/P: 1223
**/
I have found out two methods:
Method 1:
/**
Running Time: O(n*n*n)
Here we take one char see if there are any characters which equal it. If any two characters are equal we shift the array by 1 to the right(from the character till the first match) . and keep the matching element in that blank.
For example:
I/P: abcdead
Iteration 1: a bcded
Iteration 2: aabcded
Iteration 3: aabcded
Iteration 4: aabcded
Iteration 5: aabcd e
Iteration 6: aabcdde
Here Blank places mean that we shifted the array from that point till the first match from that point.

**/
main(int argc,char **argv)
{
int i = 0,j=0,k = 0;
int length = 0;
char *inputPtr;
char input[MAX_ALPHABET_LENGTH]={0};
int temp[MAX_ALPHABET_LENGTH]={0};
if(argc lessThan 2)
{
printf("Enter the input String as command line argument\n");
return;
}
strcpy(input,argv[1]);

inputPtr = input;
length = strlen(argv[1]);
printf("Method 1:\n");
printf("I/P: %s\n",inputPtr);

for(i=0;i lessThan length;i++)
{
for(j = i+1;j lessThan length; j++)
{
if(inputPtr[i] == inputPtr[j])
{
for(k = j; k greaterThan i; k-- )
{
inputPtr[k] = inputPtr[k-1];
}
inputPtr[i+1]=inputPtr[i];
}
}
}
printf("O/P: %s\n",inputPtr);

}
Method 2:
/**
Running Time: O(n) with O(1) constant space.
Here i am making the following assumption
1. The character set is limited to 256 characters.

Here we deploy hashing for this:
We have a bucket for 256 characters.
Step 1: We init the bucket to 0.
Step 2: We traverse through the input String and increment the corresponding bucket.
Step 3: We then traverse through the whole input array and check the order of the characters. So once we have printed the input character bucket[character] times then we make the bucket entry for that character to 0.

Though the last for loop seems to be O(n*n) actually it is O(n) only.
**/
main(int argc,char **argv)
{
int i = 0,j=0,k = 0;
int length = 0;
char *inputPtr;
char input[MAX_ALPHABET_LENGTH]={0};
int temp[MAX_ALPHABET_LENGTH]={0};
if(argc < 2)
{
printf("Enter the input String as command line argument\n");
return;
}

printf("Method 2:\n");
strcpy(input,argv[1]);
inputPtr = input;
length = strlen(argv[1]);
printf("I/P: %s %d\n",inputPtr,length);
for(i = 0; i lessThan length; i++)
{
temp[inputPtr[i]]++;
}
printf("O/P: ");
for( i = 0; i lessThan length ; i++ )
{
for(k=0; k lessThan temp[inputPtr[i]]; k++)
{
printf("%c",inputPtr[i]);
}
temp[inputPtr[i]]=0;
}
printf("\n");
}

1 comment:

Phani said...

in method -2 we are using a temp array so is it not O(n) extra space?