#1405
Longest Happy String
MediumStringGreedyHeap (Priority Queue)GreedyHeap (Priority Queue)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a greedy approach to build the longest happy string by always adding the character that can be added without violating the happy string conditions. This ensures we maximize the length while adhering to the constraints.
⚙️
Algorithm
3 steps- 1Step 1: Initialize an empty string to build the happy string.
- 2Step 2: While there are characters left to add, choose the character with the highest remaining count that does not create three consecutive characters.
- 3Step 3: Append the chosen character to the string and update the counts accordingly.
solution.py28 lines
1# Full working Python code
2import heapq
3
4def longest_happy_string(a, b, c):
5 max_heap = []
6 if a > 0:
7 heapq.heappush(max_heap, (-a, 'a'))
8 if b > 0:
9 heapq.heappush(max_heap, (-b, 'b'))
10 if c > 0:
11 heapq.heappush(max_heap, (-c, 'c'))
12
13 result = ""
14 while max_heap:
15 count, char = heapq.heappop(max_heap)
16 if len(result) >= 2 and result[-1] == result[-2] == char:
17 if not max_heap:
18 break
19 next_count, next_char = heapq.heappop(max_heap)
20 result += next_char
21 if next_count + 1 < 0:
22 heapq.heappush(max_heap, (next_count + 1, next_char))
23 heapq.heappush(max_heap, (count, char))
24 else:
25 result += char
26 if count + 1 < 0:
27 heapq.heappush(max_heap, (count + 1, char))
28 return resultℹ
Complexity note: The time complexity is O(n) because we are processing each character count at most once, and the heap operations are logarithmic in nature but bounded by the number of characters.
- 1Greedy algorithms often yield optimal solutions by making the best choice at each step.
- 2Using a max heap helps efficiently manage character counts and ensure the longest happy string.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.