diff --git a/dsa-problems/leetcode-problems/0200-0299.md b/dsa-problems/leetcode-problems/0200-0299.md index 2cee3a213..05285fd0a 100644 --- a/dsa-problems/leetcode-problems/0200-0299.md +++ b/dsa-problems/leetcode-problems/0200-0299.md @@ -68,7 +68,7 @@ export const problems = [ "problemName": "209. Minimum Size Subarray Sum", "difficulty": "Medium", "leetCodeLink": "https://leetcode.com/problems/minimum-size-subarray-sum", -"solutionLink": "#" +"solutionLink": "/dsa-solutions/lc-solutions/0200-0299/minimum-size-subarray-sum" }, { "problemName": "210. Course Schedule II", diff --git a/dsa-solutions/lc-solutions/0000-0099/0017-Letter-Combinations-of-a-Phone-Number.md b/dsa-solutions/lc-solutions/0000-0099/0017-Letter-Combinations-of-a-Phone-Number.md index 76a29c9c4..26cf596b7 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0017-Letter-Combinations-of-a-Phone-Number.md +++ b/dsa-solutions/lc-solutions/0000-0099/0017-Letter-Combinations-of-a-Phone-Number.md @@ -3,23 +3,21 @@ id: letter-combinations-of-a-phone-number title: Letter Combinations of a Phone Number (LeetCode) sidebar_label: 0017 Letter Combinations of a Phone Number tags: - - Back Tracking - - Mapping - - String + - Back Tracking + - Mapping + - String description: The problem requires generating all letter combinations corresponding to given digits (2-9). The solution utilizes backtracking to explore all combinations efficiently, employing a recursive approach in Java. -sidebar_position: 17 --- ## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------- | -| [Letter Combinations of a Phone Number](https://leetcode.com/problems/Letter Combinations of a Phone Number/) | [Letter Combinations of a Phone Number Solution on LeetCode](https://leetcode.com/problems/Letter Combinations of a Phone Number/solutions/5055810/video-two-pointer-solution/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | +| Problem Statement | Solution Link | LeetCode Profile | +| :----------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------- | +| [Letter Combinations of a Phone Number](https://leetcode.com/problems/Letter Combinations of a Phone Number/) | [Letter Combinations of a Phone Number Solution on LeetCode](https://leetcode.com/problems/Letter Combinations of a Phone Number/solutions/5055810/video-two-pointer-solution/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | ### Problem Description ## Problem Statement: - Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order. ### Examples @@ -34,6 +32,7 @@ Given a string containing digits from 2-9 inclusive, return all possible letter - **Input:** `digits = ""` - **Output:** `[]` + #### Example 3 - **Input:** `2` @@ -48,11 +47,9 @@ Given a string containing digits from 2-9 inclusive, return all possible letter ### Approach 1. **Mapping Digits to Letters:** - - Define a mapping of digits to their corresponding letters, similar to telephone buttons. 2. **Backtracking Function:** - - Define a recursive backtracking function to generate all possible combinations. - The function takes four parameters: - `index`: The current index in the digits string. @@ -62,7 +59,6 @@ Given a string containing digits from 2-9 inclusive, return all possible letter - After the recursive call, we remove the last character from the combination (backtracking). 3. **Base Case:** - - If the length of the current combination is equal to the length of the input digits string, we add the combination to the result list. 4. **Main Function:** @@ -157,7 +153,6 @@ public class Solution { ``` #### CPP: - ```cpp #include #include @@ -213,41 +208,40 @@ int main() { ``` #### JavaScript - ```js /** * @param {string} digits * @return {string[]} */ -var letterCombinations = function (digits) { - if (digits.length === 0) return []; - - const digitToLetters = { - 2: "abc", - 3: "def", - 4: "ghi", - 5: "jkl", - 6: "mno", - 7: "pqrs", - 8: "tuv", - 9: "wxyz", - }; - - const combinations = []; - - const backtrack = (index, path) => { - if (index === digits.length) { - combinations.push(path); - return; - } - const letters = digitToLetters[digits.charAt(index)]; - for (let letter of letters) { - backtrack(index + 1, path + letter); - } - }; - - backtrack(0, ""); - return combinations; +var letterCombinations = function(digits) { + if (digits.length === 0) return []; + + const digitToLetters = { + '2': 'abc', + '3': 'def', + '4': 'ghi', + '5': 'jkl', + '6': 'mno', + '7': 'pqrs', + '8': 'tuv', + '9': 'wxyz' + }; + + const combinations = []; + + const backtrack = (index, path) => { + if (index === digits.length) { + combinations.push(path); + return; + } + const letters = digitToLetters[digits.charAt(index)]; + for (let letter of letters) { + backtrack(index + 1, path + letter); + } + }; + + backtrack(0, ''); + return combinations; }; // Example usage: @@ -255,40 +249,39 @@ console.log(letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf" ``` #### TypeScript - ```ts class Solution { - private digitToLetters: { [key: string]: string } = { - "2": "abc", - "3": "def", - "4": "ghi", - "5": "jkl", - "6": "mno", - "7": "pqrs", - "8": "tuv", - "9": "wxyz", - }; - - letterCombinations(digits: string): string[] { - const combinations: string[] = []; - - const backtrack = (index: number, path: string): void => { - if (index === digits.length) { - combinations.push(path); - return; - } - const letters = this.digitToLetters[digits.charAt(index)]; - for (let letter of letters) { - backtrack(index + 1, path + letter); - } + private digitToLetters: { [key: string]: string } = { + '2': 'abc', + '3': 'def', + '4': 'ghi', + '5': 'jkl', + '6': 'mno', + '7': 'pqrs', + '8': 'tuv', + '9': 'wxyz' }; - if (digits.length !== 0) { - backtrack(0, ""); - } + letterCombinations(digits: string): string[] { + const combinations: string[] = []; + + const backtrack = (index: number, path: string): void => { + if (index === digits.length) { + combinations.push(path); + return; + } + const letters = this.digitToLetters[digits.charAt(index)]; + for (let letter of letters) { + backtrack(index + 1, path + letter); + } + }; - return combinations; - } + if (digits.length !== 0) { + backtrack(0, ''); + } + + return combinations; + } } // Example usage: @@ -301,11 +294,9 @@ console.log(solution.letterCombinations("23")); // Output: ["ad","ae","af","bd", Here's a step-by-step algorithm for generating all possible letter combinations of a given string of digits using backtracking: 1. **Define a mapping of digits to letters:** - - Create a map where each digit from 2 to 9 is mapped to its corresponding letters on a telephone keypad. 2. **Define a backtracking function:** - - The function will take the following parameters: - `index`: The current index in the digits string. - `path`: The current combination of letters. @@ -314,7 +305,6 @@ Here's a step-by-step algorithm for generating all possible letter combinations - After the recursive call, remove the last character from the combination (backtracking). 3. **Base Case:** - - If the length of the current combination is equal to the length of the input digits string, add the combination to the result list. 4. **Main Function:** @@ -322,4 +312,4 @@ Here's a step-by-step algorithm for generating all possible letter combinations - Call the backtracking function with the initial index set to 0 and an empty string as the initial combination. - Return the list of combinations. -This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking. +This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking. \ No newline at end of file diff --git a/dsa-solutions/lc-solutions/0200-0299/0206-Reverse-Linkedlist.md b/dsa-solutions/lc-solutions/0200-0299/0206-Reverse-Linkedlist.md index b13d40e13..944446ae4 100644 --- a/dsa-solutions/lc-solutions/0200-0299/0206-Reverse-Linkedlist.md +++ b/dsa-solutions/lc-solutions/0200-0299/0206-Reverse-Linkedlist.md @@ -11,9 +11,7 @@ tags: description: "This document provides solutions for determining the Reverse Linkedlist." --- -# 0206-Reverse LinkedList - -### Problem Statement +## Problem Statement Given the head of a singly linked list, reverse the list, and return the reversed list. diff --git a/dsa-solutions/lc-solutions/0200-0299/0209-minimum-size-subarray-sum.md b/dsa-solutions/lc-solutions/0200-0299/0209-minimum-size-subarray-sum.md new file mode 100644 index 000000000..d7c1a9b1e --- /dev/null +++ b/dsa-solutions/lc-solutions/0200-0299/0209-minimum-size-subarray-sum.md @@ -0,0 +1,227 @@ +--- +id: minimum-size-subarray-sum +title: Minimum Size Subarray Sum +sidebar_label: 0209 Minimum Size Subarray Sum +tags: + - Dynamic Programming + - C + - C++ + - Java + - Python +description: "This document provides a solution to the Minimum Size Subarray Sum problem" +--- + +## Problem Statement + +Given an array of positive integers nums and a positive integer target, return the minimal length of a +subarray +whose sum is greater than or equal to target. If there is no such subarray, return 0 instead. + +Example 1: + + Input: target = 7, nums = [2,3,1,2,4,3] + Output: 2 + Explanation: The subarray [4,3] has the minimal length under the problem constraint. + +Example 2: + + Input: target = 4, nums = [1,4,4] + Output: 1 + +Example 3: + + Input: target = 11, nums = [1,1,1,1,1,1,1,1] + Output: 0 + +## Solutions + +### Intuition + + To solve this problem efficiently, we need to avoid checking all possible subarrays one by one since doing so would result in a very slow solution when dealing with a large array. The intuitive insight here is that we can do much better by using a "sliding window" approach. This approach involves maintaining a window that expands and contracts as we iterate through the array to find the smallest window that satisfies the condition. + + Here's the thought process behind the sliding window solution: + + 1. We start with two pointers, both at the beginning of the array. These pointers represent the margins of our current window. + + 2. We move the end pointer to the right, adding numbers to our current window's sum. + + 3. As soon as the window's sum becomes equal to or greater than the target, we attempt to shrink the window from the left to find smaller valid windows that still meet the sum criterion. + + 4. Each successful window gives us a potential answer (its size), we keep track of the minimum size found. + + 5. We continue this process until the end pointer reaches the end of the array, and there are no more subarrays to check. + + 6. If the minimum length of the window is never updated from the initial setting that is larger than the array length, it means no valid subarray has been found, and we should return 0. + + 7. By using this approach, we can ensure that we only traverse the array once, giving us an efficient solution with a time complexity of O(n), where n is the length of the input array. + + Learn more about Binary Search, Prefix Sum and Sliding Window patterns. + +### Solution Approach + + The provided solution uses the Sliding Window pattern to solve the problem efficiently. This approach is useful when you need to find a subarray that meets certain criteria, and the problem can be solved in linear time without the need to check every possible subarray individually. + + Here's how the sliding window algorithm is implemented in the solution: + + 1. Initialize two pointers, j at 0 to represent the start of the window and i which will move through the array. + + 2. Maintain a running sum, s, of the values within the current window which starts at 0. + + 3. Iterate over the array using i and continuously add the value of nums[i] to s. + + 4. Inside the loop, use a while loop to check if the current sum s is greater than or equal to the target. If it is, attempt to shrink the window from the left by: + + 5. Updating the minimum length of the valid window if necessary using ans = min(ans, i - j + 1). + + 6. Subtracting nums[j] from the sum s since the left end of the window is moving to the right. + + 7. Incrementing j to actually move the window's start to the right. + + 8. Once the end of the array is reached and there are no more elements to add to the sum, check if ans was updated or not. If ans is still greater than the length of the array n, it means no valid subarray was found, so we return 0. + + 9. If ans was updated during the process (meaning a valid subarray was found), return the value of ans which holds the length of the smallest subarray with a sum of at least target. + + 10. The use of two pointers to create a window that slides over the array allows this algorithm to run in O(n) time, making it very efficient for this type of problem. + + Please note that the Reference Solution Approach mentions another method which is using PreSum & Binary Search but the provided code doesn't implement this method. The PreSum & Binary Search method involves creating an array of prefix sums and then using binary search to find the smallest valid subarray for each element. This is a bit more complex and generally not as efficient as the Sliding Window method used here which requires only O(n) time and O(1) extra space. + + + + + ```cpp + #include + #include + #include + using namespace std; + + class Solution { + public: + int minSubArrayLen(int target, vector& nums) { + int n = nums.size(); + int left = 0; + int sum = 0; + int minLength = INT_MAX; + + for (int i = 0; i < n; i++) { + sum += nums[i]; + + while (sum >= target) { + minLength = min(minLength, i - left + 1); + sum -= nums[left++]; + } + } + + return minLength == INT_MAX ? 0 : minLength; + } + }; + ``` + + + + ```java + import java.util.*; + + public class Solution { + public int minSubArrayLen(int target, int[] nums) { + int n = nums.length; + int left = 0; + int sum = 0; + int minLength = Integer.MAX_VALUE; + + for (int i = 0; i < n; i++) { + sum += nums[i]; + + while (sum >= target) { + minLength = Math.min(minLength, i - left + 1); + sum -= nums[left++]; + } + } + + return minLength == Integer.MAX_VALUE ? 0 : minLength; + } + + public static void main(String[] args) { + Solution solution = new Solution(); + int[] nums = {2, 3, 1, 2, 4, 3}; + int target = 7; + System.out.println(solution.minSubArrayLen(target, nums)); // Output: 2 + } + } + ``` + + + + ```python + from typing import List + + class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + n = len(nums) + left = 0 + sum = 0 + minLength = float('inf') + + for i in range(n): + sum += nums[i] + + while sum >= target: + minLength = min(minLength, i - left + 1) + sum -= nums[left] + left += 1 + + return 0 if minLength == float('inf') else minLength + + # Driver code + if __name__ == "__main__": + solution = Solution() + nums = [2, 3, 1, 2, 4, 3] + target = 7 + print(solution.minSubArrayLen(target, nums)) # Output: 2 + ``` + + + + ```c + #include + #include + + int minSubArrayLen(int target, int* nums, int numsSize) { + int left = 0; + int sum = 0; + int minLength = INT_MAX; + + for (int i = 0; i < numsSize; i++) { + sum += nums[i]; + + while (sum >= target) { + if (i - left + 1 < minLength) { + minLength = i - left + 1; + } + sum -= nums[left++]; + } + } + + return minLength == INT_MAX ? 0 : minLength; + } + + // Driver code + int main() { + int nums[] = {2, 3, 1, 2, 4, 3}; + int target = 7; + int result = minSubArrayLen(target, nums, sizeof(nums) / sizeof(nums[0])); + printf("%d\n", result); // Output: 2 + return 0; + } + ``` + + + + +## video lecture + +