Solving Leetcode Interviews in Seconds with AI: Longest Happy String
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1405" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
A string s is called happy if it satisfies the following conditions: s only contains the letters 'a', 'b', and 'c'. s does not contain any of "aaa", "bbb", or "ccc" as a substring. s contains at most a occurrences of the letter 'a'. s contains at most b occurrences of the letter 'b'. s contains at most c occurrences of the letter 'c'. Given three integers a, b, and c, return the longest possible happy string. If there are multiple longest happy strings, return any of them. If there is no such string, return the empty string "". A substring is a contiguous sequence of characters within a string. Example 1: Input: a = 1, b = 1, c = 7 Output: "ccaccbcc" Explanation: "ccbccacc" would also be a correct answer. Example 2: Input: a = 7, b = 1, c = 0 Output: "aabaa" Explanation: It is the only correct answer in this case. Constraints: 0 <= a, b, c <= 100 a + b + c > 0
Explanation
Here's the breakdown of the solution:
- Greedy Approach: The core idea is to greedily pick the character with the highest remaining count. This maximizes the string length.
- Preventing Substrings: After adding a character, we must check if adding the same character again would violate the "aaa", "bbb", or "ccc" constraint. If it does, we try to add one of the other characters instead.
Prioritization: We use a list of tuples (count, character) to easily sort the characters based on their remaining counts in each step.
Runtime Complexity: O(N), Storage Complexity: O(1), where N is the length of the final happy string (at most a+b+c, and is upper bounded by 300).
Code
def longest_happy_string(a: int, b: int, c: int) -> str:
"""
Generates the longest possible happy string.
"""
result = ""
counts = [(a, 'a'), (b, 'b'), (c, 'c')]
while True:
counts.sort(reverse=True)
if counts[0][0] == 0:
break
if len(result) >= 2 and result[-1] == counts[0][1] and result[-2] == counts[0][1]:
if counts[1][0] == 0:
break
else:
result += counts[1][1]
counts[1] = (counts[1][0] - 1, counts[1][1])
else:
result += counts[0][1]
counts[0] = (counts[0][0] - 1, counts[0][1])
return result