-
Notifications
You must be signed in to change notification settings - Fork 183
/
05 - Reverse Shuffle Merge.py
59 lines (43 loc) · 1.33 KB
/
05 - Reverse Shuffle Merge.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# ========================
# Information
# ========================
# Direct Link: https://www.hackerrank.com/challenges/reverse-shuffle-merge/problem
# Difficulty: Advanced
# Max Score: 50
# Language: Python
# ========================
# Solution
# ========================
import os
from collections import defaultdict
def frequency(s):
res = defaultdict(int)
for char in s:
res[char] += 1
return res
# Complete the reverseShuffleMerge function below.
def reverseShuffleMerge(s):
char_freq = frequency(s)
used_chars = defaultdict(int)
remain_chars = dict(char_freq)
res = []
def can_use(char):
return (char_freq[char] // 2 - used_chars[char]) > 0
def can_pop(char):
needed_chars = char_freq[char] // 2
return used_chars[char] + remain_chars[char] - 1 >= needed_chars
for char in reversed(s):
if can_use(char):
while res and res[-1] > char and can_pop(res[-1]):
removed_char = res.pop()
used_chars[removed_char] -= 1
used_chars[char] += 1
res.append(char)
remain_chars[char] -= 1
return "".join(res)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
RESULT = reverseShuffleMerge(s)
fptr.write(RESULT + '\n')
fptr.close()