diff --git a/3sum/jthw1005.js b/3sum/jthw1005.js new file mode 100644 index 0000000000..682244699b --- /dev/null +++ b/3sum/jthw1005.js @@ -0,0 +1,28 @@ +function threeSum(nums) { + const result = []; + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length - 2; i++) { + if (i > 0 && nums[i] === nums[i - 1]) continue; + + let left = i + 1; + let right = nums.length - 1; + + while (left < right) { + const sum = nums[i] + nums[left] + nums[right]; + if (sum === 0) { + result.push([nums[i], nums[left], nums[right]]); + left++; + right--; + + while (left < right && nums[left] === nums[left - 1]) left++; + while (left < right && nums[right] === nums[right + 1]) right--; + } else if (sum < 0) { + left++; + } else { + right--; + } + } + } + return result; +} diff --git a/climbing-stairs/jthw1005.js b/climbing-stairs/jthw1005.js new file mode 100644 index 0000000000..c4df4152a4 --- /dev/null +++ b/climbing-stairs/jthw1005.js @@ -0,0 +1,13 @@ +function climbStairs(n) { + const memo = {}; + + function dp(k) { + if (k === 1) return 1; + if (k === 2) return 2; + if (memo[k]) return memo[k]; + memo[k] = dp(k - 1) + dp(k - 2); + return memo[k]; + } + + return dp(n); +} diff --git a/product-of-array-except-self/jthw1005.js b/product-of-array-except-self/jthw1005.js new file mode 100644 index 0000000000..594036d0b8 --- /dev/null +++ b/product-of-array-except-self/jthw1005.js @@ -0,0 +1,18 @@ +function productExceptSelf(nums) { + const result = []; + let product = 1; + + for (let i = 0; i < nums.length; i++) { + result[i] = product; + product *= nums[i]; + } + + product = 1; + for (let i = nums.length - 1; i >= 0; i--) { + result[i] *= product; + product *= nums[i]; + } + return result; +} + +console.log(productExceptSelf([1, 2, 3, 4])); diff --git a/valid-anagram/jthw1005.js b/valid-anagram/jthw1005.js new file mode 100644 index 0000000000..3ba2b4a480 --- /dev/null +++ b/valid-anagram/jthw1005.js @@ -0,0 +1,14 @@ +const isAnagram = (s, t) => { + const data = new Array(26).fill(0); + const a_ascii = 'a'.charCodeAt(); + + for (const char of s) { + data[char.charCodeAt() - a_ascii]++; + } + + for (const char of t) { + data[char.charCodeAt() - a_ascii]--; + } + + return !data.some((el) => el !== 0); +}; diff --git a/validate-binary-search-tree/jthw1005.js b/validate-binary-search-tree/jthw1005.js new file mode 100644 index 0000000000..c80f6d398a --- /dev/null +++ b/validate-binary-search-tree/jthw1005.js @@ -0,0 +1,10 @@ +function isValidBST(root) { + function helper(node, min, max) { + if (!node) return true; + if (node.val <= min || node.val >= max) return false; + return ( + helper(node.left, min, node.val) && helper(node.right, node.val, max) + ); + } + return helper(root, -Infinity, Infinity); +}