From 744d7886cd97ef02bf403f8dee0c24db734ac073 Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 18 Mar 2025 16:06:39 +0530 Subject: [PATCH 01/54] Added solution for Two Sum --- Challenge-1/two-sum.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Challenge-1/two-sum.js diff --git a/Challenge-1/two-sum.js b/Challenge-1/two-sum.js new file mode 100644 index 0000000..d01621b --- /dev/null +++ b/Challenge-1/two-sum.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)); From a9b75e4912bfe42370651ea10e16893a78195d41 Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 20 Mar 2025 14:19:26 +0530 Subject: [PATCH 02/54] "Added solution for Best Time to Buy and Sell Stock" --- Challenge-2/Best Time to Buy and Sell Stock.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Challenge-2/Best Time to Buy and Sell Stock.js diff --git a/Challenge-2/Best Time to Buy and Sell Stock.js b/Challenge-2/Best Time to Buy and Sell Stock.js new file mode 100644 index 0000000..f9c989b --- /dev/null +++ b/Challenge-2/Best Time to Buy and Sell Stock.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])); + From bad8b37891a8efd6d2537387f063f71f5e53cf92 Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 20 Mar 2025 14:30:54 +0530 Subject: [PATCH 03/54] * --- .../solution.js | 0 Challenge-1/two-sum.js => two-sum/solution.js | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Challenge-2/Best Time to Buy and Sell Stock.js => Best Time to Buy and Sell Stock/solution.js (100%) rename Challenge-1/two-sum.js => two-sum/solution.js (100%) diff --git a/Challenge-2/Best Time to Buy and Sell Stock.js b/Best Time to Buy and Sell Stock/solution.js similarity index 100% rename from Challenge-2/Best Time to Buy and Sell Stock.js rename to Best Time to Buy and Sell Stock/solution.js diff --git a/Challenge-1/two-sum.js b/two-sum/solution.js similarity index 100% rename from Challenge-1/two-sum.js rename to two-sum/solution.js From e30428aaa18d95f0b4d6913fb7ccc300bd021008 Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 20 Mar 2025 14:58:46 +0530 Subject: [PATCH 04/54] added solution for Contains Duplicate --- Contains Duplicate/solution.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Contains Duplicate/solution.js 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])); From 81ef74db8d9830097f702605a1bf183d9cb3b87f Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 22 Mar 2025 18:38:50 +0530 Subject: [PATCH 05/54] added solution for sum of two integers --- Sum of Two Integers/solution.js | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Sum of Two Integers/solution.js 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 From c6d8917c4a7297f3fac6224ac94dc21e47e72162 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 22 Mar 2025 20:33:44 +0530 Subject: [PATCH 06/54] added solution for Product of Array Except Self --- Product of Array Except Self/solution.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Product of Array Except Self/solution.js 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; +}; From 32a4d4b7f006944475b762fc848f25b374d538a8 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sun, 23 Mar 2025 21:30:30 +0530 Subject: [PATCH 07/54] added solution for maxsubArray Sum --- Maximum Subarray/solution.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Maximum Subarray/solution.js 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) From 70802b98a201584b5163a401a401f2d199b2ed2f Mon Sep 17 00:00:00 2001 From: *vivek Date: Mon, 24 Mar 2025 19:59:56 +0530 Subject: [PATCH 08/54] added solution for maximum product of subarray --- Maximum Product Subarray/solution.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Maximum Product Subarray/solution.js 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; +}; From d5908a8959089a63356c2f04aeea99d05f1efc1d Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 25 Mar 2025 14:12:21 +0530 Subject: [PATCH 09/54] added solution for Find Minimum in Rotated Sorted Array --- Find Minimum in Rotated sorted array/solution.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Find Minimum in Rotated sorted array/solution.js 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]; +}; From cc6493bd628bb165553b2fecf7bc38c4d4d1072f Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 27 Mar 2025 12:18:59 +0530 Subject: [PATCH 10/54] added solution for search in a sorted array --- Search in Rotated Sorted Array/solution.js | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Search in Rotated Sorted Array/solution.js diff --git a/Search in Rotated Sorted Array/solution.js b/Search in Rotated Sorted Array/solution.js new file mode 100644 index 0000000..6103035 --- /dev/null +++ b/Search in Rotated Sorted Array/solution.js @@ -0,0 +1,25 @@ +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 + } else if (nums[mid] >= nums[left]) { + if (nums[left] <= target && target <= nums[mid]) { + right = mid - 1 + } else { + left = mid + 1 + } + } else { + if (nums[right] <= target && target <= nums[mid]) { + left = mid + 1 + } else { + right = mid - 1 + } + } + } + return -1 +}; \ No newline at end of file From d5715a4e2824d2d90f4058ff901ad63d3d94ab96 Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 27 Mar 2025 12:23:31 +0530 Subject: [PATCH 11/54] added solution for search in rotated sorted array --- Search in Rotated Sorted Array/solution.js | 41 ++++++++++++---------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/Search in Rotated Sorted Array/solution.js b/Search in Rotated Sorted Array/solution.js index 6103035..51de41f 100644 --- a/Search in Rotated Sorted Array/solution.js +++ b/Search in Rotated Sorted Array/solution.js @@ -1,25 +1,30 @@ var search = function (nums, target) { - let left = 0 - let right = nums.length - 1 + let left = 0; + let right = nums.length - 1; while (left <= right) { - let mid = Math.floor((left + right) / 2) + let mid = Math.floor((left + right) / 2); - if (nums[mid] === target) { - return mid - } else if (nums[mid] >= nums[left]) { - if (nums[left] <= target && target <= nums[mid]) { - right = mid - 1 - } else { - left = mid + 1 - } + 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 { - if (nums[right] <= target && target <= nums[mid]) { - left = mid + 1 - } else { - right = mid - 1 - } + right = mid - 1; } + } } - return -1 -}; \ No newline at end of file + return -1; +}; From 7504db59e933c8700509260c6471b9aeac7af363 Mon Sep 17 00:00:00 2001 From: *vivek Date: Fri, 28 Mar 2025 12:19:40 +0530 Subject: [PATCH 12/54] added solution for three sum --- three-sum/sloution.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 three-sum/sloution.js 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])); From 44878e94e1b8a8014606c29991edd31be4c9a9a2 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 29 Mar 2025 10:23:14 +0530 Subject: [PATCH 13/54] added solution for container with most water --- Container with most water/solution.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Container with most water/solution.js 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 From 898e1fcded74be63cd4840b4677da0908b1f1484 Mon Sep 17 00:00:00 2001 From: *vivek Date: Wed, 2 Apr 2025 12:49:54 +0530 Subject: [PATCH 14/54] added solution for number of 1 bits --- Number of 1 bits/solution.js | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Number of 1 bits/solution.js 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 From d344147028125d506ff9989382a838de71b65276 Mon Sep 17 00:00:00 2001 From: *vivek Date: Wed, 2 Apr 2025 13:15:56 +0530 Subject: [PATCH 15/54] added solution for counting bits --- Counting bits/solution.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Counting bits/solution.js 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; +}; From e81b774f474117f3e366c0b7399f0401e37fdf24 Mon Sep 17 00:00:00 2001 From: *vivek Date: Wed, 2 Apr 2025 13:28:07 +0530 Subject: [PATCH 16/54] added solution for missing num --- Missing Number/solution.js | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Missing Number/solution.js 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 From d6db18928dc07742c659f1e66e0a33e605409fbd Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 5 Apr 2025 10:20:57 +0530 Subject: [PATCH 17/54] added solution for reverse bits --- Reverse Bits/solution.js | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Reverse Bits/solution.js 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); +}; From c0d8afd805db31ea8879e0135346696b89f92481 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 5 Apr 2025 11:37:52 +0530 Subject: [PATCH 18/54] added solution for climping stairs --- Climbing stairs/solution.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Climbing stairs/solution.js 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 From a301b6773e1e7b2f0294023cb74b97a8e7fc0a66 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sun, 6 Apr 2025 16:30:27 +0530 Subject: [PATCH 19/54] added solution for coin change --- Coin change/solution.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Coin change/solution.js 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 From ec4a4a97a822666b27028cfdd207033087ea19b6 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sun, 6 Apr 2025 17:06:17 +0530 Subject: [PATCH 20/54] added solution for longest increasing subsequense --- Longest increasing subsequence/solution.js | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Longest increasing subsequence/solution.js 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 From 5c1f7c097f67d3ae5fd96c25fe9b0e2a491c4d48 Mon Sep 17 00:00:00 2001 From: *vivek Date: Wed, 9 Apr 2025 13:31:10 +0530 Subject: [PATCH 21/54] added solution for longest common subsequence --- Lonngest Common Subsequence/solution.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Lonngest Common Subsequence/solution.js 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 From 808b4d8a0babe1a40c15fd9f517296549e9a845c Mon Sep 17 00:00:00 2001 From: *vivek Date: Fri, 11 Apr 2025 15:58:00 +0530 Subject: [PATCH 22/54] added soluton for word break --- Word break/solution.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Word break/solution.js 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 From 2afd93c5792daff425a39eafac748998ee07d494 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 12 Apr 2025 10:46:33 +0530 Subject: [PATCH 23/54] added solution for combination sum --- Combination sum/solution.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Combination sum/solution.js 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 From 3a54a30a0dc2d76dd2d9cede33dc014f13d72558 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 12 Apr 2025 11:19:02 +0530 Subject: [PATCH 24/54] added solution for house robber --- House robber/solution.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 House robber/solution.js 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 From 56c67c08cb9a40cbcc0a37d9098abe8f3a3f19db Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 15 Apr 2025 15:35:17 +0530 Subject: [PATCH 25/54] added solution for house robber 2 --- House robber 2/solution.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 House robber 2/solution.js 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 From 4b0bd941e7a7f866c07d046b1baf2cd9fd591b62 Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 15 Apr 2025 15:58:14 +0530 Subject: [PATCH 26/54] added solution for decode ways --- Decode ways/solution.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Decode ways/solution.js 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 From 91783888081a40b3970dce140e0878233e289623 Mon Sep 17 00:00:00 2001 From: *vivek Date: Wed, 16 Apr 2025 10:58:56 +0530 Subject: [PATCH 27/54] added solution for unique paths --- Unique paths/solution.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Unique paths/solution.js 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 From fbeceabaf8377b43ecfe9677f5b5650bef4dee1a Mon Sep 17 00:00:00 2001 From: *vivek Date: Wed, 16 Apr 2025 11:21:49 +0530 Subject: [PATCH 28/54] added solution for jump game --- Jump game/solution.js | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Jump game/solution.js 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 From f5329ce2052eac568302efdfeb299ff7d0cfa6ed Mon Sep 17 00:00:00 2001 From: *vivek Date: Fri, 18 Apr 2025 12:18:19 +0530 Subject: [PATCH 29/54] added solution for clone graph --- Clone Graph/solution.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Clone Graph/solution.js 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 From 6ee445320faea800f049c526d8236be7ac37a9eb Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 24 Apr 2025 09:26:23 +0530 Subject: [PATCH 30/54] added solution for course schedule --- Course schedule.js/solution.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Course schedule.js/solution.js 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; +} From 930c909771690cf37c5aeb6c6471981d2798a2d6 Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 24 Apr 2025 10:35:20 +0530 Subject: [PATCH 31/54] added solution for pacific atlantic water flow --- Pacific atlantic water flow/solution.js | 46 +++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Pacific atlantic water flow/solution.js 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 From d6e68bc3efd15cc1e83cb27dd177fd21c5124050 Mon Sep 17 00:00:00 2001 From: *vivek Date: Fri, 25 Apr 2025 10:04:07 +0530 Subject: [PATCH 32/54] added solution for number of islands --- Number of islands/solution.js | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Number of islands/solution.js 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 From 6fb364d58a97fdae139bdb87f9e047f5e92841b2 Mon Sep 17 00:00:00 2001 From: *vivek Date: Fri, 25 Apr 2025 10:46:50 +0530 Subject: [PATCH 33/54] added solution for longest consecutive sequence --- Longest consecutive sequence/solution.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Longest consecutive sequence/solution.js 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 From 8877cb26598e8207d4cf00ccfd86421a4cd61697 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 26 Apr 2025 11:36:11 +0530 Subject: [PATCH 34/54] added solution for Find Building Where Alice and Bob Can Meet --- Find building alice and bob/solution.js | 58 +++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Find building alice and bob/solution.js 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 From a825c1b30a146c9f25c9712c159905cdb17acdc3 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 26 Apr 2025 12:01:34 +0530 Subject: [PATCH 35/54] added solution for maximum sum star of a graph --- Maximum star sum of a graph/solution.js | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Maximum star sum of a graph/solution.js 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 From b913998b11e2170a64316d5b7dfc6e012c8846b9 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 26 Apr 2025 15:05:58 +0530 Subject: [PATCH 36/54] added solution for unreachable pairs --- Count unreachable pairs/solution.js | 91 +++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Count unreachable pairs/solution.js 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; +}; From 6180fec0d73ab28df8e8abd43e274ffd7f090916 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 26 Apr 2025 19:35:02 +0530 Subject: [PATCH 37/54] added solution for insert interval --- Insert interval/solution.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Insert interval/solution.js 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 From 3d4d458b6e4a58c220bc4c7564a495b50f010494 Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 29 Apr 2025 21:26:19 +0530 Subject: [PATCH 38/54] added solution for merge interval --- MergeInterval/solution.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 MergeInterval/solution.js 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 From bde0caf98f99133c5225050f0ebd55be1c77d3a3 Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 29 Apr 2025 21:43:27 +0530 Subject: [PATCH 39/54] added solution for erase overlap intervals --- EraseOverLapIntervals/solution.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 EraseOverLapIntervals/solution.js 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 From 0ad008502b1c40d1d20d6d5748cf7efd44a0bfb6 Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 29 Apr 2025 22:13:04 +0530 Subject: [PATCH 40/54] added solution for can attend meetings --- Can attend meetings/solution.js | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Can attend meetings/solution.js 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 From 8fc02795e2da21f29407f5485a95fc51c0847296 Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 1 May 2025 22:28:49 +0530 Subject: [PATCH 41/54] added solution for meeting room 2 --- MeetingRooms 2/solution.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 MeetingRooms 2/solution.js 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(); + } +} From 9e241df88f180108d4dad0ccc118501d68083646 Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 1 May 2025 22:48:03 +0530 Subject: [PATCH 42/54] added solution for reverse linked list --- ReverseLinkedList/solution.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 ReverseLinkedList/solution.js 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 From d01532abe9019d8231cc2ddf50e53a52d2300f4b Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 1 May 2025 22:49:34 +0530 Subject: [PATCH 43/54] added solution for cyclles in linked list --- LinkedListCycle/solution.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LinkedListCycle/solution.js 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 From fd3af614c28c97613f09d5be9b44e5684165ba20 Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 1 May 2025 23:08:26 +0530 Subject: [PATCH 44/54] added solution for merge two linked list --- MergeTwoLinkedList/solution.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 MergeTwoLinkedList/solution.js 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 From de6cf694fd287ef5cd8482f24774985e4bc9671d Mon Sep 17 00:00:00 2001 From: *vivek Date: Fri, 2 May 2025 22:11:55 +0530 Subject: [PATCH 45/54] added solution for mergeksorted lists --- MergeKSortedLists/solution.js | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 MergeKSortedLists/solution.js 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 From fb917e7549e1f47a6311a6b66e418ad2f2598032 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 3 May 2025 20:32:31 +0530 Subject: [PATCH 46/54] added solution for remove nth node from the end of list --- RemoveNthNodeFromTheEndOfList/solution.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 RemoveNthNodeFromTheEndOfList/solution.js 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 From c6570e8b192fb3a87c24aea08bbe430b1956d31f Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 3 May 2025 21:12:36 +0530 Subject: [PATCH 47/54] added solution for reorderlist --- ReorderList/solution.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 ReorderList/solution.js 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 From da60e34c9f6162f2c557ab2123672c3a64d76bd2 Mon Sep 17 00:00:00 2001 From: *vivek Date: Sat, 3 May 2025 21:49:05 +0530 Subject: [PATCH 48/54] added solution for set matrix zeros --- SetMatrixZeros/solution.js | 67 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 SetMatrixZeros/solution.js 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 From edbd8acc788c3bec0b1cb5c090f498e0e5d16552 Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 6 May 2025 22:20:35 +0530 Subject: [PATCH 49/54] added solution for spiral order --- Spiral Order/solution.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Spiral Order/solution.js 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 From 14a4bf4b09aa7c08b28976f72f4db6fab4698f04 Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 6 May 2025 22:22:22 +0530 Subject: [PATCH 50/54] added solution for rotate image --- Rotate Image/solution.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Rotate Image/solution.js 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 From fcf5daad4338e4c19a082ae2d2a0bd5d29ec053e Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 6 May 2025 22:24:12 +0530 Subject: [PATCH 51/54] added solution for word search --- Word Search/solution.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Word Search/solution.js 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 From a32e89ea2317808cd3c5769bc6a4fca338c33772 Mon Sep 17 00:00:00 2001 From: *vivek Date: Tue, 6 May 2025 22:49:23 +0530 Subject: [PATCH 52/54] added solution for longest substring without repeating characters --- .../solution.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 LongestsubstringWithoutrepeatingCharacters/solution.js 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 From bb4c004a21abb6afd09d3e6ef79f2e30f02984a2 Mon Sep 17 00:00:00 2001 From: *vivek Date: Wed, 7 May 2025 21:20:51 +0530 Subject: [PATCH 53/54] added solution for longest repeating charcter replacement --- .../solution.js | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Longest Repeating Character Replacement/solution.js 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 From a959c49d0c8fe0c0484ea9c1cb5e362d6286e045 Mon Sep 17 00:00:00 2001 From: *vivek Date: Thu, 15 May 2025 22:12:37 +0530 Subject: [PATCH 54/54] add solution for minimum window substring --- Minimum window substring/solution.js | 43 ++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Minimum window substring/solution.js 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