767. Reorganize String
Asked at 17Amazon78Google34Bloomberg30Microsoft30Meta20Tesla90DE Shaw69Roblox89Audible78Expedia54Agoda48Pinterest44Zoho42Salesforce35Oracle35IBM35Goldman Sachs21
Problem
Rearrange the letters of s so that no two adjacent characters are equal, and return any such arrangement, or "" if it's impossible.
Example: "aab" → "aba"; "aaab" → ""
Constraints: length ≤ 500.
Greedy: always place the most frequent char that isn't the previous one. With a max-heap, pop the top, append it, then push back the previous char (held out for one turn). Impossible if any count > ⌈n/2⌉.
Complexity: O(n log 26).
class Solution:
def reorganizeString(self, s: str) -> str:
h = [(-c, ch) for ch, c in Counter(s).items()]
heapify(h)
res, prev = [], None
while h:
c, ch = heappop(h)
res.append(ch)
if prev:
heappush(h, prev)
prev = (c + 1, ch) if c + 1 < 0 else None
return "".join(res) if not prev else ""
r = Solution().reorganizeString("aab")
assert r == "aba"
assert Solution().reorganizeString("aaab") == ""
class Solution {
public String reorganizeString(String s) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) cnt[c - 'a']++;
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]); // {char, count}
for (int i = 0; i < 26; i++) if (cnt[i] > 0) pq.add(new int[]{i, cnt[i]});
StringBuilder sb = new StringBuilder();
int[] prev = null;
while (!pq.isEmpty()) {
int[] cur = pq.poll();
sb.append((char) ('a' + cur[0]));
if (prev != null) pq.add(prev);
prev = --cur[1] > 0 ? cur : null;
}
return prev == null ? sb.toString() : "";
}
}
type charCount struct {
n int
ch byte
}
type countHeap []charCount // most frequent first
func (h countHeap) Len() int { return len(h) }
func (h countHeap) Less(i, j int) bool { return h[i].n > h[j].n }
func (h countHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *countHeap) Push(x any) { *h = append(*h, x.(charCount)) }
func (h *countHeap) Pop() any {
old := *h
x := old[len(old)-1]
*h = old[:len(old)-1]
return x
}
func reorganizeString(s string) string {
var cnt [26]int
for i := 0; i < len(s); i++ {
cnt[s[i]-'a']++
}
h := &countHeap{}
for i, n := range cnt {
if n > 0 {
heap.Push(h, charCount{n, byte('a' + i)})
}
}
res := []byte{}
var prev *charCount // the letter just used waits one turn
for h.Len() > 0 {
cur := heap.Pop(h).(charCount)
res = append(res, cur.ch)
if prev != nil {
heap.Push(h, *prev)
prev = nil
}
if cur.n--; cur.n > 0 {
prev = &cur
}
}
if prev != nil { // a letter is left over with nothing to separate it
return ""
}
return string(res)
}