diff --git a/3sum/taewanseoul.ts b/3sum/taewanseoul.ts new file mode 100644 index 000000000..6412cbb60 --- /dev/null +++ b/3sum/taewanseoul.ts @@ -0,0 +1,45 @@ +/** + * 15. 3Sum + * Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. + * Notice that the solution set must not contain duplicate triplets. + * + * https://leetcode.com/problems/3sum/description/ + */ +function threeSum(nums: number[]): number[][] { + nums.sort((a, b) => a - b); + const triplets: number[][] = []; + + for (let i = 0; i < nums.length - 2; i++) { + if (nums[i] > 0 || nums[i] === nums[i - 1]) { + continue; + } + + let low = i + 1; + let high = nums.length - 1; + + while (low < high) { + const sum = nums[i] + nums[low] + nums[high]; + if (sum < 0) { + low++; + } else if (sum > 0) { + high--; + } else { + triplets.push([nums[i], nums[low], nums[high]]); + + while (low < high && nums[low] === nums[low + 1]) { + low++; + } + while (low < high && nums[high] === nums[high - 1]) { + high--; + } + low++; + high--; + } + } + } + + return triplets; +} + +// O(n^2) time +// O(n) space diff --git a/climbing-stairs/taewanseoul.ts b/climbing-stairs/taewanseoul.ts new file mode 100644 index 000000000..f6a4f0d58 --- /dev/null +++ b/climbing-stairs/taewanseoul.ts @@ -0,0 +1,26 @@ +/** + * 70. Climbing Stairs + * You are climbing a staircase. It takes n steps to reach the top. + * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? + * + * https://leetcode.com/problems/climbing-stairs/description/ + */ +function climbStairs(n: number): number { + if (n <= 2) { + return n; + } + + let prev = 1; + let cur = 2; + + for (let i = 3; i < n + 1; i++) { + const next = prev + cur; + prev = cur; + cur = next; + } + + return cur; +} + +// O(n) time +// O(1) space diff --git a/valid-anagram/taewanseoul.ts b/valid-anagram/taewanseoul.ts new file mode 100644 index 000000000..33d3706c9 --- /dev/null +++ b/valid-anagram/taewanseoul.ts @@ -0,0 +1,36 @@ +/** + * 242. Valid Anagram + * Given two strings s and t, return true if t is an anagram of s, and false otherwise. + * + * https://leetcode.com/problems/valid-anagram/description/ + */ +function isAnagram(s: string, t: string): boolean { + if (s.length !== t.length) { + return false; + } + + const charMap = new Map(); + + for (const char of s) { + const count = charMap.get(char); + if (count) { + charMap.set(char, count + 1); + } else { + charMap.set(char, 1); + } + } + + for (const char of t) { + const count = charMap.get(char); + if (count) { + charMap.set(char, count - 1); + } else { + return false; + } + } + + return true; +} + +// O(n) time +// O(n) space