Skip to content
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

[선재] WEEK02 Solutions #341

Merged
merged 7 commits into from
Aug 25, 2024
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* @description
* time complexity: O(n^2)
* space complexity: O(n)
*
* brainstorming:
* stack, Drawing a graph
*
* strategy:
* discover the rules
* leftStack = left create , rightStack = right create
*/
var buildTree = function (preorder, inorder) {
let answer = null;
let pointer = 0;

const leftStack = [];
const rightStack = [];

preorder.forEach((val, i) => {
const node = new TreeNode(val);

if (i === 0) answer = node;

const leftLen = leftStack.length;
const rightLen = rightStack.length;

if (leftLen && rightLen) {
if (leftStack[leftLen - 1].left) rightStack[rightLen - 1].right = node;
else leftStack[leftLen - 1].left = node;
}
if (leftLen && !rightLen) leftStack[leftLen - 1].left = node;
if (!leftLen && rightLen) rightStack[rightLen - 1].right = node;

leftStack.push(node);

while (leftStack.length && pointer < inorder.length) {
if (leftStack[leftStack.length - 1].val !== inorder[pointer]) break;
rightStack.push(leftStack.pop());
pointer++;
}
});
Comment on lines +20 to +42
Copy link
Contributor

Choose a reason for hiding this comment

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

굉장히 멋진 풀이네요!


return answer;
};
24 changes: 24 additions & 0 deletions counting-bits/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @description
* time complexity: O(n log n)
* space complexity: O(N)
*
* brainstorming:
* convert integer to bit
* for loop
*
* strategy:
* string change to hash table
*/
var countBits = function (n) {
return Array.from({ length: n + 1 }, (_, i) => convertBitCount(i));
};

const convertBitCount = (n) => {
let count = 0;
while (n > 0) {
count += n % 2;
n = Math.floor(n / 2);
}
return count;
};
76 changes: 76 additions & 0 deletions decode-ways/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* @description
* brainstorming:
* 1. dp -> dp[i] = dp[i-1] + count
* 2. recursive function
*
* strategy:
* https://www.algodale.com/problems/decode-ways/
*
* result:
* 1. couldn't think of the conditions
* true: 1~9, 10~27
* false: 0, 0N, 28↑
* 2. persist solution that is top down
*/
Comment on lines +10 to +15
Copy link
Contributor Author

Choose a reason for hiding this comment

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

해당부분은 직접 풀어보려 시도했지만 풀지 못한관계로 알고달레 블로그 참고해서 작성했습니다.


// https://www.algodale.com/problems/decode-ways/ Solve 1
/**
* time complexity: O(2^n)
* space complexity: O(n)
*/
var numDecodings = function (s) {
const search = (start) => {
if (start === s.length) return 1;
if (s[start] === "0") return 0;
if (start + 1 < s.length && Number(`${s[start]}${s[start + 1]}`) < 27) {
return search(start + 1) + search(start + 2);
}
return search(start + 1);
};

return search(0);
};

// https://www.algodale.com/problems/decode-ways/ Solve 2
/**
* time complexity: O(2^n)
* space complexity: O(n)
*/
var numDecodings = function (s) {
const memo = new Map();
memo.set(s.length, 1);

const search = (start) => {
if (!!memo.get(start)) return memo.get(start);

if (s[start] === "0") memo.set(start, 0);
else if (start + 1 < s.length && Number(`${s[start]}${s[start + 1]}`) < 27)
memo.set(start, search(start + 1) + search(start + 2));
else memo.set(start, search(start + 1));

return memo.get(start);
};

return search(0);
};

// https://www.algodale.com/problems/decode-ways/ Solve 3
/**
* time complexity: O(n)
* space complexity: O(n)
*/
var numDecodings = function (s) {
const dp = Array.from({ length: s.length + 1 }, (_, i) =>
i === s.length ? 1 : 0
);

for (let i = s.length - 1; i >= 0; i--) {
if (s[i] === "0") dp[i] = 0;
else if (i + 1 < s.length && Number(`${s[i]}${s[i + 1]}`) < 27)
dp[i] = dp[i + 1] + dp[i + 2];
else dp[i] = dp[i + 1];
}

return dp[0];
};
74 changes: 74 additions & 0 deletions palindromic-substrings/sunjae95.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,77 @@ var countSubstrings = function (s) {

return answer.length;
};

/**
* @description
* WEEK 01 Feedback
* 1. remove slice and change to endpoint
* 2. kadane's algorithm
*
* time complexity: O(N^3)
* space complexity: O(1)
*
* result
* solution 1 apply
*/
var countSubstrings = function (s) {
let answer = 0;
const len = s.length;

for (let startIndex = 0; startIndex < len; startIndex++) {
let subStr = "";
let isSubPalindromic = true;
answer++;

for (let endIndex = startIndex + 1; endIndex < len; endIndex++) {
if (isSubPalindromic && s[startIndex] === s[endIndex]) answer++;
subStr += s[endIndex];
Comment on lines +109 to +115
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@DaleSeo
slice를 하지말고 마지막을 추가하면서 계산하라는 말씀이 이 부분이 맞을까요?

Copy link
Contributor

Choose a reason for hiding this comment

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

제 피드백을 약간 잘못 이해하신 것 같습니다. 저는 아래에 있는 isPalindromic() 함수에 대해서 말씀을 드렸어요. 이 함수가 부분 문자열을 인자로 받는 대신에 시작 인덱스와 종료 인덱스를 받게 변경하면 공간 복잡도를 O(n)에서 O(1)로 개선할 수 있을 것 같다는 의견을 드렸습니다. 현재 코드는 여전히 O(n)의 공간을 쓰는 것으로 보입니다. 왜냐하면 subStr 변수에 최대 n개의 글자가 저장될 수 있기 때문입니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

엇.. 그렇군요! 이 부분은 다시 고민해보겠습니다 ㅎㅎ

isSubPalindromic = isPalindromic(subStr);
}
}

return answer;
};

function isPalindromic(str) {
const len = str.length;
const middleIndex = Math.floor(len / 2);

for (let i = 0; i < middleIndex; i++) {
if (str[i] !== str[len - 1 - i]) return false;
}

return true;
}
/**
* @description
* WEEK 01 Feedback
* 1. remove slice and change to endpoint
* 2. kadane's algorithm
*
* time complexity: O(N^2)
* space complexity: O(1)
*
* result
* solve 3(https://www.algodale.com/problems/palindromic-substrings/) include 1,2 solution
*/
var countSubstrings = function (s) {
let count = 0;
const len = s.length;

for (let i = 0; i < len; i++) {
let [start, end] = [i, i];

while (s[start] === s[end] && start >= 0 && end < len) {
count++;
[start, end] = [start - 1, end + 1];
}
[start, end] = [i, i + 1];
while (s[start] === s[end] && start >= 0 && end < len) {
count++;
[start, end] = [start - 1, end + 1];
}
Comment on lines +152 to +160
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@YeonguChoe
kadane's 알고리즘을 검색해보니 부분합이이라는 것을 알게 됐네요. 적용하다보니 달레님 블로그 솔루션 3번으로 귀결됐습니다 :)

Copy link
Contributor

Choose a reason for hiding this comment

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

나이스샷!

}

return count;
};
31 changes: 31 additions & 0 deletions valid-anagram/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @description
* time complexity: O(N)
* space complexity: O(N)
*
* brainstorming:
* 1. hash table value compare to count
*
* strategy:
* string change to hash table
*/
var isAnagram = function (s, t) {
if (s.length !== t.length) return false;

let answer = true;
const tableS = convertHashTable(s);
const tableT = convertHashTable(t);

tableS.forEach((_, key) => {
if (tableT.get(key) && tableT.get(key) === tableS.get(key)) return;
answer = false;
});
DaleSeo marked this conversation as resolved.
Show resolved Hide resolved

return answer;
};

const convertHashTable = (str) =>
str.split("").reduce((map, s) => {
map.set(s, (map.get(s) ?? 0) + 1);
return map;
}, new Map());
Loading