diff --git a/Best Time to Buy and Sell Stock/solution.js b/Best Time to Buy and Sell Stock/solution.js new file mode 100644 index 0000000..f9c989b --- /dev/null +++ b/Best Time to Buy and Sell Stock/solution.js @@ -0,0 +1,16 @@ +var maxProfit = function (prices) { + let buyPrice = prices[0]; + let profit = 0; + + for (let i = 0; i < prices.length; i++) { + if (buyPrice > prices[i]) { + buyPrice = prices[i]; + } + profit = Math.max(profit, prices[i] - buyPrice); + } + + return profit; +}; + +console.log(maxProfit([7, 1, 5, 3, 6, 4])); + diff --git a/Can attend meetings/solution.js b/Can attend meetings/solution.js new file mode 100644 index 0000000..4eefb3f --- /dev/null +++ b/Can attend meetings/solution.js @@ -0,0 +1,11 @@ +function canAttendMeetings(intervals) { + intervals.sort((a, b) => a.start - b.start); + + for (let i = 1; i < intervals.length; i++) { + if (intervals[i][0] < intervals[i - 1][1]) { + return false; + } + } + + return true; +} \ No newline at end of file diff --git a/Climbing stairs/solution.js b/Climbing stairs/solution.js new file mode 100644 index 0000000..6f28ab4 --- /dev/null +++ b/Climbing stairs/solution.js @@ -0,0 +1,14 @@ +var climbStairs = function (n) { + if (n <= 2) return n; + + let dp = new Array(n + 1).fill(0); + + dp[1] = 1; + dp[2] = 2; + + for (let i = 3; i <= n; i++) { + dp[i] = dp[i - 1] + dp[i - 2]; + } + + return dp[n]; +}; \ No newline at end of file diff --git a/Clone Graph/solution.js b/Clone Graph/solution.js new file mode 100644 index 0000000..f40f5f1 --- /dev/null +++ b/Clone Graph/solution.js @@ -0,0 +1,19 @@ +var cloneGraph = function(node) { + if (!node) return null; + const visited = new Map(); + + const dfs = (node) => { + if (visited.has(node)) return visited.get(node); + + const clone = new Node(node.val); + visited.set(node, clone); + + for (let neighbor of node.neighbors) { + clone.neighbors.push(dfs(neighbor)); + } + + return clone; + }; + + return dfs(node); +}; \ No newline at end of file diff --git a/Coin change/solution.js b/Coin change/solution.js new file mode 100644 index 0000000..9b70599 --- /dev/null +++ b/Coin change/solution.js @@ -0,0 +1,14 @@ +var coinChange = function(coins, amount) { + let minCoins = new Array(amount + 1).fill(amount + 1); + minCoins[0] = 0; + + for (let i = 1; i <= amount; i++) { + for (let j = 0; j < coins.length; j++) { + if (i - coins[j] >= 0) { + minCoins[i] = Math.min(minCoins[i], 1 + minCoins[i - coins[j]]); + } + } + } + + return minCoins[amount] !== amount + 1 ? minCoins[amount] : -1; +}; \ No newline at end of file diff --git a/Combination sum/solution.js b/Combination sum/solution.js new file mode 100644 index 0000000..36917b5 --- /dev/null +++ b/Combination sum/solution.js @@ -0,0 +1,14 @@ +var combinationSum4 = function(nums, target) { + const dp = Array(target + 1).fill(0); + dp[0] = 1; + + for (let i = 1; i <= target; i++) { + for (const num of nums) { + if (i - num >= 0) { + dp[i] += dp[i - num]; + } + } + } + + return dp[target]; +}; \ No newline at end of file diff --git a/Container with most water/solution.js b/Container with most water/solution.js new file mode 100644 index 0000000..fece90d --- /dev/null +++ b/Container with most water/solution.js @@ -0,0 +1,17 @@ +var maxArea = function(height) { + let maxArea = 0; + let left = 0; + let right = height.length - 1; + + while (left < right) { + maxArea = Math.max(maxArea, (right - left) * Math.min(height[left], height[right])); + + if (height[left] < height[right]) { + left++; + } else { + right--; + } + } + + return maxArea; +}; \ No newline at end of file diff --git a/Contains Duplicate/solution.js b/Contains Duplicate/solution.js new file mode 100644 index 0000000..60f9754 --- /dev/null +++ b/Contains Duplicate/solution.js @@ -0,0 +1,13 @@ +function containsDuplicate(nums) { + const hashMap = {}; + for (let i = 0; i < nums.length; i++) { + if (hashMap[nums[i]]) { + return true; + } + hashMap[nums[i]] = nums[i]; + } + + return false; +} + +console.log(containsDuplicate([1, 2, 3, 1])); diff --git a/Count unreachable pairs/solution.js b/Count unreachable pairs/solution.js new file mode 100644 index 0000000..7f58aa2 --- /dev/null +++ b/Count unreachable pairs/solution.js @@ -0,0 +1,91 @@ +var countPairs = function(n, edges) { + const graph = Array.from({ length: n }, () => []); + + // Build adjacency list + for (const [a, b] of edges) { + graph[a].push(b); + graph[b].push(a); + } + + const visited = new Array(n).fill(false); + + // DFS to count size of each connected component + const dfs = (node) => { + visited[node] = true; + let size = 1; + for (const neighbor of graph[node]) { + if (!visited[neighbor]) { + size += dfs(neighbor); + } + } + return size; + }; + + let totalPairs = 0; + let totalNodes = n; + + for (let i = 0; i < n; i++) { + if (!visited[i]) { + const componentSize = dfs(i); + totalPairs += componentSize * (totalNodes - componentSize); + totalNodes -= componentSize; + } + } + + return totalPairs; +}; + + +// using unin find + +var countPairs = function(n, edges) { + // Step 1: Create Union Find + const parent = Array.from({ length: n }, (_, i) => i); + const size = Array(n).fill(1); // Size of each component + + const find = (x) => { + if (parent[x] !== x) { + parent[x] = find(parent[x]); // Path compression + } + return parent[x]; + }; + + const union = (x, y) => { + const rootX = find(x); + const rootY = find(y); + + if (rootX === rootY) return; // Already connected + + // Union by size + if (size[rootX] < size[rootY]) { + parent[rootX] = rootY; + size[rootY] += size[rootX]; + } else { + parent[rootY] = rootX; + size[rootX] += size[rootY]; + } + }; + + // Step 2: Connect nodes + for (const [a, b] of edges) { + union(a, b); + } + + // Step 3: Count sizes of each connected component + const count = new Map(); + for (let i = 0; i < n; i++) { + const root = find(i); + count.set(root, (count.get(root) || 0) + 1); + } + + // Step 4: Calculate unreachable pairs + let totalNodes = n; + let result = 0; + + for (const sz of count.values()) { + result += sz * (totalNodes - sz); + totalNodes -= sz; + } + + return result; +}; diff --git a/Counting bits/solution.js b/Counting bits/solution.js new file mode 100644 index 0000000..3aece5d --- /dev/null +++ b/Counting bits/solution.js @@ -0,0 +1,7 @@ +var countBits = function(n) { + let res = new Array(n + 1).fill(0); + for (let i = 1; i <= n; i++) { + res[i] = res[i >> 1] + (i & 1); + } + return res; +}; diff --git a/Course schedule.js/solution.js b/Course schedule.js/solution.js new file mode 100644 index 0000000..4de1bcd --- /dev/null +++ b/Course schedule.js/solution.js @@ -0,0 +1,32 @@ +function canFinish(numCourses, prerequisites) { + const graph = new Map(); + const inDegree = new Array(numCourses).fill(0); + + // Build graph and in-degree array + for (const [course, prereq] of prerequisites) { + if (!graph.has(prereq)) graph.set(prereq, []); + graph.get(prereq).push(course); + inDegree[course]++; + } + + // Queue for courses with no prerequisites + const queue = []; + for (let i = 0; i < numCourses; i++) { + if (inDegree[i] === 0) queue.push(i); + } + + let finishedCourses = 0; + + while (queue.length > 0) { + const current = queue.shift(); + finishedCourses++; + + const neighbors = graph.get(current) || []; + for (const neighbor of neighbors) { + inDegree[neighbor]--; + if (inDegree[neighbor] === 0) queue.push(neighbor); + } + } + + return finishedCourses === numCourses; +} diff --git a/Decode ways/solution.js b/Decode ways/solution.js new file mode 100644 index 0000000..3ac40a7 --- /dev/null +++ b/Decode ways/solution.js @@ -0,0 +1,23 @@ +var numDecodings = function(s) { + if (s[0] === '0') { + return 0; + } + + const n = s.length; + const dp = new Array(n + 1).fill(0); + dp[0] = dp[1] = 1; + + for (let i = 2; i <= n; i++) { + const one = parseInt(s[i - 1]); + const two = parseInt(s.substring(i - 2, i)); + + if (1 <= one && one <= 9) { + dp[i] += dp[i - 1]; + } + if (10 <= two && two <= 26) { + dp[i] += dp[i - 2]; + } + } + + return dp[n]; +}; \ No newline at end of file diff --git a/EraseOverLapIntervals/solution.js b/EraseOverLapIntervals/solution.js new file mode 100644 index 0000000..9696751 --- /dev/null +++ b/EraseOverLapIntervals/solution.js @@ -0,0 +1,16 @@ + +var eraseOverlapIntervals = function(intervals) { + let res = 0; + intervals.sort((a, b) => a[1] - b[1]); + let prev_end = intervals[0][1]; + + for (let i = 1; i < intervals.length; i++) { + if (prev_end > intervals[i][0]) { + res++; + } else { + prev_end = intervals[i][1]; + } + } + + return res; +}; \ No newline at end of file diff --git a/Find Minimum in Rotated sorted array/solution.js b/Find Minimum in Rotated sorted array/solution.js new file mode 100644 index 0000000..f5d6840 --- /dev/null +++ b/Find Minimum in Rotated sorted array/solution.js @@ -0,0 +1,16 @@ +var findMin = function (nums) { + let left = 0; + let right = nums.length - 1; + + while (left < right) { + const mid = Math.floor((left + right) / 2); + + if (nums[mid] <= nums[right]) { + right = mid; + } else { + left = mid + 1; + } + } + + return nums[left]; +}; diff --git a/Find building alice and bob/solution.js b/Find building alice and bob/solution.js new file mode 100644 index 0000000..4eacec4 --- /dev/null +++ b/Find building alice and bob/solution.js @@ -0,0 +1,58 @@ +var leftmostBuildingQueries = function(heights, queries) { + const n = heights.length; + const st = Array.from({ length: n }, () => Array(20).fill(0)); + const Log = Array(n + 1).fill(0); + Log[0] = -1; + + for (let i = 1; i <= n; i++) { + Log[i] = Log[i >> 1] + 1; + } + + for (let i = 0; i < n; i++) { + st[i][0] = heights[i]; + } + + for (let i = 1; i < 20; i++) { + for (let j = 0; j + (1 << i) <= n; j++) { + st[j][i] = Math.max(st[j][i - 1], st[j + (1 << (i - 1))][i - 1]); + } + } + + const res = []; + + for (let i = 0; i < queries.length; i++) { + let [l, r] = queries[i]; + if (l > r) { + [l, r] = [r, l]; + } + + if (l === r) { + res.push(l); + continue; + } + + if (heights[r] > heights[l]) { + res.push(r); + continue; + } + + const maxHeight = Math.max(heights[l], heights[r]); + let left = r + 1, right = n, mid; + + while (left < right) { + mid = Math.floor((left + right) / 2); + const k = Log[mid - r + 1]; + const maxInRange = Math.max(st[r][k], st[mid - (1 << k) + 1][k]); + + if (maxInRange > maxHeight) { + right = mid; + } else { + left = mid + 1; + } + } + + res.push(left === n ? -1 : left); + } + + return res; +}; \ No newline at end of file diff --git a/House robber 2/solution.js b/House robber 2/solution.js new file mode 100644 index 0000000..6d0d806 --- /dev/null +++ b/House robber 2/solution.js @@ -0,0 +1,16 @@ +var rob = function(nums) { + const getMax = (nums) => { + let prevRob = 0, maxRob = 0; + + for (let curVal of nums) { + let temp = Math.max(maxRob, prevRob + curVal); + prevRob = maxRob; + maxRob = temp; + } + + return maxRob; + }; + + if (nums.length === 1) return nums[0]; + return Math.max(getMax(nums.slice(0, -1)), getMax(nums.slice(1)), nums[0]); +}; \ No newline at end of file diff --git a/House robber/solution.js b/House robber/solution.js new file mode 100644 index 0000000..7f4c66c --- /dev/null +++ b/House robber/solution.js @@ -0,0 +1,18 @@ +var rob = function(nums) { + const n = nums.length; + + if (n === 1) { + return nums[0]; + } + + const dp = Array(n).fill(0); + + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + + for (let i = 2; i < n; i++) { + dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]); + } + + return dp[n - 1]; +}; \ No newline at end of file diff --git a/Insert interval/solution.js b/Insert interval/solution.js new file mode 100644 index 0000000..ec7505e --- /dev/null +++ b/Insert interval/solution.js @@ -0,0 +1,16 @@ +var insert = function(intervals, newInterval) { + intervals.push(newInterval); + intervals.sort((a, b) => a[0] - b[0]); + + let res = [intervals[0]]; + + for (let i = 1; i < intervals.length; i++) { + if (res[res.length - 1][1] >= intervals[i][0]) { + res[res.length - 1][1] = Math.max(res[res.length - 1][1], intervals[i][1]); + } else { + res.push(intervals[i]); + } + } + + return res; +}; \ No newline at end of file diff --git a/Jump game/solution.js b/Jump game/solution.js new file mode 100644 index 0000000..043a962 --- /dev/null +++ b/Jump game/solution.js @@ -0,0 +1,11 @@ +var canJump = function(nums) { + let goal = nums.length - 1; + + for (let i = nums.length - 2; i >= 0; i--) { + if (i + nums[i] >= goal) { + goal = i; + } + } + + return goal === 0; +}; \ No newline at end of file diff --git a/LinkedListCycle/solution.js b/LinkedListCycle/solution.js new file mode 100644 index 0000000..80af4bd --- /dev/null +++ b/LinkedListCycle/solution.js @@ -0,0 +1,15 @@ +var hasCycle = function(head) { + let fast = head; + let slow = head; + + while (fast && fast.next) { + fast = fast.next.next; + slow = slow.next; + + if (fast === slow) { + return true; + } + } + + return false; +}; \ No newline at end of file diff --git a/Longest Repeating Character Replacement/solution.js b/Longest Repeating Character Replacement/solution.js new file mode 100644 index 0000000..ca54020 --- /dev/null +++ b/Longest Repeating Character Replacement/solution.js @@ -0,0 +1,21 @@ + +var characterReplacement = function (s, k) { + let left = 0; + let maxFreq = 0; + let maxLength = 0; + let freqMap = {}; // hashtable + + for (let right = 0; right < s.length; right++) { + freqMap[s[right]] = (freqMap[s[right]] || 0) + 1; + + maxFreq = Math.max(maxFreq, freqMap[s[right]]); + + if ((right - left) + 1 - maxFreq > k) { // more than k changes scenario + freqMap[s[left]]--; + left++; + } + + maxLength = Math.max(maxLength, (right - left) + 1); + } + return maxLength; +} \ No newline at end of file diff --git a/Longest consecutive sequence/solution.js b/Longest consecutive sequence/solution.js new file mode 100644 index 0000000..f3913ce --- /dev/null +++ b/Longest consecutive sequence/solution.js @@ -0,0 +1,18 @@ +var longestConsecutive = function(nums) { + const numSet = new Set(nums); + let longest = 0; + + for (let n of numSet) { + if (!numSet.has(n - 1)) { + let length = 1; + + while (numSet.has(n + length)) { + length++; + } + + longest = Math.max(longest, length); + } + } + + return longest; +}; \ No newline at end of file diff --git a/Longest increasing subsequence/solution.js b/Longest increasing subsequence/solution.js new file mode 100644 index 0000000..271811c --- /dev/null +++ b/Longest increasing subsequence/solution.js @@ -0,0 +1,32 @@ +var lengthOfLIS = function(nums) { + const res = []; + + const binarySearch = (arr, target) => { + let left = 0; + let right = arr.length - 1; + + while (left <= right) { + const mid = Math.floor((left + right) / 2); + if (arr[mid] === target) { + return mid; + } else if (arr[mid] > target) { + right = mid - 1; + } else { + left = mid + 1; + } + } + + return left; + }; + + for (const n of nums) { + if (!res.length || res[res.length - 1] < n) { + res.push(n); + } else { + const idx = binarySearch(res, n); + res[idx] = n; + } + } + + return res.length; +}; \ No newline at end of file diff --git a/LongestsubstringWithoutrepeatingCharacters/solution.js b/LongestsubstringWithoutrepeatingCharacters/solution.js new file mode 100644 index 0000000..12a6fb4 --- /dev/null +++ b/LongestsubstringWithoutrepeatingCharacters/solution.js @@ -0,0 +1,17 @@ +var lengthOfLongestSubstring = function(s) { + let left = 0; + let maxLength = 0; + let charSet = new Set(); + + for (let right = 0; right < s.length; right++) { + while (charSet.has(s[right])) { + charSet.delete(s[left]); + left++; + } + + charSet.add(s[right]); + maxLength = Math.max(maxLength, right - left + 1); + } + + return maxLength; +}; \ No newline at end of file diff --git a/Lonngest Common Subsequence/solution.js b/Lonngest Common Subsequence/solution.js new file mode 100644 index 0000000..019521f --- /dev/null +++ b/Lonngest Common Subsequence/solution.js @@ -0,0 +1,18 @@ +var longestCommonSubsequence = function(text1, text2) { + const dp = Array(text1.length).fill(0); + let longest = 0; + + for (const c of text2) { + let curLength = 0; + for (let i = 0; i < dp.length; i++) { + if (curLength < dp[i]) { + curLength = dp[i]; + } else if (c === text1[i]) { + dp[i] = curLength + 1; + longest = Math.max(longest, curLength + 1); + } + } + } + + return longest; +}; \ No newline at end of file diff --git a/Maximum Product Subarray/solution.js b/Maximum Product Subarray/solution.js new file mode 100644 index 0000000..1b8723f --- /dev/null +++ b/Maximum Product Subarray/solution.js @@ -0,0 +1,14 @@ +var maxProduct = function(nums) { + let res = Math.max(...nums); + let curMax = 1, curMin = 1; + + for (let n of nums) { + let temp = curMax * n; + curMax = Math.max(temp, curMin * n, n); + curMin = Math.min(temp, curMin * n, n); + + res = Math.max(res, curMax); + } + + return res; +}; diff --git a/Maximum Subarray/solution.js b/Maximum Subarray/solution.js new file mode 100644 index 0000000..bebfd62 --- /dev/null +++ b/Maximum Subarray/solution.js @@ -0,0 +1,15 @@ +var maxSubArray = function (nums) { + let maxSum = nums[0]; + let currSum = 0; + + for (let num of nums) { + currSum = Math.max(currSum, 0); + currSum += num; + maxSum = Math.max(currSum, maxSum); + } + return maxSum; +}; + +console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); + +// used kadanes algorithm, Time=O(n) space=O(1) diff --git a/Maximum star sum of a graph/solution.js b/Maximum star sum of a graph/solution.js new file mode 100644 index 0000000..4c4c204 --- /dev/null +++ b/Maximum star sum of a graph/solution.js @@ -0,0 +1,28 @@ +var maxStarSum = function (vals, edges, k) { + let maxSum = -Infinity; + + let adjList = new Map(); + + for (let [a, b] of edges) { + if (!adjList.has(a)) adjList.set(a, []); + if (!adjList.has(b)) adjList.set(b, []); + + adjList.get(a).push(vals[b]); + adjList.get(b).push(vals[a]); + } + + for (let i = 0; i < vals.length; i++) { + let neighbours = adjList.get(i) || []; + + neighbours.sort((a, b) => b - a); + let sum = vals[i]; + + for (let j = 0; j < Math.min(k, neighbours.length); j++) { + if (neighbours[j] > 0) sum += neighbours[j]; + } + + maxSum = Math.max(sum, maxSum); + } + + return maxSum; +}; \ No newline at end of file diff --git a/MeetingRooms 2/solution.js b/MeetingRooms 2/solution.js new file mode 100644 index 0000000..0cb841b --- /dev/null +++ b/MeetingRooms 2/solution.js @@ -0,0 +1,17 @@ +class Solution { + /** + * @param {Interval[]} intervals + * @returns {number} + */ + minMeetingRooms(intervals) { + intervals.sort((a, b) => a.start - b.start); + const minHeap = new MinPriorityQueue(); + for (const interval of intervals) { + if (!minHeap.isEmpty() && minHeap.front() <= interval.start) { + minHeap.pop(); + } + minHeap.push(interval.end); + } + return minHeap.size(); + } +} diff --git a/MergeInterval/solution.js b/MergeInterval/solution.js new file mode 100644 index 0000000..214f542 --- /dev/null +++ b/MergeInterval/solution.js @@ -0,0 +1,19 @@ +var merge = function(intervals) { + + intervals.sort((a, b) => a[0] - b[0]); + const merged = []; + let prev = intervals[0]; + + for (let i = 1; i < intervals.length; i++) { + let interval = intervals[i]; + if (interval[0] <= prev[1]) { + prev[1] = Math.max(prev[1], interval[1]); + } else { + merged.push(prev); + prev = interval; + } + } + + merged.push(prev); + return merged; +}; \ No newline at end of file diff --git a/MergeKSortedLists/solution.js b/MergeKSortedLists/solution.js new file mode 100644 index 0000000..6fe5a4d --- /dev/null +++ b/MergeKSortedLists/solution.js @@ -0,0 +1,36 @@ +var mergeKLists = function(lists) { + if (!lists || lists.length === 0) { + return null; + } + + while (lists.length > 1) { + let temp = []; + for (let i = 0; i < lists.length; i += 2) { + let l1 = lists[i]; + let l2 = i + 1 < lists.length ? lists[i + 1] : null; + temp.push(mergeLists(l1, l2)); + } + lists = temp; + } + + return lists[0]; +}; + +function mergeLists(l1, l2) { + let node = new ListNode(); + let ans = node; + + while (l1 && l2) { + if (l1.val > l2.val) { + node.next = l2; + l2 = l2.next; + } else { + node.next = l1; + l1 = l1.next; + } + node = node.next; + } + + node.next = l1 ? l1 : l2; + return ans.next; +} \ No newline at end of file diff --git a/MergeTwoLinkedList/solution.js b/MergeTwoLinkedList/solution.js new file mode 100644 index 0000000..3619374 --- /dev/null +++ b/MergeTwoLinkedList/solution.js @@ -0,0 +1,19 @@ +var mergeTwoLists = function(list1, list2) { + let dummy = new ListNode(); + let cur = dummy; + + while (list1 && list2) { + if (list1.val > list2.val) { + cur.next = list2; + list2 = list2.next; + } else { + cur.next = list1; + list1 = list1.next; + } + cur = cur.next; + } + + cur.next = list1 || list2; + + return dummy.next; +}; \ No newline at end of file diff --git a/Minimum window substring/solution.js b/Minimum window substring/solution.js new file mode 100644 index 0000000..61e91fa --- /dev/null +++ b/Minimum window substring/solution.js @@ -0,0 +1,43 @@ +var minWindow = function(s, t) { + if (s.length < t.length) { + return ""; + } + + const charCount = new Map(); + for (const ch of t) { + charCount.set(ch, (charCount.get(ch) || 0) + 1); + } + + let targetCharsRemaining = t.length; + let minWindow = [0, Number.POSITIVE_INFINITY]; + let startIndex = 0; + + for (let endIndex = 0; endIndex < s.length; endIndex++) { + const ch = s[endIndex]; + if (charCount.has(ch) && charCount.get(ch) > 0) { + targetCharsRemaining--; + } + charCount.set(ch, (charCount.get(ch) || 0) - 1); + + if (targetCharsRemaining === 0) { + while (true) { + const charAtStart = s[startIndex]; + if (charCount.has(charAtStart) && charCount.get(charAtStart) === 0) { + break; + } + charCount.set(charAtStart, (charCount.get(charAtStart) || 0) + 1); + startIndex++; + } + + if (endIndex - startIndex < minWindow[1] - minWindow[0]) { + minWindow = [startIndex, endIndex]; + } + + charCount.set(s[startIndex], (charCount.get(s[startIndex]) || 0) + 1); + targetCharsRemaining++; + startIndex++; + } + } + + return minWindow[1] >= s.length ? "" : s.slice(minWindow[0], minWindow[1] + 1); +}; \ No newline at end of file diff --git a/Missing Number/solution.js b/Missing Number/solution.js new file mode 100644 index 0000000..548c8ce --- /dev/null +++ b/Missing Number/solution.js @@ -0,0 +1,9 @@ +var missingNumber = function(nums) { + let res = nums.length; + + for (let i = 0; i < nums.length; i++) { + res += i - nums[i]; + } + + return res; +}; \ No newline at end of file diff --git a/Number of 1 bits/solution.js b/Number of 1 bits/solution.js new file mode 100644 index 0000000..2aa4b74 --- /dev/null +++ b/Number of 1 bits/solution.js @@ -0,0 +1,9 @@ +var hammingWeight = function(n) { + let res = 0; + for (let i = 0; i < 32; i++) { + if ((n >> i) & 1) { + res += 1; + } + } + return res; +}; \ No newline at end of file diff --git a/Number of islands/solution.js b/Number of islands/solution.js new file mode 100644 index 0000000..e8f4919 --- /dev/null +++ b/Number of islands/solution.js @@ -0,0 +1,37 @@ +var numIslands = function(grid) { + let islands = 0; + const visited = new Set(); + const rows = grid.length; + const cols = grid[0].length; + + const bfs = (r, c) => { + const q = []; + visited.add(`${r},${c}`); + q.push([r, c]); + + while (q.length > 0) { + const [row, col] = q.shift(); + const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + + for (const [dr, dc] of directions) { + const nr = row + dr; + const nc = col + dc; + if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === "1" && !visited.has(`${nr},${nc}`)) { + q.push([nr, nc]); + visited.add(`${nr},${nc}`); + } + } + } + }; + + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (grid[r][c] === "1" && !visited.has(`${r},${c}`)) { + islands += 1; + bfs(r, c); + } + } + } + + return islands; +}; \ No newline at end of file diff --git a/Pacific atlantic water flow/solution.js b/Pacific atlantic water flow/solution.js new file mode 100644 index 0000000..d8d6c0c --- /dev/null +++ b/Pacific atlantic water flow/solution.js @@ -0,0 +1,46 @@ +function pacificAtlantic(heights) { + const rows = heights.length; + const cols = heights[0].length; + + const pacific = Array.from({ length: rows }, () => new Array(cols).fill(false)); + const atlantic = Array.from({ length: rows }, () => new Array(cols).fill(false)); + + const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + + function dfs(r, c, visited, prevHeight) { + // boundary + already visited + can't flow uphill + if ( + r < 0 || c < 0 || r >= rows || c >= cols || + visited[r][c] || heights[r][c] < prevHeight + ) return; + + visited[r][c] = true; + + for (const [dr, dc] of directions) { + dfs(r + dr, c + dc, visited, heights[r][c]); + } + } + + // Start DFS from Pacific Ocean (top row and left column) + for (let c = 0; c < cols; c++) { + dfs(0, c, pacific, heights[0][c]); // top edge + dfs(rows - 1, c, atlantic, heights[rows - 1][c]); // bottom edge + } + + for (let r = 0; r < rows; r++) { + dfs(r, 0, pacific, heights[r][0]); // left edge + dfs(r, cols - 1, atlantic, heights[r][cols - 1]); // right edge + } + + const result = []; + + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (pacific[r][c] && atlantic[r][c]) { + result.push([r, c]); + } + } + } + + return result; +} \ No newline at end of file diff --git a/Product of Array Except Self/solution.js b/Product of Array Except Self/solution.js new file mode 100644 index 0000000..cf75be3 --- /dev/null +++ b/Product of Array Except Self/solution.js @@ -0,0 +1,18 @@ + +var productExceptSelf = function(nums) { + const output = Array(nums.length).fill(1); + + let left = 1; + for (let i = 0; i < nums.length; i++) { + output[i] *= left; + left *= nums[i]; + } + + let right = 1; + for (let i = nums.length - 1; i >= 0; i--) { + output[i] *= right; + right *= nums[i]; + } + + return output; +}; diff --git a/RemoveNthNodeFromTheEndOfList/solution.js b/RemoveNthNodeFromTheEndOfList/solution.js new file mode 100644 index 0000000..4eb6535 --- /dev/null +++ b/RemoveNthNodeFromTheEndOfList/solution.js @@ -0,0 +1,17 @@ +var removeNthFromEnd = function(head, n) { + let res = new ListNode(0, head); + let dummy = res; + + for (let i = 0; i < n; i++) { + head = head.next; + } + + while (head) { + head = head.next; + dummy = dummy.next; + } + + dummy.next = dummy.next.next; + + return res.next; +}; \ No newline at end of file diff --git a/ReorderList/solution.js b/ReorderList/solution.js new file mode 100644 index 0000000..9e0da64 --- /dev/null +++ b/ReorderList/solution.js @@ -0,0 +1,34 @@ +var reorderList = function(head) { + if (!head) return; + + // Step 1: Find the middle of the list + let slow = head, fast = head; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + + // Step 2: Reverse the second half of the list + let second = slow.next; + slow.next = null; + let node = null; + + while (second) { + const temp = second.next; + second.next = node; + node = second; + second = temp; + } + + // Step 3: Merge the two halves + let first = head; + second = node; + + while (second) { + const temp1 = first.next, temp2 = second.next; + first.next = second; + second.next = temp1; + first = temp1; + second = temp2; + } +}; \ No newline at end of file diff --git a/Reverse Bits/solution.js b/Reverse Bits/solution.js new file mode 100644 index 0000000..a7c6637 --- /dev/null +++ b/Reverse Bits/solution.js @@ -0,0 +1,5 @@ +var reverseBits = function (n) { + const binaryString = n.toString(2).padStart(32, 0); + const reverseBinary = binaryString.split("").reverse().join(""); + return parseInt(reverseBinary, 2); +}; diff --git a/ReverseLinkedList/solution.js b/ReverseLinkedList/solution.js new file mode 100644 index 0000000..55cc643 --- /dev/null +++ b/ReverseLinkedList/solution.js @@ -0,0 +1,12 @@ +var reverseList = function(head) { + let prev = null + + while(head){ + let next = head.next + head.next = prev + prev = head + head = next + } + + return prev +}; \ No newline at end of file diff --git a/Rotate Image/solution.js b/Rotate Image/solution.js new file mode 100644 index 0000000..d95bb2c --- /dev/null +++ b/Rotate Image/solution.js @@ -0,0 +1,24 @@ +var rotate = function(matrix) { + const edgeLength = matrix.length; + + let top = 0; + let bottom = edgeLength - 1; + + while (top < bottom) { + for (let col = 0; col < edgeLength; col++) { + let temp = matrix[top][col]; + matrix[top][col] = matrix[bottom][col]; + matrix[bottom][col] = temp; + } + top++; + bottom--; + } + + for (let row = 0; row < edgeLength; row++) { + for (let col = row + 1; col < edgeLength; col++) { + let temp = matrix[row][col]; + matrix[row][col] = matrix[col][row]; + matrix[col][row] = temp; + } + } +}; \ No newline at end of file diff --git a/Search in Rotated Sorted Array/solution.js b/Search in Rotated Sorted Array/solution.js new file mode 100644 index 0000000..51de41f --- /dev/null +++ b/Search in Rotated Sorted Array/solution.js @@ -0,0 +1,30 @@ +var search = function (nums, target) { + let left = 0; + let right = nums.length - 1; + + while (left <= right) { + let mid = Math.floor((left + right) / 2); + + if (nums[mid] === target) { + return mid; + } + + // Determine if left half is sorted + if (nums[left] <= nums[mid]) { + if (nums[left] <= target && target < nums[mid]) { + right = mid - 1; + } else { + left = mid + 1; + } + } + // Right half must be sorted + else { + if (nums[mid] < target && target <= nums[right]) { + left = mid + 1; + } else { + right = mid - 1; + } + } + } + return -1; +}; diff --git a/SetMatrixZeros/solution.js b/SetMatrixZeros/solution.js new file mode 100644 index 0000000..ca355ec --- /dev/null +++ b/SetMatrixZeros/solution.js @@ -0,0 +1,67 @@ +var setZeroes = function(matrix) { + const rows = matrix.length; + const cols = matrix[0].length; + + let first_row_has_zero = false; + let first_col_has_zero = false; + + // Check if the first row contains zero + for (let c = 0; c < cols; c++) { + if (matrix[0][c] === 0) { + first_row_has_zero = true; + break; + } + } + + // Check if the first column contains zero + for (let r = 0; r < rows; r++) { + if (matrix[r][0] === 0) { + first_col_has_zero = true; + break; + } + } + + // Use the first row and column as markers + for (let r = 1; r < rows; r++) { + for (let c = 1; c < cols; c++) { + if (matrix[r][c] === 0) { + matrix[r][0] = 0; + matrix[0][c] = 0; + } + } + } + + // Set the marked rows to zero + for (let r = 1; r < rows; r++) { + if (matrix[r][0] === 0) { + for (let c = 1; c < cols; c++) { + matrix[r][c] = 0; + } + } + } + + // Set the marked columns to zero + for (let c = 1; c < cols; c++) { + if (matrix[0][c] === 0) { + for (let r = 1; r < rows; r++) { + matrix[r][c] = 0; + } + } + } + + // Set the first row to zero if needed + if (first_row_has_zero) { + for (let c = 0; c < cols; c++) { + matrix[0][c] = 0; + } + } + + // Set the first column to zero if needed + if (first_col_has_zero) { + for (let r = 0; r < rows; r++) { + matrix[r][0] = 0; + } + } + + return matrix; +}; \ No newline at end of file diff --git a/Spiral Order/solution.js b/Spiral Order/solution.js new file mode 100644 index 0000000..f0f9c13 --- /dev/null +++ b/Spiral Order/solution.js @@ -0,0 +1,23 @@ +var spiralOrder = function(matrix) { + const rows = matrix.length; + const cols = matrix[0].length; + let x = 0; + let y = 0; + let dx = 1; + let dy = 0; + const res = []; + + for (let i = 0; i < rows * cols; i++) { + res.push(matrix[y][x]); + matrix[y][x] = "."; + + if (!(0 <= x + dx && x + dx < cols && 0 <= y + dy && y + dy < rows) || matrix[y+dy][x+dx] === ".") { + [dx, dy] = [-dy, dx]; + } + + x += dx; + y += dy; + } + + return res; +}; \ No newline at end of file diff --git a/Sum of Two Integers/solution.js b/Sum of Two Integers/solution.js new file mode 100644 index 0000000..dcbf765 --- /dev/null +++ b/Sum of Two Integers/solution.js @@ -0,0 +1,8 @@ +var getSum = function(a, b) { + while (b !== 0) { + let carry = (a & b) << 1; + a = a ^ b; + b = carry; + } + return a; +}; \ No newline at end of file diff --git a/Unique paths/solution.js b/Unique paths/solution.js new file mode 100644 index 0000000..0bf90eb --- /dev/null +++ b/Unique paths/solution.js @@ -0,0 +1,13 @@ +var uniquePaths = function(m, n) { + let aboveRow = Array(n).fill(1); + + for (let row = 1; row < m; row++) { + let currentRow = Array(n).fill(1); + for (let col = 1; col < n; col++) { + currentRow[col] = currentRow[col - 1] + aboveRow[col]; + } + aboveRow = currentRow; + } + + return aboveRow[n - 1]; +}; \ No newline at end of file diff --git a/Word Search/solution.js b/Word Search/solution.js new file mode 100644 index 0000000..295ad2c --- /dev/null +++ b/Word Search/solution.js @@ -0,0 +1,34 @@ +var exist = function(board, word) { + const rows = board.length; + const cols = board[0].length; + const visited = new Set(); + + const dfs = (r, c, k) => { + if (k === word.length) return true; + if (r < 0 || r >= rows || c < 0 || c >= cols || visited.has(`${r},${c}`) || board[r][c] !== word[k]) { + return false; + } + + visited.add(`${r},${c}`); + const res = dfs(r + 1, c, k + 1) || dfs(r - 1, c, k + 1) || dfs(r, c + 1, k + 1) || dfs(r, c - 1, k + 1); + visited.delete(`${r},${c}`); + return res; + }; + + const count = {}; + for (const c of word) { + count[c] = (count[c] || 0) + 1; + } + + if (count[word[0]] > count[word[word.length - 1]]) { + word = word.split('').reverse().join(''); + } + + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (dfs(r, c, 0)) return true; + } + } + + return false; +}; \ No newline at end of file diff --git a/Word break/solution.js b/Word break/solution.js new file mode 100644 index 0000000..b2da15a --- /dev/null +++ b/Word break/solution.js @@ -0,0 +1,20 @@ +var wordBreak = function(s, wordDict) { + let dp = new Array(s.length + 1).fill(false); + dp[0] = true; + + for (let i = 1; i <= s.length; i++) { + for (let w of wordDict) { + let start = i - w.length; + if (start >= 0 && dp[start] && s.substring(start, i) === w) { + dp[i] = true; + break; + } + } + } + return dp[s.length]; +}; + +let s = "catsandog" +let wordDict = ["cats", "dog", "sand", "and", "cat"] + +wordBreak(s,wordDict) \ No newline at end of file diff --git a/three-sum/sloution.js b/three-sum/sloution.js new file mode 100644 index 0000000..f6878c3 --- /dev/null +++ b/three-sum/sloution.js @@ -0,0 +1,34 @@ +var threeSum = function (nums) { + let res = []; + nums.sort((a, b) => a - b); + + for (let i = 0; i < nums.length; i++) { + // check previous element to avoid duplicates + if (i > 0 && nums[i] === nums[i - 1]) { + continue; + } + + let j = i + 1; + let k = nums.length - 1; + + while (j < k) { + let total = nums[i] + nums[j] + nums[k]; + if (total < 0) { + j++; + } else if (total > 0) { + k--; + } else { + res.push([nums[i], nums[j], nums[k]]); + j++; + + while (nums[j] === nums[j - 1] && j < k) { + j++; + } + } + } + } + + return res; +}; + +console.log(threeSum([-1, 0, 1, 2, -1, -4])); diff --git a/two-sum/solution.js b/two-sum/solution.js new file mode 100644 index 0000000..d01621b --- /dev/null +++ b/two-sum/solution.js @@ -0,0 +1,14 @@ +function twoSum(nums, target) { + const map = new Map(); + + for (let i = 0; i < nums.length; i++) { + let diff = target - nums[i]; + if (map.has(diff)) { + return [map.get(diff), i]; + } + map.set(nums[i], i); + } + return null; +} + +console.log(twoSum([1, 4, 3, 6, 2], 7));