Skip to content
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
63 changes: 63 additions & 0 deletions alien-dictionary/hyer0705.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
export class Solution {
alienOrder(words: string[]): string {
const indegree = new Map<string, number>();
const graph = new Map<string, Set<string>>();

for (const word of words) {
for (const ch of word) {
if (graph.has(ch)) continue;
graph.set(ch, new Set<string>());
indegree.set(ch, 0);
}
}

for (let i = 0; i < words.length - 1; i++) {
const word1 = words[i];
const word2 = words[i + 1];

let pointer = 0;
while (pointer < word1.length && pointer < word2.length && word1[pointer] === word2[pointer]) {
pointer++;
}

if (pointer < word1.length && pointer === word2.length) {
return "";
}

if (pointer < word1.length && pointer < word2.length) {
const neighbors = graph.get(word1[pointer])!;
if (!neighbors.has(word2[pointer])) {
neighbors.add(word2[pointer]);
indegree.set(word2[pointer], (indegree.get(word2[pointer]) || 0) + 1);
}
}
}

const queue: string[] = [];
const result: string[] = [];

for (const [ch, degree] of indegree) {
if (degree === 0) {
queue.push(ch);
}
}

while (queue.length > 0) {
const current = queue.shift()!;
result.push(current);

for (const neighbor of graph.get(current) || []) {
indegree.set(neighbor, (indegree.get(neighbor) || 0) - 1);
if (indegree.get(neighbor) === 0) {
queue.push(neighbor);
}
}
}

if (indegree.size === result.length) {
return result.join("");
}

return "";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* Definition for a binary tree node.
* 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)
* }
* }
*/

// 37ms
// Time Complexity: O(n^2), n: 노드의 수
// Space Complexity: O(h), h: 트리의 높이
function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
if (preorder.length === 0 || inorder.length === 0) return null;

const root = preorder[0];

const rootIdx = inorder.findIndex((el) => el === root);

const leftInorder = inorder.slice(0, rootIdx);
const leftPreorder = preorder.slice(1, leftInorder.length + 1);

const rightInorder = inorder.slice(rootIdx + 1);
const rightPreorder = preorder.slice(leftInorder.length + 1);

const rootNode = new TreeNode(root);

rootNode.left = buildTree(leftPreorder, leftInorder);
rootNode.right = buildTree(rightPreorder, rightInorder);

return rootNode;
}

// 3ms
// Time Complexity: O(n), n: 노드의 수
// Space Complexity: O(n), n: 노드의 수
function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
if (preorder.length === 0 || inorder.length === 0) return null;

const indexMap = new Map<number, number>();
inorder.forEach((node, idx) => indexMap.set(node, idx));

const build = (preStart: number, preEnd: number, inStart: number, inEnd: number): TreeNode | null => {
if (preStart > preEnd || inStart > inEnd) return null;

const rootVal = preorder[preStart];
const rootIdx = indexMap.get(rootVal);

const leftSize = rootIdx - inStart;

const root = new TreeNode(rootVal);
root.left = build(preStart + 1, preStart + leftSize, inStart, rootIdx - 1);
root.right = build(preStart + leftSize + 1, preEnd, rootIdx + 1, inEnd);
Comment on lines +57 to +58
Copy link
Member

Choose a reason for hiding this comment

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

이 부분에서 어떤 기준으로 +1 을 하고 -1 을 하셨는지 여쭤봐도 될까요 ? 문제를 읽기만 하고 풀지는 못해서 여쭤봅니다

Copy link
Contributor Author

Choose a reason for hiding this comment

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

+1, -1을 하는 이유는 인덱스 범위를 조정하기 위함입니다.

먼저 기본 개념부터:

  • preorder[0]은 항상 현재 구간의 루트 노드
  • inorder에서 루트의 위치(rootIdx)를 찾으면,
    왼쪽은 왼쪽 서브트리, 오른쪽은 오른쪽 서브트리

예시: preorder = [4, 11, 56, 78], inorder = [11, 4, 56, 78]

  • root = 4 (preorder[0])
  • rootIdx = 1 (inorder에서 4의 위치)
  • 왼쪽 서브트리 크기(leftSize) = 1 (rootIdx - inStart = 1 - 0)

왼쪽 서브트리의 범위:
preorder: [11] → 인덱스 [1, 1]
inorder: [11] → 인덱스 [0, 0]

root.left = build(preStart + 1, preStart + leftSize, inStart, rootIdx - 1)

  • preStart + 1: 루트(preorder[0])를 건너뛰고 그 다음부터 시작
  • preStart + leftSize: 왼쪽 서브트리 크기만큼만 포함 (1 + 1 = 2, 하지만 범위는 [1,1])
  • inStart: 왼쪽 서브트리는 inorder의 시작점부터 시작하므로 그대로
  • rootIdx - 1: 루트 직전까지가 왼쪽 서브트리의 끝

오른쪽 서브트리도 같은 논리로:

  • preStart + leftSize + 1: 루트 + 왼쪽 서브트리를 건너뛴 다음부터
  • rootIdx + 1: 루트 다음부터가 오른쪽 서브트리의 시작


return root;
};

