/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 35ms 17.41 MiB
#2 Accepted 49ms 18.277 MiB
#3 Accepted 50ms 18.586 MiB
#4 Accepted 49ms 18.531 MiB
#5 Accepted 48ms 18.551 MiB
#6 Accepted 48ms 18.539 MiB
#7 Accepted 47ms 18.289 MiB
#8 Accepted 48ms 18.492 MiB
#9 Accepted 40ms 18.203 MiB
#10 Accepted 48ms 18.504 MiB
#11 Accepted 52ms 18.336 MiB
#12 Accepted 54ms 18.184 MiB
#13 Accepted 53ms 18.684 MiB
#14 Accepted 53ms 18.719 MiB
#15 Accepted 51ms 18.566 MiB

Code

# ruff: noqa: E731, E741
import sys

read = sys.stdin.readline
input = lambda: read().rstrip()
ir = lambda: int(read())
rir = lambda: range(int(read()))
mir = lambda: map(int, read().split())
lmir = lambda: list(map(int, read().split()))

DUMMY = 99


def solve():
    s = [ord(c) - 97 for c in input()]
    n = len(s)
    cnt = [0] * 26
    for c in s:
        cnt[c] += 1
    m = max(cnt)
    if 2 * m > n + 1:
        return

    res = []
    prev = None
    for i in range(n):
        cur = DUMMY
        for j in range(26):
            if j == prev or cnt[j] == 0:
                continue
            if cnt[j] * 2 == n - i + 1:
                cur = j
                break
            if cur == DUMMY:
                cur = j
        # try:
        cnt[cur] -= 1
        # except:
        #     print(cnt)
        #     print("".join(chr(c + 97) for c in res))
        #     print(prev, cur)
        #     raise
        prev = cur
        res.append(cur)
    return "".join(chr(c + 97) for c in res)


def main():
    for _ in rir():
        print(solve() or -1)


def test():
    pass


if __name__ == "__main__":
    if sys.stdin.isatty():
        test()
    else:
        main()

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:43:54
Judged At
2025-07-14 15:43:54
Judged By
Score
100
Total Time
54ms
Peak Memory
18.719 MiB