Given a string s
, sort it in the following manner:
s
and append it to the result.s
which is greater than the last appended character to the result and append it.s
and append it to the result.s
which is smaller than the last appended character to the result and append it.s
.You are required to return the sorted string in the required manner.
Character Frequency Count: Use a frequency counter to keep track of the occurrences of each character.
Sorted Characters List: Maintain a list of unique characters sorted in ascending order for forward traversal and descending order for backward traversal.
Constructing Result: Create a result list and perform the operations according to the steps given in the problem. Alternate between appending characters in ascending and descending order, ensuring you decrease the frequency count and remove empty entries.
from collections import Counter
def sortString(s: str) -> str:
# Frequency counter for all characters in the string
freq = Counter(s)
# Unique characters sorted
unique_chars_asc = sorted(freq.keys())
unique_chars_desc = sorted(freq.keys(), reverse=True)
result = []
while freq:
# Smallest to largest
for char in unique_chars_asc:
if char in freq:
result.append(char)
freq[char] -= 1
if freq[char] == 0:
del freq[char]
# Largest to smallest
for char in unique_chars_desc:
if char in freq:
result.append(char)
freq[char] -= 1
if freq[char] == 0:
del freq[char]
return ''.join(result)
# Example usage:
s = "aaaabbbbcccc"
print(sortString(s)) # Output: "abccbaabccba"
Therefore, the overall time complexity is approximately (O(n + k \log k)), which simplifies to (O(n)) given that (k) is a constant (26).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?