return build(0, preorder.length - 1, 0, inorder.length - 1);
}
31 changes: 31 additions & 0 deletions longest-palindromic-substring/hyer0705.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Time Complexity: O(n^2), n: s의 길이
// Space Complexity: O(1)
function longestPalindrome(s: string): string {
const expandAroundCenter = (s: string, left: number, right: number): [number, number] => {
while (left >= 0 && right < s.length && s[left] === s[right]) {
left--;
right++;
}

return [left + 1, right - 1];
};

let longest = "";
for (let i = 0; i < s.length; i++) {
const [s1, e1] = expandAroundCenter(s, i, i);
const [s2, e2] = expandAroundCenter(s, i, i + 1);

const odd = e1 - s1 + 1;
const even = e2 - s2 + 1;
Comment on lines +15 to +19
Copy link
Member

Choose a reason for hiding this comment

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

위의 expandAroundCenter 함수의 while 부분에서는 left 와 right 로 포인터를 잡아서 서로 길이가 같을때까지 루프를 도는 것 까지는 이해를 하였는데
여기 For 문에서의 s, i, i 와 s, i, i+1 을 사용하신 부분은 어떤 의도로 사용하신지가 궁금합니다 ㅎㅎ

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Palindrome이 홀수 길이일 경우, 짝수 길이일 경우에 대해서 체크하는 코드입니다.
예시) "토마토", "라랄랄라"

홀수의 경우는 left, right 포인터가 동일하면 되지만 짝수의 경우는 가운데가 두 개여야 하므로 s, i, i+1을 사용했습니다!

expandAroundCenter() 함수는 넘겨준 파라미터인 left와 right에서 시작해서 각각 왼쪽 오른쪽 문자가 같은지 확인해서 펠린드롬을 확인합니다. left, right가 가운데로 설정하는걸 홀수일 때, 짝수일 때 확인해보기 위해서 s, i, i 를 넣어 호출(홀수) 하고 s, i, i+1을 넣어 호출(짝수)하였습니다.


if (longest.length < odd) {
longest = s.slice(s1, e1 + 1);
}

if (longest.length < even) {
longest = s.slice(s2, e2 + 1);
}
}

return longest;
}
20 changes: 20 additions & 0 deletions rotate-image/hyer0705.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
Do not return anything, modify matrix in-place instead.
*/
// Time Complexity: O(n^2), n: matrix의 한 변의 길이
// Space Complexity: O(1)
function rotate(matrix: number[][]): void {
const n = matrix.length;

for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
[matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
}
}

for (let i = 0; i < n; i++) {
for (let j = 0; j < Math.floor(n / 2); j++) {
[matrix[i][j], matrix[i][n - j - 1]] = [matrix[i][n - j - 1], matrix[i][j]];
}
}
}
33 changes: 33 additions & 0 deletions subtree-of-another-tree/hyer0705.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* Definition for a binary tree node.
* 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)
* }
* }
*/

// Time Complexity: O(m * n), m: root의 노드 수, n: subRoot의 노드 수
// Space Complexity: O(h), h: root의 높이
function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean {
if (!root) return false;

const isSameTree = (root: TreeNode | null, subRoot: TreeNode | null): boolean => {
if (!root && !subRoot) return true;
if (!root || !subRoot) return false;
if (root.val !== subRoot.val) return false;

return isSameTree(root.left, subRoot.left) && isSameTree(root.right, subRoot.right);
};
Comment on lines +20 to +26
Copy link
Member

Choose a reason for hiding this comment

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

isSameTree 구현을 정석대로 잘 구현해주신 것 같습니다 ! ts 에서는 !root 가 Null 여부를 판단해주는 것 같아서 또 배워갑니다 ㅎㅎ
마지막에 subRoot 그 자체로 포함하는지, 그리고 left, right 한번씩 넣어주어 자식들을 재귀형식으로 탐색하는 방법으로 잘 구현해주신 것 같습니다


const current = isSameTree(root, subRoot);
const left = isSubtree(root.left, subRoot);
const right = isSubtree(root.right, subRoot);

return current || left || right;
}