From 9a94e604654b0121bd8f7c96a4ae416c12c79f19 Mon Sep 17 00:00:00 2001 From: Nikita Saini Date: Mon, 10 Jun 2024 22:55:19 +0530 Subject: [PATCH 1/3] Create 0030-0030-Substring-with-Concatenation-of-All-Words Adding Solution to the leetcode problem 0030-Substring-with-Concatenation-of-All-Words --- ...bString-with-Concatenation-of-all-words.md | 377 ++++++++++++++++++ 1 file changed, 377 insertions(+) create mode 100644 dsa-solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md diff --git a/dsa-solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md b/dsa-solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md new file mode 100644 index 000000000..8b85c9fa1 --- /dev/null +++ b/dsa-solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md @@ -0,0 +1,377 @@ +--- +id: Substring with Concatenation of All Words +title: Substring with Concatenation of All Words +sidebar_label: 0030-Substring-with-Concatenation-of-All-Words +tags: + - Hard + - String + - Hash Table + - Two Pointers +description: A concatenated string is a string that exactly contains all the strings of any permutation of `words` concatenated. +--- + +### Problem Description: +| Problem Statement | Solution Link | LeetCode Profile | +| :------------------------------------------------------ | :------------------------------------------------------------------------- | :------------------------------------------------------ | +| [Substring with Concatenation of All Words](https://leetcode.com/problems/0030-Substring-with-Concatenation-of-All-Words/description/) | [Substring with Concatenation of All Words Solution on LeetCode](https://leetcode.com/problems/0030-Substring-with-Concatenation-of-All-Words/solutions/) | [Nikita Saini](https://leetcode.com/u/Saini_Nikita/) | + +## Problem Description +You are given a string `s` and an array of strings `words`. All the strings in `words` are of the same length. + +### Examples + +**Example 1:** + +- **Input:** `s = "barfoothefoobarman"`, `words = ["foo","bar"]` +- **Output:** `[0,9]` + +- **Explanation:** +- The substring starting at 0 is "barfoo". It is the concatenation of `["bar","foo"]` which is a permutation of `words`. +- The substring starting at 9 is "foobar". It is the concatenation of `["foo","bar"]` which is a permutation of `words`. + +**Example 2:** + +- **Input:** `s = "wordgoodgoodgoodbestword"`, `words = ["word","good","best","word"]` +- **Output:** `[]` + +- **Explanation:** +- There is no concatenated substring. + +**Example 3:** + +- **Input:** `s = "barfoofoobarthefoobarman"`, `words = ["bar","foo","the"]` +- **Output:** `[6,9,12]` + +- **Explanation:** +- The substring starting at 6 is "foobarthe". It is the concatenation of `["foo","bar","the"]`. +- The substring starting at 9 is "barthefoo". It is the concatenation of `["bar","the","foo"]`. +- The substring starting at 12 is "thefoobar". It is the concatenation of `["the","foo","bar"]`. + +### Constraints + +- 1 <= s.length <= 10^4 +- 1 <= words.length <= 5000 +- 1 <= words[i].length <= 30 +- s and words[i] consist of lowercase English letters. + +## Approach +We will use a sliding window approach to solve this problem. +1. First, we calculate the length of each word in the `words` array and the total length of the concatenated substring. +2. We create a hashmap to store the count of each word in `words`. +3. We iterate over each possible starting index in the string `s` using a sliding window of size equal to the total length of the concatenated substring. +4. For each substring, we check if it can be formed by concatenating all the words in `words`. +5. To check the validity of each window, we use another hashmap to count occurrences of words in the current window and compare it to the word count map. +6. If the current window is valid, we add its starting index to the result list. + +## Solution in Java +```java +import java.util.*; + +public class Solution { + public List findSubstring(String s, String[] words) { + List result = new ArrayList<>(); + if (s == null || s.length() == 0 || words == null || words.length == 0) { + return result; + } + + int wordLength = words[0].length(); + int wordCount = words.length; + int totalLength = wordLength * wordCount; + + // Create a map to count the words + Map wordMap = new HashMap<>(); + for (String word : words) { + wordMap.put(word, wordMap.getOrDefault(word, 0) + 1); + } + + // Slide the window over the string `s` + for (int i = 0; i <= s.length() - totalLength; i++) { + String currentSubstring = s.substring(i, i + totalLength); + if (isValid(currentSubstring, wordMap, wordLength, wordCount)) { + result.add(i); + } + } + + return result; + } + + private boolean isValid(String substring, Map wordMap, int wordLength, int wordCount) { + Map seen = new HashMap<>(); + for (int j = 0; j < wordCount; j++) { + int wordStartIndex = j * wordLength; + String word = substring.substring(wordStartIndex, wordStartIndex + wordLength); + if (!wordMap.containsKey(word)) { + return false; + } + seen.put(word, seen.getOrDefault(word, 0) + 1); + if (seen.get(word) > wordMap.get(word)) { + return false; + } + } + return true; + } +} +``` + +### Solution in Python +```python +class Solution: + def findSubstring(self, s: str, words: List[str]) -> List[int]: + result = [] + if not s or not words: + return result + + word_length = len(words[0]) + word_count = len(words) + total_length = word_length * word_count + + word_map = {} + for word in words: + word_map[word] = word_map.get(word, 0) + 1 + + for i in range(len(s) - total_length + 1): + current_substring = s[i:i + total_length] + if self.is_valid(current_substring, word_map, word_length, word_count): + result.append(i) + + return result + + def is_valid(self, substring, word_map, word_length, word_count): + seen = {} + for j in range(word_count): + word_start_index = j * word_length + word = substring[word_start_index:word_start_index + word_length] + if word not in word_map: + return False + seen[word] = seen.get(word, 0) + 1 + if seen[word] > word_map[word]: + return False + return True +``` + +### Solution in CPP +```cpp +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + vector findSubstring(string s, vector& words) { + vector result; + if (s.empty() || words.empty()) { + return result; + } + + int wordLength = words[0].length(); + int wordCount = words.size(); + int totalLength = wordLength * wordCount; + + unordered_map wordMap; + for (const string& word : words) { + wordMap[word]++; + } + + for (int i = 0; i <= s.length() - totalLength; i++) { + string currentSubstring = s.substr(i, totalLength); + if (isValid(currentSubstring, wordMap, wordLength, wordCount)) { + result.push_back(i); + } + } + + return result; + } + + bool isValid(string substring, unordered_map& wordMap, int wordLength, int wordCount) { + unordered_map seen; + for (int j = 0; j < wordCount; j++) { + string word = substring.substr(j * wordLength, wordLength); + if (wordMap.find(word) == wordMap.end()) { + return false; + } + seen[word]++; + if (seen[word] > wordMap[word]) { + return false; + } + } + return true; + } +}; + +int main() { + Solution solution; + string s = "barfoothefoobarman"; + vector words = {"foo", "bar"}; + vector result = solution.findSubstring(s, words); + for (int idx : result) { + cout << idx << " "; + } + cout << endl; + return 0; +} +``` + +### Solution in C +```c +#include +#include +#include + +#define MAX_WORD_LENGTH 30 + +int isValid(char* substring, char** words, int* wordMap, int wordLength, int wordCount) { + int seen[5000] = {0}; + for (int j = 0; j < wordCount; j++) { + char* word = substring + j * wordLength; + int index = -1; + for (int k = 0; k < wordCount; k++) { + if (strcmp(word, words[k]) == 0) { + index = k; + break; + } + } + if (index == -1 || wordMap[index] == 0) { + return 0; + } + seen[index]++; + if (seen[index] > wordMap[index]) { + return 0; + } + } + return 1; +} + +int* findSubstring(char* s, char** words, int wordsSize, int* returnSize) { + *returnSize = 0; + if (!s || !words || wordsSize == 0) { + return NULL; + } + + int wordLength = strlen(words[0]); + int wordCount = wordsSize; + int totalLength = wordLength * wordCount; + + int* result = (int*)malloc(sizeof(int) * 5000); + if (!result) { + return NULL; + } + + int wordMap[5000] = {0}; + for (int i = 0; i < wordCount; i++) { + int found = 0; + for (int j = 0; j < i; j++) { + if (strcmp(words[i], words[j]) == 0) { + found = 1; + wordMap[j]++; + break; + } + } + if (!found) { + wordMap[i]++; + } + } + + for (int i = 0; i <= strlen(s) - totalLength; i++) { + char currentSubstring[totalLength + 1]; + strncpy(currentSubstring, s + i, totalLength); + currentSubstring[totalLength] = '\0'; + if (isValid(currentSubstring, words, wordMap, wordLength, wordCount)) { + result[(*returnSize)++] = i; + } + } + + return result; +} + +int main() { + char* s = "barfoothefoobarman"; + char* words[2] = {"foo", "bar"}; + int wordsSize = 2; + int returnSize; + int* result = findSubstring(s, words, wordsSize, &returnSize); + for (int i = 0; i < returnSize; i++) { + printf("%d ", result[i]); + } + printf("\n"); + free(result); + return 0; +} +``` + +### Solution in JavaScript +```js +/** + * @param {string} s + * @param {string[]} words + * @return {number[]} + */ +var findSubstring = function(s, words) { + const result = []; + if (!s || !words || words.length === 0) { + return result; + } + + const wordLength = words[0].length; + const wordCount = words.length; + const totalLength = wordLength * wordCount; + + const wordMap = {}; + words.forEach(word => { + if (wordMap[word]) { + wordMap[word]++; + } else { + wordMap[word] = 1; + } + }); + + for (let i = 0; i <= s.length - totalLength; i++) { + const currentSubstring = s.substring(i, i + totalLength); + if (isValid(currentSubstring, wordMap, wordLength, wordCount)) { + result.push(i); + } + } + + return result; +}; + +function isValid(substring, wordMap, wordLength, wordCount) { + const seen = {}; + for (let j = 0; j < wordCount; j++) { + const word = substring.substr(j * wordLength, wordLength); + if (!wordMap[word]) { + return false; + } + if (!seen[word]) { + seen[word] = 1; + } else { + seen[word]++; + } + if (seen[word] > wordMap[word]) { + return false; + } + } + return true; +} + +// Example usage: +const s = "barfoothefoobarman"; +const words = ["foo", "bar"]; +console.log(findSubstring(s, words)); // Output: [0, 9] +``` + +### Step by Step Algorithm +1. Initialize an empty list `result` to store the starting indices of all the concatenated substrings. +2. Check for base cases: if `s` or `words` is empty, return the empty list `result`. +3. Calculate the length of each word in the `words` array and the total length of the concatenated substring. +4. Create a hashmap `word_map` to store the count of each word in `words`. +5. Iterate over each possible starting index in the string `s` using a sliding window of size equal to the total length of the concatenated substring. +6. For each substring, check if it can be formed by concatenating all the words in `words`. +7. To check the validity of each window, use another hashmap `seen` to count occurrences of words in the current window and compare it to the `word_map`. +8. If the current window is valid, add its starting index to the `result` list. +9. Return the `result` list. + +### Conclusion +This problem can be efficiently solved using a sliding window approach. By using a hashmap to store the count of words and iterating over each possible starting index in the string `s`, we can find all the concatenated substrings in `s` that are formed by concatenating all the strings of any permutation of `words`. The time complexity of this solution is O(NML), where N is the length of the string `s`, M is the number of words, and L is the length of each word. \ No newline at end of file From 8abb4b75ea721a5041f36ec8585f2a37c1a44b2d Mon Sep 17 00:00:00 2001 From: Nikita Saini Date: Mon, 10 Jun 2024 22:55:51 +0530 Subject: [PATCH 2/3] Update 0017 --- ...7-letter-combinations-of-a-phone-number.md | 377 ++++++++++++------ 1 file changed, 250 insertions(+), 127 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 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 From 74eb2d449cccf7fdd944f7e2391a5a05a8abebb5 Mon Sep 17 00:00:00 2001 From: Nikita Saini Date: Tue, 11 Jun 2024 14:53:44 +0530 Subject: [PATCH 3/3] Updated Code Basedon Suggestions Updated Code based on Suggestion --- .../0017-Letter-Combinations-of-a-Phone-Number.md | 4 +--- .../0017-letter-combinations-of-a-phone-number.md | 2 +- .../0030 - SubString-with-Concatenation-of-all-words.md | 9 ++++----- 3 files changed, 6 insertions(+), 9 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 fd6fed234..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 @@ -39,7 +39,6 @@ Given a string containing digits from 2-9 inclusive, return all possible letter - **Output:** `["a","b","c"]` ### Constraints: - - `0 ≤ digits.length ≤ 4` - `0 ≤ digits.length ≤ 4digits[𝑖]` - `digits[i] is a digit in the range ['2', '9'].` @@ -70,7 +69,6 @@ Given a string containing digits from 2-9 inclusive, return all possible letter This approach ensures that all possible combinations are generated using backtracking, and the result is returned in the desired format. ### Solution Code - #### Python ```python @@ -314,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/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 b14e99991..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 @@ -1,5 +1,5 @@ --- -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 tags: diff --git a/dsa-solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md b/dsa-solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md index 8b85c9fa1..4a87c4f76 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md +++ b/dsa-solutions/lc-solutions/0000-0099/0030 - SubString-with-Concatenation-of-all-words.md @@ -1,5 +1,5 @@ --- -id: Substring with Concatenation of All Words +id: substring-with-concatenation-of-all-words title: Substring with Concatenation of All Words sidebar_label: 0030-Substring-with-Concatenation-of-All-Words tags: @@ -48,10 +48,9 @@ You are given a string `s` and an array of strings `words`. All the strings in ` - The substring starting at 12 is "thefoobar". It is the concatenation of `["the","foo","bar"]`. ### Constraints - -- 1 <= s.length <= 10^4 -- 1 <= words.length <= 5000 -- 1 <= words[i].length <= 30 +- $1 \leq \text{s.length} \leq 10^4$ +- $1 \leq \text{words.length} \leq 5000$ +- $1 \leq \text{words[i].length} \leq 30$ - s and words[i] consist of lowercase English letters. ## Approach