Skip to content

[novacat25] WEEK 02 Solutions - #2933

Open
novacat25 wants to merge 17 commits into
DaleStudy:mainfrom
novacat25:week2
Open

novacat25 wants to merge 17 commits into
DaleStudy:mainfrom
novacat25:week2

Conversation

@novacat25

@novacat25 novacat25 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

답안 제출 문제

작성자 체크 리스트

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

검토자 체크 리스트

Important

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

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

@dalestudy

dalestudy Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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

@novacat25 novacat25 changed the title Week2 [novacat25] WEEK 02 Solutions Nov 16, 2026

@Yu-Jaeyoung Yu-Jaeyoung left a comment

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.

안녕하세요? 평소 TypeScript를 좋아해서 comments 남기게 되었습니다.

아직 풀이를 valid-anagram까지 밖에 안한 상태라, 이에 대한 comment만 짧게 남겨보았습니다.

매주 찾아와서 열심히 comment 남기고, 저도 개인적으로 TS 풀이 진행해보도록 하겠습니다.

좋은 하루보내세요 👍🏻

return true
}

// 기존 풀이/제출 내역.

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.

풀이한 흐름을 남겨두는게 정말 좋은것 같습니다 😃

참고하겠습니다 !!

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.

AI Reviewer는 '주석 있으면 가독성 떨어지니 지우라'고 하지만,
그래도 스스로 학습한 부분은 또 남기고 싶어지더라고요 ㅎㅎ

Comment thread valid-anagram/novacat25.ts Outdated
@@ -0,0 +1,151 @@
/*
시간 복잡도(TC): O(n)
공간 복잡도(SC): O(n)

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.

3트에서 공간복잡도를 O(1)까지 줄인것으로 확인했습니다!

수정이 필요해보입니다 😃

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 isAnagram = (s: string, t: string): boolean => {
if(s.length !== t.length) return false
const anagramMap = new Map<string, number>()

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.

Map을 사용하는 방법이 공간 복잡도는 높지만,
TypeScript 답게 작성된 문법인것 같네요 😆

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 valid-anagram/novacat25.ts Outdated
if (s.length !== t.length) return false

const BASE_CHAR_CODE = "a".charCodeAt(0)
const countArr = new Array(26).fill(0)

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.

new Array<number>(26).fill(0) 으로 작성해서 타입을 명확하게 하는건 어떨까요?
사람이 작성하다 보면 뒤에서 실수 할수도 있을 것 같아 의견 남겨봅니다 !

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.

오, 확실히 이 부분 any[]로 뜹니다..!
const countArr: number[]로도 가능하겠지만, 로 Generic을 이용해서도 고칠 수 있었군요.
하나 배워갑니다!

@novacat25 novacat25 moved this from Solving to In Review in 리트코드 스터디 9기 Nov 16, 2026
Comment thread valid-anagram/novacat25.ts Outdated
return false
}

countArr[code - BASE_CHAR_CODE]--

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.

안녕하세요 @novacat25 님 :)
저는 s, t 배열을 각각 만들어 마지막에 비교했는데, 배열 하나에서 t를 빼다가 0 이하가 되는 순간 바로 false를 반환해서 끝까지 loop를 돌지 않아도 되는 점이 인상적입니다 🙂
13줄의 길이 비교가 없었다면 마지막에 전부 0인지 확인하는 줄이 필요했을 텐데, 길이 비교 덕분에 그 과정을 생략할 수 있는 구조라 깔끔했습니다.
파이썬의 ord(-)로 문자 코드를 구하는 부분이 TS에서는 -.charCodeAt(0)에 대응되는군요!

사소하지만 code - BASE_CHAR_CODE가 25줄과 31줄에서 두 번 계산되어서, idx 같은 변수로 한 번만 구해 두면 더 깔끔할 것 같아요.

제 풀이에 도움 주셔서 감사합니다!

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.

도움이 되셨다니 다행입니다!
이쪽은 참고로 아예 전역으로 빼고, getCodeIndex 부분을 메소드화로 둘렀어요.
Reusability를 조금 더 중시하긴 했습니다.

const BASE_CHAR_CODE = "a".charCodeAt(0)

const getCodeIndex = (code: number) => code - BASE_CHAR_CODE

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.

아하, getCodeIndex로 분리해서 전역 함수로 두니 재사용하기 더 용이한 것 같네요!
설명 감사합니다 수고하셨습니다!

Comment on lines +50 to +76
/* 2트: Memoisation 활용(Top-down DP)
const countRecur = (n: number, memo: number[]) => {
// Base case
if (n < 0)
return 0
if (n === 0)
return 1
// If value is memoised
if (memo[n] !== -1) {
return memo[n]
}
// Memoise the state (dp[n] = dp[n-1] + dp[n-2])
memo[n] = countRecur(n - 1, memo) +
countRecur(n - 2, memo)
return memo[n]
}
const memoisedClimbStairs = (n: number) => {
const memo = Array(n + 1).fill(-1)
return countRecur(n, memo)
}
*/

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.

