question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
permutations | JavaScript using DP | javascript-using-dp-by-loctn-iq76 | Here's the common backtracking solution for comparison:\n\nvar permute = function(nums) {\n const res = [];\n backtrack(nums, res);\n return res;\n};\n | loctn | NORMAL | 2017-02-25T14:36:13.313000+00:00 | 2018-09-17T02:55:01.360952+00:00 | 7,773 | false | Here's the common backtracking solution for comparison:\n```\nvar permute = function(nums) {\n const res = [];\n backtrack(nums, res);\n return res;\n};\n\nfunction backtrack(nums, res, n = 0) {\n if (n === nums.length - 1) {\n res.push(nums.slice(0));\n return;\n }\n for (let i = n; i < nums.length; i++) {\n [nums[i], nums[n]] = [nums[n], nums[i]];\n backtrack(nums, res, n + 1);\n [nums[i], nums[n]] = [nums[n], nums[i]];\n }\n}\n```\nThe DP solution came more naturally to my brain and OJ seems to like it for speed:\n```\nvar permute = function(nums, n = 0) {\n if (n >= nums.length) return [[]];\n const res = [];\n const prevs = permute(nums, n + 1); // permutations of elements after n\n for (let prev of prevs) {\n for (let i = 0; i <= prev.length; i++) {\n let p = prev.slice(0);\n p.splice(i, 0, nums[n]); // successively insert element n\n res.push(p);\n }\n }\n return res;\n};\n``` | 26 | 1 | ['JavaScript'] | 3 |
permutations | Java | TC: O(N*N!) | SC: O(N) | Recursive Backtracking & Iterative Solutions | java-tc-onn-sc-on-recursive-backtracking-ncs4 | Recursive Backtracking\n\njava\n/**\n * Recursive Backtracking. In this solution passing the index of the nums that\n * needs to be set in the current recursion | NarutoBaryonMode | NORMAL | 2021-10-18T11:23:56.428444+00:00 | 2021-10-18T11:39:14.681959+00:00 | 2,438 | false | **Recursive Backtracking**\n\n```java\n/**\n * Recursive Backtracking. In this solution passing the index of the nums that\n * needs to be set in the current recursion.\n *\n * Time Complexity: O(N * N!). Number of permutations = P(N,N) = N!. Each\n * permutation takes O(N) to construct\n *\n * T(n) = n*T(n-1) + O(n)\n * T(n-1) = (n-1)*T(n-2) + O(n-1)\n * ...\n * T(2) = (2)*T(1) + O(2)\n * T(1) = O(N) -> To convert the nums array to ArrayList.\n *\n * Above equations can be added together to get:\n * T(n) = n + n*(n-1) + n*(n-1)*(n-2) + ... + (n....2) + (n....1) * n\n * = P(n,1) + P(n,2) + P(n,3) + ... + P(n,n-1) + n*P(n,n)\n * = (P(n,1) + ... + P(n,n)) + (n-1)*P(n,n)\n * = Floor(e*n! - 1) + (n-1)*n!\n * = O(N * N!)\n *\n * Space Complexity: O(N). Recursion stack.\n *\n * N = Length of input array.\n */\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<>();\n if (nums == null || nums.length == 0) {\n return result;\n }\n\n permutationsHelper(result, nums, 0);\n return result;\n }\n\n private void permutationsHelper(List<List<Integer>> result, int[] nums, int start) {\n if (start == nums.length - 1) {\n List<Integer> list = new ArrayList<>();\n for (int n : nums) {\n list.add(n);\n }\n result.add(list);\n return;\n }\n for (int i = start; i < nums.length; i++) {\n swap(nums, start, i);\n permutationsHelper(result, nums, start + 1);\n swap(nums, start, i);\n }\n }\n\n private void swap(int[] nums, int x, int y) {\n int t = nums[x];\n nums[x] = nums[y];\n nums[y] = t;\n }\n}\n```\n\n---\n**Iterative Solution**\n\n```java\n/**\n * Iterative Solution\n *\n * The idea is to add the nth number in every possible position of each\n * permutation of the first n-1 numbers.\n *\n * Time Complexity: O(N * N!). Number of permutations = P(N,N) = N!. Each\n * permutation takes O(N) to construct\n *\n * T(n) = (x=2->n) \u2211 (x-1)!*x(x+1)/2\n * = (x=1->n-1) \u2211 (x)!*x(x-1)/2\n * = O(N * N!)\n *\n * Space Complexity: O((N-1) * (N-1)!) = O(N * N!). All permutations of the first n-1 numbers.\n *\n * N = Length of input array.\n */\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<>();\n if (nums == null || nums.length == 0) {\n return result;\n }\n\n result.add(Arrays.asList(nums[0]));\n\n for (int i = 1; i < nums.length; i++) {\n List<List<Integer>> newResult = new ArrayList<>();\n for (List<Integer> cur : result) {\n for (int j = 0; j <= i; j++) {\n List<Integer> newCur = new ArrayList<>(cur);\n newCur.add(j, nums[i]);\n newResult.add(newCur);\n }\n }\n result = newResult;\n }\n\n return result;\n }\n}\n```\n\n---\n**Recursive Backtracking using visited array**\n\n```java\n/**\n * Recursive Backtracking using visited array.\n *\n * Time Complexity: O(N * N!). Number of permutations = P(N,N) = N!. Each\n * permutation takes O(N) to construct\n *\n * T(n) = n*T(n-1) + O(n)\n * T(n-1) = (n-1)*T(n-2) + O(n)\n * ...\n * T(2) = (2)*T(1) + O(n)\n * T(1) = O(n)\n *\n * Above equations can be added together to get:\n * T(n) = n (1 + n + n*(n-1) + ... + (n....2) + (n....1))\n * = n (P(n,0) + P(n,1) + P(n,1) + ... + P(n,n-1) + P(n,n))\n * = n * Floor(e*n!)\n * = O(N * N!)\n *\n * Space Complexity: O(N). Recursion stack + visited array\n *\n * N = Length of input array.\n */\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<>();\n if (nums == null) {\n return result;\n }\n\n helper(result, new ArrayList<>(), nums, new boolean[nums.length]);\n return result;\n }\n\n private void helper(List<List<Integer>> result, List<Integer> temp, int[] nums, boolean[] visited) {\n if (temp.size() == nums.length) {\n result.add(new ArrayList<>(temp));\n return;\n }\n\n for (int i = 0; i < nums.length; i++) {\n if (visited[i]) {\n continue;\n }\n temp.add(nums[i]);\n visited[i] = true;\n helper(result, temp, nums, visited);\n visited[i] = false;\n temp.remove(temp.size() - 1);\n }\n }\n}\n```\n\n---\n\nSolutions to other Permutations questions on LeetCode:\n- [47. Permutations II](https://leetcode.com/problems/permutations-ii/discuss/1527937/Java-or-TC:-O(N*N!)-or-SC:-O(N)-or-Recursive-Backtracking-and-Iterative-Solutions)\n- [266. Palindrome Permutation](https://leetcode.com/problems/palindrome-permutation/discuss/1527941/Java-or-TC:-O(N)-or-SC:-O(N)-or-Early-Exit-and-Space-Optimized-HashSet-solution)\n- [267. Palindrome Permutation II](https://leetcode.com/problems/palindrome-permutation-ii/discuss/1527948/Java-or-TC:-O(N*(N2)!)-or-SC:-O(N)-or-Optimal-Backtracking-using-CountMap)\n | 25 | 0 | ['Backtracking', 'Recursion', 'Java'] | 1 |
permutations | Easy to understand solution in C++ | easy-to-understand-solution-in-c-by-pran-873h | \nclass Solution {\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n \n sort(nums.begin(),nums.end());\n vector<vector<int>> | pran_17 | NORMAL | 2021-07-02T09:24:09.948042+00:00 | 2021-07-02T09:24:09.948085+00:00 | 941 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n \n sort(nums.begin(),nums.end());\n vector<vector<int>> ans;\n ans.push_back(nums);\n while(next_permutation(nums.begin(),nums.end()))\n {\n ans.push_back(nums);\n }\n \n return ans;\n }\n};\n``` | 25 | 7 | [] | 0 |
permutations | My simple Javascript recursive solution | my-simple-javascript-recursive-solution-praf6 | var permute = function(nums) {\n let results = [];\n \n let permutations = (current, remaining) => {\n if(remaining.length <= 0) results.pus | jsonmartin | NORMAL | 2016-06-21T20:53:02+00:00 | 2018-09-11T18:55:48.963894+00:00 | 6,701 | false | var permute = function(nums) {\n let results = [];\n \n let permutations = (current, remaining) => {\n if(remaining.length <= 0) results.push(current.slice());\n else {\n for(let i = 0; i < remaining.length; i++) { // Loop through remaining elements\n current.push(remaining[i]); // Insert the iTH element onto the end of current\n permutations(current.slice(), remaining.slice(0, i).concat(remaining.slice(i+1))); // Recurse with inserted element removed\n current.pop(); // Remove last inserted element for next iteration\n }\n }\n };\n \n permutations([], nums);\n return results;\n }; | 23 | 0 | ['JavaScript'] | 3 |
permutations | Simple Java Solution With Full Explanation || Simple Recursion || 1 ms faster than 93.44% | simple-java-solution-with-full-explanati-6vcf | \n\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n return permutation(new ArrayList<>(),nums);\n }\n public List<List<Int | bits_manipulator | NORMAL | 2022-03-18T17:44:40.225215+00:00 | 2022-03-21T02:08:47.519392+00:00 | 1,618 | false | \n```\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n return permutation(new ArrayList<>(),nums);\n }\n public List<List<Integer>> permutation(List<Integer> p,int[] up){\n \n if(up.length==0){\n List<List<Integer>> sublist=new ArrayList<>();\n sublist.add(p);\n return sublist;\n }\n int num=up[0];\n List<List<Integer>> ans=new ArrayList<>();\n for(int i=0;i<=p.size();i++){\n List<Integer> new1=new ArrayList<>();\n new1.addAll(p.subList(0,i));\n new1.add(num);\n new1.addAll(p.subList(i,p.size()));\n ans.addAll(permutation(new1,Arrays.copyOfRange(up, 1, up.length)));\n }\n return ans;\n }\n}\n\n// If it seems to easy to understand, give a upvote(reputation)\uD83D\uDC4Dto motivate me\uD83D\uDE09\n``` | 22 | 0 | ['Recursion', 'Java'] | 3 |
permutations | C++ Backtracking | c-backtracking-by-paulariri-qt44 | \nclass Solution {\nprivate:\n vector<vector<int>> result;\n \npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n helper(nums, 0, (int | paulariri | NORMAL | 2020-08-09T03:02:26.854589+00:00 | 2020-08-09T03:02:26.854741+00:00 | 6,078 | false | ```\nclass Solution {\nprivate:\n vector<vector<int>> result;\n \npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n helper(nums, 0, (int)nums.size() - 1);\n \n return result;\n }\n \n void helper(vector<int> num_arr, int l, int r) {\n if (l == r){\n result.push_back(num_arr);\n } \n else { \n for (int i = l; i <= r; i++) {\n swap(num_arr[l], num_arr[i]);\n\n helper(num_arr, l + 1, r); \n\n swap(num_arr[l], num_arr[i]); \n } \n }\n } \n};\n``` | 21 | 1 | ['Backtracking', 'Recursion', 'C', 'C++'] | 4 |
permutations | Clean JavaScript backtracking solution | clean-javascript-backtracking-solution-b-8xsj | js\nconst permute = (nums) => {\n const res = [];\n\n const go = (cur, rest) => {\n if (rest.length === 0) {\n res.push(cur);\n return;\n }\n\ | hongbo-miao | NORMAL | 2018-06-16T06:24:32.526250+00:00 | 2020-09-02T15:46:09.381045+00:00 | 2,494 | false | ```js\nconst permute = (nums) => {\n const res = [];\n\n const go = (cur, rest) => {\n if (rest.length === 0) {\n res.push(cur);\n return;\n }\n\n for (let i = 0; i < rest.length; i++) {\n // note if using array push and splice here, it will cause mutation\n go(\n [...cur, rest[i]],\n [...rest.slice(0, i), ...rest.slice(i + 1)],\n );\n }\n };\n\n go([], nums);\n return res;\n};\n```\n | 20 | 0 | [] | 1 |
permutations | Very simple[C,C++,Java,python3 codes] Easy to understand Approach. | very-simpleccjavapython3-codes-easy-to-u-3a30 | 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 integ | sriganesh777 | NORMAL | 2023-08-02T04:29:11.356524+00:00 | 2023-08-02T04:29:11.356560+00:00 | 1,039 | false | # 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\n | 19 | 0 | ['Backtracking', 'C', 'C++', 'Java', 'Python3'] | 0 |
permutations | 100% faster C++ Solution | Simple Solution | 100-faster-c-solution-simple-solution-by-2lzw | \nclass Solution {\nprivate:\n void solve(vector<int>& nums, vector<vector<int>>& ans, int index){\n if(index >= nums.size()){\n ans.push_b | code_shivam1 | NORMAL | 2022-01-10T18:33:23.160863+00:00 | 2022-01-10T18:33:23.160910+00:00 | 2,944 | false | ```\nclass Solution {\nprivate:\n void solve(vector<int>& nums, vector<vector<int>>& ans, int index){\n if(index >= nums.size()){\n ans.push_back(nums);\n return;\n }\n for(int j=index; j<nums.size(); j++){\n swap(nums[index], nums[j]);\n solve(nums, ans, index+1); //recursive call\n swap(nums[index], nums[j]); //backtracking\n }\n }\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>>ans;\n int index=0;\n solve(nums,ans,index);\n return ans;\n }\n};\n```\nPlease Upvote If You Find the Solution Helpful..\nHappy Coding ! | 19 | 2 | ['Backtracking', 'Recursion', 'C', 'C++'] | 2 |
permutations | Easyway Explanation every step | easyway-explanation-every-step-by-paul_d-in3o | \n\ndfs(nums = [1, 2, 3] , path = [] , result = [] )\n|____ dfs(nums = [2, 3] , path = [1] , result = [] )\n| |___dfs(nums = [3] , path = [1, 2] , result = | paul_dream | NORMAL | 2020-10-17T07:58:03.697226+00:00 | 2020-10-17T07:58:03.697259+00:00 | 1,944 | false | ```\n\ndfs(nums = [1, 2, 3] , path = [] , result = [] )\n|____ dfs(nums = [2, 3] , path = [1] , result = [] )\n| |___dfs(nums = [3] , path = [1, 2] , result = [] )\n| | |___dfs(nums = [] , path = [1, 2, 3] , result = [[1, 2, 3]] ) # added a new permutation to the result\n| |___dfs(nums = [2] , path = [1, 3] , result = [[1, 2, 3]] )\n| |___dfs(nums = [] , path = [1, 3, 2] , result = [[1, 2, 3], [1, 3, 2]] ) # added a new permutation to the result\n|____ dfs(nums = [1, 3] , path = [2] , result = [[1, 2, 3], [1, 3, 2]] )\n| |___dfs(nums = [3] , path = [2, 1] , result = [[1, 2, 3], [1, 3, 2]] )\n| | |___dfs(nums = [] , path = [2, 1, 3] , result = [[1, 2, 3], [1, 3, 2], [2, 1, 3]] ) # added a new permutation to the result\n| |___dfs(nums = [1] , path = [2, 3] , result = [[1, 2, 3], [1, 3, 2], [2, 1, 3]] )\n| |___dfs(nums = [] , path = [2, 3, 1] , result = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1]] ) # added a new permutation to the result\n|____ dfs(nums = [1, 2] , path = [3] , result = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1]] )\n |___dfs(nums = [2] , path = [3, 1] , result = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1]] )\n | |___dfs(nums = [] , path = [3, 1, 2] , result = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2]] ) # added a new permutation to the result\n |___dfs(nums = [1] , path = [3, 2] , result = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2]] )\n |___dfs(nums = [] , path = [3, 2, 1] , result = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] ) # added a new permutation to the results\n\n\n```\n\n```\ndef permute(self, nums):\n res = []\n self.dfs(nums, [], res)\n return res\n \ndef 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``` | 19 | 1 | ['Backtracking', 'Python', 'Python3'] | 1 |
permutations | Easy to understand recursion - beats 97.38 | easy-to-understand-recursion-beats-9738-hby43 | \nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n n = len(nums)\n\t\t\n\t\t# Base conditions\n\t\t# If length is 0 or 1, th | sumeetsarkar | NORMAL | 2020-08-14T05:24:55.754861+00:00 | 2020-08-14T05:24:55.754890+00:00 | 1,846 | false | ```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n n = len(nums)\n\t\t\n\t\t# Base conditions\n\t\t# If length is 0 or 1, there is only 1 permutation\n if n in [0, 1]:\n return [nums]\n\t\t\n\t\t# If length is 2, then there are only two permutations\n\t\t# Example: [1,2] and [2,1]\n if n == 2:\n return [nums, nums[::-1]]\n\t\t\t\n res = []\n\t\t# For every number in array, choose 1 number and permute the remaining\n\t\t# by calling permute recursively\n for i in range(n):\n permutations = self.permute(nums[:i] + nums[i+1:])\n for p in permutations:\n res.append([nums[i]] + p)\n\t\t\t\t\n return res\n``` | 19 | 0 | ['Python'] | 2 |
permutations | New approach: directly find the kth permutation (k = 1...n!) with a simple loop | new-approach-directly-find-the-kth-permu-g040 | Explanation\n\nThe general idea is the following (same as other solutions):\n\n 1. We know there are n! possible permutations for n elements.\n 2. Enumerate the | twisterrob | NORMAL | 2015-11-29T11:08:15+00:00 | 2018-08-11T13:46:56.665328+00:00 | 10,461 | false | # Explanation\n\nThe general idea is the following (same as other solutions):\n\n 1. We know there are `n!` possible permutations for `n` elements.\n 2. Enumerate them one by one\n\nMost solutions use the previous permutation to generate the next permutation or build it recursively.\nI had the idea to calculate the `k`<sup>th</sup> permutation directly from the input. Steps are as follows:\n\n 1. Build a list of all elements in ascending order. \nThe length of this list is `n` (i.e. not the original input size).\n 2. Given `k` we know what the first element will be in the `k`<sup>th</sup> permutation of the current list. \nThere are `n` groups in the lexicographical order of all permutations of the list. Inside a group each permutation's first element is the same. Each group has `(n-1)!` elements, so an easy `k / (n-1)!` will give us the index.\n 3. Append the selected element to the result, i.e. the next element in the `k`<sup>th</sup> permutation.\n 4. Remove the selected element from the list. \n 5. Now the list has one less elements and we can **repeat from Step 2** with `k' = k % n!`, \nthat is the `k'`<sup>th</sup> permutation of the reduced list.\n\nNotice that it doesn't matter what the elements are because the indices are calculated.\n\n# Examples for `n = 1...4`\n\n elements k indices\n [] - - =----- trivial\n\n [1] 0 0 =----- reduces to [] after selecting 1\n\n [1,2] 0 0 0 =----- reduces to [2] after selecting 1\n [2,1] 1 1 0 =----- reduces to [1] after selecting 2\n \n [1,2,3] 0 0 0 0 =\\____ reduces to [2,3] after selecting 1\n [1,3,2] 1 0 1 0 =/\n [2,1,3] 2 1 0 0 =\\____ reduces to [1,3] after selecting 2\n [2,3,1] 3 1 1 0 =/\n [3,1,2] 4 2 0 0 =\\____ reduces to [1,2] after selecting 3\n [3,2,1] 5 2 1 0 =/\n \n [1,2,3,4] 0 0 0 0 0 =\\\n [1,2,4,3] 1 0 0 1 0 \\\n [1,3,2,4] 2 0 1 0 0 \\__ reduces to [2,3,4] after selecting 1\n [1,3,4,2] 3 0 1 1 0 /\n [1,4,2,3] 4 0 2 0 0 /\n [1,4,3,2] 5 0 2 1 0 =/\n [2,1,3,4] 6 1 0 0 0 =\\\n [2,1,4,3] 7 1 0 1 0 \\\n [2,3,1,4] 8 1 1 0 0 \\__ reduces to [1,3,4] after selecting 2\n [2,3,4,1] 9 1 1 1 0 /\n [2,4,1,3] 10 1 2 0 0 /\n [2,4,3,1] 11 1 1 1 0 =/\n [3,1,2,4] 12 2 0 0 0 =\\\n [3,1,4,2] 13 2 0 1 0 \\\n [3,2,1,4] 14 2 1 0 0 \\__ reduces to [1,2,4] after selecting 3\n [3,2,4,1] 15 2 1 1 0 /\n [3,4,1,2] 16 2 2 0 0 /\n [3,4,2,1] 17 2 2 1 0 =/\n [4,1,2,3] 18 3 0 0 0 =\\\n [4,1,3,2] 19 3 0 1 0 \\\n [4,2,1,3] 20 3 1 0 0 \\__ reduces to [1,2,3] after selecting 4\n [4,2,3,1] 21 3 1 1 0 /\n [4,3,1,2] 22 3 2 0 0 /\n [4,3,2,1] 23 3 2 1 0 =/\n\n# Code\n\n**The fact of `FACT`**: since the problem asks for **all** permutations we can be sure it won't ask for more than `12` elements, because `13!` is out of range for `int` and all lists are indexed by `int`s. Also `12!` permutations of `12` elements in `List<List>` is good `7GiB` worth of memory.\n\n public class Solution {\n private static final int[] FACT = { // 479001600 < 2147483647 < 6227020800\n 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600\n };\n public List<List<Integer>> permute(int[] nums) {\n Arrays.sort(nums);\n List<List<Integer>> result = new ArrayList<>(nums.length);\n for (int k = 0; k < FACT[nums.length]; ++k) {\n result.add(permutation(nums, k));\n }\n return result;\n }\n List<Integer> permutation(int[] nums, int k) {\n // k %= FACT[nums.length]; // in case you want to use it elsewhere\n List<Integer> source = toList(nums);\n List<Integer> result = new ArrayList(nums.length);\n while (!source.isEmpty()) {\n int f = FACT[source.size() - 1];\n result.add(source.remove(k / f));\n k %= f;\n }\n return result;\n }\n List<Integer> toList(int[] nums) {\n List<Integer> result = new LinkedList<>();\n for (int num : nums) {\n result.add(num);\n }\n return result;\n }\n }\n\n# Analysis\n\nIt's clear that we need to iterate `n!` times, because we're generating `n!` elements.\nThe `permutation` method looks like `O(n)`, but sadly it's `O(n^2)` because `remove` takes `O(n)`:\n\n * `LinkedList` \n`i` steps to find the `i`<sup>th</sup> element and `O(1)` to remove it\n * `ArrayList` \n`O(1)` to find the `i`<sup>th</sup> element and `n-i` steps to remove the `i`<sup>th</sup> element\n * keep `int[] nums` and `boolean[] removed` \nwe have to iterate over each removed item, so `O(n)`\n * `Map<Integer, Integer>` \nmay be better, but we have to re-index all remaining elements\n * **Is there a better data structure for this?**\n\n# Code variations\n\nIn case you don't like the hardcoded `FACT`:\n\n /* 12! = 479001600 < Integer.MAX_VALUE = 2147483647 < 13! = 6227020800 */\n private static final int[] FACT = factorials(12);\n static int[] factorials(int n) {\n int[] f = new int[n+1];\n f[0] = f[1] = 1;\n for (int i = 2; i <= n; ++i) {\n f[i] = f[i-1] * i;\n }\n return f;\n }\n\nor it's even possible to calculate `n!` only once and keep reducing it, but then we have to pass an extra unrelated argument.\n\n public List<List<Integer>> permute(int[] nums) {\n Arrays.sort(nums);\n List<List<Integer>> result = new ArrayList<>(nums.length);\n int fact = factorial(nums.length);\n for (int k = 0; k < fact; ++k) {\n result.add(permutation(nums, fact, k));\n }\n return result;\n }\n List<Integer> permutation(int[] nums, int f, int k) {\n if (nums.length == 0) return Collections.emptyList();\n List<Integer> source = toList(nums);\n List<Integer> result = new ArrayList(nums.length);\n do {\n k %= f;\n f /= source.size();\n result.add(source.remove(k / f));\n } while (!source.isEmpty());\n return result;\n }\n static int factorial(int n) {\n if (n <= 1) return 1;\n int result = n;\n while (--n > 1) {\n result *= n;\n }\n return result;\n } | 19 | 1 | ['Iterator', 'Java'] | 5 |
permutations | Easy Explanation || Short Code || Backtracking | easy-explanation-short-code-backtracking-64rh | Intuition\n Describe your first thoughts on how to solve this problem. \nThe code aims to generate all possible permutations of a given set of numbers.\n\n# App | HoneyJammer | NORMAL | 2023-08-02T03:12:00.061939+00:00 | 2023-08-02T05:18:30.921702+00:00 | 2,457 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code aims to generate all possible permutations of a given set of numbers.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code uses a recursive backtracking approach to generate all the permutations. It starts by fixing the first element of the permutation and then recursively generates the permutations for the remaining elements by swapping the first element with each of the subsequent elements. This process continues until all elements have been considered as the first element.\n\n> Inside the \'solve\' function:\n- It checks if \'ind\' is equal to the size of \'nums\'. If it is, that means we have formed one permutation, so it adds \'nums\' to the \'res\' vector and returns from the function.\n- Otherwise, it enters a loop starting from the current \'ind\' up to the end of the \'nums\' vector\n- Inside the loop, it swaps the elements at \'ind\' and \'i\' indices to try different possibilities for the first element.\n- After swapping, it makes a recursive call to \'solve\' with \'ind+1\' (moving to the next index) to generate permutations for the remaining elements.\n\n`Let\'s analyze the time complexity of the code. For each element at index \'ind\', there are \'n - ind\' choices to be made for swapping (where \'n\' is the total number of elements). Then, for each choice, we make a recursive call to generate permutations for the remaining elements. Therefore, the time complexity of this algorithm can be expressed as O(n * n!), where \'n\' is the number of elements in the input vector \'nums\'.`\n\n\n\n# Complexity\n- Time complexity:O(n*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```\nclass Solution {\n private:\n void solve(int ind ,vector<int>&nums,vector<vector<int>>&res){\n if(ind == nums.size()){\n res.push_back(nums);\n return;\n }\n for(int i=ind ; i<nums.size() ; i++){\n swap(nums[ind],nums[i]);\n solve(ind+1,nums,res);\n swap(nums[i],nums[ind]);\n }\n }\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> res;\n solve(0,nums,res);\n return res;\n\n }\n};\n``` | 18 | 3 | ['Backtracking', 'Recursion', 'C++'] | 2 |
permutations | 🔥✅✅ Beat 98.64% | ✅ Full explanation with pictures ✅✅🔥 | beat-9864-full-explanation-with-pictures-axu0 | \n\n\n\n\n\n\n\n\n\n\n\n\npython []\nclass Solution(object):\n def permute(self, nums):\n def backtrack(start):\n if start == len(nums):\n | DevOgabek | NORMAL | 2024-03-10T09:12:44.907208+00:00 | 2024-03-10T09:14:26.576476+00:00 | 4,372 | false | \n\n[](https://leetcode.com/problems/permutations/submissions/1199428886?envType=study-plan-v2&envId=top-100-liked)\n\n\n\n\n\n\n\n\n\n\n```python []\nclass Solution(object):\n def permute(self, nums):\n def backtrack(start):\n if start == len(nums):\n permutations.append(nums[:])\n else:\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 permutations = []\n backtrack(0)\n return permutations\n```\n```python3 []\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n def backtrack(start):\n if start == len(nums):\n permutations.append(nums[:])\n else:\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 permutations = []\n backtrack(0)\n return permutations\n```\n```C++ []\nclass Solution {\npublic:\n void backtrack(vector<int>& nums, vector<vector<int>>& permutations, int start) {\n if (start == nums.size()) {\n permutations.push_back(nums);\n } else {\n for (int i = start; i < nums.size(); ++i) {\n swap(nums[start], nums[i]);\n backtrack(nums, permutations, start + 1);\n swap(nums[start], nums[i]);\n }\n }\n }\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> permutations;\n backtrack(nums, permutations, 0);\n return permutations;\n }\n};\n```\n```javascript []\nvar permute = function(nums) {\n const permutations = [];\n \n function backtrack(start) {\n if (start === nums.length) {\n permutations.push([...nums]);\n } else {\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 \n backtrack(0);\n return permutations;\n};\n```\n\n\n\n## **My solutions**\n\n\uD83D\uDFE2 - $$easy$$ \n\uD83D\uDFE1 - $$medium$$ \n\uD83D\uDD34 - $$hard$$\n\n\uD83D\uDFE1 [46. Permutations](https://leetcode.com/problems/permutations/solutions/4853218/beat-98-64-full-explanation-with-pictures)\n\uD83D\uDFE1 [17. Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/solutions/4845532/there-is-an-80-chance-of-being-in-the-interview-full-problem-explanation)\n\uD83D\uDFE1 [22. Generate Parentheses](https://leetcode.com/problems/generate-parentheses/solutions/4845742/simple-explanation-with-pictures)\n\uD83D\uDFE1 [39. Combination Sum](https://leetcode.com/problems/combination-sum/solutions/4847482/beat-8292-full-explanation-with-pictures)\n\uD83D\uDFE2 [2540. Minimum Common Value](https://leetcode.com/problems/minimum-common-value/solutions/4845076/beat-9759-full-explanation-with-pictures)\n\uD83D\uDFE2 [3005. Count Elements With Maximum Frequency](https://leetcode.com/problems/count-elements-with-maximum-frequency/solutions/4839796/beat-8369-full-explanation-with-pictures)\n\uD83D\uDFE2 [3028. Ant on the Boundary](https://leetcode.com/problems/ant-on-the-boundary/solutions/4837433/full-explanation-with-pictures)\n\uD83D\uDFE2 [876. Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/solutions/4834682/beat-10000-full-explanation-with-pictures)\n\uD83D\uDFE1 [1750. Minimum Length of String After Deleting Similar Ends](https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/solutions/4824224/beat-10000-full-explanation-with-pictures)\n\uD83D\uDFE1 [948. Bag of Tokens](https://leetcode.com/problems/bag-of-tokens/solutions/4818912/beat-10000-full-explanation-with-pictures)\n\uD83D\uDFE1 [19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solutions/4813340/beat-10000-full-explanation-with-pictures)\n\uD83D\uDFE2 [977. Squares of a Sorted Array](https://leetcode.com/problems/squares-of-a-sorted-array/solutions/4807704/square-sorter-python-python3-javascript-c)\n\uD83D\uDFE2 [2864. Maximum Odd Binary Number](https://leetcode.com/problems/maximum-odd-binary-number/solutions/4802402/visual-max-odd-binary-solver-python-python3-javascript-c)\n\uD83D\uDFE1 [1609. Even Odd Tree](https://leetcode.com/problems/even-odd-tree/solutions/4797529/even-odd-tree-validator-python-python3-javascript-c)\n\uD83D\uDFE2 [9. Palindrome Number](https://leetcode.com/problems/palindrome-number/solutions/4795373/why-not-1-line-of-code-python-python3-c-everyone-can-understand)\n\uD83D\uDFE1 [513. Find Bottom Left Tree Value](https://leetcode.com/problems/find-bottom-left-tree-value/solutions/4792022/binary-tree-explorer-mastered-javascript-python-python3-c-10000-efficiency-seeker)\n\uD83D\uDFE2 [1. Two Sum](https://leetcode.com/problems/two-sum/solutions/4791305/5-methods-python-c-python3-from-easy-to-difficult)\n\uD83D\uDFE2 [543. Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/solutions/4787634/surpassing-9793-memory-magician-excelling-at-9723)\n\uD83D\uDFE2 [101. Symmetric Tree](https://leetcode.com/problems/symmetric-tree/solutions/4848126/beat-100-full-explanation-with-pictures)\n\n[More...](https://leetcode.com/DevOgabek/) | 17 | 0 | ['Array', 'Backtracking', 'Python', 'C++', 'Python3', 'JavaScript'] | 3 |
permutations | ✅Simple C++ |Using Backtracking and STL ✅ | simple-c-using-backtracking-and-stl-by-x-ee4d | Intuition\n Describe your first thoughts on how to solve this problem. \nSimply do swaping recusrively for every index and bactrack.\n# Approach\n Describe your | Xahoor72 | NORMAL | 2023-01-23T12:11:11.478698+00:00 | 2023-01-30T17:39:37.491880+00:00 | 3,069 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimply do swaping recusrively for every index and bactrack.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTwo approaches \n- Using Backtracking\n- Using STL function\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**Using Backtracking**\n```\nclass Solution {\npublic:\nvector<vector<int>>ans;\n void permutation(vector<int>&arr,int start){\n if(start==arr.size())\n ans.push_back(arr);\n\n for(int i=start;i<arr.size();i++){\n swap(arr[i],arr[start]);\n permutation(arr,start+1);\n swap(arr[i],arr[start]);\n }\n }\n vector<vector<int>> permute(vector<int>& arr) {\n \n vector<int>temp;\n permutation(arr,0);\n return ans;\n }\n};\n```\n**USING STL Function**\n```\nclass Solution {\npublic:\nvector<vector<int>> permute(vector<int>& arr) {\n vector<vector<int>>ans;\n sort(arr.begin(),arr.end());\n do{\n ans.push_back(arr);\n }while(next_permutation(arr.begin(),arr.end()));\n return ans;\n }\n};\n```\n# UpVote If HELPFULL \uD83D\uDD3C\uD83D\uDD3C | 16 | 0 | ['Math', 'Backtracking', 'C++'] | 0 |
permutations | ✅ [Solution] Swift: Permutations | solution-swift-permutations-by-asahiocea-4cyd | swift\nclass Solution {\n func permute(_ nums: [Int]) -> [[Int]] {\n let len = nums.count\n guard len >= 1 && len <= 6 else { return [] }\n | AsahiOcean | NORMAL | 2022-01-18T19:08:04.007334+00:00 | 2022-01-18T19:08:04.007367+00:00 | 1,910 | false | ```swift\nclass Solution {\n func permute(_ nums: [Int]) -> [[Int]] {\n let len = nums.count\n guard len >= 1 && len <= 6 else { return [] }\n \n var permutes = [[Int]](repeating: [], count: 1)\n \n for n in nums where n >= -10 && n <= 10 {\n var values: [[Int]] = []\n for var arr in permutes {\n for i in 0..<arr.count {\n var temp = arr\n temp.insert(n, at: i)\n values.append(temp)\n }\n arr.append(n)\n values.append(arr)\n }\n permutes = values\n }\n \n return permutes\n }\n}\n``` | 16 | 0 | ['Swift'] | 0 |
permutations | Golang - Beats 100% - Recursion & Explanation | golang-beats-100-recursion-explanation-b-tvmb | \n// To solve this problem we can use recursion.\n// If we think about it, a combination is valid when it has the same length of the input.\n// So, all we need | pug_jotaro_is_not_real | NORMAL | 2020-06-16T10:21:15.805184+00:00 | 2020-06-16T10:23:52.058011+00:00 | 2,231 | false | ```\n// To solve this problem we can use recursion.\n// If we think about it, a combination is valid when it has the same length of the input.\n// So, all we need to do is, have a concept of current combination (left) and left items (right)\n// that we need to analyse every time. We start with empty current combination and left will be equal to the input.\n//\n// E.G. current: []; left: [1, 2, 3]\n// Then we would have current: [1]; left: [2, 3], current: [2]; left: [1, 3], current: [3]; left: [1, 2]\n// \n// The recursion tree looks like:\n//\n// - ([],[1, 2, 3])\n// - ([1],[2,3]); ([2],[1, 3]); ([3],[2, 1])\n// - ([1,2],[3]); ([1,3],[2]); ([2,1],[3]); ([2,3],[1]); ([3,2],[1]); ([3,1],[2])\n// - ([1,2,3]); ([1,3,2]); ([2,1,3]); ([2,3,1]); ([3,2,1]); ([3,1,2])\n//\n// T: O(n!)\n// S: O(n!)\nfunc permute(nums []int) [][]int {\n\tvar res [][]int\n\tpermuteRec([]int{}, nums, &res)\n\treturn res\n}\n\n// We use a pointer for the result so we don\'t need to worry returning it.\nfunc permuteRec(currComb, left []int, res *[][]int) {\n\t// We know that we found a new combination when we have no elements left.\n\tif 0 == len(left) {\n\t\t*res = append(*res, currComb)\n\t\treturn\n\t}\n\t// For the next iteration we consider all the left elements but the current one (idx).\n\tfor idx, l := range left {\n\t\tpermuteRec(\n\t\t\tappend(currComb, l),\n\t\t\tappend(append([]int{}, left[:idx]...), left[idx+1:]...), // Make sure to allocate a new slice.\n\t\t\tres,\n\t\t)\n\t}\n}\n``` | 16 | 2 | ['Recursion', 'Go'] | 0 |
permutations | C# solution | c-solution-by-newbiecoder1-m360 | \n\nSolution 1\n\npublic class Solution {\n public IList<IList<int>> Permute(int[] nums) {\n \n List<IList<int>> res = new List<IList<int>>();\ | newbiecoder1 | NORMAL | 2020-04-19T05:51:42.315125+00:00 | 2020-04-19T06:18:45.324262+00:00 | 961 | false | \n\n**Solution 1**\n```\npublic class Solution {\n public IList<IList<int>> Permute(int[] nums) {\n \n List<IList<int>> res = new List<IList<int>>();\n Backtracking(nums, new List<int>(), res);\n return res;\n }\n \n private void Backtracking(int[] nums, List<int> list, List<IList<int>> res)\n {\n if(list.Count == nums.Length)\n {\n res.Add(new List<int>(list));\n return;\n }\n else\n {\n for(int i = 0; i < nums.Length; i++)\n {\n if(list.Contains(nums[i]))\n continue;\n list.Add(nums[i]);\n Backtracking(nums, list, res);\n list.RemoveAt(list.Count -1);\n }\n }\n }\n}\n```\n\n**Solution 2**\n```\npublic class Solution {\n public IList<IList<int>> Permute(int[] nums) {\n \n List<IList<int>> res = new List<IList<int>>();\n Array.Sort(nums);\n bool[] used = new bool[nums.Length];\n Backtracking(nums, new List<int>(), res, used);\n return res;\n }\n \n private void Backtracking(int[] nums, List<int> list, List<IList<int>> res, bool[] used)\n {\n if(list.Count == nums.Length)\n {\n res.Add(new List<int>(list));\n return;\n }\n else\n {\n for(int i = 0; i < nums.Length; i++)\n {\n if(used[i]) continue;\n \n list.Add(nums[i]);\n used[i] = true;\n Backtracking(nums, list, res, used);\n list.RemoveAt(list.Count - 1);\n used[i] = false;\n }\n }\n }\n}\n``` | 16 | 1 | [] | 1 |
permutations | ✅ Complex Backtracking Interview Prepare | List of Common Backtracking Problems | Beats 100% ✅ | complex-backtracking-interview-prepare-l-0pts | \n# Most common Backtracking Problems\nFrom the most to the least common (from GitHub/reddit):\n\n [17. Letter Combinations of a Phone Number] [51. N-Queens] \x | Piotr_Maminski | NORMAL | 2024-10-28T00:08:01.995182+00:00 | 2024-11-02T19:06:47.910249+00:00 | 1,863 | false | \n# Most common Backtracking Problems\nFrom the most to the least common (from GitHub/reddit):\n\n [[17. Letter Combinations of a Phone Number]](https://leetcode.com/problems/letter-combinations-of-a-phone-number/solutions/5976064/complex-backtracking-interview-prepare-list-of-backtracking-questions-beats-100) [[51. N-Queens]](https://leetcode.com/discuss/topic/5988136/beats-100-list-of-common-backtracking-problems/) \xA0[[47. Permutations II ]](https://leetcode.com/problems/permutations-ii/description/) [[40. Combination Sum II]](https://leetcode.com/problems/combination-sum-ii/description/) [[46. Permutations]](https://leetcode.com/problems/permutations/solutions/5976304/complex-backtracking-interview-prepare-list-of-backtracking-questions-beats-100) [[22. Generate Parentheses]](https://leetcode.com/problems/generate-parentheses/solutions/5976224/complex-backtracking-interview-prepare-list-of-backtracking-questions-beats-100) [[78. Subsets]](https://leetcode.com/problems/subsets/description/) \xA0[[39. Combination Sum]](https://leetcode.com/problems/combination-sum/solutions/5976264/complex-backtracking-interview-prepare-list-of-backtracking-questions-beats-100)\n\nIf you\'ve encountered any of these issues or have other questions that aren\'t on this list, please leave a comment so I can update list.\n\n# Code\n```python3 []\nclass Solution:\n def solve(self, nums: list[int], l: int, r: int, result: list[list[int]]) -> None:\n # Base case: when left index equals right index\n if l == r:\n result.append(nums[:]) # Add copy of current permutation\n return\n \n # Try all possible elements at position \'l\'\n for i in range(l, r + 1):\n # 1. Swap current element with element at position \'l\'\n nums[l], nums[i] = nums[i], nums[l]\n \n # 2. Recursively generate permutations for remaining elements\n self.solve(nums, l + 1, r, result)\n \n # 3. Backtrack: restore array to original state by swapping back\n nums[l], nums[i] = nums[i], nums[l]\n \n def permute(self, nums: list[int]) -> list[list[int]]:\n result = [] # Stores all permutations\n self.solve(nums, 0, len(nums) - 1, result) # Start with full array range\n return result\n```\n```cpp []\nclass Solution {\npublic:\n // Helper function that generates all permutations using backtracking\n // nums: input array to permute\n // l: left index of current subarray being processed\n // r: right index of current subarray being processed\n // result: stores all generated permutations\n void solve(vector<int>& nums, int l, int r, vector<vector<int>>& result) {\n // Base case: when left index equals right index\n // meaning we\'ve processed all positions in current permutation\n if (l == r) {\n result.push_back(nums); // Add current permutation to result\n return;\n }\n \n // Try all possible elements at position \'l\'\n for (int i = l; i <= r; i++) {\n // 1. Swap current element with element at position \'l\'\n swap(nums[l], nums[i]);\n \n // 2. Recursively generate permutations for remaining elements\n solve(nums, l + 1, r, result);\n \n // 3. Backtrack: restore array to original state by swapping back\n swap(nums[l], nums[i]);\n }\n }\n\n // Main function that initializes the permutation generation\n // nums: input array to find permutations for\n // returns: vector containing all possible permutations\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> result; // Stores all permutations\n solve(nums, 0, nums.size() - 1, result); // Start with full array range\n return result;\n }\n};\n```\n```java []\nclass Solution {\n // Main method that initializes the permutation process\n // nums: input array to be permuted\n // returns: list containing all possible permutations\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> res = new ArrayList<>(); // Store all permutations\n backtrack(nums, 0, res); // Start backtracking from index 0\n return res; \n }\n\n // Recursive backtracking method to generate permutations\n // nums: array being permuted\n // start: current position we\'re filling\n // res: result list storing all permutations\n private void backtrack(int[] nums, int start, List<List<Integer>> res) {\n // Base case: when we\'ve filled all positions (reached end of array)\n if (start == nums.length) {\n res.add(arrayToList(nums)); // Add current permutation to result\n return;\n }\n\n // Try each number as the next element in the permutation\n for (int i = start; i < nums.length; i++) {\n swap(nums, start, i); // Place current number at start position\n backtrack(nums, start + 1, res); // Recursively generate permutations for rest\n swap(nums, start, i); // Backtrack: restore array to original state\n }\n }\n \n // Helper method to convert int array to List<Integer>\n // arr: input array to convert\n // returns: ArrayList containing array elements\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 // Helper method to swap two elements in array\n // nums: array containing elements\n // i, j: indices of elements to swap\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```csharp []\npublic class Solution {\n // Helper function that generates all permutations using backtracking\n private void Solve(int[] nums, int l, int r, IList<IList<int>> result) {\n // Base case: when left index equals right index\n if (l == r) {\n result.Add(new List<int>(nums)); // Add current permutation to result\n return;\n }\n \n // Try all possible elements at position \'l\'\n for (int i = l; i <= r; i++) {\n // 1. Swap current element with element at position \'l\'\n Swap(nums, l, i);\n \n // 2. Recursively generate permutations for remaining elements\n Solve(nums, l + 1, r, result);\n \n // 3. Backtrack: restore array to original state by swapping back\n Swap(nums, l, i);\n }\n }\n\n // Helper method to swap elements in array\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 // Main function that initializes the permutation generation\n public IList<IList<int>> Permute(int[] nums) {\n IList<IList<int>> result = new List<IList<int>>(); // Stores all permutations\n Solve(nums, 0, nums.Length - 1, result); // Start with full array range\n return result;\n }\n}\n```\n```golang []\n// permute generates all possible permutations of the input slice nums\nfunc permute(nums []int) [][]int {\n // res stores all the permutations we\'ll generate\n var res [][]int\n \n // permutation will store the current permutation we\'re building\n // initialized with same length as input slice\n permutation := make([]int, len(nums))\n \n // visit keeps track of which numbers we\'ve used in current permutation\n // using a boolean array where true means the number at that index is used\n visit := make([]bool, len(nums))\n \n // backtrack is our recursive helper function\n // index represents the current position we\'re filling in permutation\n var backtrack func(int)\n backtrack = func(index int) {\n // Base case: if we\'ve filled all positions (index == len(nums))\n // we\'ve completed one permutation\n if index == len(nums) {\n // Create a deep copy of current permutation\n // We need to copy because permutation slice will be modified\n copiedPermutation := make([]int, len(nums))\n copy(copiedPermutation, permutation)\n \n // Add the completed permutation to our results\n res = append(res, copiedPermutation)\n \n return\n } \n \n // Try placing each number at the current index\n for i := 0; i < len(nums); i++ {\n // If this number hasn\'t been used in current permutation\n if visit[i] == false {\n // Mark this number as used\n visit[i] = true\n // Place this number at current index\n permutation[index] = nums[i]\n // Recursively fill the next position\n backtrack(index+1) \n // Backtrack: mark number as unused for next iteration\n visit[i] = false\n }\n }\n }\n \n // Start the backtracking process from index 0\n backtrack(0)\n \n return res\n}\n```\n```swift []\nclass Solution {\n // Helper function that generates all permutations using backtracking\n private func solve(_ nums: inout [Int], _ l: Int, _ r: Int, _ result: inout [[Int]]) {\n // Base case: when left index equals right index\n if l == r {\n result.append(nums)\n return\n }\n \n // Try all possible elements at position \'l\'\n for i in l...r {\n // 1. Swap current element with element at position \'l\'\n nums.swapAt(l, i)\n \n // 2. Recursively generate permutations for remaining elements\n solve(&nums, l + 1, r, &result)\n \n // 3. Backtrack: restore array to original state by swapping back\n nums.swapAt(l, i)\n }\n }\n \n // Main function that initializes the permutation generation\n func permute(_ nums: [Int]) -> [[Int]] {\n var result: [[Int]] = [] // Stores all permutations\n var numsCopy = nums // Create mutable copy of input array\n solve(&numsCopy, 0, nums.count - 1, &result)\n return result\n }\n}\n```\n```javascript [JS]\n// JavaScript\n\n\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nvar permute = function(nums) {\n const result = [];\n \n // Helper function to swap elements in array\n function swap(arr, i, j) {\n const temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n \n // Backtracking function to generate permutations\n function solve(nums, l, r) {\n if (l === r) {\n result.push([...nums]); // Create a copy of current permutation\n return;\n }\n \n for (let i = l; i <= r; i++) {\n swap(nums, l, i);\n solve(nums, l + 1, r);\n swap(nums, l, i);\n }\n }\n \n solve(nums, 0, nums.length - 1);\n return result;\n};\n```\n```typescript [TS]\n// TypeScript\n\n\n\n// This function generates all possible permutations of an array of numbers\nfunction permute(nums: number[]): number[][] {\n // Store all permutations we find\n const permuations: number[][] = [];\n \n // Temporary array to build each permutation\n const chunks: number[] = [];\n\n // Backtracking function that uses bit manipulation to track used numbers\n // flags: binary number where each bit represents if a number is used (1) or not (0)\n function backtrack(flags: number) {\n // Base case: if our current permutation is same length as input array\n // we\'ve found a valid permutation\n if (chunks.length === nums.length) {\n // Add a copy of current permutation to results\n permuations.push([...chunks]);\n return;\n }\n\n // Try each number in the input array\n for (let i = 0; i < nums.length; i++) {\n // Check if number at index i is already used using bit manipulation\n // (flags >> i) shifts bits right by i positions\n // & 1 checks if rightmost bit is 1 (used) or 0 (unused)\n if ((flags >> i) & 1) continue;\n\n // Add current number to our permutation\n chunks.push(nums[i]);\n\n // Recursive call with updated flags\n // flags | (1 << i) sets the bit at position i to 1\n // marking this number as used\n backtrack(flags | (1 << i));\n\n // Backtrack by removing the number we just tried\n chunks.pop();\n }\n }\n\n // Start backtracking with no numbers used (flags = 0)\n backtrack(0);\n \n // Return all found permutations\n return permuations;\n}\n```\n```rust []\nimpl Solution {\n // Helper function for generating permutations\n fn solve(nums: &mut Vec<i32>, l: usize, r: usize, result: &mut Vec<Vec<i32>>) {\n if l == r {\n result.push(nums.clone());\n return;\n }\n \n for i in l..=r {\n // Swap elements\n nums.swap(l, i);\n \n // Recursive call\n Self::solve(nums, l + 1, r, result);\n \n // Backtrack by swapping back\n nums.swap(l, i);\n }\n }\n\n pub fn permute(mut nums: Vec<i32>) -> Vec<Vec<i32>> {\n let mut result = Vec::new();\n let len = nums.len();\n if len > 0 {\n Self::solve(&mut nums, 0, len - 1, &mut result);\n }\n result\n }\n}\n```\n```ruby []\n# @param {Integer[]} nums\n# @return {Integer[][]}\ndef permute(nums)\n @result = []\n solve(nums, 0, nums.length - 1)\n @result\nend\n\ndef solve(nums, l, r)\n if l == r\n @result.push(nums.clone)\n return\n end\n \n (l..r).each do |i|\n # Swap\n nums[l], nums[i] = nums[i], nums[l]\n \n # Recursive call\n solve(nums, l + 1, r)\n \n # Backtrack\n nums[l], nums[i] = nums[i], nums[l]\n end\nend\n```\n\n### Complexity \n- Time complexity: O(n!) \n\n- Space complexity: O(n!)\n\n\n\n\n# Backtracking template\n\n#### I\n```python3 []\nans = []\ndef dfs(start_index, path, [...additional states]):\n if is_leaf(start_index):\n ans.append(path[:]) # add a copy of the path to the result\n return\n for edge in get_edges(start_index, [...additional states]):\n # prune if needed\n if not is_valid(edge):\n continue\n path.add(edge)\n if additional states:\n update(...additional states)\n dfs(start_index + len(edge), path, [...additional states])\n # revert(...additional states) if necessary e.g. permutations\n path.pop()\n\n```\n```cpp []\nvoid dfs(int startIndex, std::vector<T> path, std::vector<std::vector<T>>& res, [...additional states]) {\n if (isLeaf(path)) {\n // add a copy of the path to the result\n res.emplace_back(std::vector<T>(path));\n return;\n }\n for (auto edge : getEdges(startIndex, [...additional states])) {\n path.emplace_back(choice);\n if (...additional states) update(...additional states)\n dfs(startIndex + edge.length(), path, res, [...addtional states]);\n path.pop();\n // revert(...additional states) if necessary, e.g. permutations\n }\n}\n\n```\n```java []\nprivate static void dfs(int startIndex, List<T> path, List<List<T>> res, [...additional states]) {\n if (isLeaf(startIndex)) {\n res.add(new ArrayList<>(path)); // add a copy of the path to the result\n return;\n }\n for (T edge : getEdges(startIndex, [...additional states])) {\n path.add(choice);\n if (...additional states) update(...additional states)\n dfs(startIndex + edge.length(), res, [...additional states]);\n path.remove(path.size() - 1);\n // revert(...additional states) if necessary e.g. permutations\n }\n}\n\n```\n```csharp []\npublic static void Dfs(int startIndex, List<T> path, List<List<T>> res, [...additional states])\n{\n if (isLeaf(path))\n {\n // add a copy of the path to the result\n res.Add(new List<T>(path));\n return;\n }\n foreach (T edge in getEdges(startIndex, [...additional states]))\n {\n path.Add(choice);\n if (...additional states) update(...additional states)\n Dfs(startIndex + edge.length(), path, res, [...addtional states]);\n path.RemoveAt(path.Count - 1);\n // revert(...additional states) if necessary, e.g. permutations\n }\n}\n\n```\n```javascript []\nfunction dfs(startIndex, path, res, [...additional states]) {\n if (isLeaf(path)) {\n res.push(new Array(path));\n return;\n }\n for (const edge of getEdges(startIndex, [...additional states])) {\n path.push(choice);\n if (...additional states) update(...additional states)\n dfs(startIndex + edge.length, path, res, [...addtional states]);\n path.pop();\n // revert(...additional states) if necessary, e.g. permutations\n }\n}\n\n```\n#### II\n```python3 []\nfunction dfs(start_index, [...additional states]):\n if is_leaf(start_index):\n return 1\n ans = initial_value\n for edge in get_edges(start_index, [...additional states]):\n if additional states: \n update([...additional states])\n ans = aggregate(ans, dfs(start_index + len(edge), [...additional states]))\n if additional states: \n revert([...additional states])\n return ans\n\n```\n```cpp []\nint dfs(int startIndex, std::vector<T>& target) {\n if (isValid(target[startIndex:])) {\n return 1;\n }\n for (auto edge : getEdges(startIndex, [...additional states])) {\n if (additional states) {\n update([...additional states]);\n }\n ans = aggregate(ans, dfs(startIndex + edge.length(), [...additional states])\n if (additional states) {\n revert([...additional states]);\n }\n }\n return ans;\n}\n\n```\n```java []\nprivate static int dfs(Integer startIndex, List<T> target) {\n if (isLeaf(startIndex)) {\n return 1;\n }\n\n ans = initialValue;\n for (T edge : getEdges(startIndex, [...additional states])) {\n if (additional states) {\n update([...additional states]);\n }\n ans = aggregate(ans, dfs(startIndex + edge.length(), [...additional states])\n if (additional states) {\n revert([...additional states]);\n }\n }\n return ans;\n}\n\n```\n```csharp []\npublic static int Dfs(int startIndex, List<T> target)\n{\n if (IsLeaf(startIndex))\n {\n return 1;\n }\n int ans = initialValue;\n foreach (T edge : getEdges(startIndex, [...additional states]))\n {\n if (additional states) {\n update([...additional states]);\n }\n ans = aggregate(ans, dfs(startIndex + edge.length(), [...additional states])\n if (additional states) {\n revert([...additional states]);\n }\n }\n return ans;\n}\n\n```\n```javascript []\nfunction dfs(startIndex, target) {\n if (isLeaf(startIndex)) {\n return 1\n }\n int ans = initialValue;\n for (const edge of getEdges(startIndex, [...additional states])) {\n if (additional states) {\n update([...additional states]);\n }\n ans = aggregate(ans, dfs(startIndex + edge.length(), [...additional states])\n if (additional states) {\n revert([...additional states]);\n }\n }\n return ans;\n}\n\n```\n\n\n\n\n# Interview Priorities\n\n| Patterns | Difficulty | Interview Frequently |\n|----------------------|---------------------|----------------------|\n| **Two Pointers** | **Easy** | **High** |\n| **Sliding Window** | **Easy** | **High** |\n| **Breadth-First Search** | **Easy** | **High** |\n| **Depth-First Search** | **Medium** | **High** |\n| **[Backtracking](https://leetcode.com/problems/letter-combinations-of-a-phone-number/solutions/5976064/complex-backtracking-interview-prepare-list-of-backtracking-questions-beats-100)** | **High** | **High** |\n| Heap | Medium | Medium |\n| Binary Search | Easy | Medium |\n| [Dynamic Programming](https://leetcode.com/problem-list/atwflvk7/) | High | Medium |\n| Divide and Conquer | Medium | Low |\n| Trie | Medium | Low |\n| Union Find | Medium | Low |\n| Greedy | High | Low |\n\n\n\n\n | 15 | 1 | ['Swift', 'C++', 'Java', 'Go', 'TypeScript', 'Python3', 'Rust', 'Ruby', 'JavaScript', 'C#'] | 0 |
permutations | clean short approach in python with intution explained | clean-short-approach-in-python-with-intu-e3uo | In recursion you want to think of an obvious solution, a solution which you\'re sure of, which is obvious. For ex: what will be the list of permutations of [1]? | bl4ckp4nther | NORMAL | 2021-01-26T15:29:06.540974+00:00 | 2021-01-26T17:06:40.867535+00:00 | 1,084 | false | In recursion you want to think of an obvious solution, a solution which you\'re sure of, which is obvious. For ex: what will be the list of permutations of [1]? obviously it\'ll be [1] only. This makes our base case.\n\nNext you need to think about how a normal typical person would go about solving it. Taking another example:\nfor [1, 2, 3] I would go about it like this:\n1) fix 1 at 1st position and get all permutation for [2, 3], which would give me [1, 2, 3], and [1, 3, 2].\n2) fix 2 at 1st position and get all permutation for [1, 3], which would give me [2, 1, 3], and [2, 3, 1].\n3) fix 3 at 1st position and get all permutation for [2, 3], which would give me [3, 2, 1], and [3, 1, 2].\n\nBelow is my code based on just the above approach\n\n\'\'\'\n\n\tclass Solution:\n\t\tdef permute(self, nums: List[int]) -> List[List[int]]:\n\t\t\tif len(nums)==1:\n\t\t\t\treturn [nums]\n\n\t\t\tans = []\n\t\t\tfor i in range(len(nums)):\n\t\t\t\tnums[0], nums[i] = nums[i], nums[0]\n\t\t\t\tsub_prob = self.permute(nums[1:])\n\t\t\t\tfor sub_ans in sub_prob:\n\t\t\t\t\tans.append([nums[0]] + sub_ans)\n\t\t\t\tnums[0], nums[i] = nums[i], nums[0]\n\n\t\t\treturn ans\n\n\'\'\'\n\nHope it helps. Thanks. | 15 | 0 | ['Array', 'Backtracking', 'Recursion', 'Python'] | 0 |
permutations | Easy and Simple C++ Approach ✅ | Beats 100%🔥🔥🔥 | easy-and-simple-c-approach-beats-100-by-iuigk | Approach\n1. Recursive Function Definition (solve):\n\n- The function solve is a private helper function that recursively generates permutations.\n- It takes th | AyushBansalCodes | NORMAL | 2024-08-08T07:04:01.228371+00:00 | 2024-08-08T07:04:01.228402+00:00 | 1,254 | false | # Approach\n1. Recursive Function Definition (`solve`):\n\n- The function `solve` is a private helper function that recursively generates permutations.\n- It takes three parameters:\n - `nums`: The current permutation of numbers being considered.\n - `index`: The current index in the array from which to start generating permutations.\n - `ans`: A reference to the vector of vectors where all generated permutations will be stored.\n\n2. Base Case:\n\n- If `index` is equal to the size of `nums`, it means a complete permutation has been generated.\n- This permutation is added to `ans`, and the function returns.\n\n3. Recursive Case:\n\n- Iterate over the elements in `nums` starting from the `index` position.\n- Swap the current element at `index` with the element at position `j` to generate a new permutation.\n- Recursively call `solve` with the next index (`index + 1`).\n- After the recursive call, backtrack by swapping the elements back to their original positions to restore the array for the next iteration.\n\n4. Public Function (`permute`):\n\n- This function is the public interface to generate permutations.\n- It initializes the `ans` vector and calls the `solve` function starting from index `0`.\n- Finally, it returns the `ans` vector containing all permutations.\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`Upvote! It only takes 1 click\uD83D\uDE09`\n# Code\n```\nclass Solution {\nprivate:\n // Recursive helper function to generate permutations\n void solve(vector<int> nums, int index, vector<vector<int>>& ans) {\n // Base case: if the current index is equal to the size of nums\n if (index == nums.size()) {\n // Add the current permutation to the answer list\n ans.push_back(nums);\n return;\n }\n\n // Iterate over the elements starting from the current index\n for (int j = index; j < nums.size(); j++) {\n // Swap the current element with the element at position j\n swap(nums[index], nums[j]);\n // Recursively generate permutations for the next index\n solve(nums, index + 1, ans);\n // Backtrack: swap the elements back to their original positions\n swap(nums[index], nums[j]);\n }\n }\n\npublic:\n // Public function to generate permutations\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> ans; // Vector to store all permutations\n int index = 0; // Start from the first index\n solve(nums, index, ans); // Call the recursive helper function\n return ans; // Return the result\n }\n};\n\n```\n`Upvote! It only takes 1 click\uD83D\uDE09`\n# Key Points to Remember:\n- **Backtracking:** The technique involves exploring all possible permutations by swapping elements and then undoing the swaps to restore the original state for the next iteration.\n- **Recursion:** The recursive nature of the `solve` function allows it to handle the permutations generation cleanly.\n- **Base Case Handling:** The base case ensures that once a complete permutation is formed, it\'s added to the results.\n\n\n | 14 | 0 | ['Backtracking', 'C++'] | 0 |
permutations | Mathematical proof that time complexity is O(e * n!) NOT O(n * n!) | mathematical-proof-that-time-complexity-0nvsn | I have seen a lot of answers here that simply state the time complexity is O(n*n!) but the justification isn\'t too well explained. Here I show a better approxi | amankhoza | NORMAL | 2022-05-26T00:43:54.564947+00:00 | 2022-05-26T00:53:18.124712+00:00 | 838 | false | I have seen a lot of answers here that simply state the time complexity is `O(n*n!)` but the justification isn\'t too well explained. Here I show a better approximation for the time complexity is actually `O(e*n!)`.\n\nFirst we must visualise the recursion tree (see other answers for recursive solution), the tree below shows the recursion for `n=4`. On the first layer of the tree we have `n` possible options to choose from, so we make `n` function calls and have `n` nodes in our tree. Now we have n partial permutations built up so far and have `n-1` numbers to choose from, so the next layer in our tree will have `n*(n-1)` nodes. The layer after this will have `n*(n-1)*(n-2)` nodes and so on and so forth. Until we have `n!` leaf nodes at the bottom of our tree. At this point it is obvious to see `O(n*n!)` is an over estimate for the time complexity of this algorithm, as it implies each layer (there are `n` in total) has `n!` nodes.\n\nWe know the time complexity of a recursive algorithm is the number of nodes in its recursion tree multiplied by the cost of computation at each node. At each node in our tree we either call the dfs function recursively (non-leaf nodes) or add to the results array, both of these operations are `O(1)`, hence the time complexity is equal to the number of nodes in the recursion tree.\n\nNow for the magic, if we sum up the nodes in each layer of the recursion tree we get to the expression:\n\n`O(n) = 1 + n + n*(n-1) + n*(n-1)*(n-2) + ... + n!`\n\nIf we reverse the order of terms in this series and factor out `n!` we get:\n\n`O(n) = n!(1/1! + 1/2! + 1/3! + ... + 1/n!)`\n\nNotice the second term is the series representation of `e`, so we have:\n\n`O(n) = e * n!`\n\n\n\nHere are some calculations for n = 1-10, of actual nodes in recursion tree (calculating the first summation expression in a while loop) vs `e*n!` vs `n*n!`:\n\n```\nn actual e*n! n*n!\n1 1 2 1\n2 4 5 4\n3 15 16 18\n4 64 65 96\n5 325 326 600\n6 1956 1957 4320\n7 13699 13700 35280\n8 109600 109601 322560\n9 986409 986410 3265920\n10 9864100 9864101 36288000\n```\n | 14 | 0 | [] | 2 |
permutations | Python BFS solution | python-bfs-solution-by-fabius11-8wkn | Python BFS solution\n\n```python\nfrom collections import deque\ndef permute(self, nums: List[int]) -> List[List[int]]: \n\tif len(nums) <= 1:\n\t\tretur | fabius11 | NORMAL | 2020-03-17T01:23:35.413589+00:00 | 2020-03-17T01:34:40.305196+00:00 | 3,076 | false | Python BFS solution\n\n```python\nfrom collections import deque\ndef permute(self, nums: List[int]) -> List[List[int]]: \n\tif len(nums) <= 1:\n\t\treturn [nums]\n\n\tans = []\n\tqueue = deque([([], nums)])\n\n\twhile queue:\n\t\tarr, options = queue.popleft()\n\n\t\tfor i in range(len(options)):\n\t\t\tnext_options = options[:i] + options[i+1:]\n\t\t\tnew_arr = arr + [options[i]]\n\n\t\t\tif next_options:\n\t\t\t\tqueue.append((new_arr, next_options))\n\t\t\telse:\n\t\t\t\tans.append(new_arr)\n\n\treturn ans | 14 | 1 | ['Breadth-First Search', 'Python', 'Python3'] | 1 |
permutations | Python iterative solution beat 99% | python-iterative-solution-beat-99-by-cha-nntl | The idea is to insert new num in the existing permutation to form new permutations.\n\nFor example, suppose we need to get all permutation of [1, 2, 3]. Assume | charleszhou327 | NORMAL | 2018-09-08T17:02:07.923443+00:00 | 2018-10-21T19:41:35.631990+00:00 | 2,194 | false | The idea is to insert new num in the existing permutation to form new permutations.\n\nFor example, suppose we need to get all permutation of `[1, 2, 3]`. Assume that we have got the permutation of `[1, 2]`, so `result = [[1, 2], [2, 1]]`. Then we could add 3 to each position of each element of result to get all permutations with number 3. The idea is kind of like BFS. \n\nAs a time optimization, we do not actually insert 3 in existing permutation because it takes O(N) for each insertation. We could simply append 3 to the end of [1, 2] and then swap each element with 3 to get new permutation. \n\n```python\nclass Solution(object):\n def permute(self, nums):\n """\n :type nums: List[int]\n :rtype: List[List[int]]\n """\n \n res = [[]]\n for num in nums:\n new_res = []\n for i in range(len(res)):\n prev = res[i]\n prev.append(num)\n for j in range(len(prev)):\n prev[j], prev[-1] = prev[-1], prev[j]\n new_res.append(prev[:])\n prev[j], prev[-1] = prev[-1], prev[j]\n res = new_res\n return res\n```\n\nThe space could be further optimized by using one array. \n\n```python\nclass Solution(object):\n def permute(self, nums):\n """\n :type nums: List[int]\n :rtype: List[List[int]]\n """\n \n res = [[]]\n for num in nums:\n size = len(res)\n for i in range(size):\n prev = res.pop(0)\n prev.append(num)\n for j in range(len(prev)):\n prev[j], prev[-1] = prev[-1], prev[j]\n res.append(prev[:])\n prev[j], prev[-1] = prev[-1], prev[j]\n return res\n```\n\nA little bit slower, since pop(0) also takes O(N), can be avoid by using `deque` though. \n\n\n | 14 | 0 | [] | 4 |
permutations | Java solution easy to understand (backtracking) | java-solution-easy-to-understand-backtra-qcum | public class Solution {\n \n List> list;\n \n public List> permute(int[] nums) {\n \n list = new ArrayList<>();\n ArrayList per | arieeel | NORMAL | 2015-08-30T04:59:27+00:00 | 2015-08-30T04:59:27+00:00 | 7,920 | false | public class Solution {\n \n List<List<Integer>> list;\n \n public List<List<Integer>> permute(int[] nums) {\n \n list = new ArrayList<>();\n ArrayList<Integer> perm = new ArrayList<Integer>();\n backTrack(perm,0,nums);\n return list;\n }\n \n void backTrack (ArrayList<Integer> perm,int i,int[] nums){\n \n //Permutation completes\n if(i==nums.length){\n list.add(new ArrayList(perm));\n return;\n }\n \n ArrayList<Integer> newPerm = new ArrayList<Integer>(perm);\n \n //Insert elements in the array by increasing index\n for(int j=0;j<=i;j++){\n newPerm.add(j,nums[i]);\n backTrack(newPerm,i+1,nums);\n newPerm.remove(j);\n }\n \n }\n} | 14 | 1 | [] | 5 |
permutations | Video solution | 2 approaches with intuition explained in detail | C++ | Backtracking | video-solution-2-approaches-with-intuiti-anzw | Video \n\nHey everyone, i have created video solution for this problem, (its in Hindi) i have solved this problem by backtracking using two methods \n\n- Using | _code_concepts_ | NORMAL | 2024-04-16T10:38:20.032336+00:00 | 2024-04-16T10:38:20.032356+00:00 | 1,076 | false | # Video \n\nHey everyone, i have created video solution for this problem, (its in Hindi) i have solved this problem by backtracking using two methods \n\n- Using visited array\n- Using swap method (more efficient and will clear all your doubts and confusion) \n\nif you have any consfusion on swap method ( when to swap back and when not to ), i have explained this thing in detail by using concept of pass by value vs. pass by reference, i am 100% sure this will clear all your doubts and will make your backtracking concepts much more clear and stronger.\n\nMethod 1 (for basic understanding ): \nhttps://www.youtube.com/watch?v=WxyVsJuF6CM\n\nMethod 2 (Swap method):\nhttps://www.youtube.com/watch?v=9P85FLRB3mM\n\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> res;\n void helper(vector<int>& nums, int start){\n if(start==nums.size()){\n res.push_back(nums);\n return;\n }\n for(int i=start;i<nums.size();i++){\n swap(nums[start],nums[i]);\n helper(nums,start+1);\n swap(nums[start],nums[i]);\n\n }\n \n } \n vector<vector<int>> permute(vector<int>& nums) {\n int start=0;\n helper(nums,start);\n return res;\n }\n};\n``` | 13 | 1 | ['C++'] | 1 |
permutations | ✔️[C++ , Python3 , Java] Easy Explanation with Image (Backtracking Solution)✔️ | c-python3-java-easy-explanation-with-ima-x12d | Intuition\nSince the n is very small we could try all the permutations. \n\n# Approach\nTo solve this problem, we will use a recursive backtracking algorithm. T | upadhyayabhi0107 | NORMAL | 2023-08-02T03:33:26.756065+00:00 | 2023-08-02T03:38:04.805594+00:00 | 2,494 | false | # Intuition\nSince the n is very small we could try all the permutations. \n\n# Approach\nTo solve this problem, we will use a recursive backtracking algorithm. The main idea behind backtracking is to explore all possible combinations by trying out different choices and then undoing those choices if they lead to invalid solutions. We will start with the main array `nums` and swap and permutate it untill we reach our base case.\n\n1. Base Case:\nWe need to identify the base case of the recursion, i.e., when to stop generating permutations. In our case, the base case will be when the i which is the index of the array reaches the end of the array which is `nums.size()`.\n\n2. Recursive Function:\nWe will define a recursive function, let\'s call it `recur`, which will be responsible for generating the permutations. This function will take the following parameters:\n - `nums`: The original array which we will use to generate all the permutations.\n - `i`: index of the element at which it is currently present.\n\n3. Initialization:\nWe will start by calling the recursive `recur` function with `nums` and `i` the 0th index at which we are starting.\n\n4. Backtracking Algorithm:\nInside the `recur` function, we will do the following steps:\n a. Check the base case: If the length of `i` equals the length of `nums`, add it to the array of valid permutations.\n b. Iterate through the `nums` array:\n i. Swap the i<sup>th</sup> element with the j<sup>th</sup> element.\n ii. Call for the function recursively for the next index which is i + 1.\n iii. Backtrack by undoing what we did with swaping back that i<sup>th</sup> element with the j<sup>th</sup> \n\nConclusion:\nBy implementing the above approach, we can efficiently generate all possible permutations of the given array `nums`. The backtracking algorithm ensures that we explore all possible combinations while efficiently avoiding invalid solutions.\n\n\n\n# Complexity\n- Time complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a permutation.\n\n- Space complexity: O(n * n!) in worst case.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> ans;\n void recur(vector<int> nums , int i){\n if(i == nums.size()){\n ans.push_back(nums);\n return ;\n }\n for(int j = i ; j < nums.size() ; j++){\n swap(nums[i] , nums[j]);\n recur(nums , i + 1);\n swap(nums[i] , nums[j]);\n }\n }\n vector<vector<int>> permute(vector<int>& nums) {\n recur(nums , 0);\n return ans;\n }\n};\n```\n```python3 []\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n ans = []\n \n def recur(nums, i):\n if i == len(nums):\n ans.append(nums[:])\n return\n \n for j in range(i, len(nums)):\n nums[i], nums[j] = nums[j], nums[i]\n recur(nums, i + 1)\n nums[i], nums[j] = nums[j], nums[i]\n \n recur(nums, 0)\n return ans\n```\n```Java []\nclass Solution {\n private List<List<Integer>> ans = new ArrayList<>();\n\n private void recur(int[] nums, int i) {\n if (i == nums.length) {\n List<Integer> temp = new ArrayList<Integer>();\n for (int num : nums) temp.add(num);\n ans.add(temp);\n return;\n }\n for (int j = i; j < nums.length; j++) {\n swap(nums, i, j);\n recur(nums, i + 1);\n swap(nums, i, j);\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 public List<List<Integer>> permute(int[] nums) {\n recur(nums, 0);\n return ans;\n }\n}\n``` | 13 | 0 | ['Backtracking', 'C++', 'Java', 'Python3'] | 1 |
permutations | Javascript DFS + Backtracking with heavy comments | javascript-dfs-backtracking-with-heavy-c-7iuo | \n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nconst permute = (nums) => {\n // Backtracking\n const used = new Set(); // Keep track of w | tommymallis | NORMAL | 2022-09-06T21:47:03.594920+00:00 | 2022-09-09T04:12:42.922878+00:00 | 2,291 | false | ```\n/**\n * @param {number[]} nums\n * @return {number[][]}\n */\nconst permute = (nums) => {\n // Backtracking\n const used = new Set(); // Keep track of what we have used\n const path = []; // Current potiential answer array\n const res = []; // Result array to be returned\n \n const dfs = () => {\n // If path is same length as nums, we know we have an answer. Push it to res array\n if(path.length === nums.length) {\n res.push([...path]); // We use spread operator to clone since arrays are pass by reference\n }\n \n // Every DFS we loop all numbers\n for(let i = 0; i < nums.length; i++) {\n // We can skip these numbers if they have been used\n if(used.has(nums[i])) continue;\n \n // Add to our potienial answer array and make it used by adding to used set\n path.push(nums[i]);\n used.add(nums[i]);\n \n // After adding, we call DFS again. DFS will continue till we hit the base case above\n\t\t\t// Think of this as just continuing down a path till we have an answer\n dfs();\n \n // Once we pop out of DFS, we need to remove from path array and remove from used Set\n // This will let it be used later in further paths\n path.pop();\n used.delete(nums[i])\n }\n \n }\n \n // Start DFS\n // All variables are global, no need to pass in anything\n dfs();\n \n return res;\n}\n``` | 13 | 0 | ['Backtracking', 'Depth-First Search', 'JavaScript'] | 3 |
permutations | ✔️ 100% Fastest Swift Solution | 100-fastest-swift-solution-by-sergeylesc-wlxo | \nclass Solution {\n\tfunc permute(_ nums: [Int]) -> [[Int]] {\n\t\tvar res: [[Int]] = []\n \n\n\t\tfunc recursion(_ list: [Int], _ rest: [Int]) -> Void | sergeyleschev | NORMAL | 2022-04-03T05:33:57.173218+00:00 | 2022-04-03T05:33:57.173366+00:00 | 1,125 | false | ```\nclass Solution {\n\tfunc permute(_ nums: [Int]) -> [[Int]] {\n\t\tvar res: [[Int]] = []\n \n\n\t\tfunc recursion(_ list: [Int], _ rest: [Int]) -> Void {\n for (i, item) in rest.enumerated() {\n\t\t\t\tvar list = list\n\t\t\t\tvar rest = rest\n\n\t\t\t\tlist.append(item)\n\t\t\t\trest.remove(at: i)\n\t\t\t\tif (list.count == nums.count) { res.append(list) }\n recursion(list, rest)\n\t\t\t}\n\t\t}\n\t\trecursion([], nums)\n\t\treturn res\n\t}\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 13 | 0 | ['Swift'] | 0 |
permutations | Simple Python solution 68ms | simple-python-solution-68ms-by-dietpepsi-9wuk | def permute(self, nums):\n ans = [nums]\n for i in xrange(1, len(nums)):\n m = len(ans)\n for k in xrange(m):\n | dietpepsi | NORMAL | 2015-10-05T06:05:14+00:00 | 2018-10-22T10:49:35.907447+00:00 | 5,698 | false | def permute(self, nums):\n ans = [nums]\n for i in xrange(1, len(nums)):\n m = len(ans)\n for k in xrange(m):\n for j in xrange(i):\n ans.append(ans[k][:])\n ans[-1][j], ans[-1][i] = ans[-1][i], ans[-1][j]\n return ans\n\n\n # 25 / 25 test cases passed.\n # Status: Accepted\n # Runtime: 68 ms\n # 99.02%\n\nswap unique pairs of numbers for all the answers in pocket to generate new answers. | 13 | 0 | ['Python'] | 0 |
permutations | 🚀 [VIDEO] Backtracking 100% - Unlocking Permutations | video-backtracking-100-unlocking-permuta-8u42 | Intuition\nUpon encountering this problem, I was immediately struck by its resemblance to a well-known puzzle: generating all possible permutations of a given s | vanAmsen | NORMAL | 2023-07-21T17:56:22.989161+00:00 | 2023-08-02T01:14:02.271729+00:00 | 1,927 | false | # 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\nhttps://youtu.be/Jlw0sIGdS_4\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. | 12 | 0 | ['Swift', 'C++', 'Go', 'Python3', 'Rust'] | 2 |
permutations | Permutations Java Solution || 2 Approaches | permutations-java-solution-2-approaches-hsy1y | \n1. First Approach :- Generating all permutations\n\nTwo Extra Data Structure Required To generate permutation\n1. ArrayList<> subset //to store subset\n2. boo | palpradeep | NORMAL | 2022-11-03T08:39:38.728028+00:00 | 2022-11-06T12:53:45.579889+00:00 | 3,282 | false | ```\n1. First Approach :- Generating all permutations\n\nTwo Extra Data Structure Required To generate permutation\n1. ArrayList<> subset //to store subset\n2. boolean map[] //this map will tell us which element is pick or not picked at that time\n\n//Let\'s Understand\nExample :- [1,2,3]\n\nfor make permutation we can pick one element from given three element\n1. if we pick 1 mark in map true ,map[T,F,F] & subset[1]\n2. if we pick 2 mark in map true , map[F,T,F] & subset[2]\n3. if we pick 3 mark in map true , map[F,F,T] & subset[3]\n\nnow suppose we picked 1 so that our map is map[T,F,F] & subset[1], again for make permutation we can pick one element from \ngiven three element but this time we already picked 1 so we have only 2 elements remaining\n1.if we pick 2 mark in map true, map[T,T,F] & subset[1,2]\n2.if we pick 3 mark in map true, map[T,F,T] & subset[1,3]\n\nnow suppose we picked 2 so that our map is map[T,T,F] & subset[1,2], again for make permutation we can pick one element from \ngiven three element but this time we already picked1 & 2 so we have only 3 remaining\n1.we picked 3 mark in map true, map[T,T,T] & subset[1,2,3]\n\nWhen subset size equal to arra size store the subset into our final ans \nand same for remaining cases\n```\n\n```\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> ans = new ArrayList();\n List<Integer> subset = new ArrayList();\n boolean map[] = new boolean[nums.length];\n helper(nums,subset,ans,map);\n return ans;\n }\n public static void helper(int nums[],List<Integer> subset,List<List<Integer>> ans,boolean map[]){\n if(subset.size()==nums.length){\n ans.add(new ArrayList(subset));\n return;\n }\n for(int i=0; i<nums.length; i++){\n if(!map[i]){\n subset.add(nums[i]);\n map[i]=true;\n helper(nums,subset,ans,map);\n subset.remove(subset.size()-1);\n map[i]=false;\n }\n }\n }\n}\nT.C :- n!(for generating all permutation) * n(for running loop i=0 to nums.length)\nS.C :- EXTRA SPACE :- n(for subset data structure) + n(for map data structure)\n :- Auxillary Space :- recursion stack i.e. O(n)\n```\n```\n2. Second Approach :- Backtracking & Swapping \n```\n\n```\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> ans = new ArrayList<>();\n\t helper(nums,0,ans);\n\t return ans;\n }\n public void helper(int[] nums, int index, List<List<Integer>> ans)\n\t {\n\t\t//BASE CASE\n\t \tif(index==nums.length){\n\t \t\t ArrayList<Integer> list =new ArrayList<>();\n\t \t for(int i = 0 ; i<nums.length ; i++){\n\t \t list.add(nums[i]);\n\t \t }\n\t \t ans.add(list);\n\t \t return;\n\t \t}\n\t for(int i = index; i<nums.length; i++){\n\t swap(i,index,nums);\n\t helper(nums, index+1, ans);\n\t swap(i,index,nums);\n\t }\n\t }\n\t public static void swap(int i , int j, int[] nums){\n\t \t int t=nums[i];\n\t \t nums[i]=nums[j];\n\t \t nums[j]=t;\n\t }\n}\nT.C :- n! * n\nS.C :- Auxillary Space - O(n)\n``` | 12 | 0 | ['Backtracking', 'Recursion', 'Java'] | 3 |
permutations | 🍿 C++ || Easy-to-Understand with Diagram || 0 ms || Backtracking | c-easy-to-understand-with-diagram-0-ms-b-unzh | \n//image source gfg\n\n\t\tclass Solution {\n\t\tpublic:\n\t\t\tvoid helper(vector> &res , vector &nums,int i){\n\t\t\t\tif(i==nums.size()){\n\t\t\t\t\tres.pus | venom-xd | NORMAL | 2022-04-18T17:49:39.901957+00:00 | 2022-04-18T17:49:39.901993+00:00 | 1,126 | false | \n**//image source gfg**\n\n\t\tclass Solution {\n\t\tpublic:\n\t\t\tvoid helper(vector<vector<int>> &res , vector<int> &nums,int i){\n\t\t\t\tif(i==nums.size()){\n\t\t\t\t\tres.push_back(nums);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\tfor(int j=i;j<nums.size();j++){\n\t\t\t swap(nums[i],nums[j]);\n\t\t\t helper(res,nums,i+1);\n\t\t\t swap(nums[i],nums[j]);\n\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvector<vector<int>> permute(vector<int>& nums) {\n\t\t\t\tvector<vector<int>> res;\n\t\t\t\thelper(res,nums,0);\n\t\t\t\treturn res;\n\t\t\t}\n\t\t};\n | 12 | 0 | ['Backtracking', 'Recursion', 'C', 'C++'] | 0 |
permutations | My C++ Solution Share | my-c-solution-share-by-jianhao-ubcj | It is obvious that N numbers has N! permutations .\n\nHere I assume an empty vector also has one permutation. It seems OJ didn't check the empty input case. Wel | jianhao | NORMAL | 2014-10-10T14:44:29+00:00 | 2014-10-10T14:44:29+00:00 | 6,168 | false | It is obvious that **N numbers has N! permutations** .\n\nHere I assume an empty vector also has one permutation. It seems OJ didn't check the empty input case. Well, it doesn't matter.\n\n\n class Solution {\n public:\n vector<vector<int> > permute(vector<int> &num) {\n // Add an empty vector as the base case (empty input)\n \tvector<vector<int> > permutations(1, vector<int>());\n \t// Algrithm description:\n \t//\tInsert the current number in different spaces of previous permutations\n \tfor (vector<int>::size_type index = 0; index != num.size(); ++index)\n \t{\n \t\tvector<vector<int> > subPermutations(permutations);\n \t\tpermutations.clear();\n \t\tfor (vector<vector<int> >::size_type i = 0; i != subPermutations.size(); ++i)\n \t\t{\n \t\t\tfor (int offset = 0; offset != subPermutations[i].size()+1; ++offset)\n \t\t\t{\n \t\t\t\tvector<int> temp(subPermutations[i]);\n \t\t\t\ttemp.insert(temp.begin() + offset, num[index]);\n \t\t\t\tpermutations.push_back(temp);\n \t\t\t}\n \t\t}\n \t}\n \treturn permutations;\n }\n };\n\nAll comments are welcome ! | 12 | 0 | [] | 6 |
permutations | 2ms Java solution beats 93%, I think it could be optimized | 2ms-java-solution-beats-93-i-think-it-co-42cc | public class Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n\t\tperm(re | andygogo | NORMAL | 2016-04-12T08:38:58+00:00 | 2016-04-12T08:38:58+00:00 | 3,571 | false | public class Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<List<Integer>>();\n\t\tperm(result,nums,0,nums.length-1);\n\t\treturn result;\n }\n public static void perm(List<List<Integer>> result, int[] nums, int start, int end){\n\t\tif(start==end){\n\t\t\tInteger[] ele = new Integer[nums.length];\n\t\t\tfor(int i=0; i<nums.length; i++){\n\t\t\t\tele[i] = nums[i];\n\t\t\t}\n\t\t\tresult.add(Arrays.asList(ele));\n\t\t}\n\t\telse{\n\t\t\tfor(int i=start; i<=end; i++){\n\t\t\t\tint temp = nums[start];\n\t\t\t\tnums[start] = nums[i];\n\t\t\t\tnums[i] = temp;\n\t\t\t\t\n\t\t\t\tperm(result, nums,start+1,end);\n\t\t\t\t\n\t\t\t\ttemp = nums[start];\n\t\t\t\tnums[start] = nums[i];\n\t\t\t\tnums[i] = temp;\n\t\t\t}\n\t\t}\n\t}\n} | 12 | 0 | ['Java'] | 1 |
permutations | easiest solution || c-plus-plus || easy to understand || only 4-5 lines code | easiest-solution-c-plus-plus-easy-to-und-0wm4 | 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 | youdontknow001 | NORMAL | 2022-11-24T07:58:30.105633+00:00 | 2022-11-24T07:58:30.105676+00:00 | 828 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n vector<vector<int>> ans;\n do {\n ans.push_back(nums);\n } while (next_permutation(nums.begin(),nums.end()));\n return ans;\n }\n};\n``` | 11 | 0 | ['C++'] | 1 |
permutations | C++ clean code- two approaches with proper comments | c-clean-code-two-approaches-with-proper-9qk2r | Approach 1\n\nusing a freq array to store the number visited because it should not be included again in the answer\n\nclass Solution {\npublic:\n void solve( | geekie | NORMAL | 2021-09-14T12:47:54.661677+00:00 | 2021-09-14T17:05:12.107784+00:00 | 1,455 | false | Approach 1\n\nusing a freq array to store the number visited because it should not be included again in the answer\n```\nclass Solution {\npublic:\n void solve(vector<int>& nums,vector<int>&v,vector<vector<int>>&ans,int freq[])\n {\n if(v.size()==nums.size()){\n ans.push_back(v);\n return;\n } \n for(int i=0;i<nums.size();i++)\n {\n if(!freq[i])\n {\n freq[i]=1; //marking that number as visited\n v.push_back(nums[i]); //pushing the number in vector\n solve(nums,v,ans,freq); \n freq[i]=0; //after recursive call is finished mark it as unvisited so that it can be considered for other permutation\n v.pop_back(); // pop it otherwise it will remain a part of other permutations too\n } \n }\n }\n vector<vector<int>> permute(vector<int>& nums) {\n vector<int>v;\n vector<vector<int>>ans;\n int n=nums.size();\n int freq[n];\n for(int i=0;i<n;i++)freq[i]=0; //initialisation of freq array\n solve(nums,v,ans,freq);\n return ans;\n }\n};\n```\n\nApproach 2\n\nWithout freq array, by swapping two numbers \n\n```\nclass Solution {\npublic:\n void solve(int ind,vector<int>& nums,vector<vector<int>>&ans)\n {\n if(ind==nums.size())\n {\n ans.push_back(nums);\n return;\n }\n for(int i=ind;i<nums.size();i++)\n {\n swap(nums[i],nums[ind]); \n solve(ind+1,nums,ans); //ind is increased by one so that swapping is done with next index element in further calls\n swap(nums[i],nums[ind]); // swapping it back to original order after recursion call is over\n }\n }\n vector<vector<int>> permute(vector<int>& nums) {\n \n vector<vector<int>>ans;\n\t solve(0,nums,ans);\n return ans;\n }\n};\n```\n\nPlease upvote if you like my solution | 11 | 1 | ['Backtracking', 'Recursion', 'C'] | 3 |
permutations | Simple python code without recursion | simple-python-code-without-recursion-by-eb34i | class Solution(object):\n def permute(self, nums):\n """\n :type nums: List[int]\n :rtype: List[List[int]]\n | holsety | NORMAL | 2016-05-24T02:52:17+00:00 | 2018-09-03T09:40:53.760034+00:00 | 4,767 | false | class Solution(object):\n def permute(self, nums):\n """\n :type nums: List[int]\n :rtype: List[List[int]]\n """\n def swap(i, j, nums):\n new_nums = list(nums)\n new_nums[i], new_nums[j] = new_nums[j], new_nums[i]\n return new_nums\n \n result = [nums,]\n \n for i in range(len(nums)-1):\n for one in result[:]:\n for j in range(i+1, len(nums)):\n result.append(swap(i, j, one))\n \n return result | 11 | 0 | [] | 4 |
permutations | C++ || Bits approach + Recursion || Day 2 | c-bits-approach-recursion-day-2-by-chiik-6y9g | Code\n\nclass Solution {\npublic:\n vector<vector<int>>ans;\n void help(int mask,vector<int>&v,vector<int>&temp){\n if(mask==0){\n ans.p | CHIIKUU | NORMAL | 2023-08-02T06:52:35.257357+00:00 | 2023-08-02T06:52:35.257389+00:00 | 482 | false | # Code\n```\nclass Solution {\npublic:\n vector<vector<int>>ans;\n void help(int mask,vector<int>&v,vector<int>&temp){\n if(mask==0){\n ans.push_back(temp);\n return;\n }\n for(int i=0;i<v.size();i++){\n if(mask & (1<<i)){\n temp.push_back(v[i]);\n help(mask ^ (1<<i), v,temp);\n temp.pop_back();\n }\n }\n }\n vector<vector<int>> permute(vector<int>& v) {\n vector<int>temp;\n help((1<<v.size())-1,v,temp);\n return ans;\n }\n};\n```\n\n | 10 | 0 | ['C++'] | 4 |
permutations | 🔥 100% Backtracking / Recursive Approach - Unlocking Permutations | 100-backtracking-recursive-approach-unlo-2emz | Intuition\nThe problem requires generating all possible permutations of a given array of distinct integers. A clear and intuitive understanding of the recursive | phistellar | NORMAL | 2023-08-02T00:13:04.865905+00:00 | 2023-08-02T00:16:52.890840+00:00 | 3,365 | false | # 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](https://youtu.be/Jlw0sIGdS_4).\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``` | 10 | 0 | ['C++', 'Java', 'Python3', 'JavaScript', 'C#'] | 1 |
permutations | Simple Python Solution. Beats 99%. with comments | simple-python-solution-beats-99-with-com-igdh | ```\nclass Solution(object):\n def permute(self, nums):\n \n res = []\n def dfs(path, num): # record the path and remaining numbers\n | cz2105 | NORMAL | 2022-07-18T00:09:36.050582+00:00 | 2022-07-18T00:09:36.050626+00:00 | 1,644 | false | ```\nclass Solution(object):\n def permute(self, nums):\n \n res = []\n def dfs(path, num): # record the path and remaining numbers\n if not num:\n res.append(path) # When finished iterating, append path to result\n return\n for i in range(len(num)):\n dfs(path + [num[i]], num[:i] + num[i + 1:]) \n # append the current number to path and iterate with the unused numbers\n \n dfs([], nums)\n return res # return results\n \n #If you find this solution helpful, please upvote :) | 10 | 0 | ['Python', 'Python3'] | 1 |
permutations | Java easy solution || Recursion and backtracking | java-easy-solution-recursion-and-backtra-ece4 | Code\n\njava\npublic List<List<Integer>> permute(int[] nums) {\n\tList<List<Integer>> list = new ArrayList<>();\n\tpermuteUtil(list, new ArrayList<>(), nums);\n | Chaitanya31612 | NORMAL | 2021-11-07T11:07:53.626714+00:00 | 2021-11-07T11:08:31.534938+00:00 | 1,663 | false | **Code**\n\n```java\npublic List<List<Integer>> permute(int[] nums) {\n\tList<List<Integer>> list = new ArrayList<>();\n\tpermuteUtil(list, new ArrayList<>(), nums);\n\treturn list;\n}\n\npublic void permuteUtil(List<List<Integer>> list, List<Integer> temp, int[] nums) {\n\t//base case\n\tif(temp.size() == nums.length) {\n\t\tlist.add(new ArrayList<>(temp));\n\t\treturn;\n\t}\n\n\t//recursive case\n\tfor(int i = 0; i < nums.length; i++) {\n\t\tif(temp.contains(nums[i])) continue;\n\t\ttemp.add(nums[i]);\n\t\tpermuteUtil(list, temp, nums);\n\t\ttemp.remove(temp.size() - 1);\n\t}\n}\n```\n\n**Explanation**\nThis is a standard problem and this approach is used in a variety of problems, I\'ve explained the approach there, do check them out, the problems are as follows:-\n- [Combination Sum](https://leetcode.com/problems/combination-sum/discuss/1560722/java-easy-solution-100-faster-recursion-and-backtracking)\n- [Combination Sum 2](https://leetcode.com/problems/combination-sum-ii/discuss/1560743/java-easy-solution-with-explanation-recursion-and-backtracking)\n- [Subsets](https://leetcode.com/problems/subsets/)\n- [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/discuss/1561260/java-easy-solution-recursion-and-backtracking)\n\nThanks | 10 | 0 | ['Backtracking', 'Recursion', 'Java'] | 2 |
permutations | Javascript BFS | javascript-bfs-by-erick_orozco-zcxj | Javascript Breath First Search. \n\nEach queue element will have two array: \n The first array is the current sequence we have constructed so far. \n The second | erick_orozco | NORMAL | 2021-09-29T02:58:52.192093+00:00 | 2021-09-29T02:59:33.189768+00:00 | 2,204 | false | Javascript Breath First Search. \n\nEach queue element will have two array: \n* The first array is the current sequence we have constructed so far. \n* The second array is the remaning numbers from nums. \n\nFor every element of the queue we add a new element for every remaning number. For example: \nif our nums = [1,2,3] and we dequed the following element: [ [1], [2, 3] ], then: \n\tWe iterate through the second array and add [ [1 ,2] , [3] ] and [ [1, 3] , [2] ] to the queue. \n\n\n```\nvar permute = function(nums) {\n \n const result = [];\n const queue = [];\n \n queue.push([[], nums]);\n \n while(queue.length){\n const [currentSequence, availableNumbers] = queue.shift();\n \n if(availableNumbers.length === 0)\n {\n result.push(currentSequence);\n continue;\n }\n \n \n for(let i =0; i < availableNumbers.length; i++)\n {\n const number = availableNumbers[i];\n queue.push([\n [...currentSequence, number], \n [...availableNumbers.slice(0, i), ...availableNumbers.slice(i + 1)]\n ]); \n } \n }\n \n return result;\n};\n``` | 10 | 0 | ['Breadth-First Search', 'JavaScript'] | 3 |
permutations | Easiest Golang solution (99% 4ms) | easiest-golang-solution-99-4ms-by-fpf999-xgld | \nfunc permute(nums []int) [][]int {\n answer := make([][]int, 0)\n aux(&answer, 0, nums)\n\treturn answer\n}\n\nfunc aux(answer *[][]int, idx int, nums [ | fpf999 | NORMAL | 2019-05-13T04:47:57.526253+00:00 | 2019-05-13T04:47:57.526284+00:00 | 1,055 | false | ```\nfunc permute(nums []int) [][]int {\n answer := make([][]int, 0)\n aux(&answer, 0, nums)\n\treturn answer\n}\n\nfunc aux(answer *[][]int, idx int, nums []int) {\n if idx == len(nums) {\n c := make([]int, len(nums))\n copy(c, nums)\n *answer = append(*answer, c)\n return\n }\n for i := idx; i < len(nums); i++ {\n nums[idx], nums[i] = nums[i], nums[idx]\n aux(answer, idx + 1, nums)\n nums[i], nums[idx] = nums[idx], nums[i]\n }\n return\n}\n\n``` | 10 | 0 | ['Recursion', 'Go'] | 1 |
permutations | JavaScript Solution | javascript-solution-by-tryck-7j7m | \nvar permute = function(nums) {\n let sol = [];\n if(nums.length < 1) {\n return [[]];\n } else if(nums.length == 1) {\n return [[nums[0 | tryck | NORMAL | 2019-04-16T22:01:53.692403+00:00 | 2019-04-16T22:01:53.692447+00:00 | 2,185 | false | ```\nvar permute = function(nums) {\n let sol = [];\n if(nums.length < 1) {\n return [[]];\n } else if(nums.length == 1) {\n return [[nums[0]]];\n } \n for(let i = 0; i < nums.length; i++) {\n let numsCopy = [...nums]; \n numsCopy.splice(i, 1); \n let rtnVal = permute(numsCopy);\n for(let j = 0; j < rtnVal.length; j++) {\n sol.push([nums[i], ...rtnVal[j]])\n } \n }\n return sol;\n};\n```\n\n# Approach:\nThe approach to this problem is quite similar to that of the [Letter Combinations of a Phone Number](https://leetcode.com/problems/letter-combinations-of-a-phone-number/). Since we\'re dealing with combinations in arrays, my intuition told me that this likely had a recursive solution. \n\nLet\'s deal with the base case first:\nIf the given array is empty (array = `[]`), then the function should return `[[]]`.\nIf the given array only had one element, then it should return `[[array[0]]`.\n\nNow, that we have our base cases, let\'s go into our recursion. We know that when the array has more than one element, each element has a number of permutations in which that element is the first element.\n\nSo that\'s why we have the outer for loop:\n```\nfor(let i = 0; i < nums.length; i++) {\n.\n.\n.\n\tsol.push(nums[i], ....);\n}\n```\n\nTo visualize:\n```\npermute([1, 2, 3]):\ni = 0: nums[0] == 1 --> [[1, ...[2,3]], [1, ...[3,2]]] --> [[1,2,3], [1,3,2]]\ni = 1: nums[1] == 2 --> [[2, ...[1,3]], [2, ...[3,1]]] --> [[2,1,3], [2,3,1]]\ni = 1: nums[2] == 3 --> [[3, ...[1,2]], [3, ...[2,1]]] --> [[3,1,2], [3,2,1]]\n```\n\nNow, in order to get the other combinations such as `[1,3], [2,3]`, I used the `splice()`. **However**, `splice()` changes the array reference and object, so you must make a copy. Which is why I did `let numsCopy = [...nums]`. \n\nNow, we simply recurse on `numsCopy` after we remove the `i-th` element and it will return an array with the permutations of `numsCopy`. Then we just add `[nums[i], ...rtnVal[j]]` to the `sol` and return the value.\n\nRuntime: `O(n!)`\nSpace Complexity: `O(n)` | 10 | 0 | [] | 2 |
permutations | 👏🏻 Python | DFS + BFS - 公瑾™ | python-dfs-bfs-gong-jin-tm-by-yuzhoujr-38u0 | 46. Permutations 此题收录在Github DFS ```python class Solution: def permute(self, nums): self.res = [] self.dfs(nums, []) return self.res | yuzhoujr | NORMAL | 2018-09-21T01:46:19.059526+00:00 | 2018-09-21T01:46:19.059605+00:00 | 1,400 | false | ### 46. Permutations
[此题收录在Github](https://github.com/yuzhoujr/leetcode/issues/33)
#### DFS
```python
class Solution:
def permute(self, nums):
self.res = []
self.dfs(nums, [])
return self.res
def dfs(self, nums, temp):
if len(nums) == len(temp):
self.res.append(temp[:])
return
for i in range(len(nums)):
if nums[i] in temp: continue
temp.append(nums[i])
self.dfs(nums, temp)
temp.pop()
```
#### BFS (Using Deque)

先把起始状态的`queue`存好: `[[1],[2],[3]]`
`while`这一层检查我们`queue`里面是否有比input `nums`长度小的单位,如果有的话,咱还有针对这个`queue`里面的元素进行增值。
`for`这一层把pop()出来的数组`temp`,进行去重比对,如果发现`nums`里面的元素没有出现在`temp`,代表着这是unique的,我们这个数组的的copy `temp[:]`加上当前的值,放回`queue`中。
```python
from collections import deque
class Solution:
def permute(self, nums):
q = deque()
for num in nums:
q.append([num])
while len(min(q,key=len)) < len(nums):
temp = q.popleft()
for num in nums:
if num in temp: continue
q.append(temp[:] + [num])
return list(q)
```
#### BFS (Acting like using Deque)
```python
from collections import deque
class Solution:
def permute(self, nums):
q = [[num] for num in nums]
while len(min(q,key=len)) < len(nums):
temp = q.pop(0)
for num in nums:
if num in temp: continue
q.append(temp[:] + [num])
return q
``` | 10 | 0 | [] | 0 |
permutations | Accepted Recursive Solution in Java | accepted-recursive-solution-in-java-by-b-9k6q | int len;\n boolean[] used;\n List<List<Integer>> result;\n List<Integer> temp;\n public List<List<Integer>> permute(int[] num) {\n len = num. | beyond2001 | NORMAL | 2015-04-03T15:30:44+00:00 | 2015-04-03T15:30:44+00:00 | 3,112 | false | int len;\n boolean[] used;\n List<List<Integer>> result;\n List<Integer> temp;\n public List<List<Integer>> permute(int[] num) {\n len = num.length;\n used = new boolean[len];\n result = new ArrayList<List<Integer>>();\n temp = new ArrayList<>();\n doPermute(num, 0);\n\n return result;\n }\n\n public void doPermute(int[] in, int level) {\n if (level == len) {\n result.add(new ArrayList<Integer>(temp));\n return;\n }\n\n for (int i = 0; i < len; i++) {\n if (used[i]) {\n continue;\n }\n\n temp.add(in[i]);\n used[i] = true;\n doPermute(in, level + 1);\n used[i] = false;\n temp.remove(level);\n }\n } | 10 | 0 | ['Probability and Statistics', 'Java'] | 0 |
permutations | Accepted as best in C | accepted-as-best-in-c-by-lhearen-0kcc | void swap(int* p, int* q)\n {\n int t = *p; *p = *q; *q = t;\n }\n void search(int* nums, int size, int*** arr, int* returnSize, int begin, int | lhearen | NORMAL | 2016-03-22T06:58:11+00:00 | 2016-03-22T06:58:11+00:00 | 3,154 | false | void swap(int* p, int* q)\n {\n int t = *p; *p = *q; *q = t;\n }\n void search(int* nums, int size, int*** arr, int* returnSize, int begin, int end)\n {\n if(begin == end)\n {\n (*returnSize)++;\n *arr = (int**)realloc(*arr, sizeof(int*)*(*returnSize));\n (*arr)[*returnSize-1] = (int*)malloc(sizeof(int)*size);\n for(int i = 0; i < size; i++)\n (*arr)[*returnSize-1][i] = nums[i];\n return;\n }\n for(int i = begin; i <= end; i++)\n {\n swap(nums+begin, nums+i); //try to use each element as the head;\n search(nums, size, arr, returnSize, begin+1, end);\n swap(nums+begin, nums+i);\n }\n }\n \n //AC - 4ms;\n int** permute(int* nums, int size, int* returnSize)\n {\n *returnSize = 0;\n int** arr = (int**)malloc(sizeof(int*));\n search(nums, size, &arr, returnSize, 0, size-1);\n return arr;\n } | 10 | 0 | [] | 3 |
permutations | ✅ One Line Solution | one-line-solution-by-mikposp-b88e | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)Code 1.1Time complexity: O(n!). Space complexity: O( | MikPosp | NORMAL | 2025-02-07T11:47:25.388341+00:00 | 2025-02-07T11:52:03.937472+00:00 | 1,932 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)
# Code 1.1
Time complexity: $$O(n!)$$. Space complexity: $$O(n!)$$.
```python3
class Solution:
def permute(self, a: List[int]) -> List[List[int]]:
return a and [[v]+p for v in a for p in self.permute([u for u in a if u != v])] or [[]]
```
# Code #1.2 - Unwrapped
```python3
class Solution:
def permute(self, a: List[int]) -> List[List[int]]:
if a:
res = []
for v in a:
b = [u for u in a if u != v]
for p in self.permute(b):
res.append([v]+p)
return res
return [[]]
```
# Code #2 - Cheat
```python3
class Solution:
def permute(self, a: List[int]) -> List[List[int]]:
return [*permutations(a)]
```
(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be 'true' oneliners - please, remind about drawbacks only if you know how to make it better) | 9 | 0 | ['Array', 'Backtracking', 'Recursion', 'Python', 'Python3'] | 0 |
permutations | c++ recurive solution || easy to understand | c-recurive-solution-easy-to-understand-b-ta5b | \n# Code\n\nclass Solution {\npublic:\n\n void findpermutation(vector<int>& nums, vector<vector<int>>&ans, vector<int>&ds,int freq[]){\n if(ds.size()= | harshil_sutariya | NORMAL | 2023-05-03T08:37:51.537314+00:00 | 2023-05-03T08:37:51.537349+00:00 | 4,437 | false | \n# Code\n```\nclass Solution {\npublic:\n\n void findpermutation(vector<int>& nums, vector<vector<int>>&ans, vector<int>&ds,int freq[]){\n if(ds.size()==nums.size()){\n ans.push_back(ds);\n return;\n }\n for(int i=0;i<nums.size(); i++){\n if(!freq[i]){\n ds.push_back(nums[i]);\n freq[i]=1;\n findpermutation(nums,ans,ds,freq);\n freq[i]=0;\n ds.pop_back();\n }\n }\n }\n\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>>ans;\n vector<int>ds;\n\n int freq[nums.size()];\n for(int i=0;i<nums.size();i++){\n freq[i]=0;\n }\n\n findpermutation(nums,ans,ds,freq);\n return ans;\n }\n};\n``` | 9 | 0 | ['Recursion', 'C++'] | 1 |
permutations | [Java] [4 Approaches] Visuals + Time Complexity Analysis | java-4-approaches-visuals-time-complexit-gdkh | For Python implementation (AND/OR) a more detailed explanation and visuals -> checkout this post:\nhttps://leetcode.com/problems/permutations/discuss/993970/Pyt | Hieroglyphs | NORMAL | 2021-01-01T04:09:43.569721+00:00 | 2021-01-01T04:13:11.518798+00:00 | 951 | false | - **For Python implementation (AND/OR) a more detailed explanation and visuals -> checkout this post:**\nhttps://leetcode.com/problems/permutations/discuss/993970/Python-4-Approaches-%3A-Visuals-%2B-Time-Complexity-Analysis\n\n- **For JAVA implementation => scroll down**\n------------------------\n\n**Recursive with backtracking**\n--------------\n-------------\n\n```\n/*\n Recursive with backtracking\n*/\n\nclass Solution {\n\n // helper\n public List<List<Integer>> recursive(List<Integer> numsLst, List<List<Integer>> res, List<Integer> path) {\n \n if (numsLst.isEmpty()) {\n res.add(new ArrayList(path));\n }\n else {\n for (int i=0; i<numsLst.size(); i++) {\n List<Integer> newNumsLst = new ArrayList(numsLst);\n newNumsLst.remove(i);\n path.add(numsLst.get(i));\n recursive(newNumsLst, res, path);\n path.remove(path.size() - 1);\n }\n }\n return res;\n }\n \n \n public List<List<Integer>> permute(int[] nums) {\n // a turn around is to instantiate vars here - equivalent to Pythonic optional vars \n List<List<Integer>> res = new ArrayList();\n List<Integer> path = new ArrayList();\n \n // convert array to list\n List<Integer> numsLst = new ArrayList<Integer>();\n for (int num: nums) {\n numsLst.add(num);\n }\n \n // call helper\n return recursive(numsLst, res, path);\n \n }\n}\n```\n------------------------\n\n**Recursive without backtracking**\n--------------\n----------\n\n```\n/*\n Recursive without backtracking\n*/\nclass Solution {\n \n // helper to convert array to arrayList\n public List<Integer> toArrayList(int[] arr) {\n List<Integer> l = new ArrayList();\n for (int num : arr) {\n l.add(num);\n }\n return l;\n }\n \n public List<List<Integer>> recursive(List<Integer> nums, List<List<Integer>> res, List<Integer> path) {\n if (nums.isEmpty()) {\n res.add(new ArrayList(path));\n } else {\n for (int i=0; i<nums.size(); i++) {\n List<Integer> newNums = new ArrayList(nums); // copy\n newNums.remove(i); // remove takes an index\n \n List<Integer> newPath = new ArrayList(path);\n path.add(nums.get(i)); \n recursive(newNums, res, newPath);\n // no backtracking needed\n }\n }\n return res;\n }\n \n public List<List<Integer>> permute(int[] nums) {\n List<Integer> numsLst = toArrayList(nums);\n List<Integer> path = new ArrayList();\n List<List<Integer>> res = new ArrayList();\n return recursive(numsLst, res, path);\n }\n}\n```\n------------------------\n\n**Iterative DFS**\n--------------\n----------\n\n```\n/*\n Iterative DFS\n*/\n\nclass Node {\n List<Integer> nums;\n List<Integer> path;\n \n // Constructor\n Node(List<Integer> nums, List<Integer> path) {\n this.nums = nums;\n this.path = path;\n }\n}\n\nclass Solution {\n\n // helper\n public List<Integer> toArrayList(int[] nums) {\n List<Integer> numsLst = new ArrayList();\n for (int num : nums) {\n numsLst.add(num);\n }\n return numsLst;\n }\n \n public List<List<Integer>> permute(int[] nums) {\n\n List<List<Integer>> res = new ArrayList();\n Stack<Node> stack = new Stack();\n List<Integer> path = new ArrayList();\n List<Integer> numsLst = toArrayList(nums);\n Node node = new Node(numsLst, path);\n stack.push(node);\n \n while (!stack.isEmpty()) {\n node = stack.pop();\n if (node.nums.isEmpty()) {\n res.add(new ArrayList(node.path));\n }\n \n for (int i=0; i<node.nums.size(); i++) {\n List<Integer> newNums = new ArrayList(node.nums);\n List<Integer> newPath = new ArrayList(node.path);\n newPath.add(node.nums.get(i));\n newNums.remove(i);\n Node newNode = new Node(newNums, newPath);\n stack.push(newNode);\n }\n }\n return res;\n }\n}\n\n```\n\n------------------------\n\n**Iterative DFS**\n--------------\n----------\n\n```\n/*\n Iterative BFS\n*/\n\nclass Node {\n List<Integer> path;\n List<Integer> nums;\n \n // Constructor\n public Node(List<Integer> nums, List<Integer> path) {\n this.nums = nums;\n this.path = path;\n }\n}\n\nclass Solution {\n public List<Integer> toArrayList(int[] nums) {\n List<Integer> numsLst = new ArrayList();\n for (int num : nums) {\n numsLst.add(num);\n }\n return numsLst;\n }\n \n \n public List<List<Integer>> permute(int[] nums) {\n Deque<Node> q = new ArrayDeque<>();\n List<List<Integer>> res = new ArrayList();\n List<Integer> numsLst = toArrayList(nums);\n List<Integer> path = new ArrayList();\n Node node = new Node(numsLst, path);\n q.add(node);\n while (!q.isEmpty()) {\n node = q.pollFirst();\n if (node.nums.isEmpty()) {\n res.add(new ArrayList(node.path));\n }\n for (int i=0; i< node.nums.size(); i++) {\n List<Integer> newPath = new ArrayList(node.path);\n newPath.add(node.nums.get(i));\n List<Integer> newNums = new ArrayList(node.nums);\n newNums.remove(i);\n Node newNode = new Node(newNums, newPath);\n q.add(newNode);\n }\n }\n return res;\n \n }\n}\n``` | 9 | 0 | ['Backtracking', 'Depth-First Search', 'Breadth-First Search', 'Recursion', 'Iterator', 'Python'] | 2 |
permutations | Python Simple Solution EXPLAINED (video + code) (beginner) | python-simple-solution-explained-video-c-a5gn | \nhttps://www.youtube.com/watch?v=DBLUa6ErLKw\n\nclass Solution:\n def __init__(self):\n self.res = []\n \n def permute(self, nums: List[int | spec_he123 | NORMAL | 2020-09-19T19:48:51.350741+00:00 | 2020-09-19T19:48:51.350774+00:00 | 1,268 | false | [](https://www.youtube.com/watch?v=DBLUa6ErLKw)\nhttps://www.youtube.com/watch?v=DBLUa6ErLKw\n```\nclass Solution:\n def __init__(self):\n self.res = []\n \n def permute(self, nums: List[int]) -> List[List[int]]:\n self.backtrack(nums, [])\n return self.res\n \n def backtrack(self, nums, path):\n if not nums:\n self.res.append(path)\n for x in range(len(nums)):\n self.backtrack(nums[:x]+nums[x+1:], path+[nums[x]])\n``` | 9 | 0 | ['Backtracking', 'Python3'] | 1 |
permutations | java solution . BACKTRACK.!! REMOVE the LAST ELEMENT!!! | java-solution-backtrack-remove-the-last-1qn0z | Please upvote if helpFul!!\n\nclass Solution {\n //[1,2,3]\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> list = new Arra | kunal3322 | NORMAL | 2020-08-13T21:20:55.571078+00:00 | 2020-08-13T21:22:04.024796+00:00 | 873 | false | * **Please upvote if helpFul!!**\n```\nclass Solution {\n //[1,2,3]\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> list = new ArrayList<>();\n backtrack(list, new ArrayList<>(), nums);\n return list;\n }\n\n private void backtrack(List<List<Integer>> resultList, ArrayList<Integer> tempSet, int[] nums) {\n\n if (tempSet.size() == nums.length) {\n resultList.add(new ArrayList<>(tempSet));\n return;\n }\n\n\n for (int i = 0; i < nums.length; i++) {\n\n if (tempSet.contains(nums[i])) continue;\n tempSet.add(nums[i]);\n backtrack(resultList, tempSet, nums);\n tempSet.remove(tempSet.size() - 1); // v v v IMP step....this is where backtrack magic happens...\n\n }\n\n }\n}\n``` | 9 | 2 | ['Backtracking', 'Java'] | 1 |
permutations | [C++] No Recursion! 8 Lines, STL (no Explanation Needed) | c-no-recursion-8-lines-stl-no-explanatio-8kd0 | ```\nclass Solution {\npublic:\n \n vector> permute(vector& nums) \n {\n vector> ourResult;\n vector singleIter = nums;\n\t\tourResult.pu | leetcodegrindtt | NORMAL | 2020-01-20T16:10:43.392675+00:00 | 2020-01-20T16:11:01.649483+00:00 | 2,077 | false | ```\nclass Solution {\npublic:\n \n vector<vector<int>> permute(vector<int>& nums) \n {\n vector<vector<int>> ourResult;\n vector<int> singleIter = nums;\n\t\tourResult.push_back(singleIter);\n next_permutation(singleIter.begin(), singleIter.end());\n while (singleIter != nums)\n {\n ourResult.push_back(singleIter);\n next_permutation(singleIter.begin(), singleIter.end());\n }\n return ourResult;\n }\n}; | 9 | 3 | ['C', 'C++'] | 2 |
permutations | Java Backtracking Solution | java-backtracking-solution-by-laonawuli-jugw | public class Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> lists = new ArrayList<>();\n if (nums == null | laonawuli | NORMAL | 2015-11-30T20:31:48+00:00 | 2015-11-30T20:31:48+00:00 | 2,884 | false | public class Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> lists = new ArrayList<>();\n if (nums == null || nums.length == 0) {\n return lists;\n }\n\n dfs(nums, lists, new ArrayList<Integer>());\n return lists;\n }\n\n private void dfs(int[] nums, List<List<Integer>> lists, List<Integer> cur) {\n if (cur.size() == nums.length) {\n List<Integer> list = new ArrayList<>(cur);\n lists.add(list);\n }\n\n for (int i = 0; i < nums.length; i++) {\n if (cur.contains(nums[i])) {\n continue;\n }\n cur.add(nums[i]);\n dfs(nums, lists, cur);\n cur.remove(cur.size() - 1);\n }\n }\n} | 9 | 0 | [] | 1 |
permutations | 📸 The Permutation Party: When Numbers Can't Stop Taking Selfies! | the-permutation-party-when-numbers-cant-db6ca | 🎢 Welcome to the Permutation Party! 🎉Imagine you're at a party where your friends (the numbers) want to take all possible group selfies. Each time they line up | trivickram_1476 | NORMAL | 2025-03-29T05:03:40.670244+00:00 | 2025-03-29T05:08:16.734994+00:00 | 715 | false | # 🎢 Welcome to the Permutation Party! 🎉
Imagine you're at a party where your friends (the numbers) want to take all possible group selfies. Each time they line up differently, they click a pic! 📸
**Step 1:** The Solo Shot
If there’s only one friend (number) at the party, the only option is to click a solo pic. Done. Easy. Next!
# 🤹 Juggling Friends Around
Now, if more friends show up, things get spicy! 🌶️
- One friend decides to be the selfie king/queen and stands at the front.
- The rest of the squad (the other numbers) go off to figure out their own order (because they also have some ego, you know!).
- Once the smaller squad gets their permutations done, the front friend photobombs every one of those selfies. 📸😎
# 🔁 Swapping Roles
- Now, the front friend says, "Hey, I’ve been the star enough! Someone else’s turn!"
- The next friend steps forward, and the process repeats.
- After everyone has had their moment of glory at the front, the group’s permutation list is complete!
# 🧠 Algorithm Recap
- Keep one number in front, get permutations of the rest.
- Combine the front number with each permutation of the rest.
- Swap out the front number with others to get all combinations.
# 🕰️ Time Complexity:
Since the number of party pics (permutations) is n! (factorial), the complexity is:
$$O(n!)$$ - That’s a lot of selfies! 😅
# 💾 Space Complexity:
Also $$O(n!)$$ because we gotta save all those glorious selfie combinations!
# Code
```java []
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
dfs(nums, new boolean[nums.length], new ArrayList<>(), ans);
return ans;
}
private void dfs(int[] nums, boolean[] used, List<Integer> path, List<List<Integer>> ans) {
if (path.size() == nums.length) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; ++i) {
if (used[i])
continue;
used[i] = true;
path.add(nums[i]);
dfs(nums, used, path, ans);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
```
```python []
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 1:
return [nums[:]]
res = []
for _ in range(len(nums)):
n = nums.pop(0)
perms = self.permute(nums)
for p in perms:
p.append(n)
res.extend(perms)
nums.append(n)
return res
```
# UpVote

| 8 | 2 | ['Array', 'Backtracking', 'Java', 'Python3'] | 3 |
permutations | 100% beats|| CPP | 100-beats-cpp-by-sunny7549-k86t | Intuition :The problem requires generating all permutations of a given array of distinct integers.
Since the order of elements matters in permutations, backtrac | Sunny7549-_ | NORMAL | 2025-03-19T15:02:23.903654+00:00 | 2025-03-19T15:02:23.903654+00:00 | 695 | false | # Intuition :
The problem requires generating all permutations of a given array of distinct integers.
Since the order of elements matters in permutations, backtracking is an ideal approach to explore all possible arrangements.
We can build permutations incrementally by trying each element, marking it as used, and continuing to explore other elements recursively.
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach :
Backtracking Setup:
Create a helper function permutations that recursively generates all permutations.
Use a sub vector to keep track of the current permutation.
Use a used boolean vector to mark elements that are already included in the permutation.
Base Case:
If the size of sub equals the size of nums, push sub into result and return.
Recursive Case:
Loop through all elements of nums.
If an element is not used (used[i] == false), mark it as used, add it to sub, and recurse.
After recursion, backtrack by removing the last element from sub and marking the element as unused.
Final Permutations:
After exploring all possibilities, return the result vector containing all permutations.
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity: O(n!)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n!)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
void permutations(vector<vector<int>> &result, vector<int> &sub, vector<int> &num, vector<bool> &used) {
if(sub.size() == num.size()) {
result.push_back(sub);
return;
}
for(int i = 0; i < num.size(); i++) {
if(used[i]) continue;
used[i] = true;
sub.push_back(num[i]);
permutations(result, sub, num, used);
sub.pop_back();
used[i] = false;
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> result;
vector<int> sub;
vector<bool> used(nums.size(), false);
permutations(result, sub, nums, used);
return result;
}
};
``` | 8 | 3 | ['C++'] | 0 |
permutations | Python Solution | python-solution-by-a_bs-1rba | Permutation Intuition, Approach, and Complexity\n\nIntuition:\n\nImagine you have a box of distinct balls (the numbers). You want to find all the possible ways | 20250406.A_BS | NORMAL | 2024-05-24T18:28:22.228784+00:00 | 2024-05-24T18:28:22.228809+00:00 | 641 | false | ## Permutation Intuition, Approach, and Complexity\n\n**Intuition:**\n\nImagine you have a box of distinct balls (the numbers). You want to find all the possible ways to arrange them in a line (permutation). We can think of this as building the arrangements step-by-step. At each step, we choose a ball from the box (remaining numbers) and place it in a slot (current permutation). Once all the slots are filled (no remaining numbers), we have a complete permutation. We repeat this process, backtracking and trying different choices of balls at each step to explore all possibilities.\n\n**Approach:**\n\nWe\'ll use a Depth-First Search (DFS) to explore all possible arrangements. DFS is a technique that systematically explores a tree-like structure by following a single path until it reaches the end. In this case, the tree represents all possible choices for the permutation.\n\n1. Define a function `dfs` that takes two arguments:\n - `current_perm`: A list representing the current permutation being built.\n - `remaining`: A list of remaining numbers that can be included.\n2. If `remaining` is empty (no more choices), it means a complete permutation is reached. Add a copy of `current_perm` to the final list of permutations.\n3. Iterate through each number (`num`) in `remaining`.\n - Append `num` to `current_perm` (making a choice).\n - Make a recursive call to `dfs` with two arguments:\n - Updated `current_perm` with the added number.\n - A new `remaining` list excluding the used `num` (ensuring no duplicates).\n - After the recursive call (exploring that path), remove `num` from `current_perm` using `pop()` (backtracking). This allows us to explore other choices at the current step.\n\n**Complexity:**\n\n* **Time Complexity:** O(n * n!), where n is the number of elements in the list. This is because for each element, we explore n possibilities (recursive calls) in the worst case, leading to n! total permutations.\n* **Space Complexity:** O(n), due to the recursion stack that can grow up to n levels (one for each element in the permutation).\n\n\n# Code\n```\nclass Solution:\n def permute(self, nums: List[int]) -> List[List[int]]:\n """\n Finds all possible permutations of a list of distinct integers.\n\n Args:\n nums: A list of distinct integers.\n\n Returns:\n A list of lists, where each sublist represents a permutation.\n """\n permutations = []\n \n def dfs(current_perm, remaining):\n """\n Performs a Depth-First Search (DFS) to explore all permutations.\n\n Args:\n current_perm: A list representing the current permutation being built.\n remaining: A list of remaining integers to be included in the permutation.\n """\n if not remaining:\n permutations.append(current_perm.copy()) # Add complete permutation\n return\n \n for num in remaining:\n current_perm.append(num)\n dfs(current_perm, [i for i in remaining if i != num]) # Recursive call with remaining elements\n current_perm.pop() # Backtrack and remove the added element\n\n dfs([], nums)\n return permutations\n\n# Example usage\nnums = [1,2,3]\npermutations = Solution().permute(nums)\nprint(f"All permutations: {permutations}")\n\n```\n\n**Java** | 8 | 0 | ['Python3'] | 2 |
permutations | ✅✅C++ Easy Recursive and Backtracking Solution || Heavy commented | c-easy-recursive-and-backtracking-soluti-d7eg | \u2705\u2705C++ Easy Recursive and Backtracking Solution\n# Please Upvote as it really motivates me\n\n\nclass Solution {\npublic:\n void rec(int idx,vector< | Conquistador17 | NORMAL | 2023-08-02T05:03:59.689729+00:00 | 2023-08-02T05:03:59.689761+00:00 | 608 | false | ## **\u2705\u2705C++ Easy Recursive and Backtracking Solution**\n# **Please Upvote as it really motivates me**\n\n```\nclass Solution {\npublic:\n void rec(int idx,vector<int>&nums,vector<vector<int>>&ans){\n //if our index reached nums.size() then we will and the nums in ans and return\n if(idx==nums.size()){\n ans.push_back(nums);\n return;\n }\n //we are traversing from idx to nums.size() and swapping the nums[i] and nums[idx]\n for(int i=idx;i<nums.size();i++){\n swap(nums[idx],nums[i]);\n rec(idx+1,nums,ans);\n //backtracking \n swap(nums[idx],nums[i]);\n }\n }\n vector<vector<int>> permute(vector<int>& nums) {\n //we have created the ans vector for storing all the permutation in it\n vector<vector<int>>ans;\n //we are calling recursive function for the 0th index\n rec(0,nums,ans);\n return ans;\n }\n};\n```\n\n\n\n | 8 | 0 | ['Backtracking', 'Recursion', 'C', 'C++'] | 0 |
permutations | Backtracking || O(n!) Time and O(n!) Space || Easiest Beginner Friendly Sol | backtracking-on-time-and-on-space-easies-lfl5 | 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# Intuitio | singhabhinash | NORMAL | 2023-05-02T04:34:15.873295+00:00 | 2023-05-02T04:34:15.873336+00:00 | 1,204 | false | **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 :\n\n\n*The problem of generating all permutations of a given array can be solved using a recursive backtracking algorithm. The basic idea is to swap each element of the array with every other element in the array, and then recursively generate all permutations of the remaining elements. Once we have generated all permutations of the remaining elements, we swap the original elements back to restore the original order of the array.*\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Code :\n```C++ []\nclass Solution {\npublic:\n // Recursive helper function to generate permutations\n void helper(int l, int r, vector<int>& nums, vector<vector<int>>& ans) {\n // Base case: when left and right pointers are equal,\n // we have generated a permutation and add it to the answer.\n if (l == r) {\n ans.push_back(nums);\n return;\n }\n // Recursive case: for each index i in the range [l, r],\n // swap nums[l] with nums[i], generate permutations of the rest\n // of the array, and then swap back to restore original order.\n else {\n for (int i = l; i <= r; i++) {\n swap(nums[l], nums[i]); // Swap nums[l] with nums[i]\n helper(l+1, r, nums, ans); // Recursively generate permutations for remaining indices\n swap(nums[l], nums[i]); // Swap back to restore original order\n }\n }\n }\n // Main function to generate permutations\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> ans;\n helper(0, nums.size()-1, nums, ans); // Generate permutations starting from index 0 to n-1\n return ans;\n }\n};\n\n```\n\n# Time Complexity and Space Complexity:\n- **Time Complexity :** **O(n * n!)**, where n! is the number of permutations of an n-element array.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- **Space Complexity :** **O(n * n!)**, In the recursive helper function, we are using the call stack to store the state of each recursive call. The maximum depth of the call stack is n, which corresponds to the length of the input array.\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 8 | 0 | ['Array', 'Backtracking', 'C++'] | 0 |
permutations | Java - Explained - Multiple Approaches | java-explained-multiple-approaches-by-ja-587n | 1. Using extra space\n\nCreate two containers \n\t- First is for candidates for next permutations\n\t- Second is for storing current permutation\n\nNow let\'s c | jainakshat425 | NORMAL | 2022-04-29T04:09:19.183563+00:00 | 2022-04-29T04:09:19.183614+00:00 | 477 | false | **1. Using extra space**\n\nCreate two containers \n\t- First is for candidates for next permutations\n\t- Second is for storing current permutation\n\nNow let\'s consider we\'ve to generate all the permutations for [1,2,3]\n\nInitially we\'ll have - \nCandidates = [1,2,3] \nPermutation = []\n\nNow we\'ll call a recursive method for each number in the candidates, remove it from candidates, put it into the permutation and recurse for remaining candidates.\n\n// Method call 1\nLoop for **i=0 to 2**, remove first candidate and put into permutation\nCandidates = [2,3] \nPermutation = [1]\n\n// Method call 2\nNow 1 is fixed and we need to find possible permutations for [2,3] so we recurse for i=1 from here\nAgain loop from **i=0 to 1** as there are only two elements left, remove first candidate and put into permutation\nCandidates = [3] \nPermutation = [1,2]\n\n// Method call 3\nNow 1,2 is fixed and we need to find possible permutations for [3] so we recurse for i=2 from here\nLoop from **i=0 to 0** as there is only one element left, remove first candidate and put into permutation\nCandidates = [] \nPermutation = [1,2,3]\n\n// Method call 4\nSince first permutation is generated, put into the result and **back track to Method call 3.**\n\n// Method call 3\nRemove the last element from permutation and put it back into candidates and **back track to Method call 2.**\nCandidates = [3] \nPermutation = [1,2]\n\n// Method call 2\nRemove the last element from permutation and put it back into candidates and **continue the loop for index 1**\nCandidates = [2,3] \nPermutation = [1]\n\nremove second candidate and put into permutation\nCandidates = [2] \nPermutation = [1,3]\n\n// Method call 3\nNow 1,3 is fixed and we need to find possible permutations for [2] so we recurse for i=2 from here.\nLoop from **i=0 to 0** as there is only one element left, remove first candidate and put into permutation\nCandidates = [] \nPermutation = [1,3,2]\n\n// Method call 4\nSecond permutation is generated, put into the result and **back track to Method call 3.**\n\n// Method call 3\nRemove the last element from permutation and put it back into candidates and **back track to Method call 2.**\nCandidates = [2] \nPermutation = [1,3]\n\n// Method call 2\nRemove the last element from permutation and put it back into candidates and **back track to Method call 1 and loop finished.**\nCandidates = [2,3] \nPermutation = [1]\n\nNow method 1 will again repeat the same steps for index 1 and 2 as well. and will generate all the possible permutations.\n\n```\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n List<List<Integer>> result = new ArrayList<>();\n \n List<Integer> candidates = new ArrayList<>();\n \n for(int num : nums) {\n candidates.add( num );\n }\n \n permute(candidates, new ArrayList<>(), result);\n \n return result;\n }\n \n private void permute(List<Integer> candidates, List<Integer> permutation, List<List<Integer>> result) {\n \n // Since no number is left for permutation, a permutation is generated\n if( candidates.isEmpty() ) {\n result.add( new ArrayList<>( permutation ) );\n return;\n }\n \n int n = candidates.size();\n \n for(int i=0; i<n; i++) {\n int num = candidates.get(i);\n \n // Fix the current number\n permutation.add( num );\n \n // Remove the current number from candidates\n candidates.remove( i );\n \n // And permute for remaining numbers\n permute(candidates, permutation, result);\n \n // Add the number back to it\'s original index\n candidates.add(i, num );\n \n // Remove the number from the permutation\n permutation.remove( permutation.size() - 1 );\n }\n }\n}\n```\n\n**2. Using Swapping**\n\n```\nclass Solution {\n public List<List<Integer>> permute(int[] nums) {\n \n List<List<Integer>> result = new ArrayList<>();\n \n permute(nums, 0, result);\n \n return result;\n }\n \n private void permute(int[] nums, int start, List<List<Integer>> result) {\n int n = nums.length;\n \n // All the permutations in the current path has been generated.\n if( start == n ) {\n result.add( new ArrayList<>( arrayToList( nums ) ));\n return;\n }\n \n for(int i=start; i<n; i++) {\n \n /* Swap the current number with the number at start to \n generate next permutation */\n swap(nums, i, start);\n \n /* Fix the start, permute the number after start */\n permute(nums, start+1, result);\n \n /* Re-swap the current number with the number at start */\n swap(nums, i, start);\n }\n }\n \n private List<Integer> arrayToList(int[] arr) {\n List<Integer> lst = new ArrayList<>();\n for(int item : arr) {\n lst.add( item );\n }\n return lst;\n }\n \n private void swap(int[] arr, int i, int j) {\n if( i == j ) return;\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n}\n```\n | 8 | 0 | ['Java'] | 0 |
permutations | Simple and easy to understand C++ using recursion [98% faster, 100% memory] | simple-and-easy-to-understand-c-using-re-qb2u | \nclass Solution {\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> results;\n generatePermutations(0, &nums, | shlom | NORMAL | 2020-03-01T17:15:02.515691+00:00 | 2020-03-01T17:15:02.515726+00:00 | 1,155 | false | ```\nclass Solution {\npublic:\n vector<vector<int>> permute(vector<int>& nums) {\n vector<vector<int>> results;\n generatePermutations(0, &nums, &results);\n return results;\n }\nprivate:\n void generatePermutations(int i, vector<int>* nums_ptr, vector<vector<int>>* results) {\n auto& nums = *nums_ptr;\n if (i == nums.size() - 1) {\n results->emplace_back(nums);\n return;\n }\n \n for (int j = i; j < nums.size(); ++j) {\n std::swap(nums[i], nums[j]);\n generatePermutations(i + 1, nums_ptr, results);\n std::swap(nums[i], nums[j]);\n }\n }\n};\n``` | 8 | 0 | ['Recursion', 'C++'] | 2 |
permutations | Javascript solution +98% | javascript-solution-98-by-xueccc-f8hd | \nvar permute = function(nums) {\n\n let permutations = []\n \n let findPermutations = function(visited = new Set(), currPerm = []) {\n if (curr | xueccc | NORMAL | 2019-09-24T02:26:13.489776+00:00 | 2019-09-24T04:23:40.413212+00:00 | 2,240 | false | ```\nvar permute = function(nums) {\n\n let permutations = []\n \n let findPermutations = function(visited = new Set(), currPerm = []) {\n if (currPerm.length === nums.length) {\n permutations.push(currPerm)\n return\n }\n for (let i = 0; i < nums.length; i++) {\n if(!visited.has(i)) {\n findPermutations(new Set([...visited, i]), [...currPerm, nums[i]])\n }\n }\n }\n \n findPermutations()\n \n return permutations;\n \n};\n``` | 8 | 0 | ['JavaScript'] | 5 |
permutations | Easy solution for Kotlin | easy-solution-for-kotlin-by-vila_teissie-5p3i | \nclass Solution {\n private val result: MutableList<List<Int>> = mutableListOf()\n\n fun permute(nums: IntArray): List<List<Int>> {\n permuteAux(m | vila_teissiere | NORMAL | 2019-03-03T06:58:44.381628+00:00 | 2019-03-03T06:58:44.381709+00:00 | 301 | false | ```\nclass Solution {\n private val result: MutableList<List<Int>> = mutableListOf()\n\n fun permute(nums: IntArray): List<List<Int>> {\n permuteAux(mutableListOf(), nums.toList())\n return result\n }\n\n private fun permuteAux(added: List<Int>, left: List<Int>) {\n if (left.isEmpty()) {\n result.add(added)\n } else {\n left.forEach { candidate ->\n permuteAux(added + candidate, left - candidate)\n }\n }\n }\n}\n``` | 8 | 0 | [] | 3 |
permutations | Share My C++ backtracksolution | share-my-c-backtracksolution-by-allenyic-8qhz | \n class Solution {\n public:\n vector > permute(vector &num) {\n \tvector > res; // result\n \tvector flags( num.size(), false); | allenyick | NORMAL | 2015-01-18T04:18:47+00:00 | 2015-01-18T04:18:47+00:00 | 2,132 | false | \n class Solution {\n public:\n vector<vector<int> > permute(vector<int> &num) {\n \tvector<vector<int> > res; // result\n \tvector<bool> flags( num.size(), false); // bool, whether num[i] is choosed\n \tvector<int> path; // num have been choosed\n \tbacktrack(num, res, path, flags); //backtrack\n \treturn res;\t\n }\n \n void backtrack(vector<int> &num, vector<vector<int> > &res, \n \tvector<int> path,vector<bool> flags)\n {\n \tif( num.size() == path.size() )\n \t{\n \t\tres.push_back(path);\n \t}\n \telse\n \t{\n \t\tfor( int i = 0; i < num.size(); i++ )\n \t\t{\n \t\t\tif( flags[i] == true )\n \t\t\t\tcontinue;\n \t\t\telse\n \t\t\t{\n \t\t\t\tpath.push_back(num[i]);\n \t\t\t\tflags[i] = true;\n \t\t\t\tbacktrack( num, res, path, flags );\n \t\t\t\tflags[i] = false;\n \t\t\t\tpath.pop_back();\n \t\t\t}\n \t\t\t\n \t\t}\n \t}\n \n } | 8 | 0 | [] | 1 |
number-of-rectangles-that-can-form-the-largest-square | [Java/Python 3] 1 pass O(n) time O(1) space. | javapython-3-1-pass-on-time-o1-space-by-dzz5q | There are 3 cases after initializing the counter cnt and the max side mx as 0:\nThe square side\n1) greater than mx, reset cnt to 1 and update mx;\n2) == mx, i | rock | NORMAL | 2021-01-17T04:02:26.468401+00:00 | 2021-01-17T08:11:37.683699+00:00 | 5,539 | false | There are 3 cases after initializing the counter `cnt` and the max side `mx` as `0`:\nThe square side\n1) greater than `mx`, reset `cnt` to `1` and update `mx`;\n2) == `mx`, increase `cnt` by 1;\n3) less than `mx`, ignore it.\n\n\n```java\n public int countGoodRectangles(int[][] rectangles) {\n int cnt = 0, mx = 0;\n for (int[] rec : rectangles) {\n int side = Math.min(rec[0], rec[1]);\n if (side > mx) {\n cnt = 1;\n mx = side;\n }else if (side == mx) {\n ++cnt;\n }\n }\n return cnt;\n }\n```\n```python\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n cnt = mx = 0\n for l, w in rectangles:\n side = min(l, w)\n if side > mx:\n cnt, mx = 1, side\n elif side == mx:\n cnt += 1\n return cnt\n``` | 88 | 7 | [] | 11 |
number-of-rectangles-that-can-form-the-largest-square | JAVA || C++ || O(n) || FASTER THAN 100% || WITH MAP || WITHOUT MAP | java-c-on-faster-than-100-with-map-witho-rweu | C++\n\n1.using map\n\nRuntime: 36 ms, faster than 100.00% of C++ online submissions \nMemory Usage: 20.2 MB, less than 100.00% of C++ online submissions\n\n\ncl | rajat_gupta_ | NORMAL | 2021-01-17T05:58:27.348753+00:00 | 2021-01-17T06:33:43.658143+00:00 | 2,978 | false | **C++**\n\n**1.using map**\n\n**Runtime: 36 ms, faster than 100.00% of C++ online submissions \nMemory Usage: 20.2 MB, less than 100.00% of C++ online submissions**\n\n```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n unordered_map<int,int> map;\n for(vector<int> rectangle: rectangles){\n\t\t //storing number of time a particular square can obtain\n map[min(rectangle[0],rectangle[1])]++; //[4,6], you can cut it to get a square with a side length of at most 4.\n }\n int cnt=INT_MIN,maxlen=INT_MIN;\n for(auto m: map){\n if(m.first>maxlen) cnt=m.second,maxlen=m.first; //finding out the maxlength square then storing its count in cnt\n }\n return cnt;\n }\n};\n```\n**2.Without map**\n\n**Runtime: 48 ms, faster than 100.00% of C++ online submissions \nMemory Usage: 20.2 MB, less than 100.00% of C++ online submissions**\n\n```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n int cnt = 0, max = 0;\n for (vector<int>rectangle: rectangles) {\n\t\t//get the minimum from width and height\n int side = min(rectangle[0], rectangle[1]); //[4,6], you can cut it to get a square with a side length of at most 4.\n if (side > max) { //comparing max side with new side \n cnt = 1; // intialise count with 1\n max = side; //update the max by new side \n }else if (side == max) { // square with maxlength \n cnt++; //just increase the count of square with max len\n }\n }\n return cnt;\n }\n};\n```\n\n**JAVA**\n\n**1.Without map**\n\n**Runtime: 1 ms, faster than 100.00% of Java online submissions\nMemory Usage: 39.1 MB, less than 100.00% of Java online submissions**\n\n```\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int cnt = 0, max = 0;\n for (int []rectangle: rectangles) {\n\t //\tget the minimum from width and height\n int side = Math.min(rectangle[0], rectangle[1]); //[4,6], you can cut it to get a square with a side length of at most 4.\n if (side > max) { //comparing max side with new side \n cnt = 1; // intialise count with 1\n max = side; //update the max by new side \n }else if (side == max) { // square with maxlength \n cnt++; //just increase the count of square with max len\n }\n }\n return cnt;\n }\n}\n```\n\n**2.using map**\n\n**Runtime: 5 ms, faster than 80.00% of Java online submissions \nMemory Usage: 39.7 MB, less than 20.00% of Java online submissions** \n\n```\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n HashMap<Integer, Integer> map = new HashMap<>();\n int max = 0, ans = 0;\n for (int[] rectangle : rectangles) {\n int min = Math.min(rectangle[0], rectangle[1]); //get the minimum from width and height\n map.put(min, map.getOrDefault(min, 0) + 1);\n ans = (min >= max) ? map.get(min) : ans;\n max = Math.max(max, min);\n }\n return ans;\n }\n}\n```\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n | 26 | 3 | ['C', 'C++', 'Java'] | 6 |
number-of-rectangles-that-can-form-the-largest-square | ✅C++ solution with sorting! | c-solution-with-sorting-by-dhruba-datta-lm0z | If you\u2019re interested in coding you can join my Discord Server, link in the comment section. Also if you find any mistakes please let me know. Thank you!\u2 | dhruba-datta | NORMAL | 2021-10-21T06:51:13.579455+00:00 | 2022-04-14T19:15:17.588044+00:00 | 1,750 | false | > **If you\u2019re interested in coding you can join my Discord Server, link in the comment section. Also if you find any mistakes please let me know. Thank you!\u2764\uFE0F**\n> \n\n---\n## Code:\n\n```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n int count=0;\n vector<int>a;\n for(int i=0; i<rectangles.size();i++)\n {\n int m=rectangles[i][0], n=rectangles[i][1];\n int y=min(m,n);\n a.push_back(y);\n }\n sort(a.begin(),a.end());\n int n=a.size();\n int x=a[n-1];\n for(int i=0;i<n;i++)\n {\n if(a[i]==x)\n count++;\n }\n return count;\n }\n};\n```\n---\n***Please upvote if it was helpful for you, thank you!*** | 25 | 0 | ['C', 'C++'] | 4 |
number-of-rectangles-that-can-form-the-largest-square | [JAVA] easy and %100 solution | java-easy-and-100-solution-by-zeldox-cddj | if you like it pls upp vote\n\nJAVA\n\n\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int max = 0;\n int res = 0;\ | zeldox | NORMAL | 2021-02-07T14:36:12.453508+00:00 | 2021-02-07T14:36:12.453537+00:00 | 1,116 | false | if you like it pls upp vote\n\nJAVA\n\n```\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int max = 0;\n int res = 0;\n for(int i = 0;i< rectangles.length;i++){\n int key = Math.min(rectangles[i][0],rectangles[i][1]);\n if(key > max){\n res = 1;\n max = key;\n }\n else if (key == max){\n res++;\n }\n }\n \n return res;\n }\n}\n``` | 20 | 1 | ['Java'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | Python - Runtime O(N) and O(1) space [ACCEPTED] | python-runtime-on-and-o1-space-accepted-xyqzq | This can be done just by tracking the max length and its count.\n\n```\ndef countGoodRectangles(rectangles):\n\tmax_len = float(\'-inf\')\n\tcount = 0\n\tfor it | jankit | NORMAL | 2021-01-17T12:51:18.817995+00:00 | 2021-01-17T13:49:13.189560+00:00 | 1,944 | false | This can be done just by tracking the max length and its count.\n\n```\ndef countGoodRectangles(rectangles):\n\tmax_len = float(\'-inf\')\n\tcount = 0\n\tfor item in rectangles:\n\t\tmin_len = min(item)\n\t\tif min_len == max_len:\n\t\t\tcount += 1\n\t\telif min_len > max_len:\n\t\t\tmax_len = min_len\n\t\t\tcount = 1\n\n\treturn count | 20 | 0 | ['Python3'] | 6 |
number-of-rectangles-that-can-form-the-largest-square | c++ solution || O(n) | c-solution-on-by-yash_pal2907-b73p | \nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n unordered_map<int,int> maxsquarelen;\n int maxlen=IN | yash_pal2907 | NORMAL | 2021-01-17T05:11:40.971541+00:00 | 2021-01-17T05:11:40.971576+00:00 | 1,451 | false | ```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n unordered_map<int,int> maxsquarelen;\n int maxlen=INT_MIN;\n for(auto rectangle : rectangles){\n maxsquarelen[min(rectangle[0],rectangle[1])]++;\n maxlen = max(maxlen,min(rectangle[0],rectangle[1]));//store the maxpossible length of square formed\n }\n return maxsquarelen[maxlen];\n //return ;\n }\n};\n``` | 11 | 1 | ['C'] | 1 |
number-of-rectangles-that-can-form-the-largest-square | Python easier solution with explanation (dictionary) | python-easier-solution-with-explanation-h2gi0 | Explanation:\nTo get maximum square from rectangle we get the minimum from width and height. By dictionary we count all squares, and the value of the biggest | it_bilim | NORMAL | 2021-01-17T06:12:18.570237+00:00 | 2021-01-17T06:12:18.570290+00:00 | 878 | false | **Explanation:**\nTo get `maximum square` from rectangle we get the minimum from `width` and `height`. By dictionary we count `all squares`, and the `value` of `the biggest square`.\n\n```\ndef countGoodRectangles(self, rectangles):\n t = {}\n for r in rectangles:\n p = min(r) # get the minimum from width and height\n if p in t:\n t[p] += 1 # increase the value of square if the square already exists in dict.\n else:\n t[p] = 1 # add new square to dict\n return t[max(t.keys())] # get the value of the biggest square\n``` | 10 | 5 | ['Python', 'Python3'] | 1 |
number-of-rectangles-that-can-form-the-largest-square | C++ 32 ms | c-32-ms-by-eridanoy-jr4f | \nclass Solution {\npublic:\n int countGoodRectangles(const vector<vector<int>>& rectangles) {\n \n int side=0, maxLen=0, count=0;\n \n | eridanoy | NORMAL | 2021-01-20T20:25:03.168981+00:00 | 2021-01-20T20:25:03.169013+00:00 | 674 | false | ```\nclass Solution {\npublic:\n int countGoodRectangles(const vector<vector<int>>& rectangles) {\n \n int side=0, maxLen=0, count=0;\n \n for(const auto& i:rectangles) {\n \n side=min(i[0],i[1]);\n \n if(maxLen<side) {\n maxLen=side;\n count=1;\n }\n else if(maxLen==side) ++count;\n }\n \n return count;\n }\n};\n``` | 9 | 0 | ['C'] | 1 |
number-of-rectangles-that-can-form-the-largest-square | Python 2 liner solution with explanation | python-2-liner-solution-with-explanation-c712 | \n######################################################\n\n# Runtime: 168ms - 100.00%\n# Memory: 14.8MB - 73.29%\n\n################################ | saisasank25 | NORMAL | 2022-01-15T07:46:25.332888+00:00 | 2022-01-15T07:46:25.332935+00:00 | 563 | false | ```\n######################################################\n\n# Runtime: 168ms - 100.00%\n# Memory: 14.8MB - 73.29%\n\n######################################################\n\nclass Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n # len_arr is a list where len_arr[i] is the max length of the square\n # that can be formed using rectangle[i] which will be min of length\n # and breadth of that rectangle\n len_arr = [min(rectangle) for rectangle in rectangles]\n # To find how many squares have max len, we first have to find the\n # max len. So, max(len_arr). Now, we need to count how many max len\n # are present in len_arr. So, len_arr.count(max(len_arr)) which is \n # the required answer. so we return it\n return len_arr.count(max(len_arr))\n``` | 8 | 0 | ['Python'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | Simple and effective Javascript Solution | simple-and-effective-javascript-solution-5bgf | \nvar countGoodRectangles = function(rectangles) {\n let max = 0;\n let count = 0;\n \n for(let i = 0; i < rectangles.length; i++) {\n let mi | kosbay12 | NORMAL | 2021-03-28T07:42:23.071145+00:00 | 2021-03-28T07:42:23.071232+00:00 | 592 | false | ```\nvar countGoodRectangles = function(rectangles) {\n let max = 0;\n let count = 0;\n \n for(let i = 0; i < rectangles.length; i++) {\n let minSide = Math.min(rectangles[i][0], rectangles[i][1])\n \n if(minSide > max) {\n count = 0\n max = minSide\n } \n \n if(minSide === max) count++\n }\n \n return count\n};\n``` | 6 | 0 | ['JavaScript'] | 2 |
number-of-rectangles-that-can-form-the-largest-square | Easiest C++ Solution without Sorting ✅ | easiest-c-solution-without-sorting-by-_s-nq5l | Intuition\nThe code first calculates the largest square that can be cut from each rectangle by taking the minimum of the rectangle\'s length and width. It then | _sxrthakk | NORMAL | 2024-08-02T10:47:05.920777+00:00 | 2024-08-02T10:47:05.920809+00:00 | 164 | false | # Intuition\nThe code first calculates the largest square that can be cut from each rectangle by taking the minimum of the rectangle\'s length and width. It then uses an unordered map to count how many times each square size appears. The code then iterates through the map to find the maximum square size (a) and stores the count (b) of how many rectangles can form this maximum square. Finally, it returns this count (b), which represents the number of rectangles that can form the largest square.\n\n# Approach\n1. Create a Map for Square Sizes: Iterate over each rectangle and determine the side length of the largest square it can form by taking the minimum of the two dimensions. Store these lengths in a map where the key is the side length and the value is the count of rectangles that can produce this square.\n2. Identify the Maximum Square Size: After populating the map, identify the largest square side length by iterating through the keys of the map.\n3. Count Rectangles for Max Square: Once the maximum square side length is determined, return the count of rectangles that can form this square, which is stored in the map.\n\n\n# Code Walkthrough \n1. The first loop populates the map m, where each key is the side length of the largest square that can be formed from a rectangle, and the value is the number of rectangles that can form that square.\n2. The second loop checks each key in the map to find the maximum square size (a) and retrieves the count (b) associated with that size.\n3. Finally, b is returned as it represents the number of rectangles that can form the largest square.\n\n# Time complexity : O(n)\n\n# Space complexity : O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& v){\n unordered_map<int,int> m;\n\n for(int i=0;i<v.size();i++){\n m[min(v[i][0],v[i][1])]++;\n }\n\n int a=INT_MIN,b=-1;\n for(auto x : m){\n if(x.first>a){\n a=x.first;\n b=x.second;\n }\n }\n \n return b;\n }\n};\n``` | 5 | 0 | ['Array', 'Hash Table', 'C++'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | solution | solution-by-vibishraj-rlaa | 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 | Vibishraj | NORMAL | 2024-07-10T16:44:37.339317+00:00 | 2024-07-10T16:44:37.339353+00:00 | 32 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int[] arr=new int[rectangles.length];\n for(int i=0;i<rectangles.length;i++)\n {\n arr[i]=Math.min(rectangles[i][0],rectangles[i][1]);\n }\n int max=0,count=0;\n for(int i=0;i<arr.length;i++)\n {\n if(max<arr[i])\n max=arr[i];\n }\n for(int i=0;i<arr.length;i++)\n {\n if(arr[i]==max)\n count++;\n }\n return count;\n }\n}\n``` | 5 | 0 | ['Java'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | Java Simple Solution 1 ms - 100% beats | java-simple-solution-1-ms-100-beats-by-a-dyls | Approach\nYou first have to create an array called "sides" to store the side lengths of each rectangle. Then, you iterate through the given "rectangles" array a | akobirswe | NORMAL | 2023-05-24T16:09:36.324774+00:00 | 2023-05-24T16:09:36.324809+00:00 | 406 | false | # Approach\nYou first have to create an array called "sides" to store the side lengths of each rectangle. Then, you iterate through the given "rectangles" array and compare the length and width of each rectangle. If the length is smaller than the width, you assign the length to the corresponding index in the "sides" array; otherwise, you assign the width.\n\nNext, you initialize two variables, "count" and "maxLen," where "count" keeps track of the count of rectangles that can form the largest square, and "maxLen" represents the maximum side length of the square.\n\nAfter populating the "sides" array, you iterate through it to find the maximum side length. For each element (num) in the "sides" array, if the current side length is greater than the current maximum (maxLen), you update the value of "maxLen" accordingly.\n\nFinally, you iterate through the "sides" array again and increment the "count" variable by 1 for each side length that matches the maximum side length (maxLen). This counts the number of rectangles that can form the largest square.\n\nIn the end, you return the value of "count" as the result, representing the number of rectangles that can make a square with a side length equal to the maximum side length obtained.\n\n---\n\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int[] sides = new int[rectangles.length];\n int count = 0;\n int maxLen = 0;\n for (int i = 0; i < rectangles.length; i++) {\n if (rectangles[i][0] < rectangles[i][1])\n sides[i] = rectangles[i][0];\n else\n sides[i] = rectangles[i][1];\n }\n\n for (int num : sides)\n if(num > maxLen) maxLen = num;\n\n for(int num : sides)\n if(num == maxLen) count++;\n\n return count;\n }\n}\n``` | 5 | 0 | ['Array', 'Java'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | C++ solution || easy to understand! | c-solution-easy-to-understand-by-mohiter-66em | ```\nclass Solution {\npublic:\n int countGoodRectangles(vector>& rect) {\n vectorans;\n int c=0;\n for(int i=0;i<rect.size();i++){\n | mohiteravi348 | NORMAL | 2022-12-03T11:33:45.951005+00:00 | 2022-12-03T11:33:45.951032+00:00 | 390 | false | ```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rect) {\n vector<int>ans;\n int c=0;\n for(int i=0;i<rect.size();i++){\n \n ans.push_back(*min_element(rect[i].begin(),rect[i].end()));\n \n \n }\n \n int m=*max_element(ans.begin(),ans.end());\n for(int i=0;i<ans.size();i++){\n \n if(ans[i]==m)c++;\n }\n return c;\n }\n}; | 5 | 0 | ['C'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | simple O(n) using HashMap | simple-on-using-hashmap-by-armageddon203-d4fo | \nvar countGoodRectangles = function (rectangles) {\n let map = new Map(),max=0;\n rectangles.forEach(el => {\n max=Math.max(max,Math.min(el[0], el[1]));\n | armageddon2033 | NORMAL | 2021-01-17T12:02:35.756364+00:00 | 2021-01-17T12:02:35.756394+00:00 | 394 | false | ```\nvar countGoodRectangles = function (rectangles) {\n let map = new Map(),max=0;\n rectangles.forEach(el => {\n max=Math.max(max,Math.min(el[0], el[1]));\n map.set(Math.min(el[0], el[1]), map.get(Math.min(el[0], el[1])) + 1 || 1);\n });\n return map.get(max);\n};\n``` | 5 | 0 | ['JavaScript'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | C++ code in linear time || Faster then others | c-code-in-linear-time-faster-then-others-zrbl | \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 | Shristha | NORMAL | 2023-01-10T15:37:16.883119+00:00 | 2023-01-10T15:37:16.883171+00:00 | 692 | false | \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```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n int max_len=min(rectangles[0][0],rectangles[0][1]),cnt=1;\n for(int i=1;i<rectangles.size();i++){\n int min_len= min(rectangles[i][0],rectangles[i][1]);\n if(min_len==max_len){\n cnt++;\n }else if(min_len>max_len){\n max_len=min_len;\n cnt=1;\n }\n }\n return cnt;\n\n \n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | C++ easy solution for beginner | c-easy-solution-for-beginner-by-richach1-jltk | \nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n vector<int> vec;\n int mini=INT_MAX;\n int co | Richach10 | NORMAL | 2022-05-14T22:33:19.455115+00:00 | 2022-05-14T22:46:01.792510+00:00 | 455 | false | ```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n vector<int> vec;\n int mini=INT_MAX;\n int count=1;\n for(int i=0;i<rectangles.size();i++){\n mini=min(rectangles[i][0],rectangles[i][1]);\n vec.push_back(mini);\n } \n sort(vec.begin(),vec.end(), greater<int>());\n int first=vec[0];\n for(int i=1;i<vec.size();i++){\n if(first==vec[i]){\n count++;\n }\n }\n return count; \n }\n};\n\n/* steps: 1- find the min value for every row\n 2- sort it int descendin order\n 3- increase the pointer if the value is similar to \n the value at first index and increase the counter. */\n\t\t \n\t\t // ****** second solution- optimized: ***************\n\t\t class Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n int mini=INT_MAX;\n int maxi=INT_MIN;\n int count=1;\n for(int i=0;i<rectangles.size();i++){\n mini=min(rectangles[i][0],rectangles[i][1]);\n if(mini>maxi){\n maxi=mini;\n count=1;\n }\n else if(mini==maxi){\n count++;\n }\n } \n return count; \n }\n};\n``` | 4 | 0 | ['C', 'C++'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | C++ | Simple O(N) two pass solution | c-simple-on-two-pass-solution-by-sekhar1-h33p | Find max possible square out of all rectangles\n2. Find all rectangles matching max square found in step 1\n\nclass Solution {\npublic:\n int countGoodRectan | sekhar179 | NORMAL | 2021-01-17T04:13:36.051145+00:00 | 2021-01-17T04:13:36.051178+00:00 | 296 | false | 1. Find max possible square out of all rectangles\n2. Find all rectangles matching max square found in step 1\n```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n int cnt = 0;\n int maxLen = 0;\n for (auto it: rectangles) {\n int len = min(it[0], it[1]);\n maxLen = max(maxLen, len);\n }\n for (auto it: rectangles) {\n int len = min(it[0], it[1]);\n if (len == maxLen)\n cnt++;\n }\n return cnt;\n }\n};\n``` | 4 | 0 | ['C'] | 1 |
number-of-rectangles-that-can-form-the-largest-square | Java O(n) Solution | java-on-solution-by-mayank_pratap-2l0e | \nhttps://achievementguru.com/leetcode-1725-number-of-rectangles-that-can-form-the-largest-square-java-solution/\n\nclass Solution {\n public int countGoodRe | mayank_pratap | NORMAL | 2021-01-17T04:03:05.210357+00:00 | 2021-01-17T04:10:47.328544+00:00 | 542 | false | \nhttps://achievementguru.com/leetcode-1725-number-of-rectangles-that-can-form-the-largest-square-java-solution/\n```\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int [] sq = new int[rectangles.length];\n \n for(int i=0;i<rectangles.length;i++)\n sq[i]=Math.min(rectangles[i][0],rectangles[i][1]);\n \n \n int count = 0;\n int max =sq[0];\n for(int i=0;i<sq.length;i++)\n if(sq[i]>max)\n max=sq[i];\n \n for(int i=0;i<sq.length;i++){\n if(sq[i]==max)\n count++;\n \n }\n \n return count;\n \n }\n}\n``` | 4 | 1 | ['Java'] | 2 |
number-of-rectangles-that-can-form-the-largest-square | Easiest C++ Solution || Beginner Friendly || Hashmap || Without using sorting || O(N) | easiest-c-solution-beginner-friendly-has-azko | Intuition\n Describe your first thoughts on how to solve this problem. \nTo maximize the side length of a square that can fit in each rectangle, use the smaller | dilpreetchhabra76 | NORMAL | 2024-12-07T23:38:12.056920+00:00 | 2024-12-07T23:38:12.056951+00:00 | 81 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo maximize the side length of a square that can fit in each rectangle, use the smaller dimension of the rectangle. Count how many rectangles can form squares with the largest possible side length.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Iterate through the list of rectangles and calculate the maximum square side length possible for each rectangle.\n2) Use a hashmap (unordered_map) to store the count of occurrences for each square side length.\n3) Traverse the hashmap to find the largest square side length and return its count.\n4) This approach ensures efficient computation with a time complexity of O(n), where n is the number of rectangles.\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```cpp []\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n // Get the number of rectangles\n int n = rectangles.size();\n \n // Variable to track the maximum side length of the square\n int maxLen = INT_MIN;\n \n // Hashmap to count occurrences of each square side length\n unordered_map<int, int> mpp;\n \n // Iterate through each rectangle\n for (int i = 0; i < n; i++) {\n // Calculate the maximum square side length for this rectangle\n int side = min(rectangles[i][0], rectangles[i][1]);\n \n // Increment the count for this side length in the map\n mpp[side]++;\n }\n \n // Variable to store the count of rectangles forming the largest squares\n int num;\n \n // Traverse the hashmap to find the maximum side length and its count\n for (auto it : mpp) {\n if (it.first > maxLen) {\n maxLen = it.first; // Update the maximum side length\n num = it.second; // Update the count of rectangles\n }\n }\n \n // Return the count of rectangles forming the largest squares\n return num;\n }\n};\n\n``` | 3 | 0 | ['C++'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | [python|| O(N)] | python-on-by-sneh713-xw4p | 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 | Sneh713 | NORMAL | 2022-10-16T14:20:21.967182+00:00 | 2022-10-16T14:20:21.967230+00:00 | 453 | false | # 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- O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n max_len = float(\'-inf\')\n count = 0\n for item in rectangles:\n min_len = min(item)\n if min_len == max_len:\n count += 1\n elif min_len > max_len:\n max_len = min_len\n count = 1\n\n return count\n``` | 3 | 0 | ['Python3'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | Beginner friendly JavaScript Solution | beginner-friendly-javascript-solution-by-9s7n | Time Complexity : O(n)\n\n/**\n * @param {number[][]} rectangles\n * @return {number}\n */\nvar countGoodRectangles = function(rectangles) {\n let count = 0, | HimanshuBhoir | NORMAL | 2022-01-26T12:12:07.731686+00:00 | 2022-01-26T12:12:07.731716+00:00 | 230 | false | **Time Complexity : O(n)**\n```\n/**\n * @param {number[][]} rectangles\n * @return {number}\n */\nvar countGoodRectangles = function(rectangles) {\n let count = 0, max = 0;\n for(let rec of rectangles){\n let len = Math.min(rec[0], rec[1]);\n if(len > max){\n count = 1;\n max = len;\n }else if(len == max){\n count++;\n }\n }\n return count;\n};\n``` | 3 | 0 | ['JavaScript'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | [Java] O(n) time, O(1) space | java-on-time-o1-space-by-alibekkarimov-qa34 | \nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int count=0, maxLen=Math.min(rectangles[0][0],rectangles[0][1]);\n | AlibekKarimov | NORMAL | 2021-10-07T14:55:09.504432+00:00 | 2021-10-07T14:55:09.504462+00:00 | 141 | false | ```\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int count=0, maxLen=Math.min(rectangles[0][0],rectangles[0][1]);\n for(int i=0;i<rectangles.length;i++){\n int curLen = Math.min(rectangles[i][0],rectangles[i][1]);\n if(curLen==maxLen) count++;\n else if(curLen>maxLen) {\n count=1;\n maxLen=curLen;\n }\n }\n return count;\n }\n}\n``` | 3 | 0 | [] | 0 |
number-of-rectangles-that-can-form-the-largest-square | [Java] solution without map beats 100% | java-solution-without-map-beats-100-by-v-wnyr | \nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int max = 0;\n int count = 0;\n for (int[] r : rectangles){\ | vinsinin | NORMAL | 2021-03-16T06:16:15.157500+00:00 | 2021-03-16T06:16:15.157545+00:00 | 223 | false | ```\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int max = 0;\n int count = 0;\n for (int[] r : rectangles){\n int min = Math.min(r[0], r[1]);\n if (min > max){\n max = min;\n count = 1;\n }\n else if (min == max) count++;\n }\n return count;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | Java Solution beats 100% | T.C-O(n) S.C-O(1) | java-solution-beats-100-tc-on-sc-o1-by-l-kdlf | \n public int countGoodRectangles(int[][] rectangles) {\n \n\t\tint ans = -1;\n\t\tint count = 0;\n\n\t\tfor (int[] rectangle : rectangles) {\n\n\t\t\ | LegendaryCoder | NORMAL | 2021-01-21T06:20:16.397122+00:00 | 2021-01-21T06:20:16.397154+00:00 | 199 | false | \n public int countGoodRectangles(int[][] rectangles) {\n \n\t\tint ans = -1;\n\t\tint count = 0;\n\n\t\tfor (int[] rectangle : rectangles) {\n\n\t\t\tint min = Math.min(rectangle[0], rectangle[1]);\n\t\t\tif (min > ans) {\n\t\t\t\tans = min;\n\t\t\t\tcount = 1;\n\t\t\t} else if (min == ans)\n\t\t\t\tcount++;\n\t\t}\n\n\t\treturn count;\n }\n | 3 | 0 | [] | 1 |
number-of-rectangles-that-can-form-the-largest-square | Simple JavaScript Solution | simple-javascript-solution-by-crazyspyde-64jr | \nvar countGoodRectangles = function(rectangles) {\n let count = 0\n let max = 0\n \n for(let i of rectangles){\n let side = Math.min(i[0], i | crazyspyder2020 | NORMAL | 2021-01-17T07:53:12.587593+00:00 | 2021-01-17T07:53:12.587632+00:00 | 276 | false | ```\nvar countGoodRectangles = function(rectangles) {\n let count = 0\n let max = 0\n \n for(let i of rectangles){\n let side = Math.min(i[0], i[1])\n if(side > max){\n max = side\n count = 1\n } else if(side == max) {\n count++\n }\n }\n return count\n};\n``` | 3 | 0 | ['JavaScript'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | [C++] O(N) Time O(1) Space Solution | c-on-time-o1-space-solution-by-davidchai-5v6h | Idea:\nWe traverse the whole vector. For each rectangle\'s maxLen curLen, we compare it with the global maxLen maxLen. If\n curLen > maxLen, we know the maxLen | davidchai | NORMAL | 2021-01-17T04:13:25.315575+00:00 | 2021-01-17T04:13:46.774090+00:00 | 133 | false | Idea:\nWe traverse the whole vector. For each rectangle\'s maxLen `curLen`, we compare it with the global maxLen `maxLen`. If\n* `curLen > maxLen`, we know the `maxLen` should be updated.\n* `curLen == maxLen`, we know we should `++res`.\n* Otherwise, we just ignore.\n\n```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n int maxLen = 0;\n int res = 0;\n for (vector<int>& r : rectangles) {\n int curLen = min(r[0], r[1]);\n if (maxLen < curLen) {\n res = 1;\n maxLen = curLen;\n } else if (maxLen == curLen) ++res;\n }\n return res;\n }\n};\n``` | 3 | 1 | ['C'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | [Python3] freq table | python3-freq-table-by-ye15-serv | Algo\nFor each pair of l and w, collect the frequency table of min(l, w). Return the freq of max of such min. \n\nImplementation\n\nclass Solution:\n def cou | ye15 | NORMAL | 2021-01-17T04:03:30.523534+00:00 | 2021-01-17T04:03:30.523564+00:00 | 375 | false | **Algo**\nFor each pair of `l` and `w`, collect the frequency table of `min(l, w)`. Return the freq of max of such min. \n\n**Implementation**\n```\nclass Solution:\n def countGoodRectangles(self, rectangles: List[List[int]]) -> int:\n freq = {}\n for l, w in rectangles: \n x = min(l, w)\n freq[x] = 1 + freq.get(x, 0)\n return freq[max(freq)]\n```\n\n**Analysis**\nTime complexity `O(N)`\nSpace complexity `O(N)` | 3 | 0 | ['Python3'] | 2 |
number-of-rectangles-that-can-form-the-largest-square | C solution | c-solution-by-pavithrav25-523p | Code | pavithrav25 | NORMAL | 2025-01-17T14:52:03.601702+00:00 | 2025-01-17T14:52:03.601702+00:00 | 31 | false |
# Code
```c []
int countGoodRectangles(int** r, int n, int* c) {
int max = 0, cnt = 0;
for (int i = 0; i < n; i++) {
int side = r[i][0] < r[i][1] ? r[i][0] : r[i][1];
if (side > max) {
max = side;
cnt = 1;
} else if (side == max) {
cnt++;
}
}
return cnt;
}
``` | 2 | 0 | ['C'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | Rust || beats 100% || 0ms | rust-beats-100-0ms-by-user7454af-bjce | Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nimpl Solution {\n pub fn count_good_rectangles(rectangles: Vec<Vec<i32>>) -> i32 | user7454af | NORMAL | 2024-06-06T20:43:50.054574+00:00 | 2024-06-06T20:43:50.054603+00:00 | 39 | false | # Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nimpl Solution {\n pub fn count_good_rectangles(rectangles: Vec<Vec<i32>>) -> i32 {\n let mut max_side = 0;\n let mut count = 0;\n for rect in rectangles.iter() {\n let mut side = std::cmp::min(rect[0], rect[1]);\n if max_side == side {\n count += 1;\n } else if side > max_side {\n max_side = side;\n count = 1;\n }\n }\n count\n }\n}\n``` | 2 | 0 | ['Rust'] | 1 |
number-of-rectangles-that-can-form-the-largest-square | Easy C++ Solution | easy-c-solution-by-adityagarg217-wgod | class Solution {\npublic:\n\n int countGoodRectangles(vector>& rectangles) {\n \n\t vector ans ; \n for(int i=0 ; irectangles[i][1]){\n | adityagarg217 | NORMAL | 2023-06-05T11:38:36.558071+00:00 | 2023-06-05T11:52:29.614846+00:00 | 196 | false | class Solution {\npublic:\n\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n \n\t vector<int> ans ; \n for(int i=0 ; i<rectangles.size();i++){\n if(rectangles[i][0]>rectangles[i][1]){\n ans.push_back(rectangles[i][1]);\n }else \n ans.push_back(rectangles[i][0]);\n }\n int max = INT_MIN;\n for(int i=0 ; i<ans.size();i++){\n if(ans[i]>max){\n max= ans[i];\n } }\n int count = 0 ; \n for(int i=0 ; i<ans.size() ; i++){\n if(ans[i]==max){\n count ++ ;}\n }\n return count ; \n }\n}; | 2 | 0 | [] | 0 |
number-of-rectangles-that-can-form-the-largest-square | Simple JAVA Solution for beginners. 2ms. Beats 92.57%. | simple-java-solution-for-beginners-2ms-b-8nhy | 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 | sohaebAhmed | NORMAL | 2023-05-09T02:23:19.039519+00:00 | 2023-05-09T02:23:19.039565+00:00 | 272 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countGoodRectangles(int[][] rectangles) {\n int maxLength = 0;\n int minLength;\n int count = 0;\n for(int i = 0; i < rectangles.length; i++) {\n minLength = Integer.min(rectangles[i][0], rectangles[i][1]);\n if(maxLength < minLength) {\n maxLength = minLength;\n count = 1;\n } else if(maxLength == minLength) {\n count++;\n }\n }\n return count;\n }\n}\n``` | 2 | 0 | ['Array', 'Java'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | C++ solution || O(n) || Using Map | c-solution-on-using-map-by-surya_2101-o0xy | \nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n int max_area=0;\n unordered_map<int,int>m;\n | Surya-2101 | NORMAL | 2023-03-29T17:34:26.654652+00:00 | 2023-03-29T17:34:26.654703+00:00 | 36 | false | ```\nclass Solution {\npublic:\n int countGoodRectangles(vector<vector<int>>& rectangles) {\n int max_area=0;\n unordered_map<int,int>m;\n for(int i=0;i<rectangles.size();i++)\n {\n int l=rectangles[i][0];\n int w=rectangles[i][1];\n int mini=min(l,w);\n max_area=max(mini,max_area);\n m[mini]++;\n }\n return m[max_area];\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
number-of-rectangles-that-can-form-the-largest-square | JavaScript Time O(n) Space O(n) with HashTable | javascript-time-on-space-on-with-hashtab-rfje | Approach\nSearch through each rectangles, find the smaller side, and add one to the count number(With hash), compare to the maximum width. Return the count numb | uncle30402 | NORMAL | 2023-01-25T15:11:02.918239+00:00 | 2023-01-25T15:11:02.918287+00:00 | 296 | false | # Approach\nSearch through each rectangles, find the smaller side, and add one to the count number(With hash), compare to the maximum width. Return the count number of the largest width.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[][]} rectangles\n * @return {number}\n */\nvar countGoodRectangles = function(rectangles) {\n let widthHash = {}\n let maxWidth = 0\n\n for(let rectangle of rectangles){\n let min = Math.min(rectangle[0], rectangle[1])\n addToHash(min)\n setMax(min)\n }\n\n return widthHash[maxWidth]\n\n function addToHash(val){\n if(!widthHash[val]){\n widthHash[val] = 1\n }else{\n widthHash[val]++\n }\n }\n\n function setMax(val){\n if(val > maxWidth){\n maxWidth = val\n }\n }\n \n};\n``` | 2 | 0 | ['JavaScript'] | 2 |
number-of-rectangles-that-can-form-the-largest-square | java | java-by-niyazjava-1274 | \n public static int countGoodRectangles(int[][] rectangles) {\n int count = 0, max = 0;\n\n for (int i = 0; i < rectangles.length; i++) {\n | NiyazJava | NORMAL | 2022-10-14T08:39:43.473557+00:00 | 2022-10-14T08:39:43.473584+00:00 | 229 | false | ```\n public static int countGoodRectangles(int[][] rectangles) {\n int count = 0, max = 0;\n\n for (int i = 0; i < rectangles.length; i++) {\n int min = Math.min(rectangles[i][0], rectangles[i][1]);\n\n if (min > max) {\n max = min;\n count = 1;\n } else if (min == max) {\n count++;\n }\n\n }\n\n return count;\n }\n``` | 2 | 0 | ['Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.