- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 64 lines of Python from the credited upstream file longest-happy-string.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import heapq5 6 7class Solution(object):8 def longestDiverseString(self, a, b, c):9 """10 :type a: int11 :type b: int12 :type c: int13 :rtype: str14 """15 max_heap = []16 if a:17 heapq.heappush(max_heap, (-a, 'a'))18 if b:19 heapq.heappush(max_heap, (-b, 'b'))20 if c:21 heapq.heappush(max_heap, (-c, 'c'))22 result = []23 while max_heap:24 count1, c1 = heapq.heappop(max_heap)25 if len(result) >= 2 and result[-1] == result[-2] == c1:26 if not max_heap:27 return "".join(result)28 count2, c2 = heapq.heappop(max_heap)29 result.append(c2)30 count2 += 131 if count2:32 heapq.heappush(max_heap, (count2, c2))33 heapq.heappush(max_heap, (count1, c1))34 continue35 result.append(c1)36 count1 += 137 if count1 != 0:38 heapq.heappush(max_heap, (count1, c1))39 return "".join(result)40 41 424344class Solution2(object):45 def longestDiverseString(self, a, b, c):46 """47 :type a: int48 :type b: int49 :type c: int50 :rtype: str51 """52 choices = [[a, 'a'], [b, 'b'], [c, 'c']]53 result = []54 for _ in xrange(a+b+c):55 choices.sort(reverse=True)56 for i, (x, c) in enumerate(choices):57 if x and result[-2:] != [c, c]:58 result.append(c)59 choices[i][0] -= 160 break61 else:62 break63 return "".join(result)64