kdn251 / interviews

Everything you need to know to get the job.
https://www.youtube.com/channel/UCKvwPt6BifPP54yzH99ff1g?view_as=subscriber
MIT License
62.72k stars 12.83k forks source link

run length encoding #109

Open knasim opened 5 years ago

knasim commented 5 years ago

Uber:

Classic run length encoding problem. Given an alphanumeric input - you are to apply run length encoding to encode the input argument.

Caveat:
The encoded value has to be <= input length. Should pass test case for following inputs: abcde 141414

knasim commented 5 years ago

The following does not work in all cases. so solution has to be better than this:

    `
    StringBuilder compressed = new StringBuilder();
    int len = input.length();

    for(int i=0; i < len; i++) {
        int counter = 1;
        while(i < len-1 && input.charAt(i) == input.charAt(i+1)) {
            i++;
            counter++;
        }
        compressed.append(counter);
        compressed.append(input.charAt(i));
    }
    return compressed.toString();

`

ctfloyd commented 5 years ago

The solution that is immediately obvious to me is to only append the counter variable to the string if counter > 1 (there was a run).

if(counter > 1) compressed.append(counter);
compressed.append(input.charAt(i));

If there are no runs in a string, the output will simply be the input string.

Without much context, I'm not sure if this fits the criteria of the problem, because it's not truly RLE, but it is a potential solution.