title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
643 values
level
stringclasses
3 values
question_hints
stringclasses
869 values
view_count
int64
19
630k
vote_count
int64
5
3.67k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Count and Say
count-and-say
The count-and-say sequence is a sequence of digit strings defined by the recursive formula: To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying. For example, the saying and conversion for digit string "3322251": Given a positive integer n, return the nth term of the count-and-say sequence.
String
Medium
The following are the terms from n=1 to n=10 of the count-and-say sequence: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
33,140
145
Idea here is keep track of the first letter in the sequence and count consecutive occurances. Once you encounter a new letter you add the previous count and letter to the chain. Repeat n-1 times (since we seeded the initial '1' case). We always update temp after the inner loop since we will never have already added the last sequence.\n\n def countAndSay(self, n):\n s = '1'\n for _ in range(n-1):\n let, temp, count = s[0], '', 0\n for l in s:\n if let == l:\n count += 1\n else:\n temp += str(count)+let\n let = l\n count = 1\n temp += str(count)+let\n s = temp\n return s
3,682
Count and Say
count-and-say
The count-and-say sequence is a sequence of digit strings defined by the recursive formula: To determine how you "say" a digit string, split it into the minimal number of groups so that each group is a contiguous section all of the same character. Then for each group, say the number of characters, then say the character. To convert the saying into a digit string, replace the counts with a number and concatenate every saying. For example, the saying and conversion for digit string "3322251": Given a positive integer n, return the nth term of the count-and-say sequence.
String
Medium
The following are the terms from n=1 to n=10 of the count-and-say sequence: 1. 1 2. 11 3. 21 4. 1211 5. 111221 6. 312211 7. 13112221 8. 1113213211 9. 31131211131221 10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
1,213
6
**IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n**** \n**Comment.** There are many somewhat similar solutions to this problem here on LeetCode. For the sake of diversity, I provide a different solution using separators. Given that the maximal size of the problem is *n=30*, it turns out that the **run-time** is not bad at all, while the **write-time** (and ease of perception) is awesome. \n**** \n**Python.** This [**solution**]() employs separators to guide iteration through blocks of repeating digits. It demonstrated **37 ms runtime (99.10%)** and used **14.1 MB memory (16.06%)**. Time complexity is exponential: **O(expN)**. Space complexity is exponential: **O(expN)**.\n```\nclass Solution:\n def countAndSay(self, n: int) -> str:\n \n # [1] only 3 repetitiotns of any digit is possible, thus,\n # we can list all possible boundaries between blocks\n sep = { "12" : "1|2", "21" : "2|1", "13" : "1|3", \n "31" : "3|1", "23" : "2|3", "32" : "3|2"}\n \n say = "1"\n \n # [2] at each iteration:\n # - first, place separators between blocks\n # - second, split using separators and build new saying\n for _ in range(n-1):\n for w, r in sep.items(): say = say.replace(w, r)\n say = "".join([f"{len(b)}{b[0]}" for b in say.split("|")])\n \n return say\n```\n**** \n**Rust.** This [**solution**]() employs separators to guide iteration through blocks of repeating digits. It demonstrated **2 ms runtime (72.92%)** and used **2.3 MB memory (20.83%)**. Time complexity is exponential: **O(expN)**. Space complexity is exponential: **O(expN)**.\n```\nimpl Solution \n{\n pub fn count_and_say(n: i32) -> String \n {\n // [1] only 3 repetitions of any digit is possible, thus,\n // we can list all possible boundaries between blocks\n let sep = [("12", "1|2"), ("21", "2|1"), ("13", "1|3"),\n ("31", "3|1"), ("23", "2|3"), ("32", "3|2")];\n \n let mut say = String::from("1");\n \n // [2] at each iteration:\n // - first, place separators between blocks\n // - second, split using separators and build new saying\n for _ in 0..n-1\n {\n say = sep.iter()\n .fold(say, |s, &r| s.replace(r.0, r.1));\n\n say = say.split("|")\n .map(|s| format!("{}{}", s.len(), s.chars().nth(0).unwrap()))\n .fold(String::with_capacity(4500), |s, add| s + &add);\n }\n\n return say;\n }\n}\n```\n**** \n**\u0421++.** This [**solution**]() employs separators to guide iteration through blocks of repeating digits. It demonstrated **108 ms runtime (14.61%)** and used **30.2 MB memory (21.61%)**. Time complexity is exponential: **O(expN)**. Space complexity is exponential: **O(expN)**.\n```\nclass Solution \n{\npublic:\n string countAndSay(int n) \n {\n // [1] only 3 repetitions of any digit is possible, thus,\n // we can list all possible boundaries between blocks\n map<string,string> sep = {{"12", "1|2"}, {"21", "2|1"}, {"13", "1|3"},\n {"31", "3|1"}, {"23", "2|3"}, {"32", "3|2"}};\n \n string say = "1";\n string block;\n \n // [2] on each iteration:\n // - first, place separators between blocks\n // - second, split using separators and build new saying\n for (int i = 0; i < n-1; ++i)\n {\n for(auto [src, dst]: sep) \n say = regex_replace(say, regex(src), dst);\n \n istringstream ss(say);\n string new_say = "";\n new_say.reserve(4500);\n while(getline(ss, block, \'|\')) \n new_say += to_string(block.size()) + block[0];\n say = new_say;\n }\n \n return say;\n }\n};\n```\n
3,685
Combination Sum
combination-sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Array,Backtracking
Medium
null
114,410
591
```\nclass Solution(object):\n def combinationSum(self, candidates, target):\n ret = []\n self.dfs(candidates, target, [], ret)\n return ret\n \n def dfs(self, nums, target, path, ret):\n if target < 0:\n return \n if target == 0:\n ret.append(path)\n return \n for i in range(len(nums)):\n self.dfs(nums[i:], target-nums[i], path+[nums[i]], ret)\n```
3,721
Combination Sum
combination-sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Array,Backtracking
Medium
null
38,165
265
I have taken solutions of @caikehe from frequently asked backtracking questions which I found really helpful and had copied for my reference. I thought this post will be helpful for everybody as in an interview I think these basic solutions can come in handy. Please add any more questions in comments that you think might be important and I can add it in the post.\n\n#### Combinations :\n```\ndef combine(self, n, k):\n res = []\n self.dfs(xrange(1,n+1), k, 0, [], res)\n return res\n \ndef dfs(self, nums, k, index, path, res):\n #if k < 0: #backtracking\n #return \n if k == 0:\n res.append(path)\n return # backtracking \n for i in xrange(index, len(nums)):\n self.dfs(nums, k-1, i+1, path+[nums[i]], res)\n``` \n\t\n#### Permutations I\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n res = []\n self.dfs(nums, [], res)\n return res\n\n def dfs(self, nums, path, res):\n if not nums:\n res.append(path)\n #return # backtracking\n for i in range(len(nums)):\n self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)\n``` \n\n#### Permutations II\n```\ndef permuteUnique(self, nums):\n res, visited = [], [False]*len(nums)\n nums.sort()\n self.dfs(nums, visited, [], res)\n return res\n \ndef dfs(self, nums, visited, path, res):\n if len(nums) == len(path):\n res.append(path)\n return \n for i in xrange(len(nums)):\n if not visited[i]: \n if i>0 and not visited[i-1] and nums[i] == nums[i-1]: # here should pay attention\n continue\n visited[i] = True\n self.dfs(nums, visited, path+[nums[i]], res)\n visited[i] = False\n```\n\n \n#### Subsets 1\n\n\n```\ndef subsets1(self, nums):\n res = []\n self.dfs(sorted(nums), 0, [], res)\n return res\n \ndef dfs(self, nums, index, path, res):\n res.append(path)\n for i in xrange(index, len(nums)):\n self.dfs(nums, i+1, path+[nums[i]], res)\n```\n\n\n#### Subsets II \n\n\n```\ndef subsetsWithDup(self, nums):\n res = []\n nums.sort()\n self.dfs(nums, 0, [], res)\n return res\n \ndef dfs(self, nums, index, path, res):\n res.append(path)\n for i in xrange(index, len(nums)):\n if i > index and nums[i] == nums[i-1]:\n continue\n self.dfs(nums, i+1, path+[nums[i]], res)\n```\n\n\n#### Combination Sum \n\n\n```\ndef combinationSum(self, candidates, target):\n res = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], res)\n return res\n \ndef dfs(self, nums, target, index, path, res):\n if target < 0:\n return # backtracking\n if target == 0:\n res.append(path)\n return \n for i in xrange(index, len(nums)):\n self.dfs(nums, target-nums[i], i, path+[nums[i]], res)\n```\n\n \n \n#### Combination Sum II \n\n```\ndef combinationSum2(self, candidates, target):\n res = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], res)\n return res\n \ndef dfs(self, candidates, target, index, path, res):\n if target < 0:\n return # backtracking\n if target == 0:\n res.append(path)\n return # backtracking \n for i in xrange(index, len(candidates)):\n if i > index and candidates[i] == candidates[i-1]:\n continue\n self.dfs(candidates, target-candidates[i], i+1, path+[candidates[i]], res)\n```
3,725
Combination Sum
combination-sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Array,Backtracking
Medium
null
20,157
145
### Approach \\#1. DFS (Backtracking)\n- Straight forward backtracking\n- `cur`: current combination, `cur_sum` current combination sum, `idx` index current at (to avoid repeats)\n- Time complexity: `O(N^(M/min_cand + 1))`, `N = len(candidates)`, `M = target`, `min_cand = min(candidates)`\n- Space complexity: `O(M/min_cand)`\n<iframe src="" frameBorder="0" width="850" height="300"></iframe>\n\n### Approach \\#2. DP (Slow)\n- Read comment for more detail\n- Time Complexity: `O(M*M*M*N)`, `N = len(candidates)`, `M = target`\n- Space Complexity: `O(M*M)`\n<iframe src="" frameBorder="0" width="850" height="300"></iframe>\n\n### Approach \\#3. DP (Fast)\n- Read comment for more detail\n- Time Complexity: `O(M*M*N)`, `N = len(candidates)`, `M = target`\n- Space Complexity: `O(M*M)`\n<iframe src="" frameBorder="0" width="850" height="300"></iframe>\n
3,742
Combination Sum
combination-sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Array,Backtracking
Medium
null
2,374
12
# 1.combination sum\n```\nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n res=[]\n def dfs(candidates,target,path,res):\n if target==0:\n res.append(path)\n return\n for i in range(len(candidates)):\n if candidates[i]>target:\n continue\n dfs(candidates[i:],target-candidates[i],path+[candidates[i]],res)\n dfs(candidates,target,[],res)\n return res\n```\n# 2.combination sum II\n```\nclass Solution:\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n list1=[]\n candidates.sort()\n def dfs(candidates,target,path,list1):\n if target==0:\n list1.append(path)\n return\n for i in range(len(candidates)):\n if candidates[i]>target:\n continue\n if i>=1 and candidates[i]==candidates[i-1]:\n continue\n dfs(candidates[i+1:],target-candidates[i],path+[candidates[i]],list1)\n dfs(candidates,target,[],list1)\n return list1\n```\n# 3. permutation\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n def back(nums,ans,temp):\n if len(nums)==0:\n ans.append(temp)\n return \n for i in range(len(nums)):\n back(nums[:i]+nums[i+1:],ans,temp+[nums[i]])\n ans=[]\n back(nums,ans,[])\n return ans\n```\n# 4. Restore IP Address\n```\nclass Solution:\n def restoreIpAddresses(self, s: str) -> List[str]:\n ans,k=[],0\n def back(s,ans,k,temp=\'\'):\n if k==4 and len(s)==0:\n ans.append(temp[:-1])\n return\n if k==4 or len(s)==0:\n return \n for i in range(3):\n if k>4 or i+1>len(s):\n break\n if int(s[:i+1])>255:\n continue\n if i!=0 and s[0]=="0":\n continue\n back(s[i+1:],ans,k+1,temp+s[:i+1]+\'.\') \n return ans\n return back(s,ans,k,\'\')\n```\n# please upvote me it would encourage me alot\n\n\n
3,759
Combination Sum
combination-sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Array,Backtracking
Medium
null
4,135
11
# Intuition:\nThe problem requires finding all possible combinations of elements from a given list of integers such that their sum is equal to a target value. The approach is to use backtracking to generate all possible combinations and keep track of the valid ones.\n\n# Approach:\nThe given code defines a class Solution and a function combinationSum that takes a list of integers and a target value as input and returns a list of lists containing all valid combinations of integers that add up to the target value.\n\nThe approach used is recursive backtracking. The backtracking function takes two arguments, curr which represents the current combination and i which represents the index of the next element to be added to the combination.\n\nInitially, the current combination is empty and the index i is set to zero. Then, for each index j starting from i, the backtracking function is called recursively with the updated combination curr+[can[j]] and the index j. This ensures that all possible combinations are explored.\n\nThe function also checks if the current combination sum equals the target value and adds it to the result list if it is valid.\n\n# Complexity:\n# Time complexity: \nThe time complexity of the backtracking function is O(2^n), where n is the length of the input list can. This is because there are 2^n possible combinations of elements from the input list. Therefore, the time complexity of the entire function is O(2^n) as well.\n\n# Space complexity: \nThe space complexity of the backtracking function is O(n) as the maximum number of elements that can be stored in the current combination at any point is n. The space complexity of the entire function is also O(2^n) as there can be at most 2^n valid combinations.\n\n# Code\n```\nclass Solution:\n def combinationSum(self, can: List[int], target: int) -> List[List[int]]:\n res=[]\n def backtracking(curr: List[int],i:int):\n s=sum(curr)\n if s==target:\n res.append(curr)\n elif s<target:\n for j in range(i,len(can)):\n backtracking(curr+[can[j]],j)\n backtracking([],0)\n return res\n```
3,781
Combination Sum
combination-sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order. The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different. It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.
Array,Backtracking
Medium
null
6,578
40
```\nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n self.ans = [] # for adding all the answers\n def traverse(candid, arr,sm): # arr : an array that contains the accused combination; sm : is the sum of all elements of arr \n if sm == target: self.ans.append(arr) # If sum is equal to target then you know it, I know it, what to do\n if sm >= target: return # If sum is greater than target then no need to move further.\n for i in range(len(candid)): # we will traverse each element from the array.\n traverse(candid[i:], arr + [candid[i]], sm+candid[i]) #most important, splice the array including the current index, splicing in order to handle the duplicates.\n traverse(candidates,[], 0)\n return self.ans\n```
3,788
Combination Sum II
combination-sum-ii
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.
Array,Backtracking
Medium
null
1,735
17
# Understanding the Question\nHELLO! Lets analyze how to solve this problem. well if you are solving this problem then i am assuming that you already solved **Combination Sum 1 problem** , Where we could pick any value multiple times. \nThis problem is a little different. Here we cant choose a single value multiple times, also here is one more thing. if we get ans=[[1,7],[7,1]] then our final ans will be [[1,7]] as duplicate combinations are not allowed.\n\n# Approach\nIn combination sum 1 problem we had two choices--\n- Either pick the current element and again pick the same element.\n**OR**\n- dont pick the current element, move 1 step ahead and repeat the same process\n\nBut in combination sum 2 problem we cant choose one value multiple times. so what options do we have?\n- Either choose the value and move ahead\n**OR**\n- Dont pick the value and move ahead\n\nso how will our recurrence relations will look?\n\n- f(i+1,sum-arr[i],arr) ***Pick the value and move on to next index***\n**OR**\n- f(i+1,sum,arr) ***dont pick the value but move onto next index***\n\nnow take a simple example to understand recursive calls:\nlets take **arr=[1,1,7]** and **target=8**\nhere i have attached a picture where pick and not_pick calls happens\n*(pardon my drawing, i draw using trackpad)*\n\n![Screenshot (11).png]()\n\nhere as you can see at last we are getting 2 answers [[1,7],[1,7]]\nbut as we know duplicate combinations are not allowed so we have to find a way to only get one set of combination.\n\n***There are Two ways-***\n1. Using Set Data Structure\n2. Using Brain\n\n*i will not talk about how to use set as it is very easy.Although i will share the code using set ds.*\n\n**Lets talk about the second approach--**\n1. if you carefully observe the answer of test cases in this problem you can notice that all the combination set are sorted. means [1,7] then [2,6] this way.\nso to achive combinations in sorted order we need to sort our arr as well.\n2. our main reason why we are getting [1,7] twice is because there is two 1 in our arr.\nif u see previous image which i attached u will see that when i picked the 1 **[0th index]** i got [1,7] as an answer combination. \nand when i **didn\'t picked** the 1 **[0th index]** i had another 1 **[1st index]** which is going in the next recursive call and giving me an extra [1,7] combination.\n\n3. so if i can manipulate my code in a way that at the time of not picking the element, which i already picked **1** **[0th index]** ,will not go to the not pick call with the same value then we can avoid getting the duplicate.\n\n![Screenshot (12).png]()\n\n4. see here i picked 1**[0th index]** which is okay.\n5. but when i am not picking 1[0th index], i am not letting any 1 value pass to the not pick call.\n6. i have picked 1 so at the time of not pick i\'ll avoid all the 1 present in the array.\n7. to skip all the 1, i have used a loop. \n8. pick 1 and go to next index. \nbut if dont pick 1 then dont pick any 1 value and go directly to the next unique element which is 7.\n\nI am not explaning about the base case here. if you r having hard time finding how i got the base case then plz comment down below. I will reply.\n\n***now see the above 2 picture again. spot the difference.***\n# PLZ UPVOTE IF YOU UNDERSTOOD THE APPROACH (\u25CF\'\u25E1\'\u25CF)\n\n# Time Complexity:\nTime complexity will be $O(2^n*n)$\n$2^n$ because every element have two choices either pick or not pick.\nand n extra because we are using a while loop inside the recursive function which will add n time complexity.\n\n# Code using SET\n```\nclass Solution:\n def f(self,i,arr,target,ds,ans):\n # BASE CASE\n if i==len(arr):\n if target==0:\n ans.add(tuple(ds))\n return\n\n # RECURENCE RELATION\n if target>=arr[i]:\n ds.append(arr[i])\n self.f(i+1,arr,target-arr[i],ds,ans)\n ds.pop()\n self.f(i+1,arr,target,ds,ans)\n\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n ds=[]\n ans=set()\n candidates.sort()\n self.f(0,candidates,target,ds,ans)\n return [list(combination) for combination in ans]\n```\n\n# Code Using Brain\n```\nclass Solution:\n def f(self,i,arr,target,ds,ans):\n # BASE CASE\n if target==0:\n ans.append(ds.copy())\n return\n if i>=len(arr):\n return\n # RECURENCE RELATION\n if target>=arr[i]:\n ds.append(arr[i])\n self.f(i+1,arr,target-arr[i],ds,ans) #PICK\n ds.pop()\n j=i+1\n while(j<len(arr) and arr[j]==arr[j-1]):\n j+=1\n self.f(j,arr,target,ds,ans) #NOT PICK\n\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n ds=[]\n ans=[]\n candidates.sort()\n self.f(0,candidates,target,ds,ans)\n return ans\n```
3,812
Combination Sum II
combination-sum-ii
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.
Array,Backtracking
Medium
null
11,561
149
I have compiled solutions for all the 6 classic backtracking problems, you can practise them together for better understanding. Good luck with your preparation/interviews! \n\n[39. Combination Sum]()\n```\nclass Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n if not candidates: return []\n res = []\n candidates.sort()\n def dfs(idx, path, cur):\n if cur > target: return\n if cur == target:\n res.append(path)\n return\n for i in range(idx, len(candidates)):\n dfs(i, path+[candidates[i]], cur+candidates[i])\n dfs(0, [], 0)\n return res\n```\n\n[40. Combination Sum II]()\n```\nclass Solution:\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n res = []\n candidates.sort()\n def dfs(idx, path, cur):\n if cur > target: return\n if cur == target:\n res.append(path)\n return\n for i in range(idx, len(candidates)):\n if i > idx and candidates[i] == candidates[i-1]:\n continue\n dfs(i+1, path+[candidates[i]], cur+candidates[i])\n dfs(0, [], 0)\n return res\n```\n[78. Subsets]()\n```\nclass Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n res = []\n def dfs(idx, path):\n res.append(path)\n for i in range(idx, len(nums)):\n dfs(i+1, path+[nums[i]])\n dfs(0, [])\n return res\n```\n\n[90. Subsets II]()\n```\nclass Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n res = []\n nums.sort()\n def dfs(idx, path):\n res.append(path)\n for i in range(idx, len(nums)):\n if i > idx and nums[i] == nums[i-1]:\n continue\n dfs(i+1, path+[nums[i]])\n dfs(0, [])\n return res\n```\n\n[46. Permutations]()\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n res = []\n def dfs(counter, path):\n if len(path) == len(nums):\n res.append(path)\n return\n for x in counter:\n if counter[x]:\n counter[x] -= 1\n dfs(counter, path+[x])\n counter[x] += 1\n dfs(Counter(nums), [])\n return res \n```\n\n[47. Permutations II]()\n```\nclass Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n res = []\n def dfs(counter, path):\n if len(path) == len(nums):\n res.append(path)\n return\n for x in counter:\n if counter[x]:\n counter[x] -= 1\n dfs(counter, path+[x])\n counter[x] += 1\n dfs(Counter(nums), [])\n return res\n```\n\nMore good backtracking problems for practice:\n[131. Palindrome Partitioning]()\n[784. Lettercase Permutation]()\n[1087. Brace Expansion]()\n[93. Restore IP addresses]()\n[1079 Letter Tile Possibilities]()
3,815
Combination Sum II
combination-sum-ii
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.
Array,Backtracking
Medium
null
1,683
7
# Backtracking Logic\n```\nclass Solution:\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n list1=[]\n candidates.sort()\n def dfs(candidates,target,path,list1):\n if target==0:\n list1.append(path)\n return\n for i in range(len(candidates)):\n if candidates[i]>target:\n continue\n if i>=1 and candidates[i]==candidates[i-1]:\n continue\n dfs(candidates[i+1:],target-candidates[i],path+[candidates[i]],list1)\n dfs(candidates,target,[],list1)\n return list1\n```\n# please upvote me it would encourage me alot\n
3,816
Combination Sum II
combination-sum-ii
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.
Array,Backtracking
Medium
null
3,407
7
\n# Approach\n- The `findAns` function is a recursive helper function that takes an index, the remaining target value, the candidates array, the answer vector (`ans`), and the current helper vector (`helper`).\n\n- The base case of the recursion is when the target value becomes 0. This means a valid combination has been found, so the current helper vector is added to the answer vector.\n\n- Within the recursive function, a loop iterates through the candidates starting from the current index. For each candidate, the following conditions are checked:\n - If the current candidate is the same as the previous candidate, it\'s skipped to avoid duplicate combinations.\n - If the current candidate is greater than the remaining target, it\'s not feasible to include it, so the loop breaks.\n - Otherwise, the current candidate is included in the helper vector, and the recursive call is made with the next index and the updated target value.\n\n- After the loop, the current candidate is removed from the helper vector (backtracking).\n\n- The `combinationSum2` function first sorts the candidates array. This sorting helps in efficiently avoiding duplicate combinations and breaking out of the loop early when candidates exceed the target.\n\n- The `ans`vector containing all valid unique combinations is returned.\n\n# Complexity\n- Time complexity:\nO((2^n)*k)\n\n- Space complexity:\nO(k*x)\n\n```C++ []\nclass Solution {\npublic:\n void findAns(int index, int target, vector<int>& arr, vector<vector<int>>& ans, vector<int>& helper) {\n if(target == 0) {\n ans.push_back(helper);\n return;\n }\n for(int i = index; i < arr.size(); i++) {\n if(i > index && arr[i] ==arr[i-1]) continue;\n if(arr[i] > target) break;\n helper.push_back(arr[i]);\n findAns(i+1, target-arr[i], arr, ans, helper);\n helper.pop_back();\n }\n }\n vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {\n sort(candidates.begin(), candidates.end());\n vector<vector<int>> ans;\n vector<int> helper;\n findAns(0, target, candidates, ans, helper);\n return ans;\n }\n};\n```\n```JAVA []\nclass Solution {\n public List<List<Integer>> combinationSum2(int[] candidates, int target) {\n Arrays.sort(candidates);\n List<List<Integer>> ans = new ArrayList<>();\n List<Integer> helper = new ArrayList<>();\n findAns(0, target, candidates, ans, helper);\n return ans;\n }\n \n private void findAns(int index, int target, int[] arr, List<List<Integer>> ans, List<Integer> helper) {\n if (target == 0) {\n ans.add(new ArrayList<>(helper));\n return;\n }\n \n for (int i = index; i < arr.length; i++) {\n if (i > index && arr[i] == arr[i - 1]) {\n continue;\n }\n if (arr[i] > target) {\n break;\n }\n helper.add(arr[i]);\n findAns(i + 1, target - arr[i], arr, ans, helper);\n helper.remove(helper.size() - 1);\n }\n }\n}\n\n```\n```Python []\nclass Solution:\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n candidates.sort()\n ans = []\n helper = []\n self.findAns(0, target, candidates, ans, helper)\n return ans\n \n def findAns(self, index, target, arr, ans, helper):\n if target == 0:\n ans.append(helper[:])\n return\n \n for i in range(index, len(arr)):\n if i > index and arr[i] == arr[i - 1]:\n continue\n if arr[i] > target:\n break\n helper.append(arr[i])\n self.findAns(i + 1, target - arr[i], arr, ans, helper)\n helper.pop()\n\n```\n
3,838
Combination Sum II
combination-sum-ii
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.
Array,Backtracking
Medium
null
34,110
172
def combinationSum2(self, candidates, target):\n # Sorting is really helpful, se we can avoid over counting easily\n candidates.sort() \n result = []\n self.combine_sum_2(candidates, 0, [], result, target)\n return result\n \n def combine_sum_2(self, nums, start, path, result, target):\n # Base case: if the sum of the path satisfies the target, we will consider \n # it as a solution, and stop there\n if not target:\n result.append(path)\n return\n \n for i in xrange(start, len(nums)):\n # Very important here! We don't use `i > 0` because we always want \n # to count the first element in this recursive step even if it is the same \n # as one before. To avoid overcounting, we just ignore the duplicates\n # after the first element.\n if i > start and nums[i] == nums[i - 1]:\n continue\n\n # If the current element is bigger than the assigned target, there is \n # no need to keep searching, since all the numbers are positive\n if nums[i] > target:\n break\n\n # We change the start to `i + 1` because one element only could\n # be used once\n self.combine_sum_2(nums, i + 1, path + [nums[i]], \n result, target - nums[i])
3,843
Combination Sum II
combination-sum-ii
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.
Array,Backtracking
Medium
null
15,654
112
```\nclass Solution(object):\n def combinationSum2(self, candidates, target):\n ret = []\n self.dfs(sorted(candidates), target, 0, [], ret)\n return ret\n \n def dfs(self, nums, target, idx, path, ret):\n if target <= 0:\n if target == 0:\n ret.append(path)\n return \n for i in range(idx, len(nums)):\n if i > idx and nums[i] == nums[i-1]:\n continue\n self.dfs(nums, target-nums[i], i+1, path+[nums[i]], ret)\n```
3,864
Combination Sum II
combination-sum-ii
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target. Each number in candidates may only be used once in the combination. Note: The solution set must not contain duplicate combinations.
Array,Backtracking
Medium
null
791
7
```\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n # to store all the potential answers\n result = []\n # Bring all the duplicate elements together\n candidates.sort()\n # helper method to get all the potential answers\n self._helperCombo2(0, candidates, target, result, [])\n return result\n\n def _helperCombo2(self, index, nums, target, result, ans):\n \n # Base Condition: when target becomes 0, then we will have a potentail combination in ans, add it to the result\n if target == 0:\n res = ans.copy()\n result.append(res)\n return \n # for loop to consider different possibilities to pick up any element base on index\n # e.g. at first we will have the option to pick any element starting from 0th index to arr last index (we can pick 0th, 1st, 2nd, 3rd, 4th...)\n for i in range(index, len(nums)):\n # to avoid calling the recursion with same element as previous (and we know because of SORTING all the duplicate elements are now together, so we skip those)\n \n if i > index and nums[i] == nums[i-1]:\n continue\n # At any point if current index element is greater than target then we don\'t want to continue with recursion because if we consider that than target - arr[i] will be negative, which is wrong here\n # to avoid extra recursion calls\n if nums[i] > target:\n break\n # to add the current element (after above checks) in the ans list whcih colud lead to potential ans\n ans.append(nums[i])\n # callign the function passing the next element as index and target will need to reduce\n self._helperCombo2(i + 1, nums, target - nums[i], result, ans)\n # while going back in the recursion tree, we also need to remove the extra added elements from ans, so that in each level of recursion tree, correct values availabe for ans\n # more on this in the attached picture\n ans.pop()\n```\n\n**Time Complexity - 2^n * k\nSpace complexity - k * x**\n\nk: average length of every combinations\nx: total combinations\n\n![image]()
3,899
First Missing Positive
first-missing-positive
Given an unsorted integer array nums, return the smallest missing positive integer. You must implement an algorithm that runs in O(n) time and uses constant extra space.
Array,Hash Table
Hard
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
11,173
111
\u2014\u2014Jump to the final code if you\'re easly bored, down below!\n\nOk, you\'re still here eh. Here are the train of thoughts to arrive to the final solution:\n\n* The answer is always between `1` to `length of nums + 1`. Why? Because the biggest positive integer we can put as answer for the input of length n, is when the input is `[1, 2, 3, ..., n]`, in that case the answer is `n+1`. Otherwise, if the input is not exactly as mentioned (in any order), then the answer must be a positive integer that is less than `n+1`. \n\n* Given that the answer is limited to said range, then we can simply solve this with linear time and linear space. We can create a `flag` booleans that indicate whether an `index` is appearing in the `nums` or not. See simple code below!\n```Python\nflags = [False] * len(nums)\n\nfor num in nums:\n\tif num > 0:\n\t\tflags[num-1] = True // notice that we -1, so that the answer set 1..n becomes 0-indexed 0..n-1\n\t\t\nfor index in range(len(flags)):\n\tif flags[index] == False:\n\t\treturn index + 1\n\t\t\nreturn len(nums) + 1 // happens when all flags are true\n```\n\n* Now, how do we improve this to be a better solution with constant additional space? In other words, how to get rid of the additional booleans? You can probably guess it already. Yes by using the original `nums` array as flags. \n\n* Let say we flag it by changing the value in `index` to `None` if it\'s appearing in `nums`. Problem? Yes, we still need to retain the original values in `nums`, because as we loop over the `nums` to flag the `index`, we will definitely get in trouble if the `index` we\'re flagging hasn\'t been evaluated yet. Take an example of `[3,1,2]` (which supposed to have the answer `4`), here is how the `nums` array is being evaluated, in each loop-step:\n** Before loop: `[3,1,2]`\n** Loop at index 0: `[3, 1, None]`. The `index` that `3` points to is index `2`, therefore the value becomes `None`. This is the part where we change index `2`, while index `2` itself hasn\'t been evaluated yet.\n** Loop at index 1: `[None, 1, None]`. The `index` that `1` points to is index `0`, therefore the value becomes `None`.\n** Loop at index 2: `[None, 1, None]`. At this step, it\'s doing nothing because the original value of `2` has already been changed to `None`, and we have no way to flag index `1` as `None`.\n\n* So how do we flag elements in `nums` while also retaining original `value` **that matters**? Notice I mentioned \'that matters\', because we only care about positive integers. We can simply discard anything that is not positive integers. And because of that, we can use positive and negative value as flag\u2014multiply the value with `-1` to flag it so it becomes negative. So positive means hasn\'t been flagged, negative means has been flagged. Whether it\'s positive or negative, we can get the original value with `abs`. So for above example, the correct steps would be:\n** Before loop: `[3, 1, 2]`\n** Loop at index 0: `[3, 1, -2]`\n** Loop at index 1: `[-3, 1, -2]`\n** Loop at index 2: `[-3, -1, -2]`\nAnd finally when we\'re looking for the answer, we find that all the values are negative (flagged), therefore the answer is `4`.\n\n* Final thoughts: what about those zeros and negative nums??? Simply change them to 0 before entering the main algorithm explained above. We just need to be careful not to multiply those zeros to `-1` when flagging, instead change it to something like `-inf` (as long as it\'s a negative value, then it\'s flagged) \n\nHere is the final full code:\n```python\ndef firstMissingPositive(self, nums: List[int]) -> int:\n\tfor i,num in enumerate(nums):\n\t\tif num <= 0:\n\t\t\tnums[i] = 0\n\n\tfor i,num in enumerate(nums):\n\t\tindex = abs(num)-1\n\t\tif index >= 0 and index < len(nums):\n\t\t\tif nums[index] == 0:\n\t\t\t\tnums[index] = -inf\n\t\t\telif nums[index] > 0: // we dont want to make negative to be positive again, when its duplicated num\n\t\t\t\tnums[index] *= -1\n\n\tfor index,num in enumerate(nums):\n\t\tif num >= 0:\n\t\t\treturn index + 1\n\n\treturn len(nums) + 1\n```\n\nTime Complexity: O(N)\nSpace Complexity: O(1)\n\nPlease upvote if you find this useful, comment if you find any improvement points!\n\n
3,959
Trapping Rain Water
trapping-rain-water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
null
50,170
288
# Approach\n- Here the approach is like we basically find the left max and right max and based on that we start our movement in two pointer , first have a glance at the below depicted figure which is later followed by explaination.\n\n![pic1.png]()\n\n>- As shown in the figure we start with finding the left most height and the right most height and then we do left++ , right-- and continue. Now if the new left height is greater than max left height then we update the lmax height and similarly for the right side.\n>- When This is not the case the we proceed with the side with the minimum height , say it\'s left for the further understanding , now we take the difference b/w the left heights and add to the water stored $i.e$ `water += lmax - height[lpos];` or `water += rmax - height[rpos];` according to the current scenario as explained above.\n\n>- In the same way depicted above we further continue till the loop $i.e$ ends `while(lpos <= ros)` then we would finally obtain the water which can be trapped during this process.\n\n---\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int trap(vector<int>& height) {\n int n = height.size();\n int lmax = height[0];\n int rmax = height[n-1];\n int lpos = 1;\n int rpos = n-2;\n int water = 0;\n while(lpos <= rpos)\n {\n if(height[lpos] >= lmax)\n {\n lmax = height[lpos];\n lpos++;\n }\n else if(height[rpos] >= rmax)\n {\n rmax = height[rpos];\n rpos--;\n }\n else if(lmax <= rmax && height[lpos] < lmax)\n {\n water += lmax - height[lpos];\n lpos++;\n }\n else\n {\n water += rmax - height[rpos];\n rpos--;\n }\n \n }\n return water;\n }\n};\n```\n```java []\nclass Solution {\n public int trap(int[] height) {\n int left = 0, right = height.length - 1;\n int leftMax = height[0], rightMax = height[height.length - 1];\n int water = 0;\n while (left < right) {\n if (leftMax < rightMax) {\n left++;\n if (leftMax < height[left]) {\n leftMax = height[left];\n } else {\n water += leftMax - height[left];\n }\n } else {\n right--;\n if (rightMax < height[right]) {\n rightMax = height[right];\n } else {\n water += rightMax - height[right];\n }\n }\n }\n return water;\n }\n}\n```\n```Python []\nclass Solution:\n def sumBackets(self, height: list[int], left, right):\n\n minHeightLeft = height[left]\n total = 0\n leftBacket = 0\n locationMinLeft = left\n\n while left < right:\n \n if height[left] < minHeightLeft:\n leftBacket += minHeightLeft - height[left] \n else:\n minHeightLeft = height[left]\n total += leftBacket\n leftBacket = 0\n locationMinLeft = left \n left += 1\n \n if minHeightLeft <= height[right]:\n return total + leftBacket, right\n else : \n return total, locationMinLeft\n\n def sumBacketsReverce(self, height: list[int], left, right):\n\n minHeightRight = height[right]\n total = 0\n rightBacket = 0\n locationMinRight = right\n\n while left < right:\n \n if height[right] < minHeightRight:\n rightBacket += minHeightRight - height[right] \n else :\n minHeightRight = height[right]\n total += rightBacket\n rightBacket = 0\n locationMinRight = right \n right -= 1\n\n\n if minHeightRight <= height[left]:\n return total + rightBacket, left\n else :\n return total, locationMinRight\n \n def trap(self, height: List[int]) -> int: \n right = len(height)-1\n left =0\n totalSum =0\n\n\n while left < right-1: \n if( height[left]< height[right]):\n total, left = self.sumBackets(height, left, right) \n else:\n total, right = self.sumBacketsReverce(height, left, right) \n \n totalSum += total \n \n return totalSum\n```\n---\n\n# Complexity\n>- Time complexity:Here the time complexity would be $O(n)$ as there is only one loop running in the two pointers.\n\n>- Space complexity:Here the space complexity is constant as we are not creating any extra space excluding the variables.\n\n---\n\n**IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.**\n\n![UPVOTE.jpg]()\n
4,002
Trapping Rain Water
trapping-rain-water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
null
1,706
30
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code calculates trapped rainwater by iterating through each element in the input array. For each element, it determines the minimum height of barriers on both sides and calculates the trapped water if the minimum height exceeds the current height. The total trapped water is returned. **However, this simple code can be optimized for efficiency. please find optimized code at bottom setion**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n* Travel the array from 1 to len(height)\n\n ``` \n for i in range ( 1 , len(height) ):\n ```\n* Find Left side maximum buiding height till \'i\' index\n ```\n left_max = max( height [ 0 : i ] )\n ```\n* Find Right side maximum building height from \'i\' index\n ```\n right_max = max ( height [ i : len(height) ] )\n ```\n* Find minimum height from left_max and right_max\n ```\n min_height = min( left_max , right_max )\n ```\n* If minimum height - height[i] is greater than 0 then add that values to water varieble by substracting element which is at \'i\' index.\n ```\n if(min_height - height[i]) > 0):\n water += ( min_height - height[i] )```\n* Finally return the total stored water\n ``` \n return water\n ```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n For simple code: O(n^2)\n For Optimized code : O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n For simple code: O(n)\n For Optimized code : O(n)\n# Code\n```\nclass Solution:\n def trap(self, height: List[int]) -> int:\n water = 0 \n for i in range(1, len(height)):\n min_height = min( max(height[0:i]), max(height[i:len(height)]))\n if((min_height - height[i]) > 0):\n water += (min_height - height[i])\n return water\n```\n\n\n# Optimized Code with O(n) time complexity:\n```\nclass Solution:\n def trap(self, height: List[int]) -> int:\n if not height:\n return 0\n \n left_max, right_max = 0, 0\n left, right = 0, len(height) - 1\n water = 0\n \n while left < right:\n if height[left] < height[right]:\n if height[left] > left_max:\n left_max = height[left]\n else:\n water += left_max - height[left]\n left += 1\n else:\n if height[right] > right_max:\n right_max = height[right]\n else:\n water += right_max - height[right]\n right -= 1\n \n return water\n```\n\n=> Please comment, If you have any questions.\n\n\u2764 Please upvote if you found this usefull \u2764\n\n![fc626f73-c07e-4a16-88f2-99293774ffd1_1686646782.1594946.png]()\n\n\n
4,019
Trapping Rain Water
trapping-rain-water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
null
518
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```\nfrom typing import List\n\nclass Solution:\n def trap(self, height: List[int]) -> int:\n if len(height) <= 2:\n return 0\n\n ans = 0\n i, j = 1, len(height) - 1\n lmax, rmax = height[0], height[-1]\n\n while i <= j:\n # Update left and right maximum for the current positions\n if height[i] > lmax:\n lmax = height[i]\n if height[j] > rmax:\n rmax = height[j]\n\n # Fill water up to lmax level for index i and move i to the right\n if lmax <= rmax:\n ans += lmax - height[i]\n i += 1\n # Fill water up to rmax level for index j and move j to the left\n else:\n ans += rmax - height[j]\n j -= 1\n\n return ans\n ##Upvote me if it Helps\n\n```
4,020
Trapping Rain Water
trapping-rain-water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
null
649
7
## Trapping Rain Water\n\nGiven an array of non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.\n\n### Approach:\n\nWe can solve this problem by maintaining two arrays, `l` and `r`, which represent the maximum height of bars to the left and right of each bar, respectively. Then, for each bar, we calculate how much water it can trap by taking the minimum of the maximum heights to its left and right and subtracting its own height.\n\n1. Initialize arrays `l` and `r`, both of size `n`, where `n` is the length of the input `height` array, with all elements initially set to 0.\n2. Initialize two variables, `lm` and `rm`, to 0. These variables will keep track of the maximum height encountered while traversing from left to right and right to left, respectively.\n3. Traverse the `height` array from left to right, and for each element `height[i]`, update `l[i]` to be equal to `lm` and update `lm` if `height[i]` is greater than `lm`.\n4. Traverse the `height` array from right to left, and for each element `height[i]`, update `r[i]` to be equal to `rm` and update `rm` if `height[i]` is greater than `rm`.\n5. Initialize a variable `ans` to 0. This variable will store the total trapped water.\n6. Traverse the `height` array again, and for each element `height[i]`, calculate the amount of trapped water as `min(l[i], r[i]) - height[i]`. If this value is greater than 0, add it to `ans`.\n7. Return `ans` as the final result.\n\n### Complexity Analysis:\n\n- Time Complexity: O(n)\n - We traverse the `height` array three times, each time taking O(n) operations. Hence, the overall time complexity is O(n).\n\n- Space Complexity: O(n)\n - We use two additional arrays, `l` and `r`, of size `n`, and a few integer variables. Therefore, the space complexity is O(n).\n\n\n# Code\n```\nclass Solution:\n def trap(self, height: List[int]) -> int:\n n = len(height)\n l = [0] * n \n r = [0] * n\n ans = 0\n lm, rm = 0, 0\n\n for i in range(n):\n l[i] = lm\n if lm < height[i]:\n lm = height[i]\n for i in range(n - 1, -1, -1):\n r[i] = rm\n if rm < height[i]:\n rm = height[i]\n for i in range(n):\n trapped = min(l[i], r[i]) - height[i]\n if trapped > 0:\n ans += trapped\n\n return ans\n\n```\n\n# Please upvote the solution if you understood it.\n\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg]()\n\n
4,042
Trapping Rain Water
trapping-rain-water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
null
1,222
5
# Intuition\n\nTo solve this problem, imagine that the map is a pyramid.\nWe have steps up to the column with the highest height.\nAfter the peak with the maximum height, we have steps going down.\nRight.\nNow we need to calculating total sum of bars with water.\n\n# Approach\n\nFirst step - for i in range(1,listLen):\nIn this loop we try to calculate sum of water bars that are located to the left of the column rith max high\n\nSecond step - for i in range(listLen-1, indexMax, -1):\nIn this loop we try to calculate sum of water bars that are located to the right of the column rith max high\n\n![rainwatertrap.png]()\n\nIn the loop we try to find nowMax that mean the highest column of i - step\nThen if we find on i+n - step the column with high $$<$$ that the nowMax\nWe can say that total sum of water bars $$=$$ nowMax - high on i+n step \n\n# Complexity\n- Time complexity:\n$$O(2N) => O(N)$$\n\n# Code\n```\nclass Solution:\n def trap(self, height: List[int]) -> int:\n indexMax = 0\n listLen = len(height)\n total = 0\n for i in range(1,listLen):\n if height[i] > height[indexMax]:\n indexMax = i\n nowMax = height[0]\n for i in range(1, indexMax):\n if height[i] > nowMax:\n nowMax = height[i]\n else:\n total += (nowMax-height[i])\n nowMax = height[listLen-1]\n for i in range(listLen-1, indexMax, -1):\n if height[i] > nowMax:\n nowMax = height[i]\n else:\n total += (nowMax-height[i])\n return total\n```
4,059
Trapping Rain Water
trapping-rain-water
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
Hard
null
4,038
37
# Intuition:\nThe task is to calculate the amount of water that can be trapped between the bars of different heights. The optimized code uses a two-pointer approach, whereas the brute force approach checks for the maximum height of bars to the left and right of every bar. The approach with two pointers calculates the water between two bars by keeping track of the maximum height bars from left and right as it moves towards the middle of the bars.\n\n# Approach:\n\n### Brute Force Approach:\n\n1. For every bar in the height array, calculate the maximum height bar to the left and right.\n2. Subtract the height of the current bar from the minimum of the left and right maximum bar heights to get the amount of water that can be trapped.\n3. Add the result to a variable "water" which keeps track of the total amount of water that can be trapped.\n4. Return the value of the "water" variable.\n\n### Optimized Approach:\n\n1. Initialize left, right pointers to the first and last bars of the height array, respectively.\n2. Initialize variables left_max and right_max to zero.\n3. While the left pointer is less than or equal to the right pointer, compare the heights of the bars pointed to by the left and right pointers.\n4. If the height of the left bar is less than or equal to the height of the right bar, check if the height of the left bar is greater than the left_max variable. If it is, update left_max, otherwise, add left_max - height[left] to the "water" variable. Move the left pointer to the next bar.\n5. If the height of the right bar is less than the height of the left bar, check if the height of the right bar is greater than the right_max variable. If it is, update right_max, otherwise, add right_max - height[right] to the "water" variable. Move the right pointer to the previous bar.\n6. Return the value of the "water" variable.\n\n# Complexity\n\n### Brute Force Approach:\n- The time complexity of the brute force approach is O(n^2), where n is the length of the height array. This is because the algorithm has to check for the maximum height bars to the left and right of every bar in the height array. \n- The space complexity is O(1), as the algorithm only uses constant extra space to store the left_max, right_max, and water variables.\n\n### Optimized Approach:\n- The time complexity of the optimized approach is O(n), where n is the length of the height array. This is because the algorithm has to traverse the height array only once with two pointers. \n- The space complexity is O(1), as the algorithm only uses constant extra space to store the left, right, left_max, right_max, and water variables.\n# Similar Question: \n[]()\n---\n\n# C++\n## Brute Force\n```\nclass Solution {\npublic:\n int trap(vector<int>& height) {\n int n = height.size();\n int water=0;\n for(int i=0;i<height.size();i++){\n int left_max=0,right_max=0;\n int j=i;\n while(j<n){\n right_max=max(right_max,height[j]);\n j++;\n }\n j=i;\n while(j>=0){\n left_max=max(left_max,height[j]);\n j--;\n }\n j=i;\n water+= min(left_max,right_max)-height[i];\n }\n return water;\n }\n};\n```\n## Optimized Code\n```\nclass Solution {\npublic:\n int trap(vector<int>& height) {\n int n = height.size();\n int left=0,right=n-1,left_max=0,right_max=0,water=0;\n while(left<=right){\n if(height[left]<=height[right]){\n if(height[left]>left_max) left_max=height[left];\n else water += left_max-height[left];\n left++;\n }\n else{\n if(height[right]>right_max) right_max=height[right];\n else water += right_max-height[right];\n right--;\n }\n }\n return water;\n }\n};\n```\n\n---\n# JavaScript\n## Brute Force\n\n```\n/**\n * @param {number[]} height\n * @return {number}\n */\nvar trap = function(height) {\n let n = height.length;\n let water = 0;\n for (let i = 0; i < n; i++) {\n let left_max = 0, right_max = 0;\n let j = i;\n while (j < n) {\n right_max = Math.max(right_max, height[j]);\n j++;\n }\n j = i;\n while (j >= 0) {\n left_max = Math.max(left_max, height[j]);\n j--;\n }\n j = i;\n water += Math.min(left_max, right_max) - height[i];\n }\n return water;\n}\n\n```\n## Optimized Code\n```\n/**\n * @param {number[]} height\n * @return {number}\n */\nvar trap = function(height) {\n let n = height.length;\n let left = 0, right = n - 1, left_max = 0, right_max = 0, water = 0;\n while (left <= right) {\n if (height[left] <= height[right]) {\n if (height[left] > left_max) left_max = height[left];\n else water += left_max - height[left];\n left++;\n } else {\n if (height[right] > right_max) right_max = height[right];\n else water += right_max - height[right];\n right--;\n }\n }\n return water;\n}\n\n\n```\n---\n# Java\n## Brute Force\n```\nclass Solution {\n public int trap(int[] height) {\n int n = height.length;\n int water = 0;\n for (int i = 0; i < n; i++) {\n int left_max = 0, right_max = 0;\n int j = i;\n while (j < n) {\n right_max = Math.max(right_max, height[j]);\n j++;\n }\n j = i;\n while (j >= 0) {\n left_max = Math.max(left_max, height[j]);\n j--;\n }\n j = i;\n water += Math.min(left_max, right_max) - height[i];\n }\n return water;\n }\n}\n\n```\n## Optimized Code\n```\nclass Solution {\n public int trap(int[] height) {\n int n = height.length;\n int left = 0, right = n - 1, left_max = 0, right_max = 0, water = 0;\n while (left <= right) {\n if (height[left] <= height[right]) {\n if (height[left] > left_max) left_max = height[left];\n else water += left_max - height[left];\n left++;\n } else {\n if (height[right] > right_max) right_max = height[right];\n else water += right_max - height[right];\n right--;\n }\n }\n return water;\n }\n}\n\n```\n---\n# Python\n## Brute Force\n```\nclass Solution(object):\n def trap(self, height):\n n = len(height)\n water = 0\n for i in range(n):\n left_max, right_max = 0, 0\n j = i\n while j < n:\n right_max = max(right_max, height[j])\n j += 1\n j = i\n while j >= 0:\n left_max = max(left_max, height[j])\n j -= 1\n j = i\n water += min(left_max, right_max) - height[i]\n return water\n\n```\n## Optimized Code\n```\nclass Solution(object):\n def trap(self, height):\n n = len(height)\n left, right, left_max, right_max, water = 0, n - 1, 0, 0, 0\n while left <= right:\n if height[left] <= height[right]:\n if height[left] > left_max:\n left_max = height[left]\n else:\n water += left_max - height[left]\n left += 1\n else:\n if height[right] > right_max:\n right_max = height[right]\n else:\n water += right_max - height[right]\n right -= 1\n return water\n\n```\n\n---\n\n# Similar Question : \n[]()
4,069
Multiply Strings
multiply-strings
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Math,String,Simulation
Medium
null
4,846
8
\nRuntime: **46 ms**, faster than 71.41% of Python3 online submissions for Multiply Strings. \nMemory Usage: 13.8 MB, less than 69.53% of Python3 online submissions for Multiply Strings. \n```\nclass Solution:\n def multiply(self, num1: str, num2: str) -> str:\n d1 = {\'0\':0, \'1\':1, \'2\':2, \'3\':3, \'4\':4, \'5\':5, \'6\':6, \'7\':7, \'8\':8, \'9\':9}\n d2 = {v:k for k,v in d1.items()}\n n1 = sum([d1[c]*(10**i) for i,c in enumerate(num1[::-1])])\n n2 = sum([d1[c]*(10**i) for i,c in enumerate(num2[::-1])])\n n3, s = n1*n2, \'\'\n while n3:\n s = d2[n3%10] + s\n n3 = n3//10\n return s if s else \'0\'\n```
4,115
Multiply Strings
multiply-strings
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Math,String,Simulation
Medium
null
886
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```\nclass Solution:\n def multiply(self, num1: str, num2: str) -> str:\n l1=len(num1)\n l2=len(num2)\n\n if (l2>l1): # taking smaller string as nums2\n num1,num2=num2,num1\n\n l1=len(num1)\n l2=len(num2)\n\n res=[0]*(l1+l2)\n res_pointer=len(res)-1\n res_pointer_count=0\n\n carry=0\n\n j=l2-1\n\n while j>-1:\n res_pointer=len(res)-1-res_pointer_count\n for i in range((l1)-1,-1,-1):\n temp1 = int(num1[i])\n temp2 = int(num2[j])\n\n inplace = (temp1*temp2)%10\n carry= (temp1*temp2)//10\n\n res[res_pointer]+=inplace\n res[res_pointer-1]+=carry\n\n if res[res_pointer]>9:\n inplace = res[res_pointer]%10\n carry= res[res_pointer]//10\n res[res_pointer]=inplace\n res[res_pointer-1]+=carry\n\n res_pointer-=1\n\n res_pointer_count+=1\n j-=1\n\n ans=""\n for i in res:\n ans=ans+str(i)\n return str(int(ans))\n```
4,140
Multiply Strings
multiply-strings
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Math,String,Simulation
Medium
null
8,274
47
```\nclass Solution:\n def multiply(self, num1: str, num2: str) -> str:\n if num1 == \'0\' or num2 == \'0\':\n return \'0\'\n \n def decode(num):\n ans = 0\n for i in num:\n ans = ans*10 +(ord(i) - ord(\'0\'))\n return ans\n\n def encode(s):\n news = \'\'\n while s:\n a = s % 10\n s = s // 10\n news = chr(ord(\'0\') + a) + news\n return news\n \n return encode(decode(num1)*decode(num2))\n```
4,150
Multiply Strings
multiply-strings
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string. Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Math,String,Simulation
Medium
null
19,603
65
```\nclass Solution(object):\n def multiply(self, num1, num2):\n res = [0] * (len(num1)+len(num2))\n for i in range(len(num1)-1, -1, -1):\n carry = 0\n for j in range(len(num2)-1, -1, -1):\n tmp = (ord(num1[i])-ord(\'0\'))*(ord(num2[j])-ord(\'0\')) + carry\n carry = (res[i+j+1]+tmp) // 10\n res[i+j+1] = (res[i+j+1]+tmp) % 10\n res[i] += carry\n res = \'\'.join(map(str, res))\n return \'0\' if not res.lstrip(\'0\') else res.lstrip(\'0\')\n```
4,198
Wildcard Matching
wildcard-matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial).
String,Dynamic Programming,Greedy,Recursion
Hard
null
190
5
# Intuition\nI solved this problem using dynamic programming .Its time complexity was $$O(len(s)*len(p))$$. However this post doesn\'t explain that solution. I am sure there are many more posts to explain that.\n\nThereafter I found a solution in linear time using 2 pointer approach. I have made some visualisations using python to understand this solution. Here is the link to the blog post for this solution by [Yu]():\n\n---\n\n\n\n# Approach\n1. Start by setting up some placeholders: We set up some variables that keep track of positions and states (s_cur, p_cur, match, star) as we move through the string and pattern.\n2. (Loop) While we haven\'t reached the end of the string, we check the following:\n 1. If the current character in the pattern matches the current character in the string or if the pattern character is a question mark, we move forward in both the string and pattern.\n 1. If we encounter a \'*\' in the pattern, we note down the current positions in the string and pattern and move the pattern position forward.\n 1. If none of the above conditions are met, but we have seen a \'\' before, we reset the pattern position after the \'\' to the next character, increment the match counter, and move the string position to the new match.\n 1. If none of the conditions are met mainly (p_cur reaches the end) and we have no \'*\' to fall back on, we know the pattern doesn\'t match the string, so we return False.\n3. After going through the string, we check if there are any \'*\' characters left in the pattern. If there are, we move the pattern position forward.\n4. Finally, if we\'ve reached the end of the pattern at this point, we know the pattern matches the string, so we return True. Otherwise, we return False.\n<!-- Describe your approach to solving the problem. -->\n\n---\n\n\n# Complexity\n- Average Time complexity: $$O(n)$$\n- Worst Case Time complexity: $$O(mn)$$ (Eg String (s): "aaaaaaaaaaab"\nPattern (p): "*aab")\n- Space complexity: $$O(1)$$\n\n\n---\n\n\n# Dry Run with Visualisation \nThe yellow highlighted cells represent s_cur and p_cur respectively\n$$\ns =\nabcabczzzde\n$$\n$$\np =\n*abc???de*\n$$\n\n![pointer_movement_visualization.gif]()\n\nWorst Case Example\n$$\ns =\naaaaaaab\n$$\n$$\np =\n*aab\n$$\n![pointer_movement_visualization2.gif]()\n$$\ns =\nabxbcbgh\n$$\n$$\np =\na*c*h\n$$\n![pointer_movement_visualization3.gif]()\n\n\n\n---\n\n\n\n# Code\n```\nclass Solution:\n def isMatch(self, s, p):\n s_cur = 0\n p_cur= 0\n match = 0\n star = -1\n while s_cur<len(s):\n if p_cur<len(p):\n print("Pattern Char",p[p_cur])\n if p_cur< len(p) and (s[s_cur]==p[p_cur] or p[p_cur]==\'?\'):\n s_cur = s_cur + 1\n p_cur = p_cur + 1\n elif p_cur<len(p) and p[p_cur]==\'*\':\n match = s_cur\n star = p_cur\n p_cur = p_cur+1\n elif (star!=-1):\n p_cur = star+1\n match = match+1\n s_cur = match\n else:\n return False\n while p_cur<len(p) and p[p_cur]==\'*\':\n p_cur = p_cur+1\n \n if p_cur==len(p):\n return True\n else:\n return False\n```\n\n---\n\nAll suggestions are welcome.\nIf you have any query or suggestion please comment below.\nPlease upvote\uD83D\uDC4D if you like\uD83D\uDC97 it. Thank you:-)\nHappy Learning, Cheers Guys \uD83D\uDE0A\nKeep Grinding \uD83D\uDE00\uD83D\uDE00\n
4,220
Wildcard Matching
wildcard-matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial).
String,Dynamic Programming,Greedy,Recursion
Hard
null
3,293
26
# Approach\n- Here the Approach is literally same as the sum []() or a small improvisation of it here the \'*\' symbol can take any pattern that is the only difference between those two, below is the pictorical representation of the approach followed and the breifing of it is given below.\n\n- ![pic1.png]()\n\n>- Here we can clearly see that the final DP table is completely dependent on its previous states $i.e$ given by the expression as follows -\n`dp[i][j] = dp[i-1][j] | dp[i][j-1] | dp[i-1][j-1] ` when `p[j-1]` is\nindicated by a \'*\' otherwise we go with `dp[i-1][j-1]` as the state transition. \n\n>- This would be the way in which we must proceed based and the prev state and the final answer would be `dp[m][n]` we always do a step down indexing for convineance purposes.\n\n---\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool isMatch(string s, string p) {\n int n=s.length();\n int m=p.length();\n bool res[m+1][n+1];\n memset(res,false,sizeof(res));\n res[0][0]=true;\n for(int i=1;i<=m;i++){\n if(p[i-1]==\'*\'){\n res[i][0]=res[i-1][0];\n }\n for(int j=1;j<=n;j++){\n if(p[i-1]==\'*\'){\n res[i][j]=res[i-1][j]||res[i][j-1];\n }\n else if(p[i-1]==s[j-1]||\'?\'==p[i-1]){\n res[i][j]=res[i-1][j-1];\n }\n }\n }\n return res[m][n];\n } \n};\n```\n```Java []\nclass Solution {\n public boolean isMatch(String s, String p) {\n int sIndex = 0, pIndex = 0, matchIndex = 0, starIndex = -1;\n \n while (sIndex < s.length()) {\n if (pIndex < p.length() && (s.charAt(sIndex) == p.charAt(pIndex) || p.charAt(pIndex) == \'?\')) {\n sIndex++;\n pIndex++;\n } else if (pIndex < p.length() && p.charAt(pIndex) == \'*\') {\n starIndex = pIndex;\n matchIndex = sIndex;\n pIndex++;\n } else if (starIndex != -1) {\n pIndex = starIndex + 1;\n matchIndex++;\n sIndex = matchIndex;\n } else {\n return false;\n }\n }\n \n while (pIndex < p.length() && p.charAt(pIndex) == \'*\') {\n pIndex++;\n }\n \n return pIndex == p.length();\n }\n}\n```\n```Python []\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n s_len, p_len, p_idx, s_idx, p_star, s_backtrack = len(s), len(p), 0, 0, -1, -1\n \n while s_idx < s_len:\n if p_idx < p_len and p[p_idx] in [\'?\', s[s_idx]]:\n p_idx += 1\n s_idx += 1\n elif p_idx < p_len and p[p_idx] == \'*\':\n p_star = p_idx\n s_backtrack = s_idx\n p_idx += 1\n else: #elif p_idx == p_len or p[p_idx] != s[s_idx]:\n if p_star == -1:\n return False\n else:\n #backtrack\n p_idx = p_star + 1\n s_idx = s_backtrack + 1\n s_backtrack = s_idx\n\n return all(p[idx] == \'*\' for idx in range(p_idx, p_len))\n```\n---\n# Complexity\n>- Time complexity: Here the complexity would be $O(n^2)$ as we can see that we need a 2d looping for the management of memoization using the length so $O(n^2)$.\n\n>- Space complexity: Here We can clearly see that we need a 2D dp so the space complexity will also be $O(n^2)$ and which can be further optimised to $O(n)$ by using space optimisation in Dp as the final states and previous states differ by one index.\n\n\n---\n\nIF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.\n\n![UPVOTE.jpg]()\n
4,227
Wildcard Matching
wildcard-matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial).
String,Dynamic Programming,Greedy,Recursion
Hard
null
12,917
139
I had to look at other solutions for the top row, we set values to true until a non "*" character is found\n```\nclass Solution:\n def isMatch(self, s, p):\n dp = [[False for _ in range(len(p)+1)] for i in range(len(s)+1)]\n dp[0][0] = True\n for j in range(1, len(p)+1):\n if p[j-1] != \'*\':\n break\n dp[0][j] = True\n \n for i in range(1, len(s)+1):\n for j in range(1, len(p)+1):\n if p[j-1] in {s[i-1], \'?\'}:\n dp[i][j] = dp[i-1][j-1]\n elif p[j-1] == \'*\':\n dp[i][j] = dp[i-1][j] or dp[i][j-1]\n return dp[-1][-1]\n```\n![image]()\n
4,234
Wildcard Matching
wildcard-matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial).
String,Dynamic Programming,Greedy,Recursion
Hard
null
2,724
18
# Complexity\n- Time complexity:\nBetter than 90%\n\n- Space complexity:\nBetter than 90%\n\n# Code\n```\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n # Initialize the pointers for the input string and the pattern\n i = 0\n j = 0\n \n # Initialize the pointers for the last character matched and the last\n # \'*\' encountered in the pattern\n last_match = 0\n star = -1\n \n # Loop through the input string and the pattern\n while i < len(s):\n # Check if the current characters in the input string and the pattern\n # match, or if the pattern character is a \'?\'\n if j < len(p) and (s[i] == p[j] or p[j] == \'?\'):\n # Move the pointers for the input string and the pattern forward\n i += 1\n j += 1\n # Check if the current pattern character is a \'*\'\n elif j < len(p) and p[j] == \'*\':\n # Store the current positions of the pointers for the input string\n # and the pattern\n last_match = i\n star = j\n # Move the pointer for the pattern forward\n j += 1\n # If none of the above conditions are met, check if we have encountered\n # a \'*\' in the pattern previously\n elif star != -1:\n # Move the pointer for the pattern back to the last \'*\'\n j = star + 1\n # Move the pointer for the input string to the next character\n # after the last character matched\n i = last_match + 1\n # Move the pointer for the last character matched forward\n last_match += 1\n # If none of the above conditions are met, the input string and the\n # pattern do not match\n else:\n return False\n \n # Loop through the remaining characters in the pattern and check if they\n # are all \'*\' characters\n while j < len(p) and p[j] == \'*\':\n j += 1\n \n # Return True if all the characters in the pattern have been processed,\n # False otherwise\n return j == len(p)\n \n```
4,250
Wildcard Matching
wildcard-matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial).
String,Dynamic Programming,Greedy,Recursion
Hard
null
624
5
**Very classical question** that could be solved using **DFS + Memo** & **DP**!\n\n**General View:**\nThe challenge part is * .\nIt could match any number of characters.\nSo how to deal with * is **the key**!\n\n**Take an example:**\nIf we match * with every possible number of characters, then the divisions in each level could be many\n```\n\t\t (*ab, abc)\n\t / | \\ \\\n(ab, abc) (ab, bc) (ab, c) (ab, \'\')\n```\nIf we give match only two options, not match or match (* will stay for next level), the the divisions in each level is two.\n```\n\t(*ab, abc)\n\t / \\\n(ab, ab) (*ab, b)\t \n```\nIt is obvious that **the latter one is better**! That is how we will deal with * .\n\n**Method 1:**\n**DFS + Memoization**\n\nWhenever will come across a * , we will generate two paths, either **not match any** or **match**.\nHowever, that is not enough, since we might have duplicate states when we have ***continuing*** * .\n**For example:**\n```\n (**, abc)\n\t / \\\n\t(*, abc) (**, bc)\n\t/ \\ / \\\n(\'\', abc) (*, bc) (**, c)\n```\nThe state (* , bc) will be reached from different paths. Meaning that we could use **memoization**!\nThe time will be reduced from O(2 ^ n) to O(m * n).\n\nWe will use index of the string as the signature of each state. Every state reached will be stored in the memo hash.\n\n**Time:** O(m * n), m is the length of string s, n is the length of string p\n**Space:** O(m * n)\n\n```\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n memo = {}\n s_index, p_index = 0, 0\n return self.memo_dfs(s, s_index, p, p_index, memo)\n \n def memo_dfs(self, s, i, p, j, memo): \n \n if len(p) == j:\n return len(s) == i\n \n if len(s) == i:\n for index in range(j, len(p)):\n if p[index] != \'*\':\n return False\n return True\n \n if (i, j) in memo:\n return memo[(i, j)]\n\n if p[j] != \'*\':\n matched = (s[i] == p[j] or p[j] == \'?\') and self.memo_dfs(s, i + 1, p, j + 1, memo)\n else: # matched & not matched\n matched = self.memo_dfs(s, i + 1, p, j, memo) or self.memo_dfs(s, i, p, j + 1, memo)\n \n memo[(i, j)] = matched\n \n return matched\n```\n\n**Method 2:**\n**DP**\n\nThe idea is very similar, **dp[i][j]** means that by index i of s and by index j of p, whether there is a matching.\n\n**Time:** O(m * n), m is the length of string s, n is the length of string p\n**Space:** O(m * n)\n\n```\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n if s is None or p is None:\n return False\n \n m, n = len(s), len(p)\n \n dp = [[False] * (n + 1) for _ in range(2)]\n \n dp[0][0] = True\n for i in range(1, n + 1): # the case that p starts with some *\n dp[0][i] = dp[0][i - 1] and p[i - 1] == \'*\'\n \n for i in range(1, m + 1):\n dp[i % 2][0] = False # Note that: we might miss this!\n for j in range(1, n + 1):\n if p[j - 1] == \'*\': # match & no match \n dp[i % 2][j] = dp[(i - 1) % 2][j] or dp[i % 2][j - 1]\n else:\n dp[i % 2][j] = dp[(i - 1) % 2][j - 1] and (\n s[i - 1] == p[j - 1] or p[j - 1] == \'?\')\n \n return dp[m % 2][n]\n```
4,264
Wildcard Matching
wildcard-matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial).
String,Dynamic Programming,Greedy,Recursion
Hard
null
661
8
Simple DFS + memoization (via ```@cache```), beats 70%\n\n```\n def isMatch(self, s: str, p: str) -> bool:\n n, m = len(s), len(p)\n\n # i is index in s, j is index in p\n @cache\n def dfs(i,j):\n # reached both string and pattern ends - matched\n if i >= n and j >= m:\n return True\n\n # reached pattern end but not string end - not matched\n if j >= m:\n return False\n\n # match characters under i and j indexes (plus additional check whether we reached end of string), move both indexes forward\n if i < n and (s[i] == p[j] or p[j] == "?"):\n return dfs(i + 1, j + 1)\n\n # for wildcard there are two options:\n # 1) use it and move i forward (plus additional check whether we reached end of string)\n # 2) do not use it and move j forward\n if (p[j] == "*"):\n return (i < n and dfs(i + 1, j)) or dfs(i, j + 1)\n\n # no wildcard and not matched (or reached end of string before reaching end of pattern)\n return False\n\n return dfs(0,0)\n```
4,269
Wildcard Matching
wildcard-matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial).
String,Dynamic Programming,Greedy,Recursion
Hard
null
1,874
5
\n# Code\n```\n def isMatch(self, s: str, p: str) -> bool:\n n = len(s);\n m = len(p);\n dp = [[0]*(m+1) for _ in range(0,n+1)]\n\n dp[0][0] = 1\n for j in range(1,m+1):\n if(p[j-1] == \'*\' ): dp[0][j] = dp[0][j-1];\n\n for i in range(1,n+1):\n for j in range(1,m+1):\n if(s[i-1] == p[j-1] or p[j-1] == \'?\' ): dp[i][j] = dp[i-1][j-1]\n elif( p[j-1] == \'*\' ):\n # did we match without the chracter in s or did we match with the character before \'*\' in p\n dp[i][j] = dp[i-1][j] or dp[i][j-1]\n\n return dp[-1][-1]\n \n \n```
4,284
Wildcard Matching
wildcard-matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: The matching should cover the entire input string (not partial).
String,Dynamic Programming,Greedy,Recursion
Hard
null
27,155
66
class Solution:\n # @return a boolean\n def isMatch(self, s, p):\n length = len(s)\n if len(p) - p.count('*') > length:\n return False\n dp = [True] + [False]*length\n for i in p:\n if i != '*':\n for n in reversed(range(length)):\n dp[n+1] = dp[n] and (i == s[n] or i == '?')\n else:\n for n in range(1, length+1):\n dp[n] = dp[n-1] or dp[n]\n dp[0] = dp[0] and i == '*'\n return dp[-1]\n\ndp[n] means the substring s[:n] if match the pattern i\n\ndp[0] means the empty string '' or s[:0] which only match the pattern '*'\n\nuse the reversed builtin because for every dp[n+1] we use the previous 'dp'\n\n\n\nadd Java O(m*n) version code\n\n public boolean isMatch(String s, String p) {\n int count = 0;\n for (char c : p.toCharArray()) {\n if (c == '*')\n count++;\n }\n if (p.length() - count > s.length())\n return false;\n boolean[][] dp = new boolean[p.length() + 1][s.length() + 1];\n dp[0][0] = true;\n for (int j = 1; j <= p.length(); j++) {\n char pattern = p.charAt(j - 1);\n dp[j][0] = dp[j - 1][0] && pattern == '*';\n for (int i = 1; i <= s.length(); i++) {\n char letter = s.charAt(i - 1);\n if (pattern != '*') {\n dp[j][i] = dp[j - 1][i - 1] && (pattern == '?' || pattern == letter);\n } else\n dp[j][i] = dp[j][i - 1] || dp[j - 1][i];\n }\n }\n return dp[p.length()][s.length()];\n }
4,289
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
22,396
194
# Intuition :\n- We have to find the minimum number of jumps required to reach the end of a given array of non-negative integers i.e the shortest number of jumps needed to reach the end of an array of numbers.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Explanation to Approach :\n- We are using a search algorithm that works by moving forward in steps and counting each step as a jump. \n- The algorithm keeps track of the farthest reachable position at each step and updates the number of jumps needed to reach that farthest position. \n- The algorithm returns the minimum number of jumps needed to reach the end of the array.\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(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A\n```\n\n# Codes [C++ |Java |Python3] with Comments :\n```C++ []\nclass Solution {\n public:\n int jump(vector<int>& nums) {\n int ans = 0;\n int end = 0;\n int farthest = 0;\n\n // Implicit BFS\n for (int i = 0; i < nums.size() - 1; ++i) {\n farthest = max(farthest, i + nums[i]);\n if (farthest >= nums.size() - 1) {\n ++ans;\n break;\n }\n if (i == end) { // Visited all the items on the current level\n ++ans; // Increment the level\n end = farthest; // Make the queue size for the next level\n }\n }\n\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int jump(int[] nums) {\n int ans = 0;\n int end = 0;\n int farthest = 0;\n\n // Implicit BFS\n for (int i = 0; i < nums.length - 1; ++i) {\n farthest = Math.max(farthest, i + nums[i]);\n if (farthest >= nums.length - 1) {\n ++ans;\n break;\n }\n if (i == end) { // Visited all the items on the current level\n ++ans; // Increment the level\n end = farthest; // Make the queue size for the next level\n }\n }\n\n return ans;\n }\n}\n```\n```Python3 []\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n ans = 0\n end = 0\n farthest = 0\n\n # Implicit BFS\n for i in range(len(nums) - 1):\n farthest = max(farthest, i + nums[i])\n if farthest >= len(nums) - 1:\n ans += 1\n break\n if i == end: # Visited all the items on the current level\n ans += 1 # Increment the level\n end = farthest # Make the queue size for the next level\n\n return ans\n```\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n![ezgif-3-22a360561c.gif]()\n
4,309
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
532
8
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about finding the minimum number of jumps to reach the end of the array. We can think of this problem as Jiraiya(A popular character from Naruto Universe) trying to detect an enemy at the n-1th position using his barrier arts technique. The furthest distance he can jump from his current position is given by the value at the current index in the array.\n![image.png]()\n\nWe start from the first index and keep track of the farthest position we can reach from the current position. We also keep a barrier that indicates the end of the current jump. When we reach the barrier, we increase the jump count and update the barrier to the farthest position we can reach. We repeat this process until we reach or cross the end of the array.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nEach jump Jiraiya makes is equivalent to a loop iteration in the code. The farthest variable represents the furthest position Jiraiya can reach with his current jump, and barrier represents the end of the current jump. When Jiraiya reaches the end of his current jump (i.e., when he reaches the barrier), he makes another jump, which is represented by incrementing res in the code. This process continues until Jiraiya reaches or crosses the enemy\u2019s position (i.e., the end of the array).\n\n\n# Complexity\n- Time complexity:\nThe time complexity is O(n)\nbecause we are visiting each element in the array once.\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\nThe space complexity is O(1) because we are not using any extra space that scales with the input size.\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n n = len(nums)\n if n==1:\n return 0\n res = 0\n curr = 0\n farthest = nums[curr]\n barrier = 0\n while True:\n for positions in range(curr,barrier+1):\n farthest = max(farthest, positions+nums[positions])\n if farthest>=n-1:\n return res+1\n curr = barrier+1\n barrier = farthest\n res+=1\n```\n\nif you think the explanation was great, please consider upvoting the solution!!\n\n![image.png]()
4,311
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
4,376
66
# Consider\uD83D\uDC4D\n```\n Please Upvote If You Find It Helpful\n```\n\n# Intuition\nIn this question we have to find the minimum number of jumps to reach the last index.\nSo, we calculate the maximum index we can reach from the current index.\nIf our pointer `i` reaches the last index that can be reached with current number of jumps then we have to make a jumps.\nSo, we increase the `count`. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : Greedy Approach\n Example\n nums = [2,3,1,1,4]\n Here at index `0` reach become 2 and `i` == `last`. \n So increase the `count`(1)\n At index `1` `reach` becomes `4`.\n So, when `i` becomes `2` it becomes equal to last.\n We update last with current maximum jump(`reach`) last = 4.\n And increase `count`.\n So, answer = 2.\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(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int jump(vector<int>& nums) {\n int reach=0, count=0, last=0; // reach: maximum reachable index from current position\n // count: number of jumps made so far\n // last: rightmost index that has been reached so far\n for(int i=0;i<nums.size()-1;i++){ // loop through the array excluding the last element\n reach = max(reach, i+nums[i]); // update reach to the maximum between reach and i+nums[i]\n if(i==last){ // if i has reached the last index that can be reached with the current number of jumps\n last = reach; // update last to the new maximum reachable index\n count++; // increment the number of jumps made so far\n }\n }\n return count; // return the minimum number of jumps required\n }\n};\n\n```\n```python []\nclass Solution:\n def jump(self, nums):\n # Initialize reach (maximum reachable index), count (number of jumps), and last (rightmost index reached)\n reach, count, last = 0, 0, 0\n \n # Loop through the array excluding the last element\n for i in range(len(nums)-1): \n # Update reach to the maximum between reach and i + nums[i]\n reach = max(reach, i + nums[i])\n \n # If i has reached the last index that can be reached with the current number of jumps\n if i == last:\n # Update last to the new maximum reachable index\n last = reach\n # Increment the number of jumps made so far\n count += 1\n \n # Return the minimum number of jumps required\n return count\n\n```\n\n```\n Give a \uD83D\uDC4D. It motivates me alot\n```\nLet\'s Connect On [Linkedin]()
4,325
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
61,504
351
This problem has a nice BFS structure. Let's illustrate it using the example `nums = [2, 3, 1, 1, 4]` in the problem statement. We are initially at position `0`. Then we can move at most `nums[0]` steps from it. So, after one move, we may reach `nums[1] = 3` or `nums[2] = 1`. So these nodes are reachable in `1` move. From these nodes, we can further move to `nums[3] = 1` and `nums[4] = 4`. Now you can see that the target `nums[4] = 4` is reachable in `2` moves. \n\nPutting these into codes, we keep two pointers `start` and `end` that record the current range of the starting nodes. Each time after we make a move, update `start` to be `end + 1` and `end` to be the farthest index that can be reached in `1` move from the current `[start, end]`. \n \nTo get an accepted solution, it is important to handle all the edge cases. And the following codes handle all of them in a unified way without using the unclean `if` statements :-)\n \n----------\n**C++**\n\n class Solution {\n public:\n int jump(vector<int>& nums) {\n int n = nums.size(), step = 0, start = 0, end = 0;\n while (end < n - 1) {\n step++; \n \t\t\tint maxend = end + 1;\n \t\t\tfor (int i = start; i <= end; i++) {\n if (i + nums[i] >= n - 1) return step;\n \t\t\t\tmaxend = max(maxend, i + nums[i]);\n \t\t\t}\n start = end + 1;\n end = maxend;\n }\n \t\treturn step;\n }\n };\n\n----------\n**Python** \n\n class Solution:\n # @param {integer[]} nums\n # @return {integer}\n def jump(self, nums):\n n, start, end, step = len(nums), 0, 0, 0\n while end < n - 1:\n step += 1\n maxend = end + 1\n for i in range(start, end + 1):\n if i + nums[i] >= n - 1:\n return step\n maxend = max(maxend, i + nums[i])\n start, end = end + 1, maxend\n return step
4,346
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
10,592
102
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nSince each element of our input array (**N**) represents the maximum jump length and not the definite jump length, that means we can visit any index between the current index (**i**) and **i + N[i]**. Stretching that to its logical conclusion, we can safely iterate through **N** while keeping track of the furthest index reachable (**next**) at any given moment (**next = max(next, i + N[i])**). We\'ll know we\'ve found our solution once **next** reaches or passes the last index (**next >= N.length - 1**).\n\nThe difficulty then lies in keeping track of how many jumps it takes to reach that point. We can\'t simply count the number of times we update **next**, as we may see that happen more than once while still in the current jump\'s range. In fact, we can\'t be sure of the best next jump until we reach the end of the current jump\'s range.\n\nSo in addition to **next**, we\'ll also need to keep track of the current jump\'s endpoint (**curr**) as well as the number of jumps taken so far (**ans**).\n\nSince we\'ll want to **return ans** at the earliest possibility, we should base it on **next**, as noted earlier. With careful initial definitions for **curr** and **next**, we can start our iteration at **i = 0** and **ans = 0** without the need for edge case return expressions.\n\n - _**Time Complexity: O(N)** where N is the length of N_\n - _**Space Cmplexity: O(1)**_\n\n---\n\n#### ***Implementation:***\n\nThere are only minor differences in the code of all four languages.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **72ms / 37.7MB** (beats 95% / 100%).\n```javascript\nvar jump = function(N) {\n let len = N.length - 1, curr = -1, next = 0, ans = 0\n for (let i = 0; next < len; i++) {\n if (i > curr) ans++, curr = next\n next = Math.max(next, N[i] + i)\n }\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **16ms / 14.0MB** (beats 100% / 99%).\n```python\nclass Solution:\n def jump(self, N: List[int]) -> int:\n Nlen, curr, nxt, ans, i = len(N) - 1, -1, 0, 0, 0\n while nxt < Nlen:\n if i > curr:\n ans += 1\n curr = nxt\n nxt = max(nxt, N[i] + i)\n i += 1\n return ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **0ms / 36.1MB** (beats 100% / 85%).\n```java\nclass Solution {\n public int jump(int[] N) {\n int len = N.length - 1, curr = -1, next = 0, ans = 0;\n for (int i = 0; next < len; i++) {\n if (i > curr) {\n ans++;\n curr = next;\n };\n next = Math.max(next, N[i] + i);\n };\n return ans;\n };\n};\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 7.9MB** (beats 100% / 100%).\n```c++\nclass Solution {\npublic:\n int jump(vector<int>& N) {\n int len = N.size() - 1, curr = -1, next = 0, ans = 0;\n for (int i = 0; next < len; i++) {\n if (i > curr) ans++, curr = next;\n next = max(next, N[i] + i);\n };\n return ans;\n }\n};\n```
4,348
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
1,542
13
\uD83D\uDD34 Check out [LeetCode The Hard Way]() for more solution explanations and tutorials. \n\uD83D\uDFE0 Check out our [Discord Study Group]() for live discussion.\n\uD83D\uDFE2 Give a star on [Github Repository]() and upvote this post if you like it.\n\uD83D\uDD35 Check out [Screencast]() if you are interested.\n\n<iframe src="" frameBorder="0" width="100%" height="600"></iframe>
4,356
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
2,279
5
# Approach\nCreate an array containing minimum steps you need to take to get to the i-th position.\nWe can simply go through all elements of the array and then iterate over all possible jump lengths updating information in our array.\nWe can either jump from our current position, or some other position that we considered earlier. Take the minimum of these two and you will get an answer.\n\n# Complexity\n- Time complexity: $$O(nk)$$, where k is a sum of all jumps (sum of nums array)\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n n=len(nums)\n dp=[float(\'inf\') for _ in range(n)]\n dp[0]=0\n for i in range(n):\n for j in range(1,nums[i]+1):\n if i+j<n:\n dp[i+j]=min(dp[i+j],dp[i]+1)\n return dp[n-1]\n```
4,369
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
19,584
108
O( n ) sol. based on greedy of coverage.\n\n---\n\n**Python**:\n\n```\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n \n size = len(nums)\n \n # destination is last index\n destination = size - 1\n \n # record of current coverage, record of last jump index\n cur_coverage, last_jump_index = 0, 0\n \n # counter for jump\n times_of_jump = 0\n \n # Quick response if start index == destination index == 0\n if size == 1:\n return 0\n \n \n # Greedy strategy: extend coverage as long as possible with lazy jump\n for i in range( 0, size):\n \n # extend current coverage as further as possible\n cur_coverage = max( cur_coverage, i + nums[i] )\n \n\n # forced to jump (by lazy jump) to extend coverage \n if i == last_jump_index:\n \n # update last jump index\n last_jump_index = cur_coverage\n \n # update counter of jump by +1\n times_of_jump += 1\n \n # check if reached destination already\n if cur_coverage >= destination:\n return times_of_jump\n \n return times_of_jump\n```\n\n---\n\n**Javascript**:\n\n```\nvar jump = function(nums) {\n\n const size = nums.length;\n\n // destination is last index\n let destination = size-1;\n\n let curCoverage = 0, lastJumpIdx = 0;\n\n // counter of jump\n let timesOfJump = 0;\n\n // Quick response if start index == destination index == 0\n if( size == 1 ){\n return 0;\n }\n\n\n // Greedy stragegy: extend coverage as long as possible with lazp jump\n for( let i = 0 ; i < size ; i++){\n\n // extend coverage\n curCoverage = Math.max(curCoverage, i + nums[i] );\n\n // forced to jump (by lazy jump) to extend coverage\n if( i == lastJumpIdx ){\n\n lastJumpIdx = curCoverage;\n\n timesOfJump++;\n\n // check if we reached destination already\n if( curCoverage >= destination){\n return timesOfJump;\n }\n }\n }\n\n return timesOfJump;\n \n\n};\n```\n\n---\n\n**C++**:\n\n```\nclass Solution {\npublic:\n int jump(vector<int>& nums) {\n \n const int size = nums.size();\n \n // destination is last index\n int destination = size-1;\n \n int curCoverage = 0, lastJumpIdx = 0;\n \n // counter of jump\n int timesOfJump = 0;\n \n // Quick response if start index == destination index == 0\n if( size == 1 ){\n return 0;\n }\n \n \n // Greedy stragegy: extend coverage as long as possible with lazp jump\n for( int i = 0 ; i < size ; i++){\n \n // extend coverage\n curCoverage = max(curCoverage, i + nums[i] );\n \n // forced to jump (by lazy jump) to extend coverage\n if( i == lastJumpIdx ){\n \n lastJumpIdx = curCoverage;\n \n timesOfJump++;\n \n // check if we reached destination already\n if( curCoverage >= destination){\n return timesOfJump;\n }\n }\n }\n \n return timesOfJump;\n }\n};\n```\n\n---\n\n**Java**:\n\n```\nclass Solution {\n public int jump(int[] nums) {\n final int size = nums.length;\n\n // destination is last index\n int destination = size-1;\n\n int curCoverage = 0, lastJumpIdx = 0;\n\n // counter of jump\n int timesOfJump = 0;\n\n // Quick response if start index == destination index == 0\n if( size == 1 ){\n return 0;\n }\n\n\n // Greedy stragegy: extend coverage as long as possible with lazp jump\n for( int i = 0 ; i < size ; i++){\n\n // extend coverage\n curCoverage = Math.max(curCoverage, i + nums[i] );\n\n // forced to jump (by lazy jump) to extend coverage\n if( i == lastJumpIdx ){\n\n lastJumpIdx = curCoverage;\n\n timesOfJump++;\n\n // check if we reached destination already\n if( curCoverage >= destination){\n return timesOfJump;\n }\n }\n }\n\n return timesOfJump;\n }\n}\n```
4,372
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
1,870
6
\n# Code\n```\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n n=len(nums)\n dp=[-1 for _ in range(n-1)]\n dp+=[0]\n for i in range(n-2,-1,-1):\n for j in range(i+1,min(n,i+nums[i]+1)):\n if dp[j]!=-1:\n if dp[i]==-1:\n dp[i]=dp[j]+1\n else:\n dp[i]=min(dp[i],dp[j]+1)\n return dp[0]\n```
4,393
Jump Game II
jump-game-ii
Given an array of non-negative integers nums, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. You can assume that you can always reach the last index.
Array,Dynamic Programming,Greedy
Medium
null
1,376
8
```\nclass Solution:\n def jump(self, nums: List[int]) -> int:\n\n x = [nums[i]+i for i in range(len(nums))] \n # each element in this represent max index that can be reached from the current index \n\n l,r,jumps = 0,0,0\n\n while r < len(nums)-1 :\n jumps += 1\n l,r = r+1,max(x[l:r+1]) \n\n return jumps\n```
4,394
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
1,649
6
<iframe width="560" height="315" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\n List<List<Integer>> result;\n public List<List<Integer>> permute(int[] nums) {\n result = new ArrayList<>();\n helper(new ArrayList<>(), nums);\n return result;\n }\n \n public void helper(List<Integer> curr, int[] nums) {\n if (curr.size() == nums.length) {\n result.add(new ArrayList<>(curr));\n return;\n }\n \n for (int num: nums) {\n if (!curr.contains(num)) {\n curr.add(num);\n helper(curr, nums);\n curr.remove(curr.size() - 1);\n }\n }\n }\n}\n```\n\n```\nclass Solution {\npublic:\n vector<vector<int>> result;\n \n vector<vector<int>> permute(vector<int>& nums) {\n vector<int> curr;\n helper(curr, nums);\n return result;\n }\n \n void helper(vector<int>& curr, vector<int>& nums) {\n if (curr.size() == nums.size()) {\n result.push_back(curr);\n return;\n }\n \n for (int num : nums) {\n if (find(curr.begin(), curr.end(), num) == curr.end()) {\n curr.push_back(num);\n helper(curr, nums);\n curr.pop_back();\n }\n }\n }\n};\n\n```\n\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n result = []\n self.helper([], nums, result)\n return result\n \n def helper(self, curr, nums, result):\n if len(curr) == len(nums):\n result.append(curr.copy())\n return\n \n for num in nums:\n if num not in curr:\n curr.append(num)\n self.helper(curr, nums, result)\n curr.pop()\n\n```
4,413
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
31,210
484
--------------------------\n**Approach 1: Recursive with backtracking (implicit stack)**\n--------------------------\n--------------------------\n\n**Big-O:**\n- **Time:** `O(N*N!)` \n\t- **Why O(N*N!) and not just O(N!) ?**\n\tMany people are debating in the solution tab whether time-complexity should be `O(N!)` or `O(N * N!)`. Below are two intuitive arguments as to why it should be `O(N*N!)`. Let\'s forget for a while about the recursive nature of the algorithm and examine the **N-ary, recursive, space-tree** that is generated by the recursive algorithm. \n\t\t\n\t\t![image]()\n\t\t\n\t1) In order to reaverse the tree, will visit each node once, we know very well that would cost us `O(N)` in a binary tree and `O(E+V)` in an N-ary tree where V = vertices and E = edges (or number of children). Now for the [1,2,3] example shown in the sketch, we can see there is a total of 16 nodes/verticies and that |E| varies from level to level with an upper limit of N and a lower limit of 1.\n\t\t* So, we can say roughly O(E+V) = a little more than 16\t\n\t\t* O(N!) on the other hand = 6\n\t\t* whereas, O(N*N!) = 3*6 = 18\n\n\t2) Another way of looking at is we know from set theory that there are N! permutations of a list of size N. We also know that the permutations are going to be the leaves of the tree, which means we will have N! leaves. In order to get to each one of those leaves, we had to go through N calls. That\'s O(N*N!). Again a little more than the total number of nodes because some nodes are shared among more than one path.\n\n\n- **Space:** `O(N!)` \n\t- Because you still need to store the permutations and there are N! of them even if the depth of the stack is maxed out at N+1 (depth of the recursion space-tree is also N+1). See figure below.\n\n\n**Code:**\n```\ndef permute(self, nums):\n\t# helper\n\tdef recursive(nums, perm=[], res=[]):\n\t\tif not nums: # -- NOTE [1] \n\t\t\tres.append(perm[::]) # -- NOTE [2] - append a copy of the perm at the leaf before we start popping/backtracking\n\n\t\tfor i in range(len(nums)): # [1,2,3]\n\t\t\tnewNums = nums[:i] + nums[i+1:]\n\t\t\tperm.append(nums[i])\n\t\t\trecursive(newNums, perm, res) # - recursive call will make sure I reach the leaf\n\t\t\tperm.pop() # -- NOTE [3] \n\t\treturn res\n\nreturn recursive(nums)\n\n# NOTE [1]:\n# --------\n# nums is empty at the leaf of the recursive tree\n\n# NOTE [2]:\n# --------\n# at the leaf -> we know we have exaushted one path/permutation (each path is a permutation in a recursive tree)\n# reason why we are copying here is because at lists are passed by reference and since we are maintaining only one path/perm variable throughput, we are gonna be modifiying that path variable (popping it to be precise) in order to revert the path to a previous state (aka parent node) in preperation to make a lateral/horizontal move to a sibling node. See explanation below for further understanding.\n\n# NOTE [3]:\n# ---------\n# See below\n```\n\n**NOTE [3] Explained further : Why do we need to backtrack?** \n\n* Notice how in the code above, there is only one variable path (or perm) throughout the problem. This variable is passed to one recursive call after another recursive call as we move from the input (the root of the tree) to the leaf (the permutation) and obvioulsy it gets modified multiple times along the way. As we keep building the path (or perm). It goes from `[ ] -> [1,2] -> [1,2,3]` as you can see in the left-most branch. However, what actually happens is that everytime we append a number to the path, **we are actively changing the path from previous recursive states as well**, since all of these point to the same path list and are not independent states/copies. Since effectively all these aliases are pointing to the same memory location, any change to the variable are echoed to all of its aliases. This can be problematic because it alters the the previous states. See below for visual illustration of the problem.\n\t\n![image]()\n\n\n\n* To overcome this problem, we need to backtrack. It\'s tempting to think backtracking is needed only in situations where we encounter an obstacle while building/searching for the solution (such as hitting a wall while traversing a maze), however, backtracking as a technique has broader scope than just that. Any situation where we might need to access a previous state of a variable that keeps changing during the execution of the program requires backtracking. As mentioned earlier an coming across an obstacle in a maze (or anything that renders the path being explored invalid) is NOT the only incident backtracking is called upon. Backtracking would still be required even if the current path being explored is valid, in order to explore the next path. Think of a parent node from which two child nodes diverge. After exploring the first child, we need to backtrack to parent to investigate the sibling node (other child). This situation takes place in our space-tree. See sketch below.\n\n![image]()\n\n\n- As you can see in the sketch above, by the time we reach node B, the path = [1,2,3]. These changes are echoed up to the parent node and even all the way up to the root if we don\'t backtrack which will ruin subsequent paths (ex: ParentNode -> node C) is missed up. This can be alleviated by popping the path after each recursive call as we did in our code.\n\n\t```\n\tfor i in range(len(nums)): # [1,2,3]\n\t\tnewNums = nums[:i] + nums[i+1:]\n\t\tperm.append(nums[i])\n\t\trecursive(newNums, perm, res) \n\t\tperm.pop() # -- BACKTRACK\n\t```\n\n- It\'s also worth-mentioning that backtracking was needed here because of the branching nature of the space-tree. Backtracking won\'t be required if the recursive algorithm produces a linked-list rather than a space-tree. An example of such algorithm is recursively summing up numbers from 0 -> N\n\n\t```\n\tdef sumPosNumLessThanN(N, res=0):\n\t\tif N == 0:\n\t\t\treturn res\n\t\telse:\n\t\t\tres = 1 + sumPosNumLessThanN(N-1)\n\t\treturn res\n\t```\n\t\n\tThe recursive algorithm above produces a chain of nodes (no branching):\n![image]()\n\n**NOTE [2] Explained further : Why do we need to copy?** \n- You probably have guessed it by now. As shown above, due to the constantly changing state of our data/variables, we need to append a copy of the path `res.append(path[::])` at the leaf, instead of appending the path itself. The reason being that lists are mutable and are passed by reference, so even after appending a path to our result list, that path will still be affected by any changes to its aliases (will be afftected by all the poppping and backtracking taking place) and by the time our recursion calls make their way to the top/root, the path will be empty `path = [ ]`\n\n**Backtracking seems like a pain in the a$$. Is there a way around it?**\n* Glad you asked, yes, there is! We can avoid backtracking all together with a little bit of book-keeping. Instead of having to backtrack to revert to a previous state of the data/variables, we could save snapshots of the data/variables at each step along the way so that we never have to manually backtrack. This can be done either recursively or iteratively by passing a copy of our data. See Approach 2 for recursive without backtracking, and Approach 3 for an itertaive solution without backtracking below.\n.\n.\n--------------------------\n**Appraoch 2: Recursive without backtracking (implicit stack)**\n--------------------------\n--------------------------\n**Big-O:**\n- Time: `O(N*N!)`\n- Space: `O(N!)`\n\n**Code:**\n```\ndef recursive(nums, perm=[], res=[]):\n \n if not nums: \n res.append(perm) # --- no need to copy as we are not popping/backtracking. Instead we\'re passing a new variable each time \n\n for i in range(len(nums)): \n newNums = nums[:i] + nums[i+1:]\n # perm.append(nums[i]) # --- instead of appending to the same variable\n newPerm = perm + [nums[i]] # --- new copy of the data/variable\n recursive(newNums, newPerm, res) \n # perm.pop() # --- no need to backtrack\n return res\n \n return recursive(nums)\n```\n\n**How backtracking was avoided? Approach 2 vs. Approach 3**\n* Below is a comparison between the two approaches. Notice how on the left side, only one `perm/path` variable is maintained throughout as opposed to multiple `perm/path` snapshots at each step on the right hand side.\n\n![image]()\n\n\n* Illustartions above are generated using this [Python Tutor tool]()\n\t* Approach 2 : Recursive w backtracking : [here]( \n)\n\t* Approach 3: Recursive w/o backtracking : [here]()\n.\n.\n--------------------------\n**Approach 3 : DFS Iterative with Explicit Stack**\n--------------------------\n--------------------------\n**Big-O:**\n- Time: `O(E+V)` which is the same as => `O(N*N!)`\n- Space: `O(N!)`\n\n**Code:**\n``` \ndef recursive(nums):\n\t stack = [(nums, [])] # -- nums, path (or perms)\n\t res = []\n\t while stack:\n\t\t nums, path = stack.pop()\n\t\t if not nums:\n\t\t\t res.append(path)\n\t\t for i in range(len(nums)): # -- NOTE [4]\n\t\t\t newNums = nums[:i] + nums[i+1:]\n\t\t\t stack.append((newNums, path+[nums[i]])) # -- just like we used to do (path + [node.val]) in tree traversal\n\t return res\n\n# NOTE [4]\n# The difference between itertaive tree/graph traversal we did before and this one is that\n# in most tree/graph traversals we are given the DS (tree/graph/edges) whereas here we have to build the nodes before we # traverse them\n# Generating the nodes is very simple, we Each node will be (nums, pathSofar)\n```\n\n.\n.\n--------------------------\n**Approach 4 : BFS Iterative with a queue**\n--------------------------\n--------------------------\n**Big-O:**\n- Time: `O(E+V)` which is the same as => `O(N*N!)`\n- Space: `O(N!)`\n\n**Code:**\n```\ndef recursive(nums):\n\tfrom collections import deque\n\tq = deque()\n\tq.append((nums, [])) # -- nums, path (or perms)\n\tres = []\n\twhile q:\n\t\tnums, path = q.popleft()\n\t\tif not nums:\n\t\t\tres.append(path)\n\t\tfor i in range(len(nums)):\n\t\t\tnewNums = nums[:i] + nums[i+1:]\n\t\t\tq.append((newNums, path+[nums[i]]))\n\treturn res\n \n```\n\n- **For JAVA implementation of all 4 approaches : checkout this post** =>
4,414
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
9,411
41
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfor every number all the positions are available if it is not filled so we can put anywhere and recursively call and generate.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\n\n or link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n1. Define a recursive function `solve` that generates permutations using backtracking. This function takes three parameters: `nums` (the original array of integers), `per` (the current permutation being constructed), and `c` (the current index indicating which element of `nums` is being considered).\n\n2. In the `solve` function, if the current index `c` reaches the length of `nums`, it means we have completed constructing one permutation. Therefore, we add the current permutation `per` to the `ans` vector.\n\n3. If the current index `c` is not equal to the length of `nums`, we continue generating permutations. For each position `i` in the current permutation `per`, if `per[i]` is equal to 11 (a marker used to indicate that the position is available), we set `per[i]` to the element at index `c` in the `nums` array, call the `solve` function recursively with `c+1` to consider the next element in `nums`, and then reset `per[i]` back to 11 after the recursive call (backtracking step).\n\n4. In the `permute` function, initialize a vector `per` with 11 as a placeholder value of the same length as `nums`. This vector will be used to construct the permutations.\n\n5. Call the `solve` function with the original `nums` array, the initial permutation `per`, and the starting index `0` to generate all possible permutations.\n\n6. Return the resulting `ans` vector, which contains all unique permutations of the input array `nums`.\n\n# Complexity\n- Time complexity:$$O(n*n!)$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(n!)$$ for ans vector otherwise without taking that space only $$(n)$$ per array size. \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\nclass Solution {\npublic:\nvector<vector<int>>ans;\n void solve(vector<int>& nums,vector<int>&per,int c){\n if(c==nums.size()){\n ans.push_back(per);\n return;\n }\n for(int i=0;i<nums.size();i++){\n if(per[i]==11){\n per[i]=nums[c];\n solve(nums,per,c+1);\n per[i]=11;\n }\n }\n }\n vector<vector<int>> permute(vector<int>& nums) {\n int n=nums.size();\n vector<int>per(n,11);\n solve(nums,per,0);\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n List<List<Integer>> ans = new ArrayList<>();\n\n void solve(int[] nums, int[] per, int c) {\n if (c == nums.length) {\n List<Integer> permutation = new ArrayList<>();\n for (int num : per) {\n permutation.add(num);\n }\n ans.add(permutation);\n return;\n }\n for (int i = 0; i < nums.length; i++) {\n if (per[i] == 11) {\n per[i] = nums[c];\n solve(nums, per, c + 1);\n per[i] = 11;\n }\n }\n }\n\n public List<List<Integer>> permute(int[] nums) {\n int n = nums.length;\n int[] per = new int[n];\n for (int i = 0; i < n; i++) {\n per[i] = 11;\n }\n solve(nums, per, 0);\n return ans;\n }\n}\n\n```\n```python []\nclass Solution:\n def permute(self, nums):\n def solve(nums, per, c):\n if c == len(nums):\n ans.append(list(per))\n return\n for i in range(len(nums)):\n if per[i] == 11:\n per[i] = nums[c]\n solve(nums, per, c + 1)\n per[i] = 11\n\n ans = []\n per = [11] * len(nums)\n solve(nums, per, 0)\n return ans\n\n```\n# Recursive tree for same\n![Screenshot (306).png]()\n\n# upvote if you understood the solution .
4,415
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
7,647
51
# Intuition\nWhen I first looked at this problem, I realized it was a classic case of generating all possible permutations of a given list of numbers. My initial thought was to use a recursive approach to solve it. Recursive algorithms, especially backtracking, often provide a clean and efficient solution for generating permutations. I implemented two different versions of the solution in Python, both capitalizing on recursion and backtracking.\n\nBoth versions achieve the same result, but v2 provides more granular control over the recursive process. Version 1 has also been implemented in other programming languages including C++, JavaScript, C#, Java, Rust, Swift, and Go, demonstrating the versatility and applicability of the recursive backtracking approach across different coding environments.\n\n\n\n# Approach\nThe main approach here is to use recursion (a form of backtracking) to generate all permutations of the input list. Here\'s a detailed step-by-step guide:\n\n1. **Initialize Result**: Create an empty list, `result`, to store the final permutations.\n\n2. **Define Backtracking Function**: Define a recursive helper function `backtrack`, which takes the remaining numbers to be permuted (`nums`) and the current permutation (`path`) as parameters.\n \n a. **Base Case**: If there are no numbers left to permute (`nums` is empty), we have a complete permutation, and we add the current `path` to the `result`.\n \n b. **Recursive Case**: For each number in `nums`, we perform the following steps:\n i. Add the current number to `path`.\n ii. Remove the current number from `nums`.\n iii. Recursively call `backtrack` with the updated `nums` and `path`.\n iv. Since we are using slicing to create new lists, there is no need to revert the changes to `nums` and `path` after the recursive call.\n\n3. **Start Recursion**: Call the `backtrack` function with the original `nums` and an empty `path` to start the process.\n\n4. **Return Result**: Return the `result` list, which will contain all the permutations.\n\nBy iteratively choosing one element and recursively calling the function on the remaining elements, this approach ensures that all permutations are explored.\n\n# Complexity\n- Time complexity: O(n*n!) \n This is because for generating permutations, we perform n! operations (since there are n! permutations for n numbers) and for each operation, we spend O(n) time for slicing the list in our recursive call.\n\n- Space complexity: O(n*n!) \n This is due to the number of solutions. In the worst case, if we have \'n\' distinct numbers, there would be n! permutations. Since each permutation is a list of \'n\' numbers, the space complexity is O(n*n!).\n\n# Code\n``` Python []\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n def backtrack(nums, path): \n if not nums: \n result.append(path) \n return \n for i in range(len(nums)): \n backtrack(nums[:i] + nums[i+1:], path + [nums[i]]) \n result = [] \n backtrack(nums, []) \n return result \n```\n``` C++ []\nclass Solution {\npublic:\n void permuteRec(vector<int>& nums, int begin, vector<vector<int>>& result) { \n if (begin == nums.size()) { \n result.push_back(nums); \n return; \n } \n for (int i = begin; i < nums.size(); i++) { \n swap(nums[begin], nums[i]); \n permuteRec(nums, begin + 1, result); \n swap(nums[begin], nums[i]); \n } \n } \n \n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> result; \n permuteRec(nums, 0, result); \n return result; \n \n }\n};\n```\n``` JavaScript []\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nvar permute = function(nums) {\n const result = [];\n const backtrack = (nums, path) => {\n if (nums.length === 0) {\n result.push(path);\n return;\n }\n for (let i = 0; i < nums.length; i++) {\n backtrack([...nums.slice(0, i), ...nums.slice(i + 1)], [...path, nums[i]]);\n }\n };\n backtrack(nums, []);\n return result;\n};\n```\n``` C# []\npublic class Solution {\n public IList<IList<int>> Permute(int[] nums) {\n IList<IList<int>> result = new List<IList<int>>();\n Backtrack(nums, new List<int>(), result);\n return result;\n }\n\n private void Backtrack(int[] nums, List<int> path, IList<IList<int>> result) {\n if (path.Count == nums.Length) {\n result.Add(new List<int>(path));\n return;\n }\n foreach (int num in nums) {\n if (path.Contains(num)) continue;\n path.Add(num);\n Backtrack(nums, path, result);\n path.RemoveAt(path.Count - 1);\n }\n }\n}\n```\n``` Java []\npublic class Solution {\n public void permuteRec(int[] nums, int begin, List<List<Integer>> result) {\n if (begin == nums.length) {\n List<Integer> temp = new ArrayList<Integer>();\n for (int num : nums) temp.add(num);\n result.add(temp);\n return;\n }\n for (int i = begin; i < nums.length; i++) {\n // Swap\n int temp = nums[begin];\n nums[begin] = nums[i];\n nums[i] = temp;\n \n permuteRec(nums, begin + 1, result);\n \n // Swap back\n temp = nums[begin];\n nums[begin] = nums[i];\n nums[i] = temp;\n }\n }\n \n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n permuteRec(nums, 0, result);\n return result;\n }\n}\n```\n``` Rust []\nimpl Solution {\n pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {\n let mut result = Vec::new();\n Self::backtrack(nums, vec![], &mut result);\n result\n }\n\n fn backtrack(nums: Vec<i32>, path: Vec<i32>, result: &mut Vec<Vec<i32>>) {\n if nums.is_empty() {\n result.push(path);\n return;\n }\n for i in 0..nums.len() {\n let mut new_nums = nums.clone();\n new_nums.remove(i);\n let mut new_path = path.clone();\n new_path.push(nums[i]);\n Self::backtrack(new_nums, new_path, result);\n }\n }\n}\n```\n``` Swift []\nclass Solution {\n func permute(_ nums: [Int]) -> [[Int]] {\n var result: [[Int]] = []\n \n func backtrack(_ nums: [Int], _ path: [Int]) {\n if nums.isEmpty {\n result.append(path)\n return\n }\n for i in 0..<nums.count {\n var newNums = nums\n newNums.remove(at: i)\n backtrack(newNums, path + [nums[i]])\n }\n }\n \n backtrack(nums, [])\n return result\n }\n}\n```\n``` Go []\nfunc permute(nums []int) [][]int {\n var result [][]int\n \n var backtrack func([]int, []int)\n backtrack = func(nums []int, path []int) {\n if len(nums) == 0 {\n result = append(result, append([]int(nil), path...))\n return\n }\n for i := 0; i < len(nums); i++ {\n newNums := append([]int(nil), nums[:i]...)\n newNums = append(newNums, nums[i+1:]...)\n newPath := append([]int(nil), path...)\n newPath = append(newPath, nums[i])\n backtrack(newNums, newPath)\n }\n }\n \n backtrack(nums, []int{})\n return result\n}\n```\n\n# Video for Python v2\n\n\n# Code v2\n``` Python \nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n def dfs(path, used): \n if len(path) == len(nums): \n result.append(path[:]) \n return \n for i in range(len(nums)): \n if not used[i]: \n path.append(nums[i]) \n used[i] = True \n dfs(path, used) \n path.pop() \n used[i] = False \n result = [] \n dfs([], [False] * len(nums)) \n return result \n```\n\n## Performance \n| Language | Runtime | Beats | Memory |\n|------------|---------|---------|---------|\n| C++ | 0 ms | 100% | 7.5 MB |\n| Java | 1 ms | 98.58% | 44.1 MB |\n| Rust | 1 ms | 87.70% | 2.3 MB |\n| Go | 2 ms | 61.28% | 3.1 MB |\n| Swift | 8 ms | 91.96% | 14.4 MB |\n| Python3 v2 | 36 ms | 99.39% | 16.5 MB |\n| Python3 | 39 ms | 98.74% | 16.7 MB |\n| JavaScript | 72 ms | 55% | 44.1 MB |\n| C# | 131 ms | 94.50% | 43.4 MB |\n\nThis sorted table provides a quick comparison of the runtime performance across different programming languages for the given problem.
4,416
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
117,273
640
\n # DFS\n def permute(self, nums):\n res = []\n self.dfs(nums, [], res)\n return res\n \n def dfs(self, nums, path, res):\n if not nums:\n res.append(path)\n # return # backtracking\n for i in xrange(len(nums)):\n self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)
4,447
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
1,561
23
# Approach\nUse a recursive function `backtrack`, in the function, we pass in a index.\nIn the function, we use a for loop swap `nums[index]` with different numbers in `nums`.\nAfter each swap, call `backtrack` again with `index+1`.\nThen swap back the values, so that we can get every permutations as the graph shown below.\n\nIf `index` reach `n-1`, we kwon that we get one of the premutations.\nSo just add `nums` into `arr`.\nAfter all the recursion, we get our answer.\n \n![image.png]()\n\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> arr;\n void backtrack(vector<int>& nums, int n, int index){\n if(index == n - 1){\n arr.push_back(nums);\n return;\n }\n for(int i=index; i<n; i++){\n swap(nums[index], nums[i]);\n backtrack(nums, n, index+1);\n swap(nums[index], nums[i]);\n }\n }\n vector<vector<int>> permute(vector<int>& nums) {\n int n = nums.size();\n backtrack(nums, n, 0);\n return arr;\n }\n};\n```\n```c []\n void swap(int* a, int* b){\n int temp = *a;\n *a = *b;\n *b = temp;\n }\n\n void backtrack(int* nums, int numsSize, int*** arr, int* returnSize, int** returnColumnSizes, int index){\n if(index == numsSize - 1){\n (*returnSize)++;\n *arr = (int**)realloc(*arr, sizeof(int*) * (*returnSize));\n (*returnColumnSizes)[*returnSize - 1] = numsSize;\n (*arr)[*returnSize - 1] = (int*)malloc(sizeof(int) * numsSize);\n for(int i=0; i<numsSize; i++){\n (*arr)[*returnSize - 1][i] = nums[i];\n }\n return;\n }\n for(int i=index; i<numsSize; i++){\n swap(nums+index, nums+i);\n backtrack(nums, numsSize, arr, returnSize, returnColumnSizes, index + 1);\n swap(nums+index, nums+i);\n }\n }\n\nint** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){\n *returnSize = 1;\n for(int i=1; i<=numsSize; i++) (*returnSize) *= i;\n *returnColumnSizes = (int*)malloc(*returnSize * sizeof(int)); \n *returnSize = 0;\n int **arr = (int**)malloc(sizeof(int*));\n backtrack(nums, numsSize, &arr, returnSize, returnColumnSizes, 0);\n return arr;\n}\n\n```\n```Python []\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n n = len(nums)\n arr = []\n\n def backtrack(index):\n if(index == n):\n arr.append(nums[:])\n return\n for i in range(index, n):\n nums[index], nums[i] = nums[i], nums[index] # swap\n backtrack(index + 1)\n nums[index], nums[i] = nums[i], nums[index] # swap back\n \n backtrack(0)\n return arr\n```\n# Please UPVOTE if this helps\n![image.png]()\n![image.png]()\n\n
4,452
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
38,585
244
Classic combinatorial search problem, we can solve it using 3-step system \n\n1. Identify states\nWhat state do we need to know whether we have reached a solution (and using it to construct a solution if the problem asks for it).\nWe need a state to keep track of the list of letters we have chosen for the current permutation\n\nWhat state do we need to decide which child nodes should be visited next and which ones should be pruned?\nWe have to know what are the letters left that we can still use (since each letter can only be used once).\n\n2. Draw the State-space Tree\n![]()\n\n3. DFS on the State-space tree\nUsing the [backtracking template]() as basis, we add the two states we identified in step 1:\n\nA list to represent permutation constructed so far, path\nA list to record which letters are already used, used, used[i] == true means ith letter in the origin list has been used.\n\nImplementation in 3 languages:\n\nPython\n```\nclass Solution:\n def permute(self, l: List[int]) -> List[List[int]]:\n def dfs(path, used, res):\n if len(path) == len(l):\n res.append(path[:]) # note [:] make a deep copy since otherwise we\'d be append the same list over and over\n return\n\n for i, letter in enumerate(l):\n # skip used letters\n if used[i]:\n continue\n # add letter to permutation, mark letter as used\n path.append(letter)\n used[i] = True\n dfs(path, used, res)\n # remove letter from permutation, mark letter as unused\n path.pop()\n used[i] = False\n \n res = []\n dfs([], [False] * len(l), res)\n return res\n```\n\nJava\n```\nclass Solution {\n public List<List<Integer>> permute(int[] letters) {\n List<List<Integer>> res = new ArrayList<>();\n dfs(new ArrayList<>(), new boolean[letters.length], res, letters);\n return res;\n }\n\n private static void dfs(List<Integer> path, boolean[] used, List<List<Integer>> res, int[] letters) {\n if (path.size() == used.length) {\n // make a deep copy since otherwise we\'d be append the same list over and over\n res.add(new ArrayList<Integer>(path));\n return;\n }\n\n for (int i = 0; i < used.length; i++) {\n // skip used letters\n if (used[i]) continue;\n // add letter to permutation, mark letter as used\n path.add(letters[i]);\n used[i] = true;\n dfs(path, used, res, letters);\n // remove letter from permutation, mark letter as unused\n path.remove(path.size() - 1);\n used[i] = false;\n }\n } \n}\n```\n\nJavascript\n```\nvar permute = function(letters) {\n let res = [];\n dfs(letters, [], Array(letters.length).fill(false), res);\n return res;\n}\n\nfunction dfs(letters, path, used, res) {\n if (path.length == letters.length) {\n // make a deep copy since otherwise we\'d be append the same list over and over\n res.push(Array.from(path));\n return;\n }\n for (let i = 0; i < letters.length; i++) {\n // skip used letters\n if (used[i]) continue;\n // add letter to permutation, mark letter as used\n path.push(letters[i]);\n used[i] = true;\n dfs(letters, path, used, res);\n // remove letter from permutation, mark letter as unused\n path.pop();\n used[i] = false;\n }\n}\n```\n\nPlease upvote if you find it useful. And learn more about backtracking/dfs here
4,458
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
1,804
10
# Intuition\nThe problem requires generating all possible permutations of a given array of distinct integers. A clear and intuitive understanding of the recursive approach can be achieved by watching vanAmsen\'s video explanation, where the permutations are constructed by choosing one element at a time and recursively calling the function on the remaining elements. The video thoroughly explains the underlying logic and how to implement it in code. Special thanks to vanAmsen for the insightful explanation! [Watch the video here]().\n\n\n# Approach\n1. We define a recursive function `backtrack` that takes the current numbers and the path of the permutation being constructed.\n2. In the base case, if there are no numbers left, we append the current path to the result list.\n3. We iterate through the numbers, and for each number, we add it to the current path and recursively call `backtrack` with the remaining numbers (excluding the current number).\n4. We initialize an empty result list and call the `backtrack` function with the original numbers and an empty path to start the process.\n5. The result list will contain all the permutations, and we return it.\n\n# Complexity\n- Time complexity: \\(O(n!)\\)\n - We generate \\(n!\\) permutations, where \\(n\\) is the length of the input list.\n\n- Space complexity: \\(O(n)\\)\n - The maximum depth of the recursion is \\(n\\), and we use additional space for the current path and slicing operations.\n\n# Code\n``` Python []\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n def backtrack(nums, path): \n if not nums: \n result.append(path) \n return \n for i in range(len(nums)): \n backtrack(nums[:i] + nums[i+1:], path + [nums[i]]) \n result = [] \n backtrack(nums, []) \n return result \n```\n``` C++ []\nclass Solution {\npublic:\n void permuteRec(vector<int>& nums, int begin, vector<vector<int>>& result) { \n if (begin == nums.size()) { \n result.push_back(nums); \n return; \n } \n for (int i = begin; i < nums.size(); i++) { \n swap(nums[begin], nums[i]); \n permuteRec(nums, begin + 1, result); \n swap(nums[begin], nums[i]); \n } \n } \n \n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> result; \n permuteRec(nums, 0, result); \n return result; \n \n }\n};\n```\n``` JavaScript []\nvar permute = function(nums) {\n let result = []; \n permuteRec(nums, 0, result); \n return result; \n \n};\n\nfunction permuteRec(nums, begin, result) { \n if (begin === nums.length) { \n result.push(nums.slice()); \n return; \n } \n for (let i = begin; i < nums.length; i++) { \n [nums[begin], nums[i]] = [nums[i], nums[begin]]; \n permuteRec(nums, begin + 1, result); \n [nums[begin], nums[i]] = [nums[i], nums[begin]]; \n } \n} \n```\n``` C# []\npublic class Solution {\n public void PermuteRec(int[] nums, int begin, IList<IList<int>> result) {\n if (begin == nums.Length) {\n var temp = new List<int>(nums);\n result.Add(temp);\n return;\n }\n for (int i = begin; i < nums.Length; i++) {\n // Swap\n int temp = nums[begin];\n nums[begin] = nums[i];\n nums[i] = temp;\n \n PermuteRec(nums, begin + 1, result);\n \n // Swap back\n temp = nums[begin];\n nums[begin] = nums[i];\n nums[i] = temp;\n }\n }\n \n public IList<IList<int>> Permute(int[] nums) {\n IList<IList<int>> result = new List<IList<int>>();\n PermuteRec(nums, 0, result);\n return result;\n }\n}\n```\n``` Java []\npublic class Solution {\n public void permuteRec(int[] nums, int begin, List<List<Integer>> result) {\n if (begin == nums.length) {\n List<Integer> temp = new ArrayList<Integer>();\n for (int num : nums) temp.add(num);\n result.add(temp);\n return;\n }\n for (int i = begin; i < nums.length; i++) {\n // Swap\n int temp = nums[begin];\n nums[begin] = nums[i];\n nums[i] = temp;\n \n permuteRec(nums, begin + 1, result);\n \n // Swap back\n temp = nums[begin];\n nums[begin] = nums[i];\n nums[i] = temp;\n }\n }\n \n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n permuteRec(nums, 0, result);\n return result;\n }\n}\n```
4,468
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
3,152
18
# Intuition\nUsing backtracking to create all possible combinations\n\n---\n\n# Solution Video\n## *** Please upvote for this article. *** \n\n\n\n# Subscribe to my channel from here. I have 238 videos as of August 2nd\n\n\n---\n\n# Approach\nThis is based on Python solution. Other might be different a bit.\n\n1. The function `permute` takes a list of integers `nums` as input and aims to generate all possible permutations of the elements in the input list.\n\n2. The base case is checked: if the length of the `nums` list is 1, then it means there\'s only one element left to permute, and at this point, a list containing that single element is returned as a permutation.\n\n3. If the `nums` list has more than one element, the algorithm proceeds with permutation generation.\n\n4. Initialize an empty list `res` to store the permutations.\n\n5. Iterate over each element in the `nums` list (using `_` as a placeholder for the loop variable). In each iteration, pop the first element `n` from the `nums` list.\n\n6. Recursively call the `permute` function on the remaining elements in `nums` after removing the first element. This generates all possible permutations of the remaining elements.\n\n7. For each permutation `p` generated in the recursive call, append the previously removed element `n` to it.\n\n8. Extend the `res` list with the permutations generated in the recursive calls, each with the element `n` appended.\n\n9. After the loop completes, add the removed element `n` back to the end of the `nums` list, restoring the original state for the next iteration.\n\n10. Finally, return the list `res` containing all the generated permutations.\n\nIn summary, this code uses a recursive approach to generate all possible permutations of the input list `nums`. It removes one element at a time, generates permutations for the remaining elements, appends the removed element to those permutations, and collects all permutations in the `res` list. The recursion continues until only one element is left in the list, at which point a permutation containing that single element is returned. \n\n# Complexity\n- Time complexity: O(n * n!)\n\n - Recursive Calls: The permute function is called recursively, and each time it generates permutations for a smaller list by removing one element. In the worst case, the recursion depth is equal to the length of the input list nums, which is n.\n\n - Permutation Generation: For each index, we are generating permutations for the remaining elements and appending the removed element at the end. This involves recursive calls and list manipulations. In general time complexity of permutation should be O(n!)\n\n- Space complexity: O(n)\n - Recursion Depth: The depth of recursion goes up to the number of elements in the input list. So, the maximum recursion depth is O(n).\n - Additional Memory: The additional memory usage includes the res list, the n variable, and the space used in each recursive call.\n\n Considering these factors, the space complexity is O(n)\n\n\n```python []\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n if len(nums) == 1:\n return [nums[:]]\n \n res = []\n\n for _ in range(len(nums)):\n n = nums.pop(0)\n perms = self.permute(nums)\n\n for p in perms:\n p.append(n)\n \n res.extend(perms)\n nums.append(n)\n \n return res\n \n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nvar permute = function(nums) {\n if (nums.length === 1) {\n return [nums.slice()];\n }\n \n var res = [];\n\n for (var i = 0; i < nums.length; i++) {\n var n = nums.shift();\n var perms = permute(nums.slice());\n\n for (var p of perms) {\n p.push(n);\n }\n \n res.push(...perms);\n nums.push(n);\n }\n \n return res; \n};\n```\n```java []\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> res = new ArrayList<>();\n if (nums.length == 1) {\n List<Integer> singleList = new ArrayList<>();\n singleList.add(nums[0]);\n res.add(singleList);\n return res;\n }\n\n for (int i = 0; i < nums.length; i++) {\n int n = nums[i];\n int[] remainingNums = new int[nums.length - 1];\n int index = 0;\n for (int j = 0; j < nums.length; j++) {\n if (j != i) {\n remainingNums[index] = nums[j];\n index++;\n }\n }\n \n List<List<Integer>> perms = permute(remainingNums);\n for (List<Integer> p : perms) {\n p.add(n);\n }\n \n res.addAll(perms);\n }\n \n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> res;\n if (nums.size() == 1) {\n vector<int> singleList;\n singleList.push_back(nums[0]);\n res.push_back(singleList);\n return res;\n }\n\n for (int i = 0; i < nums.size(); i++) {\n int n = nums[i];\n vector<int> remainingNums;\n for (int j = 0; j < nums.size(); j++) {\n if (j != i) {\n remainingNums.push_back(nums[j]);\n }\n }\n \n vector<vector<int>> perms = permute(remainingNums);\n for (vector<int> p : perms) {\n p.insert(p.begin(), n); // Insert n at the beginning of the permutation\n res.push_back(p); // Append the modified permutation to the result\n }\n }\n \n return res; \n }\n};\n```\n\n- This is bonus codes I don\'t explain in the article.\n\n```python []\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n\n def backtrack(start):\n if start == len(nums):\n res.append(nums[:])\n return\n \n for i in range(start, len(nums)):\n nums[start], nums[i] = nums[i], nums[start]\n backtrack(start + 1)\n nums[start], nums[i] = nums[i], nums[start]\n\n res = []\n backtrack(0)\n return res\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nvar permute = function(nums) {\n const backtrack = (start) => {\n if (start === nums.length) {\n res.push([...nums]);\n return;\n }\n \n for (let i = start; i < nums.length; i++) {\n [nums[start], nums[i]] = [nums[i], nums[start]];\n backtrack(start + 1);\n [nums[start], nums[i]] = [nums[i], nums[start]];\n }\n };\n\n const res = [];\n backtrack(0);\n return res; \n};\n```\n```java []\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> res = new ArrayList<>();\n backtrack(nums, 0, res);\n return res; \n }\n\n private void backtrack(int[] nums, int start, List<List<Integer>> res) {\n if (start == nums.length) {\n res.add(arrayToList(nums));\n return;\n }\n\n for (int i = start; i < nums.length; i++) {\n swap(nums, start, i);\n backtrack(nums, start + 1, res);\n swap(nums, start, i);\n }\n }\n \n private List<Integer> arrayToList(int[] arr) {\n List<Integer> list = new ArrayList<>();\n for (int num : arr) {\n list.add(num);\n }\n return list;\n }\n \n private void swap(int[] nums, int i, int j) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n } \n}\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> res;\n backtrack(nums, 0, res);\n return res;\n }\n\n void backtrack(vector<int>& nums, int start, vector<vector<int>>& res) {\n if (start == nums.size()) {\n res.push_back(nums);\n return;\n }\n\n for (int i = start; i < nums.size(); i++) {\n swap(nums[start], nums[i]);\n backtrack(nums, start + 1, res);\n swap(nums[start], nums[i]);\n }\n }\n \n void swap(int& a, int& b) {\n int temp = a;\n a = b;\n b = temp;\n } \n};\n```\n\n\n\n\n
4,469
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
605
11
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to generate all possible permutations of a given array of distinct integers. A permutation is an arrangement of elements in a specific order. For example, given the array [1, 2, 3], the permutations are [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]].\n\nTo solve this problem, we can use a recursive approach known as backtracking. The intuition behind the backtracking approach is to try out all possible combinations by swapping elements to find the different arrangements.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Create a helper function that takes the current index as a parameter and generates permutations for the remaining elements.\n- The base case for recursion is when the current index reaches the end of the array. At this point, we have a valid permutation, so we add it to the result list.\n- For each index from the current position, swap the element at the current index with the element at the current position, and then recursively generate permutations for the rest of the array.\n- After the recursive call, swap the elements back to their original positions to restore the original array for further exploration.\n\n# Complexity\n- Time complexity: **O(n!)** We have to generate all possible permutations, and there are n! permutations for an array of size n.\n\n- Space complexity:**O(n)** The space required for recursion depth and the result list\n\n# Code\n## C++\n```\nclass Solution {\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> result;\n generatePermutations(nums, 0, result);\n return result;\n }\n\nprivate:\n void generatePermutations(vector<int>& nums, int index, vector<vector<int>>& result) {\n if (index == nums.size()) {\n result.push_back(nums);\n return;\n }\n\n for (int i = index; i < nums.size(); ++i) {\n swap(nums[index], nums[i]);\n generatePermutations(nums, index + 1, result);\n swap(nums[index], nums[i]); // Backtrack\n }\n }\n};\n```\n## Java\n```\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<>();\n generatePermutations(nums, 0, result);\n return result;\n }\n\n private void generatePermutations(int[] nums, int index, List<List<Integer>> result) {\n if (index == nums.length) {\n List<Integer> currentPerm = new ArrayList<>();\n for (int num : nums) {\n currentPerm.add(num);\n }\n result.add(currentPerm);\n return;\n }\n\n for (int i = index; i < nums.length; i++) {\n swap(nums, index, i);\n generatePermutations(nums, index + 1, result);\n swap(nums, index, i); // Backtrack\n }\n }\n\n private void swap(int[] nums, int i, int j) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n }\n}\n```\n## Python3\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n def generate_permutations(index):\n if index == len(nums):\n result.append(nums.copy())\n return\n \n for i in range(index, len(nums)):\n nums[index], nums[i] = nums[i], nums[index]\n generate_permutations(index + 1)\n nums[index], nums[i] = nums[i], nums[index] # Backtrack\n \n result = []\n generate_permutations(0)\n return result\n```\n## C\n```\nvoid swap(int* nums, int i, int j) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n}\n\nvoid generatePermutations(int* nums, int numsSize, int index, int** result, int* returnSize, int** returnColumnSizes) {\n if (index == numsSize) {\n result[*returnSize] = malloc(numsSize * sizeof(int));\n memcpy(result[*returnSize], nums, numsSize * sizeof(int));\n (*returnColumnSizes)[*returnSize] = numsSize;\n (*returnSize)++;\n return;\n }\n\n for (int i = index; i < numsSize; i++) {\n swap(nums, index, i);\n generatePermutations(nums, numsSize, index + 1, result, returnSize, returnColumnSizes);\n swap(nums, index, i); // Backtrack\n }\n}\n\nint** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {\n int totalPermutations = 1;\n for (int i = 1; i <= numsSize; i++) {\n totalPermutations *= i;\n }\n\n int** result = (int**)malloc(totalPermutations * sizeof(int*));\n *returnColumnSizes = (int*)malloc(totalPermutations * sizeof(int));\n *returnSize = 0;\n\n generatePermutations(nums, numsSize, 0, result, returnSize, returnColumnSizes);\n return result;\n}\n```\n\n![upvote img.jpg]()\n
4,479
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
476
6
# Approach\nRecursive call tries to add a number that was not used earlier (not in the list). If the list gains the right length it goes to the result. The process repeats with each num as a first element.\n# Code\n```re\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n res = []\n def solve(s=[], nums=[]):\n if len(s) == len(nums):\n res.append(s)\n return\n for i in range(len(nums)):\n if nums[i] not in s:\n solve(s + [nums[i]], nums)\n solve([], nums)\n return res\n\n```\n\n\n## UPVOTE makes me happy --> (o\u02D8\u25E1\u02D8o)
4,483
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
2,556
7
\n# Code\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n return list(itertools.permutations(nums,len(nums)))\n```
4,494
Permutations
permutations
Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Array,Backtracking
Medium
null
903
9
# Intuition\nUpon encountering this problem, I was immediately struck by its resemblance to a well-known puzzle: generating all possible permutations of a given sequence. It\'s like holding a Rubik\'s Cube of numbers and twisting it to discover every conceivable arrangement. With the challenge laid out, my mind gravitated towards the elegant world of recursion, an approach that often weaves simplicity with efficiency. In particular, the concept of backtracking emerged as a promising path. Imagine walking through a maze of numbers, exploring every turn and alley, but with the magical ability to step back and try a different route whenever needed. That\'s the beauty of backtracking in recursion. It\'s not just about finding a solution; it\'s about crafting an adventure through the mathematical landscape, one permutation at a time.\n\n\n\n# Approach\nThe solution to this problem is elegantly found through recursion, a form of backtracking. The approach begins by initializing an empty list, `result`, to store the final permutations. Then, a recursive helper function `backtrack` is defined, which takes the remaining numbers (`nums`) and the current permutation (`path`) as parameters. The base case is reached when there are no numbers left to permute; at this point, the current `path` is added to the `result`. In the recursive case, for each number in `nums`, the following steps are performed: (i) add the current number to `path`, (ii) remove the current number from `nums`, (iii) recursively call `backtrack` with the updated `nums` and `path`, and (iv) proceed without needing to revert the changes to `nums` and `path` due to the use of list slicing. Finally, the `backtrack` function is called with the original `nums` and an empty `path` to start the process, and the `result` list containing all the permutations is returned. This method ensures that all permutations are explored by iteratively choosing one element and recursively calling the function on the remaining elements.\n\n# Complexity\n- Time complexity: O(n*n!) \n This is because for generating permutations, we perform n! operations (since there are n! permutations for n numbers) and for each operation, we spend O(n) time for slicing the list in our recursive call.\n\n- Space complexity: O(n*n!) \n This is due to the number of solutions. In the worst case, if we have \'n\' distinct numbers, there would be n! permutations. Since each permutation is a list of \'n\' numbers, the space complexity is O(n*n!).\n\n# Code\n``` Python []\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n def backtrack(nums, path): \n if not nums: \n result.append(path) \n return \n for i in range(len(nums)): \n backtrack(nums[:i] + nums[i+1:], path + [nums[i]]) \n result = [] \n backtrack(nums, []) \n return result \n```\n``` C++ []\nclass Solution {\npublic:\n void permuteRec(vector<int>& nums, int begin, vector<vector<int>>& result) { \n if (begin == nums.size()) { \n result.push_back(nums); \n return; \n } \n for (int i = begin; i < nums.size(); i++) { \n swap(nums[begin], nums[i]); \n permuteRec(nums, begin + 1, result); \n swap(nums[begin], nums[i]); \n } \n } \n \n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> result; \n permuteRec(nums, 0, result); \n return result; \n \n }\n};\n```\n``` JavaScript []\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nvar permute = function(nums) {\n const result = [];\n const backtrack = (nums, path) => {\n if (nums.length === 0) {\n result.push(path);\n return;\n }\n for (let i = 0; i < nums.length; i++) {\n backtrack([...nums.slice(0, i), ...nums.slice(i + 1)], [...path, nums[i]]);\n }\n };\n backtrack(nums, []);\n return result;\n};\n```\n``` C# []\npublic class Solution {\n public IList<IList<int>> Permute(int[] nums) {\n IList<IList<int>> result = new List<IList<int>>();\n Backtrack(nums, new List<int>(), result);\n return result;\n }\n\n private void Backtrack(int[] nums, List<int> path, IList<IList<int>> result) {\n if (path.Count == nums.Length) {\n result.Add(new List<int>(path));\n return;\n }\n foreach (int num in nums) {\n if (path.Contains(num)) continue;\n path.Add(num);\n Backtrack(nums, path, result);\n path.RemoveAt(path.Count - 1);\n }\n }\n}\n```\n``` Java []\npublic class Solution {\n public void permuteRec(int[] nums, int begin, List<List<Integer>> result) {\n if (begin == nums.length) {\n List<Integer> temp = new ArrayList<Integer>();\n for (int num : nums) temp.add(num);\n result.add(temp);\n return;\n }\n for (int i = begin; i < nums.length; i++) {\n // Swap\n int temp = nums[begin];\n nums[begin] = nums[i];\n nums[i] = temp;\n \n permuteRec(nums, begin + 1, result);\n \n // Swap back\n temp = nums[begin];\n nums[begin] = nums[i];\n nums[i] = temp;\n }\n }\n \n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n permuteRec(nums, 0, result);\n return result;\n }\n}\n```\n``` Rust []\nimpl Solution {\n pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {\n let mut result = Vec::new();\n Self::backtrack(nums, vec![], &mut result);\n result\n }\n\n fn backtrack(nums: Vec<i32>, path: Vec<i32>, result: &mut Vec<Vec<i32>>) {\n if nums.is_empty() {\n result.push(path);\n return;\n }\n for i in 0..nums.len() {\n let mut new_nums = nums.clone();\n new_nums.remove(i);\n let mut new_path = path.clone();\n new_path.push(nums[i]);\n Self::backtrack(new_nums, new_path, result);\n }\n }\n}\n```\n``` Swift []\nclass Solution {\n func permute(_ nums: [Int]) -> [[Int]] {\n var result: [[Int]] = []\n \n func backtrack(_ nums: [Int], _ path: [Int]) {\n if nums.isEmpty {\n result.append(path)\n return\n }\n for i in 0..<nums.count {\n var newNums = nums\n newNums.remove(at: i)\n backtrack(newNums, path + [nums[i]])\n }\n }\n \n backtrack(nums, [])\n return result\n }\n}\n```\n``` Go []\nfunc permute(nums []int) [][]int {\n var result [][]int\n \n var backtrack func([]int, []int)\n backtrack = func(nums []int, path []int) {\n if len(nums) == 0 {\n result = append(result, append([]int(nil), path...))\n return\n }\n for i := 0; i < len(nums); i++ {\n newNums := append([]int(nil), nums[:i]...)\n newNums = append(newNums, nums[i+1:]...)\n newPath := append([]int(nil), path...)\n newPath = append(newPath, nums[i])\n backtrack(newNums, newPath)\n }\n }\n \n backtrack(nums, []int{})\n return result\n}\n```\n## Performance \n| Language | Runtime | Beats | Memory |\n|------------|---------|---------|---------|\n| C++ | 0 ms | 100% | 7.5 MB |\n| Java | 1 ms | 98.58% | 44.1 MB |\n| Rust | 1 ms | 87.70% | 2.3 MB |\n| Go | 2 ms | 61.28% | 3.1 MB |\n| Swift | 8 ms | 91.96% | 14.4 MB |\n| Python3 | 39 ms | 98.74% | 16.7 MB |\n| JavaScript | 72 ms | 55% | 44.1 MB |\n| C# | 131 ms | 94.50% | 43.4 MB |\n\n\nThis sorted table provides a quick comparison of the runtime performance across different programming languages for the given problem.
4,499
Permutations II
permutations-ii
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Array,Backtracking
Medium
null
7,556
44
The problem is solved using a backtracking approach. For this particular case, as we have duplicates in input, we can track the count of each number. Python provides a built-in lib `Counter` which I will be using for this problem. As the order of output results doesn\'t matter, we can use this `Counter` variable to track visited elements in the exploration path\n\nThe solution Tree for this problem for an input `[1,1,2]` would look like this:\n\n<img width="400" src="">\n\nBelow is the code that will represent the above solution tree\n```\nclass Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n \n permutations = []\n counter = Counter(nums)\n def findAllPermutations(res):\n if len(res) == len(nums):\n permutations.append(res)\n return \n \n for key in counter:\n if counter[key]:\n counter[key]-=1 # decrement visited key\n findAllPermutations(res + [key]) \n counter[key]+=1 # restore the state of visited key to find the next path\n \n findAllPermutations([])\n return permutations\n```\n**Space** - `O(N)` - Each call stack depth would be `N` where `N` is the length of input list.\n**Time** - `O(n * \u03A3(P(N, k)))` - In worst case, all numbers in the input array will be unique. In this case, each path will go upto `N` depth in solution tree. At each level, the branching factor is reduced by `1` so it will go like `N, N-1, N-2...1` starting from root. (Time complexity shared by [@AntonBelski]())\n\n\n---\n\n***Please upvote if you find it useful***
4,522
Permutations II
permutations-ii
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Array,Backtracking
Medium
null
1,039
8
```\nclass Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n ans = []\n n = len(nums)\n visited = [False] * len(nums)\n \n nums.sort()\n \n def backtracking(nums, res):\n # GOAL / Base case\n if len(res) == n:\n ans.append(res[:])\n return\n \n for i in range(len(nums)):\n # CONSTRAINTs\n # if current element is duplicated of previous one\n if visited[i] or (i > 0 and nums[i] == nums[i-1] and not visited[i-1]):\n continue\n \n # Make CHOICE\n res.append(nums[i])\n \n # BACKTRACKING\n visited[i] = True\n backtracking(nums, res)\n \n # RESET STATE\n visited[i] = False\n res.pop()\n \n\t\t# Inital state\n backtracking(nums, [])\n return ans\n \n```\n\nand visual explanation -\n![image]()\n\n\nPlease vote if you like my solution :D\n
4,539
Permutations II
permutations-ii
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Array,Backtracking
Medium
null
1,677
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRecursive Tree\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. I\'ve considered the original array, and have done the operations in it.\n2. Basically I have swapped all the values at differnt indices from a value at a particular index.\n3. Here is the example: \n \n![image.png]()\n\n- Initally we are on index 0:\nSwap 1 with 1 then 2 with 1 and then 3 with 1.\nNow we have got three differnt arrays\n- Now we are on index 1:\n**For array 1:**\nSwap 2 with 2 and then swap 3 with 2\n**For array 2:**\nSwap 1 with 1 and then swap 3 with 1.\n**For array 3:**\nSwap 2 with 2 and then swap 1 with 2.\n\nSo in total we have got 6 different arrays.\n\n4. Now let\'s say instead of [1,2,3] we had [1,1,2]\nIn this case, there would be **duplicate arrays**, so for removing them I have **used MAP**.\n\n\nFeel free to mention your doubts in the comments below :)\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# Code\n```\nclass Solution {\npublic:\n\n void solve(vector<int> nums, int index, vector<vector<int>> & ans)\n {\n if(index >= nums.size())\n {\n ans.push_back(nums);\n return;\n }\n\n for(int i = index; i < nums.size(); i++)\n {\n swap(nums[index], nums[i]);\n solve(nums, index + 1, ans);\n\n //backtrack\n swap(nums[index], nums[i]);\n }\n }\n vector<vector<int>> permuteUnique(vector<int>& nums) {\n vector<vector<int>> ans, unique;\n int index = 0;\n\n map<vector<int>, int> mp;\n\n solve(nums, index, ans);\n\n for(int i = 0; i < ans.size(); i++)\n {\n mp[ans[i]]++;\n }\n\n for(auto & it: mp)\n {\n unique.push_back(it.first);\n }\n\n return unique;\n }\n};\n```
4,557
Permutations II
permutations-ii
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Array,Backtracking
Medium
null
16,599
142
```\ndef permuteUnique(self, nums):\n res = []\n nums.sort()\n self.dfs(nums, [], res)\n return res\n \ndef dfs(self, nums, path, res):\n if not nums:\n res.append(path)\n for i in xrange(len(nums)):\n if i > 0 and nums[i] == nums[i-1]:\n continue\n self.dfs(nums[:i]+nums[i+1:], path+[nums[i]], res)\n```
4,559
Permutations II
permutations-ii
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Array,Backtracking
Medium
null
1,194
5
\n\n# Code\n```\nclass Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n return set(permutations(nums)) \n```
4,573
Rotate Image
rotate-image
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Array,Math,Matrix
Medium
null
108,177
1,133
While these solutions are Python, I think they're understandable/interesting for non-Python coders as well. But before I begin: No mathematician would call a matrix `matrix`, so I'll use the usual `A`. Also, btw, the 40 ms reached by two of the solutions is I think the fastest achieved by Python solutions so far.\n\n---\n\n**Most Pythonic - `[::-1]` and `zip`** - 44 ms\n\nThe most pythonic solution is a simple one-liner using `[::-1]` to flip the matrix upside down and then `zip` to transpose it. It assigns the result back into `A`, so it's "in-place" in a sense and the OJ accepts it as such, though some people might not.\n\n class Solution:\n def rotate(self, A):\n A[:] = zip(*A[::-1])\n\n---\n\n**Most Direct** - 52 ms\n\nA 100% in-place solution. It even reads and writes each matrix element only once and doesn't even use an extra temporary variable to hold them. It walks over the *"top-left quadrant"* of the matrix and directly rotates each element with the three corresponding elements in the other three quadrants. Note that I'm moving the four elements in parallel and that `[~i]` is way nicer than `[n-1-i]`.\n\n class Solution:\n def rotate(self, A):\n n = len(A)\n for i in range(n/2):\n for j in range(n-n/2):\n A[i][j], A[~j][i], A[~i][~j], A[j][~i] = \\\n A[~j][i], A[~i][~j], A[j][~i], A[i][j]\n\n---\n\n**Clean Most Pythonic** - 56 ms\n\nWhile the OJ accepts the above solution, the the result rows are actually tuples, not lists, so it's a bit dirty. To fix this, we can just apply `list` to every row:\n\n class Solution:\n def rotate(self, A):\n A[:] = map(list, zip(*A[::-1]))\n\n---\n\n**List Comprehension** - 60 ms\n\nIf you don't like `zip`, you can use a nested list comprehension instead:\n\n class Solution:\n def rotate(self, A):\n A[:] = [[row[i] for row in A[::-1]] for i in range(len(A))]\n\n---\n\n**Almost as Direct** - 40 ms\n\nIf you don't like the little repetitive code of the above "Most Direct" solution, we can instead do each four-cycle of elements by using three swaps of just two elements.\n\n class Solution:\n def rotate(self, A):\n n = len(A)\n for i in range(n/2):\n for j in range(n-n/2):\n for _ in '123':\n A[i][j], A[~j][i], i, j = A[~j][i], A[i][j], ~j, ~i\n i = ~j\n\n---\n\n**Flip Flip** - 40 ms\n\nBasically the same as the first solution, but using `reverse` instead of `[::-1]` and transposing the matrix with loops instead of `zip`. It's 100% in-place, just instead of only moving elements around, it also moves the rows around.\n\n class Solution:\n def rotate(self, A):\n A.reverse()\n for i in range(len(A)):\n for j in range(i):\n A[i][j], A[j][i] = A[j][i], A[i][j]\n\n---\n\n**Flip Flip, all by myself** - 48 ms\n\nSimilar again, but I first transpose and then flip left-right instead of upside-down, and do it all by myself in loops. This one is 100% in-place again in the sense of just moving the elements.\n\n class Solution:\n def rotate(self, A):\n n = len(A)\n for i in range(n):\n for j in range(i):\n A[i][j], A[j][i] = A[j][i], A[i][j]\n for row in A:\n for j in range(n/2):\n row[j], row[~j] = row[~j], row[j]
4,626
Rotate Image
rotate-image
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Array,Math,Matrix
Medium
null
28,813
310
\t# reverse\n\tl = 0\n\tr = len(matrix) -1\n\twhile l < r:\n\t\tmatrix[l], matrix[r] = matrix[r], matrix[l]\n\t\tl += 1\n\t\tr -= 1\n\t# transpose \n\tfor i in range(len(matrix)):\n\t\tfor j in range(i):\n\t\t\tmatrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]\n\t\t\t\nWe want to rotate\n[1,2,3],\n[4,5,6],\n[7,8,9]\n->\n[7,4,1],\n[8,5,2],\n[9,6,3]]\n\nWe can do this in two steps.\nReversing the matrix does this:\n[1,2,3],\n[4,5,6],\n[7,8,9]] \n-> \n[7, 8, 9],\n[4, 5, 6], \n[1, 2, 3]\n\nTransposing means: rows become columns, columns become rows.\n\n[7, 8, 9], \n[4, 5, 6], \n[1, 2, 3]\n ->\n[7,4,1],\n[8,5,2],\n[9,6,3]\nIf you like this explanation, please consider giving it a star on my [github](). Means a lot to me.
4,639
Rotate Image
rotate-image
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Array,Math,Matrix
Medium
null
5,902
43
**Appreciate if you could upvote this solution**\n\nMethod: `math`\n\nIn this question, we just need to swap the values of selected elements\n\nCase 1: len(matrix) is even\n![image]()\n\nCase 2: len(matrix) is odd\n![image]()\n\nThe start element of each round swaping are in red background.\n<br/>\nCode:\n```\ndef rotate(self, matrix: List[List[int]]) -> None:\n\tn = len(matrix)\n\tfor row in range(math.ceil(n / 2)):\n\t\tfor col in range(int(n - n / 2)):\n\t\t\t(\n\t\t\t\tmatrix[row][col],\n\t\t\t\tmatrix[~col][row],\n\t\t\t\tmatrix[~row][~col],\n\t\t\t\tmatrix[col][~row],\n\t\t\t) = (\n\t\t\t\tmatrix[~col][row],\n\t\t\t\tmatrix[~row][~col],\n\t\t\t\tmatrix[col][~row],\n\t\t\t\tmatrix[row][col],\n\t\t\t)\n\treturn matrix\n```\n\n**Time Complexity**: `O(n^2)`\n**Space Complexity**: `O(1)`\n<br/>\n\n\n
4,647
Rotate Image
rotate-image
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Array,Math,Matrix
Medium
null
14,139
168
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\nThe trick here is to realize that cells in our matrix (**M**) can be swapped out in groups of four in a self-contained manner. This will allow us to keep our **space complexity** down to **O(1)**.\n\nThe remaining difficulty lies in setting up our **nested for loops** to accomplish the entirety of these four-way swaps. If we consider each ring of data as a larger iteration, we can notice that each successive ring shortens in the length of its side by **2**. This means that we will need to perform this process to a maximum **depth** of **floor(n / 2)** times. We can use floor here because the center cell of an odd-sided matrix will not need to be swapped.\n\nFor each ring, we\'ll need to perform a number of iterations equal to the length of the side minus 1, since we will have already swapped the far corner as our first iteration. As noticed earlier, the length of the side of a ring is shortened by **2** for each layer of depth we\'ve achieved (**len = n - 2 * i - 1**).\n\nInside the nested for loops, we need to perform a four-way swap between the linked cells. In order to save on some processing, we can store the value of the opposite side of **i** (**opp = n - 1 - i**) as that value will be reused many times over.\n\n![Visual 1]()\n\nOnce the nested loops are finished, **M** has been successfully transformed in-place.\n\n - _**Time Complexity: O(N^2)** where N is the length of each side of the matrix_\n - _**Space Complexity: O(1)**_\n\n---\n\n#### ***Implementation:***\n\nThere are only minor differences between the code of all four languages.\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **72ms / 38.4MB** (beats 94% / 92%).\n```javascript\nvar rotate = function(M) {\n let n = M.length, depth = ~~(n / 2)\n for (let i = 0; i < depth; i++) {\n let len = n - 2 * i - 1, opp = n - 1 - i\n for (let j = 0; j < len; j++) {\n let temp = M[i][i+j]\n M[i][i+j] = M[opp-j][i]\n M[opp-j][i] = M[opp][opp-j]\n M[opp][opp-j] = M[i+j][opp]\n M[i+j][opp] = temp\n }\n }\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **28ms / 14.2MB** (beats 95% / 84%).\n```python\nclass Solution:\n def rotate(self, M: List[List[int]]) -> None:\n n = len(M)\n depth = n // 2\n for i in range(depth):\n rlen, opp = n - 2 * i - 1, n - 1 - i\n for j in range(rlen):\n temp = M[i][i+j]\n M[i][i+j] = M[opp-j][i]\n M[opp-j][i] = M[opp][opp-j]\n M[opp][opp-j] = M[i+j][opp]\n M[i+j][opp] = temp\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **0ms / 38.7MB** (beats 100% / 96%).\n```java\nclass Solution {\n public void rotate(int[][] M) {\n int n = M.length, depth = n / 2;\n for (int i = 0; i < depth; i++) {\n int len = n - 2 * i - 1, opp = n - 1 - i;\n for (int j = 0; j < len; j++) {\n int temp = M[i][i+j];\n M[i][i+j] = M[opp-j][i];\n M[opp-j][i] = M[opp][opp-j];\n M[opp][opp-j] = M[i+j][opp];\n M[i+j][opp] = temp;\n }\n }\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 7.0MB** (beats 100% / 68%).\n```c++\nclass Solution {\npublic:\n void rotate(vector<vector<int>>& M) {\n int n = M.size(), depth = n / 2;\n for (int i = 0; i < depth; i++) {\n int len = n - 2 * i - 1, opp = n - 1 - i;\n for (int j = 0; j < len; j++) {\n int temp = M[i][i+j];\n M[i][i+j] = M[opp-j][i];\n M[opp-j][i] = M[opp][opp-j];\n M[opp][opp-j] = M[i+j][opp];\n M[i+j][opp] = temp;\n }\n }\n }\n};\n```
4,685
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
84,672
822
\n# Intuition:\n\nThe intuition is to group words that are anagrams of each other together. Anagrams are words that have the `same` characters but in a `different` order.\n\n# Explanation:\n\nLet\'s go through the code step by step using the example input `["eat","tea","tan","ate","nat","bat"]` to understand how it works.\n\n1. **Initializing Variables**\n - We start by initializing an empty unordered map called `mp` (short for map), which will store the groups of anagrams.\n\n2. **Grouping Anagrams**\nWe iterate through each word in the input vector `strs`. Let\'s take the first word, "eat", as an example.\n\n - **Sorting the Word**\nWe create a string variable called `word` and assign it the value of the current word ("eat" in this case). \n\n Next, we sort the characters in `word` using the `sort()` function. After sorting, `word` becomes "aet". \n\n - **Grouping the Anagram**\nWe insert `word` as the key into the `mp` unordered map using `mp[word]`, and we push the original word ("eat") into the vector associated with that key using `mp[word].push_back(x)`, where `x` is the current word.\n\n Since "aet" is a unique sorted representation of all the anagrams, it serves as the key in the `mp` map, and the associated vector holds all the anagrams. \n\nFor the given example, the `mp` map would look like this after processing all the words:\n```\n{\n "aet": ["eat", "tea", "ate"],\n "ant": ["tan", "nat"],\n "abt": ["bat"]\n}\n```\n\n3. **Creating the Result**\nWe initialize an empty vector called `ans` (short for answer) to store the final result.\n\n - We iterate through each key-value pair in the `mp` map using a range-based for loop. For each pair, we push the vector of anagrams (`x.second`) into the `ans` vector.\n\nFor the given example, the `ans` vector would look like this:\n```\n[\n ["eat", "tea", "ate"],\n ["tan", "nat"],\n ["bat"]\n]\n```\n\n4. **Returning the Result**\nWe return the `ans` vector, which contains the groups of anagrams.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<vector<string>> groupAnagrams(vector<string>& strs) {\n unordered_map<string, vector<string>> mp;\n \n for(auto x: strs){\n string word = x;\n sort(word.begin(), word.end());\n mp[word].push_back(x);\n }\n \n vector<vector<string>> ans;\n for(auto x: mp){\n ans.push_back(x.second);\n }\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public List<List<String>> groupAnagrams(String[] strs) {\n Map<String, List<String>> map = new HashMap<>();\n \n for (String word : strs) {\n char[] chars = word.toCharArray();\n Arrays.sort(chars);\n String sortedWord = new String(chars);\n \n if (!map.containsKey(sortedWord)) {\n map.put(sortedWord, new ArrayList<>());\n }\n \n map.get(sortedWord).add(word);\n }\n \n return new ArrayList<>(map.values());\n }\n}\n```\n```Python3 []\nclass Solution:\n def groupAnagrams(self, strs):\n anagram_map = defaultdict(list)\n \n for word in strs:\n sorted_word = \'\'.join(sorted(word))\n anagram_map[sorted_word].append(word)\n \n return list(anagram_map.values())\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. [Valid Anagram]()\n11. [Group Anagrams]()\n12. **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.**
4,700
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
31,371
163
**Appreciate if you could upvote this solution**\n\n\nMethod: `Hash Table`\n\nSince the output needs to group the anagrams, it is suitable to use `dict` to store the different anagrams.\nThus, we need to find a common `key` for those anagrams.\nAnd one of the best choices is the `sorted string` as all the anagrams have the same anagrams.\n\n![image]()\n\n\n\n```\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n strs_table = {}\n\n for string in strs:\n sorted_string = \'\'.join(sorted(string))\n\n if sorted_string not in strs_table:\n strs_table[sorted_string] = []\n\n strs_table[sorted_string].append(string)\n\n return list(strs_table.values())\n```\nTime complexity: `O(m*nlogn))`\nSpace complexity: `O(n)`\n<br/>
4,721
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
10,190
38
\n\n# Python Solution\n```\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n dic={}\n for word in strs:\n sorted_word="".join(sorted(word))\n if sorted_word not in dic:\n dic[sorted_word]=[word]\n else:\n dic[sorted_word].append(word)\n return dic.values()\n```\n# please upvote me it would encourage me alot\n
4,748
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
1,857
13
# Code Explanation\nThe provided Python code defines a class `Solution` with a method `groupAnagrams`. This method takes a list of strings `strs` as input and is supposed to group the anagrams from the input list into lists of lists, where each inner list contains words that are anagrams of each other. Anagrams are words or phrases formed by rearranging the letters of another, such as "listen" and "silent."\n\nLet\'s break down the code step by step:\n\n1. **Initialize a Dictionary**: The code starts by initializing an empty dictionary called `ans`. This dictionary will be used to store groups of anagrams, with the keys being the character counts of the letters in the anagrams and the values being lists of strings that belong to each group.\n\n ```python\n ans = collections.defaultdict(list)\n ```\n\n Here, `collections.defaultdict(list)` creates a dictionary where the default value for each key is an empty list.\n\n2. **Iterate Through the Input List**: The code then enters a loop to iterate through each string `s` in the input list `strs`.\n\n ```python\n for s in strs:\n ```\n\n3. **Initialize a Character Count List**: Inside the loop, a list called `count` is initialized with 26 zeros. This list will be used to count the occurrences of each letter in the current string `s`. Each index in the `count` list corresponds to a letter in the lowercase English alphabet.\n\n ```python\n count = [0] * 26\n ```\n\n4. **Count the Occurrence of Letters in the String**: The code then enters another loop to iterate through each character `c` in the current string `s`.\n\n ```python\n for c in s:\n ```\n\n5. **Increment the Count for Each Letter**: Inside the inner loop, the code calculates the position of the character `c` in the alphabet (by subtracting the ASCII value of \'a\' from the ASCII value of `c`) and increments the corresponding element in the `count` list. This effectively counts the occurrence of each letter in the current string `s`.\n\n ```python\n count[ord(c) - ord("a")] += 1\n ```\n\n6. **Group Anagrams Using Character Counts as Keys**: After counting the occurrences of letters in the current string `s`, the code converts the `count` list into a tuple. This tuple is used as a key in the `ans` dictionary. The value associated with this key is a list, and the current string `s` is appended to this list. This step groups strings with the same character count together.\n\n ```python\n ans[tuple(count)].append(s)\n ```\n\n7. **Return Grouped Anagrams**: After processing all strings in the input list `strs`, the code returns the values of the `ans` dictionary. These values are lists of grouped anagrams.\n\n ```python\n return ans.values()\n ```\n\nSo, in summary, this code efficiently groups anagrams by counting the occurrences of each letter in each string and using these counts as keys in a dictionary. It ensures that anagrams with the same character counts are grouped together, and it returns these groups as a list of lists.\n\n# Python Code\n```\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n ans = collections.defaultdict(list)\n\n for s in strs:\n count = [0] * 26\n for c in s:\n count[ord(c) - ord("a")] += 1 \n ans[tuple(count)].append(s)\n\n return ans.values()\n\n```\n\n**Please upvote if you like the solution.\nHappy Coding! \uD83D\uDE0A**\n
4,751
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
2,326
6
```C++ []\nclass Solution {\npublic:\n vector<vector<string>> groupAnagrams(vector<string>& strs) {\n unordered_map<string,vector<string>>mp;\n vector<vector<string>>ans;\n for(int i=0;i<strs.size();i++){\n string t=strs[i];\n sort(t.begin(),t.end());\n mp[t].push_back(strs[i]);\n \n }\n for(auto it=mp.begin();it!=mp.end();it++){\n ans.push_back(it->second);\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nf = open(\'user.out\', \'w\'); [print(json.dumps(list(reduce(lambda res, s: res[str(sorted(s))].append(s) or res, json.loads(line.rstrip()), defaultdict(list)).values())), file=f) for line in stdin];exit(); \n\nf = open("user.out", "w");[print(json.dumps(list(reduce(lambda res, s: res[str(sorted(s))].append(s) or res, json.loads(line.rstrip()), defaultdict(list)).values())), file=f) for line in stdin];exit()\n```\n\n```Java []\nimport java.util.AbstractList;\nclass Solution {\n public List<List<String>> groupAnagrams(String[] strs) {\n \n Map<String, List<String>> map = new HashMap<>();\n \n return new AbstractList<List<String>>(){\n \n List<List<String>> result;\n public List<String> get(int index) {\n if (result == null) init();\n return result.get(index);\n }\n\n public int size() {\n if (result == null) init();\n return result.size();\n }\n\n private void init() {\n for (String s: strs) {\n char[] keys = new char[26];\n for (int i = 0; i < s.length(); i++)\n keys[s.charAt(i) - \'a\']++;\n\n String key = new String(keys);\n System.out.println(key);\n List<String> list = map.get(key);\n if (list == null) map.put(key, new ArrayList<>());\n map.get(key).add(s);\n }\n result = new ArrayList<>(map.values());\n }\n };\n \n }\n}\n```\n
4,754
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
479
5
# Intuition\nTo solve the problem of grouping anagrams, one common method is to represent each word by a unique signature. Since anagrams have the same letters, just rearranged, their signatures will be the same. One way to create such a signature is by counting the frequency of each letter in the word.\n\n# Approach\nFor each word in the list strs, we count the occurrence of each letter (from \'a\' to \'z\') and store this in the chr list. We then use this list (converted to a tuple since lists can\'t be dictionary keys) as a key in our solution dictionary. The value for each key in the dictionary is a list of words (anagrams) that match the signature. By iterating through the entire list of strs, we effectively group all anagrams together.\n\n# Complexity\n- Time complexity:\nThe time complexity is O(nk), where n is the number of words in strs and k is the maximum length of a word in strs. This is because for each word, we are counting its letters which takes O(k) time.\n- Space complexity:\nThe space complexity is O(nk), where n is the number of words and k is the maximum length of a word. This is because we store each word and its signature in the solution dictionary.\n\n# Tips\n\n- I utilized defaultdict(list) to ensure that the default value for each key in the dictionary is a list. This allows me to group multiple values under a single key, producing a structure like {"dog": ["Matilda", "Sparky", "John"]}\n\n- The ord function returns the Unicode value of a character. By performing the calculation ord(k) - ord("a"), I can map characters "a" through "z" to indices 0 through 25, respectively. For instance, \'a\' maps to 0, \'b\' to 1, and so forth.\n\n# Code\n```\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n from collections import defaultdict\n\n solution=defaultdict(list)\n\n for i in strs:\n chr=[0]*26 # from a to z\n for k in i:\n chr[ord(k)-ord("a")]+=1\n solution[tuple(chr)].append(i)\n return solution.values()\n \n\n```
4,762
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
5,084
6
# Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nSorted anagrams string will always be equal.\nHence, create a hash_map where key will the sorted string.\nAdd current string if its key is present, other wise create a new entry.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\nAs, first we are traversing over the given list.\nFor each list sorting and join operation will take constant time as its given string size will be max of 100 characters.\n\n- Space complexity:\n$$O(n)$$\nAs, in worst case all unique string in given list. \n\n\n# Code\n```\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n # Hash Map\n hash_map = {}\n # Iterate over each string in given list\n for s in strs:\n # Hash function to get key\n key = \'\'.join(sorted(s))\n # CASE: If key is in hash map\n if key in hash_map:\n hash_map[key].append(s)\n # CASE: If key is not in hash map\n else:\n hash_map[key] = [s]\n return list(hash_map.values())\n```
4,763
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
4,911
6
\n# Code\n```\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n answer = defaultdict(list)\n for word in strs:\n answer["".join(sorted(word))].append(word)\n return list(answer.values())\n\n\n```
4,771
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
6,772
30
[]()\n
4,777
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
91,279
292
```\nfrom collections import defaultdict\n\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n letters_to_words = defaultdict(list)\n for word in strs:\n letters_to_words[tuple(sorted(word))].append(word)\n return list(letters_to_words.values())\n```\n
4,780
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
28,938
124
```\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n h = {}\n for word in strs:\n sortedWord = \'\'.join(sorted(word))\n if sortedWord not in h:\n h[sortedWord] = [word]\n else:\n h[sortedWord].append(word)\n final = []\n for value in h.values():\n final.append(value)\n return final\n```\nWe recall that anagrams are strings which have identical counts of characters. So anagrams, when sorted, result in the same string. We take advantage of this last property.\n\nWe create a dictionary and for each word in the input array, we add a key to the dictionary if the **sorted version of the word** doesn\'t already exist in the list of keys. The key then becomes the sorted version of the word, and the value for the key is an array that stores each anagram of the key. i.e. for every next word that is an anagram, **we would sort the word, find the key that is equal to the sorted form, and add the original word to the list of values for the key**.\n\nAt the end of it, we just add every value in the dictionary to the final array.
4,788
Group Anagrams
group-anagrams
Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Hash Table,String,Sorting
Medium
null
5,015
19
# Intuition\n**Find a way to associate similar words together.** \nWe can utilize the **wo**rd **co**unt **ap**proach but I preferred the approach where you **so**rt the **wo**rd. This allows **an**agrams to be **so**rted and we can then **ma**tch the **wo**rds. \nFor example, \n\n`\'tan\' and \'nat\' when sorted would become \'ant\' and \'ant\'`\n\n\n\n# Approach\n1. Iterate over the \'strs\' and sort each word.\n2. Check if the sorted word exists as key in the dictionary/hashmap\n3. Because we are going to use the original word in the returned output,create a temp variable to store the sorted word.\n4. Now check if the temporary sorted word exists in the dictionary/hashmap\n5. If yes, append the word to the values list.\n6. If no, add a new key-value pair in the dictionary/hashmap.\n\n\n# Code\n```\nclass Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n # Create a dictionary to act as hashmap\n res = {}\n for word in strs:\n # We want to retain the original word to add to the dictionary\n # Therefore, create a temporary variable with the sorted word\n temp = \'\'.join(sorted(word))\n # If the sorted word exists in the dictionary, \n # append to the values list\n if temp in res:\n res[temp].append(word)\n # Else, add a new key-value pair to the dictionary\n else:\n res[temp] = [word]\n # We only require the values list to be returned\n return res.values()\n\n```\n<br><br>\nPlease **up**vote if you find the approach and **ex**planation **us**eful!\n<br>
4,789
Pow(x, n)
powx-n
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Math,Recursion
Medium
null
9,963
34
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key intuition behind this implementation is to reduce the number of recursive calls and avoid redundant calculations by dividing the problem into smaller subproblems. By using the "exponentiation by squaring" technique, the function efficiently computes the power of `x` to `n` in logarithmic time complexity.\n\nThis implementation is quite efficient, making it suitable for calculating large powers of numbers without causing a stack overflow due to excessive recursion\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\n\n or link in my profile.Here,you can find any solution in playlists monthwise from June 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation (5-10) minutes.\n\n# Approach\nThe given code implements a function `myPow` to calculate the power of a given number `x` raised to the integer `n`. The implementation uses a recursive approach called "exponentiation by squaring" to efficiently compute the result in O(log n) time complexity.\n\nApproach:\n1. The `myPow` function takes two parameters: `x` (the base) and `n` (the exponent).\n2. Inside `myPow`, it calls the `solve` function, passing `x` and the absolute value of `n`.\n3. The `solve` function recursively calculates the power of `x` raised to `n`, using the following steps:\n a. If `n` is 0, it returns 1 since any number raised to the power of 0 is 1.\n b. Otherwise, it calculates `temp`, which is the result of `myPow(x, n/2)`. This is done to reduce redundant calculations and improve the efficiency.\n c. It squares `temp` to handle even exponents (`n%2==0`). If the exponent is odd, it multiplies `temp` by `x`.\n d. The function then returns the calculated result.\n\n# Complexity\n- Time complexity:$$O(logn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(logn)$$(Recursion stack)\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n double solve(double x,int n){\n if(n==0){\n return 1; //power of 0 is 1;\n }\n double temp=myPow(x,n/2);\n temp=temp*temp;\n if(n%2==0){ // if even return just without doing nothing\n return temp;\n }\n else{\n return temp*x;//if odd multiple return by multipling once more with given number\n }\n }\n double myPow(double x, int n) {\n double ans=solve(x,abs(n));\n if(n<0)\n return 1/ans;\n return ans;\n \n }\n};\n```\n```java []\npublic class Solution {\n public double solve(double x, long n) {\n if (n == 0) {\n return 1; // power of 0 is 1\n }\n double temp = solve(x, n / 2);\n temp = temp * temp;\n\n if (n % 2 == 0) { // if even, return just without doing anything\n return temp;\n } else {\n return temp * x; // if odd, return by multiplying once more with the given number\n }\n }\n\n public double myPow(double x, int n) {\n long longN = n; // Convert n to a long to handle Integer.MIN_VALUE\n double ans = solve(x, Math.abs(longN));\n\n if (longN < 0) {\n return 1 / ans;\n }\n return ans;\n }\n}\n\n```\n```python []\nclass Solution:\n def solve(self, x, n):\n if n == 0:\n return 1 # power of 0 is 1\n \n temp = self.myPow(x, n // 2)\n temp = temp * temp\n \n if n % 2 == 0: # if even, return just without doing anything\n return temp\n else:\n return temp * x # if odd, return by multiplying once more with given number\n \n def myPow(self, x, n):\n ans = self.solve(x, abs(n))\n \n if n < 0:\n return 1 / ans\n return ans\n\n```\n\n# Code 2\n```C++ []\nclass Solution {\npublic:\n//i am passing long long here because the value `-2147483648` after abs will cause overflow because int can store max `-2147483647`.so type casting.\n double solve(double x,long long n){\n double ans=1;\n while(n>0){\n int c=n&1;//checking if it is odd then we will multiply one extra value of x\n for odd value adding extra x \n if(c==1){\n ans=ans*x;\n }\n x=x*x;\n n=n>>1;\n }\n return ans;\n }\n double myPow(double x, int n) {\n if(x == 1) return 1;\n // -2147483648\n double ans=solve(x,abs(n));\n if(n<0)\n return 1/ans;\n cout<<INT_MAX;\n return ans;\n }\n};\n```\n```java []\npublic class Solution {\n public double solve(double x, long n) {\n double ans = 1;\n while (n > 0) {\n if ((n & 1) == 1) { // checking if it is odd then we will multiply one extra value of x\n ans *= x;\n }\n x *= x;\n n >>= 1;\n }\n return ans;\n }\n\n public double myPow(double x, int n) {\n if (x == 1) return 1;\n long longN = n;\n double ans = solve(x, Math.abs(longN));\n if (longN < 0)\n return 1 / ans;\n return ans;\n }\n}\n\n```\n```python []\nclass Solution:\n def solve(self, x, n):\n ans = 1\n while n > 0:\n if n & 1: # checking if it is odd then we will multiply one extra value of x\n ans *= x\n x *= x\n n >>= 1\n return ans\n \n def myPow(self, x, n):\n if x == 1:\n return 1\n long_n = abs(n)\n ans = self.solve(x, long_n)\n if n < 0:\n return 1 / ans\n return ans\n\n def main(self):\n x = 2.00000\n n = -2147483648\n print(self.myPow(x, n)) # Output: 0.0\n\nif __name__ == "__main__":\n solution = Solution()\n solution.main()\n\n```\n\n# Complexity\n- Time complexity:$$O(logn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$
4,810
Pow(x, n)
powx-n
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Math,Recursion
Medium
null
5,364
8
<iframe width="560" height="315" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n```\nclass Solution {\npublic:\n double myPow(double x, int n) {\n if (n < 0) return 1.0 / pow(x, static_cast<long>(-n));\n return pow(x, static_cast<long>(n));\n }\n \n double pow(double x, long n) {\n if (n == 0) return 1;\n if (n % 2 == 0) return pow(x * x, n / 2);\n else return x * pow(x * x, (n - 1) / 2);\n }\n};\n```\n```\nclass Solution {\npublic:\n double myPow(double x, int n) {\n if (n < 0) return 1.0 / pow(x, (long long)-1*n);\n return pow(x, (long long) n);\n }\n \n double pow(double x, long long n) {\n if (n == 0) return 1;\n if (n % 2 == 0) return pow(x * x, n / 2);\n else return x * pow(x * x, (n - 1) / 2);\n }\n};\n\n```\n\n```\nclass Solution:\n def myPow(self, x: float, n: int) -> float:\n if n < 0:\n return 1.0 / self.pow(x, -n)\n return self.pow(x, n)\n \n def pow(self, x: float, n: int) -> float:\n if n == 0:\n return 1.0\n if n % 2 == 0:\n return self.pow(x * x, n // 2)\n else:\n return x * self.pow(x * x, (n - 1) // 2)\n\n```
4,811
Pow(x, n)
powx-n
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Math,Recursion
Medium
null
70,077
483
[Surprisingly](), I can just use Python's existing `pow` like this:\n\n class Solution:\n myPow = pow\n\nThat's even shorter than the other more obvious "cheat":\n\n class Solution:\n def myPow(self, x, n):\n return x ** n\n\nAnd to calm down the haters, here's me *"doing it myself"*:\n\nRecursive:\n\n class Solution:\n def myPow(self, x, n):\n if not n:\n return 1\n if n < 0:\n return 1 / self.myPow(x, -n)\n if n % 2:\n return x * self.myPow(x, n-1)\n return self.myPow(x*x, n/2)\n\nIterative:\n\n class Solution:\n def myPow(self, x, n):\n if n < 0:\n x = 1 / x\n n = -n\n pow = 1\n while n:\n if n & 1:\n pow *= x\n x *= x\n n >>= 1\n return pow
4,854
Pow(x, n)
powx-n
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Math,Recursion
Medium
null
2,705
19
# Intuition\n\nDivide and Conquer\n\nTake $x^{10}$ and as example\n\n$x^{10} = x^5 * x^5 * x^0$\n$x^5 = x^2 * x^2 * x^1$\n$x^2 = x^1 * x^1 * x^0$\n\n# Complexity\n- Time complexity: $$O(logN)$$\n\n- Space complexity: $$O(logN)$$\n\n# Code\n```\nclass Solution:\n @cache\n def myPow(self, x: float, n: int) -> float:\n if n == 0:\n return 1\n elif n == 1:\n return x\n elif n == -1:\n return 1/x\n return self.myPow(x, n//2) * self.myPow(x, n//2) * self.myPow(x, n%2)\n```\n\n# Note\n`@cache` stores the results of an immutable input function and its respective outcomes. To illustrate, after executing self.myPow(x, 5) and obtaining the results, any subsequent calls to self.myPow(x, 5) will reference a hash table to swiftly retrieve the stored value, thus preventing unnecessary recomputation. While this approach does consume additional memory, it offers significant convenience.\n\n\n\n\n
4,858
Pow(x, n)
powx-n
Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Math,Recursion
Medium
null
19,800
147
![image]()\n```\nclass Solution:\n def myPow(self, x: float, n: int) -> float:\n\n def function(base=x, exponent=abs(n)):\n if exponent == 0:\n return 1\n elif exponent % 2 == 0:\n return function(base * base, exponent // 2)\n else:\n return base * function(base * base, (exponent - 1) // 2)\n\n f = function()\n \n return float(f) if n >= 0 else 1/f\n```
4,884
N-Queens
n-queens
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Array,Backtracking
Hard
null
59,107
352
ideas: <br>\nUse the `DFS` helper function to find solutions recursively. A solution will be found when the length of `queens` is equal to `n` ( `queens` is a list of the indices of the queens).<br><br>\nIn this problem, whenever a location `(x, y`) is occupied, any other locations `(p, q )` where `p + q == x + y` or `p - q == x - y` would be invalid. We can use this information to keep track of the indicators (`xy_dif` and `xy_sum` ) of the invalid positions and then call DFS recursively with valid positions only. <br><br>\n\nAt the end, we convert the result (a list of lists; each sublist is the indices of the queens) into the desire format.\n\n\n def solveNQueens(self, n):\n def DFS(queens, xy_dif, xy_sum):\n p = len(queens)\n if p==n:\n result.append(queens)\n return None\n for q in range(n):\n if q not in queens and p-q not in xy_dif and p+q not in xy_sum: \n DFS(queens+[q], xy_dif+[p-q], xy_sum+[p+q]) \n result = []\n DFS([],[],[])\n return [ ["."*i + "Q" + "."*(n-i-1) for i in sol] for sol in result]
4,929
N-Queens
n-queens
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Array,Backtracking
Hard
null
954
8
```\nclass Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n d, boards = set(), []\n\n def backtracking(row, leaft, board):\n if not leaft:\n boards.append([\'\'.join(row )for row in board])\n return\n\n line = [\'.\' for _ in range(n)]\n for col in range(n): #process all columns in current row\n colKey = f\'col_{col}\'\n majorDiagKey = f\'d1_{row-col}\'\n subDiagKey = f\'d2_{row+col}\'\n local_d = set([colKey, majorDiagKey, subDiagKey])\n\n if local_d & d: continue #has intersection (collision)\n \n line[col] = \'Q\'\n board.append(line)\n d.update(local_d)\n \n backtracking(row+1, leaft-1, board)\n \n #return data to previously state\n line[col] = \'.\' \n board.pop() \n d.difference_update(local_d) \n\n backtracking(0, n, [])\n \n return boards\n```
4,931
N-Queens
n-queens
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Array,Backtracking
Hard
null
7,601
46
The approach that we will be using is backtracking. I have added comments in the code to help understand better.\n\n```\nclass Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n state= [["."] * n for _ in range(n)] # start with empty board\n res=[]\n \n # for tracking the columns which already have a queen\n visited_cols=set()\n \n # This will hold the difference of row and col\n # This is required to identify diagonals\n # specifically for diagonals with increasing row and increasing col pattern\n # example: square (1,0) = 1-0 = 1\n # squares in same diagonals will have same difference\n # example: squares (0,0) and (8,8) are in the same diagonal\n # as both have same difference which is `0`\n \n visited_diagonals=set()\n \n # This will hold the sum of row and col\n # This is required to identify antidiagonals.\n # specifically for diagonals with increasing row and decreasing col pattern\n # the squares in same diagonal won\'t have the same difference.\n # example: square (1,0) = 1-0 = 1\n # squares in same diagonals will have same difference\n # example: squares (0,7) and (1,6) are in the same diagonal\n # as both have same sum which is `7`\n visited_antidiagonals=set()\n \n def backtrack(r):\n if r==n: \n res.append(["".join(row) for row in state])\n return\n \n for c in range(n):\n diff=r-c\n _sum=r+c\n \n # If the current square doesn\'t have another queen in same column and diagonal.\n if not (c in visited_cols or diff in visited_diagonals or _sum in visited_antidiagonals): \n visited_cols.add(c)\n visited_diagonals.add(diff)\n visited_antidiagonals.add(_sum)\n state[r][c]=\'Q\' # place the queen\n backtrack(r+1) \n\n # reset the path\n visited_cols.remove(c)\n visited_diagonals.remove(diff)\n visited_antidiagonals.remove(_sum)\n state[r][c]=\'.\' \n\n backtrack(0)\n return res\n```\n\n**Time - O(N!)** - In the solution tree, number of valid exploration paths from a node reduces by 2 at each level. In first level, we have N columns options to place the queen i.e N paths from the root node. In the next level, we have max N-2 options available because we can\'t place the queen in same column and same diagonal as previous queen. In the next level, it will be N-4 because of two columns and two diagonals occupied by previous two queens. This will continue and give us a `O(N!)`Time. (Let me know if you think otherwise :) )\n\n**Space - O(N^2)** - recursive call stack to explore all possible solutions\n\n---\n\n***Please upvote if you find it useful***
4,940
N-Queens
n-queens
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Array,Backtracking
Hard
null
2,473
21
```\nclass Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n def issafe(r,c):\n n = len(board)\n for i in range(n):\n if board[i][c] == \'Q\':\n return False\n if r - i >= 0 and c - i >= 0 and board[r-i][c-i] == \'Q\':\n return False\n if r - i >= 0 and c + i < n and board[r-i][c+i] == \'Q\':\n return False\n return True\n \n def solve(r):\n n = len(board)\n if r == n:\n print(board)\n ans.append(["".join(i) for i in board])\n return \n for c in range(0,n):\n if issafe(r,c):\n board[r][c] = \'Q\'\n solve(r+1)\n board[r][c] = \'.\'\n board = [[\'.\']*n for i in range(n)]\n ans =[]\n solve(0) \n return ans\n# Please upvote if you understand the solution
4,958
N-Queens
n-queens
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Array,Backtracking
Hard
null
23,185
119
\n \n def solveNQueens(self, n):\n res = []\n self.dfs([-1]*n, 0, [], res)\n return res\n \n # nums is a one-dimension array, like [1, 3, 0, 2] means\n # first queen is placed in column 1, second queen is placed\n # in column 3, etc.\n def dfs(self, nums, index, path, res):\n if index == len(nums):\n res.append(path)\n return # backtracking\n for i in xrange(len(nums)):\n nums[index] = i\n if self.valid(nums, index): # pruning\n tmp = "."*len(nums)\n self.dfs(nums, index+1, path+[tmp[:i]+"Q"+tmp[i+1:]], res)\n \n # check whether nth queen can be placed in that column\n def valid(self, nums, n):\n for i in xrange(n):\n if abs(nums[i]-nums[n]) == n -i or nums[i] == nums[n]:\n return False\n return True
4,970
N-Queens
n-queens
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Array,Backtracking
Hard
null
909
15
```\nclass Solution:\n \n #BackTracking\n def IsSafe(self,row,column,n,board):\n\n # Check in the row if Q is present or not\n for i in range(column):\n if board[row][i] == "Q":\n return False\n \n # Check in the upper Diagonal\n i,j = row,column\n while(i>=0 and j>=0):\n if(board[i][j] == "Q"):\n return False\n i -= 1\n j -= 1\n\n #Check Lower Diagonal\n i,j = row,column\n while(i<n and j>=0):\n if(board[i][j] == "Q"):\n return False\n i += 1\n j -= 1\n\n return True\n\n\n def solveQueens(self,column,n,board,result):\n\n if column == n:\n result.append(["".join(i) for i in board])\n \n return\n \n for row in range(n):\n if(self.IsSafe(row,column,n,board)):\n board[row][column] = "Q"\n self.solveQueens(column+1,n,board,result)\n board[row][column] = "."\n \n return\n\n def solveNQueens(self, n: int) -> List[List[str]]:\n board = [["." for i in range(n)] for i in range(n)]\n result = []\n self.solveQueens(0,n,board,result)\n return result\n```
4,998
N-Queens II
n-queens-ii
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Backtracking
Hard
null
775
9
**UPVOTE IF HELPFUL**\n\nWe first create a **( n X n )** chess board and assign **0** to every index.\nWhenever a queen will be placed, index will be made **1**.\n\nIn this approach , we fill queens **column-wise** starting from left side.\n\nWhenever a queen is placed, at first it is checked if it satisfies the conditions given that it is not under attack.\n\n**validMove** function.\nFirst it check there are no other queen in row the queen is filled.\nAs we are putting queen column wise so no need to check for column.\nThen there are two diagonals to check for.\n* Only left part of the diagonals are checked as positions to the right of the present column are still unfilled.\n\nIf conditions satisfied, Queen is placed and we move to next column.\nIf no queen satisfy the problem, we backtrack and try to change the position of previous queen.\n\n**UPVOTE IF HELPFUL**\n```\nclass Solution:\n def totalNQueens(self, n: int) -> List[List[str]]:\n def validMove(board,row,col):\n i=col\n while i>=0:\n if board[row][i]:\n return False\n i-=1\n i=row\n j=col\n while (i>=0 and j>=0):\n if board[i][j]:\n return False\n i-=1\n j-=1\n i=row\n j=col\n while (i<n and j>=0):\n if board[i][j]:\n return False\n i+=1\n j-=1\n return True\n def solve(board,col):\n if (col==n):\n res[0]+=1\n return\n for i in range(n):\n if validMove(board,i,col):\n board[i][col]=1\n solve(board,col+1)\n board[i][col]=0\n return\n \n res=[0]\n board=[]\n for i in range(n):\n board.append([])\n for j in range(n):\n board[-1].append(0)\n solve(board,0)\n return res[0]\n```\n![image]()\n
5,035
N-Queens II
n-queens-ii
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Backtracking
Hard
null
3,027
22
This problem is an extension on the yesterday\'s daily challenge problem [N-Queens](). Please refer the link to understand how **N-Queens** is implemented. \n\n\nThe below code is just a slight modification on yesterday\'s [solution]() that I had posted. In this, instead of returning the list of valid solutions, I am returning the count of number of valid solutions.\n\n```\nclass Solution:\n def totalNQueens(self, n: int) -> int:\n state=[[\'.\'] * n for _ in range(n)]\n\t\t\n\t\t# for tracking the columns which already have a queen\n visited_cols=set()\n\t\t\n\t\t# This will hold the difference of row and col\n # This is required to identify diagonals\n # specifically for diagonals with increasing row and increasing col pattern\n # example: square (1,0) = 1-0 = 1\n # squares in same diagonals will have same difference\n # example: squares (0,0) and (8,8) are in the same diagonal\n # as both have same difference which is `0`\n visited_diagonals=set()\n\t\t\n\t\t # This will hold the sum of row and col\n # This is required to identify antidiagonals.\n # specifically for diagonals with increasing row and decreasing col pattern\n # the squares in same diagonal won\'t have the same difference.\n # example: square (1,0) = 1-0 = 1\n # squares in same diagonals will have same difference\n # example: squares (0,7) and (1,6) are in the same diagonal\n # as both have same sum which is `7`\n visited_antidiagonals=set()\n \n res=set()\n def backtrack(r):\n if r==n:\n res.add(map(\'#\'.join, map(\'\'.join, state))) # add a valid solution\n return\n \n for c in range(n):\n\t\t\t # If the current square doesn\'t have another queen in same column and diagonal.\n if not(c in visited_cols or (r-c) in visited_diagonals or (r+c) in visited_antidiagonals):\n visited_cols.add(c)\n visited_diagonals.add(r-c)\n visited_antidiagonals.add(r+c)\n state[r][c]=\'Q\'\n backtrack(r+1)\n \n\t\t\t\t\t# reset the exploration path for backtracking\n visited_cols.remove(c)\n visited_diagonals.remove(r-c)\n visited_antidiagonals.remove(r+c)\n state[r][c]=\'.\'\n \n backtrack(0)\n return len(res)\n\n```\n\nBut sometimes while building a solution for a problem that is an extension or similar to another problem, we might end up with similar solution with slight change. This is what I did in my above approach. We were already tracking valid solutions in [N-Queens](). So instead of returning the list of valid solutions, I am returning count of the number of solutions in the list.\n\nIf you observe the exploration path that solution tree takes, you would notice that it starts at a different row each time. Each path it takes is unique. So instead of tracking the valid solutions. We can just track the count of valid solutions. Whenever we hit the required number of queens, we just add that path to overall tally.\n\n```\nclass Solution:\n def totalNQueens(self, n: int) -> int: \n visited_cols=set()\n visited_diagonals=set()\n visited_antidiagonals=set()\n \n res=set()\n def backtrack(r):\n if r==n: # valid solution state \n return 1\n \n cnt=0\n for c in range(n):\n if not(c in visited_cols or (r-c) in visited_diagonals or (r+c) in visited_antidiagonals):\n visited_cols.add(c)\n visited_diagonals.add(r-c)\n visited_antidiagonals.add(r+c) \n cnt+=backtrack(r+1) # count the overall tally from this current state\n \n visited_cols.remove(c)\n visited_diagonals.remove(r-c)\n visited_antidiagonals.remove(r+c) \n \n return cnt\n \n return backtrack(0)\n\n```\n\n**Time - O(N!)** - In the solution tree, number of valid exploration paths from a node reduces by 2 at each level. In first level, we have `N` columns options to place the queen i.e `N` paths from the root node. In the next level, we have max `N-2` options available because we can\'t place the queen in same column and same diagonal as previous queen. In the next level, it will be `N-4` because of two columns and two diagonals occupied by previous two queens. This will continue and give us a `O(N!)`Time. (Let me know if you think otherwise :) )\n\n**Space - O(N^2)** - recursive call stack to explore all possible solutions\n\n---\n\n***Please upvote if you find it useful***
5,041
N-Queens II
n-queens-ii
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Backtracking
Hard
null
425
5
**UPVOTE IF HELPFUL**\nWe first create a **( n X n )** chess board and assign **0** to every index.\nWhenever a queen will be placed, index will be made **1**.\n\nIn this approach , we fill queens **column-wise** starting from left side.\n\nWhenever a queen is placed, at first it is checked if it satisfies the conditions given that it is not under attack.\n\n**validMove** function.\nFirst it check there are no other queen in row the queen is filled.\nAs we are putting queen column wise so no need to check for column.\nThen there are two diagonals to check for.\n* Only left part of the diagonals are checked as positions to the right of the present column are still unfilled.\n\nIf conditions satisfied, Queen is placed and we move to next column.\nIf no queen satisfy the problem, we backtrack and try to change the position of previous queen.\n**UPVOTE IF HELPFUL**\n```\nclass Solution:\n def totalNQueens(self, n: int) -> List[List[str]]:\n def validMove(board,row,col):\n i=col\n while i>=0:\n if board[row][i]:\n return False\n i-=1\n i=row\n j=col\n while (i>=0 and j>=0):\n if board[i][j]:\n return False\n i-=1\n j-=1\n i=row\n j=col\n while (i<n and j>=0):\n if board[i][j]:\n return False\n i+=1\n j-=1\n return True\n def solve(board,col):\n if (col==n):\n res[0]+=1\n return\n for i in range(n):\n if validMove(board,i,col):\n board[i][col]=1\n solve(board,col+1)\n board[i][col]=0\n return\n \n res=[0]\n board=[]\n for i in range(n):\n board.append([])\n for j in range(n):\n board[-1].append(0)\n solve(board,0)\n return res[0]\n```\n![image]()\n\n
5,047
N-Queens II
n-queens-ii
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Backtracking
Hard
null
2,565
27
*(Note: This is part of a series of Leetcode solution explanations. If you like this solution or find it useful,* ***please upvote*** *this post.)*\n\n---\n\n#### ***Idea:***\n\n_(**Note**: This problem is an easier duplicate to the previous problem, [**51: N-Queens**](), except that it doesn\'t require us to return the actual boards, just the count.)_\n\nA naive approach here would attempt every possible combination of locations, but there are **(N^2)! / (N^2 - N)!** different combinations, which is up to **~1e17** when **N = 9**. Instead, we need to make sure we only attempt to place queens where it\'s feasible to do so, based on the instructions. This would seem to call for a **depth first search** (**DFS**) approach with a **recursive** helper function (**place**), so that we only pursue workable combinations without wasting time on known dead-ends.\n\nFirst, we should consider how the queens will be placed. Since each row can only have one queen, our basic process will be to **place** a queen and then recurse to the next row. On each row, we\'ll have to iterate through the possible options, check the cell for validity, then **place** the queen on the board.\n\nRather than store the whole board, we can save on **space complexity** if we only keep track of the different axes of attack in which a queen might be placed. Since a queen has four axes of attack, we\'ll need to check the three remaining axes (other than the horizontal row, which our iteration will naturally take care of) for validity.\n\nThere are **N** possible columns and **2 * N - 1** possible left-downward diagonals and right-downward diagonals. With a constraint of **1 <= N <= 9,** each of the two diagonal states represents up to **17 bits**\' worth of data and the vertical state up to **9 bits**, so we can use **bit manipulation** to store these states efficiently.\n\nSo for each recursive call to **place** a queen, we should pass along the board state in the form of only three integers (**vert, ldiag, rdiag**). We can then use **bitmasks** to check for cell validity before attempting to recurse to the next row.\n\nIf we successfully reach the end of the board without failing, we should increment our answer counter (**ans**).\n\n - _**Time Complexity: O(N!)** which represents the maximum number of queens placed_\n - _**Space Complexity: O(N)** for the recursion stack_\n\n---\n\n#### ***Javascript Code:***\n\nThe best result for the code below is **68ms / 38.0MB** (beats 100% / 99%).\n```javascript\nvar totalNQueens = function(N) {\n let ans = 0\n \n const place = (i, vert, ldiag, rdiag) => {\n if (i === N) ans++\n else for (let j = 0; j < N; j++) {\n let vmask = 1 << j, lmask = 1 << (i+j), rmask = 1 << (N-i-1+j)\n if (vert & vmask || ldiag & lmask || rdiag & rmask) continue\n place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask)\n }\n }\n\n place(0,0,0,0)\n return ans\n};\n```\n\n---\n\n#### ***Python Code:***\n\nThe best result for the code below is **44ms / 13.9MB** (beats 90% / 99%).\n```python\nclass Solution:\n def totalNQueens(self, N: int) -> int:\n self.ans = 0\n \n def place(i: int, vert: int, ldiag: int, rdiag:int) -> None:\n if i == N: self.ans += 1\n else:\n for j in range(N):\n vmask, lmask, rmask = 1 << j, 1 << (i+j), 1 << (N-i-1+j)\n if vert & vmask or ldiag & lmask or rdiag & rmask: continue\n place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask)\n \n place(0,0,0,0)\n return self.ans\n```\n\n---\n\n#### ***Java Code:***\n\nThe best result for the code below is **0ms / 35.2MB** (beats 100% / 99%).\n```java\nclass Solution {\n int ans;\n \n public int totalNQueens(int N) {\n ans = 0;\n place(0,0,0,0,N);\n return ans;\n }\n \n private void place(int i, int vert, int ldiag, int rdiag, int N) {\n if (i == N) ans++;\n else for (int j = 0; j < N; j++) {\n int vmask = 1 << j, lmask = 1 << (i+j), rmask = 1 << (N-i-1+j);\n if ((vert & vmask) + (ldiag & lmask) + (rdiag & rmask) > 0) continue;\n place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask, N);\n }\n }\n}\n```\n\n---\n\n#### ***C++ Code:***\n\nThe best result for the code below is **0ms / 5.8MB** (beats 100% / 99%).\n```c++\nclass Solution {\npublic:\n int totalNQueens(int N) {\n ans = 0;\n place(0,0,0,0,N);\n return ans;\n }\n \nprivate:\n int ans;\n \n void place(int i, int vert, int ldiag, int rdiag, int N) {\n if (i == N) ans++;\n else for (int j = 0; j < N; j++) {\n int vmask = 1 << j, lmask = 1 << (i+j), rmask = 1 << (N-i-1+j);\n if (vert & vmask || ldiag & lmask || rdiag & rmask) continue;\n place(i+1, vert | vmask, ldiag | lmask, rdiag | rmask, N);\n }\n }\n};\n```
5,056
N-Queens II
n-queens-ii
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Backtracking
Hard
null
912
5
\n\n# 1. BackTracking Logic Solution\n\n```\nclass Solution:\n def totalNQueens(self, n: int) -> int:\n res,col,pos,neg=0,set(),set(),set()\n def backtracking(r):\n if n==r:\n nonlocal res\n res+=1\n for c in range(n):\n if c in col or (c+r) in pos or (r-c) in neg:\n continue\n col.add(c)\n pos.add(c+r)\n neg.add(r-c)\n backtracking(r+1)\n col.remove(c)\n pos.remove(c+r)\n neg.remove(r-c)\n backtracking(0)\n return res\n #please upvote me it would encourage me alot\n\n\n```\n\n# please upvote me it would encourage me alot\n
5,057
N-Queens II
n-queens-ii
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Backtracking
Hard
null
8,405
41
The idea here is quite similar to [N-Queens ][1] while we don\'t need to record the path, and as the return value is a number not a list, it\'s better to use a global variable to record the result.\n \n def totalNQueens(self, n):\n self.res = 0\n self.dfs([-1]*n, 0)\n return self.res\n \n def dfs(self, nums, index):\n if index == len(nums):\n self.res += 1\n return #backtracking\n for i in range(len(nums)):\n nums[index] = i\n if self.valid(nums, index):\n self.dfs(nums, index+1)\n \n def valid(self, nums, n):\n for i in range(n):\n if nums[i] == nums[n] or abs(nums[n]-nums[i]) == n-i:\n return False\n return True\n\n\n [1]:
5,080
N-Queens II
n-queens-ii
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Backtracking
Hard
null
585
5
This solution is basically the same as the solution introduced in the article, but I condensed it into 10 lines of code to look more compact.\n\n```\nclass Solution:\n def totalNQueens(self, n: int) -> int: \n def rec(col, horizontal, diag, anti_diag):\n if col == n: return 1\n res = 0\n for row in range(n):\n if row not in horizontal and (row + col) not in diag and (row - col) not in anti_diag:\n horizontal[row] = True; diag[row + col] = True; anti_diag[row - col] = True;\n res += rec(col + 1, horizontal, diag, anti_diag)\n del horizontal[row]; del diag[row + col]; del anti_diag[row - col];\n return res\n return rec(0, {}, {}, {})\n```
5,096
Maximum Subarray
maximum-subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array.
Array,Divide and Conquer,Dynamic Programming
Easy
null
63,716
324
# Intuition\nThe Intuition behind the code is to find the maximum sum of a contiguous subarray within the given array `nums`. It does this by scanning through the array and keeping track of the current sum of the subarray. Whenever the current sum becomes greater than the maximum sum encountered so far, it updates the maximum sum. If the current sum becomes negative, it resets the sum to 0 and starts a new subarray. By the end of the loop, the code returns the maximum sum found.\n\n# Approach:\n\n1. We start by initializing two variables: `maxSum` and `currentSum`.\n - `maxSum` represents the maximum sum encountered so far and is initially set to the minimum possible integer value to ensure that any valid subarray sum will be greater than it.\n - `currentSum` represents the current sum of the subarray being considered and is initially set to 0.\n2. We iterate through the `nums` array using a for loop, starting from the first element and going up to the last element.\n3. For each element in the array, we add it to the current sum `currentSum`. This calculates the sum of the subarray ending at the current element.\n4. Next, we check if the current sum `currentSum` is greater than the current maximum sum `maxSum`.\n - If it is, we update `maxSum` with the new value of `currentSum`. This means we have found a new maximum subarray sum.\n5. If the current sum `currentSum` becomes negative, it indicates that including the current element in the subarray would reduce the overall sum. In such cases, we reset `currentSum` to 0. This effectively discards the current subarray and allows us to start a fresh subarray from the next element.\n6. We repeat steps 3 to 5 for each element in the array.\n7. After iterating through the entire array, the variable `maxSum` will contain the maximum subarray sum encountered.\n8. Finally, we return the value of `maxSum` as the result, representing the maximum sum of a contiguous subarray within the given array `nums`.\n\n# Code\n\n```C++ []\nclass Solution {\npublic:\n int maxSubArray(vector<int>& nums) {\n int maxSum = INT_MIN;\n int currentSum = 0;\n \n for (int i = 0; i < nums.size(); i++) {\n currentSum += nums[i];\n \n if (currentSum > maxSum) {\n maxSum = currentSum;\n }\n \n if (currentSum < 0) {\n currentSum = 0;\n }\n }\n \n return maxSum;\n }\n};\n```\n```Java []\nclass Solution {\n public int maxSubArray(int[] nums) {\n int maxSum = Integer.MIN_VALUE;\n int currentSum = 0;\n \n for (int i = 0; i < nums.length; i++) {\n currentSum += nums[i];\n \n if (currentSum > maxSum) {\n maxSum = currentSum;\n }\n \n if (currentSum < 0) {\n currentSum = 0;\n }\n }\n \n return maxSum;\n }\n}\n```\n```Python3 []\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n maxSum = float(\'-inf\')\n currentSum = 0\n \n for num in nums:\n currentSum += num\n \n if currentSum > maxSum:\n maxSum = currentSum\n \n if currentSum < 0:\n currentSum = 0\n \n return maxSum\n```\n\n# clean code\n\n```C++ []\nclass Solution {\npublic:\n int maxSubArray(vector<int>& nums) {\n int maxSum = nums[0];\n int currentSum = nums[0];\n\n for (int i = 1; i < nums.size(); i++) {\n currentSum = max(nums[i], currentSum + nums[i]);\n maxSum = max(maxSum, currentSum);\n }\n\n return maxSum;\n }\n};\n```\n```Java []\nclass Solution {\n public int maxSubArray(int[] nums) {\n int maxSum = nums[0];\n int currentSum = nums[0];\n\n for (int i = 1; i < nums.length; i++) {\n currentSum = Math.max(nums[i], currentSum + nums[i]);\n maxSum = Math.max(maxSum, currentSum);\n }\n\n return maxSum;\n }\n}\n```\n```Python3 []\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n maxSum = nums[0]\n currentSum = nums[0]\n\n for num in nums[1:]:\n currentSum = max(num, currentSum + num)\n maxSum = max(maxSum, currentSum)\n\n return maxSum\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\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\n
5,101
Maximum Subarray
maximum-subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array.
Array,Divide and Conquer,Dynamic Programming
Easy
null
24,881
103
**NOTE - PLEASE READ INTUITION AND APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n# Intuition of this Problem:\nWe can solve this problem using **Kadane\'s Algorithm**\n\n**LETS DRY RUN THIS CODE WITH ONE EXAPMPLE :**\n\nSuppose we have the following input vector: **[-2, 1, -3, 4, -1, 2, 1, -5, 4].**\n\nWe initialize the maximumSum = INT_MIN (-2147483648) and currSumSubarray = 0.\n\nWe loop through the input vector and perform the following operations:\n\nAt the first iteration, currSumSubarray becomes -2 and since it is less than 0, we set it to 0. maximumSum remains at INT_MIN.\n\nAt the second iteration, currSumSubarray becomes 1, which is greater than 0, so we keep it as it is. We update maximumSum to 1.\n\nAt the third iteration, currSumSubarray becomes -2, which is less than 0, so we set it to 0. maximumSum remains at 1.\n\nAt the fourth iteration, currSumSubarray becomes 4, which is greater than 0, so we keep it as it is. We update maximumSum to 4.\n\nAt the fifth iteration, currSumSubarray becomes 3, which is greater than 0, so we keep it as it is. maximumSum remains at 4.\n\nAt the sixth iteration, currSumSubarray becomes 5, which is greater than 0, so we keep it as it is. We update maximumSum to 5.\n\nAt the seventh iteration, currSumSubarray becomes 6, which is greater than 0, so we keep it as it is. We update maximumSum to 6.\n\nAt the eighth iteration, currSumSubarray becomes 1, which is greater than 0, so we keep it as it is. maximumSum remains at 6.\n\nAt the ninth iteration, currSumSubarray becomes 5, which is greater than 0, so we keep it as it is. maximumSum remains at 6.\n\nAfter iterating through the input vector, we return maximumSum which is equal to 6. Therefore, the maximum sum subarray of the given input vector is [4, -1, 2, 1], and the sum of this subarray is 6.\n\n\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach for this Problem:\n1. Initialize two variables, maximumSum and currSumSubarray to the minimum integer value (INT_MIN) and 0, respectively.\n2. Loop through the array from index 0 to n-1, where n is the size of the array.\n3. In each iteration, add the current element of the array to the currSumSubarray variable.\n4. Take the maximum between maximumSum and currSumSubarray and store it in the maximumSum variable.\n5. Take the maximum between currSumSubarray and 0 and store it in currSumSubarray. This is done because if the currSumSubarray becomes negative, it means that we should start a new subarray, so we reset currSumSubarray to 0.\n6. After the loop ends, return the maximumSum variable, which contains the maximum sum of a subarray.\n<!-- Describe your approach to solving the problem. -->\n\n\n# Code:\n```C++ []\nclass Solution {\npublic:\n int maxSubArray(vector<int>& nums) {\n int n = nums.size();\n //maximumSum will calculate our ans and currSumSubarray will calculate maximum sum subarray till ith position \n int maximumSum = INT_MIN, currSumSubarray = 0;\n for (int i = 0; i < n; i++) {\n currSumSubarray += nums[i]; \n maximumSum = max(maximumSum, currSumSubarray);\n //here we are taking max with 0 bcz if currSumSubarray = -1 or any negative value then it again starts with currSumSubarray = 0\n currSumSubarray = max(currSumSubarray, 0);\n } \n return maximumSum;\n }\n};\n```\n```Java []\nclass Solution {\n public int maxSubArray(int[] nums) {\n int n = nums.length;\n int maximumSum = Integer.MIN_VALUE, currSumSubarray = 0;\n for (int i = 0; i < n; i++) {\n currSumSubarray += nums[i]; \n maximumSum = Math.max(maximumSum, currSumSubarray);\n currSumSubarray = Math.max(currSumSubarray, 0);\n } \n return maximumSum;\n }\n}\n\n```\n```Python []\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n n = len(nums)\n maximumSum, currSumSubarray = float(\'-inf\'), 0\n for i in range(n):\n currSumSubarray += nums[i]\n maximumSum = max(maximumSum, currSumSubarray)\n currSumSubarray = max(currSumSubarray, 0)\n return maximumSum\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(n)**, where n is the size of the input array. The algorithm has to loop through the array only once.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(1)**, since the algorithm is using only a constant amount of extra space regardless of the input size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
5,157
Maximum Subarray
maximum-subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. A subarray is a contiguous part of an array.
Array,Divide and Conquer,Dynamic Programming
Easy
null
29,876
151
# **Java Solution (Dynamic Programming Approach):**\nRuntime: 1 ms, faster than 89.13% of Java online submissions for Maximum Subarray.\n```\nclass Solution {\n public int maxSubArray(int[] nums) {\n // Initialize currMaxSum & take first element of array from which we start to do sum...\n int maxSum = nums[0];\n // Initialize the current sum of our subarray as nums[0]...\n int currSum = nums[0];\n // Traverse all the element through the loop...\n for (int i = 1; i < nums.length; i++) {\n // Do sum of elements contigous with curr sum...\n // Compare it with array element to get maximum result...\n currSum = Math.max(currSum + nums[i], nums[i]);\n // Compare current sum and max sum.\n maxSum = Math.max(maxSum, currSum);\n }\n return maxSum; // return the contiguous subarray which has the largest sum...\n }\n}\n```\n\n# **C++ Solution (Kadane\u2019s approach):**\n```\nclass Solution {\npublic:\n int maxSubArray(vector<int>& nums) {\n // Initialize maxSum as an integer that cannot store any value below the limit...\n int maxSum = INT_MIN;\n // Initialize maxSum...\n int maxSumSoFar = 0;\n // Traverse all the element through the loop...\n for(int i = 0; i < nums.size(); i++){\n // Keep adding the current value...\n maxSumSoFar += nums[i];\n // Update maxSum to maxSum and maxSumSoFar...\n if(maxSum < maxSumSoFar){\n maxSum = maxSumSoFar;\n }\n // if maxSumSoFar is less than 0 then update it to 0...\n if(maxSumSoFar < 0){\n maxSumSoFar = 0;\n }\n }\n return maxSum; // Return the contiguous subarray which has the largest sum...\n }\n};\n```\n\n# **Python Solution (Dynamic Programming Approach):**\nRuntime: 585 ms, faster than 95.18% of Python online submissions for Maximum Subarray.\nMemory Usage: 25.3 MB, less than 97.76% of Python online submissions for Maximum Subarray.\n```\nclass Solution(object):\n def maxSubArray(self, nums):\n # Create an array...\n arr = []\n arr.append(nums[0])\n # Initialize the max sum...\n maxSum = arr[0]\n # Traverse all the element through the loop...\n for i in range(1, len(nums)):\n # arr[i] represents the largest sum of all subarrays ending with index i...\n # then its value should be the larger one between nums[i]...\n # arr[i-1] + nums[i] (largest sum plus current number with using prefix)...\n # calculate arr[0], arr[1]\u2026, arr[n] while comparing each one with current largest sum...\n arr.append(max(arr[i-1] + nums[i], nums[i]))\n # if arr[i] > maxSum then maxSum = arr[i].\n if arr[i] > maxSum:\n maxSum = arr[i]\n return maxSum # Return the contiguous subarray which has the largest sum...\n```\n \n# **JavaScript Solution (Dynamic Programming Approach):**\nRuntime: 103 ms, faster than 75.34% of JavaScript online submissions for Maximum Subarray.\n```\nvar maxSubArray = function(nums) {\n // Initialize the max sum...\n let maxSum = nums[0];\n // Traverse all the element through the loop...\n for (let i = 1; i < nums.length; i++) {\n // nums[i] represents the largest sum of all subarrays ending with index i...\n // then its value should be the larger one between nums[i]...\n // nums[i-1] + nums[i] (largest sum plus current number with using prefix)...\n // calculate nums[0], nums[1]\u2026, nums[n] while comparing each one with current largest sum...\n nums[i] = Math.max(0, nums[i - 1]) + nums[i];\n // if nums[i] > maxSum then maxSum = nums[i]...\n if (nums[i] > maxSum)\n maxSum = nums[i];\n }\n return maxSum; // return the contiguous subarray which has the largest sum...\n};\n```\n\n# **C Language (Kadane\u2019s approach):**\n```\nint maxSubArray(int* nums, int numsSize){\n // Initialize maxSum as an integer that cannot store any value below the limit...\n int maxSum = nums[0];\n // Initialize maxSum...\n int maxSumSoFar = 0;\n // Traverse all the element through the loop...\n for(int i = 0; i < numsSize; i++){\n // Keep adding the current value...\n maxSumSoFar += nums[i];\n // Update maxSum to maxSum and maxSumSoFar...\n if(maxSum < maxSumSoFar){\n maxSum = maxSumSoFar;\n }\n // if maxSumSoFar is less than 0 then update it to 0...\n if(maxSumSoFar < 0){\n maxSumSoFar = 0;\n }\n }\n return maxSum; // Return the contiguous subarray which has the largest sum...\n}\n```\n\n# **Python3 Solution (Dynamic Programming Approach):**\n```\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n # Create an array...\n arr = []\n arr.append(nums[0])\n # Initialize the max sum...\n maxSum = arr[0]\n for i in range(1, len(nums)):\n # arr[i] represents the largest sum of all subarrays ending with index i...\n # then its value should be the larger one between nums[i]...\n # arr[i-1] + nums[i] (largest sum plus current number with using prefix)...\n # calculate arr[0], arr[1]\u2026, arr[n] while comparing each one with current largest sum...\n arr.append(max(arr[i-1] + nums[i], nums[i]))\n # if arr[i] > maxSum then maxSum = arr[i].\n if arr[i] > maxSum:\n maxSum = arr[i]\n return maxSum # Return the contiguous subarray which has the largest sum...\n```\n**I am working hard for you guys...\nPlease upvote if you find any help with this code...**
5,176
Spiral Matrix
spiral-matrix
Given an m x n matrix, return all elements of the matrix in spiral order.
Array,Matrix,Simulation
Medium
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
44,782
215
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. I planned to give for next 10,000 Subscribers as well. If you\'re interested **DON\'T FORGET** to Subscribe\n\n# Search \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n# Video Solution \n\n# Search \uD83D\uDC49 `Spiral Matrix by Tech Wired `\n\n# or\n\n# Click the Link in my Profile\n\n# Approach:\n\n- We will use a while loop to traverse the matrix in a clockwise spiral order.\n- We will define four variables: left, right, top, bottom to represent the four boundaries of the current spiral.\n- We will use four for loops to traverse each edge of the current spiral in clockwise order and add the elements to the result list.\n- We will update the boundaries of the current spiral and continue the process until all elements have been traversed.\n\n# Intuition:\n\n- We start with the outermost layer of the matrix and traverse it in a clockwise spiral order, adding the elements to the result list.\n- Then we move on to the next inner layer of the matrix and repeat the process until we have traversed all layers.\n- To traverse each layer, we need to keep track of the four boundaries of the current spiral.\n- We start at the top-left corner of the current spiral and move right until we hit the top-right corner.\n- Then we move down to the bottom-right corner and move left until we hit the bottom-left corner.\n- Finally, we move up to the top-left corner of the next spiral and repeat the process until we have traversed all elements in the matrix.\n\n\n\n\n\n```Python []\nclass Solution:\n def spiralOrder(self, matrix: List[List[int]]) -> List[int]:\n if not matrix:\n return []\n\n rows, cols = len(matrix), len(matrix[0])\n top, bottom, left, right = 0, rows-1, 0, cols-1\n result = []\n \n while len(result) < rows * cols:\n for i in range(left, right+1):\n result.append(matrix[top][i])\n top += 1\n \n for i in range(top, bottom+1):\n result.append(matrix[i][right])\n right -= 1\n \n if top <= bottom:\n for i in range(right, left-1, -1):\n result.append(matrix[bottom][i])\n bottom -= 1\n \n if left <= right:\n for i in range(bottom, top-1, -1):\n result.append(matrix[i][left])\n left += 1\n \n return result\n\n```\n```Java []\nclass Solution {\n public List<Integer> spiralOrder(int[][] matrix) {\n List<Integer> result = new ArrayList<>();\n if (matrix == null || matrix.length == 0) {\n return result;\n }\n \n int rows = matrix.length, cols = matrix[0].length;\n int left = 0, right = cols-1, top = 0, bottom = rows-1;\n \n while (left <= right && top <= bottom) {\n for (int i = left; i <= right; i++) {\n result.add(matrix[top][i]);\n }\n top++;\n \n for (int i = top; i <= bottom; i++) {\n result.add(matrix[i][right]);\n }\n right--;\n \n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n result.add(matrix[bottom][i]);\n }\n bottom--;\n }\n \n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n result.add(matrix[i][left]);\n }\n left++;\n }\n }\n \n return result;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n vector<int> spiralOrder(vector<vector<int>>& matrix) {\n vector<int> result;\n if (matrix.empty() || matrix[0].empty()) {\n return result;\n }\n \n int rows = matrix.size(), cols = matrix[0].size();\n int left = 0, right = cols-1, top = 0, bottom = rows-1;\n \n while (left <= right && top <= bottom) {\n for (int i = left; i <= right; i++) {\n result.push_back(matrix[top][i]);\n }\n top++;\n \n for (int i = top; i <= bottom; i++) {\n result.push_back(matrix[i][right]);\n }\n right--;\n \n if (top <= bottom) {\n for (int i = right; i >= left; i--) {\n result.push_back(matrix[bottom][i]);\n }\n bottom--;\n }\n \n if (left <= right) {\n for (int i = bottom; i >= top; i--) {\n result.push_back(matrix[i][left]);\n }\n left++;\n }\n }\n \n return result;\n }\n};\n\n```\n\n# An Upvote will be encouraging \uD83D\uDC4D
5,213