Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 27888c7

Browse files
authored
Add files via upload
1 parent 48d0930 commit 27888c7

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

‎Top_K_Elements/reorganize_string.py‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /