diff --git a/dsa-solutions/lc-solutions/0000-0099/0001-two-sum.md b/dsa-solutions/lc-solutions/0000-0099/0001-two-sum.md index 957fa5207..d2a11bb87 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0001-two-sum.md +++ b/dsa-solutions/lc-solutions/0000-0099/0001-two-sum.md @@ -1,6 +1,6 @@ --- id: two-sum -title: Two Sum Problem (LeetCode) +title: Two Sum Solution sidebar_label: 0001 - Two Sum tags: - Two Sum @@ -13,11 +13,7 @@ tags: description: "This is a solution to the Two Sum problem on LeetCode." --- -## Problem Description - -| Problem Statement | Solution Link | LeetCode Profile | -| :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------- | -| [Two Sum on LeetCode](https://leetcode.com/problems/two-sum/) | [Two Sum Solution on LeetCode](https://leetcode.com/problems/two-sum/solutions/4958021/two-sum-problem-solution-using-hash-table-ts-js-java-py-cpp-recommended-solutions) | [Ajay Dhangar](https://leetcode.com/ajaydhangar49/) | +In this page, we will solve the Two Sum problem using three different approaches: brute force, hash table, and two-pointer technique. We will provide the implementation of the solution in JavaScript, TypeScript, Python, Java, C++, and more. ## Problem Description @@ -29,21 +25,21 @@ You can return the answer in any order. ### Examples -**`Example 1:`** +**Example 1:** ```plaintext Input: nums = [2,7,11,15], target = 9 Output: [0,1] ``` -**`Example 2:`** +**Example 2:** ```plaintext Input: nums = [3,2,4], target = 6 Output: [1,2] ``` -**`Example 3:`** +**Example 3:** ```plaintext Input: nums = [3,3], target = 6 @@ -69,7 +65,8 @@ The problem can be solved using a brute force approach, a hash table, or the two - ### Approach 1: Brute Force (Naive) + +### Approach 1: Brute Force (Naive) The brute force approach is simple. We iterate through each element `nums[i]` and check if there is another element `nums[j]` such that `nums[i] + nums[j] == target`. If we find such a pair, we return the indices `[i, j]`. @@ -109,6 +106,7 @@ function twoSumProblem() { + ```javascript function twoSum(nums, target) { for (let i = 0; i < nums.length; i++) { @@ -124,7 +122,8 @@ function twoSumProblem() { ``` - + + ```typescript function twoSum(nums: number[], target: number): number[] { for (let i = 0; i < nums.length; i++) { @@ -140,7 +139,8 @@ function twoSumProblem() { ``` - + + ```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: @@ -153,7 +153,8 @@ function twoSumProblem() { ``` - + + ```java class Solution { public int[] twoSum(int[] nums, int target) { @@ -171,7 +172,8 @@ function twoSumProblem() { ``` - + + ```cpp class Solution { public: @@ -247,6 +249,7 @@ function twoSumProblem() { + ```javascript function twoSum(nums, target) { const numMap = new Map(); @@ -264,7 +267,8 @@ function twoSumProblem() { ``` - + + ```typescript function twoSum(nums: number[], target: number): number[] { const numMap = new Map(); @@ -282,7 +286,8 @@ function twoSumProblem() { ``` - + + ```python class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: @@ -297,7 +302,8 @@ function twoSumProblem() { ``` - + + ```java class Solution { public int[] twoSum(int[] nums, int target) { @@ -317,7 +323,8 @@ function twoSumProblem() { ``` - + + ```cpp class Solution { public: @@ -405,6 +412,7 @@ function twoSumProblem() { + ```javascript function twoSum(nums, target) { const sortedNums = nums.map((num, index) => [num, index]); @@ -429,8 +437,10 @@ function twoSumProblem() { ``` - - ```typescript + + + + ```ts function twoSum(nums: number[], target: number): number[] { const sortedNums = nums.map((num, index) => [num, index]); sortedNums.sort((a, b) => a[0] - b[0]); @@ -454,8 +464,9 @@ function twoSumProblem() { ``` - - ```python + + + ```py class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: sorted_nums = sorted(enumerate(nums), key=lambda x: x[1]) @@ -475,7 +486,8 @@ function twoSumProblem() { ``` - + + ```java class Solution { public int[] twoSum(int[] nums, int target) { @@ -506,7 +518,9 @@ function twoSumProblem() { ``` - + + + ```cpp class Solution { public: @@ -562,6 +576,8 @@ The hash table approach is the most efficient and is recommended for large input ::: -## Conclusion +## References -In this tutorial, we learned how to solve the Two Sum problem on LeetCode using different approaches. We discussed the brute force approach, the hash table approach, and the two-pointer approach. We implemented the solutions in JavaScript, TypeScript, Python, Java, and C++. We also analyzed the time and space complexity of each approach and compared them to determine the best approach for this problem. The hash table approach is the most efficient and is recommended for large inputs. +- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/two-sum/) +- **Solution Link:** [Two Sum Solution on LeetCode](https://leetcode.com/problems/two-sum/solutions/4958021/two-sum-problem-solution-using-hash-table-ts-js-java-py-cpp-recommended-solutions) +- **Authors LeetCode Profile:** [Ajay Dhangar](https://leetcode.com/ajaydhangar49/) \ No newline at end of file diff --git a/dsa-solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md b/dsa-solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md index 486fc9107..651e83e72 100644 --- a/dsa-solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md +++ b/dsa-solutions/lc-solutions/0000-0099/0002-Add-Two-Numbers.md @@ -1,6 +1,6 @@ --- id: add-two-numbers -title: Two Sum Problem (LeetCode) +title: Add Two Numbers Solution sidebar_label: 0002 - Add Two Numbers tags: - Linked List @@ -8,20 +8,29 @@ tags: - Recursion description: "This is a solution to the Add Two Numbers problem on LeetCode." --- -## Problem Description -| Problem Statement | Solution Link | LeetCode Profile | -| :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------- | -| [Add Two Numbers on LeetCode](https://leetcode.com/problems/add-two-numbers/) | [Add Two Numbers Solution on LeetCode](https://leetcode.com/problems/add-two-numbers/solutions/5234194/solution/) | [Amruta Jayanti](https://leetcode.com/u/user7669cY/)| +In this page, we will solve the Add Two Numbers problem. We will provide an overview of the problem, the intuition and approach to solve it, the implementation, and the code in various languages, along with a detailed explanation of the solution and its complexity analysis. Let's start by understanding the problem. +## Problem Statement -## Problem Description - -You are given two `non-empty` linked lists representing two non-negative integers. The digits are stored in `reverse order`, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. +You are given two **non-empty** linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. - +```mermaid +graph LR +M[(Input)] --> A([l1]) +M[(Input)] --> E([l2]) +A --> B((2)) +B --> C((4)) +C --> D((3)) +E --> F((5)) +F((5)) --> G((6)) +G --> H((4)) +I[(Output)] --> J((7)) +J --> K((0)) +K --> L((8)) +``` **Example 1:** @@ -43,128 +52,308 @@ Output: [0] ```plaintext Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] Output: [8,9,9,9,0,0,0,1] -``` +``` -### Constraints: +### Constraints - The number of nodes in each linked list is in the range `[1, 100]`. - `0 <= Node.val <= 9` - It is guaranteed that the list represents a number that does not have leading zeros. +--- -## Solution to the problem +## Solution for Add Two Numbers Problem ### Intuition and Approach -This is a simple problem. It can be done by maintaining two pointers , each for each linked list. Add the values store them and then move to next node. - -#### Implementation -```python -# Definition for singly-linked list. -# class ListNode(object): -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution(object): - def addTwoNumbers(self, l1, l2): - """ - :type l1: ListNode - :type l2: ListNode - :rtype: ListNode - """ - carry = 0 - dummy = ListNode() - current = dummy - while l1 or l2 or carry: - # Extract values from the current nodes - val1 = l1.val if l1 else 0 - val2 = l2.val if l2 else 0 - - # Calculate the sum and carry - total_sum = val1 + val2 + carry - carry = total_sum // 10 - current.next = ListNode(total_sum % 10) - - # Move to the next nodes - if l1: - l1 = l1.next - if l2: - l2 = l2.next +We iterate through both linked lists, adding corresponding node's values along with a carry from the previous addition. If the sum of the current node's values and carry is 10 or more, we keep the carry for the next addition. We continue this process until we traverse both linked lists. + +### Flowchart + +```mermaid +flowchart TD + A[Start] --> B{l1 or l2 or carry} + B --> |Yes| C[Add values of l1, l2, and carry] + C --> D[Calculate new carry and current node value] + D --> E[Add node with value to result list] + E --> F{Move to next node in l1 and l2 if exist} + F --> |Next nodes exist| G{l1 or l2 or carry} + G --> |Yes| C + G --> |No| H[Return result list] + F --> |Next nodes do not exist| H + B --> |No| H +``` - # Move to the next result node - current = current.next +### Pseudocode - return dummy.next +```plaintext +1. Initialize a dummy node and a current node to keep track of the current node. +2. Initialize a carry variable to 0. +3. Iterate through both linked lists until both are empty. + 1. Calculate the sum of the current node values and carry. + 2. Update the carry and current node value. + 3. Add the new node to the result list. + 4. Move to the next nodes in l1 and l2 if they exist. +4. Return the next node of the dummy node. ``` -Above is the implementation in Python. Here total_sum stores the value and adds to the dummy. Variable carry is used to handle the carry bits. - -#### Complexity Analysis: -- Time Complexity : $$O(max(n,m))$$ Here, n,m are the lengths of the input linked lists -- Space Complexity : $$O(max(n,m))$$ -#### Codes in different languages: -`CPP`: -```cpp -class Solution { -public: - ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { - ListNode* dummyHead = new ListNode(0); - ListNode* tail = dummyHead; - int carry = 0; +### Implementation and Code - while (l1 != nullptr || l2 != nullptr || carry != 0) { - int digit1 = (l1 != nullptr) ? l1->val : 0; - int digit2 = (l2 != nullptr) ? l2->val : 0; +Here is a live code editor for you to play around with the solution: - int sum = digit1 + digit2 + carry; - int digit = sum % 10; - carry = sum / 10; +```jsx live +function addTwoNumbersProblem() { + class ListNode { + constructor(val = 0, next = null) { + this.val = val; + this.next = next; + } + } + + const l1 = new ListNode(2, new ListNode(4, new ListNode(3))); + const l2 = new ListNode(5, new ListNode(6, new ListNode(4))); + + const addTwoNumbers = function (l1, l2) { + let dummyHead = new ListNode(0); + let p = l1, + q = l2, + curr = dummyHead; + let carry = 0; + + while (p !== null || q !== null) { + let x = p !== null ? p.val : 0; + let y = q !== null ? q.val : 0; + let sum = carry + x + y; + carry = Math.floor(sum / 10); + curr.next = new ListNode(sum % 10); + curr = curr.next; + if (p !== null) p = p.next; + if (q !== null) q = q.next; + } - ListNode* newNode = new ListNode(digit); - tail->next = newNode; - tail = tail->next; + if (carry > 0) { + curr.next = new ListNode(carry); + } - l1 = (l1 != nullptr) ? l1->next : nullptr; - l2 = (l2 != nullptr) ? l2->next : nullptr; - } + return dummyHead.next; + }; - ListNode* result = dummyHead->next; - delete dummyHead; - return result; + const result = addTwoNumbers(l1, l2); + const listToArray = (node) => { + const arr = []; + while (node) { + arr.push(node.val); + node = node.next; } -}; + return arr; + }; + + const resultArray = listToArray(result); + return ( +
+

