Pattern visualizer
Rearrange Characters
Treat each (character, count) pair as a node in a max-heap ordered by count. Repeatedly pulling the two most frequent characters left and placing them next to each other guarantees the dominant character never has to sit beside itself, as long as no character starts out more than (n+1)/2 of the string. Animated on: Rearrange the characters of a string so that no two adjacent characters are the same, or report it is impossible. s = "dcabab"..
Max-heap greedy alternation
Count every character in "dcabab": d:1, c:1, a:2, b:2. Max count is 2, and (n+1)/2 = 3, so a valid rearrangement is possible. Laid out in insertion order it is not yet a max-heap.
1FUNCTION rearrange(s):2 count <- FREQUENCY of each character in s3 IF MAX(count) > (LENGTH(s) + 1) / 2: RETURN ""4 heap <- BUILD max-heap of (char, count) pairs5 out <- EMPTY string6 WHILE SIZE(heap) >= 2:7 first, second <- EXTRACT-MAX(heap) TWICE8 APPEND first.char, second.char TO out9 DECREMENT first.count, second.count10 IF first.count > 0: INSERT first INTO heap11 IF second.count > 0: INSERT second INTO heap12 IF SIZE(heap) = 1: APPEND heap[0].char TO out13 RETURN out14END FUNCTION
← / → step · space play · Home restart