title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
707 values
level
stringclasses
3 values
question_hints
stringlengths
19
3.98k
view_count
int64
8
630k
vote_count
int64
5
10.4k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
630,455
3,674
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe Two Sum problem asks us to find two numbers in an array that sum up to a given target value. We need to return the indices of these two numbers.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. One brute force approach is to consider every pair of elements and check if their sum equals the target. This can be done using nested loops, where the outer loop iterates from the first element to the second-to-last element, and the inner loop iterates from the next element to the last element. However, this approach has a time complexity of O(n^2).\n2. A more efficient approach is to use a hash table (unordered_map in C++). We can iterate through the array once, and for each element, check if the target minus the current element exists in the hash table. If it does, we have found a valid pair of numbers. If not, we add the current element to the hash table.\n\n**Approach using a hash table:**\n1. Create an empty hash table to store elements and their indices.\n2. Iterate through the array from left to right.\n3. For each element nums[i], calculate the complement by subtracting it from the target: complement = target - nums[i].\n4. Check if the complement exists in the hash table. If it does, we have found a solution.\n5. If the complement does not exist in the hash table, add the current element nums[i] to the hash table with its index as the value.\n6. Repeat steps 3-5 until we find a solution or reach the end of the array.\n7. If no solution is found, return an empty array or an appropriate indicator.\n\nThis approach has a time complexity of O(n) since hash table lookups take constant time on average. It allows us to solve the Two Sum problem efficiently by making just one pass through the array.\n\n# Code\n# Solution 1: (Brute Force)\n```C++ []\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n int n = nums.size();\n for (int i = 0; i < n - 1; i++) {\n for (int j = i + 1; j < n; j++) {\n if (nums[i] + nums[j] == target) {\n return {i, j};\n }\n }\n }\n return {}; // No solution found\n }\n};\n\n```\n```Java []\nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n int n = nums.length;\n for (int i = 0; i < n - 1; i++) {\n for (int j = i + 1; j < n; j++) {\n if (nums[i] + nums[j] == target) {\n return new int[]{i, j};\n }\n }\n }\n return new int[]{}; // No solution found\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n n = len(nums)\n for i in range(n - 1):\n for j in range(i + 1, n):\n if nums[i] + nums[j] == target:\n return [i, j]\n return [] # No solution found\n\n```\n\n# Solution 2: (Two-pass Hash Table)\n```C++ []\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int, int> numMap;\n int n = nums.size();\n\n // Build the hash table\n for (int i = 0; i < n; i++) {\n numMap[nums[i]] = i;\n }\n\n // Find the complement\n for (int i = 0; i < n; i++) {\n int complement = target - nums[i];\n if (numMap.count(complement) && numMap[complement] != i) {\n return {i, numMap[complement]};\n }\n }\n\n return {}; // No solution found\n }\n};\n\n```\n```Java []\nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n Map<Integer, Integer> numMap = new HashMap<>();\n int n = nums.length;\n\n // Build the hash table\n for (int i = 0; i < n; i++) {\n numMap.put(nums[i], i);\n }\n\n // Find the complement\n for (int i = 0; i < n; i++) {\n int complement = target - nums[i];\n if (numMap.containsKey(complement) && numMap.get(complement) != i) {\n return new int[]{i, numMap.get(complement)};\n }\n }\n\n return new int[]{}; // No solution found\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n numMap = {}\n n = len(nums)\n\n # Build the hash table\n for i in range(n):\n numMap[nums[i]] = i\n\n # Find the complement\n for i in range(n):\n complement = target - nums[i]\n if complement in numMap and numMap[complement] != i:\n return [i, numMap[complement]]\n\n return [] # No solution found\n\n```\n# Solution 3: (One-pass Hash Table)\n```C++ []\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int, int> numMap;\n int n = nums.size();\n\n for (int i = 0; i < n; i++) {\n int complement = target - nums[i];\n if (numMap.count(complement)) {\n return {numMap[complement], i};\n }\n numMap[nums[i]] = i;\n }\n\n return {}; // No solution found\n }\n};\n\n```\n```Java []\nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n Map<Integer, Integer> numMap = new HashMap<>();\n int n = nums.length;\n\n for (int i = 0; i < n; i++) {\n int complement = target - nums[i];\n if (numMap.containsKey(complement)) {\n return new int[]{numMap.get(complement), i};\n }\n numMap.put(nums[i], i);\n }\n\n return new int[]{}; // No solution found\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n numMap = {}\n n = len(nums)\n\n for i in range(n):\n complement = target - nums[i]\n if complement in numMap:\n return [numMap[complement], i]\n numMap[nums[i]] = i\n\n return [] # No solution found\n\n```\n![CUTE_CAT.png]()\n\n**If you are a beginner solve these problems which makes concepts clear for future coding:**\n1. [Two Sum]()\n2. [Roman to Integer]()\n3. [Palindrome Number]()\n4. [Maximum Subarray]()\n5. [Remove Element]()\n6. [Contains Duplicate]()\n7. [Add Two Numbers]()\n8. [Majority Element]()\n9. [Remove Duplicates from Sorted Array]()\n10. **Practice them in a row for better understanding and please Upvote for more questions.**\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**\n
0
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
480,307
1,288
# Beginner doubt - Where is main function?\n- Answer is very simple. LeetCode uses Class and Member method. In future I came with detailed answer of this question.\n- Lets Connect on LinkedIn (Leave a note) - \n\n# Problem Constraints\n- Test cases written like more than one solution cannot exist. Either solution exist or not.\n# Brute Force Approach\n- Run two nested loops to check every possible pair of numbers in the given array to see if they add up to the target sum.\n- If they add up to the target sum return the indexes.\n\n# Brute Force Code\n\n```C++ []\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n for (int i = 0; i < nums.size(); i++) {\n for (int j = i + 1; j < nums.size(); j++) {\n if (nums[i] + nums[j] == target) {\n return {i, j};\n }\n }\n }\n return {};\n }\n};\n\n```\n```Java []\nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n for (int i = 0; i < nums.length; i++) {\n for (int j = i + 1; j < nums.length; j++) {\n if (nums[i] + nums[j] == target) {\n return new int[] {i, j};\n }\n }\n }\n return new int[] {};\n }\n}\n\n```\n```Python []\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if (i != j and nums[i] + nums[j] == target):\n return [i, j]\n return []\n\n```\n# Complexity\n- Time complexity: O(N^2);\n- Space Complexity: O(1);\n\n---\n\n# Optimized Code\n\n```C++ []\n#include <unordered_map>\n \nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int, int> mp;\n \n for(int i = 0; i < nums.size(); i++){\n if(mp.find(target - nums[i]) == mp.end())\n mp[nums[i]] = i;\n else\n return {mp[target - nums[i]], i};\n }\n \n return {-1, -1};\n }\n};\n\n```\n```Java []\nimport java.util.HashMap;\nimport java.util.Map;\n \nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n Map<Integer, Integer> numToIndex = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n if (numToIndex.containsKey(target - nums[i])) {\n return new int[] {numToIndex.get(target - nums[i]), i};\n }\n numToIndex.put(nums[i], i);\n }\n return new int[] {};\n }\n}\n\n\n```\n```Python []\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n numToIndex = {}\n for i in range(len(nums)):\n if target - nums[i] in numToIndex:\n return [numToIndex[target - nums[i]], i]\n numToIndex[nums[i]] = i\n return []\n\n```\n# Complexity\n- Time complexity: O(N);\n- Space Complexity: O(N);\n\n# DRY Run\nSuppose we have an array nums = [2, 7, 11, 15] and a target of target = 9. We want to find two numbers in nums that add up to target.\n\nInitially, the unordered_map mp is empty. We start iterating through the array from left to right.\n\nFor the first element nums[0] = 2, we check if its complement target - nums[0] = 7 exists in the map by using the find() method. Since it does not exist in the map, we add the key-value pair (2, 0) to the map. The map now looks like this: {2: 0}.\n\nFor the second element nums[1] = 7, we check if its complement target - nums[1] = 2 exists in the map. Since it does exist in the map, we return the indices mp[2] = 0 and i = 1 as a vector {0, 1}.\n\nTherefore, the code returns the expected output of [0, 1], indicating that the indices of the two elements that add up to the target are 0 and 1.\n\n---\n\n# Upvote Me If You Like It \n\n![supermeme_12h13_27.png]()\n
1
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
6,898
16
# **Read article Explaination and codes : \n\nThe LeetCode Two Sum 1 problem is a popular coding challenge that requires finding the indices of two numbers in an array that add up to a specific target. The problem statement provides an array of integers and a target value, and the task is to return the indices of the two numbers that sum up to the target.\n\nOne approach to solve this problem efficiently is by using a hash map or dictionary. We can iterate through the given array, checking if the complement of each element (target minus current element) exists in our hash map. If it does, we have found our solution and can return the indices. Otherwise, we add the current element and its index to our hash map for future reference.\n\nAnother possible solution is by using two pointers. We can sort the array first and then initialize two pointers at the beginning and end of the array. By comparing their sum with the target value, we can move either pointer closer to each other until we find a match or exhaust all possibilities.\n\nBoth approaches have a time complexity of O(n), where n is the length of the input array. However, using a hash map might be more efficient when dealing with large arrays or when multiple solutions are expected.\n\n\n\n[![image]()]()\n\nExplanation Eg.\nTime Complexity:\n\nBruteforce: O(n^2)\n\nHashMap: O(n)\n\nTwo pass Hashmap: O(n)\n\nTwo Pointer: O(n log n)\n\n![image]()\n\n![image]()\n\nPython :\nJava:\nc++:\nJavaScript:\n\n\nRead Whole article :\n![image]()\n\n
2
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
181,399
460
```\nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n int n=nums.length;\n Map<Integer,Integer> map=new HashMap<>();\n int[] result=new int[2];\n for(int i=0;i<n;i++){\n if(map.containsKey(target-nums[i])){\n result[1]=i;\n result[0]=map.get(target-nums[i]);\n return result;\n }\n map.put(nums[i],i);\n }\n return result;\n }\n}\n```\n**Please Upvote if u like it**
4
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
51,383
263
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n dict={}\n for i,n in enumerate(nums):\n if n in dict:\n return dict[n],i\n else:\n dict[target-n]=i\n #please upvote me it would encourage me alot\n\n```
6
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
107,540
1,045
If you\'re a newbie and sometimes have a hard time understanding the logic. Don\'t worry, you\'ll catch up after a month of doing Leetcode on a daily basis. Try to do it, even one example per day. It\'d help. I\'ve compiled a bunch on `sum` problems here, go ahead and check it out. Also, I think focusing on a subject and do 3-4 problems would help to get the idea behind solution since they mostly follow the same logic. Of course there are other ways to solve each problems but I try to be as uniform as possible. Good luck. \n\nIn general, `sum` problems can be categorized into two categories: 1) there is any array and you add some numbers to get to (or close to) a `target`, or 2) you need to return indices of numbers that sum up to a (or close to) a `target` value. Note that when the problem is looking for a indices, `sort`ing the array is probably NOT a good idea. \n\n\n **[Two Sum:]()** \n \n This is the second type of the problems where we\'re looking for indices, so sorting is not necessary. What you\'d want to do is to go over the array, and try to find two integers that sum up to a `target` value. Most of the times, in such a problem, using dictionary (hastable) helps. You try to keep track of you\'ve observations in a dictionary and use it once you get to the results. \n\nNote: try to be comfortable to use `enumerate` as it\'s sometime out of comfort zone for newbies. `enumerate` comes handy in a lot of problems (I mean if you want to have a cleaner code of course). If I had to choose three built in functions/methods that I wasn\'t comfortable with at the start and have found them super helpful, I\'d probably say `enumerate`, `zip` and `set`. \n \nSolution: In this problem, you initialize a dictionary (`seen`). This dictionary will keep track of numbers (as `key`) and indices (as `value`). So, you go over your array (line `#1`) using `enumerate` that gives you both index and value of elements in array. As an example, let\'s do `nums = [2,3,1]` and `target = 3`. Let\'s say you\'re at index `i = 0` and `value = 2`, ok? you need to find `value = 1` to finish the problem, meaning, `target - 2 = 1`. 1 here is the `remaining`. Since `remaining + value = target`, you\'re done once you found it, right? So when going through the array, you calculate the `remaining` and check to see whether `remaining` is in the `seen` dictionary (line `#3`). If it is, you\'re done! you\'re current number and the remaining from `seen` would give you the output (line `#4`). Otherwise, you add your current number to the dictionary (line `#5`) since it\'s going to be a `remaining` for (probably) a number you\'ll see in the future assuming that there is at least one instance of answer. \n \n \n ```\n class Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n seen = {}\n for i, value in enumerate(nums): #1\n remaining = target - nums[i] #2\n \n if remaining in seen: #3\n return [i, seen[remaining]] #4\n else:\n seen[value] = i #5\n```\n \n \n\n **[Two Sum II:]()** \n\nFor this, you can do exactly as the previous. The only change I made below was to change the order of line `#4`. In the previous example, the order didn\'t matter. But, here the problem asks for asending order and since the values/indicess in `seen` has always lower indices than your current number, it should come first. Also, note that the problem says it\'s not zero based, meaning that indices don\'t start from zero, that\'s why I added 1 to both of them. \n\n```\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n \n seen = {}\n for i, value in enumerate(numbers): \n remaining = target - numbers[i] \n \n if remaining in seen: \n return [seen[remaining]+1, i+1] #4\n else:\n seen[value] = i \n```\n\nAnother approach to solve this problem (probably what Leetcode is looking for) is to treat it as first category of problems. Since the array is already sorted, this works. You see the following approach in a lot of problems. What you want to do is to have two pointer (if it was 3sum, you\'d need three pointers as you\'ll see in the future examples). One pointer move from `left` and one from `right`. Let\'s say you `numbers = [1,3,6,9]` and your `target = 10`. Now, `left` points to 1 at first, and `right` points to 9. There are three possibilities. If you sum numbers that `left` and `right` are pointing at, you get `temp_sum` (line `#1`). If `temp_sum` is your target, you\'r done! You\'re return it (line `#9`). If it\'s more than your `target`, it means that `right` is poiting to a very large value (line `#5`) and you need to bring it a little bit to the left to a smaller (r maybe equal) value (line `#6`) by adding one to the index . If the `temp_sum` is less than `target` (line `#7`), then you need to move your `left` to a little bit larger value by adding one to the index (line `#9`). This way, you try to narrow down the range in which you\'re looking at and will eventually find a couple of number that sum to `target`, then, you\'ll return this in line `#9`. In this problem, since it says there is only one solution, nothing extra is necessary. However, when a problem asks to return all combinations that sum to `target`, you can\'t simply return the first instace and you need to collect all the possibilities and return the list altogether (you\'ll see something like this in the next example). \n\n```\nclass Solution:\n def twoSum(self, numbers: List[int], target: int) -> List[int]:\n \n for left in range(len(numbers) -1): #1\n right = len(numbers) - 1 #2\n while left < right: #3\n temp_sum = numbers[left] + numbers[right] #4\n if temp_sum > target: #5\n right -= 1 #6\n elif temp_sum < target: #7\n left +=1 #8\n else:\n return [left+1, right+1] #9\n```\n\n\n\n\n[**3Sum**]()\n\nThis is similar to the previous example except that it\'s looking for three numbers. There are some minor differences in the problem statement. It\'s looking for all combinations (not just one) of solutions returned as a list. And second, it\'s looking for unique combination, repeatation is not allowed. \n\nHere, instead of looping (line `#1`) to `len(nums) -1`, we loop to `len(nums) -2` since we\'re looking for three numbers. Since we\'re returning values, `sort` would be a good idea. Otherwise, if the `nums` is not sorted, you cannot reducing `right` pointer or increasing `left` pointer easily, makes sense? \n\nSo, first you `sort` the array and define `res = []` to collect your outputs. In line `#2`, we check wether two consecutive elements are equal or not because if they are, we don\'t want them (solutions need to be unique) and will skip to the next set of numbers. Also, there is an additional constrain in this line that `i > 0`. This is added to take care of cases like `nums = [1,1,1]` and `target = 3`. If we didn\'t have `i > 0`, then we\'d skip the only correct solution and would return `[]` as our answer which is wrong (correct answer is `[[1,1,1]]`. \n\nWe define two additional pointers this time, `left = i + 1` and `right = len(nums) - 1`. For example, if `nums = [-2,-1,0,1,2]`, all the points in the case of `i=1` are looking at: `i` at `-1`, `left` at `0` and `right` at `2`. We then check `temp` variable similar to the previous example. There is only one change with respect to the previous example here between lines `#5` and `#10`. If we have the `temp = target`, we obviously add this set to the `res` in line `#5`, right? However, we\'re not done yet. For a fixed `i`, we still need to check and see whether there are other combinations by just changing `left` and `right` pointers. That\'s what we are doing in lines `#6, 7, 8`. If we still have the condition of `left < right` and `nums[left]` and the number to the right of it are not the same, we move `left` one index to right (line `#6`). Similarly, if `nums[right]` and the value to left of it is not the same, we move `right` one index to left. This way for a fixed `i`, we get rid of repeative cases. For example, if `nums = [-3, 1,1, 3,5]` and `target = 3`, one we get the first `[-3,1,5]`, `left = 1`, but, `nums[2]` is also 1 which we don\'t want the `left` variable to look at it simply because it\'d again return `[-3,1,5]`, right? So, we move `left` one index. Finally, if the repeating elements don\'t exists, lines `#6` to `#8` won\'t get activated. In this case we still need to move forward by adding 1 to `left` and extracting 1 from `right` (lines `#9, 10`). \n\n```\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n \n nums.sort()\n res = []\n\n for i in range(len(nums) -2): #1\n if i > 0 and nums[i] == nums[i-1]: #2\n continue\n left = i + 1 #3\n right = len(nums) - 1 #4\n \n while left < right: \n temp = nums[i] + nums[left] + nums[right]\n \n if temp > 0:\n right -= 1\n \n elif temp < 0:\n left += 1\n \n else:\n res.append([nums[i], nums[left], nums[right]]) #5\n while left < right and nums[left] == nums[left + 1]: #6\n left += 1\n while left < right and nums[right] == nums[right-1]:#7\n right -= 1 #8\n \n right -= 1 #9 \n left += 1 #10\n \n```\n\nAnother way to solve this problem is to change it into a two sum problem. Instead of finding `a+b+c = 0`, you can find `a+b = -c` where we want to find two numbers `a` and `b` that are equal to `-c`, right? This is similar to the first problem. Remember if you wanted to use the exact same as the first code, it\'d return indices and not numbers. Also, we need to re-arrage this problem in a way that we have `nums` and `target`. This code is not a good code and can be optimipized but you got the idea. For a better version of this, check [this](). \n\n```\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n res = []\n nums.sort()\n \n for i in range(len(nums)-2):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n output_2sum = self.twoSum(nums[i+1:], -nums[i])\n if output_2sum ==[]:\n continue\n else:\n for idx in output_2sum:\n instance = idx+[nums[i]]\n res.append(instance)\n \n output = []\n for idx in res:\n if idx not in output:\n output.append(idx)\n \n \n return output\n \n \n def twoSum(self, nums, target):\n seen = {}\n res = []\n for i, value in enumerate(nums): #1\n remaining = target - nums[i] #2\n \n if remaining in seen: #3\n res.append([value, remaining]) #4\n else:\n seen[value] = i #5\n \n return res\n```\n\n[**4Sum**]()\n\nYou should have gotten the idea, and what you\'ve seen so far can be generalized to `nSum`. Here, I write the generic code using the same ideas as before. What I\'ll do is to break down each case to a `2Sum II` problem, and solve them recursively using the approach in `2Sum II` example above. \n\nFirst sort `nums`, then I\'m using two extra functions, `helper` and `twoSum`. The `twoSum` is similar to the `2sum II` example with some modifications. It doesn\'t return the first instance of results, it check every possible combinations and return all of them now. Basically, now it\'s more similar to the `3Sum` solution. Understanding this function shouldn\'t be difficult as it\'s very similar to `3Sum`. As for `helper` function, it first tries to check for cases that don\'t work (line `#1`). And later, if the `N` we need to sum to get to a `target` is 2 (line `#2`), then runs the `twoSum` function. For the more than two numbers, it recursively breaks them down to two sum (line `#3`). There are some cases like line `#4` that we don\'t need to proceed with the algorithm anymore and we can `break`. These cases include if multiplying the lowest number in the list by `N` is more than `target`. Since its sorted array, if this happens, we can\'t find any result. Also, if the largest array (`nums[-1]`) multiplied by `N` would be less than `target`, we can\'t find any solution. So, `break`. \n\n\nFor other cases, we run the `helper` function again with new inputs, and we keep doing it until we get to `N=2` in which we use `twoSum` function, and add the results to get the final output. \n\n```\nclass Solution:\n def fourSum(self, nums: List[int], target: int) -> List[List[int]]:\n nums.sort()\n results = []\n self.helper(nums, target, 4, [], results)\n return results\n \n def helper(self, nums, target, N, res, results):\n \n if len(nums) < N or N < 2: #1\n return\n if N == 2: #2\n output_2sum = self.twoSum(nums, target)\n if output_2sum != []:\n for idx in output_2sum:\n results.append(res + idx)\n \n else: \n for i in range(len(nums) -N +1): #3\n if nums[i]*N > target or nums[-1]*N < target: #4\n break\n if i == 0 or i > 0 and nums[i-1] != nums[i]: #5\n self.helper(nums[i+1:], target-nums[i], N-1, res + [nums[i]], results)\n \n \n def twoSum(self, nums: List[int], target: int) -> List[int]:\n res = []\n left = 0\n right = len(nums) - 1 \n while left < right: \n temp_sum = nums[left] + nums[right] \n\n if temp_sum == target:\n res.append([nums[left], nums[right]])\n right -= 1\n left += 1\n while left < right and nums[left] == nums[left - 1]:\n left += 1\n while right > left and nums[right] == nums[right + 1]:\n right -= 1\n \n elif temp_sum < target: \n left +=1 \n else: \n right -= 1\n \n return res\n```\n[**Combination Sum II**]()\nI don\'t post combination sum here since it\'s basically this problem a little bit easier. \nCombination questions can be solved with `dfs` most of the time. if you want to fully understand this concept and [backtracking](.***.org/backtracking-introduction/), try to finish [this]() post and do all the examples. \n\nRead my older post first [here](). This should give you a better idea of what\'s going on. The solution here also follow the exact same format except for some minor changes. I first made a minor change in the `dfs` function where it doesn\'t need the `index` parameter anymore. This is taken care of by `candidates[i+1:]` in line `#3`. Note that we had `candidates` here in the previous post. \n\n```\nclass Solution(object):\n def combinationSum2(self, candidates, target):\n """\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n """\n res = []\n candidates.sort()\n self.dfs(candidates, target, [], res)\n return res\n \n \n def dfs(self, candidates, target, path, res):\n if target < 0:\n return\n \n if target == 0:\n res.append(path)\n return res\n \n for i in range(len(candidates)):\n if i > 0 and candidates[i] == candidates[i-1]: #1\n continue #2\n self.dfs(candidates[i+1:], target - candidates[i], path+[candidates[i]], res) #3\n```\n\n\nThe only differences are lines `#1, 2, 3`. The difference in problem statement in this one and `combinations` problem of my previous post is >>>candidates must be used once<<< and lines `#1` and `2` are here to take care of this. Line `#1` has two components where first `i > 0` and second `candidates[i] == candidates[i-1]`. The second component `candidates[i] == candidates[i-1]` is to take care of duplicates in the `candidates` variable as was instructed in the problem statement. Basically, if the next number in `candidates` is the same as the previous one, it means that it has already been taken care of, so `continue`. The first component takes care of cases like an input `candidates = [1]` with `target = 1` (try to remove this component and submit your solution. You\'ll see what I mean). The rest is similar to the previous [post]()\n\n================================================================\nFinal note: Please let me know if you found any typo/error/ect. I\'ll try to fix them.
7
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
8,066
9
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n vector<int> ans;\n unordered_map<int,int> mp;\n for(int i =0;i<nums.size();i++){\n if(mp.find(target-nums[i])!=mp.end()){\n ans.push_back(mp[target-nums[i]]);\n ans.push_back(i); \n }\n mp[nums[i]]=i; \n }\n return ans;\n }\n};\n```\nPlease upvote to motivate me to write more solutions
9
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
33,037
143
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n for(int i = 0;i < nums.size();i++){\n for(int j = i+1;j<nums.size();j++){\n if(nums[i] + nums[j] == target) return {i,j};\n }\n }\n return {};\n }\n};\n```\n![c5b565d0-6f8d-49f1-92c3-b618d8997854_1674098653.7034152.jpeg]()
17
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
2,372
15
```\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n hashMap = {} # key: value -> number:index\n \n for i in range(len(nums)): \n diff = target - nums[i] \n \n if diff in hashMap:\n return [hashMap[diff], i]\n else:\n hashMap[nums[i]] = i\n return []\n```
34
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
56,009
134
# Approach\n\nThe way to approach this problem is to iterate over every single item in the array and find difference between target and current number being processed.\n\nLet\u2019s keep the processed items and their index in a map (nums[i], i), so that every time we calculate the new difference, we quickly check whether that map has that item or not.\n\nLet\u2019s take 2 and 7 as an example. These are their differences and the order of when they\'ll be processed:\n```\n1. 9 - 2 = 7\n2. 9 - 7 = 2\n```\n\nFirst processed is `9 - 2`. Since difference is `7`, check if there is an element with key `7` in the map. In this case, not yet. But store `2, 0` pair.\nThe next pair that will be processed: `9 - 7`. Check for existence of 2 in the map. In this case it exists so pull out the assigned index to it and create a resulting array.\n\n# Complexity\n- Time complexity: O(n) - worse case, there are no pairs and we iterate over every single item; fetching items from a map is 0(1)\n\n- Space complexity: O(n) - we are using map to store the pairs\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[]}\n */\nvar twoSum = function(nums, target) {\n let mp = new Map()\n \n for (let i = 0; i < nums.length; i++) {\n let diff = target - nums[i]\n \n if (mp.has(diff)) {\n return [i, mp.get(diff)]\n }\n \n mp.set(nums[i], i)\n }\n};\n```
35
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
29,496
34
# Problem\n#### The problem statement describes a classic coding interview question. You are given an array of integers (nums) and an integer (target). Your task is to find two distinct numbers in the array that add up to the target. You need to return the indices of these two numbers.\n\n---\n# Solution\n\n##### 1. The twoSum function takes two arguments: nums, which is the list of integers, and target, which is the desired sum.\n\n##### 2. The solution uses a nested loop. The outer loop iterates through the elements of the nums list using enumerate. The outer loop variable i represents the index, and x represents the element at that index.\n\n##### 3.The inner loop also uses enumerate but starts from the i+1 index. This ensures that you don\'t use the same element twice (as the problem specifies). The inner loop variable j represents the index, and y represents the element at that index.\n\n##### 4.The condition if x + y == target checks whether the sum of the current elements x and y is equal to the target.\n\n##### 5.If a pair of elements is found that satisfies the condition, the next function returns a tuple (i, j) representing the indices of the two elements that add up to the target.\n---\n\n# Code\n```Python3 []\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n return next((i, j) for i, x in enumerate(nums) for j, y in enumerate(nums[i+1:], i+1) if x + y == target)\n\n```\n```python []\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n return next((i, j) for i, x in enumerate(nums) for j, y in enumerate(nums[i+1:], i+1) if x + y == target)\n\n```\n```C# []\npublic class Solution\n{\n public int[] TwoSum(int[] nums, int target)\n {\n for (int i = 0; i < nums.Length; i++)\n {\n for (int j = i + 1; j < nums.Length; j++)\n {\n if (nums[i] + nums[j] == target)\n {\n return new int[] { i, j };\n }\n }\n }\n throw new ArgumentException("No solution found");\n }\n}\n\n```\n```javascript []\nvar twoSum = function(nums, target) {\n const numToIndex = new Map(); // Create a Map to store numbers and their indices\n\n for (let i = 0; i < nums.length; i++) {\n const complement = target - nums[i];\n\n // Check if the complement exists in the Map\n if (numToIndex.has(complement)) {\n return [numToIndex.get(complement), i];\n }\n\n // Store the current number and its index in the Map\n numToIndex.set(nums[i], i);\n }\n\n throw new Error("No solution found");\n};\n```\n```C []\nint* twoSum(int* nums, int numsSize, int target, int* returnSize) {\n int* result = (int*)malloc(2 * sizeof(int)); // Allocate memory for the result array\n if (result == NULL) {\n *returnSize = 0;\n return NULL; // Return NULL if memory allocation fails\n }\n\n for (int i = 0; i < numsSize; i++) {\n for (int j = i + 1; j < numsSize; j++) {\n if (nums[i] + nums[j] == target) {\n result[0] = i;\n result[1] = j;\n *returnSize = 2; // Set the return size to 2\n return result; // Return the result array\n }\n }\n }\n\n *returnSize = 0; // If no solution found, set return size to 0\n free(result); // Free the allocated memory before returning NULL\n return NULL; // Return NULL if no solution is found\n}\n```\n```Java []\npublic class Solution {\n public int[] twoSum(int[] nums, int target) {\n Map<Integer, Integer> numToIndex = new HashMap<>();\n for (int i = 0; i < nums.length; i++) {\n int complement = target - nums[i];\n if (numToIndex.containsKey(complement)) {\n return new int[]{numToIndex.get(complement), i};\n }\n numToIndex.put(nums[i], i);\n }\n throw new IllegalArgumentException("No solution found");\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n std::vector<int> twoSum(std::vector<int>& nums, int target) {\n std::unordered_map<int, int> numToIndex;\n for (int i = 0; i < nums.size(); i++) {\n int complement = target - nums[i];\n if (numToIndex.find(complement) != numToIndex.end()) {\n return {numToIndex[complement], i};\n }\n numToIndex[nums[i]] = i;\n }\n throw std::invalid_argument("No solution found");\n }\n};\n\n```\n\n
36
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
3,121
11
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n(1) Start by sorting the input vector in ascending order. This step allows us to utilize the binary search algorithm efficiently.\n(2) For each element num in the sorted vector, calculate its complement complement by subtracting it from the target value. Then, perform a binary search on the sorted vector to find complement.\n(3) If complement is found in the sorted vector and is not the same as num, then we have found a valid pair. Return the indices of num and complement in the original unsorted vector.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBinary Search\n# Complexity\n- Time complexity: O(logN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n vector<int> sortedNums = nums;\n sort(sortedNums.begin(), sortedNums.end());\n \n int left = 0;\n int right = sortedNums.size() - 1;\n \n while (left < right) {\n int sum = sortedNums[left] + sortedNums[right];\n \n if (sum == target) {\n break;\n } else if (sum < target) {\n left++;\n } else {\n right--;\n }\n }\n \n vector<int> result;\n for (int i = 0; i < nums.size(); i++) {\n if (nums[i] == sortedNums[left] || nums[i] == sortedNums[right]) {\n result.push_back(i);\n }\n }\n \n return result;\n }\n};\n```
37
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
27,983
117
# Complexity\n- Time complexity : $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```JAVA []\nclass Solution {\n public int[] twoSum(int[] A, int k) {\n HashMap<Integer, Integer> map = new HashMap<>();\n for(int i = 0, a;; i++){\n if(map.containsKey(A[i]))\n return new int[]{i, map.get(A[i])};\n map.put(k - A[i], i);\n }\n }\n}\n```\n```C []\nint* twoSum(int* nums, int N, int target, int* returnSize){\n int *arr = malloc(2*sizeof(int));\n *returnSize = 2;\n for(int i=0; i < N-1; i++){\n for(int j=i+1; j < N; j++){\n if(nums[i] + nums[j] == target){\n arr[0] = i; arr[1] = j;\n return arr;\n }\n }\n }\n return arr;\n}\n```\n>>> ## Upvote\uD83D\uDC4D if you find helpful\n
39
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
1,179
6
# Intuition\nBasically, Here instead of using an extra loop, we will use the HashMap to check if the other element i.e. target-(selected element) exists. Thus we can trim down the time complexity of the problem.\n\nAnd for the second variant, we will store the element along will its index in the HashMap. Thus we can easily retrieve the index of the other element i.e. target-(selected element) without iterating the array.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe steps are as follows:\n\n1) We will select the element of the array one by one using a loop(say i).\n\n2) Then we will check if the other required element(i.e. target-arr[i]) exists in the hashMap.\n\n If that element exists, then we will return \u201CYES\u201D for the first variant or we will return the current index i.e. i, and the index of the element found using map i.e. mp[target-arr[i]].\n\n If that element does not exist, then we will just store the current element in the hashMap along with its index. Because in the future, the current element might be a part of our answer.\n\n3) Finally, if we are out of the loop, that means there is no such pair whose sum is equal to the target. In this case, we will return either \u201CNO\u201D or {-1, -1} as per the variant of the question.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N) as we use the map data structure.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n int ans[] = new int [2];\n ans[0] = ans[1] = -1;\n HashMap<Integer , Integer>mapp = new HashMap<>();\n for(int i =0 ; i<nums.length ; i++){\n int G = nums[i];\n int R = target - G ;\n if(mapp.containsKey(R)){\n ans[0] = i;\n ans[1] = mapp.get(R);\n\n return ans;\n }\n\n\n mapp.put(nums[i],i);\n }\n return ans;\n }\n}\n```\n\nYour 1 upvote will make me happy...\n\n
40
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
50,350
70
# Intuition\nMethod 1: A brute-force solution to find two numbers in the nums list that add up to the target value.\n\nMethod 2: By list concept\n\nMethod 3: By Dictionary (more efficient solution)\n# Approach\nMethod 1: \nThe code uses nested loops to iterate over each pair of numbers in the nums list. The outer loop runs from 0 to len(nums)-1, and the inner loop runs from i+1 to len(nums)-1, where i is the current index of the outer loop. Within the nested loops, constant time operations are performed, such as checking if the sum of two numbers equals the target, appending indices to the a list, and using break and continue statements.\nTherefore, the overall time complexity of the code is O(n^2) due to the nested loops.\n\nMethod 2: \nThe code uses one loop to iterate over the number and subtract from target and if that subtracted number is present in list then return the index of both number. \n(here if condition of a==i means that possibly the target is 10 and present number in list might be [5,5] but it will return the same index so we need to skip)\n\nMethod 3: \nThe dictionary will help us to find the complement of each number more efficiently. In Method 2, Change the loop variable from i to num using the enumerate() function. This allows us to directly access the numbers from the nums list instead of using indexing.\nReplaced the variable p with complement to improve code readability.\nReplaced if p in nums with if complement in num_dict. This change allows us to check if the complement exists in the num_dict dictionary, which provides a more efficient lookup compared to the in operator on a list.\nModified the return statement to return [num_dict[complement], i] instead of i, a. This returns the indices of the two numbers that add up to the target, as required.\n\n\n# Complexity\n- Time complexity:\n\nMethod 1: \nO(n^2) due to nested loops\n\nMethod 2: \nO(n^2) because the the code uses a single loop that iterates over each element in the nums list which takes O(n) and index() method is called within the loop which takes O(n) time in the worst case to call the index of element.\n\nMethod 3: \n**O(n)** The use of the dictionary (num_dict) allows for efficient lookup of complements in constant time, improving the overall time complexity to O(n) compared to the previous methods with a time complexity of O(n^2) when using the brute force and index() method.\n\n\n- Space complexity:\nthe space complexity of the code is O(1) in all 3 methods.\n\n$$KINDLY$$ $$UPVOTE$$\n# Code\n\nMethod 1: \n```\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n a=[]\n for i in range(len(nums)):\n for j in range(i+1,len(nums)):\n if (nums[i]+nums[j]==target):\n a.append(i)\n a.append(j)\n break \n return a\n```\nMethod 2:\n```\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n a=0\n for i in range(len(nums)):\n p = target-nums[i]\n if p in nums:\n a=nums.index(p)\n if a==i:\n continue\n break\n return i,a\n```\nMethod 3:\n```\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n num_dict = {}\n for i, num in enumerate(nums):\n complement = target - num\n if complement in num_dict:\n return [num_dict[complement], i]\n num_dict[num] = i\n return []\n```
41
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
9,736
99
# First solution using Brute Force\n\n## Approach\n\nThe approach used in this solution is a brute force approach which involves iterating through each element of the array and checking if there is another element in the array that can be added to it to get the target value.\n\nThe function starts by getting the length of the input array. It then iterates through each element of the array using a nested loop. The outer loop iterates through the array from the first element to the second last element. The inner loop iterates through the array from the next element after the current outer loop index to the last element of the array.\n\nFor each iteration of the inner loop, the function checks if the sum of the current element and the element pointed to by the inner loop index is equal to the target value. If it is, the function returns an array of the two indices.\n\nIf no two elements in the array add up to the target value, the function returns an empty array.\n\n## Complexity\n\nAlthough this approach is simple and easy to understand, it has a *time complexity* of $$O(n^2)$$ which is not very efficient for large input arrays.\n\nThe *space complexity* of the function is $$O(1)$$.\n\n## Code\n```swift\nclass Solution {\n func twoSum(_ nums: [Int], _ target: Int) -> [Int] {\n let n = nums.count\n\n for i in 0 ..< n {\n for j in i + 1 ..< n {\n if nums[i] + nums[j] == target {\n return [i, j]\n }\n }\n }\n \n return []\n }\n}\n```\n\n---\n\n# Second solution using Dictionary\n\n## Approach\n\nThis approach to solving the problem uses a dictionary to keep track of the difference between the target and each element in the input array. \n\nThe function first initializes an empty dictionary called `dict`. \n\nThen, it loops through the array using the `enumerated()` method to get both the `index` and `value` of each element in the array. For each element, it checks if the difference between the `target` and the element is already in the dictionary. If it is, that means the current element plus the element at the index in the dictionary adds up to the `target`, so it returns the indices of those two elements. If the difference is not in the dictionary, it adds the difference as a key and the `index` as a value to the dictionary. \n\nIf the loop is completed and no two elements in the array add up to the target, the function returns an empty array. \n\n## Complexity\n\nOverall, this approach has a time complexity of $$O(n)$$ because it only needs to loop through the array once, and a space complexity of $$O(n)$$ because it needs to store the dictionary.\n\n## Code\n```swift\nclass Solution {\n func twoSum(_ nums: [Int], _ target: Int) -> [Int] {\n var dict = [Int: Int]()\n \n for (index, value) in nums.enumerated() {\n if let addent = dict[value] {\n return [addent, index]\n } else {\n dict[target - value] = index\n }\n }\n \n return []\n }\n}\n```\n\n---\n\n# Third solution using Two Pointer\n\n## Approach\n\nThe approach used in this solution is a two-pointer approach. The given array of integers `nums` is first sorted in ascending order in the line `let sortedNums = nums.sorted()`.\n\nAfter sorting, two pointers `left` and `right` are initialized at the beginning and end of the sorted array respectively. The pointers are then moved inward from both ends towards the middle of the array while checking whether the sum of the values at these pointers is equal to the target value.\n\nIf the sum of the values at the `left` and `right` pointers is equal to the `target` value, the indices of these values in the initial unsorted array are returned. If the sum is less than the `target` value, the `left` pointer is moved one step to the `right`. If the sum is greater than the `target` value, the `right` pointer is moved one step to the `left`.\n\nThis process of incrementing and decrementing the pointers continues until the sum of the values at the pointers is equal to the `target` value, or the pointers meet in the middle and there are no more values to check.\n\n## Complexity\n\nThe time complexity of this approach is $$O(n^2)$$.\n\nThe space complexity is $$O(n)$$ due to the creation of a new sorted array.\n\n## Code\n```\nclass Solution {\n func twoSum(_ nums: [Int], _ target: Int) -> [Int] {\n let sortedNums = nums.sorted()\n var left = 0\n var right = nums.count - 1\n\n while left < right {\n let sum = sortedNums[left] + sortedNums[right]\n if sum == target {\n if let index1 = nums.firstIndex(of: sortedNums[left]),\n let index2 = nums.lastIndex(of: sortedNums[right]) {\n return [index1, index2]\n }\n } else if sum < target {\n left += 1\n } else {\n right -= 1\n }\n }\n\n return []\n }\n}\n```\n\n# Upvote ^^\n\n![upvote.png]()\n\n\n
43
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
12,802
36
# Pair Approach:\n\n---\n\n\n# Intuition\nCreating a pair then sort it and using two pointer. **Approach understood by example.**\n\n# Approach\nI provide the approach with a test cases. The test case is as follows --->>>\n\n**Test Case 1:**\n[2,9,7,5] and target = 9.\n1. Making a vector of pair [[2,0], [9,1], [7,2], [5,3]].\n2. Now sort it and the pair becomes --- [[2,0], [5,1], [7,2], [9,3]].\n3. Now applying two pointer on it.\n\n1. Here low is set to 0 and high is set to 3\n2. Now sum = 2+9 = 11 which is grater than target 9, sow high pointer will be decreased.\n3. Now sum = 2+7 = 9 == target.\n4. So we push index of 2 and 7 to the ans vector and return it.\n# Complexity\n- Time complexity:\n**O(nlogn)**\n\n- Space complexity:\n**O(n)**\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n \n vector<pair<int, int>> v;\n vector<int> v2;\n pair<int, int> p;\n for(int i=0; i<nums.size(); i++){\n p.first = nums[i];\n p.second = i;\n v.push_back(p);\n }\n sort(v.begin(), v.end());\n auto it = v.begin(), it2 = v.end();\n it2 --;\n while(it < it2){\n int sum = it->first + it2->first;\n if(sum == target){\n v2.push_back(it->second);\n v2.push_back(it2->second);\n return v2;\n }\n else if(sum < target)\n it ++;\n else \n it2 --;\n }\n \n return v2;\n }\n};\n```\n\n\n\n\n# Map Approach:\n\n---\n\n# Intuition\nCreating a map and searching through it. **Approach understood by example.**\n\n# Approach\nI provide the approach with two test cases. If approach of test case 1 can\'t understood by you then see approach 2 also. The test cases are as follows --->>>\n\n**Test Case 1:**\n[2,5,7,9] and target = 9.\n1. First we insert the first element of the array i.e. 2 into the map.\n2. Now the map contain [2,0], where 2 is key and 0 is index.\n3. Now we iterate the for loop from 1. So nums[i] i.e. nums[1]=5. To make the some 9 we need the element, 9-5 i.e. 4.\n4. So we store in temp i.e. temp = target-nums[i] i.e. 4.\n5. Now checking that is 4 present in the map. If present then push the index of it to the vector i.e. v.push_back(mp[temp]) and v.push_back(i). But the if condition does not satisfy here.\n6. Else if the temp value not present in the map insert the current element with it index into the map i.e. the else statement is executed here. So after this the map will contain [[2,0], [5,1]].\n7. For second ieration of the loop the element is 7 and to make sum 9 we need the element 9-7=2. Now searching that if two presented in the map and the ans is yes so if condition executed and pushing the index of element 2 to the vector and the inde of 7 also and return it.\n\n**Test Case 2:**\n[3,3] and target = 6.\n1. First we insert the first element of the array i.e. 3 into the map.\n2. Now the map contain [3,0].\n3. Now we iterate the for loop from 1. So nums[i] i.e. nums[1]=3. To make the some 6 we need the element, 6-3 i.e. 3.\n4. So we store in temp i.e. temp = target-nums[i] i.e. 3.\n5. Now checking that is 3 present in the map. Here it present so push the index of it to the vector i.e. v.push_back(mp[temp]) which will push 0 and v.push_back(i) which will push the current index 1.\n# Complexity\n- Time complexity:\n**O(n)**\n\n- Space complexity:\n**O(n)**\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int,int> mp;\n vector<int> v;\n mp[nums[0]] = 0;\n for(int i=1; i<nums.size(); i++){\n int temp = target-nums[i];\n if(mp.find(temp) != mp.end()){\n v.push_back(mp[temp]);\n v.push_back(i);\n return v;\n }\n else\n mp[nums[i]] = i;\n }\n return v;\n }\n};\n```
44
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
498,117
1,307
Hi, this is my accepted JAVA solution. It only go through the list once. It\'s shorter and easier to understand. Hope this can help someone. Please tell me if you know how to make this better :)\n\n\n public int[] twoSum(int[] numbers, int target) {\n int[] result = new int[2];\n Map<Integer, Integer> map = new HashMap<Integer, Integer>();\n for (int i = 0; i < numbers.length; i++) {\n if (map.containsKey(target - numbers[i])) {\n result[1] = i;\n result[0] = map.get(target - numbers[i]);\n return result;\n }\n map.put(numbers[i], i);\n }\n return result;\n }
45
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
2,045
10
# Intuition\n1. The problem requires finding two numbers in the given vector that add up to a target value.\n\n1. By using an unordered map, we can efficiently store the elements of the vector along with their indices for quick access.\n\n1. The idea is to iterate through the vector and for each element, calculate the required number needed to reach the target value.\n\n1. We check if the required number is already present in the map. If it is, it means we have found a pair of numbers that add up to the target.\n\n1. If the required number is not found in the map, we store the current element and its index in the map.\n\n1. This way, as we iterate through the vector, we can quickly check if the required number for each element is present in the map.\n\n1. Once we find a pair of numbers that add up to the target, we return their indices.\n\n1. If we iterate through the entire vector without finding a solution, we return {-1, -1} to indicate that no valid pair of numbers was found.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int, int> mp; // Map to store number-index pairs\n vector<int> ans; // Vector to store the indices of the two numbers\n \n for (int i = 0; i < nums.size(); i++) {\n int required = target - nums[i]; // Calculate the number required to achieve the target\n \n // Check if the required number is already in the map\n if (mp.find(required) != mp.end()) {\n ans.push_back(i); // Index of the current number\n ans.push_back(mp[required]); // Index of the required number\n return ans; // Return the indices and exit the loop\n }\n \n mp[nums[i]] = i; // Add the number-index pair to the map\n }\n \n return {-1, -1}; // Return {-1, -1} if no solution is found\n }\n};\n```
49
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
54
7
\n# Code\n```\nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n \n Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();\n \n for (int i = 0; i < nums.length; i++) {\n if (indexMap.containsKey(target - nums[i])) {\n return new int[]{indexMap.get(target - nums[i]), i};\n }\n indexMap.put(nums[i], i);\n }\n \n return null;\n }\n}\n```
50
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
795
5
# Intuition\nYou can use Brute Force to sovle this ques in O(n^2) but the task was to reduce the time complexity .\n\n# Approach\n1--> If we sort this array and use 2 pointer to find sum of the target then the time complexity can be reducted .\n\n2--> Put s on 0 and e on n-1 then is nums[s]+nums[e]>target ; e-- and if it is less than target than s++; eventually you fill find those numbers .\n\n2--> Create a copy of origanl vector and find those number in it for index value .\n\n3--> Included a variable p so that it does not returns the same index again for same numbers .\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int indexFinder(vector<int> v,int n,int &p){\n for(int i=0; i<v.size(); i++){\n if(v[i]==n && p!=i){\n p=i;\n return i;\n }\n }\n return -1;\n }\n\n vector<int> twoSum(vector<int>& nums, int target) {\n vector<int> ans;\n vector<int> orignal = nums;\n sort(nums.begin(),nums.end());\n int s=0;\n int e=nums.size()-1;\n while(s<e){\n if(nums[s]+nums[e]==target){\n break;\n }\n else if(nums[s]+nums[e]>target){\n e--;\n }\n else{\n s++;\n }\n }\n int i=-2;\n ans.push_back(indexFinder(orignal,nums[s],i));\n ans.push_back(indexFinder(orignal,nums[e],i));\n return ans;\n }\n};\n```
51
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
5,209
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n for(int i=0;i<nums.length;i++){\n for(int j=i+1;j<nums.length;j++){\n if(nums[i]+nums[j]==target){\n return new int[]{i,j};\n }\n }\n }\n return new int[]{}; }\n}\n```
52
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
399,175
1,040
The key to the problem is that there is ALWAYS only 1 pair of numbers that satisfy the condition of adding together to be the target value. \nWe can assume that for all the numbers in the list (**x1, x2, ... xn**) that there exists a pair such that **xa + xb = target** \nTo solve this with a single pass of the list we can change the equation above to **xa = target - xb** and since we know the target as long as we maintain a record of all previous values in the list we can compare the current value (**xa**) to it\'s ONLY pair, if it exists, in record of all previous values (**xb**)\n\nTo keep a record of the previous values and their indices I have used a dictionary. Commonly known as a map in other languages. This allows me to record each previous number in the dictionary alongside the indice as a key value pair (target-number, indice). \n```\nclass Solution(object):\n\tdef twoSum(self, nums, target):\n\t\tbuffer_dictionary = {}\n\t\tfor i in rangenums.__len()):\n\t\t\tif nums[i] in buffer_dictionary:\n\t\t\t\treturn [buffer_dictionary[nums[i]], i] #if a number shows up in the dictionary already that means the \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t#necesarry pair has been iterated on previously\n\t\t\telse: # else is entirely optional\n\t\t\t\tbuffer_dictionary[target - nums[i]] = i \n\t\t\t\t# we insert the required number to pair with should it exist later in the list of numbers\n```
53
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
36,970
290
**If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries or some improvements please feel free to comment and share your views.**\n```\n//Ist Approach\n vector<int> twoSum(vector<int>& nums, int target) {\n vector<pair<int,int>> v;\n for(int i=0;i<nums.size();i++)\n v.push_back({nums[i],i});\n sort(v.begin(),v.end());\n int i=0;\n int j=v.size()-1;\n int idx1=0;\n int idx2=0;\n while(i<j)\n {\n if(v[i].first+v[j].first==target)\n {\n idx1=v[i].second;\n idx2=v[j].second;\n break;\n \n }\n if(v[i].first+v[j].first<target)\n i++;\n if(v[i].first+v[j].first>target)\n j--;\n }\n return {idx1,idx2};\n }\n//Time Complexity:O(nlogn)\n//Time Complexity:O(n)\n\n//Second Approach\n\n vector<int> twoSum(vector<int>& nums, int target) {\n vector<int> v;\n unordered_map<int,int> m;\n for(int i=0;i<nums.size();i++)\n {\n if(m.find(target-nums[i])!=m.end())\n {\n v.push_back(m[target-nums[i]]);\n v.push_back(i);\n return v;\n }\n else\n m[nums[i]]=i;\n }\n return v;\n }\n\n//Time Complexity:O(n)\n//Space Complexity:O(n)\n\n//Third Approach\nvector<int> twoSum(vector<int>& nums, int target) {\n vector<int> index;\n int size=nums.size();\n for(int i=0;i<size;i++)\n {\n int k=target-nums[i];\n for(int j=i+1;j<size;j++)\n {\n if(nums[j]==k)\n {\n index.push_back(i);\n index.push_back(j);\n break;\n }\n }\n if(index.size()==2)\n break;\n }\n return index;\n }\n\t//Time Complexity: O(n^2)\n```
54
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
30,026
302
**\u2714\uFE0F Solution 1: HashMap**\n- We need to find 2 numbers `a`, `b` so that `a + b = target`.\n- We need a HashMap datastructure to store elements in the past, let name it `seen`. \n- The idea is that we iterate `b` as each element in `nums`, we check if we found `a` (where `a = target - b`) in the past.\n\t- If `a` exists in `seen` then we already found 2 numbers `a` and `b`, so that `a + b = target`, just output their indices.\n\t- Else add `b` to the `seen`.\n<iframe src="" frameBorder="0" width="100%" height="280"></iframe>\n\n**Complexity**\n- Time: `O(N)`, where `N <= 10^4` is number of elements in the array `nums`.\n- Space: `O(N)`\n\n---\n\n**\u2714\uFE0F Solution 2: Sort then Two Pointers**\n- Since this problem require to output **pair of indices** instead of **pair of values**, so we need an array, let say `arr` to store their value with their respective indices. \n- Sort array `arr` in increasing order by their values.\n- Then use two pointer, left point to first element, right point to last element.\n\n<iframe src="" frameBorder="0" width="100%" height="450"></iframe>\n\n**Complexity**\n- Time: `O(N * logN)`, where `N <= 10^4` is number of elements in the array `nums`.\n- Space: `O(N)`
57
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
126,066
114
58
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
2,757
7
# Intuition\nThe Two Sum issue requires us to discover two integers in an array that add up to a certain goal value. We must return the indices of these two integers.\n\n# Approach\nA hash table (unordered_map in C++) is a more efficient technique. We may cycle through the array once and verify if the goal minus the current element exists in the hash table for each element. If it does, we\'ve discovered a legitimate pair of numbers. If not, the current element is added to the hash table.\n\n\n\n\n\n**Approach using a hash table**:\n\n1Make an empty hash table to to store elements and their indices.\n\n2.Iterate through the array from left to right.\n\n3.For each element nums[i], calculate the complement by subtracting it from the target: complement = target - nums[i].\n\n4.Determine whether the complement exists in the hash table. If it does, we have found a solution.\n\n5.If the complement does not exist in the hash table, add the current element nums[i] to the hash table with its index as the value.\n\n6.Repeat steps 3-5 until a solution is found or reach the end of the array.\n\n7.Return an empty array or an acceptable indication if no solution is discovered.\n\n\n\nThis method has a time complexity of **O(n)** because the average lookup time in a hash table is constant. By iterating through the array only once, we can efficiently solve the Two Sum problem using this approach.\n\n\n\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int, int> numMap;\n int n = nums.size();\n\n for (int i = 0; i < n; i++) {\n int complement = target - nums[i];\n if (numMap.count(complement)) {\n return {numMap[complement], i};\n }\n numMap[nums[i]] = i;\n }\n\n return {}; \n }\n};\n```\n\n**If you found my solution to be useful, I would greatly appreciate your upvote, as it would encourage me to continue sharing more solutions.**\n\n\n\n\n
59
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
3,199
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo find the pair of numbers that sum up to the given target, we can try to find the $$complement$$ of each number and if it is present in the array, we can return it as our answer. \n\nHere, the term \'complement\' refers to the following equation-\n\nLet \'n\' be an element in the given array.\nComplement of n = target-n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTraverse through the given array and try to find $$complement$$ of it in the hashtable. If found, return the indices of both the numbers. Else, add the element and its index to the hashmap and repeat the process for the subsequent elements in the array.\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n**NOTE:** The space complexity for the above question can be reduced by sorting the array and using two-pointer approach. However, this will be at the cost of the time complexity as sorting the given array will bump it upto $$O(NlogN)$$.\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int, int> numsMap;\n\n for(int i=0;i<nums.size();i++){\n auto it=numsMap.find(target-nums[i]);\n\n if(it!=numsMap.end()) return {i, it->second};\n numsMap.insert({nums[i], i});\n }\n return {-1, -1};\n }\n};\n```
61
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
9,575
27
# Approach\nThis code defines a Python class called `Solution` with a method named `twoSum`. The purpose of this method is to find two numbers in a list (`nums`) that add up to a specific target number (`target`). Here\'s a simple explanation of how it works:\n\n1. Create an empty dictionary called `numsList` to store numbers from the list `nums` and their corresponding indices.\n \n2. Loop through each element (`n`) in the `nums` list along with its index (`i`).\n\n3. Calculate the difference (`diff`) between the `target` and the current number `n`. This difference represents the value we need to find in the list in order to reach the target.\n\n4. Check if the `diff` is already in the `numsList` dictionary. If it is, it means we have found a pair of numbers whose sum equals the target. In this case, return a list containing the indices of those two numbers: `[numsList[diff], i]`. This pair of indices will identify the two numbers in the original list that add up to the target.\n\n5. If the `diff` is not in the `numsList` dictionary, it means we haven\'t seen this number before. So, we add the current number `n` to the `numsList` dictionary, with its index `i` as the associated value. This allows us to look up this number later if we encounter its complement in the list.\n\n6. Repeat steps 3 to 5 for each number in the `nums` list until a pair of numbers that adds up to the `target` is found, at which point the function returns the indices of those numbers.\n\nIn summary, this code efficiently finds a pair of numbers in the `nums` list that add up to the given `target`, using a dictionary to keep track of the numbers seen so far and their indices.\n\n# Code\n```\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n numsList = {}\n for i,n in enumerate(nums):\n diff = target-n\n if diff in numsList:\n return [numsList[diff], i]\n else:\n numsList[n] = i\n```\n\n**Please upvote if you like the solution.\nHappy Coding! \uD83D\uDE0A**
62
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
4,568
7
\nit\'s easy.\n# Code\n```\nclass Solution {\n public int[] twoSum(int[] nums, int target) {\n for(int i=0;i<nums.length;i++){\n for(int j=i+1;j<nums.length;j++){\n if(nums[j]==target-nums[i]){\n return new int[]{i,j};\n }\n }\n }\n return null;\n }\n}\n```
63
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
7,372
29
```\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n dict={}\n for index, ele in enumerate(nums):\n if target- ele in dict:\n return dict[target- ele], index\n dict[ele]= index\n```
70
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
5,406
7
**//Brute force method**\n\n# Complexity\n- Time complexity:O(n^2)\n- Space complexity:O(1)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n for(int i = 0;i<nums.size();i++){\n for(int j = i+1;j<nums.size();j++){\n if(nums[i]+nums[j]==target){\n //Here we can return like this without creating new vector for answer\n return {i,j}; \n }\n }\n }\n return {};\n }\n};\n```
71
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
575
5
\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n* An **unordered map** `mp` is created to store the elements of the array a and their indices.\n\n* For loop is used to iterate over each element in the array a.\n\n* For each element, the difference between the target value and the element is calculated and stored in the variable `diff`.\n\n* If the difference `diff` is** not present** in the map `mp`, the element **a[i]** is added to the map with its index as the value.\n\n* If the difference `diff` is present in the map `mp`, the indices of the two numbers that add up to the target are returned as a vector.\n\nIf no such pair is found in the array, the function returns the vector `{-1,-1}`.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& a , int target) {\n\n int n=a.size();\n unordered_map<int,int>mp;\n\n for(int i=0;i<n;i++){\n int diff=target-a[i];\n if(mp.find(diff)==mp.end()) mp[a[i]]=i;\n else return {mp[diff],i};\n }\n return {-1,-1};\n }\n};\n```
74
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
768
5
\n~~~\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n for i in range(len(nums)):\n j = target - nums[i]\n if j in nums and nums.index(j) != i:\n return [i,nums.index(j)]
75
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
26,505
67
```\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n dict={}\n for index, ele in enumerate(nums):\n if target- ele in dict:\n return dict[target- ele], index\n dict[ele]= index\n```
76
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
3,408
12
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code 1.1\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n\n unordered_map<int, int> mp;\n\n for(int i = 0; i < nums.size(); i++){\n if(mp.count(target - nums[i]))\n return {mp[target - nums[i]], i};\n else\n mp[nums[i]] = i;\n }\n return {};\n } \n};\n```\n# Code 1.2\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int, int> mp;\n for(int i = 0; i < nums.size(); i++){\n if(mp.find(target - nums[i]) == mp.end())\n mp[nums[i]] = i;\n else\n return {mp[target - nums[i]], i};\n }\n return {};\n } \n};\n```\n# Code 2\n```\nclass Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n int l=0;\n int r=1;\n while(l<nums.size()-1){\n while(r<nums.size()){\n if(nums[l]+nums[r] == target){\n return {l,r};\n }\n r++;\n }\n l++;\n r=l+1;\n }\n return {};\n } \n};\n```\n![4i5ri4f9.png]()\n
77
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
25,660
91
\n\nInstead of checking every single combination of pairs, the key realization is that for each number in the array, there is only **one** number that can be added to it to reach the target.\n\nWe combine this with a hash table, which can look up values in constant time, to keep track of array elements and its indices as we traverse it. For each array element **x**, we calculate **target - x** and check if we\'ve encountered it in the array before.\n\nIn the worst case, the array will only have to be traversed once, resulting in an O(n) solution.\n\n# Code\n```\nclass Solution(object):\n def twoSum(self, nums, target):\n seen = {}\n for i in range(len(nums)):\n diff = target - nums[i]\n if diff in seen:\n return [seen[diff], i]\n else:\n seen[nums[i]] = i\n```
78
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
3,497
7
* class Solution {\npublic:\n vector<int> twoSum(vector<int>& nums, int target) {\n unordered_map<int, int> seen;\n for (int i = 0; i < nums.size(); ++i) {\n int b = nums[i], a = target - b;\n if (seen.count(a)) return {seen[a], i}; // Found pair of (a, b), so that a + b = target\n seen[b] = i;\n }\n return {};\n }\n};
81
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
508
10
```\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\n```
87
Two Sum
two-sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.
Array,Hash Table
Easy
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
111
5
import java.util.Scanner;\n class Solution {\n public static int[] twoSum(int[] nums, int target) {\n int addOfIndex;\n // System.out.println("Number of elements in nums :"+nums.length);\n for (int i = 0; i < nums.length; i++) {\n for (int j = i + 1; j < nums.length; j++) {\n int[] add = new int[2];\n addOfIndex = nums[i] + nums[j];\n if (addOfIndex == target) {\n add[0] = i;\n add[1] = j;\n return add;\n }\n }\n }\n\n return null;\n }\n public static void main(String []args){\n Scanner sc=new Scanner(System.in);\n // Solution s1=new Solution;\n System.out.println("Enter number of element :");\n int n=sc.nextInt();\n System.out.println("Enter your elements :");\n int [] nums=new int[n];\n for(int k=0; k<n; k++){\n nums[k]=sc.nextInt();\n }\n System.out.println("Enter your target :");\n int target= sc.nextInt();\n int[] ret = new Solution().twoSum(nums, target);\n// System.out.println(ret);\n System.out.println("["+ret[0]+","+ret[1]+"]");\n }\n }\n\n
88
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
176,104
921
# Intuition:\nThe Intuition is to iterate through two linked lists representing non-negative integers in reverse order, starting from the least significant digit. It performs digit-wise addition along with a carry value and constructs a new linked list to represent the sum. The process continues until both input lists and the carry value are exhausted. The resulting linked list represents the sum of the input numbers in the correct order.\n\n# Explanation: \n1. Create a placeholder node called `dummyHead` with a value of 0. This node will hold the resulting linked list.\n2. Initialize a pointer called `tail` and set it to `dummyHead`. This pointer will keep track of the last node in the result list.\n3. Initialize a variable called `carry` to 0. This variable will store the carry value during addition.\n4. Start a loop that continues until there are no more digits in both input lists (`l1` and `l2`) and there is no remaining carry value.\n5. Inside the loop:\n - Check if there is a digit in the current node of `l1`. If it exists, assign its value to a variable called `digit1`. Otherwise, set `digit1` to 0.\n - Check if there is a digit in the current node of `l2`. If it exists, assign its value to a variable called `digit2`. Otherwise, set `digit2` to 0.\n - Add the current digits from `l1` and `l2`, along with the carry value from the previous iteration, and store the sum in a variable called `sum`.\n - Calculate the unit digit of `sum` by taking the modulus (`%`) of `sum` by 10. This digit will be placed in a new node for the result.\n - Update the `carry` variable by dividing `sum` by 10 and taking the integer division (`/`) part. This gives us the carry value for the next iteration.\n - Create a new node with the calculated digit as its value.\n - Attach the new node to the `tail` node of the result list.\n - Move the `tail` pointer to the newly added node.\n - Move to the next nodes in both `l1` and `l2`, if they exist. If either list is exhausted, set the corresponding pointer to `nullptr`.\n6. After the loop, obtain the actual result list by skipping the `dummyHead` node.\n7. Delete the `dummyHead` node.\n8. Return the resulting list.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n ListNode* dummyHead = new ListNode(0);\n ListNode* tail = dummyHead;\n int carry = 0;\n\n while (l1 != nullptr || l2 != nullptr || carry != 0) {\n int digit1 = (l1 != nullptr) ? l1->val : 0;\n int digit2 = (l2 != nullptr) ? l2->val : 0;\n\n int sum = digit1 + digit2 + carry;\n int digit = sum % 10;\n carry = sum / 10;\n\n ListNode* newNode = new ListNode(digit);\n tail->next = newNode;\n tail = tail->next;\n\n l1 = (l1 != nullptr) ? l1->next : nullptr;\n l2 = (l2 != nullptr) ? l2->next : nullptr;\n }\n\n ListNode* result = dummyHead->next;\n delete dummyHead;\n return result;\n }\n};\n```\n```Java []\nclass Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode dummyHead = new ListNode(0);\n ListNode tail = dummyHead;\n int carry = 0;\n\n while (l1 != null || l2 != null || carry != 0) {\n int digit1 = (l1 != null) ? l1.val : 0;\n int digit2 = (l2 != null) ? l2.val : 0;\n\n int sum = digit1 + digit2 + carry;\n int digit = sum % 10;\n carry = sum / 10;\n\n ListNode newNode = new ListNode(digit);\n tail.next = newNode;\n tail = tail.next;\n\n l1 = (l1 != null) ? l1.next : null;\n l2 = (l2 != null) ? l2.next : null;\n }\n\n ListNode result = dummyHead.next;\n dummyHead.next = null;\n return result;\n }\n}\n```\n```Python3 []\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummyHead = ListNode(0)\n tail = dummyHead\n carry = 0\n\n while l1 is not None or l2 is not None or carry != 0:\n digit1 = l1.val if l1 is not None else 0\n digit2 = l2.val if l2 is not None else 0\n\n sum = digit1 + digit2 + carry\n digit = sum % 10\n carry = sum // 10\n\n newNode = ListNode(digit)\n tail.next = newNode\n tail = tail.next\n\n l1 = l1.next if l1 is not None else None\n l2 = l2.next if l2 is not None else None\n\n result = dummyHead.next\n dummyHead.next = None\n return result\n```\n\n![CUTE_CAT.png]()\n\n**If you are a beginner solve these problems which makes concepts clear for future coding:**\n1. [Two Sum]()\n2. [Roman to Integer]()\n3. [Palindrome Number]()\n4. [Maximum Subarray]()\n5. [Remove Element]()\n6. [Contains Duplicate]()\n7. [Add Two Numbers]()\n8. [Majority Element]()\n9. [Remove Duplicates from Sorted Array]()\n10. **Practice them in a row for better understanding and please Upvote the post for more questions.**\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**
100
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
142,363
1,237
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(max(l1,l2)).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n ListNode* dummy=new ListNode();\n ListNode* temp=dummy;\n int carry=0;\n while(l1!=NULL || l2!=NULL || carry){\n int sum=0;\n if(l1!=NULL){\n sum+=l1->val;\n l1=l1->next;\n }\n if(l2!=NULL){\n sum+=l2->val;\n l2=l2->next;\n }\n sum+=carry;\n carry=sum/10;\n ListNode* newnode=new ListNode(sum%10);\n temp->next=newnode;\n temp=temp->next;\n }\n return dummy->next;\n }\n};\nif it helps plzz dont\'t forget to upvote it :)\n```
101
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
436
6
\n\nFirst we create a new ListNode, `head`, which will hold our answer. We then traverse the two lists, and at every node, we add the values together, create a new node with the sum, and link it to `head`. However, the problem is complicated by the need to keep track of <i>carries</i>. Here\'s how we deal with it. After adding two digits together:\n\n- The <i>non-carry</i> part is obtained by doing `total % 10`. By taking the remainder of a number after dividing by 10, we only get what\'s left in the ones place. For example, if the total is 15, then 15 % 10 = 5, so we create a new ListNode with value 5 and link it to `head`\n- The <i>carry</i> is obtained by doing `total // 10` (floor division by 10). By dividing by 10 and rounding down, we get the carry value. So 15 // 10 = 1 (1.5 rounded down is 1) so that corresponds to a carry of 1.\n\nWe then keep repeating this until all lists have reached the end AND there are no more carry values. At the end, `head.next`holds the very first node of our answer, so we return `head.next`.\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n head = ListNode()\n current = head\n carry = 0\n while (l1 != None or l2 != None or carry != 0):\n l1_value = l1.val if l1 else 0\n l2_value = l2.val if l2 else 0\n total = l1_value + l2_value + carry\n current.next = ListNode(total % 10)\n carry = total // 10\n # Move list pointers forward\n l1 = l1.next if l1 else None\n l2 = l2.next if l2 else None\n current = current.next\n return head.next\n```
102
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
137,281
638
How\'s going, Ladies n Gentlemen, today we are going to solve one of the coolest problem **Add Two Numbers**\n\nSo, what the problem statement is saying we have given 2 linkedlist we have to add them and get the sum in another linkedlist.\n\nWhat, am saying let\'s understand with an example:-\n**Input**: l1 = [1,2,4,3], l2 = [5,4,6]\n**Output**: [6,6,0,4]\n\n![image]()\n\nNow let\'s create another list in which we will get our sum. So, that list intially we will called as dummy list with any value of your choice present in that. *I\'ll put 0 as we indian has invented that. <^^>*\n\nAnd one more last thing, we\'ll gonna create one pointer and let\'s say i\'ll call it **curr** which is pointing on dummy node and traverse along with it\n\n![image]()\n\nAlright so, here we go ladies n gentlemen, It\'s time to sum up these node value, for that we will create one another variable let\'s called it **sum** and put the sum of **l1 & l2** them into our dummy list. So, we start it from all the way left go to all the way right. Now you will ask, dude what about the carry values we get after sum up.\nWell, hold on i\'m coming on that point don\'t worry.\n\nSo, for that what you have to do is, we will intialize one more variable name **carry** if we found carry of let\'s say 10. First we will modulo it like carry = sum % 10 i.e. carry = 10 % 10 i.e. 0 we will add 0 into our node and after that what we will do is get the carry as carry = sum / 10 i.e. carry = 10 / 10 i.e. 1. Now we are having carry as 1. So, in the next node sum of l1 & l2 we will add carry as well.\n\nFor sum we will use this formula :- **sum = l1 + l2 + carry**\n\nWe did a lot of talk, let\'s understand it visually:-\n* 1st step->\n![image]()\n\n* 2nd Step->\n![image]()\n* 3rd Step->\n![image]()\n\nNow I hope Ladies n Gentlemen, you got the crystal clear idea, what we are doing. So, without any further due ***let\'s code up***\n\n**Java**\n\n```\nclass Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode dummy = new ListNode(0); // creating an dummy list\n ListNode curr = dummy; // intialising an pointer\n int carry = 0; // intialising our carry with 0 intiall\n // while loop will run, until l1 OR l2 not reaches null OR if they both reaches null. But our carry has some value in it. \n\t\t// We will add that as well into our list\n while(l1 != null || l2 != null || carry == 1){\n int sum = 0; // intialising our sum\n if(l1 != null){ // adding l1 to our sum & moving l1\n sum += l1.val;\n l1 = l1.next;\n }\n if(l2 != null){ // adding l2 to our sum & moving l2\n sum += l2.val;\n l2 = l2.next;\n }\n sum += carry; // if we have carry then add it into our sum\n carry = sum/10; // if we get carry, then divide it by 10 to get the carry\n ListNode node = new ListNode(sum % 10); // the value we\'ll get by moduloing it, will become as new node so. add it to our list\n curr.next = node; // curr will point to that new node if we get\n curr = curr.next; // update the current every time\n }\n return dummy.next; // return dummy.next bcz, we don\'t want the value we have consider in it intially!!\n }\n}\n```\n\n**C++**\n```\nclass Solution {\npublic:\n ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n ListNode *dummy = new ListNode(0);\n ListNode *curr = dummy;\n int carry = 0;\n \n while(l1 != NULL || l2 != NULL || carry == 1){\n int sum = 0;\n if(l1 != NULL){\n sum += l1->val;\n l1 = l1->next;\n }\n if(l2 != NULL){\n sum += l2->val;\n l2 = l2->next;\n }\n sum += carry;\n carry = sum/10;\n ListNode *node = new ListNode(sum % 10);\n curr->next = node;\n curr = curr->next;\n }\n return dummy->next;\n }\n};\n```\n\nANALYSIS :-\n* **Time Complexity :-** BigO(max(N, M)) where N is length of l1 & M is length of l2\n\n* **Space Complexity :-** BigO(max(N,M))
104
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
11,697
19
\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n int c=0;\n ListNode head=new ListNode(0);\n ListNode l3=head,p1=l1,p2=l2;\n while(p1!=null||p2!=null){\n if(p1!=null){\n c+=p1.val;\n p1=p1.next;\n }\n if(p2!=null){\n c+=p2.val;\n p2=p2.next;\n }\n l3.next=new ListNode(c%10);\n l3=l3.next;\n c/=10; \n }\n if(c==1){\n l3.next=new ListNode(1);\n \n }\n return head.next;\n }\n}\n```\nUpvotes are encouraging
116
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
121,571
2,158
### Description\nOne of the basic structures in algorithm which can be used to achieve lots of funny algorithms and problems. \n\n### Problems\nThere will be some of the most typical problems in this aspect, which I believe almost covers all the basic techniques that you need to solve a linked list problem.\n\n#### Remove Duplicates from Sorted List\nGiven a sorted linked list, delete all duplicates such that each element appear only once.\n\n> For example,\nGiven 1->1->2, return 1->2.\nGiven 1->1->2->3->3, return 1->2->3.\n\n##### Solution\n\nWe can just solve it like in an array using another index to collect the valid nodes. Here, once I made a serious mistake inserting extra `;` after `while` which directly result in an in-debuggeable situation.\n\n```\nListNode* deleteDuplicates(ListNode* head) {\n if(!head) return head;\n ListNode *t = head, *p = head->next;\n int pre = head->val;\n while(p) {\n if(pre != p->val) {\n t->next = p;\n pre = p->val;\n t = t->next;\n }\n p = p->next;\n }\n t->next = NULL;\n return head;\n}\n```\n#### Remove Duplicates from Sorted List II\nGiven a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.\n\n> For example,\nGiven 1->2->3->3->4->4->5, return 1->2->5.\nGiven 1->1->1->2->3, return 2->3.\n\n##### Solution\n###### Iterative\n```\nListNode* deleteDuplicates(ListNode* head) {\n\tListNode* dummy = new ListNode(0);\n\tdummy->next = head;\n\tListNode* cur = dummy;\n\tint duplicate;\n\twhile (cur->next && cur->next->next) {\n\t\tif (cur->next->val == cur->next->next->val) {\n\t\t\tduplicate = cur->next->val;\n\t\t\twhile (cur->next && cur->next->val == duplicate) \n\t\t\t\tcur->next = cur->next->next;\n\t\t}\n\t\telse cur = cur->next;\n\t}\n\treturn dummy->next;\n}\n```\n###### Recursive\n```\nListNode* deleteDuplicates(ListNode* head) {\n if (!head) return 0;\n if (!head->next) return head;\n int val = head->val;\n ListNode* p = head->next;\n if (p->val != val) { head->next = deleteDuplicates(p); return head;} \n else { \n while (p && p->val == val) p = p->next; \n return deleteDuplicates(p); \n }\n}\n```\n\n#### Palindrome Linked List\nGiven a singly linked list, determine if it is a palindrome. \n\n> Follow up:\nCould you do it in O(n) time and O(1) space?\n\n##### Solution\nConverting the linked list into an array to simplify the checking.\n```\nbool isPalindrome(ListNode* head) {\n vector<int> v;\n while(head) {\n v.push_back(head->val);\n head = head->next;\n }\n for(int i = 0; i < v.size()/2; ++i) {\n if(v[i] != v[v.size()-i-1]) return false;\n }\n return true;\n}\n```\n\nJust do it using linked list\n\n```\nbool isPalindrome(ListNode* head) {\n if(!head || !head->next) return true;\n ListNode *slow = head, *fast = head->next;\n while(fast && fast->next) {//split into two halves while the first half can be one-node longer;\n slow = slow->next;\n fast = fast->next->next;\n }\n fast = slow->next;\n slow->next = NULL;\n ListNode newHead(0); //reverse the second half;\n ListNode *next = NULL, *p = fast;\n while(p) {\n next = p->next;\n p->next = newHead.next;\n newHead.next = p;\n p = next;\n }\n fast = newHead.next; //compare the two lists;\n while(fast) {\n if(fast->val != head->val) return false;\n fast = fast->next;\n head = head->next;\n }\n return fast == NULL;\n}\n```\n\n#### Rotate List\nGiven a list, rotate the list to the right by k places, where k is non-negative.\n\n> For example:\nGiven 1->2->3->4->5->NULL and k = 2,\nreturn 4->5->1->2->3->NULL.\n\n##### Solution\n\n```\nListNode* rotateRight(ListNode* head, int k) {\n if(!head) return head;\n int len = 1;\n ListNode *p = head;\n while(p->next) { len++; p = p->next; }\n p->next = head;\n if(k %= len)\n for(int i = 0; i < len-k; ++i, p=p->next) ; \n ListNode* newHead = p->next;\n p->next = NULL;\n return newHead;\n}\n```\n\n#### Add Two Numbers\nYou are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.\n\n> Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)\nOutput: 7 -> 0 -> 8\n\n##### Solution\n\n###### Iterative \n\n```\nListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n int c = 0;\n ListNode newHead(0);\n ListNode *t = &newHead;\n while(c || l1 || l2) {\n c += (l1? l1->val : 0) + (l2? l2->val : 0);\n t->next = new ListNode(c%10);\n t = t->next;\n c /= 10;\n if(l1) l1 = l1->next;\n if(l2) l2 = l2->next;\n }\n return newHead.next;\n}\n```\n\n###### Recursive\n```\nListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n if(!l1 && !l2) return NULL;\n int c = (l1? l1->val:0) + (l2? l2->val:0);\n ListNode *newHead = new ListNode(c%10), *next = l1? l1->next:NULL;\n c /= 10;\n if(next) next->val += c;\n else if(c) next = new ListNode(c);\n newHead->next = addTwoNumbers(l2? l2->next:NULL, next);\n return newHead;\n}\n```\n\n#### Reverse Linked List II\nReverse a linked list from position m to n. Do it in-place and in one-pass.\n\n> For example:\nGiven 1->2->3->4->5->NULL, m = 2 and n = 4, \nreturn 1->4->3->2->5->NULL.\n\n> Note: Given m, n satisfy the following condition: 1 \u2264 m \u2264 n \u2264 length of list.\n\n##### Solution\n\n```\nListNode* reverseBetween(ListNode* head, int m, int n) {\n ListNode newHead(0);\n newHead.next = head;\n ListNode *pre = &newHead, *cur = head, *next = NULL;\n int i = 1;\n while(i < n) {\n if(i++ < m) { pre = cur; cur = cur->next; }\n else { \n next = cur->next; \n cur->next = cur->next->next; \n next->next = pre->next; \n pre->next = next; \n }\n }\n return newHead.next;\n}\n```\n\n#### Linked List Cycle II\nGiven a linked list, return the node where the cycle begins. If there is no cycle, return null. Note: Do not modify the linked list. \n\n> Follow up:\nCan you solve it without using extra space?\n\n##### Solution\nActually we can just use `set.insert(key).second` to check but it will take up O(n) space which is quite an awful waste, so here we just going to check the circle and then locate it.\n\n- If there is a circle then once the slow meets the fast the first time, there will be a formula as follows: a+b+kl = 2(a+b) -> kl-b = a (a is the length between the head and the start of the circle, b is the steps the slow pointer moves in the circle while l is the length of the circle).\n- After that we can reset the fast and slow down the fast (same speed as the slow using kl-b = a) then once they meet again, the location will be the start of the circle.\n\nAt last we take up constant space to solve this and traverse the linked list twice at most (as for the slow pointer).\n\n```\nListNode *detectCycle(ListNode *head) {\n ListNode *slow = head, *fast = head; \n while(fast && fast->next) {\n slow = slow->next;\n fast = fast->next->next;\n if(slow == fast) break;\n }\n if(slow != fast) return NULL;\n fast = head;\n while(fast && fast->next) {\n if(slow == fast) return slow;\n slow = slow->next;\n fast = fast->next;\n }\n return NULL;\n}\n```\n\n#### Copy List with Random Pointer\n linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. \nReturn a deep copy of the list.\n\n[test]()\n\n##### Solution\n\n\n###### Recursive\n\n```\nclass Solution {\n unordered_map<RandomListNode*, RandomListNode*> cloneMap;\n RandomListNode *helper(RandomListNode* head){\n if(head == NULL) return NULL;\n if(cloneMap.count(head)) return cloneMap[head];\n RandomListNode *cloned = new RandomListNode(head->label);\n cloneMap[head] = cloned; //crucial;\n cloned->next = helper(head->next);\n cloned->random = helper(head->random);\n return cloned;\n }\npublic:\n RandomListNode *copyRandomList(RandomListNode *head) {\n return helper(head);\n } \n};\n```\n\n###### Iterative\n\n```\nRandomListNode *copyRandomList(RandomListNode *head) {\n\tRandomListNode newHead(0), *p = head, *t = NULL;\n\twhile(p) {\n\t\tRandomListNode *cloned = new RandomListNode(p->label);\n\t\tcloned->next = p->next;\n\t\tp->next = cloned;\n\t\tp = cloned->next;\n\t}\n\tp = head;\n\twhile(p && p->next) {\n\t\tif(p->random) p->next->random = p->random->next;\n\t\tp = p->next->next;\n\t}\n\tp = head;\n\tt = &newHead;\n\twhile(p && p->next) {\n\t\tt->next = p->next;\n\t\tp->next = p->next->next;\n\t\tt = t->next;\n\t\tp = p->next;\n\t}\n\tt->next = NULL;\n\treturn newHead.next;\n}\n```\n\n#### Reverse Nodes in k-Group\nGiven a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in the nodes, only nodes itself may be changed. Only constant memory is allowed.\n\n> For example,\nGiven this linked list: 1->2->3->4->5 \nFor k = 2, you should return: 2->1->4->3->5 \nFor k = 3, you should return: 3->2->1->4->5\n\n##### Solution\n\n```\nListNode* reverseKGroup(ListNode* head, int k) {\n\tif(!head || !head->next) return head;\n\tListNode newHead(0);\n\tListNode *pre = &newHead, *cur = head, *next = NULL;\n\tnewHead.next = head;\n\tint len = 0;\n\tfor(ListNode *p = head; p; p = p->next) len++;\n\tint times = len/k;\n\twhile(times) {\n\t\tfor(int i = 1; i < k; ++i) {\n\t\t\tnext = cur->next;\n\t\t\tcur->next = cur->next->next;\n\t\t\tnext->next = pre->next;\n\t\t\tpre->next = next;\n\t\t\tif(i == k-1) {\n\t\t\t\tpre = cur;\n\t\t\t\tcur = cur->next;\n\t\t\t}\n\t\t}\n\t\ttimes--;\n\t}\n\treturn newHead.next;\n}\n```\n\nAlways welcome new ideas and `practical` tricks, just leave them in the comments!
118
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
4,402
6
```\nclass Solution{\npublic:\n int len(ListNode *&head){\n ListNode *p = head;\n int c = 0;\n while (p){\n c++;\n p = p->next;\n }\n return c;\n }\n ListNode *addTwoNumbers(ListNode *l1, ListNode *l2){\n ListNode *p = l1, *q = l2, *temp;\n bool c = 0;\n bool bre = 0;\n if (len(l1) >= len(l2)){\n while (p){\n if (q == NULL){\n bre = 1;\n break;\n }\n p->val += (q->val + c);\n if (p->val > 9){\n c = 1;\n p->val = p->val - 10;\n }\n else{\n c = 0;\n }\n if (p->next == NULL){\n temp = p;\n }\n p = p->next;\n q = q->next;\n }\n if(bre){\n while (p){\n p->val += c;\n if (p->val == 10){\n p->val = 0;\n c = 1;\n }\n else{\n c = 0;\n }\n if (p->next == NULL){\n temp = p;\n }\n p = p->next;\n }\n }\n if (c){\n ListNode *n = new ListNode(1);\n temp->next = n;\n }\n return l1;\n }\n while (q){\n if (p == NULL){\n bre = 1;\n break;\n }\n q->val += p->val + c;\n if (q->val > 9){\n c = 1;\n q->val = q->val - 10;\n }\n else{\n c = 0;\n }\n if (q->next == NULL){\n temp = q;\n }\n p = p->next;\n q = q->next;\n }\n while (q){\n q->val += c;\n if (q->val == 10){\n q->val = 0;\n c = 1;\n }\n else{\n c = 0;\n }\n if (q->next == NULL){\n temp = q;\n }\n q = q->next;\n }\n if (c){\n ListNode *n = new ListNode(1);\n temp->next = n;\n }\n return l2;\n }\n};\n```
120
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
4,230
18
# Your upvote is my motivation!\n\n\n# Code\n```\n# Definition for singly-linked list.\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n dummyHead = ListNode(0)\n curr = dummyHead\n carry = 0\n while l1 != None or l2 != None or carry != 0:\n l1Val = l1.val if l1 else 0\n l2Val = l2.val if l2 else 0\n columnSum = l1Val + l2Val + carry\n carry = columnSum // 10\n newNode = ListNode(columnSum % 10)\n curr.next = newNode\n curr = newNode\n l1 = l1.next if l1 else None\n l2 = l2.next if l2 else None\n return dummyHead.next\n\n\n<!-- ========================================================= -->\n# Long Approach to understand\n<!-- Same Approach but diff way -- 99.9% beats in Memory -->\n\n newhead = ListNode(-1)\n temphead = newhead\n c = 0\n\n while l1 and l2:\n cur_digit = l1.val + l2.val + c # 25\n\n if cur_digit >= 10:\n c = cur_digit // 10 #2\n cur_digit = cur_digit % 10 #5\n else:\n c = 0\n \n new_node = ListNode(cur_digit)\n temphead.next = new_node\n temphead = new_node\n \n l1 = l1.next\n l2 = l2.next\n \n while l1:\n cur_digit = l1.val + c\n if cur_digit >= 10:\n c = cur_digit // 10 #2\n cur_digit = cur_digit % 10 #5\n else:\n c = 0\n new_node = ListNode(cur_digit)\n temphead.next = new_node\n temphead = new_node\n l1 = l1.next\n \n while l2:\n cur_digit = l2.val + c\n if cur_digit >= 10:\n c = cur_digit // 10 #2\n cur_digit = cur_digit % 10 #5\n else:\n c = 0\n new_node = ListNode(cur_digit)\n temphead.next = new_node\n temphead = new_node\n l2 = l2.next\n \n if c == 0:\n return newhead.next\n else:\n new_node = ListNode(c)\n temphead.next = new_node\n return newhead.next\n\n```
128
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
21
7
\n# Code\n```\nclass Solution {\n public ListNode addTwoNumbers(ListNode list1, ListNode list2) {\n ListNode dummyHead = new ListNode(0);\n ListNode result = dummyHead;\n int sum = 0, carry = 0;\n \n while (list1 != null || list2 != null) {\n sum = 0;\n \n if (list1 != null) {\n sum += list1.val;\n list1 = list1.next;\n }\n \n if (list2 != null) {\n sum += list2.val;\n list2 = list2.next;\n }\n \n if (carry != 0) {\n sum += carry;\n }\n \n if (sum / 10 != 0) {\n ListNode newNode = new ListNode(sum % 10);\n result.next = newNode;\n carry = sum / 10;\n result = newNode;\n } else {\n ListNode newNode = new ListNode(sum);\n result.next = newNode;\n carry = 0;\n result = newNode;\n }\n }\n \n if (carry != 0) {\n ListNode newNode = new ListNode(carry);\n result.next = newNode;\n result = newNode;\n }\n \n return dummyHead.next;\n }\n}\n\n```
133
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
266
5
# **PLEASE UPVOTE IF YOU LIKE THE SOLUTION**\n[]()\n[]()\n# Approach\nnitialization:\n\ncarry is initialized to 0, which represents the carry-over value when adding digits.\nA new linked list l3 is created with a dummy node containing value 0. The head points to the start of this list, and l3 is used to build the result linked list.\nMain Loop:\nThe main loop iterates through both input linked lists (l1 and l2) until either of them becomes NULL. The loop performs the following steps:\n\nCalculate the sum of the corresponding digits from l1 and l2, along with the carry value.\nUpdate carry with the value of sum / 10 (integer division).\nAdd a new node to the l3 linked list with a value of sum % 10 (remainder of the division).\nMove to the next nodes in l1, l2, and l3.\nRemaining Digits:\nAfter the main loop, there might be remaining digits in either l1 or l2. Two separate loops handle these remaining digits:\n\nIf there are remaining digits in l1, add them to the current l3 node along with the carry.\nIf there are remaining digits in l2, add them to the current l3 node along with the carry.\nFinal Carry:\nIf there is a carry value left after all addition operations, add a new node with the carry value to the end of the l3 linked list.\n\nReturn Result:\nThe result linked list is stored in l3, but since the first node of l3 is a dummy node, the actual result starts from the second node. The head->next node is returned as the result, representing the sum of the two input linked lists.\n\nThe approach is based on simulating the process of adding digits manually, carrying over the excess value when necessary. The code handles cases where one linked list is longer than the other or when there\'s a final carry left after all additions.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(N)(whichever linkedlist is longer + 1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n int carry=0;\n ListNode* l3= new ListNode(0);\n ListNode* head= l3;\n\n while(l1!=NULL && l2!=NULL)\n {\n int value= l1->val+l2->val+carry;\n carry = value/10;\n l3->next= new ListNode(value%10);\n l3=l3->next;\n l1=l1->next;\n l2=l2->next;\n }\n while(l1)\n {\n int value= l1->val+carry;\n carry = value/10;\n l3->next= new ListNode(value%10);\n l3=l3->next;\n l1=l1->next;\n }\n while(l2)\n {\n int value= l2->val+carry;\n carry = value/10;\n l3->next= new ListNode(value%10);\n l3=l3->next;\n l2=l2->next;\n }\n if(carry)\n {\n l3->next=new ListNode(carry);\n }\n return head->next;\n\n }\n};\n```
144
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
32,575
90
```\nvar addTwoNumbers = function(l1, l2) {\n const iter = (n1, n2, rest = 0) => {\n if (!n1 && !n2 && !rest) return null;\n const newVal = (n1?.val || 0) + (n2?.val || 0) + rest;\n const nextNode = iter(n1?.next, n2?.next, Math.floor(newVal / 10));\n return new ListNode(newVal % 10, nextNode);\n }\n return iter(l1, l2);\n};\n```
149
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
4,613
22
```\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n \nclass Solution:\n def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n num1, num2 = \'\', \'\'\n node1, node2 = l1, l2\n while node1 is not None:\n num1 = str(node1.val) + num1\n node1 = node1.next\n while node2 is not None:\n num2 = str(node2.val) + num2\n node2 = node2.next\n num1 = int(num1)\n num2 = int(num2)\n summ = num1 + num2\n summ = str(summ)\n \n digitnodes = list(summ)\n \n for idx, digit in enumerate(summ):\n if idx == 0:\n digitnodes[idx] = ListNode(val = digit, next=None)\n else: \n digitnodes[idx] = ListNode(val = digit, next=digitnodes[idx-1])\n \n \n return(digitnodes[len(digitnodes)-1]) \n```
150
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
28,478
84
# Approach\nThis is a simple addition flow. \n1. 2 numbers like ( 743, 564 )\n2. Start from the left to right ( loop - index)\n3. Get the number by index ( index = 0 => 7, 5 )\n4. Add those numbers ( 7 + 5 => 12 )\n5. Carry it if it is greater than 9 ( var carry = 12 / 10 => 1 )\n6. Increase the index ( index + 1 )\n7. Go to step 3 ( We need to pass carry value )\n\nlet\'s revise the steps\n\n3. Get the number by index ( index = 1 => 4, 6 )\n4. Add those numbers and carry ( 4 + 6 + 1)\n5. Carry it if it is greater than 9 ( var carry = 11 / 10 => 1 )\n6. Increase the index ( index + 1 => 2 )\n7. Go to step 3 ( We need to pass carry value )\n\nActually it is done if we know all the number places and length of the numbers.\n\nHowever we don\'t know it. It is a linked list. So we don\'t have the length and index. But we can use infinity loops. Let\'s start with a while loop.\n\n1_) let\'s start coding\n```\nwhile(true)\n{\n\t// step-3 : l1.val and l2.val \n\t// step-4\n\tint total = l1.val + l2.val;\n\t// step - 5\n\tint carry = total / 10;\n int val = total % 10;\n\t// step-6 : we don\'t have index but we have l1 and l2, so we can set them for the next loop\n\tl1 = l1.next;\n\tl2 = l2.next;\n // We need to store the val field and set the next field in the next loop, it seems a perfect sample for recursive methods\n // let\'s create a method then\n} \n```\n2_) we need pass value of 1 and 2 and carry values\n\n```\nnewMethod(int val1, int val2, int carry, ListNode next1, ListNode next2)\n{\n\tint total = val1 + val2;\n\tcarry = total / 10;\n\tint place = total % 10;\n\treturn new ListNode(place, /* we need to do the same for the next values */)\n}\n```\n\n3_) make it recursive. You can run the program and see the errors.\n\n```\nnewMethod(ListNode next1, ListNode next2, int carry)\n{\n\tint total = next1.val + next2.val + carry;\n\tcarry = total / 10;\n\tint val = total % 10;\n\treturn new ListNode(val, newMethod(next1.next, next2.next, carry))\n}\n\n\npublic ListNode AddTwoNumbers(ListNode l1, ListNode l2) \n{\n\treturn newMethod(l1, l2, 0);\n}\n```\n\n4_) add null check\n\n```\nnewMethod(ListNode next1, ListNode next2, int carry)\n{\n\tint total = (next1 != null ? next1.val : 0) + (next2 != null ? next2.val : 0) + carry;\n\tcarry = total / 10;\n\treturn new ListNode(total % 10, newMethod(next1?.next, next2?.next, carry))\n}\n```\n\n5_) stop the recursive method when next1 and next2 null\n\n```\nnewMethod(ListNode next1, ListNode next2, int carry)\n{\n\tif(next1 == null && next2 == null && carry == 0) return null;\n\n\tint total = (next1 != null ? next1.val : 0) + (next2 != null ? next2.val : 0) + carry;\n\tcarry = total / 10;\n\treturn new ListNode(total % 10, newMethod(next1?.next, next2?.next, carry))\n}\n```\n\n6_) AddTwoNumbers and newMethod are almost same parameters. So if I add carry as an optional parameter, it would be great.\n```\npublic ListNode AddTwoNumbers(ListNode l1, ListNode l2, int carry = 0) \n{\n\tif(l1 == null && l2 == null && carry == 0) return null;\n\n\tint total = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;\n\tcarry = total / 10;\n\treturn new ListNode(total % 10, AddTwoNumbers(l1?.next, l2?.next, carry));\n}\n\n```\n\n> You can also use `l1?.val ?? 0` instead of using ternary operators.\n\n> JS version: `l1?.val || 0`\n\n\n# Final Code C#\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public int val;\n * public ListNode next;\n * public ListNode(int val=0, ListNode next=null) {\n * this.val = val;\n * this.next = next;\n * }\n * }\n */\npublic class Solution \n{\n public ListNode AddTwoNumbers(ListNode l1, ListNode l2, int carry = 0) \n {\n if(l1 == null && l2 == null && carry == 0) return null;\n\n int total = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;\n carry = total / 10;\n return new ListNode(total % 10, AddTwoNumbers(l1?.next, l2?.next, carry));\n }\n}\n```\n\n\n# Final Code Typescript\n```\n/**\n * Definition for singly-linked list.\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n */\n\nfunction addTwoNumbers(l1: ListNode | null, l2: ListNode | null, carry: number = 0): ListNode | null {\n if(!l1 && !l2 && !carry) return null;\n\n var total : number = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + (carry || 0);\n carry = parseInt(total / 10 + \'\');\n return new ListNode(total % 10, addTwoNumbers(l1?.next, l2?.next, carry));\n};\n```\n\n# Final Code Javascript\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nvar addTwoNumbers = function(l1, l2, carry) {\n if(!l1 && !l2 && !carry) return null;\n\n var total = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + (carry || 0);\n carry = parseInt(total / 10);\n return new ListNode(total % 10, addTwoNumbers(l1?.next, l2?.next, carry));\n};\n```\n\n
152
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
213,406
821
public class Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode c1 = l1;\n ListNode c2 = l2;\n ListNode sentinel = new ListNode(0);\n ListNode d = sentinel;\n int sum = 0;\n while (c1 != null || c2 != null) {\n sum /= 10;\n if (c1 != null) {\n sum += c1.val;\n c1 = c1.next;\n }\n if (c2 != null) {\n sum += c2.val;\n c2 = c2.next;\n }\n d.next = new ListNode(sum % 10);\n d = d.next;\n }\n if (sum / 10 == 1)\n d.next = new ListNode(1);\n return sentinel.next;\n }\n }
169
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
16,696
59
# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n d = n = ListNode(0)\n num1 = num2 = ""\n while l1:\n num1 += str(l1.val)\n l1 = l1.next\n while l2:\n num2 += str(l2.val)\n l2 = l2.next\n res = str(int(num1[::-1]) + int(num2[::-1]))[::-1]\n for i in res:\n d.next = ListNode(i)\n d = d.next\n return n.next \n```\nDo upvote if you like the Solution :)
170
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
769
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode res = new ListNode();\n ListNode r = res;\n int carry = 0;\n while(l1 != null || l2 != null || carry != 0) {\n int n1 = l1 != null ? l1.val : 0;\n int n2 = l2 != null ? l2.val : 0;\n int sum = carry + n1 + n2;\n r.next = new ListNode(sum % 10);\n r = r.next;\n carry = sum / 10;\n l1 = l1 != null ? l1.next : null;\n l2 = l2 != null ? l2.next : null;\n }\n return res.next;\n }\n}\n```
171
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
3,512
19
\n### steps\n1. Initialize a dummy node and a current node to keep track of the result linked list.\n2. Initialize carry to 0.\n3. Traverse both input linked lists simultaneously.\n4. At each step, calculate the sum of the current nodes\' values along with the carry.\n5. Calculate the carry for the next iteration as sum / 10.\n6. Create a new node with the value sum % 10 and append it to the result list.\n7. Move to the next nodes in both input lists.\n8. Repeat steps 4-7 until you have processed all digits in both input lists.\n9. If there is still a carry left after the loop, create an additional node with the carry as its value and append it to the result list.\n10. Return the next node of the dummy node, which represents the head of the result linked list.\n\n\n``` java []\nclass Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode dummy = new ListNode(0); // Dummy node to simplify result list handling\n ListNode current = dummy; // Current node to build the result list\n int carry = 0; // Initialize carry to 0\n\n while (l1 != null || l2 != null) {\n int x = (l1 != null) ? l1.val : 0; // Get the current digit from l1 or set to 0 if null\n int y = (l2 != null) ? l2.val : 0; // Get the current digit from l2 or set to 0 if null\n\n int sum = x + y + carry; // Calculate the sum of digits and carry\n carry = sum / 10; // Calculate the carry for the next iteration\n\n // Create a new node with the value sum % 10 and append it to the result list\n current.next = new ListNode(sum % 10);\n current = current.next; // Move to the next node in the result list\n\n // Move to the next nodes in both input lists if they are not null\n if (l1 != null) l1 = l1.next;\n if (l2 != null) l2 = l2.next;\n }\n\n // If there is still a carry left after the loop, create an additional node for it\n if (carry > 0) {\n current.next = new ListNode(carry);\n }\n\n return dummy.next; // Return the next node of the dummy node, which is the head of the result list\n }\n}\n```\n``` C++ []\nclass Solution {\npublic:\n ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n ListNode* dummy_head = new ListNode(0); // Dummy head to simplify the code\n ListNode* current = dummy_head;\n int carry = 0;\n\n while (l1 || l2) {\n int x = (l1) ? l1->val : 0;\n int y = (l2) ? l2->val : 0;\n int sum = x + y + carry;\n\n carry = sum / 10;\n current->next = new ListNode(sum % 10);\n current = current->next;\n\n if (l1) l1 = l1->next;\n if (l2) l2 = l2->next;\n }\n\n if (carry > 0) {\n current->next = new ListNode(carry);\n }\n\n return dummy_head->next; // Return the actual result, not the dummy head.\n\n }\n};\n```\n``` Python []\n\ndef addTwoNumbers(l1, l2):\n dummy = ListNode()\n current = dummy\n p, q = l1, l2\n carry = 0\n \n while p or q:\n x = p.val if p else 0\n y = q.val if q else 0\n val = carry + x + y\n carry = val // 10\n current.next = ListNode(val % 10)\n current = current.next\n \n if p:\n p = p.next\n if q:\n q = q.next\n \n if carry > 0:\n current.next = ListNode(carry)\n \n return dummy.next\n\n```\n``` javascript []\nvar addTwoNumbers = function(l1, l2) {\n let dummyHead = new ListNode(0); // Create a dummy node to simplify the code.\n let current = dummyHead; // Initialize a current pointer to the dummy node.\n let carry = 0; // Initialize a variable to store the carry value.\n\n while (l1 || l2) {\n const x = l1 ? l1.val : 0;\n const y = l2 ? l2.val : 0;\n const sum = x + y + carry;\n\n carry = Math.floor(sum / 10); // Calculate the carry for the next iteration.\n current.next = new ListNode(sum % 10); // Create a new node with the current digit.\n\n current = current.next; // Move the current pointer to the next node.\n\n if (l1) l1 = l1.next;\n if (l2) l2 = l2.next;\n }\n\n // If there is a carry after processing all digits, add it as a new node.\n if (carry > 0) {\n current.next = new ListNode(carry);\n }\n\n return dummyHead.next; // Return the result, skipping the dummy node.\n}\n```\n\n``` C# []\npublic class Solution {\n public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {\n ListNode dummyHead = new ListNode();\n ListNode current = dummyHead;\n int carry = 0;\n\n while (l1 != null || l2 != null)\n {\n int x = (l1 != null) ? l1.val : 0;\n int y = (l2 != null) ? l2.val : 0;\n\n int sum = x + y + carry;\n carry = sum / 10;\n\n current.next = new ListNode(sum % 10);\n current = current.next;\n\n if (l1 != null) l1 = l1.next;\n if (l2 != null) l2 = l2.next;\n }\n\n if (carry > 0)\n {\n current.next = new ListNode(carry);\n }\n\n return dummyHead.next; \n }\n}\n```\n\n``` PHP []\n\nfunction addTwoNumbers($l1, $l2) {\n $dummy = new ListNode(0);\n $current = $dummy;\n $carry = 0;\n \n while ($l1 !== null || $l2 !== null) {\n $x = ($l1 !== null) ? $l1->val : 0;\n $y = ($l2 !== null) ? $l2->val : 0;\n \n $sum = $x + $y + $carry;\n $carry = (int)($sum / 10);\n \n $current->next = new ListNode($sum % 10);\n $current = $current->next;\n \n if ($l1 !== null) $l1 = $l1->next;\n if ($l2 !== null) $l2 = $l2->next;\n }\n \n if ($carry > 0) {\n $current->next = new ListNode($carry);\n }\n \n return $dummy->next;\n}\n```
172
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
159,689
652
class Solution:\n # @return a ListNode\n def addTwoNumbers(self, l1, l2):\n carry = 0\n root = n = ListNode(0)\n while l1 or l2 or carry:\n v1 = v2 = 0\n if l1:\n v1 = l1.val\n l1 = l1.next\n if l2:\n v2 = l2.val\n l2 = l2.next\n carry, val = divmod(v1+v2+carry, 10)\n n.next = ListNode(val)\n n = n.next\n return root.next
175
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
111,120
562
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {\n ListNode preHead(0), *p = &preHead;\n int extra = 0;\n while (l1 || l2 || extra) {\n int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;\n extra = sum / 10;\n p->next = new ListNode(sum % 10);\n p = p->next;\n l1 = l1 ? l1->next : l1;\n l2 = l2 ? l2->next : l2;\n }\n return preHead.next;\n }
189
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
1,655
20
# Intuition\nMy initial approach to solving this problem involves simulating the process of adding two numbers represented as linked lists. I\'ll iterate through both linked lists simultaneously, adding corresponding digits along with any carry from the previous sum.\n\n# Approach\nI will use a dummy node to keep track of the resulting linked list. I\'ll initialize a carry variable to store any carry from the previous sum. I\'ll iterate through both linked lists while there are still digits left to process or a carry exists. For each step, I\'ll calculate the sum of the corresponding digits from both linked lists along with the carry. I\'ll update the carry for the next step and add the current digit to the result linked list. Finally, I\'ll move the pointers to the next nodes in both linked lists.\n\n# Complexity\n- Time complexity: O(max(N, M))\n Here, \'N\' is the length of the first linked list and \'M\' is the length of the second linked list. The algorithm iterates through both linked lists simultaneously, performing constant-time operations for each step.\n- Space complexity: O(max(N, M))\n The algorithm uses extra space for the result linked list, which can have a length of at most max(N, M) + 1.\n\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode temp = new ListNode(0);\n ListNode head = temp;\n int carry = 0;\n while (l1 != null || l2 != null || carry>0 ) {\n int sum = carry;\n if (l1 != null) {\n sum += l1.val;\n l1 = l1.next;\n }\n\n if (l2 != null) {\n sum += l2.val;\n l2 = l2.next;\n }\n\n carry=sum/10;\n\n sum %=10;\n\n head.next = new ListNode(sum);\n\n head = head.next;\n\n }\n\n return temp.next;\n\n\n\n \n }\n}\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]()
194
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
3,383
6
```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode addTwoNumbers(ListNode l1, ListNode l2) {\n ListNode l3 = new ListNode();\n ListNode head = l3;\n int num = 0;\n int h = 0;\n \n while(l1 != null || l2 != null){\n if(l1 != null && l2 != null)\n num = l1.val + l2.val + h;\n else if(l1 == null)\n num = l2.val + h;\n else if(l2 == null)\n num = l1.val + h;\n \n if(l1 != null)\n l1 = l1.next;\n if(l2 != null)\n l2 = l2.next;\n \n if(num > 9){\n l3.val = num%10;\n h = 1;\n }\n else{\n l3.val = num;\n h = 0;\n }\n \n if(l1 != null || l2 != null){\n l3.next = new ListNode();\n l3 = l3.next;\n }\n }\n if(h == 1){\n l3.next = new ListNode(1);\n }\n return head;\n }\n}\n```
197
Add Two Numbers
add-two-numbers
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.
Linked List,Math,Recursion
Medium
null
3,396
28
\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n \n ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n if(l1==NULL &&l2==NULL) return l2;\n else if(l1==NULL) return l2;\n else if(l2==NULL) return l1;\n\n int a =l1->val+l2->val;\n //taking the unit digit only in consideration \n ListNode* p=new ListNode(a%10);\n p->next=addTwoNumbers(l1->next,l2->next);\n //if the sum has carry it will be not more than 1 so \n //we introduce a new node and add the next value of the\n //linkedlist with the carry one \n if(a>=10){\n p->next=addTwoNumbers(p->next,new ListNode(1));\n }\n return p;\n\n\t}\n};\n```
199
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
167,429
818
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the 3 solutions is to iteratively find the longest substring without repeating characters by maintaining a sliding window approach. We use two pointers (`left` and `right`) to represent the boundaries of the current substring. As we iterate through the string, we update the pointers and adjust the window to accommodate new unique characters and eliminate repeating characters.\n\n# Approach 1 - Set\n<!-- Describe your approach to solving the problem. -->\n\n1. We use a set (`charSet`) to keep track of unique characters in the current substring.\n2. We maintain two pointers, `left` and `right`, to represent the boundaries of the current substring.\n3. The `maxLength` variable keeps track of the length of the longest substring encountered so far.\n4. We iterate through the string using the `right` pointer.\n5. If the current character is not in the set (`charSet`), it means we have a new unique character.\n6. We insert the character into the set and update the `maxLength` if necessary.\n7. If the character is already present in the set, it indicates a repeating character within the current substring.\n8. In this case, we move the `left` pointer forward, removing characters from the set until the repeating character is no longer present.\n9. We insert the current character into the set and continue the iteration.\n10. Finally, we return the `maxLength` as the length of the longest substring without repeating characters.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int n = s.length();\n int maxLength = 0;\n unordered_set<char> charSet;\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (charSet.count(s[right]) == 0) {\n charSet.insert(s[right]);\n maxLength = max(maxLength, right - left + 1);\n } else {\n while (charSet.count(s[right])) {\n charSet.erase(s[left]);\n left++;\n }\n charSet.insert(s[right]);\n }\n }\n \n return maxLength;\n }\n};\n```\n```Java []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int n = s.length();\n int maxLength = 0;\n Set<Character> charSet = new HashSet<>();\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (!charSet.contains(s.charAt(right))) {\n charSet.add(s.charAt(right));\n maxLength = Math.max(maxLength, right - left + 1);\n } else {\n while (charSet.contains(s.charAt(right))) {\n charSet.remove(s.charAt(left));\n left++;\n }\n charSet.add(s.charAt(right));\n }\n }\n \n return maxLength;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n n = len(s)\n maxLength = 0\n charSet = set()\n left = 0\n \n for right in range(n):\n if s[right] not in charSet:\n charSet.add(s[right])\n maxLength = max(maxLength, right - left + 1)\n else:\n while s[right] in charSet:\n charSet.remove(s[left])\n left += 1\n charSet.add(s[right])\n \n return maxLength\n\n```\n\n# Approach 2 - Unordered Map\n1. We improve upon the first solution by using an unordered map (`charMap`) instead of a set.\n2. The map stores characters as keys and their indices as values.\n3. We still maintain the `left` and `right` pointers and the `maxLength` variable.\n4. We iterate through the string using the `right` pointer.\n5. If the current character is not in the map or its index is less than `left`, it means it is a new unique character.\n6 We update the `charMap` with the character\'s index and update the `maxLength` if necessary.\n7. If the character is repeating within the current substring, we move the `left` pointer to the next position after the last occurrence of the character.\n8. We update the index of the current character in the `charMap` and continue the iteration.\n9. At the end, we return the `maxLength` as the length of the longest substring without repeating characters.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int n = s.length();\n int maxLength = 0;\n unordered_map<char, int> charMap;\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (charMap.count(s[right]) == 0 || charMap[s[right]] < left) {\n charMap[s[right]] = right;\n maxLength = max(maxLength, right - left + 1);\n } else {\n left = charMap[s[right]] + 1;\n charMap[s[right]] = right;\n }\n }\n \n return maxLength;\n }\n};\n```\n```Java []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int n = s.length();\n int maxLength = 0;\n Map<Character, Integer> charMap = new HashMap<>();\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (!charMap.containsKey(s.charAt(right)) || charMap.get(s.charAt(right)) < left) {\n charMap.put(s.charAt(right), right);\n maxLength = Math.max(maxLength, right - left + 1);\n } else {\n left = charMap.get(s.charAt(right)) + 1;\n charMap.put(s.charAt(right), right);\n }\n }\n \n return maxLength;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n n = len(s)\n maxLength = 0\n charMap = {}\n left = 0\n \n for right in range(n):\n if s[right] not in charMap or charMap[s[right]] < left:\n charMap[s[right]] = right\n maxLength = max(maxLength, right - left + 1)\n else:\n left = charMap[s[right]] + 1\n charMap[s[right]] = right\n \n return maxLength\n\n```\n\n# Approach 3 - Integer Array\n1. This solution uses an integer array `charIndex` to store the indices of characters.\n2. We eliminate the need for an unordered map by utilizing the array.\n3. The `maxLength`, `left`, and `right` pointers are still present.\n4. We iterate through the string using the `right` pointer.\n5. We check if the current character has occurred within the current substring by comparing its index in `charIndex` with `left`.\n6. If the character has occurred, we move the `left` pointer to the next position after the last occurrence of the character.\n7. We update the index of the current character in `charIndex`.\n8. At each step, we update the `maxLength` by calculating the length of the current substring.\n9. We continue the iteration until reaching the end of the string.\n10. Finally, we return the `maxLength` as the length of the longest substring without repeating characters.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n int n = s.length();\n int maxLength = 0;\n vector<int> charIndex(128, -1);\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (charIndex[s[right]] >= left) {\n left = charIndex[s[right]] + 1;\n }\n charIndex[s[right]] = right;\n maxLength = max(maxLength, right - left + 1);\n }\n \n return maxLength;\n }\n};\n```\n```Java []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int n = s.length();\n int maxLength = 0;\n int[] charIndex = new int[128];\n Arrays.fill(charIndex, -1);\n int left = 0;\n \n for (int right = 0; right < n; right++) {\n if (charIndex[s.charAt(right)] >= left) {\n left = charIndex[s.charAt(right)] + 1;\n }\n charIndex[s.charAt(right)] = right;\n maxLength = Math.max(maxLength, right - left + 1);\n }\n \n return maxLength;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n n = len(s)\n maxLength = 0\n charIndex = [-1] * 128\n left = 0\n \n for right in range(n):\n if charIndex[ord(s[right])] >= left:\n left = charIndex[ord(s[right])] + 1\n charIndex[ord(s[right])] = right\n maxLength = max(maxLength, right - left + 1)\n \n return maxLength\n\n```\n\n![CUTE_CAT.png]()\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**\n\n\n
200
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
109,390
738
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nif you know sliding window...then it can be intuitive. But if you don\'t know ...no worry i will teach you...\nRefer below approach points.....\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use sliding window with hashset, use left and right pointers to move the window . \n2. If the set doesn\'t contains character then first add into the set and calculate the maxLength hand-in-hand... \n3. if character already present in the set that means you have to move your sliding window by 1 , before that you have to remove all the characters that are infront of the character that is present already in window before.\n4. Now you have to remove that character also and move the left pointer and also add the new character into the set.\n5. THAT\'S ALL........EASY APPROACH USING SIMPLE HASHSET+SLIDING WINDOW\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(k), where k is the number of distinctive characters prsent in the hashset.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n Set<Character>set=new HashSet<>();\n int maxLength=0;\n int left=0;\n for(int right=0;right<s.length();right++){\n \n if(!set.contains(s.charAt(right))){\n set.add(s.charAt(right));\n maxLength=Math.max(maxLength,right-left+1);\n \n }else{\n while(s.charAt(left)!=s.charAt(right)){\n set.remove(s.charAt(left));\n left++;\n }\n set.remove(s.charAt(left));left++;\n set.add(s.charAt(right));\n }\n \n }\n return maxLength;\n }\n}\n```\n\n![upvote.jpg]()\n\n\n**PLEASE UPVOTE** .....if you find this solution useful , and if any suggestions to improve then please comment.
201
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
832
6
\n\nA brute force solution would first require finding every possible substring, which would run in O(n<sup>2</sup>) time. We\'re not done yet though, because we now have to check every substring for duplicate characters by iterating through every substring. Each check for duplicate characters runs in O(n) time, and we need to do that for every substring generated (which ran in O(n<sup>2</sup>) time), so the brute force approach ends up running in O(n<sup>3</sup>) time.\n\nInstead, we can reduce this to O(n) time by using a sliding window approach and eliminating unnecessary computations. We use two pointers, `l` and `r`, to denote where the substring starts and ends, and a dictionary called `seen` to keep track of the index of each character encountered. Then, we move the right pointer one character at a time to the right to expand our substring.\n\nAt each iteration, we check for two things.\n1. Have we seen the newly added character (at index `r`) before? If we haven\'t, then this is a brand new character and we can just add it to the substring and extend the length\n2. If we have seen it before, is its last known position greater than or equal to the left index? If it is, then that means it\'s repeated somewhere in the substring. If not, then that means it\'s <i>outside</i> of the substring, so we can just add it to the substring and extend the length\n\nSo if both conditions are true, the new character is repeated and we have a problem. We can get rid of the repeated character by moving up the left pointer to be one index past the last recorded index in `seen`. Then, we just keep moving up the right pointer until it reaches the end of the string. Since we only have to loop through the string once, and since hash table lookups run in constant time, this algorithm ends up running in O(n) time.\n\nFor an intuitive proof of why this works and why we don\'t need to check all the other substrings while moving up the left pointer, please see the video - it\'s a bit difficult to explain without a visualization and a concrete example. But basically, all the other substrings will either still contain a repeated character or will be shorter than the last valid substring encountered, so they can be safely ignored.\n\n\n# Code\n```\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n seen = {}\n l = 0\n length = 0\n for r in range(len(s)):\n char = s[r]\n if char in seen and seen[char] >= l:\n l = seen[char] + 1\n else:\n length = max(length, r - l + 1)\n seen[char] = r\n\n return length\n```
202
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
97,994
895
So, the prerequisit of this problem is **Sliding Window**, if you know then it\'s a plus point. But, if you don\'t know don\'t worry I\'ll try to teach you.\n\nLet\'s understand first of all what the problem is saying!!\n```\nGiven a string s, find the length of the longest substring without repeating characters.\n```\nOkay, so from the given statement we will try to find out wether it is a **Sliding Window** problem or not>>\n\nSo, to check that out I\'m giving you a tempelate & it\'ll work in almost all of the questions of **sliding window**\n\n```\nTo, find out a sliding window problem :-\n> First thing is, we have given something like an "Array" | OR | "String"\n> Second thing is, they are talking about either "subsequence" | OR | "substring"\n> And third most thing is, either we have given a "window size i.e. k" | OR | we have to "manually find out window size" \n```\n\nNow, using above keys let\'s understand wether this problem is of a sliding window or not.\n```\n> Are they talking about, "Array" or "String" --> yes they are talking about "string" +1 point\n> Are they asking to find out "subsequence" or "substring" --> yes they are talking about "substring" +1 point\n> Do, we have given a window size --> No, we don\'t have\n\nTotal score is "2 / 3" so, it\'s a 100% sliding window problem. If your score lies from 2/3 to 3/3 that\'s a gauranteed sliding window problem \n```\n\nNow, let\'s talk about how we gonna implement sliding window in this problem, but before that I just want to tell you one more thing. There\'s exist basically 2 types of sliding window.\n1. Fix size sliding window **{means K is given}**\n\n\n2. Variable silze sliding window **{means K is not given}**\n\n**Before moving to the problem I want to give you a template which you can use in any sliding window `{Variable size}` problem**\n\n```\nwhile(j < size()){\n\n // Calculation\'s happen\'s here\n-----------------------------------------------\n if(condition < k){\n j++;\n }\n-----------------------------------------------\n\n-----------------------------------------------\n else if(condition == k){\n // ans <-- calculation\n j++;\n }\n----------------------------------------------\n\n----------------------------------------------\n else if(condition > k){\n while(condition > k){\n // remove calculation for i\n i++;\n }\n j++;\n }\n----------------------------------------------\n}\nreturn ans;\n```\n\nSo, in this problem we gonna deal with variable size sliding window. Let\'s take one example :-\n\n```\nInput: s = "abcabcbb"\nOutput: 3\n```\n\nSo, inorder to solve this, what I\'m thinking is, we should have to use one more Data Structure to store the occurence of these characters, I thing HashMap will be best to use.\n\n* Now, what I\'ll do is create 2 pointer\'s i & j initally they both start from 0\n* The j pointer will helps us to fill the array while the i pointer will helps in removing from the map {Don\'t know what I\'m talking about} just wait. You\'ll understand :)\n\n```\nLet\'s understand it visually :-\n```\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n![image]()\n\n\n**Java**\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n Map<Character, Integer> map = new HashMap<>();\n int i = 0;\n int j = 0;\n int max = 0;\n while(j < s.length()){\n map.put(s.charAt(j), map.getOrDefault(s.charAt(j), 0) + 1);\n if(map.size() == j - i + 1){\n max = Math.max(max, j - i + 1);\n j++;\n }\n else if(map.size() < j - i + 1){\n while(map.size() < j - i + 1){\n map.put(s.charAt(i), map.get(s.charAt(i)) - 1);\n if(map.get(s.charAt(i)) == 0) map.remove(s.charAt(i));\n i++;\n }\n j++;\n }\n }\n return max;\n }\n}\n```\n**C++**\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n if(s.length()==0)return 0; //if string of length zero comes simply return 0\n unordered_map<char,int> m; //create map to store frequency,(get to know all unique characters\n int i=0,j=0,ans=INT_MIN; \n while(j<s.length()) \n {\n m[s[j]]++; //increase the frequency of the element as you traverse the string\n if(m.size()==j-i+1) // whem map size is equal to the window size means suppose window size is 3 and map size is also three that means in map all unique characters are their\n {\n ans = max(ans,j-i+1); //compare the length of the maximum window size\n }\n else if(m.size()<j-i+1) //if the map size is less than the window size means there is some duplicate present like window size = 3 and map size = 2 means there is a duplicates\n {\n while(m.size()<j-i+1) //so till the duplicates are removed completely\n {\n m[s[i]]--; //remove the duplicates\n if(m[s[i]]==0) //if the frequency becomes zero \n {\n m.erase(s[i]);//delete it completely\n }\n i++; //go for next element \n }\n }\n j++; //go for the next element\n }\n return ans;\n }\n};\n```
203
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
58,805
255
# C++ Code\n``` C++ []\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n if(s.length()==0)return 0; //if string of length zero comes simply return 0\n unordered_map<char,int> m; //create map to store frequency,(get to know all unique characters\n int i=0,j=0,ans=INT_MIN; \n while(j<s.length()) \n {\n m[s[j]]++; //increase the frequency of the element as you traverse the string\n if(m.size()==j-i+1) // whem map size is equal to the window size means suppose window size is 3 and map size is also three that means in map all unique characters are their\n {\n ans = max(ans,j-i+1); //compare the length of the maximum window size\n }\n else if(m.size()<j-i+1) //if the map size is less than the window size means there is some duplicate present like window size = 3 and map size = 2 means there is a duplicates\n {\n while(m.size()<j-i+1) //so till the duplicates are removed completely\n {\n m[s[i]]--; //remove the duplicates\n if(m[s[i]]==0) //if the frequency becomes zero \n {\n m.erase(s[i]);//delete it completely\n }\n i++; //go for next element \n }\n }\n j++; //go for the next element\n }\n return ans;\n }\n};\n```\n\n![kitty.jpeg]()\n
207
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
270
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n- Initialize pointers strt and i to represent the start and end of the current substring.\n- Use a HashMap (mp) to track the occurrence of characters.\n- Iterate through the string with the i pointer.\n- If a repeating character is found, move the strt pointer to the right until the substring becomes valid again.\n- Update the HashMap and calculate the current window size (i - strt + 1).\n- Keep track of the maximum window size encountered.\n- Return the maximum window size as the result.\n\n<!-- Describe your approach to solving the problem. -->\n\n\n\n\n# Time complexity: **O(N)**\n \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Space complexity: **O(N)**\n \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int strt =0 ;\n int windsz = 0;\n HashMap<Character, Integer> mp = new HashMap<Character, Integer>();\n\n for(int i=0; i<s.length(); i++){\n while(mp.getOrDefault(s.charAt(i),0)==1){\n mp.put(s.charAt(strt),0);\n strt++;\n }\n mp.put(s.charAt(i),1);\n windsz = Math.max(windsz,i-strt+1);\n }\n return windsz;\n }\n}\n```\n![WhatsApp Image 2023-12-03 at 12.33.52.jpeg]()\n
209
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
386,655
1,825
the basic idea is, keep a hashmap which stores the characters in string as keys and their positions as values, and keep two pointers which define the max substring. move the right pointer to scan through the string , and meanwhile update the hashmap. If the character is already in the hashmap, then move the left pointer to the right of the same character last found. Note that the two pointers can only move forward. \n\n public int lengthOfLongestSubstring(String s) {\n if (s.length()==0) return 0;\n HashMap<Character, Integer> map = new HashMap<Character, Integer>();\n int max=0;\n for (int i=0, j=0; i<s.length(); ++i){\n if (map.containsKey(s.charAt(i))){\n j = Math.max(j,map.get(s.charAt(i))+1);\n }\n map.put(s.charAt(i),i);\n max = Math.max(max,i-j+1);\n }\n return max;\n }
210
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
2,768
12
read full article \n\nIntuition\nApproach\n1 window\n2 hashmap\n3 Two Pointer\n\nComplexity\nO(n) and the space complexity is O(min(n, m))\n\nCode\n\n\n![image]()\n
211
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
108,578
819
**Sliding window**\nWe use a dictionary to store the character as the key, the last appear index has been seen so far as value.\nseen[charactor] = index\n\n move the pointer when you met a repeated character in your window.\n\n\t \n```\nindext 0 1 2 3 4 5 6 7\nstring a c b d b a c d\n ^ ^\n | |\n\t\tleft right\n\t\tseen = {a : 0, c : 1, b : 2, d: 3} \n\t\t# case 1: seen[b] = 2, current window is s[0:4] , \n\t\t# b is inside current window, seen[b] = 2 > left = 0. Move left pointer to seen[b] + 1 = 3\n\t\tseen = {a : 0, c : 1, b : 4, d: 3} \nindext 0 1 2 3 4 5 6 7\nstring a c b d b a c d\n\t\t\t\t\t\t ^ ^\n\t\t\t\t\t | |\n\t\t\t\t left right\t\t\nindext 0 1 2 3 4 5 6 7\nstring a c b d b a c d\n\t\t\t\t\t ^ ^\n\t\t\t\t\t | |\n\t\t\t\t left right\t\t\n\t\t# case 2: seen[a] = 0,which means a not in current window s[3:5] , since seen[a] = 0 < left = 3 \n\t\t# we can keep moving right pointer.\n```\n\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n seen = {}\n l = 0\n output = 0\n for r in range(len(s)):\n """\n If s[r] not in seen, we can keep increasing the window size by moving right pointer\n """\n if s[r] not in seen:\n output = max(output,r-l+1)\n """\n There are two cases if s[r] in seen:\n case1: s[r] is inside the current window, we need to change the window by moving left pointer to seen[s[r]] + 1.\n case2: s[r] is not inside the current window, we can keep increase the window\n """\n else:\n if seen[s[r]] < l:\n output = max(output,r-l+1)\n else:\n l = seen[s[r]] + 1\n seen[s[r]] = r\n return output\n```\n* Time complexity :O(n). \n\tn is the length of the input string.\n\tIt will iterate n times to get the result.\n\n* Space complexity: O(m)\n\tm is the number of unique characters of the input. \n\tWe need a dictionary to store unique characters.\n\n
212
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
38,144
200
![image]()\n\n**Window Sliding Technique** is a computational technique which aims to reduce the use of nested loop and replace it with a single loop, thereby reducing the time complexity.\nThe Sliding window technique can reduce the time complexity to **O(n).**\n\n![image]()\n![image]()\n\n\n\nBelow are some basic tips for identifying this kind of problem where we could use the sliding window technique:\n\n* The problem will be based on an array, string, or list data structure.\n* You need to find the subrange in this array or string that should provide the longest, shortest, or target values.\n* A classic problem: to find the largest/smallest sum of given k (for example, three) consecutive numbers in an array.\n\nThe length can be **fixed**, as in the example above, or it can be **dynamic**, just like in this problem.\n\nSo to solve this problem, we can use the hash table and iterate over our term. Let\'s do two checks on 0 and 1 so as not to waste extra time. Now we can start, in the picture above you can see our **window** (blue rectangle) and its movement during the scan. We gradually add our letters to the **hash table**, and if it already contains this letter, we delete the letter corresponding to the leftmost index, do this until we get to the desired one and delete the repetition. Only after that we add our new element. \nThe maximum length is found by comparing our current length with the new one, using **Math.max**.\n\nIn the picture you can see all the movement of the window and the state of our hash table.\n\n\n```\nvar lengthOfLongestSubstring = function (s) {\n let set = new Set();\n let left = 0;\n let maxSize = 0;\n\n if (s.length === 0) return 0;\n if (s.length === 1) return 1;\n\n for (let i = 0; i < s.length; i++) {\n\n while (set.has(s[i])) {\n set.delete(s[left])\n left++;\n }\n set.add(s[i]);\n maxSize = Math.max(maxSize, i - left + 1)\n }\n return maxSize;\n}\n```\n\nI hope I was able to explain clearly.\n**Happy coding**! \uD83D\uDE43\n
218
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
4,856
9
# First Approach\n- Using set stl.\n- Time complexity: O(2*n)~O(n)\n- Space complexity: O(n) \n# Code\n```\nlass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n unordered_set<char> t;\n int m=0;\n int l=0,r=0;\n while(r<s.size())\n {\n //To eliminate the below loop for finding the index of \n //repeated character use the below approach by storing the\n //indicies using a vector or hasmap.\n while(t.find(s[r])!=t.end())\n {\n t.erase(s[l]);\n l++;\n }\n t.insert(s[r]);\n m=max(m,r-l+1);\n r++;\n \n }\n return m;\n \n }\n};\n```\n\n# Approach for optimization\n- Using index array\n\n# Complexity\n- Time complexity: O(n) \n- Space complexity: O(1) \n\n\n# Code\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n vector<int> m(256,-1); //index array \n int len=0;\n\n int r=0,l=0;\n while(r<s.size())\n {\n if(m[s[r]]!=-1 and l<m[s[r]]+1)\n {\n l=m[s[r]]+1; \n }\n m[s[r]]=r;\n len=max(len,r-l+1);\n r++;\n }\n return len;\n \n }\n};\n```\n
219
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
61
7
\n# Code\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n int len = s.length(), ans=0;\n Map<Character,Integer> ht = new HashMap(); \n for(int i=0,j=0;j<len;j++){\n if(ht.containsKey(s.charAt(j)))i=Math.max(ht.get(s.charAt(j)),i);\n ans=Math.max(ans,j-i+1);\n ht.put(s.charAt(j),j+1);\n }\n return ans;\n }\n}\n```
222
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
8,672
7
See Code and Explanation : **\u2B50[]()\u2B50**\n\n**Examples : C# - HashSet**\n```\npublic class Solution {\n public int LengthOfLongestSubstring(string s) {\n \n if(string.IsNullOrEmpty(s))\n {\n return 0;\n }\n\n HashSet<char> hSet = new HashSet<char>();\n int max = 0;\n int i = 0;\n int j = 0;\n \n while(i<s.Length)\n {\n if(!hSet.Contains(s[i]))\n {\n hSet.Add(s[i]);\n i++;\n \n }\n else\n {\n max = Math.Max(max,hSet.Count);\n hSet.Remove(s[j]);\n j++;\n }\n }\n max = Math.Max(max,hSet.Count);\n return max;\n \n }\n}\n```\n\n**Examples : C# - Dictionary**\n```\npublic class Solution {\n public int LengthOfLongestSubstring(string s) {\n Dictionary<char,int> dict = new Dictionary<char,int>();\n int max = 0;\n \n for (int i = 0;i < s.Length;i++)\n {\n char c = s[i];\n if (!dict.ContainsKey(c))\n {\n dict.Add(c, i);\n max = Math.Max(dict.Count, max);\n }\n else\n {\n i = dict[c] ;\n dict.Clear();\n }\n }\n return max; \n }\n}\n```\n\n\nIf you got any problem about the explanation or you need other programming language solution, please feel free to leave your comment.\n\n\uD83E\uDDE1See more problems solutions - **[Zyrastory - LeetCode Solution]()**\n\nThanks!
223
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
202,104
1,094
int lengthOfLongestSubstring(string s) {\n vector<int> dict(256, -1);\n int maxLen = 0, start = -1;\n for (int i = 0; i != s.length(); i++) {\n if (dict[s[i]] > start)\n start = dict[s[i]];\n dict[s[i]] = i;\n maxLen = max(maxLen, i - start);\n }\n return maxLen;\n }
224
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
1,276
10
```\nint lengthOfLongestSubstring(string s) {\n vector<int> dict(256, -1);\n int maxLen = 0, start = -1;\n for (int i = 0; i != s.length(); i++) {\n if (dict[s[i]] > start)\n start = dict[s[i]];\n dict[s[i]] = i;\n maxLen = max(maxLen, i - start);\n }\n return maxLen;\n }\n```
226
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
23,483
96
# JAVA Code\n``` JAVA []\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n Set<Character>set=new HashSet<>();\n int maxLength=0;\n int left=0;\n for(int right=0;right<s.length();right++){\n \n if(!set.contains(s.charAt(right))){\n set.add(s.charAt(right));\n maxLength=Math.max(maxLength,right-left+1);\n \n }else{\n while(s.charAt(left)!=s.charAt(right)){\n set.remove(s.charAt(left));\n left++;\n }\n set.remove(s.charAt(left));left++;\n set.add(s.charAt(right));\n }\n \n }\n return maxLength;\n }\n}\n```\n\n### hey friend, why not upvote? \uD83E\uDD72\n\n![upvote_me.jpeg]()\n
227
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
39,447
508
A solution for beginners, which is straightforward, easy to understand, without too many complications and room to optimize once you understand the basic premise of the question. Hope this helps!\n\nTime Complexity: O(n)\nSpace Complexity: O(min of a,b) for the unordered set. a, is the upper bound of the space complexity.\nWhere a: Size of the string\nb: Size of the number of characters in the character-set\n\n\tclass Solution {\n\tpublic:\n\t\tint lengthOfLongestSubstring(string s) \n\t\t{\n\t\t\tunordered_set<char> set;\n \n\t\t\tint i = 0, j = 0, n = s.size(), ans = 0;\n \n\t\t\twhile( i<n && j<n)\n\t\t\t{\n\t\t\t\tif(set.find(s[j]) == set.end()) //If the character does not in the set\n\t\t\t\t{\n\t\t\t\t\tset.insert(s[j++]); //Insert the character in set and update the j counter\n\t\t\t\t\tans = max(ans, j-i); //Check if the new distance is longer than the current answer\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tset.erase(s[i++]); \n\t\t\t\t\t/*If character does exist in the set, ie. it is a repeated character, \n\t\t\t\t\twe update the left side counter i, and continue with the checking for substring. */\n\t\t\t\t}\n\t\t\t}\n \n\t\t\treturn ans;\n\t\t}\n\t};
228
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
1,016
14
```\ndef lengthOfLongestSubstring(self, s: str) -> int:\n maxLength = 0\n dict = {}\n\n i,j = 0,0\n n = len(s)\n\n while(j < n):\n c = s[j] \n \n dict[c] = 1 if not c in dict else dict[c] + 1\n \n \n if dict[c] > 1:\n while(dict[c] > 1):\n dict[s[i]] -= 1\n i += 1\n \n maxLength = max(maxLength, j - i + 1)\n j += 1\n\n return maxLength\n```
235
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
17,285
111
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have to find the length of longest substring which does not contain any repeating characters\n\nThe first thing which should come in our mind is to traverse in the string and store the frequence of each character in a map type of "map<char ,int>" and try to maintain frequency of all the characters present in the map to 1 and storing the maximum length \n\n\n# Approach\n1:- We will first iterate over the string and store the frequencies of all the character we have visited in a map of type "map<char ,int>"\n\n2:- In each iteration we will check if the frequency of character at ith index is greater than one.....if yes it means that that character is repeated twice in our map so we will start erasing all the characters from the starting jth index untill we delete the same character which is repeated twice...... from the left\n\nex :- `Input: s = "abcabcbb"`\n\n`i=0 mp:{[a:1]}`\n|| length =1 , maxlength = 1 \n\n`i=1 mp:{[a:1] , [b:1]}`\n|| length =2 , maxlength = 2\n\n`i=2 mp:{[a:1] , [b:1] , [c:1]}`\n|| length =3 , maxlength = 3\n\n`i=3 mp:{[a:2] , [b:1] , [c:1]}`\n|| length =4 , maxlength =3\n\n\'a\' appeared 2 times , so we will start removing characters from the left untill the frequency of \'a\' becomes 1 again.\nwhile(mp[a]>1) , we will decrease the frequency of all the characters from left i.e. "mp[s[j++]]--" ......Variable j stores the starting index of our subarray , Initially it is 0 but as we start deleting characters from left , this j will be get increment....that is why we did j++ there.\nwhen j=0 , mp[s[j++]] will get decrease by one and the frequency of a will again be equal to 1\n\n`i=3 mp:{[a:1] , [b:1] , [c:1]}`\n|| length =3 , maxlength =3\n\n3:- In each iteration we will take the maximum of (maxlength ,length) and store it in max length\n\nThis process will continue till we reach the end of the string and will return maxlength which is the length of longest substring with no repeating characters in it \n\n\n\n\n# Code\n```\n int lengthOfLongestSubstring(string s) {\n int length=0 , maxlength=0,j=0;\n map<char ,int> mp;\n for(int i=0 ;i<s.size(); i++){\n mp[s[i]]++;\n length++;\n while(mp[s[i]]>1){\n mp[s[j++]]--;\n length--;\n }\n maxlength = max(maxlength,length);\n }\n return maxlength;\n }\n```\n\n# Please do upvote if you like the Explanation
236
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
2,743
25
\n\n# Code\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n l=len(s)\n if l==0:\n return 0\n dicts={}\n max_len=0\n start=0\n for i in range(l):\n if s[i] in dicts and start<=dicts[s[i]]:\n start = dicts[s[i]]+1\n else:\n max_len=max(max_len,i-start+1)\n dicts[s[i]]=i\n return max_len\n \n```\n![7abc56.jpg]()\n
237
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
915
5
```\n/*\nTo Solve this problem we need to have two pointers that both start at 0 index, or the first char of the given\nstring, and an empty set also a var for the longestSubstringLength We start looping over the string chars and\ncheck if the char is not in our set we add it to the set then we move the right pointer, increasing the sliding window, get\nthe max between longestSubstringLength, which is intialized as 0 and our chars set size or length, and so on untill \nwe find a char existed in the list, if so we delete the first char in our set then we increase the left pointer to start\nfrom the next Letter\n */\n \n const lengthOfLongestSubstring = (string) => {\n\t// Left and right pointers\n let left = 0;\n let right = 0;\n\t// Longest Sub and our empty Set\n let longestSub = 0;\n let charsSet = new Set();\n\n while(right < string.length) {\n\t\t// The set doesn\'t contain the char\n if(!charsSet.has(string[right])) {\n charsSet.add(string[right]);\n longestSub = Math.max(longestSub, charsSet.size);\n right++;\n\n } else {\n\t\t// The char is found in our set\n charsSet.delete(string[left]);\n left++;\n }\n } \n return longestSub;\n}
238
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
115,713
906
The idea is use a hash set to track the longest substring without repeating characters so far, use a fast pointer j to see if character j is in the hash set or not, if not, great, add it to the hash set, move j forward and update the max length, otherwise, delete from the head by using a slow pointer i until we can put character j to the hash set.\n\n public int lengthOfLongestSubstring(String s) {\n int i = 0, j = 0, max = 0;\n Set<Character> set = new HashSet<>();\n \n while (j < s.length()) {\n if (!set.contains(s.charAt(j))) {\n set.add(s.charAt(j++));\n max = Math.max(max, set.size());\n } else {\n set.remove(s.charAt(i++));\n }\n }\n \n return max;\n }
239
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
22,487
348
Lets start with the following example: \n\n**Assume you had no repeating characters** (In below example, just look at *first three* characters)\n\nWe take two pointers, `l` and `r`, both starting at `0`. At every iteration, we update the longest string with non-repeating characters found = `r-l+1` and just keep a note of which character we see at which index\n\n\n<img src="" width=400/>\n\n\n```python\n def lengthOfLongestSubstringSimpler(self, s):\n seen = {}\n left, right = 0, 0\n longest = 1\n while right < len(s):\n longest = max(longest, right - left + 1)\n seen[s[right]] = right\n right += 1\n return longest\n```\n\nAfter 3 iterations, if you were keeping a map of when you last saw the character, you\'d have something like this:\n\n<img src="" width=300/>\n\nat this point, `longest = r-l+1 = 2 - 0 + 1 = 3`\n\nNow, lets face it - our string _does_ have repeating characters. We look at index 3, we\'re realizing we\'ve seen `a` before. So we now, we can\'t just calculate the value of `longest` like we were doing before. We need to make sure our left pointer, or `l`, is at least past the index where we last saw `a` , thus - we move `l ` to ` seen[right]+1`. We also update our map with last seen of `a` to `3`\n\n<img src="" width=300/>\n\nAnd this interplay goes on\n\n<img src="" width=300/>\n\n\n```python\n def lengthOfLongestSubstring(self, s):\n """\n :type s: str\n :rtype: int \n """\n if len(s) == 0:\n return 0\n seen = {}\n left, right = 0, 0\n longest = 1\n while right < len(s):\n if s[right] in seen:\n left = seen[s[right]]+1\n longest = max(longest, right - left + 1)\n seen[s[right]] = right\n right += 1\n return longest\n```\n\nLife was good, until this test case came into our lives:\n`abba`\n\n<img src="" width=200/>\n\nAnd we realised, after 4 iterations, our left pointer was to be moved `seen[s[right]]+1 = seen[a] + 1 = 1` - wait what, left was to move back ? That doesn\'t sound correct - that\'d give us longest to be 3 (bba) which is NOT CORRECT\n\nThus, we need to ensure that `l` always goes to the right of it, or just stays at its position\n\nIn other words;\n\n```python\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n """\n :type s: str\n :rtype: int abcabcbb\n """\n if len(s) == 0:\n return 0\n seen = {}\n left, right = 0, 0\n longest = 1\n while right < len(s):\n if s[right] in seen:\n left = max(left,seen[s[right]]+1)\n longest = max(longest, right - left + 1)\n seen[s[right]] = right\n right += 1\n print(left, right, longest)\n return longest\n```\n\nThanks, and don\'t forget to upvote if it helped you !\n\n\n\n**BONUS** Trying to be a strong Java Developer ? Checkout this [awesome hands-on series]() with illustrations! \n
246
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
1,519
6
\n\n# Approach\nSliding Window Technique with Set:\n\nThe function uses a set data structure to keep track of the characters in the current window (substring) without any duplicates.\nIt also uses two pointers start and end to define the current window. The start pointer represents the beginning of the current substring, and the end pointer represents the end of the substring.\nLoop through the String:\n\nThe function uses a while loop that continues until the start pointer reaches the end of the string s.\nIn each iteration of the loop, the function checks if the character at index start is already present in the set.\nIf the character is not present in the set, it means it is a new character in the current window. The function inserts it into the set and updates the maximum length max by comparing it with the length of the current window (start - end + 1).\nIf the character is already present in the set, it means the window needs to be shifted to the right. The function erases the character at index end from the set and increments the end pointer to move the window one step to the right.\nUpdating Window and Maximum Length:\n\nThe function continues this process, sliding the window to the right and updating the set and maximum length, until the start pointer reaches the end of the string.\nOutput:\n\nThe function returns the maximum length of the substring without repeating characters, which is stored in the max variable.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(NlogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(1) \n0(27) WORST CASE\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s)\n {\n set<char>set;\n int max = 0;\n int start = 0;\n int end = 0;\n while(start<s.size())\n {\n auto it = set.find(s[start]);\n if(it==set.end()) //it searches the element in the set \n {\n if(start-end+1>max) //if the difference btw start and end is incresed then update max\n {\n max=start-end+1;\n }\n set.insert(s[start]); //and also insert the character to the set\n start++;\n }\n else\n {\n // if else is not unique then delete that element at end and increment end\n set.erase(s[end]);\n end++;\n }\n }\n return max;\n }\n};\n```
247
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
864
19
# Intuition\nUpon encountering this problem, my initial instinct is to utilize the sliding window technique to identify the length of the longest substring without repeating characters.\n\n# Approach\nMy approach to tackling this problem involves implementing the sliding window technique to ascertain the length of the longest substring that does not contain any repeated characters. To do so, I maintain a HashSet called `uniqueChars` to keep track of the characters present in the current window. Additionally, two pointers named `start` and `end` denote the beginning and end of the present substring segment. Furthermore, a variable named `maxSubstringLength` is utilized to track the length of the longest valid substring.\n\nThe algorithm operates as follows:\n1. While the `end` pointer remains within the bounds of the string:\n - If the character at the `end` position is not present in the `uniqueChars` set:\n - Add the character to the set.\n - Update the `maxSubstringLength` by comparing it to the length of the current substring (`end - start + 1`).\n - Increment the `end` pointer.\n - If the character at the `end` position is already in the `uniqueChars` set:\n - Remove the character at the `start` position from the set.\n - Increment the `start` pointer to slide the window to the right.\n\nUpon completing the iteration, the algorithm returns the calculated `maxSubstringLength`.\n\nThis sliding window approach efficiently identifies the length of the longest substring without repeating characters, accomplishing the task in a single traversal of the string.\n\n# Complexity\n- Time complexity: O(n)\n The algorithm traverses the provided string once, performing constant-time operations at each step.\n\n- Space complexity: O(k)\n The algorithm employs a HashSet named `uniqueChars` to store distinct characters in the current window. In the worst case, the HashSet may contain all characters from the input string, leading to a space complexity of O(k), where k is the size of the character set.\n\n# Code\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\nHashSet<Character> uniqueChars = new HashSet<>();\n int start = 0;\n int end = 0;\n int maxSubstringLength = 0;\n\n while (end < s.length()) {\n if (!uniqueChars.contains(s.charAt(end))) {\n uniqueChars.add(s.charAt(end));\n maxSubstringLength = Math.max(maxSubstringLength, end - start + 1);\n end++;\n } else {\n uniqueChars.remove(s.charAt(start));\n start++;\n }\n }\n\n return maxSubstringLength;\n }\n}\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]()
249
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
3,760
9
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n start=0\n count=0\n for end in range(1,len(s)+1):\n if len(set(s[start:end]))==len(s[start:end]):\n if (end-start+1)>count:\n count=len(s[start:end])\n else:\n start+=1\n return(count)\n\n```
252
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
2,555
5
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSliding window technique , we maintain a window of unique characters and move it to the right until we find a repeating character. We then remove the leftmost character from the window and continue the process until we reach the end of the string.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Maintains a list arr to store the current substring being considered. It also maintains three variables: mc to store the maximum length of the substring seen so far, c to store the length of the current substring being considered, and p to store the position of the leftmost character in the current substring.\n- Iterates over the input string s and checks if the current character is already present in the arr list. If it is, it updates the mc variable with the maximum length seen so far, resets the c variable to 0, sets the index i to p, increments p by 1, and clears the arr list. If the current character is not present in the arr list, it adds the character to the arr list and increments the c variable. Finally, the code returns the maximum of c and mc as the length of the longest substring without repeating characters\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int lengthOfLongestSubstring(String s) {\n List<Character> arr=new ArrayList<>();\n int mc=0,c=0,p=1;\n for(int i=0;i<s.length();i++){\n if(arr.contains(s.charAt(i))){\n mc = c>mc ? c:mc;\n c=0;\n i=p;\n p=p+1;\n arr=new ArrayList<>();\n }\n c++;\n arr.add(s.charAt(i));\n }\n return c>mc ? c:mc;\n }\n}\n```
253
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
26,459
259
```\nclass Solution {\npublic:\n int lengthOfLongestSubstring(string s) {\n \n //SLIDING WINDOW - TIME COMPLEXITY O(2n)\n // SPACE COMPLEXITY O(m) //size of array\n \n int store[256]={0}; //array to store the occurences of all the characters\n int l=0; //left pointer\n int r=0; //right pointer\n int ans=0; //initializing the required length as 0\n \n while(r<s.length()) //iterate over the string till the right pointer reaches the end of the string \n {\n store[s[r]]++; //increment the count of the character present in the right pointer \n \n while(store[s[r]]>1) //if the occurence become more than 1 means the char is repeated\n { \n store[s[l]]--; //reduce the occurence of temp as it might be present ahead also in the string\n l++; //contraction of the present window till the occurence of the \'t\' char becomes 1\n }\n \n ans = max(ans,r-l+1); //As the index starts from 0 , ans will be (right pointer-left pointer + 1)\n r++; // now will increment the right pointer \n }\n return ans;\n }\n};\n```\n**If you like it, Do upvote \nHappy Coding;**\n\n
262
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
882
6
\n# Code\n```\nclass Solution {\npublic:\n \n int lengthOfLongestSubstring(string s) {\n int n=s.length();\n int ans=0;\n map<char,int> mpp;\n int l=0;\n for(int i=0;i<n;i++){\n if(mpp.find(s[i])==mpp.end())\n {\n ans=max(ans,i-l+1);\n }else{\n if(mpp[s[i]]<l){\n ans=max(ans,i-l+1);\n }else{\n l=mpp[s[i]]+1;\n }\n }\n mpp[s[i]]=i;\n }\n return ans;\n }\n};\n```
277
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
8,070
12
# Intuition\nwe use a **starting point** while iterating over the given string and every time we find a repeated character we calculate the length of the substring between the starting point and the current point - 1.\nevery time we find a repetition we set the starting point to the character next to the last occurrence.\n\n**Ex :** consider the string **`abcdae`**\n\nthe starting point will be $$0$$ initially, we keep iterating until we find the second **`a`**. we calculate then the length of the substring **`abcd`** and then set the starting point to the character next to the first **`a`**, which is **`b`**.\nthen, we will keep iterating until the end since there are no more repetitions and the answer will be $$5$$ (the length of **`bcdae`**).\n\n# Approach\nwe will need $$2$$ variables: \n1. $$`longest`$$ to **save the length of the longest substring found**\n2. $$`offset`$$ for **the starting point**.\n\nwe will also need to save the encountered characters to check repetition, a dictionary will be ideal for this case as it doesn\'t allow repetition. for that we will use an extra variable \n- $$`indexes`$$: to save characters and their indexes, **characters** will be **keys** and **indexes** will be **values**.\n\nwe start then: for every character: \n1. we get its index from indexes dictionary.\n2. if the index wasn\'t null `(meaning that it was encountered before)`, we check if its index is **greater or equal to the offset** `(meaning that its in the current substring)`.\nif so :\n - we calculate the length of the substring : $$i\\,(current\\: position) - offset$$\n - we set the offset to the next character of the last occurrence : $$index\\,(last\\:occurrence) + 1$$\n - if the length of this substring is greater than the length of the current longest substring, we update it\n3. we update the index of the last occurrence of the current character (or add it if this is its first occurrence).\n\nFinally, we return the **maximum** between $$`longest`$$ and **the length of the last substring** `(which is equal to the difference between the length of the string and offset)`as it contains **no repeated characters** and its length is **never compared** to $$`longest`$$ because **we get out of the loop**.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n longest = 0\n indexes = {}\n offset = 0\n for i in range(len(s)):\n char = s[i]\n index = indexes.get(char)\n if index is not None and index >= offset:\n length = i - offset\n offset = index + 1\n if length > longest:\n longest = length\n indexes[char] = i\n return max(longest, (len(s) - offset))\n```
278
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
2,281
10
# Intuition\nTo find the length of the longest substring without repeating characters in a given string "s", you can use the "Sliding Window" technique. Here\'s the general idea:\n\nCreate two pointers, "start" and "end", initially set to 0.\nUse a hash set to store the characters in the current substring.\nWhile "end" is less than the length of the string:\na. If the character at "end" is not in the hash set, add it and move the "end" pointer to the right.\nb. If the character at "end" is already in the hash set, remove the character at "start" from the hash set and move the "start" pointer to the right.\nThe length of the longest substring is the maximum distance between the "start" and "end" pointers.\n# Approach\nWhile "end" is less than the length of the string:\na. If the character at "end" is not in the hash set, add it to the hash set and move the "end" pointer to the right.\nb. If the character at "end" is already in the hash set, remove the character at "start" from the hash set and move the "start" pointer to the right.\nThis way, the "start" and "end" pointers are moved towards each other until a repeating character is found, at which point the "start" pointer is moved to the right to exclude the repeating character. The process continues until the "end" pointer reaches the end of the string.\n\nThe length of the longest substring without repeating characters is equal to the maximum distance between the "start" and "end" pointers. The time complexity of this approach is O(n), where n is the length of the string.\n\n# Complexity\n- Time complexity:\no(n)\n\n- Space complexity:\n O(k), where k is the number of unique characters in the string.\n\n# Code\n```\nclass Solution {\npublic:\n\n\n\n int lengthOfLongestSubstring(string s) {\n int start = 0, end = 0, max_len = 0;\n unordered_set<char> char_set;\n\n while (end < s.length()) {\n if (char_set.find(s[end]) == char_set.end()) {\n char_set.insert(s[end]);\n end++;\n max_len = max(max_len, end - start);\n } else {\n char_set.erase(s[start]);\n start++;\n }\n }\n\n return max_len;\n }\n};\n```
281
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
12,446
117
### Logic:\nThis difficulty in this question is finding out where to pick our next substring once we\'ve spotted a duplicate character. Using two pointers and a sliding window, we can quite easily choose what substring we want to look at. In fact, finding the longest substring without repeating characters becomes even easier once you realise the following observation.\n\n**Key Observation:**\n> Once we\'ve landed on a character we\'ve seen before, we want to move the left pointer of our window to the index *after* the last occurrence of that character.\n\nPay attention to the following example with the input string `s = "babcadba"` to see this in action:\n\n![image]()\n\nAs you can see, our `nextIndex[]` array functions as both a hashset and a way to keep track of indexes. In particular, our array is storing the index AFTER the last occurrence of any character. That way, our left pointer can move directly there. \n___\n### How does this work in code?\nTurns out characters can function as integers. As such, we can use the characters themselves to access values of our `nextIndex[]` array. We\'ll need an array that has range: [0, 128) as that covers all ASCII characters that could be used in this question. \n\nSince we\'re working with two pointers, we can quite conveniently find the length of our current window using `r - l + 1`. We can update this anytime it\'s larger than our current maximum.\n\nAwesome. Now we\'re ready to start coding!\n\n___\n### Code\nIf you have any questions, suggestions or improvements, feel free to let me know. Thanks for reading!\n```java\npublic int lengthOfLongestSubstring(String s) {\n\tint n = s.length(), longest = 0;\n\tint[] nextIndex = new int[128]; \n\n\tfor (int r=0, l=0; r<n; r++) {\n\t\tl = Math.max(nextIndex[s.charAt(r)], l); \n\t\tlongest = Math.max(longest, r - l + 1);\n\t\tnextIndex[s.charAt(r)] = r + 1;\n\t}\n\n\treturn longest;\n}\n```\n**Time Complexity:** `O(n)` where `n` is the length of the string.\n**Space Complexity:** `O(128)` for the `nextIndex` array.
286
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
181,603
632
class Solution:\n # @return an integer\n def lengthOfLongestSubstring(self, s):\n start = maxLength = 0\n usedChar = {}\n \n for i in range(len(s)):\n if s[i] in usedChar and start <= usedChar[s[i]]:\n start = usedChar[s[i]] + 1\n else:\n maxLength = max(maxLength, i - start + 1)\n \n usedChar[s[i]] = i\n \n return maxLength
291
Longest Substring Without Repeating Characters
longest-substring-without-repeating-characters
Given a string s, find the length of the longest substring without repeating characters.
Hash Table,String,Sliding Window
Medium
null
13,990
81
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\nThis solution employs storage of positions and calculation of their differences for repeated characters. Time complexity is linear: **O(N)**. Space complexity is constant: **O(1)**. \n\n| Language | [**Python**]() | [**C++**]() | [**Java**]() | [**Rust**]() | \n|---|---|---|---|---|\n| Runtime | **62 ms (95.17%)** | **0 ms (100.00%)** | **2 ms (100.00%)** | **0 ms (100.00%)** |\n| Memory | **14.0 MB (93.06%)** | **7.6 MB (87.55%)** | **42.1 MB (98.23%)** | **7.6 MB (87.55%)** |\n\n<iframe src="" frameBorder="0" width="800" height="600"></iframe>
294
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Array,Binary Search,Divide and Conquer
Hard
null
1,050
59
I made a super detailed video walkthrough, since this is a really tough question \uD83D\uDE42 \nPlease upvote if you find this helpful!\n\n\n\nCode:\n```\nclass Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n if len(nums1) > len(nums2):\n nums1, nums2 = nums2, nums1\n \n m, n = len(nums1), len(nums2)\n left, right = 0, m\n N = m + n\n\n while left <= right:\n A = (left + right) // 2\n B = ((N + 1) // 2) - A\n\n x1 = -float("inf") if A - 1 < 0 else nums1[A - 1]\n y1 = float("inf") if A == m else nums1[A]\n x2 = -float("inf") if B - 1 < 0 else nums2[B - 1]\n y2 = float("inf") if B == n else nums2[B]\n\n if x1 <= y2 and x2 <= y1:\n if N % 2 == 0:\n return (max(x1, x2) + min(y1, y2)) / 2\n else:\n return max(x1, x2)\n elif x1 > y2:\n right = A - 1\n else:\n left = A + 1\n```
300
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Array,Binary Search,Divide and Conquer
Hard
null
46,767
802
# Problem Understanding:\nIn simpler terms, you need to **find the middle value of the combined**, sorted array formed by merging nums1 and nums2. If the combined **array has an even number** of elements, you should return the average of the two middle values. **If it has an odd number of elements, you should return the middle value itself.**\n<!-- Describe your first thoughts on how to solve this problem. -->\n# Hint:\n```Hint1 []\nThink of a brute force approach.\n```\n```Hint2 []\nDo you think how two pointer will help us?\n```\n```Hint3 []\nCan you observe the fact that the given arrays are sorted?\n```\n**I would recommend you, don\'t jump directly on solution.**\n# Approach 1: Merge and Sort\n- **Create a new array** with a size equal to the total number of elements in both input arrays.\n- **Insert elements** from both input arrays into the new array.\n- **Sort the new array.**\n- **Find and return the median of the sorted array.**\n\n**Time Complexity**\n- In the worst case TC is **O((n + m) * log(n + m))**.\n\n**Space Complexity**\n - **O(n + m)**, where \u2018n\u2019 and \u2018m\u2019 are the sizes of the arrays.\n# Approach 2: Two-Pointer Method\n\n- **Initialize two pointers**, i and j, both initially set to 0.\n- **Move the pointer** that corresponds to the **smaller value forward at each step.**\n- Continue moving the pointers **until you have processed half of the total number of elements.**\n- Calculate and **return the median** based on the values pointed to by i and j.\n\n\n**Time Complexity**\n- **O(n + m)**, where \u2018n\u2019 & \u2018m\u2019 are the sizes of the two arrays.\n\n**Space Complexity**\n - **O(1)**.\n\n# Approach 3: Binary Search\n\n- **Use binary search to partition the smaller of the two input arrays into two parts.**\n- Find the partition of the **larger array such that the sum of elements on the left side of the partition in both arrays is half of the total elements.**\n- Check if this partition **is valid by verifying** if the largest number on the left side is smaller than the smallest number on the right side.\n- **If the partition is valid,** calculate and return the median.\n\n**Time Complexity**\n- **O(logm/logn)**\n\n**Space Complexity**\n - **O(1)**\n\n---\n\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n\n---\n\n\n<!-- Describe your approach to solving the problem. -->\n# Code Brute Force- Merge and Sort\n```C++ []\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n // Get the sizes of both input arrays.\n int n = nums1.size();\n int m = nums2.size();\n\n // Merge the arrays into a single sorted array.\n vector<int> merged;\n for (int i = 0; i < n; i++) {\n merged.push_back(nums1[i]);\n }\n for (int i = 0; i < m; i++) {\n merged.push_back(nums2[i]);\n }\n\n // Sort the merged array.\n sort(merged.begin(), merged.end());\n\n // Calculate the total number of elements in the merged array.\n int total = merged.size();\n\n if (total % 2 == 1) {\n // If the total number of elements is odd, return the middle element as the median.\n return static_cast<double>(merged[total / 2]);\n } else {\n // If the total number of elements is even, calculate the average of the two middle elements as the median.\n int middle1 = merged[total / 2 - 1];\n int middle2 = merged[total / 2];\n return (static_cast<double>(middle1) + static_cast<double>(middle2)) / 2.0;\n }\n }\n};\n\n```\n```Java []\nimport java.util.Arrays;\n\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n // Get the sizes of both input arrays.\n int n = nums1.length;\n int m = nums2.length;\n\n // Merge the arrays into a single sorted array.\n int[] merged = new int[n + m];\n int k = 0;\n for (int i = 0; i < n; i++) {\n merged[k++] = nums1[i];\n }\n for (int i = 0; i < m; i++) {\n merged[k++] = nums2[i];\n }\n\n // Sort the merged array.\n Arrays.sort(merged);\n\n // Calculate the total number of elements in the merged array.\n int total = merged.length;\n\n if (total % 2 == 1) {\n // If the total number of elements is odd, return the middle element as the median.\n return (double) merged[total / 2];\n } else {\n // If the total number of elements is even, calculate the average of the two middle elements as the median.\n int middle1 = merged[total / 2 - 1];\n int middle2 = merged[total / 2];\n return ((double) middle1 + (double) middle2) / 2.0;\n }\n }\n}\n\n```\n```python3 []\nclass Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n # Merge the arrays into a single sorted array.\n merged = nums1 + nums2\n\n # Sort the merged array.\n merged.sort()\n\n # Calculate the total number of elements in the merged array.\n total = len(merged)\n\n if total % 2 == 1:\n # If the total number of elements is odd, return the middle element as the median.\n return float(merged[total // 2])\n else:\n # If the total number of elements is even, calculate the average of the two middle elements as the median.\n middle1 = merged[total // 2 - 1]\n middle2 = merged[total // 2]\n return (float(middle1) + float(middle2)) / 2.0\n\n```\n\n\n# Code for Two-Pointer Method\n```C++ []\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n int n = nums1.size();\n int m = nums2.size();\n int i = 0, j = 0, m1 = 0, m2 = 0;\n\n // Find median.\n for (int count = 0; count <= (n + m) / 2; count++) {\n m2 = m1;\n if (i != n && j != m) {\n if (nums1[i] > nums2[j]) {\n m1 = nums2[j++];\n } else {\n m1 = nums1[i++];\n }\n } else if (i < n) {\n m1 = nums1[i++];\n } else {\n m1 = nums2[j++];\n }\n }\n\n // Check if the sum of n and m is odd.\n if ((n + m) % 2 == 1) {\n return static_cast<double>(m1);\n } else {\n double ans = static_cast<double>(m1) + static_cast<double>(m2);\n return ans / 2.0;\n }\n }\n};\n\n```\n```Java []\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n int n = nums1.length;\n int m = nums2.length;\n int i = 0, j = 0, m1 = 0, m2 = 0;\n\n // Find median.\n for (int count = 0; count <= (n + m) / 2; count++) {\n m2 = m1;\n if (i != n && j != m) {\n if (nums1[i] > nums2[j]) {\n m1 = nums2[j++];\n } else {\n m1 = nums1[i++];\n }\n } else if (i < n) {\n m1 = nums1[i++];\n } else {\n m1 = nums2[j++];\n }\n }\n\n // Check if the sum of n and m is odd.\n if ((n + m) % 2 == 1) {\n return (double) m1;\n } else {\n double ans = (double) m1 + (double) m2;\n return ans / 2.0;\n }\n }\n}\n\n```\n```python []\nclass Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n n = len(nums1)\n m = len(nums2)\n i = 0\n j = 0\n m1 = 0\n m2 = 0\n\n # Find median.\n for count in range(0, (n + m) // 2 + 1):\n m2 = m1\n if i < n and j < m:\n if nums1[i] > nums2[j]:\n m1 = nums2[j]\n j += 1\n else:\n m1 = nums1[i]\n i += 1\n elif i < n:\n m1 = nums1[i]\n i += 1\n else:\n m1 = nums2[j]\n j += 1\n\n # Check if the sum of n and m is odd.\n if (n + m) % 2 == 1:\n return float(m1)\n else:\n ans = float(m1) + float(m2)\n return ans / 2.0\n\n```\n\n\n# Code for Binary Search\n```C++ []\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int> &nums1, vector<int> &nums2) {\n int n1 = nums1.size(), n2 = nums2.size();\n \n // Ensure nums1 is the smaller array for simplicity\n if (n1 > n2)\n return findMedianSortedArrays(nums2, nums1);\n \n int n = n1 + n2;\n int left = (n1 + n2 + 1) / 2; // Calculate the left partition size\n int low = 0, high = n1;\n \n while (low <= high) {\n int mid1 = (low + high) >> 1; // Calculate mid index for nums1\n int mid2 = left - mid1; // Calculate mid index for nums2\n \n int l1 = INT_MIN, l2 = INT_MIN, r1 = INT_MAX, r2 = INT_MAX;\n \n // Determine values of l1, l2, r1, and r2\n if (mid1 < n1)\n r1 = nums1[mid1];\n if (mid2 < n2)\n r2 = nums2[mid2];\n if (mid1 - 1 >= 0)\n l1 = nums1[mid1 - 1];\n if (mid2 - 1 >= 0)\n l2 = nums2[mid2 - 1];\n \n if (l1 <= r2 && l2 <= r1) {\n // The partition is correct, we found the median\n if (n % 2 == 1)\n return max(l1, l2);\n else\n return ((double)(max(l1, l2) + min(r1, r2))) / 2.0;\n }\n else if (l1 > r2) {\n // Move towards the left side of nums1\n high = mid1 - 1;\n }\n else {\n // Move towards the right side of nums1\n low = mid1 + 1;\n }\n }\n \n return 0; // If the code reaches here, the input arrays were not sorted.\n }\n};\n\n\n```\n```Java []\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n int n1 = nums1.length, n2 = nums2.length;\n \n // Ensure nums1 is the smaller array for simplicity\n if (n1 > n2)\n return findMedianSortedArrays(nums2, nums1);\n \n int n = n1 + n2;\n int left = (n1 + n2 + 1) / 2; // Calculate the left partition size\n int low = 0, high = n1;\n \n while (low <= high) {\n int mid1 = (low + high) >> 1; // Calculate mid index for nums1\n int mid2 = left - mid1; // Calculate mid index for nums2\n \n int l1 = Integer.MIN_VALUE, l2 = Integer.MIN_VALUE, r1 = Integer.MAX_VALUE, r2 = Integer.MAX_VALUE;\n \n // Determine values of l1, l2, r1, and r2\n if (mid1 < n1)\n r1 = nums1[mid1];\n if (mid2 < n2)\n r2 = nums2[mid2];\n if (mid1 - 1 >= 0)\n l1 = nums1[mid1 - 1];\n if (mid2 - 1 >= 0)\n l2 = nums2[mid2 - 1];\n \n if (l1 <= r2 && l2 <= r1) {\n // The partition is correct, we found the median\n if (n % 2 == 1)\n return Math.max(l1, l2);\n else\n return ((double)(Math.max(l1, l2) + Math.min(r1, r2))) / 2.0;\n }\n else if (l1 > r2) {\n // Move towards the left side of nums1\n high = mid1 - 1;\n }\n else {\n // Move towards the right side of nums1\n low = mid1 + 1;\n }\n }\n \n return 0; // If the code reaches here, the input arrays were not sorted.\n }\n}\n\n```\n```python []\nclass Solution:\n def findMedianSortedArrays(self, nums1, nums2):\n n1 = len(nums1)\n n2 = len(nums2)\n \n # Ensure nums1 is the smaller array for simplicity\n if n1 > n2:\n return self.findMedianSortedArrays(nums2, nums1)\n \n n = n1 + n2\n left = (n1 + n2 + 1) // 2 # Calculate the left partition size\n low = 0\n high = n1\n \n while low <= high:\n mid1 = (low + high) // 2 # Calculate mid index for nums1\n mid2 = left - mid1 # Calculate mid index for nums2\n \n l1 = float(\'-inf\')\n l2 = float(\'-inf\')\n r1 = float(\'inf\')\n r2 = float(\'inf\')\n \n # Determine values of l1, l2, r1, and r2\n if mid1 < n1:\n r1 = nums1[mid1]\n if mid2 < n2:\n r2 = nums2[mid2]\n if mid1 - 1 >= 0:\n l1 = nums1[mid1 - 1]\n if mid2 - 1 >= 0:\n l2 = nums2[mid2 - 1]\n \n if l1 <= r2 and l2 <= r1:\n # The partition is correct, we found the median\n if n % 2 == 1:\n return max(l1, l2)\n else:\n return (max(l1, l2) + min(r1, r2)) / 2.0\n elif l1 > r2:\n # Move towards the left side of nums1\n high = mid1 - 1\n else:\n # Move towards the right side of nums1\n low = mid1 + 1\n \n return 0 # If the code reaches here, the input arrays were not sorted.\n\n```\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n![upvotememe.png]()\n\n\n
301
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Array,Binary Search,Divide and Conquer
Hard
null
98,483
656
*****SUGGESTION**:\nWhen we are trying to approach a problem, we should always start from brute force solution, even though you have been trained by solving a lot of similar problems previously and been able to give a O(N) solution off the top of your head, I still recommend you to start from a brute force solution. This is the only way you can avoid geting stuck in your fixed mindset when you encounter a completely unseen or unfamiliar problem that unfortunately doesn\'t match any existing pattern in your trained mind.***\n```\n// Brute Force:\n // 1.Merge Both Array\n // 2.Sort them\n // 3.Find Median\n // TIME COMPLEXITY: O(n)+O(nlogn)+O(n)\n // SPACE COMPLEXITY: O(1)\n \nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n // Initialization some neccessary variables\n vector<int>v;\n \n // store the array in the new array\n for(auto num:nums1) // O(n1)\n v.push_back(num);\n \n for(auto num:nums2) // O(n2)\n v.push_back(num);\n \n // Sort the array to find the median\n sort(v.begin(),v.end()); // O(nlogn)\n \n // Find the median and Return it\n int n=v.size(); // O(n)\n \n return n%2?v[n/2]:(v[n/2-1]+v[n/2])/2.0;\n }\n};\n\n** Accepted **\n```\n\n```\n// Optimized Using: Two Pointer with Extra Space\n // Time Complexity: O(m+n)\n // Space Complexity: O(m+n)\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n \n // Create a single sorted by merging two sorted arrays\n int n1=nums1.size();\n int n2=nums2.size();\n int i=0;\n int j=0;\n int lastindex=-1;\n \n // Initialize a new array\n vector<int>v(n1+n2,0);\n \n while(i<n1&&j<n2)\n {\n if(nums1[i]<=nums2[j])\n v[++lastindex]=nums1[i++];\n else\n v[++lastindex]=nums2[j++];\n }\n \n while(i<n1)\n v[++lastindex]=nums1[i++];\n while(j<n2)\n v[++lastindex]=nums2[j++];\n \n // Return the result\n int n=n1+n2;\n return n%2?v[n/2]:(v[n/2]+v[n/2-1])/2.0;\n \n }\n};\n\n** Accepted **\n```\n\n```\n// Optimized Using: Two Pointer without Extra Space (Insertion Sort)\n // Time Complexity: O(n1*n2)\n // Space Complexity: O(1)\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n \n // Calculate Total length of final array: O(N)\n int n1=nums1.size(); \n int n2=nums2.size();\n int n=n1+n2; \n \n // Edge Cases\n if(n2==0)\n return n1%2?nums1[n1/2]:(nums1[n1/2-1]+nums1[n1/2])/2.0;\n if(n1==0)\n return n2%2?nums2[n2/2]:(nums2[n2/2-1]+nums2[n2/2])/2.0;\n \n // Resize the array \'nums1\': O(N), N is size of resized array\n nums1.resize(n);\n \n // Now use pointer to compare arrays elements \n int i=0;\n int j=0;\n \n // Store all element in \'array 1\' in sorted order \n while(i<n1) // O(n1)\n {\n if(nums1[i]>nums2[0])\n {\n swap(nums1[i],nums2[0]); // O(1)\n // Rearrange Array nums2\n rearrangeArray(nums2); // O(n2)\n }\n i++;\n }\n \n // Store remaining elements of \'array 2\' in \'array 1\' \n while(j<nums2.size()) // O(n2)\n nums1[i++]=nums2[j++];\n \n // Return Result\n return n%2?nums1[n/2]:(nums1[n/2-1]+nums1[n/2])/2.0;\n \n }\n \n void rearrangeArray(vector<int>&nums2)\n {\n // Using insertion sort for insertion \n // worst case Time Complexity Would be: O(n)\n for(int i=1;i<nums2.size()&&nums2[i]<nums2[i-1];i++)\n swap(nums2[i],nums2[i-1]);\n }\n};\n\n** Accepted **\n```\n\n```\n// Optimized Approach: Using gap method:\n // Time Complexity: O((log base 2 power N)*(N))\n // Space Complexity: O(1)\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n \n // Do some pre-calculation : O(N)\n int n1=nums1.size();\n int n2=nums2.size();\n int n=n1+n2;\n \n // Now Create Two Pointer\n int gap=ceil((n1+n2)/2.0);\n int i=0;\n int j=gap;\n \n // Edge Cases\n if(n1==0)\n return n2%2?nums2[n2/2]:(nums2[n2/2]+nums2[n2/2-1])/2.0;\n \n if(n2==0)\n return n1%2?nums1[n1/2]:(nums1[n1/2]+nums1[n1/2-1])/2.0;\n \n // Apply gap method: O((log base 2 power N)*N)\n \n while(gap)\n { i=0;\n j=gap;\n // Move both pointer until they reach at last \n while(j<n)\n {\n // If \'i\' in \'nums1\' and \'j\' is also in \'nums1\'\n if(i<n1&&j<n1&&nums1[i]>nums1[j])\n swap(nums1[i],nums1[j]);\n else\n // if \'i\' in \'nums1\' and \'j\' is in \'nums2\'\n if(i<n1&&j>=n1&&nums1[i]>nums2[j-n1])\n swap(nums1[i],nums2[j-n1]);\n else \n // if \'i\' in \'nums2\' and \'j\' is also in \'nums2\'\n if(i>=n1&&j>=n1&&nums2[i-n1]>nums2[j-n1])\n swap(nums2[i-n1],nums2[j-n1]);\n \n // Move both pointer ahead by only one step\n i++;\n j++;\n }\n \n // Edge Case, because of \'ceil()\' gap never becomes zero\n if(gap==1)\n gap=0;\n \n gap=ceil(gap/2.0);\n } \n \n //Return Result\n if(n%2)\n return n/2<n1?nums1[n/2]:nums2[n/2-n1];\n else\n if(n/2<n1)\n return (nums1[n/2]+nums1[n/2-1])/2.0;\n else\n if((n/2-1)<n1)\n return (nums1[n/2-1]+nums2[n/2-n1])/2.0;\n else \n return (nums2[n/2-n1]+nums2[n/2-1-n1])/2.0;\n \n }\n};\n\n** Accepted **\n```\n\n```\n// Optimized Approach: Binary Search\n // Time Complexity: O(log(min(m,n)))\n // Space Complexity: O(1)\nclass Solution {\npublic:\n double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n \n // ** Intuition **\n // I have to find out correct left half and correct right half\n // i.e : // 7 , || 12 , 14 , 15 --> parition it\n // 1 , 2 , 3 , 4 , || 9 , 11 --> parition it\n // Now just findout max(left1,left2), min(right1,right2)\n \n \n // Initilaization of some neccessary variables\n int n1=nums1.size();\n int n2=nums2.size();\n int n=n1+n2;\n \n if(n1>n2) return findMedianSortedArrays(nums2,nums1);\n \n // When length is even, let\'s say 10 then left half length should be: (10+1)/2 =>5\n // When length is odd, let\'s say 11 then left half length should be: (11+1)/2 =>6\n // This mean that this formula gonna work in both condition\n int partition=(n+1)/2; \n \n \n // Edge Case\n if(n1==0)\n return n2%2?nums2[n2/2]:(nums2[n2/2]+nums2[n2/2-1])/2.0;\n \n if(n2==0)\n return n1%2?nums1[n1/2]:(nums1[n1/2]+nums1[n1/2-1])/2.0;\n \n // Now do Partioning\n int left1=0;\n int right1=n1;\n int cut1,cut2;\n int l1,r1,l2,r2;\n \n do\n { \n //Findout \'cut1\' and \'cut2\'\n cut1=(left1+right1)/2;\n cut2=partition-cut1;\n \n // Calculation for l1\n l1=cut1==0?INT_MIN:nums1[cut1-1];\n \n // Calculation for l2\n l2=cut2==0?INT_MIN:nums2[cut2-1];\n \n // Calculation for r1\n r1=cut1>=n1?INT_MAX:nums1[cut1];\n \n // Calculation for r2\n r2=cut2>=n2?INT_MAX:nums2[cut2];\n \n if(l1<=r2&&l2<=r1)\n // Return Result\n return n%2?max(l1,l2):(max(l1,l2)+min(r1,r2))/2.0;\n else\n \n if(l1>r2)\n right1=cut1-1;\n else\n left1=cut1+1;\n \n \n }while(left1<=right1);\n \n \n return 0.0;\n }\n};\n\n** Accepted **\n```\n\n***Please correct me if i take time complexity wrong.***\n\n***PLEASE UPVOTE IF YOU FIND IT A LITTLE BIT HELPFUL, MEANS A LOT ;)***
303
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
Array,Binary Search,Divide and Conquer
Hard
null
386
9
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n## 1. Initialize Variables:\n\n- m and n store the lengths of nums1 and nums2 arrays, respectively.\n- Create a new array res of size m + n to store the merged result.\n- Initialize variables i, j, and k to 0, representing the indices of nums1, nums2, and res, respectively.\n## 2. Merge Arrays:\n\n- Use a while loop to iterate through both arrays (nums1 and nums2) until either of them is exhausted.\n- Compare the elements at the current indices (i for nums1 and j for nums2).\n- Place the smaller element in the res array and increment the corresponding indices.\n## 3. Handle Remaining Elements:\n\n- After merging the arrays, there might be remaining elements in either nums1 or nums2.\n- Use two separate while loops to copy any remaining elements from both arrays to the res array.\n## 4. Calculate Median:\n\n- Determine the length of the merged array (ln).\n- Check if the length is even or odd.\n- If even, calculate the average of the middle two elements.\n- If odd, directly return the middle element.\n## 5. Return Result:\n\n- Return the calculated median\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: **O(N+M)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(N+M)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public double findMedianSortedArrays(int[] nums1, int[] nums2) {\n int m = nums1.length, n = nums2.length;\n int [] res = new int[n+m];\n int i=0, j=0, k=0;\n while(i<m && j<n){\n if(nums1[i]<nums2[j]) res[k++] = nums1[i++];\n else res[k++] = nums2[j++];\n }\n while(i<m) res[k++] = nums1[i++];\n while(j<n) res[k++] = nums2[j++];\n int ln = res.length;\n return ln%2==0 ? (double)(res[ln/2]+res[ln/2-1])/2 : res[ln/2];\n }\n}\n```\n![WhatsApp Image 2023-12-03 at 12.33.52.jpeg]()\n
308