Problem solution · Python

Longest Happy String

Longest Happy String: a Python solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Heap or priority queue
Source
Kamyu LeetCode Solutions
Length
64 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Longest Happy String, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeLongest Happy String · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n)# Space: O(1) import heapq  class Solution(object):    def longestDiverseString(self, a, b, c):        """        :type a: int        :type b: int        :type c: int        :rtype: str        """        max_heap = []        if a:            heapq.heappush(max_heap, (-a, 'a'))        if b:            heapq.heappush(max_heap, (-b, 'b'))        if c:            heapq.heappush(max_heap, (-c, 'c'))        result = []        while max_heap:            count1, c1 = heapq.heappop(max_heap)            if len(result) >= 2 and result[-1] == result[-2] == c1:                if not max_heap:                    return "".join(result)                count2, c2 = heapq.heappop(max_heap)                result.append(c2)                count2 += 1                if count2:                    heapq.heappush(max_heap, (count2, c2))                heapq.heappush(max_heap, (count1, c1))                continue            result.append(c1)            count1 += 1            if count1 != 0:                heapq.heappush(max_heap, (count1, c1))        return "".join(result)  # Time:  O(n)# Space: O(1)class Solution2(object):    def longestDiverseString(self, a, b, c):        """        :type a: int        :type b: int        :type c: int        :rtype: str        """        choices = [[a, 'a'], [b, 'b'], [c, 'c']]        result = []        for _ in xrange(a+b+c):            choices.sort(reverse=True)            for i, (x, c) in enumerate(choices):                if x and result[-2:] != [c, c]:                    result.append(c)                    choices[i][0] -= 1                    break            else:                break        return "".join(result) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