Skip to content
Open
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
49 changes: 49 additions & 0 deletions coin-change/novacat25.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
시간 복잡도: O(amount * n)
공간 복잡도: O(amount)
풀이 기법: Dynamic Programming을 이용한다. Greedy Algorithm의 경우, [1,3,4]와 6의 반례에서는 실패하기에 remain = amount - coin 기준으로 Min 값을 반환할 수 있도록 하는 DP를 이용하는 것이 이상적.
*/
/* 풀이 1: Bottom-up */
const coinChange = (coins: number[], amount: number): number => {
const INVALID_ANSWER_CONDITION = Infinity

const dp: number[] = new Array(amount + 1).fill(INVALID_ANSWER_CONDITION) //Invalid Value: Infinity
dp[0] = 0

for (let i = 1; i <= amount; i++) {
for (const coin of coins) {
if (coin <= i) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1)
}
}
}

return dp[amount] > amount ? -1 : dp[amount]
}

/* 풀이 2: Top-Down */
// // 값을 찾지 못한 경우 -Infinity, 조건 상 성립할 수 없는 경우 Infinity. 그로 인해 답이 없다면 -1을 반환함.
// const NOT_SEARCHED = -Infinity
// const INVALID_ANSWER_CONDITION = Infinity
// const INVALID_ANSWER = -1

// const solveCoin = (memo: number[], coins: number[], remaining: number): number => {
// if (remaining === 0) return 0
// if (remaining < 0) return INVALID_ANSWER_CONDITION
// if (memo[remaining] !== NOT_SEARCHED) return memo[remaining]

// let minCoins = INVALID_ANSWER_CONDITION

// for (const coin of coins) {
// const sub = solveCoin(memo, coins, remaining - coin)
// minCoins = Math.min(minCoins, sub + 1)
// }
// memo[remaining] = minCoins
// return minCoins
// }

// const coinChange = (coins: number[], amount: number): number => {
// const memo: number[] = new Array(amount + 1).fill(NOT_SEARCHED)
// const result = solveCoin(memo, coins, amount)
// return result === INVALID_ANSWER_CONDITION ? INVALID_ANSWER : result
// }
33 changes: 33 additions & 0 deletions find-minimum-in-rotated-sorted-array/novacat25.ts

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 left, right를 사용해서 이진탐색으로 구현한 풀이 잘 봤습니다!
저는 매번 새로운 배열을 만드는 방식으로 진행했는데 풀이대로 하면 공간 복잡도를 줄일 수 있겠네요.

이진 탐색의 조건을 주석으로 적어주신 것도 감사합니다! 공부가 됐습니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문제 조건에서 뜻을 도출하는 것도 중요한 거 같더라고요!
거기서 꽤 많은 힌트가 녹아 있고, 특히 LeetCode는 이 부분을 되게 꼼꼼하게 잡아주는 것 같습니다.
(DP에서 일반 재귀를 쓰면 TLE가 나도록 설계를 했다던지)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

시간 복잡도가 O(log n)으로 제한되어 있어서, mid를 보고 최솟값이 속한 구간이 left인지 right인지 판단해 절반씩 줄여 나가는 방식이군요!
저는 아직 O(n) 복잡도에서 못 줄여서 어떻게 줄일지 다른 분들 풀이를 보고 있었는데, 덕분에 영감을 얻어 갑니다 🙂

Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
시간 복잡도(TC): O(log n)
공간 복잡도(SC): O(1)
풀이: Binary Search를 이용하여 O(log n) 시간 이내에 답을 구한다.
조건:
- 모든 Item을 Search하는 Linear Search는 시간 복잡도가 O(n)이므로 문제 요구사항을 위배한다.
- 모든 item 값은 unique하다. => 중복된 값이 있는 경우라면 index 연산이 애매해지겠으나, 모든 값이 유일하다면 Binary Search를 일관되게 보장할 수 있다.

Binary Search를 적용할 수 있는 조건
- 반드시 해당 배열이 정렬되어 있어야 한다.
- Input Array의 경우에는 완전히 정렬되어 있지는 않으나, 'n번 rotate 후 원래의 배열로 돌아간다 = 2개의 Sort된 배열이 합쳐져 있다'는 조건으로 간주되어 Binary Search 적용이 가능하다.
- 분기는 다음과 같다.
- nums[mid] > nums[right]인 경우 => left ~ mid 구간까지는 더 큰 값이 들어 있는 sorted Array임이 자명하므로, mid까지 포함하지 않고 left = mid + 1로 배제하여 탐색 범위를 크게 줄인다.
- nums[mid] <= nums[right]인 경우 => mid ~ right 구간은 sorted & ascending 상태가 보장된다. minimum value는 mid가 될 수도 있으므로 right 값에 mid를 덮어씌운다.
*/

