From f2adf9f6734ca42ae7efb13a3be0f381138485cc Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Tue, 11 Jun 2024 19:41:03 +0530 Subject: [PATCH 1/2] Added stack using arrays --- docs/dsa/stack/stack-using-array.md | 244 ++++++++++++++++++ ...7-letter-combinations-of-a-phone-number.md | 140 +++++----- package-lock.json | 14 +- 3 files changed, 316 insertions(+), 82 deletions(-) create mode 100644 docs/dsa/stack/stack-using-array.md diff --git a/docs/dsa/stack/stack-using-array.md b/docs/dsa/stack/stack-using-array.md new file mode 100644 index 000000000..f3a012c6d --- /dev/null +++ b/docs/dsa/stack/stack-using-array.md @@ -0,0 +1,244 @@ +--- +id: stack-in-dsa +title: Stack Using Array +sidebar_label: Stack +sidebar_position: 1 +description: "" +tags: [dsa, data-structures, stack] +--- + +### Introduction to Stack + +A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first one to be removed. Stacks are used in various applications such as expression evaluation, function call management in recursion, and more. + +### Stack Operations + +1. **Push**: Add an element to the top of the stack. +2. **Pop**: Remove the top element from the stack. +3. **Peek (or Top)**: Retrieve the top element of the stack without removing it. +4. **isEmpty**: Check if the stack is empty. +5. **Size**: Get the number of elements in the stack. + +### Pseudocode + +#### Basic Operations + +1. **Push**: + + ```text + function push(stack, element): + stack.append(element) + ``` + +2. **Pop**: + + ```text + function pop(stack): + if isEmpty(stack): + return "Stack Underflow" + return stack.pop() + ``` + +3. **Peek**: + + ```text + function peek(stack): + if isEmpty(stack): + return "Stack is empty" + return stack[-1] + ``` + +4. **isEmpty**: + + ```text + function isEmpty(stack): + return len(stack) == 0 + ``` + +5. **Size**: + ```text + function size(stack): + return len(stack) + ``` + +### Implementation in Python, C++, and Java + +#### Python Implementation + +```python +class Stack: + def __init__(self): + self.elements = [] + + def push(self, element): + self.elements.append(element) + + def pop(self): + if self.is_empty(): + return "Stack Underflow" + return self.elements.pop() + + def peek(self): + if self.is_empty(): + return "Stack is empty" + return self.elements[-1] + + def is_empty(self): + return len(self.elements) == 0 + + def size(self): + return len(self.elements) + +# Example usage +stack = Stack() +stack.push(10) +stack.push(20) +print(stack.pop()) # Output: 20 +print(stack.peek()) # Output: 10 +print(stack.is_empty()) # Output: False +print(stack.size()) # Output: 1 +``` + +#### C++ Implementation + +```cpp +#include +#include + +class Stack { +private: + std::vector.elements; + +public: + void push(int element) { + .elements.push_back(element); + } + + int pop() { + if (isEmpty()) { + std::cerr << "Stack Underflow" << std::endl; + return -1; + } + int top =.elements.back(); + .elements.pop_back(); + return top; + } + + int peek() { + if (isEmpty()) { + std::cerr << "Stack is empty" << std::endl; + return -1; + } + return.elements.back(); + } + + bool isEmpty() { + return.elements.empty(); + } + + int size() { + return.elements.size(); + } +}; + +// Example usage +int main() { + Stack stack; + stack.push(10); + stack.push(20); + std::cout << stack.pop() << std::endl; // Output: 20 + std::cout << stack.peek() << std::endl; // Output: 10 + std::cout << std::boolalpha << stack.isEmpty() << std::endl; // Output: false + std::cout << stack.size() << std::endl; // Output: 1 + return 0; +} +``` + +#### Java Implementation + +```java +import java.util.ArrayList; + +public class Stack { + private ArrayList.elements; + + public Stack() { + .elements = new ArrayList<>(); + } + + public void push(int element) { + .elements.add(element); + } + + public int pop() { + if (isEmpty()) { + System.out.println("Stack Underflow"); + return -1; + } + return.elements.remove.elements.size() - 1); + } + + public int peek() { + if (isEmpty()) { + System.out.println("Stack is empty"); + return -1; + } + return.elements.get.elements.size() - 1); + } + + public boolean isEmpty() { + return.elements.isEmpty(); + } + + public int size() { + return.elements.size(); + } + + // Example usage + public static void main(String[] args) { + Stack stack = new Stack(); + stack.push(10); + stack.push(20); + System.out.println(stack.pop()); // Output: 20 + System.out.println(stack.peek()); // Output: 10 + System.out.println(stack.isEmpty()); // Output: false + System.out.println(stack.size()); // Output: 1 + } +} +``` + +### Complexity + +- **Time Complexity**: + + - Push: $O(1)$ + - Pop: $O(1)$ + - Peek: $O(1)$ + - isEmpty: $O(1)$ + - Size: $O(1)$ + +- **Space Complexity**: $O(n)$, where $n$ is the number of elements in the stack. + +### Example + +Consider a stack with the following operations: + +1. Push 10 +2. Push 20 +3. Pop +4. Peek +5. Check if empty +6. Get size + +**Operations**: + +- Push 10: Stack becomes [10] +- Push 20: Stack becomes [10, 20] +- Pop: Removes 20, Stack becomes [10] +- Peek: Returns 10, Stack remains [10] +- isEmpty: Returns false +- Size: Returns 1 + +### Conclusion + +A stack is a fundamental data structure used in computer science for various applications where the LIFO (Last In First Out) principle is required. It is simple to implement and provides efficient operations for adding and removing elements. Understanding and using stacks effectively can help solve many algorithmic problems. 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 90b0bd8a5..890c371f1 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` @@ -49,11 +48,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. @@ -63,7 +60,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:** @@ -159,7 +155,6 @@ public class Solution { ``` #### CPP: - ```cpp #include #include @@ -215,41 +210,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: @@ -257,40 +251,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: @@ -303,11 +296,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. @@ -316,7 +307,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:** @@ -324,4 +314,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/package-lock.json b/package-lock.json index 6c2093a62..f7331a46e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5464,11 +5464,11 @@ } }, "node_modules/braces": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", - "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "dependencies": { - "fill-range": "^7.0.1" + "fill-range": "^7.1.1" }, "engines": { "node": ">=8" @@ -9682,9 +9682,9 @@ } }, "node_modules/fill-range": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", - "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "dependencies": { "to-regex-range": "^5.0.1" }, From 68a39de7d4d287fa600b5a9e5f98591483db796a Mon Sep 17 00:00:00 2001 From: Hema Sree Date: Tue, 11 Jun 2024 19:54:31 +0530 Subject: [PATCH 2/2] Added stack --- docs/dsa/stack/_category_.json | 8 ++++++++ docs/dsa/stack/stack-using-array.md | 6 +++--- 2 files changed, 11 insertions(+), 3 deletions(-) create mode 100644 docs/dsa/stack/_category_.json diff --git a/docs/dsa/stack/_category_.json b/docs/dsa/stack/_category_.json new file mode 100644 index 000000000..7fee1f14e --- /dev/null +++ b/docs/dsa/stack/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Stack", + "position": 9, + "link": { + "type": "generated-index", + "description": "Stack is a linear data structure that follows LIFO principle" + } +} diff --git a/docs/dsa/stack/stack-using-array.md b/docs/dsa/stack/stack-using-array.md index f3a012c6d..3dd65eb53 100644 --- a/docs/dsa/stack/stack-using-array.md +++ b/docs/dsa/stack/stack-using-array.md @@ -1,10 +1,10 @@ --- id: stack-in-dsa title: Stack Using Array -sidebar_label: Stack +sidebar_label: Stack Using Array sidebar_position: 1 -description: "" -tags: [dsa, data-structures, stack] +description: "Stack is a linear data structure that follows LIFO principle" +tags: [dsa, data-structures, stack, LIFO] --- ### Introduction to Stack