-
Notifications
You must be signed in to change notification settings - Fork 126
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
[pepper] WEEK 2 Solution #363
Merged
Merged
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
33af494
1. valid-anagram
whewchews 31b7ee6
2: counting bits
whewchews 8f4e343
4. construct-binary-tree-from-preorder-and-inorder-traversal
whewchews 9529512
5. decode-ways
whewchews 4b4859b
4. binary tree 설명 추가
whewchews 6843903
1. replace || with ?? for safer nullish coalescing
whewchews File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
49 changes: 49 additions & 0 deletions
49
construct-binary-tree-from-preorder-and-inorder-traversal/whewchews.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
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; | ||
} | ||
} | ||
|
||
/** | ||
* preorder: [root, left, right] | ||
* inorder: [left, root, right] | ||
* preorder의 첫번째 값은 root이다. (1. 현재 root 찾기) | ||
* 모든 node의 val는 unique하기 때문에 이 값을 기준으로 inorder에서 root의 위치를 찾을 수 있다. | ||
* | ||
* inorder에서 root의 위치를 찾으면, root를 기준으로 왼쪽은 left subtree, 오른쪽은 right subtree이다. (2. left subtree, right subtree 구분) | ||
* inorder: [...left, root, ...right] | ||
* root값은 이미 찾았기 때문에 shift로 제거한다. | ||
* | ||
* 남은 preorder에서 첫번째 값은 left subtree의 root이다. (3. left subtree 구성) | ||
* preorder에서 하나씩 shift하면서 왼쪽 트리를 먼저 구성한다. | ||
* preorder에서 첫번째 값이 왼쪽 subtree의 root이다. (1. 현재 root 찾기) | ||
* inorder에서 root의 위치를 찾아서 왼쪽 subtree를 구성한다. (2. left subtree, right subtree 구분) (3. left subtree 구성) | ||
* root 기준 왼쪽 subtree 구성이 끝나면 오른쪽 subtree를 구성한다. | ||
* 위 과정을 재귀적으로 반복하면, 전체 트리를 구성할 수 있다. (1-3 과정 반복) | ||
*/ | ||
function buildTree(preorder: number[], inorder: number[]): TreeNode | null { | ||
// build 함수가 각 노드마다 호출됨(N) * 각 노드마다 shift, indexOf 수행(N) = O(N^2) | ||
function build(preorder, inorder) { | ||
if (inorder.length) { | ||
// TC: O(N) | ||
const idx = inorder.indexOf(preorder.shift()); | ||
const root = new TreeNode(inorder[idx]); | ||
|
||
root.left = build(preorder, inorder.slice(0, idx)); | ||
root.right = build(preorder, inorder.slice(idx + 1)); | ||
|
||
return root; | ||
} | ||
return null; | ||
} | ||
|
||
return build(preorder, inorder); | ||
} | ||
|
||
// TC: O(N^2) | ||
// SC: O(N^2) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
function countBits(n: number): number[] { | ||
// SC: O(N) | ||
const ans = Array(n + 1).fill(0); | ||
// TC: O(N) | ||
for (let i = 1; i <= n; i++) { | ||
let k = i; | ||
|
||
// TC: O(log N) | ||
while (k > 0) { | ||
ans[i] += k % 2; | ||
k = Math.floor(k / 2); | ||
} | ||
} | ||
|
||
return ans; | ||
} | ||
|
||
// TC: O(N log N) | ||
// SC: O(N) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
function numDecodings(s: string): number { | ||
// SC: O(N) | ||
const memo: { [key: number]: number } = { [s.length]: 1 }; | ||
|
||
// TC: O(N) | ||
const dfs = (start: number): number => { | ||
if (start in memo) { | ||
return memo[start]; | ||
} | ||
|
||
if (s[start] === "0") { | ||
// 0으로 시작하는 경우 가능한 경우의 수가 없음 | ||
memo[start] = 0; | ||
} else if ( | ||
start + 1 < s.length && | ||
parseInt(s.substring(start, start + 2)) < 27 | ||
) { | ||
// 다음에 오는 글자가 두글자 이상 있고, start start+1 두글자가 1~26 사이의 값인 경우 | ||
memo[start] = dfs(start + 1) + dfs(start + 2); | ||
} else { | ||
// 1글자만 남은 경우 or 첫 두글자가 27보다 큰 경우 | ||
memo[start] = dfs(start + 1); | ||
} | ||
|
||
return memo[start]; | ||
}; | ||
|
||
// SC: 재귀호출 O(N) | ||
return dfs(0); | ||
} | ||
|
||
// TC: O(N) | ||
// SC: O(N) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
function isAnagram(s: string, t: string): boolean { | ||
// TC: O(1) | ||
if (s.length !== t.length) return false; | ||
|
||
// SC: O(N) | ||
const count: { [key: string]: number } = {}; | ||
|
||
// TC: O(N) | ||
for (let i = 0; i <= s.length - 1; i++) { | ||
const sChar = s[i]; | ||
const tChar = t[i]; | ||
count[sChar] = (count[sChar] || 0) + 1; | ||
count[tChar] = (count[tChar] || 0) - 1; | ||
} | ||
|
||
// TC: O(N) | ||
return Object.values(count).every((v) => v === 0); | ||
} | ||
|
||
// TC: O(N) | ||
// SC: O(N) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: 이 문제의 경우 무방하지만, 일반적으로는
||
대신에??
를 사용하는 것이 더 안전하지 않을까 생각이 들었습니다.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
감사합니다! 말씀해주신대로 ?? 을 사용하는게 좋을 것 같습니다.
이런 코드에서는 원하는 값이 없는 경우에, 기본값을 사용할 목적이니 JS의 falsy한 값을 모두 처리하는 ||(논리OR연산자)가 아닌 null이나 undefined 값만 처리하는 ??(널병합연산자) 를 사용하는게 더 목적에 맞고 안전하게 처리해줄 수 있겠네요!