Skip to content

[kimyoung] WEEK 01 Solutions #321

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

Merged
merged 6 commits into from
Aug 17, 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
13 changes: 13 additions & 0 deletions contains-duplicate/kimyoung.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
var containsDuplicate = function (nums) {
let set = new Set(); // create a set to keep track of items within the nums array
for (const el of nums) set.add(el); // add items to the set, duplicates will automatically be ignored (set vs map)
return set.size !== nums.length; // compare the length of nums array and the size of the set, which shows if there's a duplicate or not
};

// test cases
console.log(containsDuplicate([])); // false
console.log(containsDuplicate([1, 2, 3, 1])); // true
console.log(containsDuplicate([1, 2, 3, 4])); // false

// space - O(n) - creating a set to store elements
// time - O(n) - traverse through the array
15 changes: 15 additions & 0 deletions kth-smallest-element-in-a-bst/kimyoung.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
var kthSmallest = function (root, k) {
const nums = [];
function helper(node) { // helper method to traverse the binary tree to map the node values to nums array
if (!node) return;
nums.push(node.val);
if (node.left) helper(node.left); // recursive call to left node if it exists
if (node.right) helper(node.right); // recursive call to right node if it exists
}
helper(root);
const sorted = nums.sort((a, b) => a - b); // sort the nums array
return sorted[k - 1]; // return kth smallest val
};

// space - O(n) - mapping node values into nums array
// time - O(nlogn) - sort
16 changes: 16 additions & 0 deletions number-of-1-bits/kimyoung.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
var hammingWeight = function (n) {
let bitVal = n.toString(2); // convert input value to bit
Copy link
Contributor

Choose a reason for hiding this comment

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

저를 포함해서 다른 분들도 pythonic한 풀이를 많이 사용하셨는데, 비트연산을 활용한 Brian Kernighan's Algorithm도 참고해보시면 좋을 것 같습니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

리뷰 해주셔서 감사합니다! 저도 스스로 문제들 풀어보고 (PR 섭밋 후) 달레님께서 제공해주신 풀이들을 봤는데, 말씀 해주신 알고리즘을 접할수 있었습니다! 따로 체크인은 안했지만 릿코드에서 다시 한번 풀어봤는데 다른 접근 방식이 있다는게 신기하더라고요 👍

let setBits = 0;
for (const char of bitVal) { // iterate through the string bit value to check the number of "1"s
if (char === "1") setBits++; // increment if char === "1"
}
return setBits;
};

// test cases
console.log(hammingWeight(11)); // 3
console.log(hammingWeight(128)); // 1
console.log(hammingWeight(2147483645)); // 30

// space - O(1) - created only constant variables
// time - O(n) - iterate through the bitVal string (larger the number the longer the string)
29 changes: 29 additions & 0 deletions palindromic-substrings/kimyoung.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
var countSubstrings = function (s) {
let result = 0;
for (let i = 0; i < s.length; i++) {
let left = i,
right = i; // odd length substrings
helper(s, left, right);
Copy link
Contributor

Choose a reason for hiding this comment

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

이건 알고리즘과는 관련 없는 이야기지만, helper 보다는 해당 함수의 역할을 나타내는 이름이 가독성을 위해 좋을 것 같습니다

Copy link
Contributor Author

Choose a reason for hiding this comment

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

저도 모르게 helper 로 쓰는게 습관이 되었네요. 좋은 지적해주셔서 감사합니다!


(left = i), (right = i + 1); // even length substrings
helper(s, left, right);
}
function helper(s, l, r) {
// increment result and keep expanding left and right, while left and right indexes are within range and they're equal
while (l >= 0 && r <= s.length && s[l] === s[r]) {
result++;
l--;
r++;
}
}
return result;
};

// test cases
console.log(countSubstrings("abc")); // 3
console.log(countSubstrings("aaa")); // 6
console.log(countSubstrings("a")); // 1
console.log(countSubstrings("")); // 0

// space - O(1) - constant variable `result`
// time - O(n^2) - iterating through the string and expanding both ways
19 changes: 19 additions & 0 deletions top-k-frequent-elements/kimyoung.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
var topKFrequent = function (nums, k) {
let obj = {};
for (const num of nums) {
obj[num] ? obj[num]++ : (obj[num] = 1);
}
let sorted = Object.entries(obj).sort((a, b) => b[1] - a[1]);
let result = [];
for (let i = 0; i < k; i++) {
result.push(sorted[i][0]);
}
return result;
};

// test cases
console.log(topKFrequent([1, 1, 1, 2, 2, 3], 2)); // [1, 2]
console.log(topKFrequent([1], 1)); // [1]

// space - O(n) - mapping the object in [key, freq]
// time - O(nlogn) - sorting the mapped objects in the order of frequency