Given a sequence of heads and tails I want to count the number significant substrings in which the number of heads is not less than the number of tails. I want to achieve this in O(NlogN) time.
Example input:
[ 'H', 'T', 'H', 'T', 'T', 'H' ]
Example output:
11
Explanation:
{H} {H} {H}
{H, T} {T, H} {H, T} {T, H}
{H, T, H}
{H, T, H, T}
{H, T, T, H}
{H, T, H, T, T, H}
I believe my current algorithm is O(N^2). I solve the problem recursively, iterating with the list of coins sliced on either end.
Here is my current algorithm. How can I achieve O(NLogN) time?
def count_sequences( data ):
print go(range(0,len(data)),data)
seen = set()
def go(rang,data):
if tuple(rang) in seen: return 0
seen.add(tuple(rang))
h = 0
summ = 0
if len(rang)==0: return 0
for i in rang:
if data[i] == 'H': h += 1
summ += go(rang[1:],data)
summ += go(rang[:-1],data)
if len(rang) == 1:
if h ==1: return 1
else: return 0
if h > (len(rang)-1)/2 :
return 1 + summ
else: return summ