Skip to content

[novacat25] WEEK 04 Solutions - #2965

Open
novacat25 wants to merge 14 commits into
DaleStudy:mainfrom
novacat25:week4
Open

novacat25 wants to merge 14 commits into
DaleStudy:mainfrom
novacat25:week4

Conversation

@novacat25

@novacat25 novacat25 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

답안 제출 문제

작성자 체크 리스트

  • Projects의 오른쪽 버튼(▼)을 눌러 확장한 뒤, Week를 현재 주차로 설정해주세요.
  • 문제를 모두 푸시면 프로젝트에서 Status를 In Review로 설정해주세요.
  • 코드 검토자 1분 이상으로부터 승인을 받으셨다면 PR을 병합해주세요.

검토자 체크 리스트

Important

본인 답안 제출 뿐만 아니라 다른 분 PR 하나 이상을 반드시 검토를 해주셔야 합니다!

  • 바로 이전에 올라온 PR에 본인을 코드 리뷰어로 추가해주세요.
  • 본인이 검토해야하는 PR의 답안 코드에 피드백을 주세요.
  • 토요일 전까지 PR을 병합할 수 있도록 승인해주세요.

@dalestudy

dalestudy Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

🤖 AI 리뷰(알고리즘 패턴, 시간/공간 복잡도, 학습 현황) 결과는 Checks 탭에서 볼 수 있어요.

@github-actions github-actions Bot added the ts label Nov 30, 2026
@novacat25 novacat25 changed the title Resolved: merge-two-sorted-lists#224 [novacat25] WEEK 04 Solutions Nov 30, 2026
@novacat25 novacat25 moved this from Solving to In Review in 리트코드 스터디 9기 Dec 1, 2026
Comment on lines +49 to +62
[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
// }

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로 푸셨네요!

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 풀이와 대조해서 보여 주셔서 인상 깊습니다 ㅎㅎ

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가 나도록 설계를 했다던지)

Comment on lines +27 to +43
while (!isQueueEmpty(nodeQueue)) {
const levelSize = nodeQueue.length

for (let i = 0; i < levelSize; i++) {
const currentNode = nodeQueue.shift()

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

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

depth++
}

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를 늘려서 구하는 방식 좋은 것 같습니다!
트리 순회를 방문한 노드로 푸는 방식이 직관적으로 와닿아서 배워갑니다.

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을 연결해서 풀 수 있다는 원리가
손풀이나 이론을 알 수 없으면 이해하는데까지 시간이 엄청 걸리긴 하더라고요..!

Comment on lines +30 to +31
for (let i = 0; i < levelSize; i++) {
const currentNode = nodeQueue.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.

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만큼만 꺼내고 나머지는 다음 층으로 넘기는 구조 기억하도록 하겠습니다
파이썬에서도 이 구조를 한번 찾아봐서 다음에 적용해 봐야겠어요 🙂

}
}

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.

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

Comment on lines +2 to +5
핵심 팁
문제에서 주어지는 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

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에서 '이거 어떻게 처리해야 하나?' 하고 막혀있었던 걸 조금 더 확실히 하기 위해 쓴 거에요!

Comment thread merge-two-sorted-lists/novacat25.ts Outdated
const dummyNode = new ListNode(0)
let tail = dummyNode

while (list1 !== null && list2 != null) {

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.

파이썬은 !=만 있는데, 여기는 !==와 != 둘 다 있군요
찾아보니 전자는 타입까지 엄격하게 비교하고, 후자는 타입을 맞춘 뒤 비교하는데 이 문제에서는 list1, list2가 ListNode 아니면 null이라 !=나 !==가 결과가 같네요 🙂

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.

네, !==가 조금 더 엄격합니다.
다만, 왜 list2 != null 인가? 는..
아마 코드 실수일 가능성이 높습니다.

Comment thread coin-change/novacat25.ts Outdated
}
}

return dp[amount] > amount ? INVALID_ANSWER : dp[amount]

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.

