Reorganize String
LeetCode 778 | Difficulty: Mediumβ
MediumProblem 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?
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?
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.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 84 ms)β
| Metric | Value |
|---|---|
| Runtime | 84 ms |
| Memory | 36.2 MB |
| Date | 2022-01-20 |
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β
| Approach | Time | Space |
|---|---|---|
| Sort + Process | $O(n log n)$ | $O(1) to O(n)$ |
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- 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.