Skip to content

Commit

Permalink
Merge pull request #508 from mangodm-web/main
Browse files Browse the repository at this point in the history
[mangodm-web] Week 08 Solutions
  • Loading branch information
SamTheKorean authored Oct 6, 2024
2 parents 76fe4b5 + f1f82aa commit 99a1eb9
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
26 changes: 26 additions & 0 deletions longest-repeating-character-replacement/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from collections import defaultdict


class Solution:
def characterReplacement(self, s: str, k: int) -> int:
"""
- Idea: ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋ฅผ ์ด์šฉํ•ด ํ˜„์žฌ ์œˆ๋„์šฐ ๋‚ด์—์„œ ๊ฐ€์žฅ ์ž์ฃผ ๋‚˜ํƒ€๋‚˜๋Š” ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถ”์ ํ•œ๋‹ค.
์ตœ๋Œ€ k๊ฐœ์˜ ๋ฌธ์ž๋ฅผ ๋ฐ”๊ฟจ์„ ๋•Œ, ๋ชจ๋“  ๋ฌธ์ž๊ฐ€ ๊ฐ™์€ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ์ตœ๋Œ€ ๊ธธ์ด๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค.
์œˆ๋„์šฐ๊ฐ€ ์œ ํšจํ•˜์ง€ ์•Š์œผ๋ฉด, ์™ผ์ชฝ ํฌ์ธํ„ฐ๋ฅผ ์ด๋™์‹œ์ผœ ์œˆ๋„์šฐ ํฌ๊ธฐ๋ฅผ ์กฐ์ •ํ•œ๋‹ค.
- Time Complexity: O(n), n์€ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋‹ค. ๊ฐ ๋ฌธ์ž๋ฅผ ํ•œ๋ฒˆ์”ฉ ์ˆœํšŒํ•˜๊ณ , ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ๋ฅผ ์กฐ์ •ํ•œ๋‹ค.
- Space Complexity: O(26) = O(1), ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ ๋‚ด์— ํฌํ•จ๋œ ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๊ธฐ ์œ„ํ•œ ๊ณต๊ฐ„์œผ๋กœ, ์ตœ๋Œ€ ์•ŒํŒŒ๋ฒณ ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜(26๊ฐœ)๋งŒํผ ๋Š˜์–ด๋‚  ์ˆ˜ ์žˆ๋‹ค.
"""
result = 0
counter = defaultdict(int)
left = 0

for right in range(len(s)):
counter[s[right]] = counter[s[right]] + 1

while (right - left + 1) - max(counter.values()) > k:
counter[s[left]] -= 1
left += 1

result = max(result, right - left + 1)

return result
34 changes: 34 additions & 0 deletions merge-two-sorted-lists/mangodm-web.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import Optional


class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next


class Solution:
def mergeTwoLists(
self, list1: Optional[ListNode], list2: Optional[ListNode]
) -> Optional[ListNode]:
"""
- Idea: dummy node๋ฅผ ํ•˜๋‚˜ ๋งŒ๋“ค๊ณ , ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ ๋” ์ž‘์€ ๋…ธ๋“œ๋ฅผ dummy node์— ์ด์–ด ๋ถ™์ธ๋‹ค.
๋‘˜ ์ค‘ ํ•˜๋‚˜๊ฐ€ ๋จผ์ € ์ˆœํšŒ๊ฐ€ ๋๋‚ฌ๋‹ค๋ฉด, ๋‚˜๋จธ์ง€ ๋ฆฌ์ŠคํŠธ์˜ ๋‚จ์€ ๋…ธ๋“œ๋“ค์„ ๊ทธ๋Œ€๋กœ ์ด์–ด ๋ถ™์ธ๋‹ค. (๋ฆฌ์ŠคํŠธ ๋‚ด์—์„œ๋Š” ์ˆœ์„œ๊ฐ€ ์ •๋ ฌ๋˜์–ด ์žˆ์Œ์ด ๋ณด์žฅ๋˜์–ด ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐ€๋Šฅํ•˜๋‹ค.)
- Time Complexity: O(n), n์€ m + k, m๊ณผ k์€ ๊ฐ๊ฐ list1, list2์˜ ๊ธธ์ด์ด๋‹ค.
- Space Complexity: O(1), ์ถ”๊ฐ€์ ์ธ ๊ณต๊ฐ„์€ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ , ๊ธฐ์กด ๋…ธ๋“œ๋ฅผ ์žฌ์‚ฌ์šฉํ•˜์—ฌ ์—ฐ๊ฒฐํ•œ๋‹ค.
"""
merged = ListNode()
cur = merged

while list1 and list2:
if list1.val > list2.val:
cur.next = list2
list2 = list2.next
else:
cur.next = list1
list1 = list1.next
cur = cur.next

cur.next = list1 or list2

return merged.next

0 comments on commit 99a1eb9

Please sign in to comment.