{x}
blog image

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: ""

 

Constraints:

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.

Problem Description

The problem asks to reorganize a given string s such that no two adjacent characters are the same. If such a reorganization is impossible, return an empty string.

Solution Explanation

The provided solutions use a greedy approach. The core idea is to prioritize characters that appear most frequently. If the most frequent character appears too many times (more than (n+1)/2 where n is the string length), reorganization is impossible. Otherwise, we can iteratively place the most frequent characters in the result string, ensuring that no two adjacent characters are identical.

Solution 1 (More Efficient):

This solution directly constructs the rearranged string using an array. It counts character frequencies, then iterates through the sorted frequencies, placing characters in the ans array with a stride of 2 (to ensure no adjacent duplicates). If an index goes beyond the array bounds, it wraps around to the next available index (starting at index 1).

Time Complexity: O(N log K), where N is the length of the string and K is the number of unique characters (due to sorting the character counts).

Space Complexity: O(K), to store character counts.

Solution 2 (Using Heap):

This solution utilizes a priority queue (heap) to maintain the characters in order of their frequencies. Characters are extracted from the heap, added to the result, and then added to a queue for a later iteration to ensure there is no adjacent same character. This approach manages the order more effectively than direct sorting in Solution 1, especially for larger alphabets or longer strings.

Time Complexity: O(N log K), where N is the string length and K is the number of unique characters. The heap operations dominate the runtime.

Space Complexity: O(K), for the heap and queue to store character frequencies and temporary data.

Code Explanation (Python Solution 1 - More concise and efficient)

from collections import Counter
 
class Solution:
    def reorganizeString(self, s: str) -> str:
        n = len(s)
        cnt = Counter(s)  # Count character frequencies
        mx = max(cnt.values())  # Find the maximum frequency
        if mx > (n + 1) // 2:  # Check if reorganization is impossible
            return ''
 
        ans = [None] * n  # Initialize the result array
        i = 0  # Index for placing characters
        for k, v in cnt.most_common():  # Iterate through characters by frequency
            while v:  # Place as many occurrences as possible
                ans[i] = k
                v -= 1
                i += 2  # Move to the next available even index
                if i >= n:
                    i = 1  # Wrap around to odd indices if necessary
 
        return ''.join(ans)  # Join the characters into a string
 

The code is well-commented and easy to follow. It efficiently constructs the reorganized string without unnecessary overhead. The other language solutions follow similar logic with appropriate data structure usage for their respective languages. The heap-based solution (Solution 2) provides a more robust solution for cases with a very high number of unique characters or when k (maximum distance between identical characters) is greater than 2. However, for the specific constraints of this problem (k=2), Solution 1 might be more efficient in practice due to its simpler implementation.