Taro Logo

Reorganize String

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+20
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
2.9K views
Topics:
StringsGreedy AlgorithmsArrays

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set does the string `s` consist of? For example, are we only dealing with lowercase English letters, or could it include uppercase letters, digits, and special characters?
  2. What is the maximum length of the string `s` that we need to handle?
  3. If there are multiple valid rearranged strings that satisfy the condition, does it matter which one I return, or is any valid rearrangement acceptable?
  4. Should I return an empty string `""` when it is impossible to reorganize the string so that no two adjacent characters are identical?
  5. How should I handle edge cases such as an empty string or a string of length 1?

Brute Force Solution

Approach

Imagine you have a collection of colored beads that you need to string together such that no two beads of the same color are right next to each other. The brute force approach involves exploring every possible order in which you could arrange the beads until you stumble upon a valid sequence.

Here's how the algorithm would work step-by-step:

  1. Start by generating a completely new ordering of all the beads from your pile.
  2. Lay out the beads in this specific order from the first position to the last.
  3. Examine every neighboring pair of beads in this layout to see if any two beads of the same color are touching each other.
  4. If you find even one pair of identical colors sitting side by side, reject this arrangement as invalid.
  5. If all neighboring pairs have different colors, you have successfully found a valid arrangement, so you can stop here and celebrate.
  6. If the arrangement is invalid, throw it away, go back to the drawing board, and try a completely different ordering of the beads.
  7. Repeat this process of guessing an order and checking it until you either find a successful arrangement or run out of possible orders to try.

Code Implementation

import itertools


def reorganize_string(input_string):
    character_list = list(input_string)
    
    # Generate every possible permutation to check all candidate arrangements exhaustively
    for candidate_permutation in itertools.permutations(character_list):
        is_arrangement_valid = True
        
        for current_index in range(len(candidate_permutation) - 1):
            if candidate_permutation[current_index] == candidate_permutation[current_index + 1]:
                is_arrangement_valid = False
                break
        
        # Early exit if we find any valid sequence satisfying the no-adjacent-duplicates rule
        if is_arrangement_valid:
            return "".join(candidate_permutation)
            
    # Return empty string if no valid arrangement exists after exhausting permutations
    return ""

Big(O) Analysis

Time Complexity
O(n * n!) – The brute force approach generates permutations of the string of length n, and there are n! possible unique orderings to try. For each generated ordering, we must examine all neighboring pairs, which takes linear time proportional to n. Multiplying the number of possible orderings by the cost of validating each one results in approximately n * n! total operations. Simplifying this expression yields a final time complexity of O(n * n!).
Space Complexity
O(N) – The brute force approach requires storing and evaluating permutations of the beads, where N is the total number of characters in the input string. The algorithm generates candidate orderings that require temporary storage structures proportional in size to N. Additionally, the recursion stack or permutation generator holds up to N elements at a time to track the current arrangement being tested. As the input string length N increases, the extra memory needed to hold these intermediate sequences grows linearly.

Optimal Solution

Approach

To successfully rearrange the characters so that no two identical neighbors touch, the optimal strategy prioritizes the most frequently appearing elements. By strategically placing the most common items first and interleaving them with other items, we prevent any potential clumping.

Here's how the algorithm would work step-by-step:

  1. Count how many times each character appears in the text so you know which ones are the most common.
  2. Sort the characters by their counts so the most frequent ones are at the front of your attention.
  3. Take the character that appears the most often and place it in the first available slot, but skip every other slot to leave room between them.
  4. Keep placing this most common character into alternating slots until you run out of them.
  5. Move on to the next most common character and fill in the remaining empty alternating slots.
  6. If you ever run out of alternating slots and still have characters left to place, wrap around to the beginning to fill the gaps.
  7. If at any point a single character appears so often that it takes up more than half of the total space, recognize that it is impossible to separate them and give up.

Code Implementation

from collections import Counter


def reorganize_string(input_string):
    character_counts = Counter(input_string)
    
    # We validate frequency first because any character exceeding half the length makes separation mathematically impossible.
    max_allowed_frequency = (len(input_string) + 1) // 2
    for char, freq in character_counts.items():
        if freq > max_allowed_frequency:
            return ""

    sorted_characters = sorted(input_string, key=lambda char: (-character_counts[char], char))
    result_array = [None] * len(input_string)
    
    current_index = 0
    # Alternating placement ensures identical characters are spaced out and never placed adjacently.
    for character in sorted_characters:
        result_array[current_index] = character
        current_index += 2
        
        # Wrapping around ensures remaining slots are filled seamlessly when even indices are exhausted.
        if current_index >= len(input_string):
            current_index = 1
            
    return "".join(result_array)

Big(O) Analysis

Time Complexity
O(n + k log k) – Counting the frequency of each character in the input string of size n takes O(n) time, where n is the length of the string and k is the number of unique characters. Sorting these unique characters by their counts requires O(k log k) operations. Placing the characters into alternating slots and filling the remaining gaps processes each of the n characters a constant number of times, taking O(n) time. Since the alphabet size k is fixed to at most 26 lowercase English letters, the k log k term becomes a constant, simplifying the total time complexity to O(n).
Space Complexity
O(N) – To implement the strategy of counting and arranging characters, we use a frequency hash map and an auxiliary result array of size N. The frequency map requires at most 26 entries for the English alphabet, which is constant space. However, the resulting string builder or character array scales directly with the input length N. Therefore, the total auxiliary space complexity is driven by the output storage and simplifies to Big O of N.

Edge Cases

Empty string or single character string
How to Handle:
Return the input string immediately as no adjacent characters can be identical.
String with all identical characters like aaa
How to Handle:
Detect that the most frequent character exceeds the threshold (n + 1) / 2 and return an empty string.
Two character string with identical characters like aa
How to Handle:
The frequency check correctly identifies that the count is too high and returns an empty string.
Two character string with distinct characters like ab
How to Handle:
Place them sequentially into the result array and return the valid reorganized string.
Highly skewed frequency where one character dominates like aaabc
How to Handle:
Greedily place the most frequent character at alternating even indices first, then fill odd indices.
Maximum length constraints up to the problem limit
How to Handle:
Use a linear time O(n) frequency array and greedy placement to scale efficiently without performance bottlenecks.
Cases where no valid rearrangement is possible
How to Handle:
Ensure the max frequency check catches this scenario early and returns an empty string.
Multiple valid solutions exist for the same input string
How to Handle:
Any valid placement adhering to the alternating index rule is accepted by the problem statement.