|
| 1 | +# importing libraries |
| 2 | +from collections import Counter |
| 3 | +import heapq |
| 4 | + |
| 5 | +def reorganize_string(str): |
| 6 | + |
| 7 | + char_counter = Counter(str) |
| 8 | + most_freq_chars = [] |
| 9 | + |
| 10 | + for char, count in char_counter.items(): |
| 11 | + most_freq_chars.append([-count, char]) |
| 12 | + |
| 13 | + heapq.heapify(most_freq_chars) |
| 14 | + |
| 15 | + previous = None |
| 16 | + result = "" |
| 17 | + |
| 18 | + while len(most_freq_chars) > 0 or previous: |
| 19 | + |
| 20 | + if previous and len(most_freq_chars) == 0: |
| 21 | + return "" |
| 22 | + |
| 23 | + count, char = heapq.heappop(most_freq_chars) |
| 24 | + result = result + char |
| 25 | + count += 1 |
| 26 | + |
| 27 | + if previous: |
| 28 | + heapq.heappush(most_freq_chars, previous) |
| 29 | + previous = None |
| 30 | + |
| 31 | + if count != 0: |
| 32 | + previous = [count, char] |
| 33 | + |
| 34 | + return result |
| 35 | + |
| 36 | + |
| 37 | + |
| 38 | +# Time Complexity = O(n) |
| 39 | +# Space Complexity = O(1) |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | +############################################################################ |
| 44 | + |
| 45 | + |
| 46 | + |
| 47 | +# Driver code |
| 48 | +def main(): |
| 49 | + test_cases = ["programming", "hello", "fofjjb", |
| 50 | + "abbacdde", "aba", "awesome", "aaab"] |
| 51 | + for i in range(len(test_cases)): |
| 52 | + print(i+1, '. \tInput string: "', test_cases[i], '"', sep="") |
| 53 | + temp = reorganize_string(test_cases[i]) |
| 54 | + print('\tReorganized string: "', temp + '"' if temp else '"', sep="") |
| 55 | + print("-"*100) |
| 56 | + |
| 57 | + |
| 58 | +if __name__ == '__main__': |
| 59 | + main() |
| 60 | + |
| 61 | + |
0 commit comments