Skip to content

[hi-rachel] Week 05 Solutions #1401

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions best-time-to-buy-and-sell-stock/hi-rachel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# TC: O(N), SC: O(1)

class Solution:
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
min_price = prices[0]

for price in prices:
max_profit = max(price - min_price, max_profit)
min_price = min(price, min_price)
return max_profit

# TS 풀이
# 배열 요소(숫자값)을 직접 순회하려면 for ... of 사용 혹은 forEach
# for ... in -> 인덱스를 가져옴

# function maxProfit(prices: number[]): number {
# let max_profit: number = 0;
# let min_price: number = prices[0];

# for (let price of prices) {
# max_profit = Math.max(max_profit, price - min_price);
# min_price = Math.min(min_price, price);
# }
# return max_profit;
# };
30 changes: 30 additions & 0 deletions encode-and-decode-strings/hi-rachel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# 문제: https://neetcode.io/problems/string-encode-and-decode
# TC: O(N), SC: O(1)
# ASCII 문자열이 아닌 이모티콘으로 구분자 선택

class Solution:
def encode(self, strs: List[str]) -> str:
return '🤍'.join(strs)

def decode(self, s: str) -> List[str]:
return s.split('🤍')

# ASCII 문자열에 포함된 기호로 구분자를 써야할 때
# -> 글자 수 표시
class Solution:
def encode(self, strs: List[str]) -> str:
text = ""
for str in strs:
text += f"{len(str)}:{str}"
return text

def decode(self, s: str) -> List[str]:
ls, start = [], 0
while start < len(s):
mid = s.find(":", start)
length = int(s[start : mid])
word = s[mid + 1 : mid + 1 + length]
ls.append(word)
start = mid + 1 + length
return ls

14 changes: 14 additions & 0 deletions group-anagrams/hi-rachel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# TC O(N * K log K), SC O(N * K)

from collections import defaultdict

class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
anagram_map = defaultdict(list)

for word in strs:
key = ''.join(sorted(word))
anagram_map[key].append(word)

return list(anagram_map.values())

51 changes: 51 additions & 0 deletions group-anagrams/hi-rachel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// TC O(N * K log K), N: 단어 수, K: 평균 단어 길이, 각 단어를 정렬
// SC O(N * K)

/**
* Array.from() => 이터러블 -> 일반 배열로 변환
*/
function groupAnagrams(strs: string[]): string[][] {
const anagramMap: Map<string, string[]> = new Map();

for (const word of strs) {
const key = word.split("").sort().join("");
const group = anagramMap.get(key) || [];
group.push(word);
anagramMap.set(key, group);
}
return Array.from(anagramMap.values());
}

/**
* reduce 풀이
*/
// function groupAnagrams(strs: string[]): string[][] {
// const anagramMap = strs.reduce((map, word) => {
// const key = word.split("").sort().join("");
// if (!map.has(key)) {
// map.set(key, []);
// }
// map.get(key).push(word);
// return map;
// }, new Map<string, string[]>());

// return Array.from(anagramMap.values());
// }

/** 간결한 버전
* x ||= y (ES2021)
* x가 falsy 값이면 y를 할당
* JS에서 falsy 값 = false, 0, '', null, undefined, NaN
*
* Object.values() => 객체의 값들만 배열로 추출할때 사용
*/
// function groupAnagrams(strs: string[]): string[][] {
// const anagramMap: {[key: string]: string[]} = {};

// strs.forEach((word) => {
// const key = word.split('').sort().join('');
// (anagramMap[key] ||= []).push(word);
// });

// return Object.values(anagramMap);
// }
45 changes: 45 additions & 0 deletions implement-trie-prefix-tree/hi-rachel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Trie Data Structure 구현
# TC: O(n), SC: O(N)
# autocomplete and spellchecker 등에 사용

class Node:
def __init__(self, ending=False):
self.children = {}
self.ending = ending

class Trie:
def __init__(self):
self.root = Node(ending=True) # 노드 객체 생성

def insert(self, word: str) -> None:
node = self.root #Trie의 최상위 노드부터 시작
for ch in word:
if ch not in node.children:
node.children[ch] = Node() # 새로운 노드 생성
node = node.children[ch]
node.ending = True

def search(self, word: str) -> bool:
node = self.root

for ch in word:
if ch not in node.children:
return False
node = node.children[ch]
return node.ending

def startsWith(self, prefix: str) -> bool:
node = self.root

for ch in prefix:
if ch not in node.children:
return False
node = node.children[ch]
return True


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
54 changes: 54 additions & 0 deletions implement-trie-prefix-tree/hi-rachel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
class TrieNode {
children: Map<string, TrieNode>;
ending: boolean;

constructor(ending = false) {
this.children = new Map();
this.ending = ending;
}
}

class Trie {
private root: TrieNode;

constructor() {
this.root = new TrieNode(true);
}

insert(word: string): void {
let node = this.root;
for (const ch of word) {
if (!node.children.has(ch)) {
node.children.set(ch, new TrieNode());
}
node = node.children.get(ch)!; // 노드 포인터를 ch로 이동
}
node.ending = true;
}

search(word: string): boolean {
let node = this.root;
for (const ch of word) {
if (!node.children.has(ch)) return false;
node = node.children.get(ch)!;
}
return node.ending;
}

startsWith(prefix: string): boolean {
let node = this.root;
for (const ch of prefix) {
if (!node.children.has(ch)) return false;
node = node.children.get(ch)!;
}
return true;
}
}

/**
* Your Trie object will be instantiated and called as such:
* var obj = new Trie()
* obj.insert(word)
* var param_2 = obj.search(word)
* var param_3 = obj.startsWith(prefix)
*/
33 changes: 33 additions & 0 deletions word-break/hi-rachel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// wordDict 조합으로 s를 만들 수 있는지 반환해라
// TC: O(n^2) SC: O(n + m * k) => s의 길이 + (단어 수 * 평균 단어 길이)
// .has(word) => O(1)

function wordBreak(s: string, wordDict: string[]): boolean {
const wordSet = new Set(wordDict);
const dp: boolean[] = Array(s.length + 1).fill(false);
dp[0] = true;

for (let i = 1; i <= s.length; i++) {
for (let j = 0; j < i; j++) {
if (dp[j] && wordSet.has(s.slice(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length];
}

// PY 풀이
// class Solution:
// def wordBreak(self, s: str, wordDict: List[str]) -> bool:
// wordSet = set(wordDict)
// dp = [False] * (len(s)+1)
// dp[0] = True

// for i in range(1, len(s)+1):
// for j in range(0, i):
// if dp[j] and s[j:i] in wordSet:
// dp[i] = True

// return dp[len(s)]