/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 44ms 18.477 MiB
#2 Accepted 51ms 18.77 MiB
#3 Accepted 54ms 18.672 MiB
#4 Accepted 57ms 19.035 MiB
#5 Accepted 63ms 19.242 MiB
#6 Accepted 52ms 18.988 MiB
#7 Accepted 57ms 19.184 MiB
#8 Accepted 60ms 19.293 MiB
#9 Accepted 44ms 18.566 MiB
#10 Accepted 52ms 19.031 MiB
#11 Accepted 53ms 18.992 MiB
#12 Accepted 53ms 18.742 MiB
#13 Accepted 53ms 18.875 MiB
#14 Accepted 53ms 18.691 MiB
#15 Accepted 53ms 18.992 MiB

Code

import sys
from itertools import *
from bisect import *
from collections import *
from math import gcd
import heapq

input = lambda: sys.stdin.readline().rstrip("\r\n")
rint = lambda: int(input())
rlist = lambda: list(map(int, input().split()))
rgrid = lambda n: [rlist() for _ in range(n)]

fmin = lambda x, y: x if x < y else y
fmax = lambda x, y: x if x > y else y
# MOD = 998244353
MOD = 10**9 + 7
INF = float("inf")


def solve():
    # N = rint()
    S = input()
    n = len(S)

    count = [0] * 26
    for c in S:
        count[ord(c) - 97] += 1
    m = max(count)
    if m > (n + 1) // 2:
        return -1

    p = -1
    ans = []
    for i in range(n):
        for ci in range(26):
            if ci == p or count[ci] == 0:
                continue

            count[ci] -= 1
            m = n - (i + 1)
            if max(count) <= (m + 1) // 2:
                ans.append(chr(ci + 97))
                p = ci
                break
            count[ci] += 1
        else:
            return -1
    return "".join(ans)


TT = 1
TT = rint()
for tc in range(TT):
    ans = solve()

    print(ans)
    # print(*ans)
    # print("Yes" if ans else "No")

Information

Submit By
Type
Submission
Problem
P1209 B. Rearrange the String
Contest
Educational Round 1
Language
PyPy 3 (Python 3.9.18 PyPy 7.3.15)
Submit At
2025-07-14 15:36:27
Judged At
2025-07-14 15:36:27
Judged By
Score
100
Total Time
63ms
Peak Memory
19.293 MiB