저랑 풀이 히스토리가 굉장히 비슷하네요..! 여담이지만 저도 2트에 Top-down DP로 풀었었습니다...
저는 0부터 시작하면 계단 수와 매칭이 안 되어서 1칸, 2칸의 답을 직접 넣고 시작했는데,
nova님께서는 남은 계단 수가 0이면 1, 음수면 이미 도착 지점을 넘어간 것이라 0으로 처리하셔서, 저처럼 1칸, 2칸을 따로 세팅할 필요가 없겠네요!
그리고 저는 메모(제 풀이에서는 dp에 대응)를 모두 0으로 초기화했는데, -1로 초기화하면 더 안전할 것 같네요 🙂

@novacat25 novacat25 Nov 17, 2026 •

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.

배열로서 '방문하지 않은 값'이 확실해야 하기 때문에, -1이 확실히 제일 안전하긴 하지요.
그래도 Bottom-up 방식이나 Tabulation 방식 전부 n < 0인 경우(유효하지 않은 위치) 0으로 초기화하기 때문에,
if(memo[n] !== 0)도 충분히 있을 법한 로직이지 않나 싶습니다.

dp[0] = 1(아무 이동 하지 않고 출발점),
dp[1] = 1(일단 한 칸 이동)

까지는 거의 다 같으니까요.

그리고 점화식 특징 상 n-1, n-2 값을 미리 계산해두고
i = 3부터 iteration 도는 방법도 알고달레 링크에도 소개되어 있다 보니, 아주 미세한 디테일차 아닐까 싶네요 ㅎㅎ

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을 기준으로 두는 편이지만, 이 문제처럼 n < 0을 0으로 처리하는 구조라면 0으로 두어도 충분히 성립하겠네요.
알고달레 풀이도 같이 확인해서 점검해봐야겠습니다
감사합니다~

Comment on lines +28 to +34
for (let i = 2; i <= n; i++) {
const current = prev1 + prev2

prev2 = prev1
prev1 = current
}

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.

최종 제출하신 풀이는 저와 구조는 동일한 것 같습니다
저는 파이썬이다보니 first, second = second, first + second처럼 튜플로 표현했는데,
궁금해서 찾아보니 ts에서는 쉼표만 쓰거나(소괄호 지원도 안 되네요!), [prev2, prev1] = [prev1, current]처럼 대괄호로 써야 작동하네요..
29~32줄을 current 없이 [prev2, prev1] = [prev1, prev1 + prev2] 한 줄로 줄일 수도 있을 것 같네요:)

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.

  for (let i = 2; i <= n; i++) {
    ;[prev2, prev1] = [prev1, prev1 + prev2]
  }

네, 이 부분은 말씀대로 current가 없어지는 만큼 한줄로 줄여지네요.
Prettier가 코드를 저장할 때마다 코드 스타일을 잡아줬는데, 앞에 ;가 붙은 게 인상적이었습니다.

다만, 이 부분은 확답이 힘들 것 같네요..
prev2에게 prev1 값을 덮고, prev1이 current를 받는다는 명시적인 의미 전달에 있어서 지금 방식이 조금 더 확실하다고 느꼈거든요!

그래서 이 부분은 조금 더 고민이 필요할 것 같습니다.
그래도 대안이 하나 생겨서 배워가네요.

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.

말씀을 듣고보니 무조건 줄을 줄이는 것보다, 무엇을 받는지 명시적으로 드러나는 것이 더 좋을 때도 있는 것 같습니다..! 이번 코드리뷰를 통해 많은 것을 배워가네요:)

Comment on lines +20 to +23
if (i === START_IDX) {
resultArr[i] = 1
continue
}

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.

저는 왼쪽 누적곱은 i = 0을 제외하고 i = 1부터 시작하고, 오른쪽은 마지막 칸에도 1을 곱하는 방식으로 했는데, 곱할 원소가 없는 양 끝에서 continue로 건너뛰셨네요!

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.

아, 이 부분은 작성 당시에 조금 더 의미를 확실하게 하고 싶어서 예외처리를 추가한 거긴 해요!
말씀대로 i = 1부터 시작, 마지막 칸에는 1로 곱하기 등의 방법도 충분히 유효하다고 봅니다.

