Date and Time: Feb 16, 2025, 19:17 (EST)
Link: https://leetcode.com/problems/reorganize-string
Given a string s
, rearrange the characters of s
so that any two adjacent characters are not the same.
Return any possible rearrangement of s
or return ""
if not possible.
Example 1:
Input: s = "aab"
Output: "aba"
Example 2:
Input: s = "aaab"
Output: ""
-
1 <= s.length <= 500
-
s
consists of lowercase English letters.
-
Build hashmap for each char with their counts.
-
Convert hashmap into maxHeap with
[-counts, char]
. -
First pop the most frequent char
char1
frommaxHeap[]
, then append it toans[]
ifans[]
is empty orchar1 != ans[-1]
it doesn't equal to the last char inans[]
(avoid duplicate). If not, we are going pop the second most frequent charchar2
, but before we do that, we need to check ifmaxHeap[]
now is empty, if so, we return""
. Otherwise, we can appendchar2
. Don't forget to update thecounts + 1
after we appendchar1
orchar2
correspondingly. If we addchar2
, don't forget to put backchar1
with justcount1
.
class Solution:
def reorganizeString(self, s: str) -> str:
# Count each letter with frequency
# Use minHeap to place the most frequent letter first, then put the second most frequent letter
# Before we pop the 2nd letter, check if not minHeap, if so, and cnt for 1st char > 0, return ""
# TC: O(nlogk), n=len(s), k=#distinct chars in s, SC: O(k)
hashmap = {}
maxHeap = []
ans = ""
for i in s:
hashmap[i] = hashmap.get(i, 0) + 1
# Convert hashmap to maxHeap, O(klogk)
for key, cnts in hashmap.items():
heapq.heappush(maxHeap, [-cnts, key])
# Fill in ans
while maxHeap:
cnt1, c1 = heapq.heappop(maxHeap)
ans += c1
if len(maxHeap) > 0:
cnt2, c2 = heapq.heappop(maxHeap)
ans += c2
# Push back c2 if cnt2 > 1
if cnt2 < -1:
heapq.heappush(maxHeap, [cnt2+1, c2])
# When we have no c2 and cnt1 is more than 1, return ""
elif not maxHeap and cnt1 < -1:
return ""
# Push back c1
if cnt1 < -1:
heapq.heappush(maxHeap, [cnt1+1, c1])
return ans
Time Complexity:
Space Complexity: