|
| 1 | +# 767. Reorganize String |
| 2 | + |
| 3 | +## Greedy Heap Solution |
| 4 | +- Runtime: O(Nlog(N)) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of characters in string |
| 7 | + |
| 8 | +Playing around with different examples like 'aabb', 'aabbc', 'aabbcc' or 'aaabbc'. |
| 9 | +We can see a pattern where a greedy approach can be taken. |
| 10 | +We can build the string by taking the most occurring element. |
| 11 | +This leads us to using a max heap to determine this. |
| 12 | +We will need a dictionary to count the occurrences and use that to store tuples of (occurrences, character) pairs into the heap. |
| 13 | + |
| 14 | +Another thing we notice is that there can be a scenario where the most occurring element on top of the heap is the same as the last character we just used to build the string, for example, 'aaaabb'. This means that we need to pop two elements from the heap to guarantee that we can use one of these characters. |
| 15 | + |
| 16 | +Last case is when we cannot build a valid string. |
| 17 | +This can be determined if the occurrence of the last element in the heap is of one or not after the above sub-solution has be done processing and created the longest valid string possible. |
| 18 | + |
| 19 | +``` |
| 20 | +from collections import Counter |
| 21 | +
|
| 22 | +class Solution: |
| 23 | + def reorganizeString(self, S: str) -> str: |
| 24 | + counter = Counter(S) |
| 25 | + max_heap = list((-v, k) for k, v in counter.items()) |
| 26 | + heapq.heapify(max_heap) |
| 27 | + str_builder = list() |
| 28 | + while len(max_heap) >= 2: |
| 29 | + val1, ch1 = heapq.heappop(max_heap) |
| 30 | + val2, ch2 = heapq.heappop(max_heap) |
| 31 | + if len(str_builder) == 0 or (len(str_builder) and str_builder[-1] != ch1): |
| 32 | + str_builder.append(ch1) |
| 33 | + if val1 != -1: |
| 34 | + heapq.heappush(max_heap, (val1+1, ch1)) |
| 35 | + else: |
| 36 | + heapq.heappush(max_heap, (val1, ch1)) |
| 37 | + if len(str_builder) and str_builder[-1] != ch2: |
| 38 | + str_builder.append(ch2) |
| 39 | + if val2 != -1: |
| 40 | + heapq.heappush(max_heap, (val2+1, ch2)) |
| 41 | + else: |
| 42 | + heapq.heappush(max_heap, (val2, ch2)) |
| 43 | + if len(max_heap): # last node in heap |
| 44 | + val, ch = heapq.heappop(max_heap) |
| 45 | + if val != -1: |
| 46 | + return '' |
| 47 | + else: |
| 48 | + str_builder.append(ch) |
| 49 | + return ''.join(str_builder) |
| 50 | +``` |
0 commit comments