그러고 보니, 이미 1로 fill이 되었는데 또 resultArr[0] = 1로 초기화하고 있었네요.
이 부분 조금 더 다듬어 볼 여지가 있겠어요.

@novacat25 novacat25 Nov 19, 2026 •

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.

제안 주신 부분,여러모로 검토해 보았습니다만 역시 continue로 불필요한 예외처리가 들어가 있는 것 같아 아예 뜯어고쳤습니다..ㅋㅋ

  const lastIdx = nums.length - 1

  for (let i = 1; i <= lastIdx; i++) {
    leftProductedVal *= nums[i - 1]
    resultArr[i] = leftProductedVal
  }

  for (let i = lastIdx - 1; i >= 0; i--) {
    rightProductedVal *= nums[i + 1]
    resultArr[i] *= rightProductedVal
  }

제가 쓴 코드 말고 배열을 쓰는 다른 코드들도 쭉 훑어 보았는데... START_IDX나 MAX_INDEX처럼 배열 인덱스에 상수 처리가 맞나? 는 의문이 들더라고요.
관례 상으로 보아도 const PI = 3.14 같이 값이 일관적인 경우라면 모를까, 배열 인덱스 같은 경우에는 일반적인 camelCase 변수로 두는 게 더 나아 보이더라고요.

따라서, 시작 부분은 0으로 처리, 배열 top 부분은 lastIdx로 설정했습니다!

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.

언어별로도 변수명 관례가 상이한 것 같네요..
저는 주로 lowercase로만 변수명을 작성하는데 공부하면 할수록 새롭네요 ㅎㅎ
continue를 제외하고 반복 범위로 처리하니 더 깔끔해진 것 같네요
저는 continue 쓸 생각은 못했어서 리뷰를 남긴건데 덕분에 또 다른 풀이가 나온 것 같아 배워갑니다🙂

Comment on lines +25 to +26
leftProductedVal *= nums[i - 1]
resultArr[i] = leftProductedVal

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.

저는 answer[i - 1]에 nums[i - 1]을 곱해 answer[i]에 저장하는 식으로 했는데, leftProductedVal 변수에 따로 누적하니 더 명시적인 것 같네요..! 풀이가 비슷하면서도 정의방식이 달라 코드 읽는 재미가 있네요 ㅎㅎ
수고하셨습니다!

Comment thread 3sum/novacat25.ts
Comment on lines +33 to +34
while (j < k && nums[j] === nums[j - 1]) j++
while (j < k && nums[k] === nums[k + 1]) k--

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.

저는 중복 제거는 set으로 설정!이라는 나름 저만의 규칙을 정해두고 코드를 짜는데,
res를 일반 배열로 두고 탐색 과정에서 중복값을 제외하는 방법도 시간복잡도는 비슷해서 문제풀이의 흐름을 파악하기에 더 용이한 것 같습니다.
저 정답을 찾은 뒤 left, right를 한 칸씩만 이동해서 중복 조합이 발생할 수 있는데, 이 부분에서 같은 값을 건너뛰면 굳이 set을 쓰지 않아도 될 것 같네요 🙂

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.

네, 탐색 중에 중복을 아예 치워버리면 나중에 tuple이나 set 등의 처리가 들어가지 않아도 그만큼 이득이긴 하니까요!

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.

이번에 백준 재오픈한김에 https://acmicpc.net/problem/3273
투 포인터 기법으로 다시 풀어봤는데, leetcode문제보다는 두 합이라서 더 난이도는 쉽지만
확실히 적용방법을 알게되어서 좋네요~!
감사합니다:)

Comment on lines +11 to +13
const BASE_CHAR_CODE = "a".charCodeAt(0)

const getCodeIndex = (code: number) => code - BASE_CHAR_CODE

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.

👍 유니코드와 알파벳 숫자의 수로 제한해둔 풀이 방법이 좋은 것 같습니다.

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.

처음에는 정렬이나 Map 등을 생각했는데,
문제 조건으로 힌트를 보고 나서 이런 방법이 있더라고요..!
저도 그래서 공간 복잡도를 이렇게 아낄 수 있었구나..하고 배웠습니다.

Comment on lines +18 to +23

const dfs = (node: TreeNode | null, low: number, high: number): boolean => {
if (!node) return true // Null인 Node는 BST 조건을 만족한다고 간주해 재귀적으로 True를 반환한다.
if (!(low < node.val && node.val < high)) return false // 현재 Node의 값이 허용 범위에 속하지 않으면 False를 반환한다.
return dfs(node.left, low, node.val) && dfs(node.right, node.val, high) // 왼쪽 서브트리와 오른쪽 서브트리를 재귀적으로 확인하며, 허용 범위를 갱신한다.
}

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이렇게 해서 값이 오름차순이 나오는지를 코드로 구현하였는데
low, high로 범위를 두고 노드값의 포함범위를 좁혀 나가는 방식도 굉장히 깔끔하네요!

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.

