7
\$\begingroup\$

A friend of mine got this question during an interview. The interview ended with no luck for him, but still, we're very curious to hear the solution. The question is as follows:

Modify the code below (change 3 lines maximum) so the function will return the length of the longest sequence of the same bit, if you would flip one bit in the given array. Note: the method's parameter is a bits array.

For example: take the bits array: "11001001010". By flipping the 5th bit from "1" to "0", we'll get: "11000001010" and the result would be: 5.

private static int solution(int[] a) {

    int n = a.length;
    int result = 0;
    int i;

    for (i = 0; i < n - 1; i++) {

        if(a[i] == a[i + 1])
            result = result  + 1;
    }
    int r = 0;
    for (i = 0; i < n; i++) {

        int count = 0;
        if(i > 0)   {
            if(a[i - 1] != a[i])
                count = count + 1;
            else
                count = count - 1;
        }
        if(i < n - 1)   {
            if(a[i + 1] != a[i])
                count = count + 1;
            else
                count = count - 1;
        }

        if(count > r)
            r = count;
    }

    return result + r;
}
\$\endgroup\$
  • 5
    \$\begingroup\$ Why is this off topic? This looks exactly like what the the tag wiki describes for for programming-puzzle. And we've had programming puzzles that are just solved, without additional scoring like fewest bytes. \$\endgroup\$ – xnor Jul 20 '15 at 10:28
  • 2
    \$\begingroup\$ I voted "unclear". What counts as changing a line? It seems that in principle this would allow dropping in a one-liner solution and using none of the supplied code at all. And what do you mean by "the length of the longest sequence of the same bit, if you would flip one bit in the given array"? I presume we have to interpret the int[] as a bit[] and maximise the longest sequence over each case of "flip bit X", but what endianness (or endiannesses - in some contexts it's different for the 4 bytes in an int and the 8 bits in a byte) should we use to interpret the int[] as a bit[]? \$\endgroup\$ – Peter Taylor Jul 20 '15 at 11:16
  • 3
    \$\begingroup\$ @Doorknob Isn't programming-puzzle relieved from that requirement, just like popularity-contest? \$\endgroup\$ – orlp Jul 20 '15 at 11:47
  • 1
    \$\begingroup\$ @orlp Popularity-contest is absolutely not relieved from that requirement (most votes is the primary objective winning criterion), nor is programming-puzzle to the best of my knowledge. Do you have a meta post or a tag wiki that is the source of that rule? \$\endgroup\$ – Doorknob Jul 20 '15 at 11:50
  • 3
    \$\begingroup\$ @Doorknob It would be rather strange if a site called "Programming Puzzles and Code Golf" does not actually allow programming puzzles. \$\endgroup\$ – xnor Jul 20 '15 at 19:54