const findMin = (nums: number[]): number => {
let left = 0
let right = nums.length - 1

if (nums[left] < nums[right]) return nums[left]

while (left < right) {
const mid = Math.floor(left + (right - left) / 2)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(left + right) / 2 대신 left + (right - left) / 2로 쓰신 이유는 overflow 방지 때문인가요?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://medium.com/@silverraining/binary-search-in-javascript-simple-fast-and-real-world-ready-191373488be0
에 의하면,

일부 프로그래밍 언어에서는 (left + right) / 2 연산으로 인해 오버플로의 리스크가 있을 수 있어
더 안전한 기법이라고 합니다!

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

타입스크립트에선 64비트 부동소수점 자료형이라 이번 경우엔 필요는 없는데요. 다만, 매우 큰 정수 범위를 대상으로 하는 경우 이 방식으로 정밀도 손실을 방지할 수 있을 거 같습니다.

if (nums[mid] > nums[right]) {
left = mid + 1
} else {
Comment on lines +25 to +27

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

정렬되있는 경우엔 즉시 반환할 수 있어서 최적화 해보셔도 좋을 거 같습니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

힌트 감사합니다!
이 부분은 조금 더 시뮬레이션 돌려보고 와야겠네요.
막히는 부분이 있으면 다시 여쭤보겠습니다 ㅎㅎ

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

좀더 최적화 하는 느낌이라 해보시면 재밌으실 거 같아요!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@parkhojeong
감사합니다! 덕분에 이 부분 확실하게 캐치했습니다.

if(nums[left] < nums[right]) return nums[left]
이걸 Binary Search 전에 추가하면 됩니다.

  • [3,4,5,1,2] 와 같은 배열값은 rotation이 돌아야 하는 상태, [1,2,3,4,5]는 이미 정렬된 상태입니다.
  • rotation을 돌지 않아도 되는 배열은 nums[left] < nums[right]가 일관되게 지켜집니다. [3,4,5,1,2]와 같이 rotation이 돌아야 하는 경우에는 nums[left]가 nums[right]보다 항상 큽니다.
  • 문제 조건 덕분에 [1,4,3,2,5]와 같은 반례는 대상에서 제외됩니다.

따라서 nums[left] < nums[right]로 검사하면
최적의 경우에는 O(1), 최악의 경우에도 시간 복잡도는 O(log n)로 바뀌지 않습니다.

right = mid
}
}

return nums[left]
}
62 changes: 62 additions & 0 deletions maximum-depth-of-binary-tree/novacat25.ts

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

수평을 모두 탐색한 뒤 다음 층으로 넘어가는 BFS 풀이까지 1차 DFS 풀이와 대조해서 보여 주셔서 인상 깊습니다 ㅎㅎ

Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
[2차 풀이]
시간 복잡도(TC): O(n)
공간 복잡도(SC): O(n)
풀이: BFS와 Queue를 이용해, 수평 방향으로 우선하여 탐색한다. Queue는 발견했지만 탐색되지 않은 노드열이다.
*/
class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val
this.left = left === undefined ? null : left
this.right = right === undefined ? null : right
}
}

const isQueueEmpty = (queue: TreeNode[]) => queue.length === 0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while (nodeQueue.length) 대신 큐가 비어있다는 것을 확인하기 위해 함수를 따로 만드신 것이군요!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네, 조금 더 가독성에 사치를 부려 봤어요!


const maxDepth = (root: TreeNode | null): number => {
const DEFAULT_VALUE = 0
if (!root) return DEFAULT_VALUE

const nodeQueue = [root]
let depth = 0

while (!isQueueEmpty(nodeQueue)) {
const levelSize = nodeQueue.length

for (let i = 0; i < levelSize; i++) {
const currentNode = nodeQueue.shift()
Comment on lines +30 to +31

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

child node가 계속 push되니까 levelSize를 미리 const로 고정해 두고, 그 길이만큼 꺼내서 한 층을 처리한 뒤 depth를 추가하는 원리군요

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네, 해당 Queue의 levelSize만큼만 shift로 빼고, 나머지는 다음 while 분기에 넘기도록 했습니다.
JS에서 일반 배열로 Queue를 사용할 경우 또 shift() 연산을 통해 이루어지니 이렇게 짰어요!

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

설명 감사합니다! levelSize만큼만 꺼내고 나머지는 다음 층으로 넘기는 구조 기억하도록 하겠습니다
파이썬에서도 이 구조를 한번 찾아봐서 다음에 적용해 봐야겠어요 🙂


if (currentNode?.left) {
nodeQueue.push(currentNode.left)
}

if (currentNode?.right) {
nodeQueue.push(currentNode.right)
}
}

depth++
}
Comment on lines +27 to +43

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 같은 siblings끼리 확인할 때마다 depth를 늘려서 구하는 방식 좋은 것 같습니다!
트리 순회를 방문한 노드로 푸는 방식이 직관적으로 와닿아서 배워갑니다.


return depth
}

