I have a tuple of zeros and ones, for instance:
(1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1)
It turns out:
(1, 0, 1, 1, 1, 0, 1, 1, 1,
You can archive it in sublinear time by XOR'ing the rotated binary form for the input array:
input_binary
i = 1 to len(input_array)/2
, and for each loop, rotate the input_binary
to the right by i
bits, save it as rotated_bin
, then compare the XOR
of rotated_bin
and input_binary
.i
that yields 0, is the index to which is the desired substring.Complete code:
def get_substring(arr):
binary = ''.join(map(str, arr)) # join the elements to get the binary form
for i in xrange(1, len(arr) / 2):
# do a i bit rotation shift, get bit string sub_bin
rotated_bin = binary[-i:] + binary[:-i]
if int(rotated_bin) ^ int(binary) == 0:
return arr[0:i]
return None
if __name__ == "__main__":
test = [1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1]
print get_substring(test) # [1,0,1,1]