Solving Leetcode Interviews in Seconds with AI: String Compression III
Introduction
In this blog post, we will explore how to solve the LeetCode problem "3163" 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
Given a string word, compress it using the following algorithm: Begin with an empty string comp. While word is not empty, use the following operation: Remove a maximum length prefix of word made of a single character c repeating at most 9 times. Append the length of the prefix followed by c to comp. Return the string comp. Example 1: Input: word = "abcde" Output: "1a1b1c1d1e" Explanation: Initially, comp = "". Apply the operation 5 times, choosing "a", "b", "c", "d", and "e" as the prefix in each operation. For each prefix, append "1" followed by the character to comp. Example 2: Input: word = "aaaaaaaaaaaaaabb" Output: "9a5a2b" Explanation: Initially, comp = "". Apply the operation 3 times, choosing "aaaaaaaaa", "aaaaa", and "bb" as the prefix in each operation. For prefix "aaaaaaaaa", append "9" followed by "a" to comp. For prefix "aaaaa", append "5" followed by "a" to comp. For prefix "bb", append "2" followed by "b" to comp. Constraints: 1 <= word.length <= 2 * 105 word consists only of lowercase English letters.
Explanation
- Iterate through the input string
word.- For each character, find the maximum length prefix consisting of the same character (up to a maximum length of 9).
- Append the length of the prefix and the character to the compressed string.
- Runtime Complexity: O(n), where n is the length of the input string. Storage Complexity: O(1), excluding the output string.
Code
def compress_word(word: str) -> str:
"""Compresses a string by replacing repeating characters with their count."""
comp = ""
i = 0
while i < len(word):
char = word[i]
count = 0
j = i
while j < len(word) and word[j] == char and count < 9:
count += 1
j += 1
comp += str(count) + char
i = j
return comp