Skip to content

Commit

Permalink
Dec 17
Browse files Browse the repository at this point in the history
  • Loading branch information
siddydutta committed Dec 17, 2024
1 parent 0ebd8c3 commit 9af362a
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -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()
4 changes: 2 additions & 2 deletions 2024-12-December-LeetCoding-Challenge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 | []() | | |
Expand All @@ -39,5 +39,5 @@
| Level | Problems | Solved | Unsolved |
| --- | --- | --- | --- |
| Easy | 4 | 4 | 0 |
| Medium | 12 | 7 | 5 |
| Medium | 13 | 8 | 5 |
| Hard | 0 | 0 | 0 |

0 comments on commit 9af362a

Please sign in to comment.