def rearange_string(S):
    from collections import Counter
    import heapq
    
    if not S:
        return ""
    
    counts = Counter(S)
    max_count = max(counts.values())
    
    # If any character appears more than (len+1)//2 times, impossible
    if max_count > (len(S) + 1) // 2:
        return ""
    
    # Use a max heap to always pick the most frequent character
    heap = [(-count, char) for char, count in counts.items()]
    heapq.heapify(heap)
    
    result = []
    
    while len(heap) >= 2:
        count1, char1 = heapq.heappop(heap)
        count2, char2 = heapq.heappop(heap)
        
        result.append(char1)
        result.append(char2)
        
        if count1 + 1 < 0:
            heapq.heappush(heap, (count1 + 1, char1))
        if count2 + 1 < 0:
            heapq.heappush(heap, (count2 + 1, char2))
    
    if heap:
        count, char = heapq.heappop(heap)
        result.append(char)
    
    return "".join(result)