767. Reorganize String
Problem description:
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:1
2Input: S = "aab"
Output: "aba"
Example 2:1
2Input: S = "aaab"
Output: ""
Note:
S will consist of lowercase letters and have length in range [1, 500].
Solution:
When we first see this problem, we should use an example to walk through it, and we can see that we need to know what character has the greatest occurrence in the string.
- Use an unordered_map to count occurrence
- Use priority queue to store the occurrence, it will automatically sort it.
- Put the character into the result string, take
2 different character
at a time, this can ensure the outcome will not have same adjacent character.
1 | class Solution { |
The goal is to first exhaust the most-frequent chars. We build a frequency dict of the letters in the string. We push all the letters into a max heap together with their -ve
frequencies (max heap: high-freq letters are towards the top of the heap)
We pop two letters at a time from the heap, add them to our result string, decrement their frequencies and push them back into heap. Why do we have to pop two items/letters at a time you’re wondering? Because if we only pop one at a time, we will keep popping and pushing the same letter over and over again if that letter has a freq greater than 1. Hence by popping two at time, adding them to result, decrementing their freq and finally pushing them back into heap, we guranatee that we are always alternating between letters.
For example: for the string s = aab
The freq dict will be: d = {"a": 2, "b":1}
And the heap: h = [(-2, "a"), (-1, "b")]
After the first iteration:h = [(-1, "a")]
and so on…
Edge Case:
NOTE [1]
- Since we are always popping two items at a time, we will definitely run into an out of bounds error if we have an odd number of unique items in the given string. To avoid this, we need to make sure our heap at least has two items at any given time. We achive this by running our main logic inside a while len(heap) > 1 instead of a while heap
NOTE [2]
- Again if the there is an odd number of unique letters in the string, there will be one last item/letter remaining in the heap when our loop terminates. Hence we need to examine that last item:
- If the last item has a freq greater than 1: -> then return “” becasue we can’t escape having the same letter repeated contigiously.
- else if the item has freq = 1, we pop it, add it to our result and we’re done.
1 | class Solution: |
Solution - Sorting
- count letter appearance
- find the letter with most frequent.
- If the most frequent letter is over half of string, then return
""
- put the letter into
even
index number (0, 2, 4 …) char array - put the letter into
odd
index number (1, 3, 5 …) char array
1 | class Solution: |
reference: