Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
22 changes: 22 additions & 0 deletions contains-duplicate/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* @description
* time complexity: O(n)
* space complexity: O(n)
* approach/strategy:
* 1. brute force + hash table
*/

/**
* @param {number[]} nums
* @return {boolean}
*/
var containsDuplicate = function (nums) {
const hashTable = new Set();

for (const num of nums) {
if (hashTable.has(num)) return true;
hashTable.add(num);
}

return false;
};
33 changes: 33 additions & 0 deletions kth-smallest-element-in-a-bst/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @description
* time complexity: O(N)
* space complexity: O(N)
*
* brainstorming:
* 1. BFS, DFS
* 2. Brute force
*
* strategy:
* inOrder search
*
* reason:
* tree features
*/
var kthSmallest = function (root, k) {
let answer = 0;

inOrder(root, (value) => {
k -= 1;
if (k > 0) return false;
if (k === 0) answer = value;
return true;
});

return answer;
};

function inOrder(tree, isEnd) {
if (tree.left) inOrder(tree.left, isEnd);
if (isEnd(tree.val)) return;
if (tree.right) inOrder(tree.right, isEnd);
}
22 changes: 22 additions & 0 deletions number-of-1-bits/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* @description
* time complexity: O(logN)
* space complexity: O(1)
* approach/strategy:
* 1. decimal to binary
*/

/**
* @param {number} n
* @return {number}
*/
var hammingWeight = function (n) {
let answer = 0;

while (n > 0) {
answer += n % 2;
n = Math.floor(n / 2);
}

return answer;
};
90 changes: 90 additions & 0 deletions palindromic-substrings/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/**
* @description
* time complexity: O(N^3)
* space complexity: O(N)
*
* brainstorming:
* 1. stack, permutation
* 2. Brute force
*
* strategy:
* Brute force, calculate
*
* reason:
* intuitive way
*
* @param {string} s
* @return {number}
*/
var countSubstrings = function (s) {
let answer = 0;
const len = s.length;

for (let i = 0; i < len; i++) {
for (let j = i + 1; j < len + 1; j++) {
const subStr = s.slice(i, j);
if (isPalindrome(subStr)) answer++;
}
}

return answer;
};

function isPalindrome(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
* time complexity: O(N^2)
* space complexity: O(N^2)
*
* brainstorming:
* 1. https://sbslc.tistory.com/56
*
* strategy:
* dynamic programming
*
* reason:
* to challenge dp
*
* @param {string} s
* @return {number}
*/
var countSubstrings = function (s) {
const answer = [];
const MAX_LENGTH = s.length;
const dp = Array.from({ length: MAX_LENGTH }, (_, i) =>
Array.from({ length: MAX_LENGTH }, (_, j) => {
if (i === j) answer.push(s[i]);
return i === j;
})
);
// Check next step ex) aa, bb, cc
for (let i = 0; i < MAX_LENGTH - 1; i++) {
const nextIndex = i + 1;
if (s[i] === s[nextIndex]) {
dp[i][nextIndex] = true;
answer.push(s.slice(i, nextIndex + 1));
}
}
// Check against values calculated in the previous step
for (let len = 2; len <= MAX_LENGTH; len++) {
for (let i = 0; i < MAX_LENGTH - len; i++) {
const lastIndex = len + i;
if (s[i] === s[lastIndex] && dp[i + 1][lastIndex - 1]) {
dp[i][lastIndex] = true;
answer.push(s.slice(i, lastIndex + 1));
}
}
}

return answer.length;
};
31 changes: 31 additions & 0 deletions top-k-frequent-elements/sunjae95.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @description
* time complexity: O(N logN)
* space complexity: O(N)
*
* brainstorming:
* 1. javascript sort method
* 2. priority queue
*
* strategy:
* javascript sort method
*
* reason:
* javascript sort method is easier to implement.
Comment on lines +13 to +14
Copy link
Member

Choose a reason for hiding this comment

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

이렇게 이유를 남겨주시니 완전 납득이 되네요 ㅋㅋㅋ
다음 주차까지 아직 시간이 많으니 brainstorming하셨던 priority queue를 사용해서도 풀어보시면 좋을 것 같습니다. 물론 현실 프로젝트에서는 간단하고 읽기 쉬운 코드가 더 선호되지만, 코딩 테스트에서는 결국 더 효율적인 알고리즘을 제시하는 것이 목표이니까요.

*/

var topKFrequent = function (nums, k) {
const answer = [];
const array = [];
const hashTable = new Map();

nums.forEach((num) => hashTable.set(num, (hashTable.get(num) ?? 0) + 1));

hashTable.forEach((count, number) => array.push({ number, count }));

array.sort((a, b) => b.count - a.count);

for (let i = 0; i < k; i++) answer.push(array[i].number);
Copy link
Contributor

Choose a reason for hiding this comment

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

이렇게 구현하셔도 좋습니다. 그런데 .slice()를 사용해서 구현해도 더 짧은 코드로 같은 의도를 전달할 수 있을것 같습니다.

Copy link
Member Author

Choose a reason for hiding this comment

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

haklee님 안녕하세요 첫 리뷰어시네요 방문감사합니다 :)
리뷰내용이 answer 배열대신 array에서 값을 리턴하라는 의도로 해석되는데요.

만약에 제가 해석한 의도가 맞다면 for문을 사용한 이유는 아래와 같습니다.
slice에 데이터를 정제할 수 있는 부분이 있으면 좋겠지만 JS의 array.slice 내장 메서드는 값을 변경하는 기능이 존재하지 않습니다. slice를 사용한다면 데이터가 원시값이 아닌 객체로 이기에 데이터를 변경해야하므로 배열을 한번더 순회해야하는 불편함이 있기에 for문으로 작성하게 됐네요.

리뷰해주신 의도가 제가 답변한 내용과 맞을까요?
혹시 틀리거나 잘못된 내용있다면 확인후 코멘트 부탁드립니다 :)

Copy link
Contributor

Choose a reason for hiding this comment

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

어떤 의도셨는지는 알겠습니다! 제가 js를 아주 잘 알지는 않아서 궁금한 것이 있는데요, 혹시 slice 후 map을 사용하는 것과 k번 array에 push하는 것 중에 어떤 것이 오버헤드가 더 크게 걸릴까요? 알고리즘의 TC가 O(N logN)이라고 적어주셔서 동작에는 크게 영향을 주지 않을 것이라 중요한 질문은 아닙니다.

Copy link
Member Author

Choose a reason for hiding this comment

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

결론은 둘다 O(n)으로 동일입니다.

코멘트보고 곰곰이 생각해봤는데요. slice와 map은 별개로 동작해서 O(n) + O(n) 으로 시간복잡도가 계산되네요?
제가 method chaining 으로 인해 O(n^2)로 된다고 잘못알고있었네요.

이러면 haklee님 리뷰내용대로 array.slice().map()으로 구현하면 명시적일거 같습니다.

중요한 질문이었네요. 감사합니다 :)


return answer;
};