/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 16ms 3.312 MiB
#2 Accepted 19ms 3.492 MiB
#3 Accepted 35ms 3.52 MiB
#4 Accepted 33ms 3.359 MiB
#5 Accepted 33ms 3.52 MiB
#6 Accepted 34ms 3.535 MiB
#7 Accepted 25ms 3.52 MiB
#8 Accepted 40ms 3.465 MiB
#9 Accepted 16ms 3.418 MiB
#10 Accepted 29ms 3.52 MiB
#11 Accepted 23ms 3.422 MiB
#12 Accepted 24ms 3.355 MiB
#13 Accepted 33ms 3.52 MiB
#14 Accepted 22ms 3.27 MiB
#15 Accepted 21ms 3.406 MiB

Code

from collections import Counter

def rearrange_lexicographically_smallest(s):
    count = Counter(s)
    n = len(s)
    max_freq = max(count.values())
    if max_freq > (n + 1) // 2:
        return "-1"
    
    result = []
    prev_char = ''
    
    for _ in range(n):
        found = False
        for c in sorted(count.keys()):
            if count[c] == 0 or c == prev_char:
                continue
            # فرض کنیم این کاراکتر را انتخاب کنیم
            count[c] -= 1
            # بررسی می‌کنیم که بعد از انتخاب، آیا امکان ادامه وجود دارد یا نه
            if max(count.values(), default=0) <= (n - len(result) - 1 + 1) // 2:
                result.append(c)
                prev_char = c
                found = True
                break
            # اگر انتخاب این حرف باعث مشکل شد، آن را برمی‌گردانیم
            count[c] += 1
        
        if not found:
            return "-1"
    
    return ''.join(result)

# دریافت ورودی و چاپ خروجی
T = int(input())
for _ in range(T):
    s = input().strip()
    print(rearrange_lexicographically_smallest(s))

Information

Submit By
Type
Submission
Problem
P1209 B. Rearrange the String
Contest
Educational Round 1
Language
Python 3 (Python 3.12.3)
Submit At
2025-07-14 15:43:41
Judged At
2025-07-14 15:43:41
Judged By
Score
100
Total Time
40ms
Peak Memory
3.535 MiB