Reorganize String – Python 3 (Week 13 – 04)

heapq is a binary heap, with O(log n) push and O(log n) pop.

Solution 1

    for ct, cha in c:
        if -ct > (len(S) + 1) / 2:
            return ''

    ans = []
    while len(c) > 1:
        ct1, ch1 = heapq.heappop(c)
        ct2, ch2 = heapq.heappop(c)

        ans.append(ch1)
        ans.append(ch2)
        if ct1 + 1: heapq.heappush(c, (ct1 + 1, ch1))
        if ct2 + 1: heapq.heappush(c, (ct2 + 1, ch2))

    return ''.join(ans) + (c[0][1] if c else'')

Time O(n). Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started