From d5fc630f38a448d70e88afa4657b526f40b68282 Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Sun, 9 Jun 2024 21:49:11 +0530 Subject: [PATCH 1/4] Addedleetcode solution for 136 --- ...7-letter-combinations-of-a-phone-number.md | 377 ++++++++++++------ .../0100-0199/0136-single-number.md | 121 ++++++ 2 files changed, 371 insertions(+), 127 deletions(-) create mode 100644 dsa-solutions/lc-solutions/0100-0199/0136-single-number.md 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 a112c79fb..de07f5ca6 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 @@ -1,89 +1,104 @@ --- -id: letter-combinations-of-a-phone-number +id: Letter Combinations of a Phone Number title: Letter Combinations of a Phone Number (LeetCode) -sidebar_label: 0017-Letter Combinations of a Phone Number +sidebar_label: 0017-Letter-Combinations-of-a-Phone-Number tags: - - String - - Backtracking -description: "Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent." + - 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. --- ## 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/) | [gabaniyash846](https://leetcode.com/u/gabaniyash846/) | +| [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. -A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. - ### Examples #### Example 1 + - **Input:** `digits = "23"` - **Output:** `["ad","ae","af","bd","be","bf","cd","ce","cf"]` #### Example 2 + - **Input:** `digits = ""` - **Output:** `[]` + #### Example 3 -- **Input:** `digits = "2"` + +- **Input:** `2` - **Output:** `["a","b","c"]` -### Constraints -- `0 <= digits.length <= 4` -- `digits[i]` is a digit in the range `['2', '9']`. +### Constraints: +- `0 ≤ digits.length ≤ 4` +- `0 ≤ digits.length ≤ 4digits[𝑖]` +- `digits[i] is a digit in the range ['2', '9'].` +- `A mapping of digits to letters (similar to telephone buttons) is given below. Note that 1 does not map to any letters.` -### Topics -- String -- Backtracking +### Approach -### Intuition -- Use backtracking to generate all possible combinations. +1. **Mapping Digits to Letters:** + - Define a mapping of digits to their corresponding letters, similar to telephone buttons. -### Complexity -- **Time Complexity:** $O(3^N \cdot 4^M)$ where $N$ is the number of digits in the input that maps to 3 letters (2, 3, 4, 5, 6, 8) and $M$ is the number of digits in the input that maps to 4 letters (7, 9). -- **Space Complexity:** $O(3^N \cdot 4^M)$ for storing the results. +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. + - `path`: The current combination of letters. + - If the index is equal to the length of the digits string, it means we have reached the end of a combination, so we add it to the result list. + - Otherwise, for each letter corresponding to the current digit, we append it to the current combination and recursively call the function with the next index. + - After the recursive call, we remove the last character from the combination (backtracking). -### Solution Code and Explanation +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. -#### C++ +4. **Main Function:** + - Initialize an empty list to store the 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. -```cpp -#include -#include -#include +This approach ensures that all possible combinations are generated using backtracking, and the result is returned in the desired format. -class Solution { -public: - std::vector letterCombinations(std::string digits) { - if (digits.empty()) return {}; - std::unordered_map phoneMap = { - {'2', "abc"}, {'3', "def"}, {'4', "ghi"}, - {'5', "jkl"}, {'6', "mno"}, {'7', "pqrs"}, - {'8', "tuv"}, {'9', "wxyz"} - }; - std::vector result; - backtrack(digits, phoneMap, 0, "", result); - return result; - } +### Solution Code -private: - void backtrack(const std::string& digits, const std::unordered_map& phoneMap, int index, std::string current, std::vector& result) { - if (index == digits.size()) { - result.push_back(current); - return; - } - const std::string& letters = phoneMap.at(digits[index]); - for (const char& letter : letters) { - backtrack(digits, phoneMap, index + 1, current + letter, result); +#### Python + +```python +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + if not digits: + return [] + + digit_to_letters = { + '2': 'abc', + '3': 'def', + '4': 'ghi', + '5': 'jkl', + '6': 'mno', + '7': 'pqrs', + '8': 'tuv', + '9': 'wxyz' } - } -}; + + def backtrack(index, path): + if index == len(digits): + combinations.append(path) + return + for letter in digit_to_letters[digits[index]]: + backtrack(index + 1, path + letter) + + combinations = [] + backtrack(0, '') + return combinations ``` #### Java @@ -94,100 +109,208 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -class Solution { +public class Solution { + private Map digitToLetters = new HashMap<>(); + + public Solution() { + digitToLetters.put('2', "abc"); + digitToLetters.put('3', "def"); + digitToLetters.put('4', "ghi"); + digitToLetters.put('5', "jkl"); + digitToLetters.put('6', "mno"); + digitToLetters.put('7', "pqrs"); + digitToLetters.put('8', "tuv"); + digitToLetters.put('9', "wxyz"); + } + public List letterCombinations(String digits) { - List result = new ArrayList<>(); - if (digits.isEmpty()) return result; - Map phoneMap = new HashMap<>() {{ - put('2', "abc"); - put('3', "def"); - put('4', "ghi"); - put('5', "jkl"); - put('6', "mno"); - put('7', "pqrs"); - put('8', "tuv"); - put('9', "wxyz"); - }}; - backtrack(digits, phoneMap, 0, new StringBuilder(), result); - return result; + List combinations = new ArrayList<>(); + if (digits == null || digits.isEmpty()) { + return combinations; + } + backtrack(combinations, digits, 0, new StringBuilder()); + return combinations; } - private void backtrack(String digits, Map phoneMap, int index, StringBuilder current, List result) { + private void backtrack(List combinations, String digits, int index, StringBuilder path) { if (index == digits.length()) { - result.add(current.toString()); + combinations.add(path.toString()); return; } - String letters = phoneMap.get(digits.charAt(index)); + String letters = digitToLetters.get(digits.charAt(index)); for (char letter : letters.toCharArray()) { - current.append(letter); - backtrack(digits, phoneMap, index + 1, current, result); - current.deleteCharAt(current.length() - 1); + path.append(letter); + backtrack(combinations, digits, index + 1, path); + path.deleteCharAt(path.length() - 1); } } + + public static void main(String[] args) { + Solution solution = new Solution(); + List result = solution.letterCombinations("23"); + System.out.println(result); // Output: [ad, ae, af, bd, be, bf, cd, ce, cf] + } } ``` -#### Python +#### CPP: +```cpp +#include +#include +#include -```python -from typing import List +using namespace std; -class Solution: - def letterCombinations(self, digits: str) -> List[str]: - if not digits: - return [] - - phone_map = { - "2": "abc", "3": "def", "4": "ghi", "5": "jkl", - "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" +class Solution { +private: + unordered_map digitToLetters; + vector combinations; + +public: + Solution() { + digitToLetters = { + {'2', "abc"}, + {'3', "def"}, + {'4', "ghi"}, + {'5', "jkl"}, + {'6', "mno"}, + {'7', "pqrs"}, + {'8', "tuv"}, + {'9', "wxyz"} + }; + } + + vector letterCombinations(string digits) { + if (digits.empty()) return {}; + backtrack(digits, 0, ""); + return combinations; + } + + void backtrack(const string& digits, int index, string path) { + if (index == digits.length()) { + combinations.push_back(path); + return; + } + for (char letter : digitToLetters[digits[index]]) { + backtrack(digits, index + 1, path + letter); + } + } +}; + +int main() { + Solution solution; + vector result = solution.letterCombinations("23"); + for (const string& comb : result) { + cout << comb << " "; + } + // Output: ad ae af bd be bf cd ce cf + return 0; +} +``` + +#### 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; +}; + +// Example usage: +console.log(letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] +``` + +#### 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); + } + }; + + if (digits.length !== 0) { + backtrack(0, ''); } - def backtrack(index: int, path: str): - if index == len(digits): - combinations.append(path) - return - possible_letters = phone_map[digits[index]] - for letter in possible_letters: - backtrack(index + 1, path + letter) - - combinations = [] - backtrack(0, "") - return combinations + return combinations; + } +} + +// Example usage: +const solution = new Solution(); +console.log(solution.letterCombinations("23")); // Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"] ``` -### Explanation +### Step-by-Step Algorithm -1. **Initialize Phone Map:** - Create a mapping from digit to corresponding letters. - ```python - phone_map = { - "2": "abc", "3": "def", "4": "ghi", "5": "jkl", - "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz" - } - ``` +Here's a step-by-step algorithm for generating all possible letter combinations of a given string of digits using backtracking: -2. **Backtracking Function:** - Define a recursive function `backtrack` to generate combinations. - - **Base case:** If the current index is equal to the length of digits, add the current path to combinations. - - **Recursive case:** For each letter corresponding to the current digit, append the letter to the path and call `backtrack` with the next index. - ```python - def backtrack(index: int, path: str): - if index == len(digits): - combinations.append(path) - return - possible_letters = phone_map[digits[index]] - for letter in possible_letters: - backtrack(index + 1, path + letter) - ``` - -3. **Initiate Backtracking:** - Initialize the result list `combinations` and start the backtracking process. - ```python - combinations = [] - backtrack(0, "") - return combinations - ``` - -### Conclusion - -The above solution efficiently generates all possible letter combinations for a given string of digits. It employs a backtracking approach to explore all potential combinations, leveraging a recursive function to build the combinations step-by-step. The time complexity of $O(3^N \cdot 4^M)$ and space complexity of $O(3^N \cdot 4^M)$ ensure that the algorithm can handle input sizes up to the upper limit specified in the constraints efficiently. +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. + - If the index is equal to the length of the digits string, it means we have formed a complete combination, so add it to the result list. + - Otherwise, for each letter corresponding to the current digit at the given index, append it to the current combination and recursively call the function with the next index. + - 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:** + - Initialize an empty list to store the 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. \ No newline at end of file diff --git a/dsa-solutions/lc-solutions/0100-0199/0136-single-number.md b/dsa-solutions/lc-solutions/0100-0199/0136-single-number.md new file mode 100644 index 000000000..1209c581e --- /dev/null +++ b/dsa-solutions/lc-solutions/0100-0199/0136-single-number.md @@ -0,0 +1,121 @@ +--- +id: single-number +title: Single Number +sidebar_label: 0136 Single Number +tags: + - Java + - Python + - C++ + - XOR +description: "This is a solution to the Single Number problem on LeetCode." +--- + +## Problem Description + +Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. + +You must implement a solution with a linear runtime complexity and use only constant extra space. + +### Examples + +**Example 1:** + +``` +Input: nums = [2,2,1] +Output: 1 + +``` + +**Example 2:** + +Input: nums = [4,1,2,1,2] +Output: 4 + +**Example 3:** + +``` +Input: nums = [1] +Output: 1 +``` + +### Constraints + +- $1 <= nums.length <= 3 * 10^4$ +- $-3 * 10^4 <= nums[i] <= 3 _ 10^4$ +- Each element in the array appears twice except for one element which appears only once. + +--- + +## Solution for Single Number Problem + +### Intuition + +When faced with this problem, the first hurdle to overcome is the strict limitations imposed on the solution: linear time complexity and constant space complexity. This means traditional methods of identifying duplicates like hash tables or sorting won't cut it. Instead, we'll need to use a different kind of magic, one rooted in the world of bitwise operations! + +### Approach + +Our saviour here is the XOR operation. XOR stands for 'exclusive or', and the magic lies in its properties. When a number is XORed with itself, the result is 0. And when a number is XORed with 0, the result is the number itself. + +So, if we XOR all the numbers in the array, all the numbers appearing twice will cancel each other out and we'll be left with the single number that appears only once. + +#### Code in Different Languages + + + + + ```java + class Solution { + public int singleNumber(int[] nums) { + int result = 0; + for (int num : nums) { + result ^= num; + } + return result; + } +} + +````` + + + + +````python +class Solution: + def singleNumber(self, nums: List[int]) -> int: + result = 0 + for num in nums: + result ^= num + return result + +````` + + + + +```cpp +class Solution { +public: + int singleNumber(vector& nums) { + int result = 0; + for (int num : nums) { + result ^= num; + } + return result; + } +}; + +``` + + + +#### Complexity Analysis + +- Time complexity: $O(n)$, as we're iterating over the array only once. +- Space complexity: $O(1)$, because we're only using a single variable to store the result, irrespective of the size of the input. + +## References + +- **LeetCode Problem:** [Single Number](https://leetcode.com/problems/single-number/description/) +- **Solution Link:** [Single NUmber on LeetCode](https://leetcode.com/problems/single-number/solutions/3801367/video-single-number-a-bitwise-magic-trick/) +- **Authors Leetcode Profile:** [vanAmsen](https://leetcode.com/u/vanAmsen/) +``` From 60b2935afc4e235918af89510a5cd3f297a50586 Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Mon, 10 Jun 2024 11:29:02 +0530 Subject: [PATCH 2/4] updated changes --- ...7-letter-combinations-of-a-phone-number.md | 144 ++++++++++-------- 1 file changed, 77 insertions(+), 67 deletions(-) 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 de07f5ca6..b084ac27e 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 @@ -1,23 +1,24 @@ --- -id: Letter Combinations of a Phone Number +id: letter-combinations-of-a-phone-number title: Letter Combinations of a Phone Number (LeetCode) -sidebar_label: 0017-Letter-Combinations-of-a-Phone-Number +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. --- ## 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 @@ -32,13 +33,13 @@ Given a string containing digits from 2-9 inclusive, return all possible letter - **Input:** `digits = ""` - **Output:** `[]` - #### Example 3 - **Input:** `2` - **Output:** `["a","b","c"]` ### Constraints: + - `0 ≤ digits.length ≤ 4` - `0 ≤ digits.length ≤ 4digits[𝑖]` - `digits[i] is a digit in the range ['2', '9'].` @@ -47,9 +48,11 @@ 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. @@ -59,6 +62,7 @@ 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:** @@ -154,6 +158,7 @@ public class Solution { ``` #### CPP: + ```cpp #include #include @@ -209,40 +214,41 @@ 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: @@ -250,39 +256,40 @@ 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' + 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); + } }; - 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); - } - }; - - if (digits.length !== 0) { - backtrack(0, ''); - } - - return combinations; + if (digits.length !== 0) { + backtrack(0, ""); } + + return combinations; + } } // Example usage: @@ -295,9 +302,11 @@ 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. @@ -306,6 +315,7 @@ 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:** @@ -313,4 +323,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. \ No newline at end of file +This algorithm ensures that all possible combinations are generated by exploring all valid paths through backtracking. From 13c4b85d4f5686e0340232b1303befa49fcd749b Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Mon, 10 Jun 2024 11:31:07 +0530 Subject: [PATCH 3/4] updated changes --- ...7-letter-combinations-of-a-phone-number.md | 144 ++++++++---------- 1 file changed, 67 insertions(+), 77 deletions(-) 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 b084ac27e..de07f5ca6 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 @@ -1,24 +1,23 @@ --- -id: letter-combinations-of-a-phone-number +id: Letter Combinations of a Phone Number title: Letter Combinations of a Phone Number (LeetCode) -sidebar_label: 0017-Letter Combinations of a Phone Number +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. --- ## 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 @@ -33,13 +32,13 @@ Given a string containing digits from 2-9 inclusive, return all possible letter - **Input:** `digits = ""` - **Output:** `[]` + #### Example 3 - **Input:** `2` - **Output:** `["a","b","c"]` ### Constraints: - - `0 ≤ digits.length ≤ 4` - `0 ≤ digits.length ≤ 4digits[𝑖]` - `digits[i] is a digit in the range ['2', '9'].` @@ -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:** @@ -158,7 +154,6 @@ public class Solution { ``` #### CPP: - ```cpp #include #include @@ -214,41 +209,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: @@ -256,40 +250,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: @@ -302,11 +295,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. @@ -315,7 +306,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:** @@ -323,4 +313,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 From 3ab1b9f402cd23d4ab23a887d1c6cbb3abd8816e Mon Sep 17 00:00:00 2001 From: Ajay Dhangar <99037494+Ajay-Dhangar@users.noreply.github.com> Date: Mon, 10 Jun 2024 16:50:49 +0530 Subject: [PATCH 4/4] Update 0136-single-number.md --- dsa-solutions/lc-solutions/0100-0199/0136-single-number.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dsa-solutions/lc-solutions/0100-0199/0136-single-number.md b/dsa-solutions/lc-solutions/0100-0199/0136-single-number.md index 1209c581e..1bd606fec 100644 --- a/dsa-solutions/lc-solutions/0100-0199/0136-single-number.md +++ b/dsa-solutions/lc-solutions/0100-0199/0136-single-number.md @@ -40,8 +40,8 @@ Output: 1 ### Constraints -- $1 <= nums.length <= 3 * 10^4$ -- $-3 * 10^4 <= nums[i] <= 3 _ 10^4$ +- $1 \leq nums.length \leq 3 * 10^4$ +- $-3 \times 10^4 \leq nums[i] \leq 3 \times 10^4$ - Each element in the array appears twice except for one element which appears only once. ---