Skip to main content

Reorganize String

LeetCode 778 | Difficulty: Medium​

Medium

Problem Description​

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.

Topics: Hash Table, String, Greedy, Sorting, Heap (Priority Queue), Counting


Approach​

Hash Map​

Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?

When to use

Need fast lookups, counting frequencies, finding complements/pairs.

Greedy​

At each step, make the locally optimal choice. The challenge is proving the greedy choice leads to a global optimum. Look for: can I sort by some criterion? Does choosing the best option now ever hurt future choices?

When to use

Interval scheduling, activity selection, minimum coins (certain denominations), Huffman coding.

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 84 ms)​

MetricValue
Runtime84 ms
Memory36.2 MB
Date2022-01-20
Solution
public class Solution {
public string ReorganizeString(string s) {
int[] freq = new int[26];
int max = 0; char maxLetter = ' ';
foreach (var c in s)
{
freq[c-'a']++;
if(freq[c-'a']>max)
{
max = freq[c-'a'];
maxLetter = c;
}
}
if(max>(s.Length+1)/2) return "";
char[] result = new char[s.Length];
int index = 0;
for (int i=0; i< max; i++)
{
result[index] = maxLetter;
freq[maxLetter-'a']--;
index+=2;
}
for (int i = 0; i < 26; i++)
{
while(freq[i]>0)
{
if (index >= s.Length)
{
index = 1;
}
result[index]= (char)(i+'a');
index+=2;
freq[i]--;
}
}

return new string(result);
}
}

Complexity Analysis​

ApproachTimeSpace
Sort + Process$O(n log n)$$O(1) to O(n)$
Hash Map$O(n)$$O(n)$

Interview Tips​

Key Points
  • Discuss the brute force approach first, then optimize. Explain your thought process.
  • Hash map gives O(1) lookup β€” think about what to use as key vs value.
  • LeetCode provides 1 hint(s) for this problem β€” try solving without them first.
πŸ’‘ Hints

Hint 1: Alternate placing the most common letters.