네, left->Parent-> child, Parent에서 left-child 전개 등 각자 풀이 방식이 있는 것 같더라고요..!
저는 Parent에서도 left/right를 재귀적으로 불러 해결했습니다.

}

const dfs = (node: TreeNode | null, low: number, high: number): boolean => {
if (!node) return true // Null인 Node는 BST 조건을 만족한다고 간주해 재귀적으로 True를 반환한다.

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.

!node로 빈 노드는 바로 건너뛰는건요

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.

네! child로 node.left / node.right를 부를 때, 저 조건문을 충족시켜 검사를 아예 빠집니다.


const dfs = (node: TreeNode | null, low: number, high: number): boolean => {
if (!node) return true // Null인 Node는 BST 조건을 만족한다고 간주해 재귀적으로 True를 반환한다.
if (!(low < node.val && node.val < high)) return false // 현재 Node의 값이 허용 범위에 속하지 않으면 False를 반환한다.

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.

질문이 있습니다..!
파이썬에서는 low < node.val < high처럼 부등식을 한번에 쓸 수 있는데, TS에서는 이렇게 쓰면 안 되는 건가요?

@novacat25 novacat25 Nov 21, 2026 •

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.

image 네, TS에서는 이렇게 오류가 터지는 것 같더라고요..! image 이렇게 처리해야 하는 것 같습니다.

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.

오 ts에서는 operator 연산자를 boolean과 number 사이에는 쓸 수 없다는 내용 새롭게 알고갑니다!
더불어 파이썬의 and 대신 &&로 쓰는 표기법도 배우고 갑니다~

}
}

const dfs = (node: TreeNode | null, low: number, high: number): boolean => {

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.

ts에서는 반환타입 (여기서는 boolean)을 항상 명시해줘야하는지 궁금합니다..!
이 문제에서는 dfs 함수가 true/false를 return해서 boolean을 따로 써 주신 건지 궁금했습니다 🙂

@novacat25 novacat25 Nov 21, 2026 •

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.

보통은 TS에서 return value 값을 보고 추론을 해 주기 때문에 생략해도 문제는 없습니다.
타입 추론이 확실하고 코드로 알아챌 수 있다면 없는 게 나을 수 있으며,

(나쁜 예시)

const name = "John"
const age = 20
const names = ["John", "Terry"]

TypeScript가 일반적으로 추론하기 힘든 경우(Generic, API response 등)거나

const users: User[] = []
const [users, setUsers] = useState<User[]>([])

타입이 코드의 설계 의도를 나타낸다면

type UserStatus = "active" | "inactive" | "pending"

const getUserStatus = (user: User): UserStatus => {
  // 복잡한 비즈니스 로직
}

이런 식으로 명시해주는 게 좋다고 하네요.

하지만, 이번 dfs 코드 같은 경우에는 재귀함수가 불러져 있는 이유인지 자력으로 Type Check가 불가능한 상황이었으며,
타입 명시를 통해 분명하게 해줘야 했습니다.

const dfs = (node: TreeNode | null, low: number, high: number) => {
  if (!node) return true // Null인 Node는 BST 조건을 만족한다고 간주해 재귀적으로 True를 반환한다.
  if (!(low < node.val && node.val < high)) return false // 현재 Node의 값이 허용 범위에 속하지 않으면 False를 반환한다.
  return dfs(node.left, low, node.val) && dfs(node.right, node.val, high) // 왼쪽 서브트리와 오른쪽 서브트리를 재귀적으로 확인하며, 허용 범위를 갱신한다.
}

'dfs' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.

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.

상세한 예시까지 들어주셔서 감사합니다
추론이 확실한 경우엔 생략하는 게 더 깔끔하고, 반대의 케이스나 타입이 설계 의도를 드러낼 때는 명시하는 게 좋군요
dfs처럼 반환식에서 자기 자신을 호출한 결과를 반환하는 재귀 함수는 반환 타입을 명시해 줘야 한다는 점도 알고 갑니다!

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.

저야말로 이번에 또 블로그 포스트 주제로 타입 추론/명시 부분이 떠오른 거 있죠..!
덕분에 이번 기회에도 싹 몰아서 정리할 수 있었어요.

@Chaewon-Park-STUDY Chaewon-Park-STUDY Nov 21, 2026 •

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.

이번 블로그 글도 기대하겠습니다..! 감사합니다:) 이번주차도 정말 수고많으셨습니다

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