Skip to content

[Sehwan] Week3 solutions with javascript #80

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 4 commits into from
May 18, 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
20 changes: 20 additions & 0 deletions climbing-stairs/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function (n) {
// Make an array to store each number of ways
let steps = new Array(n);
// When stairs is 1 and 2 has exact number 1 and 2
steps[1] = 1;
steps[2] = 2;
// Iterate to get ways of 3 more steps stairs
// ((n-1) + (n-2))
for (let i = 3; i <= n; i++) {
steps[i] = steps[i - 1] + steps[i - 2];
}
return steps[n];
};

// TC: O(n)
// SC: O(n)
Copy link
Contributor

Choose a reason for hiding this comment

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

간단하게 수정해서 O(1) 로도 가능한데 도전해보셔도 좋을 것 같습니다 : )

Copy link
Contributor

Choose a reason for hiding this comment

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

저도 처음에 O(n)으로 풀었지만, 다른 분들도 보니 처음부터 O(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.

네 찾아보니 공간복잡도를 O(1)으로 만드는게 가능하더라고요!

  // Initialize the first two steps
  let first = 1;
  let second = 2;

  // Iterate to compute the number of ways to reach step n
  for (let i = 3; i <= n; i++) {
    let current = first + second;
    first = second;
    second = current;
  }

피드백 감사드립니다!! :^)

46 changes: 46 additions & 0 deletions maximum-depth-of-binary-tree/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function (root) {
// Check root is null or not
if (root === null) {
return 0;
}
// Make queue array to store root and depth variable
let queue = [root];
let depth = 0;
// Iterate until there is an element inside of queue
while (queue.length > 0) {
// Record level size to avoid fault size measuring
let levelSize = queue.length;
Comment on lines +19 to +24
Copy link
Member

Choose a reason for hiding this comment

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

안녕하세요 세환님!

for 문 안에 node는 const keyword로 선언된 데 반해, queue랑 levelSize는 let로 선언한 이유가 따로 있을까요?

저 같은 경우는 처음에 변수를 선언할 때 먼저 const keyword로 선언하고 이후에 재할당 된다면 선언을 let으로 변경하는데요.
그렇게 행동하는 편이 나중에 코드를 읽을 때 해당 변수가 어떻게 조작될지 예측할 수 있고, 선언 이후에 실수로라도 의도치 않은 재할당을 방지할 수 있는 이득이 있기 때문이에요.

시간 나신다면, 혹시 아래 suggestion 참고해주셨으면 좋겠습니다!

Suggested change
let queue = [root];
let depth = 0;
// Iterate until there is an element inside of queue
while (queue.length > 0) {
// Record level size to avoid fault size measuring
let levelSize = queue.length;
const queue = [root];
let depth = 0;
// Iterate until there is an element inside of queue
while (queue.length > 0) {
// Record level size to avoid fault size measuring
const levelSize = queue.length;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

안녕하세요 Evan님!

네 코맨트 주신대로 queue와 levelSize는 const로 선언하는게 좋은 접근방법인것 같아요.
저도 실제 업무에는 const로 선언하고 시작하는 편인데 알고리즘 풀이할 땐 습관적으로 let을 과도하게 썼던 것 같습니다. 🤦🏻‍♂️

좋은 피드백 감사드려요!


for (let i = 0; i < levelSize; i++) {
// Grasp first element from the queue
const node = queue.shift();
// Push the left node into the queue
if (node.left) {
queue.push(node.left);
}
// Push the right node into the queue
if (node.right) {
queue.push(node.right);
}
}
// Increase depth value
depth++;
}

return depth;
};

// TC: O(n)
// SC: O(n)
32 changes: 32 additions & 0 deletions meeting-rooms/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Definition of Interval:
* class Interval {
* constructor(start, end) {
* this.start = start;
* this.end = end;
* }
* }
*/

class Solution {
/**
* @param {Interval[]} intervals
* @returns {boolean}
*/
canAttendMeetings(intervals) {
// Sort the intervals based on their start times
intervals.sort((a, b) => a.start - b.start);

for (let i = 0; i < intervals.length - 1; i++) {
// Check if the current interval overlaps with the next interval
if (intervals[i].end > intervals[i + 1].start) {
return false;
}
}

return true;
}
}

// TC: O(nlogn)
// SC: O(1)
24 changes: 24 additions & 0 deletions same-tree/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function (p, q) {
// If p and q is null, return true
if (!p && !q) return true;
// Compare root and length between p and q
if (!p || !q || p.val !== q.val) return false;
// Execute recursive function to search each tree
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};

// TC: O(n)
// SC: O(n)
39 changes: 39 additions & 0 deletions subtree-of-another-tree/nhistory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {TreeNode} subRoot
* @return {boolean}
*/
var isSubtree = function (root, subRoot) {
// Make function to check two triangle is same or not
const isSame = (root1, root2) => {
// If both of root1 and root2 is null, return true
if (!root1 && !root2) return true;
// If one of root1 and root2 is null or root1.val is not equal to root2.val, return false
if (!root1 || !root2 || root1.val !== root2.val) return false;
// Compare each left and right value with recursive
return isSame(root1.left, root2.left) && isSame(root1.right, root2.right);
};

// Make dfs function to check nodes inside of root tree
const dfs = (node) => {
// if node is null, return false
if (!node) return false;
// Check triangle is equal to subRoot
if (isSame(node, subRoot)) return true;
// Check one of the left or right node is same with triangle
return dfs(node.left) || dfs(node.right);
};
// Execute dfs function
return dfs(root);
};

// TC: O(n*m)
// SC: O(max(m,n))