C interview question---run-length coding of strings -


a friend of mine asked following question yahoo interview:

given string of form "abbccc" print "a1b2c3". write function takes string , return string. take care of special cases.

how experts code it?

thanks lot

there's more 1 way it, i'd run on input string twice: once count how many bytes required output, allocate output buffer , go again generate output.

another possibility allocate front twice number of bytes in input string (plus one), , write output that. keeps code simpler, potentially wasteful of memory. since operation looks rudimentary compression (rle), perhaps it's best first implementation doesn't have output occupy double memory of input.

another possibility take single pass, , reallocate output string necessary, perhaps increasing size exponentially ensure o(n) overall performance. quite fiddly in c, not initial implementation of function, in interview conditions. it's not faster first version.

however it's done, obvious "special case" empty input string, because obvious (to me) implementation start storing first character, enter loop. it's easy write output may ambiguous: "1122" output input "122", perhaps output input consisting of 122 1 characters. might want limit run lengths @ 9 characters (assuming base 10 representation) prevent ambiguity. depends function - conjuring complete function specification single example input , output not possible.

there's more 1 way design interface: question says "returns string", presumably that's nul-terminated string in buffer newly-allocated malloc. in long run, though, that's not great way write string apis. in real project prefer design function takes input string process, pointer output buffer , length of buffer. returns either number of bytes written, or if output buffer isn't big enough returns number have been written. implementing stated function using new function easy:

char *stated_function(const char *in) {     size_t sz = new_function(in, null, 0);     char *buf = malloc(sz);     if (buf) new_function(in, buf, sz);     return buf; } 

i'm confused "print" means in question - other answerers have taken mean "write stdout", meaning no allocation necessary. interviewer want function prints encoded string and returns it? prints , returns else? returns string, , using "print" when don't mean it?


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -