I came across an interview question that asked to remove a duplicate char from a given string in place. Therefore, if the input was “hi there,” the expected result was “hi.” It was also said to consider only alphabetical repetitions and all alphabets were in lower case. I came up with the following program. I have comments to make my logic clear. But the program does not work as expected for some inputs. If the input "hii" works, but if its "hello there", it fails. Please, help.
#include <stdio.h> int main() { char str[] = "programming is really cool"; // original string. char hash[26] = {0}; // hash table. int i,j; // loop counter. // iterate through the input string char by char. for(i=0,j=0;str[i];) { // if the char is not hashed. if(!hash[str[i] - 'a']) { // hash it. hash[str[i] - 'a'] = 1; // copy the char at index i to index j. str[j++] = str[i++]; } else { // move to next char of the original string. // do not increment j, so that later we can over-write the repeated char. i++; } } // add a null char. str[j] = 0; // print it. printf("%s\n",str); // "progamin s ely c" expected. return 0;
}
source share