/*
[1차 풀이]
시간 복잡도(TC): O(n)
공간 복잡도(SC): O(h) - h는 Tree의 높이
풀이: 재귀 코드를 활용하여, root 기준으로 left/right를 전개하여 풀어나간다. root가 존재하지 않는 기본값은 0으로, Math.max(left, right) 후 추가로 높이 보정치인 1을 더한다.
*/
// const maxDepth = (root: TreeNode | null): number => {
// const DEFAULT_VALUE = 0

// if (!root) return DEFAULT_VALUE
// let leftHeight = maxDepth(root.left)
// let rightHeight = maxDepth(root.right)

// return Math.max(leftHeight, rightHeight) + 1
// }
Comment on lines +49 to +62

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1번째 풀이는 재귀dfs로 푸셨네요!

82 changes: 82 additions & 0 deletions merge-two-sorted-lists/novacat25.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
핵심 팁
문제에서 주어지는 list1 = [1,2,4] 및 list2 = [1,3,4]는 그대로 배열을 쓰는 것이 아니다!! (constructor 부분 주목)
const list1 = new ListNode(1, new ListNode(2, new ListNode(4))) // [1] -> [2] -> [4] -> null
const list2 = new ListNode(1, new ListNode(3, new ListNode(4))) // [1] -> [3] -> [4] -> null
Comment on lines +2 to +5

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

팁까지 적어 주셔서 감사합니다 :)
저도 첫 번째 풀이 때는 리스트 그 자체로 보려다 보니 풀이가 길어지고 복잡해졌는데, 덕분에 노드를 직접 연결하는 방식으로 풀 수 있었네요

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아, 이 부분은 LeetCode가 input sample을 줄 때 Online TS Compiler에서 '이거 어떻게 처리해야 하나?' 하고 막혀있었던 걸 조금 더 확실히 하기 위해 쓴 거에요!

*/

class ListNode {
val: number
next: ListNode | null
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val
this.next = next === undefined ? null : next
}
}

/*
[2차 풀이]
시간 복잡도: O(n + m)
공간 복잡도: O(n + m) -> O(1)
풀이 기법: Iterative(Dummy Node)로 문제 분해 + Call Stack 기법 대신 객체 참조(Reference)와 포인터 이동을 통해 공간 복잡도를 절약함.
풀이 원리:
(1) tail.next = list1 or list2로 dummy의 객체 속성을 변경시킨다.
(2) list1 = list1.next or list2 = list2.next로 입력 리스트의 참조를 이동한다.
(3) tail = tail.next로 결과 리스트의 참조를 이동한다.

이 과정에서 dummy는 시작 위치를 그대로 저장하고 있는다.
*/

const mergeTwoLists = (
list1: ListNode | null,
list2: ListNode | null,
): ListNode | null => {
const dummyNode = new ListNode(0)
let tail = dummyNode

while (list1 !== null && list2 !== null) {
if (list1.val <= list2.val) {
tail.next = list1
list1 = list1.next
} else {
tail.next = list2
list2 = list2.next
}
tail = tail.next

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 tail에 계속 조건에 맞는 리스트 노드를 추가하는 방식이 직관적으로 드러나는 것 같아서 좋은 것 같습니다.
작성해주신 코드로 그림 그려보면서 풀이하니까 링크드 리스트에 대한 이해도 되면서 js에서 변수에 값을 할당하는 방식을 한번 더 확인해볼 수 있었습니다.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이게 Reference 기능을 통해 dummy에 tail을 연결해서 풀 수 있다는 원리가
손풀이나 이론을 알 수 없으면 이해하는데까지 시간이 엄청 걸리긴 하더라고요..!

}

tail.next = list1 ?? list2

return dummyNode.next
}

/*
[1차 풀이]
시간 복잡도: O(n + m)
공간 복잡도: O(n + m)
풀이 기법: Recursion

Self Feedback:
- 최초 풀이에서는 Linked List의 구조 및 재귀적 문제 분해에 대한 이해 부족으로 아이디어를 독립적으로 도출하지 못했다.
- 외부 해설에서 원리를 참고한 뒤 직접 구현하여 정답에 도달했다.
- 이후 ListNode의 constructor와 객체 참조를 확인하며 자료구조에 대한 이해를 보완했다.
- 손풀이를 통해 재귀 호출의 인자 변화, Base case 및 반환 과정까지 추적했다.
- 추후 해설 없이 재귀 풀이를 재구현할 필요가 있다.
*/

// const mergeTwoLists = (
// list1: ListNode | null,
// list2: ListNode | null,
// ): ListNode | null => {
// // Base cases
// if (!list1) return list2
// if (!list2) return list1

// if (list1.val <= list2.val) {
// list1.next = mergeTwoLists(list1.next, list2)
// return list1
// } else {
// list2.next = mergeTwoLists(list1, list2.next)
// return list2
// }
// }
Loading
Loading