Skip to main content

Longest Happy String

Medium
Data Structures and Algorithms
Editorial
Topics:
Heap
Greedy
String

Implement the Solution class and its longestDiverseString method. The method receives three nonnegative counts: a for the available letter 'a', b for 'b', and c for 'c'.

A happy string contains only the letters 'a', 'b', and 'c', uses no more than the available count of any letter, and never contains three identical letters consecutively. The string may use fewer copies of a letter than its corresponding parameter.

Return any happy string with maximum possible length. If no non-empty happy string can be formed, return the empty string "". The answer does not need to be unique.

Example 1:

Input: a = 2, b = 1, c = 0
Output: "aab"
Explanation: The string uses all available letters and never has three equal consecutive characters, so its length is maximal.

Example 2:

Input: a = 5, b = 1, c = 1
Output: "aabaaca"
Explanation: All seven available letters can be arranged without creating aaa, making this a longest happy string.

Example 3:

Input: a = 0, b = 0, c = 4
Output: "cc"
Explanation: At most two c characters can be consecutive, so only two of the four available characters can be used.

Constraints:

  • ``a, b, and c are JSON integers.
  • 0 <= a <= 100.
  • 0 <= b <= 100.
  • 0 <= c <= 100.
  • a + b + c > 0.

Need help or want more practice?

Practise in an interviewGet AI Coach help