diff --git a/2024-12-December-LeetCoding-Challenge/Construct String With Repeat Limit.py b/2024-12-December-LeetCoding-Challenge/Construct String With Repeat Limit.py new file mode 100644 index 0000000..05b3f76 --- /dev/null +++ b/2024-12-December-LeetCoding-Challenge/Construct String With Repeat Limit.py @@ -0,0 +1,51 @@ +from collections import Counter +from heapq import heapify, heappop, heappush +from typing import List, Optional, Tuple + + +class Solution: + def __heappop(self, heap: List[int]) -> Tuple[Optional[str], int]: + if len(heap) == 0: + return (None, 0) + asc, count = heappop(heap) + ch = chr(-asc) + return (ch, count) + + def __heappush(self, heap: List[int], ch: str, count: int): + if count == 0: + return + entry = (-ord(ch), count) + heappush(heap, entry) + + def repeatLimitedString(self, s: str, repeatLimit: int) -> str: + freq = [(-ord(ch), count) for ch, count in Counter(s).items()] + heapify(freq) + string = '' + while freq: + curr_ch, curr_count = self.__heappop(freq) + if string and string[-1] == curr_ch: + next_ch, next_count = self.__heappop(freq) + if next_ch is None and next_count == 0: + break + string += next_ch + self.__heappush(freq, next_ch, next_count-1) + self.__heappush(freq, curr_ch, curr_count) + else: + repeat = min(curr_count, repeatLimit) + string += (curr_ch * repeat) + self.__heappush(freq, curr_ch, curr_count-repeat) + return string + + +def main(): + s = 'cczazcc' + repeatLimit = 3 + assert Solution().repeatLimitedString(s, repeatLimit) == 'zzcccac' + + s = 'aababab' + repeatLimit = 2 + assert Solution().repeatLimitedString(s, repeatLimit) == 'bbabaa' + + +if __name__ == '__main__': + main() diff --git a/2024-12-December-LeetCoding-Challenge/README.md b/2024-12-December-LeetCoding-Challenge/README.md index 2192ed6..1f02111 100644 --- a/2024-12-December-LeetCoding-Challenge/README.md +++ b/2024-12-December-LeetCoding-Challenge/README.md @@ -19,7 +19,7 @@ | December 14 | [2762. Continuous Subarrays](https://leetcode.com/problems/continuous-subarrays/) | Medium | Unsolved | | December 15 | [1792. Maximum Average Pass Ratio](https://leetcode.com/problems/maximum-average-pass-ratio/) | Medium | Unsolved | | December 16 | [3264. Final Array State After K Multiplication Operations I](https://leetcode.com/problems/final-array-state-after-k-multiplication-operations-i/) | Easy | Solved | -| December 17 | []() | | | +| December 17 | [2182. Construct String With Repeat Limit](https://leetcode.com/problems/construct-string-with-repeat-limit/) | Medium | Solved | | December 18 | []() | | | | December 19 | []() | | | | December 20 | []() | | | @@ -39,5 +39,5 @@ | Level | Problems | Solved | Unsolved | | --- | --- | --- | --- | | Easy | 4 | 4 | 0 | -| Medium | 12 | 7 | 5 | +| Medium | 13 | 8 | 5 | | Hard | 0 | 0 | 0 |