+ Input: l1 = {"[" + listToArray(l1).join(", ") + "]"}, l2 ={" "} + {"[" + listToArray(l2).join(", ") + "]"} +

+

+ Output: {"[" + resultArray.join(", ") + "]"} +

+
+ ); +} ``` -`Java`: -```java -class Solution { +### Code in Different Languages + + + + + ```javascript + var addTwoNumbers = function(l1, l2) { + let dummy = new ListNode(0); + let curr = dummy; + let carry = 0; + while (l1 !== null || l2 !== null) { + let x = (l1 !== null) ? l1.val : 0; + let y = (l2 !== null) ? l2.val : 0; + let sum = x + y + carry; + carry = Math.floor(sum / 10); + curr.next = new ListNode(sum % 10); + curr = curr.next; + if (l1 !== null) l1 = l1.next; + if (l2 !== null) l2 = l2.next; + } + if (carry > 0) { + curr.next = new ListNode(carry); + } + return dummy.next; + }; + ``` + + + + + ```python + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + dummy = ListNode(0) + curr = dummy + carry = 0 + while l1 or l2: + x = l1.val if l1 else 0 + y = l2.val if l2 else 0 + sum = x + y + carry + carry = sum // 10 + curr.next = ListNode(sum % 10) + curr = curr.next + if l1: + l1 = l1.next + if l2: + l2 = l2.next + if carry > 0: + curr.next = ListNode(carry) + return dummy.next + ``` + + + + ```java public ListNode addTwoNumbers(ListNode l1, ListNode l2) { - ListNode dummyHead = new ListNode(0); - ListNode tail = dummyHead; + ListNode dummy = new ListNode(0); + ListNode curr = dummy; + int carry = 0; + while (l1 != null || l2 != null) { + int x = (l1 != null) ? l1.val : 0; + int y = (l2 != null) ? l2.val : 0; + int sum = x + y + carry; + carry = sum / 10; + curr.next = new ListNode(sum % 10); + curr = curr.next; + if (l1 != null) l1 = l1.next; + if (l2 != null) l2 = l2.next; + } + if (carry > 0) { + curr.next = new ListNode(carry); + } + return dummy.next; + } + ``` + + + + ```cpp + ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { + ListNode* dummy = new ListNode(0); + ListNode* curr = dummy; + int carry = 0; + while (l1 || l2) { + int x = l1 ? l1->val : 0; + int y = l2 ? l2->val : 0; + int sum = x + y + carry; + carry = sum / 10; + curr->next = new ListNode(sum % 10); + curr = curr->next; + if (l1) l1 = l1->next; + if (l2) l2 = l2->next; + } + if (carry > 0) { + curr->next = new ListNode(carry); + } + return dummy->next; + } + ``` + + + + ```c + struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { + struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode)); + dummy->val = 0; + dummy->next = NULL; + struct ListNode* curr = dummy; int carry = 0; + while (l1 || l2) { + int x = l1 ? l1->val : 0; + int y = l2 ? l2->val : 0; + int sum = x + y + carry; + carry = sum / 10; + curr->next = (struct ListNode*)malloc(sizeof(struct ListNode)); + curr->next->val = sum % 10; + curr->next->next = NULL; + curr = curr->next; + if (l1) l1 = l1->next; + if (l2) l2 = l2->next; + } + if (carry > 0) { + curr->next = (struct ListNode*)malloc(sizeof(struct ListNode)); + curr->next->val = carry; + curr->next->next = NULL; + } + return dummy->next; + } + ``` + + + + ```typescript + function addTwoNumbers(l1: ListNode | null, l2: ListNode | null): ListNode | null { + let dummy = new ListNode(0); + let curr = dummy; + let carry = 0; + while (l1 || l2) { + let x = l1 ? l1.val : 0; + let y = l2 ? l2.val : 0; + let sum = x + y + carry; + carry = Math.floor(sum / 10); + curr.next = new ListNode(sum % 10); + curr = curr.next; + if (l1) l1 = l1.next; + if (l2) l2 = l2.next; + } + if (carry > 0) { + curr.next = new ListNode(carry); + } + return dummy.next; + } + ``` + + - while (l1 != null || l2 != null || carry != 0) { - int digit1 = (l1 != null) ? l1.val : 0; - int digit2 = (l2 != null) ? l2.val : 0; +### Complexity Analysis - int sum = digit1 + digit2 + carry; - int digit = sum % 10; - carry = sum / 10; +The time complexity for this solution is $O(max(m, n))$, where m and n are the lengths of the two linked lists. We iterate through both linked lists once, and the space complexity is $O(max(m, n))$, where m and n are the lengths of the two linked lists. The space complexity is due to the new linked list created to store the result. - ListNode newNode = new ListNode(digit); - tail.next = newNode; - tail = tail.next; +### Test Cases - l1 = (l1 != null) ? l1.next : null; - l2 = (l2 != null) ? l2.next : null; - } + + +```plaintext +Input: l1 = [2,4,3], l2 = [5,6,4] +Output: [7,0,8] +``` + + +```plaintext +Input: l1 = [0], l2 = [0] +Output: [0] +``` + - ListNode result = dummyHead.next; - dummyHead.next = null; - return result; - } -} + +```plaintext +Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] +Output: [8,9,9,9,0,0,0,1] ``` + + + +:::info + +**Note:** The above code is a solution to the Add Two Numbers problem on LeetCode. It is a simple and efficient solution that uses a dummy node to keep track of the result linked list. The solution iterates through both linked lists, adding the corresponding node values and carry to generate the result. The time complexity of this solution is $O(max(m, n))$, where m and n are the lengths of the two linked lists, and the space complexity is $O(max(m, n))$. +::: +## Resources +- **LeetCode Problem:** [Add Two Numbers Problem](https://leetcode.com/problems/add-two-numbers/) +- **Solution Link:** [Add Two Numbers Solution on LeetCode](https://leetcode.com/problems/add-two-numbers/solutions/3368572/easy-and-understanding-solution-with-intuition-approach-complexity-and-codes) +- **Authors LeetCode Profile:** [Ajay Dhangar](https://leetcode.com/ajaydhangar49/), [Amruta Jayanti](https://leetcode.com/u/user7669cY/) \ No newline at end of file