저는 dp 초기값을 큰 수로 설정해서 마지막에 이 초기값과 같은지로 판별했는데, 최소 동전 수가 amount를 넘을 수 없다는 점을 이용해 dp[amount] > amount로 판별하는 방식이 깔끔하네요!

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.

네, 미탐색 dp[index]는 amount보다 의도적으로 크게 설정시켜서 '값이 될 수 없는 조건'을 의도했습니다!
amount + 1 등의 숫자로 가능이야 하지만, Infinity가 좀 더 직관적일 것 같더라고요.

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) 복잡도에서 못 줄여서 어떻게 줄일지 다른 분들 풀이를 보고 있었는데, 덕분에 영감을 얻어 갑니다 🙂

let right = nums.length - 1

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비트 부동소수점 자료형이라 이번 경우엔 필요는 없는데요. 다만, 매우 큰 정수 범위를 대상으로 하는 경우 이 방식으로 정밀도 손실을 방지할 수 있을 거 같습니다.

Comment thread word-search/novacat25.ts
Comment on lines +111 to +122
const temp = board[i][j]
board[i][j] = VISITED_POSITION

// 수평 및 수직으로 일괄 탐색. Call Stack에 의해 순차적으로 실행됨.
const found =
backtrack(i + 1, j, idx + 1) ||
backtrack(i - 1, j, idx + 1) ||
backtrack(i, j + 1, idx + 1) ||
backtrack(i, j - 1, idx + 1)

// Backtracking 적용
board[i][j] = temp

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.

저는 처음에 visit set에 방문한 좌표를 다 넣었더니, 잘못 들어갔던 경로에서 방문한 칸이 그대로 남아서 에러가 났었습니다..
그래서 경로마다 path를 복사해서 들고 다니는 식으로 해결했는데, #로 임시로 방문 표시를 하고 탐색이 끝나면 원래 글자로 돌려놓으면 복사 없이도 되는군요. 훨씬 깔끔해서 배워 갑니다~!

@parkhojeong parkhojeong left a comment

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.

수고하셨습니다! 몇 가지 커멘트 남겼습니다.

Comment thread coin-change/novacat25.ts Outdated
*/
/* 풀이 1: Bottom-up */
const coinChange = (coins: number[], amount: number): number => {
const ANSWER_NOT_FOUND = -1

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.

상단에 써있어서 로직에 쓰이는 줄 알았습니다. 리턴에서만 쓰이는 변수니 리턴 직전에 상수로 선언해서 쓰거나 간단히 주석으로 남겨두는 것도 괜찮을 거 같습니다.

let right = nums.length - 1

while (left < right) {
const mid = Math.floor(left + (right - left) / 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비트 부동소수점 자료형이라 이번 경우엔 필요는 없는데요. 다만, 매우 큰 정수 범위를 대상으로 하는 경우 이 방식으로 정밀도 손실을 방지할 수 있을 거 같습니다.

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

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)로 바뀌지 않습니다.

Comment thread merge-two-sorted-lists/novacat25.ts Outdated
tail = tail.next
}

tail.next = list1 !== null ? list1 : list2

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.

list1 ?? list2 로 적어도 같을 거 같네요

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.

맞네요, ?? 연산자를 쓴다면 더 간소화 가능할 것 같습니다.

Comment thread merge-two-sorted-lists/novacat25.ts Outdated
Comment on lines +49 to +51
const answerNode = dummyNode.next

return answerNode

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.

바로 dummyNode.next 를 리턴해도 될 거 같습니다.

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.

요거는 있는게 더 잘 읽힐 거 같기는 한데, dummyNode의 next가 왜 answerNode인지에 대한 문맥을 변수 선언하는 시점에 주석으로 적어주면 더 좋지 않을까 싶습니다!

Comment thread word-search/novacat25.ts Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: In Review

Development

Successfully merging this pull request may close these issues.

4 participants