title
stringlengths 1
100
| titleSlug
stringlengths 3
77
| Java
int64 0
1
| Python3
int64 1
1
| content
stringlengths 28
44.4k
| voteCount
int64 0
3.67k
| question_content
stringlengths 65
5k
| question_hints
stringclasses 970
values |
|---|---|---|---|---|---|---|---|
Python Top Down + Bottom Up
|
longest-palindromic-subsequence
| 0
| 1
|
# Approach\nTop Down is intuitive. Start from outside and work your way inside. Bottom Up is less intuitive, and is technically less efficient too since we check irrelevant states. For example, if the word is "bab", the Top Down approach would go from (0, 2) to (1,1). Whereas the Bottom Up approach would check (2,2), (1,1), (1,2), (0,0), (0,1), (0, 2).\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N^2), where N = len(s). This is because there are N^2 pairings of left and right.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N^2) for the cache or dp table. Top Down requires extra O(N) for recusion.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n\n @cache\n def dfs(l, r):\n\n if l == r:\n return 1\n\n if l > r:\n return 0\n\n if s[l] == s[r]:\n return 2 + dfs(l + 1, r - 1)\n else:\n return max(dfs(l + 1, r), dfs(l, r - 1))\n \n return dfs(0, len(s) - 1)\n```\n```\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n \n dp = [([0] * len(s)) for _ in range(len(s))]\n\n for left in range(len(s) - 1, -1, -1):\n\n dp[left][left] = 1\n\n for right in range(left + 1, len(s)):\n\n if s[left] == s[right]:\n dp[left][right] = 2 + dp[left + 1][right - 1]\n else:\n dp[left][right] = max(dp[left + 1][right], dp[left][right - 1])\n\n return dp[0][len(s) - 1]\n```\n
| 1
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
Python3 Solution
|
longest-palindromic-subsequence
| 0
| 1
|
\n```\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n n=len(s)\n m=[[1 for x in range(n)] for y in range(n)]\n for ss in range(1,n):\n for i in range(n-ss):\n j=i+ss\n if s[i]==s[j] and ss==1:\n m[i][j]=2\n\n elif s[i]==s[j]:\n m[i][j]=m[i+1][j-1]+2\n\n else:\n m[i][j]=max(m[i+1][j],m[i][j-1])\n\n\n return m[0][-1] \n```
| 1
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
Python solution
|
longest-palindromic-subsequence
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n n = len(s)\n prev = [0] * n\n prev[n-1] = 1\n for i in range(n-2, -1, -1):\n curr = [0] * n\n curr[i] = 1\n for j in range(i+1, n):\n x = 0\n if s[i] == s[j]:\n x = prev[j-1] + 2\n y = max(prev[j], curr[j-1])\n curr[j] = max(x, y)\n prev = curr\n return prev[-1]\n```
| 1
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
Solution
|
longest-palindromic-subsequence
| 1
| 1
|
```C++ []\nclass Solution {\npublic:\n int longestPalindromeSubseq(string s){\n int m = s.size();\n\n int tab[3][m];\n for(int i = 0; i<m; i++){\n tab[0][i] = 0;\n tab[1][i] = 1;\n }\n int _2, _1, _0;\n for(int gap = 1; gap<m; gap++){\n _2 = (gap+1)%3, _1 = (gap+3)%3, _0 = (gap-1)%3;\n for(int i = 0,j = gap; j<m; i++,j++ ){\n if(s[i] == s[j]){\n tab[_2][j] = tab[_0][j-1]+2;\n }\n else{\n tab[_2][j] = max(tab[_1][j],tab[_1][j-1]);\n }\n } \n }\n return tab[m%3][m-1];\n }\n};\n```\n\n```Python3 []\nfrom functools import cache\n\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n @cache\n def search_palindromes(s):\n if not s:\n return 0\n longest_palindrome = 1\n for character in string.ascii_lowercase: \n index_forward, index_backward = s.find(character), s.rfind(character)\n if index_forward != index_backward:\n longest_palindrome = max(longest_palindrome, search_palindromes(s[index_forward+1:index_backward]) + 2)\n return longest_palindrome \n return search_palindromes(s)\n```\n\n```Java []\nclass Solution {\n public int longestPalindromeSubseq(String s) {\n char[] c = s.toCharArray();\n int n = c.length, max = 0;\n int[] dp = new int[n];\n for(int j = 0; j < n; j++) {\n dp[j] = 1;\n max = 0;\n for(int i = j-1; i >= 0; i--) {\n int len = dp[i];\n if(c[i] == c[j]) {\n dp[i] = 2 + max;\n }\n max = Math.max(max, len);\n }\n }\n for(int len: dp) max = Math.max(max, len);\n return max;\n }\n}\n```\n
| 1
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
MOST OPTIMIZED PYTHON SOLUTION || BOTTOM-UP APPROACH
|
longest-palindromic-subsequence
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(N^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n n=len(s)\n prev=[0]*n\n # for i in range(n):\n prev[n-1]=1\n for i in range(n-2,-1,-1):\n curr=[0]*n\n curr[i]=1\n for j in range(i+1,n):\n x=0\n if s[i]==s[j]:\n x=prev[j-1]+2\n y=max(prev[j],curr[j-1])\n curr[j]=max(x,y)\n prev=curr\n # print(prev)\n return prev[-1]\n```
| 1
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
MEMOIZATION || DP APPROACH
|
longest-palindromic-subsequence
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n cache={}\n p=s[::-1]\n def dp(i,j):\n if (i,j) in cache:\n return cache[(i,j)]\n if i>=len(s) or j>=len(p):\n return 0\n if s[i]==p[j]:\n return 1+dp(i+1,j+1)\n else:\n cache[(i,j)]=max(dp(i+1,j),dp(i,j+1))\n return cache[(i,j)]\n return dp(0,0)\n \n```
| 1
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
Python3 || Dynamic || Memoization || detailed explained
|
longest-palindromic-subsequence
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**Using memoization**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- we know for palindrome we have to check string reverse and original order if both same then it\'s palindrome.\n- now we want subsequence so for that [LCSS](https://leetcode.com/problems/longest-common-subsequence/solutions/3273259/python3-easiest-solution-and-detailed/) concept can be useful.\n---\n- make dp of given string and for reverse of that.\n- initialise it with 0.\n- now iterate through row and column when we find any match update memo[i][j] by 1 + it\'s predecessor block, we do this because if palindrom is continuous then we want to keep it continue and update max length.\n- if not then get maximum of it\'s upper and left neighbour, because till this point we\'ve not traversed downward and right elements.\n- do this till all row*column elements are covered.\n- return memo[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(N*N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n memo = [[0 for _ in range(len(s))] for __ in range(len(s))]\n def helper():\n nonlocal memo\n maxi = float("-inf")\n rev = s[::-1]\n if rev == s: return len(s)\n for i in range(len(s)):\n for j in range(len(s)):\n if rev[i] == s[j]:\n memo[i][j] = 1 + memo[i-1][j-1] if i and j else 1\n else:\n memo[i][j] = max(memo[i-1][j] if i else 0, memo[i][j-1] if j else 0)\n return memo[len(s)-1][len(s)-1]\n return helper()\n```
| 2
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
Easy to follow DP with explanation
|
longest-palindromic-subsequence
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**$$Disclaimer:$$** I am aware this is not the optimal solution in terms of memory. However, in my opinion, it was one of the easier DP solutions to conceptualize.\n\nFor this problem, we are taking a DP approach with subsequences. As such, for our DP table, `dp[i][j]` represents the length of the longest palindrome subsequence from indices `i` to `j`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNow that we know our DP table is 2D, we must determine the order in which we will fill it in. Since each subsequence will utilize the subsequences contained within it, we therefore need to solve subproblems from the "inside out" (hence the reversed for loop).\n\nThen, there are 3 cases we need to consider when creating our transition function:\n1. Two chars are matching and not adjacent (first if statement)\n2. Two chars are matching and are adjacent (second if statement)\n3. Two chars are not matching (else statement)\n\nFor case 1, we can simply look at the best subsequence excluding the matching characters and then add 2, as any palindrome with 2 matching characters appending on each end is also a palindrome. Thus, our transition function is `dp[i][j] = dp[i+1][j-1] + 2`\n\nFor case 2, since the characters are adjacent and matching, it is a base case for a palindrome of length 2. Thus, our transition function is `dp[i][j] = 2`\n\nFor case 3, we need to consider two cases, one in which the subsequence has the first character removed and the other in which the ending character is removed. Hence, our transition function is `dp[i][j] = max(dp[i+1][j], dp[i][j-1])`\n# Complexity\n- Time complexity:$$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n N = len(s)\n dp = [[1 for _ in range(N)] for _ in range(N)]\n\n for j in range(N):\n for i in range(j-1, -1, -1):\n if s[i] == s[j] and i + 1 < j:\n dp[i][j] = dp[i+1][j-1] + 2\n elif s[i] == s[j] and i + 1 == j:\n dp[i][j] = 2\n else:\n dp[i][j] = max(dp[i+1][j], dp[i][j-1])\n return dp[0][N-1]\n\n```
| 4
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
Python || Easy || DP || LCS Approach
|
longest-palindromic-subsequence
| 0
| 1
|
```\n#Tabulation(Top-Down)\n#Time Complexity: O(n^2)\n#Space Complexity: O(n^2)\nclass Solution1:\n def longestPalindromeSubseq(self, s: str) -> int:\n n=len(s)\n s2=s[-1::-1]\n dp=[[0 for j in range(n+1)] for i in range(n+1)]\n for i in range(1,n+1):\n for j in range(1,n+1):\n if s[i-1]==s2[j-1]:\n dp[i][j]=1+dp[i-1][j-1]\n else:\n dp[i][j]=max(dp[i-1][j],dp[i][j-1])\n return dp[n][n]\n \n#Space Optimization\n#Time Complexity: O(n^2)\n#Space Complexity: O(n)\nclass Solution:\n def longestPalindromeSubseq(self, s: str) -> int:\n n=len(s)\n s2=s[-1::-1]\n prev=[0]*(n+1)\n for i in range(1,n+1):\n curr=[0]*(n+1)\n for j in range(1,n+1):\n if s[i-1]==s2[j-1]:\n curr[j]=1+prev[j-1]\n else:\n curr[j]=max(prev[j],curr[j-1])\n prev=curr[:]\n return prev[n]\n```\n**An upvote will be encouraging**
| 1
|
Given a string `s`, find _the longest palindromic **subsequence**'s length in_ `s`.
A **subsequence** is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** s = "bbbab "
**Output:** 4
**Explanation:** One possible longest palindromic subsequence is "bbbb ".
**Example 2:**
**Input:** s = "cbbd "
**Output:** 2
**Explanation:** One possible longest palindromic subsequence is "bb ".
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists only of lowercase English letters.
| null |
Python 3 || 4 lines, w/ map, accumulate || T/M: 99% / 6%
|
super-washing-machines
| 0
| 1
|
```\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n\n ave, rem = divmod(sum(machines),len(machines))\n if rem: return -1\n \n machines = [m - ave for m in machines]\n\n return max(*machines,*map(abs,(accumulate(machines))))\n```\n[https://leetcode.com/problems/super-washing-machines/submissions/926167284/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*).\n
| 3
|
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`.
**Example 1:**
**Input:** machines = \[1,0,5\]
**Output:** 3
**Explanation:**
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
**Example 2:**
**Input:** machines = \[0,3,0\]
**Output:** 2
**Explanation:**
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
**Example 3:**
**Input:** machines = \[0,2,0\]
**Output:** -1
**Explanation:**
It's impossible to make all three washing machines have the same number of dresses.
**Constraints:**
* `n == machines.length`
* `1 <= n <= 104`
* `0 <= machines[i] <= 105`
| null |
Python 3 || 4 lines, w/ explanation || T/M: 100% / 97%
|
super-washing-machines
| 0
| 1
|
Here\'s the plan:\n1. We can arrive at the final state `arr = [n,n,n..,n]` (where`n`is the average of the elements of`machine`) if and only if`n*len(arr) == sum(machines)`). If not, we return -1. \n2. If so, we revise the problem to a simpler, equivalent probem by decrementing each element in`machines`by`n`, which means the final state we seek becomes`arr = [0,0,0..,0]`. Now, one of two conditions will determine the minimum number of moves. \n3. The first condition is to determine `max(machines)`. (Think about how many dresses must be removed from this machine to empty the machine, one per move.)\n4. The second condtion is the greatest absolute value of any element of the prefix sum of`machines`. The number of moves to the right or left must exceed or equal num or -num, respectively. (Think about how many dresses must pass through this machine, one per move.)\n\nHere\'s the code:\n\n```\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n\n ave, rem = divmod(sum(machines),len(machines)) # <\u2013 1.\n if rem: return -1 #\n \n machines = [m - ave for m in machines] # <\u2013 2.\n\n return max(max(machines), # <\u2013 3.\n max(map(abs,(accumulate(machines))))) # <\u2013 4.\n```\n[https://leetcode.com/problems/super-washing-machines/submissions/926204715/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*).\n
| 5
|
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`.
**Example 1:**
**Input:** machines = \[1,0,5\]
**Output:** 3
**Explanation:**
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
**Example 2:**
**Input:** machines = \[0,3,0\]
**Output:** 2
**Explanation:**
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
**Example 3:**
**Input:** machines = \[0,2,0\]
**Output:** -1
**Explanation:**
It's impossible to make all three washing machines have the same number of dresses.
**Constraints:**
* `n == machines.length`
* `1 <= n <= 104`
* `0 <= machines[i] <= 105`
| null |
517: Solution with step by step explanation
|
super-washing-machines
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Get the length of the list \'machines\' and the sum of all the dresses.\n2. Check if the total number of dresses is evenly divisible by the number of machines. If not, it is not possible to make all the machines have the same number of dresses, return -1.\n3. Calculate the target number of dresses that each machine should have.\n4. Initialize \'moves\' and \'dresses_so_far\' to 0.\n5. Iterate through the machines.\n6. Calculate the difference between the current number of dresses in the machine and the target number of dresses.\n7. Add this difference to \'dresses_so_far\'.\n8. Calculate the maximum value of abs(dresses_so_far), which indicates the maximum number of dresses that needs to be moved in a single move.\n9. Calculate the maximum value of (machines[i] - target_dresses), which indicates the maximum number of dresses that needs to be moved from this machine.\n10. Take the maximum of the above two values and update \'moves\'.\n11. Return \'moves\'.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n n = len(machines)\n total_dresses = sum(machines)\n \n if total_dresses % n != 0:\n return -1\n \n target_dresses = total_dresses // n\n moves = 0\n dresses_so_far = 0\n \n for i in range(n):\n dresses_so_far += machines[i] - target_dresses\n # The maximum value of abs(dresses_so_far) indicates the \n # maximum number of dresses that needs to be moved in a single move\n moves = max(moves, abs(dresses_so_far), machines[i] - target_dresses)\n \n return moves\n```
| 3
|
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`.
**Example 1:**
**Input:** machines = \[1,0,5\]
**Output:** 3
**Explanation:**
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
**Example 2:**
**Input:** machines = \[0,3,0\]
**Output:** 2
**Explanation:**
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
**Example 3:**
**Input:** machines = \[0,2,0\]
**Output:** -1
**Explanation:**
It's impossible to make all three washing machines have the same number of dresses.
**Constraints:**
* `n == machines.length`
* `1 <= n <= 104`
* `0 <= machines[i] <= 105`
| null |
Solution
|
super-washing-machines
| 1
| 1
|
```C++ []\nclass Solution {\npublic:\n int findMinMoves(vector<int>& ms) {\n int n = ms.size();\n int sum = 0;\n for (int &i : ms) sum += i;\n if (sum % n) return -1;\n int t = sum / n;\n int ans = 0, toRight = 0;\n for (int &i : ms) {\n toRight = toRight + i - t;\n ans = max(ans, max(abs(toRight), i - t));\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n\n ave, rem = divmod(sum(machines),len(machines))\n if rem: return -1\n \n machines = [m - ave for m in machines]\n abspref = max(map(abs,(accumulate(machines))))\n\n return max(max(machines),abspref)\n```\n\n```Java []\nclass Solution {\n public int findMinMoves(int[] machines) {\n int total = 0;\n for(int i: machines){\n total += i;\n } \n if(total % machines.length != 0){\n return -1;\n }\n int avg = total / machines.length;\n int count = 0;\n int max = 0;\n for(int load: machines){\n count = count + load - avg;\n max = Math.max(Math.max(max, Math.abs(count)), load-avg);\n }\n return max;\n }\n}\n```\n
| 1
|
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`.
**Example 1:**
**Input:** machines = \[1,0,5\]
**Output:** 3
**Explanation:**
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
**Example 2:**
**Input:** machines = \[0,3,0\]
**Output:** 2
**Explanation:**
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
**Example 3:**
**Input:** machines = \[0,2,0\]
**Output:** -1
**Explanation:**
It's impossible to make all three washing machines have the same number of dresses.
**Constraints:**
* `n == machines.length`
* `1 <= n <= 104`
* `0 <= machines[i] <= 105`
| null |
Four Line Code and easy to execute
|
super-washing-machines
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n C,F,E=0,0,sum(machines)//len(machines)\n if ((sum(machines))%(len(machines))!=0):\n return -1\n for i in range(len(machines)):\n C+=machines[i]-E\n F=max(F,abs(C),machines[i]-E)\n return F\n\n\n \n```
| 0
|
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`.
**Example 1:**
**Input:** machines = \[1,0,5\]
**Output:** 3
**Explanation:**
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
**Example 2:**
**Input:** machines = \[0,3,0\]
**Output:** 2
**Explanation:**
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
**Example 3:**
**Input:** machines = \[0,2,0\]
**Output:** -1
**Explanation:**
It's impossible to make all three washing machines have the same number of dresses.
**Constraints:**
* `n == machines.length`
* `1 <= n <= 104`
* `0 <= machines[i] <= 105`
| null |
Python3 with explanation
|
super-washing-machines
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n totalDresses = sum(machines)\n n = len(machines)\n \n # If total dresses is not divisible by number of machines, return -1\n if totalDresses % n != 0:\n return -1\n \n target = totalDresses // n\n moves = 0\n flow = 0\n \n for machine in machines:\n # Calculate the excess or deficiency for the current machine\n diff = machine - target\n \n # Update the flow\n flow += diff\n \n # Calculate moves for the current machine\n moves = max(moves, abs(flow), diff)\n \n return moves\n\n```
| 0
|
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`.
**Example 1:**
**Input:** machines = \[1,0,5\]
**Output:** 3
**Explanation:**
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
**Example 2:**
**Input:** machines = \[0,3,0\]
**Output:** 2
**Explanation:**
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
**Example 3:**
**Input:** machines = \[0,2,0\]
**Output:** -1
**Explanation:**
It's impossible to make all three washing machines have the same number of dresses.
**Constraints:**
* `n == machines.length`
* `1 <= n <= 104`
* `0 <= machines[i] <= 105`
| null |
Greedy with explanation
|
super-washing-machines
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- toLeft[i]: machine in ith position pass number of clothes to it\'s left side\n- toRight[i]: machine in ith position pass number of clothes to it\'s right side\n- -toLeft[i]: machine in (i-1)th position pass number of clothes to it\'s right side, equals toRight[i - 1]\n- -toRight[i]: machine in (i + 1)th position pass number of clothes to it\'s left side, equals toLeft[i + 1]\n- -toLeft[i + 1] = toRight[i]\n- toLeft[i] + toRight[i] = m - target \n- - toLeft = -toRight # for the above state\n- - toRight = m + toRight - target # for the above state\n- the final result can be pass from left or pass from right, or pass from left and right, here I used t for these 3 cases\n- vote up if helps\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)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n total, n = sum(machines), len(machines)\n if total % n: return -1\n target, res, toRight = total // n, 0, 0\n for m in machines:\n t = 0\n toLeft = -toRight\n toRight = m + toRight - target\n if toLeft >= 0: t += toLeft\n if toRight >= 0: t += toRight\n res = max(res, t)\n return res\n```
| 0
|
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`.
**Example 1:**
**Input:** machines = \[1,0,5\]
**Output:** 3
**Explanation:**
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
**Example 2:**
**Input:** machines = \[0,3,0\]
**Output:** 2
**Explanation:**
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
**Example 3:**
**Input:** machines = \[0,2,0\]
**Output:** -1
**Explanation:**
It's impossible to make all three washing machines have the same number of dresses.
**Constraints:**
* `n == machines.length`
* `1 <= n <= 104`
* `0 <= machines[i] <= 105`
| null |
Python (Simple Maths)
|
super-washing-machines
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findMinMoves(self, machines):\n n, total = len(machines), sum(machines)\n\n if total%n != 0:\n return -1\n\n target, running_sum, max_val = total//n, 0, 0\n\n for i in machines:\n max_val = max(max_val,abs(running_sum),i-target)\n running_sum += i-target\n\n return max_val\n\n\n\n\n \n \n```
| 0
|
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`.
**Example 1:**
**Input:** machines = \[1,0,5\]
**Output:** 3
**Explanation:**
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
**Example 2:**
**Input:** machines = \[0,3,0\]
**Output:** 2
**Explanation:**
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
**Example 3:**
**Input:** machines = \[0,2,0\]
**Output:** -1
**Explanation:**
It's impossible to make all three washing machines have the same number of dresses.
**Constraints:**
* `n == machines.length`
* `1 <= n <= 104`
* `0 <= machines[i] <= 105`
| null |
python 3
|
super-washing-machines
| 0
| 1
|
\n# Code\n```\nclass Solution:\n def findMinMoves(self, machines: List[int]) -> int:\n res = c = 0\n if (sum(machines)%len(machines)) != 0 :\n return -1\n a = int(sum(machines)/len(machines))\n for i in machines :\n diff = i - a\n c += diff\n res = max(abs(c),diff,res)\n return res \n\n\n \n\n```
| 0
|
You have `n` super washing machines on a line. Initially, each washing machine has some dresses or is empty.
For each move, you could choose any `m` (`1 <= m <= n`) washing machines, and pass one dress of each washing machine to one of its adjacent washing machines at the same time.
Given an integer array `machines` representing the number of dresses in each washing machine from left to right on the line, return _the minimum number of moves to make all the washing machines have the same number of dresses_. If it is not possible to do it, return `-1`.
**Example 1:**
**Input:** machines = \[1,0,5\]
**Output:** 3
**Explanation:**
1st move: 1 0 <-- 5 => 1 1 4
2nd move: 1 <-- 1 <-- 4 => 2 1 3
3rd move: 2 1 <-- 3 => 2 2 2
**Example 2:**
**Input:** machines = \[0,3,0\]
**Output:** 2
**Explanation:**
1st move: 0 <-- 3 0 => 1 2 0
2nd move: 1 2 --> 0 => 1 1 1
**Example 3:**
**Input:** machines = \[0,2,0\]
**Output:** -1
**Explanation:**
It's impossible to make all three washing machines have the same number of dresses.
**Constraints:**
* `n == machines.length`
* `1 <= n <= 104`
* `0 <= machines[i] <= 105`
| null |
simple iterative DP C++/Python||Beats 100.00%
|
coin-change-ii
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is a standard DP question. Use simple DP in an iterative way to solve it\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe initial case is\n```\ndp[0][0]=1;//1 comb: no coins for no amount \n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(|coins|amount)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(|coins|amount)\\to O(amount)$$\n\n# 2D iterative DP code\n```\nclass Solution {\npublic:\n int change(int amount, vector<int>& coins) {\n vector<vector<int>> dp(coins.size() + 1, vector<int>(amount + 1, 0));\n dp[0][0] = 1;//1 comb: no coins for no amount \n\n for (int j = 1; j <= coins.size(); j++) {\n for (int i = 0; i <= amount; i++) {\n dp[j][i] = dp[j-1][i]; // Exclude the current coin\n \n if (i >= coins[j-1]) {\n dp[j][i] += dp[j][i-coins[j-1]];//Include the current coin\n }\n }\n }\n return dp[coins.size()][amount];\n }\n};\n```\n# 1D optimized Code Beats 100.00%\n```\nclass Solution {\npublic:\n int change(int amount, vector<int>& coins) {\n vector<int> dp(amount+1, 0);\n dp[0]=1;//1 comb: no coins for no amount \n for(int c:coins){\n for(int i=1; i<=amount; i++)\n if (i-c>=0)\n dp[i]+=dp[i-c];\n }\n return dp[amount]; \n }\n};\n```\nThe C++ code can be furthermore optimized by replacing the inner loop with the following \n```\n for(int i=c; i<=amount; i++)\n dp[i]+=dp[i-c];\n```\n# Python code\n\n```\nclass Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n dp=[1]+[0]*amount\n for c in coins:\n for i in range(c, amount+1):\n dp[i]+=dp[i-c]\n return dp[amount]\n```\n# Leetcode 322. Coin Change\nThis is a similar question to find the fewest number of coins that you need to make up that amount. [Leetcode 322. Coin Change](https://leetcode.com/problems/coin-change/solutions/3680783/c-dp-vs-bfs-visited-gcd-beats-93-94/)\n[Please turn on English subtitles if neccessary]\n[https://youtu.be/HujyE-ob058](https://youtu.be/HujyE-ob058)\nVarious solutions:\n1. The greedy algorithm can only solve canonical currency\n2. Euclidean algorithm can solve coins.length=2\n3. DFS+DP can solve\n4. Iterative DP can be solved quickly\n5. BFS +visited marking can quickly solve\n6. BFS can solve the problem by changing the queue to priority queue
| 6
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
MEMOIZATION || DP || SUPER EASY
|
coin-change-ii
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n cache={}\n def dp(i,k):\n if (i,k) in cache:\n return cache[(i,k)]\n if i>len(coins)-1:\n cache[(i,k)]=0\n return 0\n if k<0:\n cache[(i,k)]=0\n return 0\n if k==0:\n cache[(i,k)]=1\n return 1\n take=dp(i,k-coins[i])\n ntake=dp(i+1,k)\n cache[(i,k)]=take+ntake\n return take+ntake\n return dp(0,amount)\n```
| 2
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Python 59ms, beats 100%
|
coin-change-ii
| 0
| 1
|
# Code\n```\ndef change(self, amount: int, coins: List[int]) -> int:\n coins = [c for c in coins if c <= amount]\n dp = [0] * (amount + 1)\n dp[0] = 1\n coins.sort(reverse=True)\n\n for coin in coins:\n dp[coin] = 1\n for i in range(coin, amount - coin + 1):\n dp[i+coin] += dp[i]\n\n return dp[-1]\n```
| 2
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Python 6 lines
|
coin-change-ii
| 0
| 1
|
Not optimized\n\n# Code\n```\nclass Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n @cache\n def foo(v, startIndex):\n if v == 0:\n return 1\n return reduce(add, [foo(v-coins[i], i) for i in range(startIndex, len(coins)) if coins[i] <= v], 0)\n\n return foo(amount, 0)\n```
| 2
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
MOST OPTIMIZED DP SOLUTION
|
coin-change-ii
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def dp(self,i,coins,tr,dct):\n if tr==0:\n return 1\n if i==0:\n if tr%coins[0]==0:\n return 1\n return 0\n if (i,tr) in dct:\n return dct[(i,tr)]\n x=0\n if coins[i]<=tr:\n x=self.dp(i,coins,tr-coins[i],dct)\n y=self.dp(i-1,coins,tr,dct)\n dct[(i,tr)]=x+y\n return dct[(i,tr)]\n\n def change(self, amount: int, coins: List[int]) -> int:\n n=len(coins)\n # dp=[[0]*(amount+1) for i in range(n)]\n prev=[0]*(amount+1)\n # for i in range(n):\n # dp[i][0]=1\n prev[0]=1\n for i in range(amount+1):\n if i%coins[0]==0:\n prev[i]=1\n for i in range(1,n):\n curr=[0]*(amount+1)\n curr[0]=1\n for j in range(amount+1):\n x=0\n if j>=coins[i]:\n x=curr[j-coins[i]]\n y=prev[j]\n curr[j]=x+y\n prev=curr\n return prev[amount]\n```
| 2
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Python easy solutions
|
coin-change-ii
| 0
| 1
|
# Code\n```\nfrom typing import List\n\nclass Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n dp = [0] * (amount + 1)\n dp[0] = 1\n\n for coin in coins:\n for i in range(coin, amount + 1):\n dp[i] += dp[i - coin]\n\n return dp[amount]\n```
| 1
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Easiest Solution|| Beats 100%
|
coin-change-ii
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n coins = [c for c in coins if c <= amount]\n temp = [0] * (amount + 1)\n temp[0] = 1\n coins.sort()\n coins = coins[::-1]\n for i in coins:\n temp[i] = 1\n for j in range(i, amount - i + 1):\n temp[j+i] += temp[j]\n return temp[-1]\n \n```
| 1
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
✅ 100% Dynamic Programming [VIDEO] - Optimal Solution
|
coin-change-ii
| 1
| 1
|
# Problem Understanding\n\nIn the "Coin Change II" problem, we are given coins of various denominations and a specific amount. Our task is to determine the number of different ways we can make up that amount using the coins. Unlike other coin change problems where we need to minimize or maximize the number of coins, here we need to find the total number of possible combinations.\n\nFor instance, with coins [1,2,5] and amount 5, we have the following combinations:\n\n1. 5 = 5\n2. 5 = 2 + 2 + 1\n3. 5 = 2 + 1 + 1 + 1\n4. 5 = 1 + 1 + 1 + 1 + 1\n\nHence, there are 4 ways to make up the amount 5 using the coins [1,2,5].\n\n---\n\n# Live Coding & Explenation:\nhttps://youtu.be/7V3FiGBEThg\n\n## Live coding in:\n- [Python: \uD83D\uDC0D](https://youtu.be/7V3FiGBEThg)\n- [Rust: \uD83E\uDD80](https://youtu.be/fm80-oJGTUw)\n- [Go: \uD83D\uDC39](https://youtu.be/aJw_5d1CiwE)\n\n# Approach\n\nThe intuitive way to approach this problem is by leveraging dynamic programming. We can envision a solution where, for each coin, we update the number of ways to create every amount from 0 to the given amount.\n\n## Using a 1D Dynamic Programming Array\n\nTo find the solution in an optimized manner, we use a one-dimensional array, `dp`, of size `amount + 1`, where `dp[i]` represents the number of ways to make up the amount `i` using the coins considered so far.\n\n1. Initialize `dp` with all zeros and set `dp[0]` to 1 since there\'s only one way to make up amount 0, which is by not choosing any coin.\n2. For each coin in `coins`, update the array `dp` from the coin value to the total amount.\n3. For each amount `i` from the coin value to the total amount, increment `dp[i]` by `dp[i - coin_value]`.\n4. The final answer will be `dp[amount]`.\n\n## Example\n\nGiven the sample example with coins \\([1,2,5]\\) and amount \\(5\\), let\'s visualize how the `dp` array changes with each iteration:\n\n1. Initialization:\n - `dp = [1, 0, 0, 0, 0, 0]`\n\n2. Processing coin \\(1\\):\n - For each \\(j\\) from \\(1\\) to \\(5\\), add `dp[j - 1]` to `dp[j]`\n - After this step: `dp = [1, 1, 1, 1, 1, 1]`\n\n3. Processing coin \\(2\\):\n - For each \\(j\\) from \\(2\\) to \\(5\\), add `dp[j - 2]` to `dp[j]`\n - After this step: `dp = [1, 1, 2, 2, 3, 3]`\n\n4. Processing coin \\(5\\):\n - For \\(j = 5\\), add `dp[0]` to `dp[5]`\n - After this step: `dp = [1, 1, 2, 2, 3, 4]`\n\nNow, let\'s visualize these iterations using a table.\n\nHere\'s a tabular representation of the algorithm\'s progression for the given example:\n\n| Iteration | 0 | 1 | 2 | 3 | 4 | 5 |\n|-----------|---|---|---|---|---|---|\n| Initial | 1 | 0 | 0 | 0 | 0 | 0 |\n| Coin 1 | 1 | 1 | 1 | 1 | 1 | 1 |\n| Coin 2 | 1 | 1 | 2 | 2 | 3 | 3 |\n| Coin 5 | 1 | 1 | 2 | 2 | 3 | 4 |\n\n- The "Initial" row indicates the state of the `dp` array right after initialization.\n- Each subsequent row represents the state of the `dp` array after processing the respective coin.\n \nFrom the table, we can trace how the algorithm calculates the number of combinations for each amount using the available coins. The final value in the `dp` array, `dp[5]`, gives the total number of ways to make up the amount 5 using the coins [1,2,5], which is 4 in this case.\n\n## Rationale\n\nThe solution\'s efficiency comes from its bottom-up construction. By building upon previously computed solutions for smaller amounts, we avoid redundant calculations. This method ensures that by the time we want to compute the number of ways for a particular amount, we\'ve already determined the number of ways for all smaller amounts using the current set of coins.\n\n# Complexity\n\n**Time Complexity:** $$O(\\text{amount} \\times \\text{len(coins)})$$\n\n**Space Complexity:** $$O(\\text{amount})$$\n\nThis optimized solution ensures that we\'re using both time and space resources efficiently.\n\n# Performance\n\nThis implementation performs competitively on LeetCode, often beating a significant portion of other submissions in terms of runtime and memory usage.\n\nLanguage | Runtime (ms) | Runtime Beat (%) | Memory (MB) | Memory Beat (%)\n------------|--------------|------------------|-------------|-----------------\nRust | 0 | 100% | 2.0 | 64.29%\nGo | 1 | 74.57% | 2.3 | 100%\nJava | 2 | 100% | 39.4 | 99.94%\nC++ | 4 | 97.86% | 7.1 | 90.15%\nJavaScript | 55 | 95.24% | 42.3 | 77.78%\nC# | 78 | 90.96% | 38.3 | 90.36%\nPython3 | 104 | 99.40% | 16.6 | 77.13%\n\n\n\n\n# Code\n``` Python []\nclass Solution:\n def change(self, amount: int, coins: List[int]) -> int:\n dp = [0] * (amount + 1)\n dp[0] = 1\n \n for coin in coins:\n for j in range(coin, amount + 1):\n dp[j] += dp[j - coin]\n \n return dp[amount]\n```\n``` C++ []\nclass Solution {\npublic:\n int change(int amount, vector<int>& coins) {\n vector<int> dp(amount + 1, 0);\n dp[0] = 1;\n \n for (int coin : coins) {\n for (int j = coin; j <= amount; j++) {\n dp[j] += dp[j - coin];\n }\n }\n \n return dp[amount];\n }\n};\n```\n``` Rust []\nimpl Solution {\n pub fn change(amount: i32, coins: Vec<i32>) -> i32 {\n let mut dp = vec![0; (amount + 1) as usize];\n dp[0] = 1;\n \n for coin in &coins {\n for j in *coin..=amount {\n dp[j as usize] += dp[(j - coin) as usize];\n }\n }\n \n dp[amount as usize]\n }\n}\n```\n``` Go []\nfunc change(amount int, coins []int) int {\n dp := make([]int, amount+1)\n dp[0] = 1\n \n for _, coin := range coins {\n for j := coin; j <= amount; j++ {\n dp[j] += dp[j - coin]\n }\n }\n \n return dp[amount]\n}\n```\n``` Java []\npublic class Solution {\n public int change(int amount, int[] coins) {\n int[] dp = new int[amount + 1];\n dp[0] = 1;\n \n for (int coin : coins) {\n for (int j = coin; j <= amount; j++) {\n dp[j] += dp[j - coin];\n }\n }\n \n return dp[amount];\n }\n}\n```\n``` C# []\npublic class Solution {\n public int Change(int amount, int[] coins) {\n int[] dp = new int[amount + 1];\n dp[0] = 1;\n \n foreach (int coin in coins) {\n for (int j = coin; j <= amount; j++) {\n dp[j] += dp[j - coin];\n }\n }\n \n return dp[amount];\n }\n}\n```\n``` JavaScript []\n/**\n * @param {number} amount\n * @param {number[]} coins\n * @return {number}\n */\nvar change = function(amount, coins) {\n let dp = new Array(amount + 1).fill(0);\n dp[0] = 1;\n \n for (let coin of coins) {\n for (let j = coin; j <= amount; j++) {\n dp[j] += dp[j - coin];\n }\n }\n \n return dp[amount];\n};\n```\n\n---\n\n# Conclusion\n\nThe "Coin Change II" problem is an excellent demonstration of the power and efficiency of dynamic programming. By breaking down the problem into smaller subproblems and building the solution from the ground up, we\'re able to solve a seemingly complex problem in a computationally efficient manner.\n\nWhether you\'re preparing for interviews or just honing your algorithmic skills, problems like this reinforce the importance of understanding the underlying principles of dynamic programming and applying them in various scenarios. Keep practicing, and never stop learning!\n\n# Live Coding in Rust & Go\nhttps://youtu.be/fm80-oJGTUw\nhttps://youtu.be/aJw_5d1CiwE
| 91
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
faster than 70.49% of Python3 submission || Easy Solution || Better Approach
|
coin-change-ii
| 0
| 1
|
### Approach:-\nTwo lists prev and curr are created, each of length value + 1, initialized with zeros. These lists will be used to store the number of ways to make change for each value from 0 to value.\n\nFor the first denomination arr[0], the prev list is updated. If a particular value i is divisible by arr[0], it means we can use this denomination to make change for that value. So, prev[i] is set to 1. Otherwise, prev[i] remains 0.\n\nFor each subsequent denomination arr[i] (starting from the second denomination, since we already processed the first one), we update the curr list based on the values in the prev list.\n\nFor each value j from 0 to value, we consider two possibilities:\n\nnottake: The number of ways to make change without using the current denomination arr[i]. This is simply the value of prev[j].\ntake: The number of ways to make change by considering the current denomination arr[i]. This is calculated by looking up the number of ways to make change for the value (j - arr[i]) from the previous iteration, i.e., curr[j - arr[i]].\nThe curr[j] value is updated as the sum of nottake and take for each value of j.\n\nAfter processing all denominations, the prev list is updated with the values of the curr list (this is done with the line prev = curr[:]), so that prev now contains the updated number of ways to make change for each value from 0 to value.\n\nFinally, the method returns the number of ways to make change for the given value, which is stored at the index value in the prev list.\n### Code Below\n```\nclass Solution:\n def change(self, value: int, arr: List[int]) -> int:\n \n\t\n prev=[0 for i in range(value+1)] \n curr=[0 for i in range(value+1)] \n for i in range(value+1):\n if i%arr[0]==0:\n prev[i]=1 \n else:\n prev[i]=0\n for i in range(1,len(arr)):\n for j in range(value+1):\n nottake=prev[j]\n take=0\n if j>=arr[i]:\n take=curr[j-arr[i]]\n curr[j]=take+nottake \n prev=curr[:]\n return prev[value] \n```\n\n\n### Please Upvote it :)\n\n\n
| 3
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Solution
|
random-flip-matrix
| 1
| 1
|
```C++ []\nclass Solution {\npublic:\n Solution(int m, int n) : rows(m), cols(n), total(m * n) {\n }\n vector<int> flip() {\n if (used.size() == total) return {};\n int index = rand() % total;\n while (used.count(index))\n index = ++index % total;\n used.insert(index);\n return {index / cols, index % cols};\n }\n void reset() {\n used.clear();\n }\n private:\n unordered_set<int> used;\n int rows;\n int cols;\n int total;\n};\n```\n\n```Python3 []\nclass Solution:\n\n def __init__(self, n_rows: int, n_cols: int):\n self.c = n_cols\n self.start = 0\n self.end = n_rows * n_cols - 1\n self.d = {}\n \n def flip(self):\n rand = random.randint(self.start, self.end)\n res = self.d.get(rand, rand)\n self.d[rand] = self.d.get(self.start, self.start)\n self.start += 1\n return divmod(res, self.c)\n \n def reset(self):\n self.d = {}\n self.start = 0\n```\n\n```Java []\nclass Solution {\n int i=0,j=0;\n int m=0;int n=0;\n public Solution(int m, int n) {\n this.m=m;\n this.n=n;\n }\n public int[] flip() {\n j++;\n if(j==n){\n j=0;\n i++;\n }\n if(i==m){\n i=0;\n j=0;\n }\n return new int[]{i,j}; \n }\n public void reset() { \n }\n}\n```\n
| 1
|
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.
|
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
|
Solution
|
random-flip-matrix
| 1
| 1
|
```C++ []\nclass Solution {\npublic:\n Solution(int m, int n) : rows(m), cols(n), total(m * n) {\n }\n vector<int> flip() {\n if (used.size() == total) return {};\n int index = rand() % total;\n while (used.count(index))\n index = ++index % total;\n used.insert(index);\n return {index / cols, index % cols};\n }\n void reset() {\n used.clear();\n }\n private:\n unordered_set<int> used;\n int rows;\n int cols;\n int total;\n};\n```\n\n```Python3 []\nclass Solution:\n\n def __init__(self, n_rows: int, n_cols: int):\n self.c = n_cols\n self.start = 0\n self.end = n_rows * n_cols - 1\n self.d = {}\n \n def flip(self):\n rand = random.randint(self.start, self.end)\n res = self.d.get(rand, rand)\n self.d[rand] = self.d.get(self.start, self.start)\n self.start += 1\n return divmod(res, self.c)\n \n def reset(self):\n self.d = {}\n self.start = 0\n```\n\n```Java []\nclass Solution {\n int i=0,j=0;\n int m=0;int n=0;\n public Solution(int m, int n) {\n this.m=m;\n this.n=n;\n }\n public int[] flip() {\n j++;\n if(j==n){\n j=0;\n i++;\n }\n if(i==m){\n i=0;\n j=0;\n }\n return new int[]{i,j}; \n }\n public void reset() { \n }\n}\n```\n
| 1
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
python solution beats 90%
|
random-flip-matrix
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to simulate a 2D grid of size m x n and flip a cell at random, with the restriction that a cell can only be flipped once. The solution uses a set to keep track of the cells that have been flipped, and uses the randint function from the random module to generate a random number between 0 and (m*n)-1.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to use a set to keep track of the cells that have been flipped and generate a random number between 0 and (m*n)-1, which represents the index of the cell to flip. If the cell has already been flipped, a new random number is generated until an unflipped cell is found. The index is then used to determine the corresponding row and column of the 2D grid.\n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(mn)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.m = m\n self.n = n\n self.total = m*n\n self.used = set()\n self.r = random.Random()\n\n def flip(self) -> List[int]:\n r = self.r.randint(0, self.total-1)\n while r in self.used:\n r = self.r.randint(0, self.total-1)\n self.used.add(r)\n return [r//self.n, r%self.n]\n\n def reset(self) -> None:\n self.used = set()\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 1
|
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.
|
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
|
python solution beats 90%
|
random-flip-matrix
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to simulate a 2D grid of size m x n and flip a cell at random, with the restriction that a cell can only be flipped once. The solution uses a set to keep track of the cells that have been flipped, and uses the randint function from the random module to generate a random number between 0 and (m*n)-1.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to use a set to keep track of the cells that have been flipped and generate a random number between 0 and (m*n)-1, which represents the index of the cell to flip. If the cell has already been flipped, a new random number is generated until an unflipped cell is found. The index is then used to determine the corresponding row and column of the 2D grid.\n# Complexity\n- Time complexity: O(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(mn)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.m = m\n self.n = n\n self.total = m*n\n self.used = set()\n self.r = random.Random()\n\n def flip(self) -> List[int]:\n r = self.r.randint(0, self.total-1)\n while r in self.used:\n r = self.r.randint(0, self.total-1)\n self.used.add(r)\n return [r//self.n, r%self.n]\n\n def reset(self) -> None:\n self.used = set()\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 1
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
Python3 Approach 1 with formal mathematical proof
|
random-flip-matrix
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition is to always partition the numbers into two parts: 1) the unvisited numbers and 2) the already visited numbers. Logically, the indices [0, `remain`] and [remain+1, `nRows`*`nCols`]) correspond to part 1 and part 2, respectively. What\'s left to be done is to ensure that every logical index in [0, remain] is linked to an actual unvisited number. Then, each time, we can randomly access an index in [0, remain] and output the associated number.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe keep track of the `mapping` hashtable for the linkages. Initially, `mapping` maps every index to itselt (However, we initiate this self-mapping only when one index is accessed in order to save memory).\n\nEvery round:\n1. We take a random index `r` in [0, remain], and obtain the number associated with `r`: mapping[r] (it can be nums[r] if r is not visited before, or the index could be relinked, see below).\n2. Try to link the index `r` visited in this round to index mapping[remain]. Again, the mapping of remain could be itself or relinked. It is guranteed that after this step, `r` is either 1) no longer accessible after this round (r == remain), or 2) `r` is still accessible but it maps to an unvisited index.\n# Proof\nConsider a 1-d array `nums` of size `n` (0-indexed).\n\n1. In the **first** round:\nCase 1: if r == n-1, then nums[n-1] is returned in this round. r is still mapped to n-1 and will never be accessed later.\nCase 2: if r < n-1, then nums[r] is returned in this round. r is relinked to n-1. Since index n-1 is not visited before, we know that after this round, any index in [0, remain] maps to an unvisited index through `mapping`.\n\n2. In round **k**, k<nCol*nRow. Assume any index in [0, remain] maps to an unvisited index as proved in round 1 to k-1. Then\n\n**Return value**: The nums[r] where r is a random index $r\\in[0,\\text{remain}]$ returns a random, unvisited number.\n\n**Relink**: If r == remain, r\'s mapping is unchanged, but will never be accessed later. If r < remainThe index `r` is then linked to mapping[remain], which is guaranteed to be an unvisited index.\n\nQ.E.D.\n# Complexity\n- Time complexity: $O(1)$ preprocessing. $O(1)$ flip. $O(\\min(F,\\text{nRows}\u22C5\\text{nCols}))$ reset, where $F$ is the total number of flips.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(\\min(F,\\text{nRows}\u22C5\\text{nCols}))$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.m,self.n=m,n\n self.reset()\n\n def flip(self) -> List[int]:\n self.remain-=1\n ridx=random.randint(0,self.remain)\n x=self.mapping[ridx] if ridx in self.mapping else ridx\n self.mapping[ridx]=self.mapping[self.remain] if self.remain in self.mapping else self.remain\n return divmod(x,self.n)\n\n def reset(self) -> None:\n self.remain=self.m*self.n\n self.mapping=dict()\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 0
|
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.
|
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
|
Python3 Approach 1 with formal mathematical proof
|
random-flip-matrix
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition is to always partition the numbers into two parts: 1) the unvisited numbers and 2) the already visited numbers. Logically, the indices [0, `remain`] and [remain+1, `nRows`*`nCols`]) correspond to part 1 and part 2, respectively. What\'s left to be done is to ensure that every logical index in [0, remain] is linked to an actual unvisited number. Then, each time, we can randomly access an index in [0, remain] and output the associated number.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe keep track of the `mapping` hashtable for the linkages. Initially, `mapping` maps every index to itselt (However, we initiate this self-mapping only when one index is accessed in order to save memory).\n\nEvery round:\n1. We take a random index `r` in [0, remain], and obtain the number associated with `r`: mapping[r] (it can be nums[r] if r is not visited before, or the index could be relinked, see below).\n2. Try to link the index `r` visited in this round to index mapping[remain]. Again, the mapping of remain could be itself or relinked. It is guranteed that after this step, `r` is either 1) no longer accessible after this round (r == remain), or 2) `r` is still accessible but it maps to an unvisited index.\n# Proof\nConsider a 1-d array `nums` of size `n` (0-indexed).\n\n1. In the **first** round:\nCase 1: if r == n-1, then nums[n-1] is returned in this round. r is still mapped to n-1 and will never be accessed later.\nCase 2: if r < n-1, then nums[r] is returned in this round. r is relinked to n-1. Since index n-1 is not visited before, we know that after this round, any index in [0, remain] maps to an unvisited index through `mapping`.\n\n2. In round **k**, k<nCol*nRow. Assume any index in [0, remain] maps to an unvisited index as proved in round 1 to k-1. Then\n\n**Return value**: The nums[r] where r is a random index $r\\in[0,\\text{remain}]$ returns a random, unvisited number.\n\n**Relink**: If r == remain, r\'s mapping is unchanged, but will never be accessed later. If r < remainThe index `r` is then linked to mapping[remain], which is guaranteed to be an unvisited index.\n\nQ.E.D.\n# Complexity\n- Time complexity: $O(1)$ preprocessing. $O(1)$ flip. $O(\\min(F,\\text{nRows}\u22C5\\text{nCols}))$ reset, where $F$ is the total number of flips.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(\\min(F,\\text{nRows}\u22C5\\text{nCols}))$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.m,self.n=m,n\n self.reset()\n\n def flip(self) -> List[int]:\n self.remain-=1\n ridx=random.randint(0,self.remain)\n x=self.mapping[ridx] if ridx in self.mapping else ridx\n self.mapping[ridx]=self.mapping[self.remain] if self.remain in self.mapping else self.remain\n return divmod(x,self.n)\n\n def reset(self) -> None:\n self.remain=self.m*self.n\n self.mapping=dict()\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 0
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
An excellent solution
|
random-flip-matrix
| 0
| 1
|
# Intuition\n\n\n# Approach\nYou don\'t have to draw randomly, just pull out [i,j] with values of zero in order.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n from collections import defaultdict\n myM = None\n myN = None\n a = None\n b = None\n vis = None\n\n def __init__(self, m: int, n: int):\n global myM, myN, a, b,vis\n vis = defaultdict(int)\n a = b = 0\n myM = m\n myN = n\n \n\n def flip(self) -> List[int]:\n global a, b, myN, myM\n \n while 1:\n\n if b >= myN:\n a += 1\n b = 0\n \n if a >= myM:\n a = 0\n \n if (a,b) not in vis:\n ret = [a,b]\n vis[(a,b)] = 1\n b += 1\n return ret\n\n \n\n def reset(self) -> None:\n global vis\n vis.clear()\n\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 0
|
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.
|
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
|
An excellent solution
|
random-flip-matrix
| 0
| 1
|
# Intuition\n\n\n# Approach\nYou don\'t have to draw randomly, just pull out [i,j] with values of zero in order.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n from collections import defaultdict\n myM = None\n myN = None\n a = None\n b = None\n vis = None\n\n def __init__(self, m: int, n: int):\n global myM, myN, a, b,vis\n vis = defaultdict(int)\n a = b = 0\n myM = m\n myN = n\n \n\n def flip(self) -> List[int]:\n global a, b, myN, myM\n \n while 1:\n\n if b >= myN:\n a += 1\n b = 0\n \n if a >= myM:\n a = 0\n \n if (a,b) not in vis:\n ret = [a,b]\n vis[(a,b)] = 1\n b += 1\n return ret\n\n \n\n def reset(self) -> None:\n global vis\n vis.clear()\n\n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 0
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
No tricks. Python. Beats 98%.
|
random-flip-matrix
| 0
| 1
|
# Intuition\nIn this case, due to task size constraints, it is much more efficient to just track the already flipped indices, and let random fail-and-repeat from time to time.\n\nTo reduce the number of random calls, it makes sence to calculate the index as flattenned into one dimension.\n\n# Complexity\n- Time complexity: $$O(k)$$ where k is the number of flips.\n\n- Space complexity: $$O(k)$$ where k is the number of flips.\n\n# Code\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.mn = m * n\n self.n = n\n self.flipped = set()\n\n def flip(self) -> List[int]:\n iflat = randrange(0, self.mn)\n while iflat in self.flipped:\n iflat = randrange(0, self.mn)\n self.flipped.add(iflat)\n return [iflat // self.n, iflat % self.n]\n\n def reset(self) -> None:\n self.flipped = set()\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 0
|
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.
|
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
|
No tricks. Python. Beats 98%.
|
random-flip-matrix
| 0
| 1
|
# Intuition\nIn this case, due to task size constraints, it is much more efficient to just track the already flipped indices, and let random fail-and-repeat from time to time.\n\nTo reduce the number of random calls, it makes sence to calculate the index as flattenned into one dimension.\n\n# Complexity\n- Time complexity: $$O(k)$$ where k is the number of flips.\n\n- Space complexity: $$O(k)$$ where k is the number of flips.\n\n# Code\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.mn = m * n\n self.n = n\n self.flipped = set()\n\n def flip(self) -> List[int]:\n iflat = randrange(0, self.mn)\n while iflat in self.flipped:\n iflat = randrange(0, self.mn)\n self.flipped.add(iflat)\n return [iflat // self.n, iflat % self.n]\n\n def reset(self) -> None:\n self.flipped = set()\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 0
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
Python3 - Switch Modes
|
random-flip-matrix
| 0
| 1
|
# Intuition\nFor very large sets, it makes sense to just maintain selected\nFor very small sets, it makes sense to just maintain available\nFor middle sized, it depends on how it is used\n\nSo, for a compromise, I just switch modes if more than half the positions are filled.\n\n# Code\n```\nimport secrets\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.w = m\n self.h = n\n self.filled = set()\n self.avail = None\n if m * n <= 1000:\n self.avail = []\n for i in range(self.w):\n for j in range(self.h):\n self.avail.append((i,j))\n\n def flip(self) -> List[int]:\n if self.avail is not None:\n x, y = self.avail.pop(secrets.randbelow(len(self.avail)))\n self.filled.add((x,y))\n return [x, y]\n else:\n while True:\n r = secrets.randbelow(self.w*self.h)\n x, y = divmod(r, self.h)\n if (x,y) not in self.filled:\n self.filled.add((x,y))\n return (x,y)\n if len(self.filled) >= self.w * self.h // 2:\n self.avail = []\n for i in range(self.w):\n for j in range(self.h):\n if (i,j) not in self.filled:\n self.avail.append((i,j))\n\n def reset(self) -> None:\n self.filled = set()\n self.avail = None\n```
| 0
|
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.
|
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
|
Python3 - Switch Modes
|
random-flip-matrix
| 0
| 1
|
# Intuition\nFor very large sets, it makes sense to just maintain selected\nFor very small sets, it makes sense to just maintain available\nFor middle sized, it depends on how it is used\n\nSo, for a compromise, I just switch modes if more than half the positions are filled.\n\n# Code\n```\nimport secrets\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.w = m\n self.h = n\n self.filled = set()\n self.avail = None\n if m * n <= 1000:\n self.avail = []\n for i in range(self.w):\n for j in range(self.h):\n self.avail.append((i,j))\n\n def flip(self) -> List[int]:\n if self.avail is not None:\n x, y = self.avail.pop(secrets.randbelow(len(self.avail)))\n self.filled.add((x,y))\n return [x, y]\n else:\n while True:\n r = secrets.randbelow(self.w*self.h)\n x, y = divmod(r, self.h)\n if (x,y) not in self.filled:\n self.filled.add((x,y))\n return (x,y)\n if len(self.filled) >= self.w * self.h // 2:\n self.avail = []\n for i in range(self.w):\n for j in range(self.h):\n if (i,j) not in self.filled:\n self.avail.append((i,j))\n\n def reset(self) -> None:\n self.filled = set()\n self.avail = None\n```
| 0
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
97% faster soln
|
random-flip-matrix
| 0
| 1
|
# 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\n def __init__(self, m: int, n: int):\n self.m = m \n self.n = n\n self.r = -1\n self.c = -1\n self.isreset =False\n\n def flip(self) -> List[int]:\n if self.c < self.n-1:\n self.c += 1\n if self.r < 0:\n self.r =0 \n else:\n if self.r < self.m-1:\n self.r += 1\n else:\n self.r = 0\n self.c = 0\n \n return [self.r, self.c]\n \n\n def reset(self) -> None:\n self.isreset = True\n if self.c == self.n-1 and self.r ==self.m-1:\n self.c = -1\n self.r = -1 \n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 0
|
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.
|
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
|
97% faster soln
|
random-flip-matrix
| 0
| 1
|
# 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\n def __init__(self, m: int, n: int):\n self.m = m \n self.n = n\n self.r = -1\n self.c = -1\n self.isreset =False\n\n def flip(self) -> List[int]:\n if self.c < self.n-1:\n self.c += 1\n if self.r < 0:\n self.r =0 \n else:\n if self.r < self.m-1:\n self.r += 1\n else:\n self.r = 0\n self.c = 0\n \n return [self.r, self.c]\n \n\n def reset(self) -> None:\n self.isreset = True\n if self.c == self.n-1 and self.r ==self.m-1:\n self.c = -1\n self.r = -1 \n \n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(m, n)\n# param_1 = obj.flip()\n# obj.reset()\n```
| 0
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
[Python] Explained solution O(m*n) -> O(1)
|
random-flip-matrix
| 0
| 1
|
# Intuition\nThe idea is to first represent the matrix as a list of points `zeros = [(i, j) for i in range(m) for j in range(n)]`.\nNow we can keep track of picked points during flips by splitting the list into left and right parts. We\'ll store picked ones in the right part, while left part will be the source for new flips.\n\n# Approach\nIf we\'re fine with populating and storing the list `zeros`, which is $O(m*n)$ in TC and SC, we can do the flips in place by keeping track of the length of the source - `zeros_len`. And each time we do a flip, we\'ll:\n1. Pick randomly index `idx` so that `idx < zeros_len`\n2. Decrease `zeros_len` by `1`.\n3. Swap the flipped point `zeros[idx]` with the last element in the left side - `zeros[zeros_len]`\n\nThis approach TLEs on the last test, because it\'s linear in time. So we can do better then that. The important observation here is that we don\'t actually need to store the list `zeros`. All we care about are the swaps and we can keep track of them using a hashmap - `idxs`. `idxs[i]` is the current point under index `i`.\n\n# Complexity\n- Time complexity:\n$O(1)$\n\n- Space complexity:\n$O(k)$, where $k$ - the number of consecutive flips\n\n# Code\n$O(m*n)$ solution using a list of all elements in the matrix. TLEs on the last test\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.zeros_len = m*n\n self.zeros = [(i, j) for i in range(m) for j in range(n)]\n\n def flip(self) -> List[int]:\n idx = choice(range(self.zeros_len))\n self.zeros_len -= 1\n self.zeros[idx], self.zeros[self.zeros_len] = self.zeros[self.zeros_len], self.zeros[idx]\n return self.zeros[self.zeros_len]\n\n def reset(self) -> None:\n self.zeros_len = len(self.zeros)\n```\n\n$O(1)$ solution using a hashmap\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.m, self.n, self.zeros_len = m, n, m*n\n self.idxs = {}\n\n def flip(self) -> List[int]:\n idx = choice(range(self.zeros_len))\n self.zeros_len -= 1\n x = self.idxs.get(idx, idx)\n self.idxs[idx] = self.idxs.get(self.zeros_len, self.zeros_len) \n return divmod(x, self.n)\n\n def reset(self) -> None:\n self.zeros_len = self.m*self.n\n self.idxs.clear()\n```
| 0
|
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.
|
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
|
[Python] Explained solution O(m*n) -> O(1)
|
random-flip-matrix
| 0
| 1
|
# Intuition\nThe idea is to first represent the matrix as a list of points `zeros = [(i, j) for i in range(m) for j in range(n)]`.\nNow we can keep track of picked points during flips by splitting the list into left and right parts. We\'ll store picked ones in the right part, while left part will be the source for new flips.\n\n# Approach\nIf we\'re fine with populating and storing the list `zeros`, which is $O(m*n)$ in TC and SC, we can do the flips in place by keeping track of the length of the source - `zeros_len`. And each time we do a flip, we\'ll:\n1. Pick randomly index `idx` so that `idx < zeros_len`\n2. Decrease `zeros_len` by `1`.\n3. Swap the flipped point `zeros[idx]` with the last element in the left side - `zeros[zeros_len]`\n\nThis approach TLEs on the last test, because it\'s linear in time. So we can do better then that. The important observation here is that we don\'t actually need to store the list `zeros`. All we care about are the swaps and we can keep track of them using a hashmap - `idxs`. `idxs[i]` is the current point under index `i`.\n\n# Complexity\n- Time complexity:\n$O(1)$\n\n- Space complexity:\n$O(k)$, where $k$ - the number of consecutive flips\n\n# Code\n$O(m*n)$ solution using a list of all elements in the matrix. TLEs on the last test\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.zeros_len = m*n\n self.zeros = [(i, j) for i in range(m) for j in range(n)]\n\n def flip(self) -> List[int]:\n idx = choice(range(self.zeros_len))\n self.zeros_len -= 1\n self.zeros[idx], self.zeros[self.zeros_len] = self.zeros[self.zeros_len], self.zeros[idx]\n return self.zeros[self.zeros_len]\n\n def reset(self) -> None:\n self.zeros_len = len(self.zeros)\n```\n\n$O(1)$ solution using a hashmap\n```\nclass Solution:\n\n def __init__(self, m: int, n: int):\n self.m, self.n, self.zeros_len = m, n, m*n\n self.idxs = {}\n\n def flip(self) -> List[int]:\n idx = choice(range(self.zeros_len))\n self.zeros_len -= 1\n x = self.idxs.get(idx, idx)\n self.idxs[idx] = self.idxs.get(self.zeros_len, self.zeros_len) \n return divmod(x, self.n)\n\n def reset(self) -> None:\n self.zeros_len = self.m*self.n\n self.idxs.clear()\n```
| 0
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
If used take next available, 95% speed
|
random-flip-matrix
| 0
| 1
|
Runtime: 48 ms, faster than 95.00% of Python3 online submissions for Random Flip Matrix.\nMemory Usage: 14.7 MB, less than 59.17% of Python3 online submissions for Random Flip Matrix.\n```\nfrom random import randint\nclass Solution:\n\n def __init__(self, n_rows: int, n_cols: int):\n self.rows = n_rows\n self.cols = n_cols\n self.len_range = n_rows * n_cols\n self.upper_limit = self.len_range - 1\n self.used = set()\n\n def flip(self):\n val = randint(0, self.upper_limit)\n while val in self.used:\n val += 1\n if val == self.len_range:\n val = 0\n self.used.add(val)\n return list(divmod(val, self.cols))\n\n def reset(self) -> None:\n self.used = set()\n```
| 2
|
There is an `m x n` binary grid `matrix` with all the values set `0` initially. Design an algorithm to randomly pick an index `(i, j)` where `matrix[i][j] == 0` and flips it to `1`. All the indices `(i, j)` where `matrix[i][j] == 0` should be equally likely to be returned.
Optimize your algorithm to minimize the number of calls made to the **built-in** random function of your language and optimize the time and space complexity.
Implement the `Solution` class:
* `Solution(int m, int n)` Initializes the object with the size of the binary matrix `m` and `n`.
* `int[] flip()` Returns a random index `[i, j]` of the matrix where `matrix[i][j] == 0` and flips it to `1`.
* `void reset()` Resets all the values of the matrix to be `0`.
**Example 1:**
**Input**
\[ "Solution ", "flip ", "flip ", "flip ", "reset ", "flip "\]
\[\[3, 1\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, \[1, 0\], \[2, 0\], \[0, 0\], null, \[2, 0\]\]
**Explanation**
Solution solution = new Solution(3, 1);
solution.flip(); // return \[1, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
solution.flip(); // return \[2, 0\], Since \[1,0\] was returned, \[2,0\] and \[0,0\]
solution.flip(); // return \[0, 0\], Based on the previously returned indices, only \[0,0\] can be returned.
solution.reset(); // All the values are reset to 0 and can be returned.
solution.flip(); // return \[2, 0\], \[0,0\], \[1,0\], and \[2,0\] should be equally likely to be returned.
**Constraints:**
* `1 <= m, n <= 104`
* There will be at least one free cell for each call to `flip`.
* At most `1000` calls will be made to `flip` and `reset`.
|
Keep prefix sums of both arrays. Can the difference between the prefix sums at an index help us? What happens if the difference between the two prefix sums at an index a is x, and x again at a different index b? This means that the sum of nums1 from index a + 1 to index b is equal to the sum of nums2 from index a + 1 to index b.
|
If used take next available, 95% speed
|
random-flip-matrix
| 0
| 1
|
Runtime: 48 ms, faster than 95.00% of Python3 online submissions for Random Flip Matrix.\nMemory Usage: 14.7 MB, less than 59.17% of Python3 online submissions for Random Flip Matrix.\n```\nfrom random import randint\nclass Solution:\n\n def __init__(self, n_rows: int, n_cols: int):\n self.rows = n_rows\n self.cols = n_cols\n self.len_range = n_rows * n_cols\n self.upper_limit = self.len_range - 1\n self.used = set()\n\n def flip(self):\n val = randint(0, self.upper_limit)\n while val in self.used:\n val += 1\n if val == self.len_range:\n val = 0\n self.used.add(val)\n return list(divmod(val, self.cols))\n\n def reset(self) -> None:\n self.used = set()\n```
| 2
|
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns.
The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph.
The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`.
During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`.
Additionally, it is not allowed for the Cat to travel to the Hole (node 0.)
Then, the game can end in three ways:
* If ever the Cat occupies the same node as the Mouse, the Cat wins.
* If ever the Mouse reaches the Hole, the Mouse wins.
* If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw.
Given a `graph`, and assuming both players play optimally, return
* `1` if the mouse wins the game,
* `2` if the cat wins the game, or
* `0` if the game is a draw.
**Example 1:**
**Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\]
**Output:** 1
**Constraints:**
* `3 <= graph.length <= 50`
* `1 <= graph[i].length < graph.length`
* `0 <= graph[i][j] < graph.length`
* `graph[i][j] != i`
* `graph[i]` is unique.
* The mouse and the cat can always move.
| null |
C++ || PYTHON || O(N) || 0ms || Beats 100%
|
detect-capital
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- First we can simply check whether all of the characters are capital or not, we can use ascii value to check this.\n\n- If all are not capital, then we can check the characters excluding the first character if they are all small or not.\n\n- If alll characters are not capital then it does not matter if first character is capital or small.\n\n- Then we just just have to check for remaining characters if theyt are all small or not.\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\nCPP / C++\n```\nclass Solution {\npublic:\n bool detectCapitalUse(string word) {\n bool allcaps = false;\n for(int i=0; i<word.length(); i++) {\n int temp = word[i];\n\n if( temp <= 90) allcaps = true;\n else {\n allcaps = false;\n break;\n }\n }\n\n if( allcaps ) return true;\n\n for(int i=1; i<word.length(); i++) {\n int temp = word[i];\n if( temp < 97 ) return false;\n }\n\n return true;\n \n }\n};\n```\n---\nPYTHON\n```\nclass Solution:\n def detectCapitalUse(self, word: str) -> bool:\n allCaps = False\n\n for i in word:\n if ord(i)<=90:\n allCaps =True\n else:\n allCaps = False\n break\n if allCaps:\n return True\n\n for i in range(1, len(word)):\n if ord(word[i])<97:\n return False\n\n \n return True\n```
| 2
|
We define the usage of capitals in a word to be right when one of the following cases holds:
* All letters in this word are capitals, like `"USA "`.
* All letters in this word are not capitals, like `"leetcode "`.
* Only the first letter in this word is capital, like `"Google "`.
Given a string `word`, return `true` if the usage of capitals in it is right.
**Example 1:**
**Input:** word = "USA"
**Output:** true
**Example 2:**
**Input:** word = "FlaG"
**Output:** false
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase and uppercase English letters.
| null |
Solution
|
detect-capital
| 1
| 1
|
```C++ []\nclass Solution {\npublic:\n bool detectCapitalUse(string word) {\n int count = count_if(word.begin(), word.end(), [](char c){ return isupper(c); });\n return count == word.length() || count == 0 || (count == 1 && isupper(word[0]));\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def detectCapitalUse(self, s: str) -> bool:\n if s.isupper() or s.islower() or s.title() == s:\n return True\n else:\n return False\n```\n\n```Java []\nclass Solution {\n public boolean detectCapitalUse(String word) {\n if(word.length() == 0 || word.length() == 1) return true;\n \n if(Character.isUpperCase(word.charAt(0))){\n boolean isFirstCharacter = Character.isUpperCase(word.charAt(1));\n for(int i = 2; i < word.length(); i++){\n boolean currentCharState = Character.isUpperCase(word.charAt(i));\n if(currentCharState != isFirstCharacter) return false;\n }\n }else{\n for(int i = 1; i < word.length(); i++){\n if(Character.isUpperCase(word.charAt(i))) return false;\n }\n }\n return true;\n }\n}\n```\n
| 1
|
We define the usage of capitals in a word to be right when one of the following cases holds:
* All letters in this word are capitals, like `"USA "`.
* All letters in this word are not capitals, like `"leetcode "`.
* Only the first letter in this word is capital, like `"Google "`.
Given a string `word`, return `true` if the usage of capitals in it is right.
**Example 1:**
**Input:** word = "USA"
**Output:** true
**Example 2:**
**Input:** word = "FlaG"
**Output:** false
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase and uppercase English letters.
| null |
python one liner :)
|
detect-capital
| 0
| 1
|
c0ck funny haha\n\n# Code\n```\nclass Solution:\n def detectCapitalUse(self, c0ck: str) -> bool:\n return c0ck.isupper() or c0ck.islower() or c0ck.istitle()\n```
| 1
|
We define the usage of capitals in a word to be right when one of the following cases holds:
* All letters in this word are capitals, like `"USA "`.
* All letters in this word are not capitals, like `"leetcode "`.
* Only the first letter in this word is capital, like `"Google "`.
Given a string `word`, return `true` if the usage of capitals in it is right.
**Example 1:**
**Input:** word = "USA"
**Output:** true
**Example 2:**
**Input:** word = "FlaG"
**Output:** false
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase and uppercase English letters.
| null |
Solution
|
longest-uncommon-subsequence-i
| 1
| 1
|
```C++ []\nclass Solution {\npublic:\n int findLUSlength(string a, string b) {\n if (a == b) {\n return -1;\n }\n return max(a.length(), b.length());\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n return -1 if a == b else max(len(a), len(b))\n```\n\n```Java []\nclass Solution {\n public int findLUSlength(String a, String b) {\n if(a.equals(b)){\n return -1;\n }\n return Math.max(a.length(),b.length());\n }\n}\n```\n
| 1
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
[Python 3] One-liner - Greedy - Simple solution
|
longest-uncommon-subsequence-i
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n return -1 if a == b else max(len(a), len(b))\n```
| 4
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
521: Time 91.38% and Space 94.99%, Solution with step by step explanation
|
longest-uncommon-subsequence-i
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if both strings a and b are equal. If they are, then there is no uncommon subsequence between them, so return -1.\n2. If both strings a and b are not equal, then the longest uncommon subsequence would be the longest string among a and b. Because any subsequence of the longer string that is also a subsequence of the shorter string cannot be uncommon. Hence, return the length of the longest string between a and b.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n # Check if both strings are equal\n if a == b:\n return -1\n else:\n # Return the length of the longest string between a and b\n return max(len(a), len(b))\n\n```
| 5
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
Python3||O(1)
|
longest-uncommon-subsequence-i
| 0
| 1
|
# 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(1)\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 findLUSlength(self, A: str, B: str) -> int:\n if A == B:\n return -1\n return max(len(A), len(B))\n```
| 2
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
python two lines | easy
|
longest-uncommon-subsequence-i
| 0
| 1
|
```\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n if a==b:return -1\n else:return max(len(a),len(b))\n```\n**if you like do upvote !**
| 6
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
Longest Uncommon Subsequence via String Comparison
|
longest-uncommon-subsequence-i
| 0
| 1
|
# Approach\n1. If both strings, a and b, are equal, it means there\'s no uncommon subsequence, so you set output to -1.\n2. Otherwise, if the strings are not equal, the longest uncommon subsequence would be the length of the longer string between a and b. You return the length of the longer string as the output.\n\n# Complexity\n- Time complexity:\n O(min(len(a), len(b)))\n\n- Space complexity:\n O(1) \n\n# Code\n```\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n \n output = 0\n\n if a == b:\n output = -1\n else:\n output = max(len(b),len(a))\n\n\n return output\n\n \n\n```
| 0
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
very easy solution for begginers
|
longest-uncommon-subsequence-i
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n if a!=b:\n return max(len(a),len(b))\n else:\n return -1\n \n```
| 0
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
sergey solution
|
longest-uncommon-subsequence-i
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n return -1 if a == b else max(len(a), len(b))\n```
| 0
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
Easy Loop Solution
|
longest-uncommon-subsequence-i
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLUSlength(self, a: str, b: str) -> int:\n C=0\n if (a==b):\n return -1\n else:\n for i in range(len(a)):\n if a[i]!=b[i]:\n continue\n else:\n break\n return max(len(a),len(b))\n \n```
| 0
|
Given two strings `a` and `b`, return _the length of the **longest uncommon subsequence** between_ `a` _and_ `b`. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between two strings is a string that is a **subsequence of one but not the other**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** a = "aba ", b = "cdc "
**Output:** 3
**Explanation:** One longest uncommon subsequence is "aba " because "aba " is a subsequence of "aba " but not "cdc ".
Note that "cdc " is also a longest uncommon subsequence.
**Example 2:**
**Input:** a = "aaa ", b = "bbb "
**Output:** 3
**Explanation:** The longest uncommon subsequences are "aaa " and "bbb ".
**Example 3:**
**Input:** a = "aaa ", b = "aaa "
**Output:** -1
**Explanation:** Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
**Constraints:**
* `1 <= a.length, b.length <= 100`
* `a` and `b` consist of lower-case English letters.
| null |
Solution
|
longest-uncommon-subsequence-ii
| 1
| 1
|
```C++ []\nclass Solution {\npublic:\n int findLUSlength(vector<string>& strs) {\n if (strs.empty()) return -1;\n int rst = -1;\n for(auto i = 0; i < strs.size(); ++i) {\n int j = 0;\n for(; j < strs.size(); ++j) {\n if(i==j) continue;\n if(LCS(strs[i], strs[j])) break;\n }\n if(j==strs.size()) rst = max(rst, static_cast<int>(strs[i].size()));\n }\n return rst;\n }\n bool LCS(const string& a, const string& b) {\n if (b.size() < a.size()) return false;\n int i = 0;\n for(auto ch: b) {\n if(i < a.size() && a[i] == ch) i++;\n }\n return i == a.size();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findLUSlength(self, strs: List[str]) -> int:\n def subseq(w1, w2):\n if len(w1) > len(w2):\n return False\n i = 0\n for c in w2:\n if i < len(w1) and w1[i] == c:\n i += 1\n return i == len(w1)\n \n strs.sort(key = len, reverse = True)\n for i, word1 in enumerate(strs):\n if all(not subseq(word1, word2) \n for j, word2 in enumerate(strs) if i != j): \n return len(word1)\n return -1\n```\n\n```Java []\nclass Solution {\n public int findLUSlength(String[] strs) {\n Arrays.sort(strs, new Comparator<String>() {\n public int compare(String o1, String o2) {\n return o2.length() - o1.length();\n }\n });\n Set<String> duplicates = getDuplicates(strs);\n for(int i = 0; i < strs.length; i++) {\n if(!duplicates.contains(strs[i])) {\n if(i == 0) return strs[0].length();\n for(int j = 0; j < i; j++) {\n if(isSubsequence(strs[j], strs[i])) break;\n if(j == i-1) return strs[i].length();\n }\n }\n }\n return -1;\n }\n public boolean isSubsequence(String a, String b) {\n int i = 0, j = 0;\n while(i < a.length() && j < b.length()) {\n if(a.charAt(i) == b.charAt(j)) j++;\n i++;\n }\n return j == b.length();\n }\n private Set<String> getDuplicates(String[] strs) {\n Set<String> set = new HashSet<String>();\n Set<String> duplicates = new HashSet<String>();\n for(String s : strs) {\n if(set.contains(s)) duplicates.add(s);\n set.add(s);\n }\n return duplicates;\n }\n}\n```\n
| 1
|
Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between an array of strings is a string that is a **subsequence of one string but not the others**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** strs = \["aba","cdc","eae"\]
**Output:** 3
**Example 2:**
**Input:** strs = \["aaa","aaa","aa"\]
**Output:** -1
**Constraints:**
* `2 <= strs.length <= 50`
* `1 <= strs[i].length <= 10`
* `strs[i]` consists of lowercase English letters.
| null |
522: Solution with step by step explanation
|
longest-uncommon-subsequence-ii
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We define a helper function isSubsequence(a: str, b: str) -> bool that returns True if string a is a subsequence of string b, and False otherwise. We do this by iterating through each character in b, and for each character that matches the current character in a, we move to the next character in a. If we\'ve successfully matched all characters in a, then it is a subsequence of b.\n\n2. We sort the input list strs in descending order of length using the sort() method and a lambda function that returns the negative length of each string.\n\n3. We iterate through each string in the sorted list using the enumerate() function. For each string s and its index i, we check if s is a subsequence of any other string in the list using a list comprehension with the all() function. The comprehension iterates through each string strs[j] in the input list, where j is the index of strs[j]. We exclude the current string s by adding the condition if j != i.\n\n4. If s is not a subsequence of any other string in the list, then it is an uncommon subsequence. We return its length using the len() function.\n\n5. If we\'ve checked every string in the list and found no uncommon subsequences, we return -1.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLUSlength(self, strs: List[str]) -> int:\n def isSubsequence(a: str, b: str) -> bool:\n i = 0\n for char in b:\n if i < len(a) and a[i] == char:\n i += 1\n return i == len(a)\n \n strs.sort(key=lambda s: -len(s))\n \n for i, s in enumerate(strs):\n if all(not isSubsequence(s, strs[j]) for j in range(len(strs)) if j != i):\n return len(s)\n \n return -1\n\n```
| 4
|
Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between an array of strings is a string that is a **subsequence of one string but not the others**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** strs = \["aba","cdc","eae"\]
**Output:** 3
**Example 2:**
**Input:** strs = \["aaa","aaa","aa"\]
**Output:** -1
**Constraints:**
* `2 <= strs.length <= 50`
* `1 <= strs[i].length <= 10`
* `strs[i]` consists of lowercase English letters.
| null |
98% TC and 78% SC easy python solution
|
longest-uncommon-subsequence-ii
| 0
| 1
|
```\ndef findLUSlength(self, strs: List[str]) -> int:\n\tdef isSub(x, y):\n\t\ti = j = 0\n\t\twhile(i<len(x) and j<len(y)):\n\t\t\tif(x[i] == y[j]):\n\t\t\t\ti += 1\n\t\t\tj += 1\n\t\treturn i == len(x)\n\tstrs.sort(key = len, reverse = True)\n\tn = len(strs)\n\tfor i in range(n):\n\t\tp = 1\n\t\tfor j in range(n):\n\t\t\tif(i != j and isSub(strs[i], strs[j])):\n\t\t\t\tp = 0\n\t\t\t\tbreak\n\t\tif(p):\n\t\t\treturn len(strs[i])\n\treturn -1\n```
| 1
|
Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between an array of strings is a string that is a **subsequence of one string but not the others**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** strs = \["aba","cdc","eae"\]
**Output:** 3
**Example 2:**
**Input:** strs = \["aaa","aaa","aa"\]
**Output:** -1
**Constraints:**
* `2 <= strs.length <= 50`
* `1 <= strs[i].length <= 10`
* `strs[i]` consists of lowercase English letters.
| null |
✅Bruet force solution || python
|
longest-uncommon-subsequence-ii
| 0
| 1
|
# Code\n```\nclass Solution:\n\n def sub(self,s,i,temp,d):\n if(i==len(s)):\n d[temp[:]]=d.get(temp[:],0)+1\n return \n self.sub(s,i+1,temp+s[i],d)\n self.sub(s,i+1,temp,d)\n return \n\n def findLUSlength(self, strs: List[str]) -> int:\n d={}\n for s in strs:\n self.sub(s,0,"",d)\n ans=-1\n for a,b in d.items():\n if(b>1):continue\n ans=max(ans,len(a))\n return ans\n \n```
| 0
|
Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between an array of strings is a string that is a **subsequence of one string but not the others**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** strs = \["aba","cdc","eae"\]
**Output:** 3
**Example 2:**
**Input:** strs = \["aaa","aaa","aa"\]
**Output:** -1
**Constraints:**
* `2 <= strs.length <= 50`
* `1 <= strs[i].length <= 10`
* `strs[i]` consists of lowercase English letters.
| null |
Concise and short implementation in Python, Faster than 98%
|
longest-uncommon-subsequence-ii
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimilar to the previuos [problem](https://leetcode.com/problems/longest-uncommon-subsequence-i/), the answer is the longest string that is not a subsequence of another strings. So, a string that appears more than once is not an answer. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe solution is trivial. Count the occurrances of each distinct string, and sort the strings by their lengths. From the longest string, we check the occurrence of the string and check if it is a subsequence of another longer string. \n\n# Complexity\n- Time complexity: $$O(N \\log N + NM)$$, where $$N$$ is the number of strings, $$M$$ is the maximum length of strings. My implementation is slower because the string lengths are computed during sorting. The length can be precomputed for large $$M$$. \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLUSlength(self, strs: List[str]) -> int:\n def is_subseq(s, t):\n for c in s:\n if c == t[0]:\n t = t[1:]\n if not t:\n return True\n return False\n\n strs = sorted(Counter(strs).items(), key=lambda x: -len(x[0]))\n for i, (s, c) in enumerate(strs):\n if c == 1 and all(not is_subseq(strs[j][0], s) for j in range(i)):\n return len(s)\n return -1\n```
| 0
|
Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between an array of strings is a string that is a **subsequence of one string but not the others**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** strs = \["aba","cdc","eae"\]
**Output:** 3
**Example 2:**
**Input:** strs = \["aaa","aaa","aa"\]
**Output:** -1
**Constraints:**
* `2 <= strs.length <= 50`
* `1 <= strs[i].length <= 10`
* `strs[i]` consists of lowercase English letters.
| null |
BRUTE FORCE SOLUTION
|
longest-uncommon-subsequence-ii
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBRUTE FORCE \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUSING LCS\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLUSlength(self, s: List[str]) -> int:\n def lcs(X, Y):\n m = len(X)\n n = len(Y)\n L = [[None]*(n + 1) for i in range(m + 1)]\n for i in range(m + 1):\n for j in range(n + 1):\n if i == 0 or j == 0 :\n L[i][j] = 0\n elif X[i-1] == Y[j-1]:\n L[i][j] = L[i-1][j-1]+1\n else:\n L[i][j] = max(L[i-1][j], L[i][j-1])\n return L[m][n]\n \n k = 0 \n mp = {}\n for i in s:\n if len(i) not in mp:\n mp[len(i)] = [i]\n else:\n mp[len(i)].append(i)\n k = max(k , len(i))\n \n t = k\n while(k):\n if k not in mp:\n k -= 1\n else:\n curr = mp[k]\n n = len(curr)\n for i in range(n):\n f = 0\n for j in range(n):\n if(i != j and curr[i] == curr[j]):\n f = 1\n break\n if(not(f)):\n ff = 0 \n for j in range(k+1 , t+1):\n if(ff):break\n if(j not in mp): continue\n for jj in mp[j]:\n if(lcs(curr[i] , jj) == len(curr[i])):\n ff = 1\n break\n if(not(ff)):return len(curr[i])\n k-=1\n \n return -1\n\n \n\n \n```
| 0
|
Given an array of strings `strs`, return _the length of the **longest uncommon subsequence** between them_. If the longest uncommon subsequence does not exist, return `-1`.
An **uncommon subsequence** between an array of strings is a string that is a **subsequence of one string but not the others**.
A **subsequence** of a string `s` is a string that can be obtained after deleting any number of characters from `s`.
* For example, `"abc "` is a subsequence of `"aebdc "` because you can delete the underlined characters in `"aebdc "` to get `"abc "`. Other subsequences of `"aebdc "` include `"aebdc "`, `"aeb "`, and `" "` (empty string).
**Example 1:**
**Input:** strs = \["aba","cdc","eae"\]
**Output:** 3
**Example 2:**
**Input:** strs = \["aaa","aaa","aa"\]
**Output:** -1
**Constraints:**
* `2 <= strs.length <= 50`
* `1 <= strs[i].length <= 10`
* `strs[i]` consists of lowercase English letters.
| null |
Solution
|
longest-word-in-dictionary-through-deleting
| 1
| 1
|
```C++ []\n\nclass Solution {\npublic:\n string findLongestWord(string s, vector<string>& dictionary) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n string res;\n for (int i = 0; i < dictionary.size();i++)\n {\n string &word = dictionary[i];\n\n if (word.size() > s.size() || word.size() < res.size())\n continue;\n\n auto found = s.find(word[0]); \n\n int j = 1;\n for (j; j < word.size(); j++)\n { \n found = s.find(word[j],found+1);\n if (found == string::npos)\n break; \n }\n if (found == string::npos)\n continue;\n\n if (j > res.size())\n {\n res = word;\n continue;\n }\n if (j == res.size())\n {\n for (int i = 0; i < res.size();i++)\n {\n if (word[i] < res[i])\n {\n res = word;\n break;\n }\n else if (word[i] == res[i])\n continue;\n else\n break;\n }\n }\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findLongestWord(self, S: str, D: List[str]) -> str:\n ans = ""\n for word in D:\n a, b = len(word), len(ans)\n if a < b or (a == b and word > ans): continue\n pos = -1\n for char in word:\n pos = S.find(char, pos + 1)\n if pos == -1: break\n else: ans = word\n return ans\n```\n\n```Java []\nclass Solution {\n public String findLongestWord(String s, List<String> dictionary) {\n int[][] nextChar = preprocess(s);\n String output = null;\n for(String word : dictionary)\n if(found(nextChar, word) && (output==null || output.length() < word.length() || (output.length() == word.length() && output.compareTo(word)>0)))\n output = word;\n return (output==null)?"":output;\n }\n private boolean found(int[][] nextChar, String word) {\n int ind=nextChar[0][word.charAt(0)-\'a\']+1;\n for(int i=1;i<word.length();i++) {\n if(ind==0)return false;\n ind = nextChar[ind][word.charAt(i)-\'a\']+1;\n }\n return ind!=0;\n }\n private int[][] preprocess(String s) {\n int n = s.length();\n int[][] nextChar = new int[n+1][26];\n Arrays.fill(nextChar[n], -1);\n for(int i=n-1;i>=0;i--) {\n for(int j=0;j<26;j++)\n nextChar[i][j] = nextChar[i+1][j];\n nextChar[i][s.charAt(i)-\'a\'] = i;\n }\n return nextChar;\n }\n}\n```\n
| 1
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
python3 two solutions
|
longest-word-in-dictionary-through-deleting
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLongestWord(self, s: str, d: List[str]) -> str:\n longest_word = \'\'\n for word in d:\n i , j =0 , 0\n while i < len(word) and j < len(s):\n if word[i] == s[j]:\n i+=1\n j+=1\n else:\n j+=1\n if i == len(word):\n if len(longest_word) < len(word):\n longest_word = word\n elif len(word) == len(longest_word):\n longest_word = min(longest_word , word)\n return longest_word\n\nclass Solution:\n def findLongestWord(self, s: str, d: List[str]) -> str:\n res = \'\'\n for cand in d:\n if self.find(s, cand) and (len(cand) > len(res) or (len(cand) == len(res) and cand < res)):\n res = cand\n return res\n \n\n def find(self , s ,d):\n i , j = 0 , 0\n while i < len(s) and j < len(d):\n if s[i] == d[j]:\n i+=1\n j+=1\n else:\n i+=1\n return j == len(d)\n
| 1
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
524: Solution with step by step explanation
|
longest-word-in-dictionary-through-deleting
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Sort the dictionary d in descending order by length and then lexicographically.\n2. Traverse through the dictionary d using a for loop.\n3. Set a variable i to 0 to keep track of the index of the current character in the word.\n4. Traverse through the string s using a for loop.\n5. If the current character in s is the same as the character at the current index i in the word, increment i by 1.\n6. If we have found all the characters in the word, break the loop.\n7. If we have found all the characters in the word, return the word.\n8. If we have not found any word, return an empty string.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLongestWord(self, s: str, d: List[str]) -> str:\n # Sort the dictionary by length and lexicographically\n d.sort(key=lambda x: (-len(x), x))\n \n # Traverse through the dictionary\n for word in d:\n i = 0\n # Traverse through the string s\n for char in s:\n if i < len(word) and char == word[i]:\n i += 1\n # If we have found all the characters in the word, break the loop\n if i == len(word):\n break\n # If we have found all the characters in the word, return the word\n if i == len(word):\n return word\n return ""\n\n```
| 6
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
Python simple straight-forward solution
|
longest-word-in-dictionary-through-deleting
| 0
| 1
|
```\nclass Solution:\n def findLongestWord(self, s: str, dictionary: list[str]) -> str:\n def is_valid(string): # can we get the string by deleting some letters or not\n i = 0\n for letter in s:\n if letter == string[i]:\n i += 1\n if i == len(string):\n return True\n return i == len(string)\n\n dictionary.sort() # sorting alphabetically\n dictionary.sort(key=len, reverse=True) # sorting by the length; as a result - sorting both alphabetically and by length\n for word in dictionary:\n if is_valid(word):\n return word\n return \'\'\n```
| 4
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
Python. very clear and simplistic solution.
|
longest-word-in-dictionary-through-deleting
| 0
| 1
|
```\nclass Solution:\n def findLongestWord(self, s: str, d: List[str]) -> str:\n def is_subseq(main: str, sub: str) -> bool:\n i, j, m, n = 0, 0, len(main), len(sub)\n while i < m and j < n and n - j >= m - i:\n if main[i] == sub[j]:\n i += 1\n j += 1\n return i == m\n \n res = \'\'\n helper = sorted(d, key = lambda x: len(x), reverse = True)\n for word in helper:\n if len(word) < len(res): return res\n if ( not res or word < res ) and is_subseq(word, s):\n res = word\n return res
| 6
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
Python N pointers + Bucket sort O(m * n) Solution
|
longest-word-in-dictionary-through-deleting
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhile traversing through the string, increment pointers that each correspond to the current position of the word. When a pointer reaches the end of a word, add it to a complete list that is used later in the bucket sort.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(M * N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M + N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLongestWord(self, s: str, dictionary: List[str]) -> str:\n n = len(dictionary)\n pointers = [0] * n\n\n complete = [-1] * (len(s) + 1)\n for ch in s:\n for i in range(n):\n word = dictionary[i]\n if pointers[i] == -1:\n continue\n if ch == word[pointers[i]]:\n pointers[i] += 1\n l = len(word)\n if pointers[i] == l:\n if complete[l] == -1 or word < dictionary[complete[l]]:\n complete[l] = i\n pointers[i] = -1\n \n for i in range(len(s), 0, -1):\n if complete[i] != -1:\n return dictionary[complete[i]]\n\n return ""\n \n```
| 0
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
✅Easy Solution Brute Force Approach✅
|
longest-word-in-dictionary-through-deleting
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLongestWord(self, s: str, dictionary: List[str]) -> str:\n dictionary.sort(key=lambda x: len(x), reverse=True)\n l = []\n length = []\n for word in dictionary:\n j = 0\n for i in range(len(s)):\n if j < len(word) and s[i] == word[j]:\n j += 1\n if j == len(word):\n l.append(word)\n length.append(len(word))\n l.sort()\n for i in l:\n if len(i)==max(length):\n return i\n return "" \n\n\n```
| 0
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
Python3 | 2 Pointers approach
|
longest-word-in-dictionary-through-deleting
| 0
| 1
|
# Approach\n<!-- Describe your approach to solving the problem. --> Iterate every dictionary string within s, increase the index of s if element matches or not, increase index for dictionary string only if element matches, maintain a count(here j, index for dict string is acting as count as well), if count equals to length of string dict(2 approaches):\n* If we have sorted dict initially using ``, then directly return dict string(Space complexity will increase)\n```python []\ndictionary.sort(key = lambda x: (-len(x), x))\n```\n\n* Use conditions to check lexographical order based on first length then value(Better Space complexity): \n```python []\nif j==n and (len(ans)<n or ((len(ans)==n) and st<ans))\n```\n\n# Complexity\n- Time complexity: O(number_of_string_in_dict * length_of_string)\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 def findLongestWord(self, s: str, dictionary: List[str]) -> str:\n m=len(s)\n ans=""\n for st in dictionary:\n i=0\n n=len(st)\n for c in s:\n if i<n and c==st[i]:\n i=i+1;\n if i==n and (len(ans)<n or ((len(ans)==n) and st<ans)) :\n ans=st\n return ans\n\n```
| 0
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
720. Longest Word in Dictionary
|
longest-word-in-dictionary-through-deleting
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findLongestWord(self, s: str, dictionary: List[str]) -> str:\n ans=\'\'\n for word in dictionary:\n a,b=len(word),len(ans)\n if a<b or (a==b and word>ans): continue\n pos=-1\n i=0\n for char in word:\n pos=s.find(char,pos+1) # \u4ECEpos+1\u4F4D\u7F6E\u5F00\u59CB\u627E\n if pos==-1:break\n i+=1\n if i==a: ans=word\n \n return ans\n \n```
| 0
|
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
**Example 1:**
**Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\]
**Output:** "apple "
**Example 2:**
**Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\]
**Output:** "a "
**Constraints:**
* `1 <= s.length <= 1000`
* `1 <= dictionary.length <= 1000`
* `1 <= dictionary[i].length <= 1000`
* `s` and `dictionary[i]` consist of lowercase English letters.
| null |
Solution
|
contiguous-array
| 1
| 1
|
```C++ []\nclass Solution {\npublic:\n int findMaxLength(vector<int>& nums) {\n int n = nums.size();\n vector<int> vect(2 * n + 1, INT_MIN);\n vect[nums.size()] = -1;\n int totalSum = 0, maxLength = 0;\n for (int i = 0; i < n; i++)\n {\n totalSum += (nums[i] == 0 ? -1 : 1);\n if (vect[totalSum + n] >= -1)\n maxLength = max(maxLength, i - vect[totalSum + n]);\n else\n vect[totalSum + n] = i;\n }\n return maxLength;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findMaxLength(self, nums: List[int]) -> int:\n totalsum,hashmap=0,{0:-1}\n res,diff=0,0\n for i in range(len(nums)):\n if(nums[i]==0):\n totalsum-=1\n else:\n totalsum+=1\n try:\n diff=i-hashmap[totalsum]\n if(diff>res):\n res=diff\n except:\n hashmap[totalsum]=i\n return res\n```\n\n```Java []\nclass Solution {\n public int findMaxLength(int[] nums) {\n int N = nums.length;\n int[] mp = new int[2*N+2];\n int current = N;\n int result = 0;\n\n for(int i = 0; i < N; i++) {\n current += (nums[i] << 1) - 1;\n if(current == N) {\n result = i+1;\n }\n else if(mp[current] == 0) {\n mp[current] = i+1;\n }\n else {\n result = Math.max(result, i - mp[current]+1);\n }\n }\n return result;\n }\n}\n```\n
| 2
|
Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`.
**Example 1:**
**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1.
**Example 2:**
**Input:** nums = \[0,1,0\]
**Output:** 2
**Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
| null |
525: Solution with step by step explanation
|
contiguous-array
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a dictionary count with a key-value pair of 0: -1 to keep track of the count difference of 0\'s and 1\'s and the index at which it occurs.\n2. Initialize two variables, max_len and count_diff to keep track of the maximum length of contiguous subarray and the difference between the count of 0\'s and 1\'s, respectively.\n3. Traverse through the input nums list using a for loop and enumerate() function to get the index and value of each element in the list.\n4. For each element in the nums list, update the count_diff variable by incrementing 1 if the element is 1 or decrementing 1 if the element is 0.\n5. If the count_diff variable is present in the count dictionary, update the max_len variable with the maximum value of max_len and the difference between the current index and the index of the previous occurrence of the same count_diff.\n6. Else, add the count_diff and its corresponding index to the count dictionary.\n7. Return the max_len variable, which stores the length of the longest contiguous subarray with an equal number of 0 and 1.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def findMaxLength(self, nums: List[int]) -> int:\n count = {0: -1} # Initial count of 0\'s and 1\'s\n max_len = count_diff = 0\n \n for i, num in enumerate(nums):\n count_diff += 1 if num == 1 else -1 # Increment count of 1\'s or 0\'s\n if count_diff in count:\n max_len = max(max_len, i - count[count_diff])\n else:\n count[count_diff] = i\n \n return max_len\n\n```
| 5
|
Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`.
**Example 1:**
**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1.
**Example 2:**
**Input:** nums = \[0,1,0\]
**Output:** 2
**Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
| null |
Python Permutation Solution
|
beautiful-arrangement
| 0
| 1
|
It took a while for me to understand this question. In the end all they were asking for was to find a permutation of n numbers that satisfy **one of these conditions**. EIther the number at index + 1 is divisible by the index + 1 or index + 1 is divisible by the number. Also a much better example would have been to show what happens with 3 numbers.\n\nI\'ll just put one example of where this fails because it seems like a better example.\n\n***[1,3,2] - This fails because 3 is not divisible by index + 1 (2) and also index + 1 (2) is not divisible by 3.***\n\n1. Generate the array of numbers that will be used to create permutations of 1 to n (n inclusive) **ex**: 3 will become [1,2,3]\n2. Iterate through all elements in the list and compare it to i which is initialized at 1 to avoid the while index + 1 thing.\n3. If the number is divisible by i or i is divisible by the number, remove the number from nums and continue generating the permutation.\n4. If a full permutation is generated (i == n+1, aka went past the index) then we have one solution. Add that to the result.\n\n```\nclass Solution:\n def countArrangement(self, n: int) -> int:\n \n self.res = 0\n nums = [i for i in range(1, n+1)]\n \n def dfs(nums: list, i: int = 1):\n if i == n+1: \n self.res += 1\n return\n \n for j, num in enumerate(nums):\n if not(num % i and i % num):\n dfs(nums[:j] + nums[j+1:], i+1)\n \n dfs(nums)\n return self.res
| 32
|
Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true:
* `perm[i]` is divisible by `i`.
* `i` is divisible by `perm[i]`.
Given an integer `n`, return _the **number** of the **beautiful arrangements** that you can construct_.
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:**
The first beautiful arrangement is \[1,2\]:
- perm\[1\] = 1 is divisible by i = 1
- perm\[2\] = 2 is divisible by i = 2
The second beautiful arrangement is \[2,1\]:
- perm\[1\] = 2 is divisible by i = 1
- i = 2 is divisible by perm\[2\] = 1
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 15`
| null |
526: Space 98.18%, Solution with step by step explanation
|
beautiful-arrangement
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create a list of integers from 1 to n using the range function and the list constructor. Assign it to the variable nums.\n2. Initialize a variable count to 0.\n3. Define a nested function backtrack which takes an integer start as its argument and has no return value. This function will be used to generate all possible permutations of the nums list.\n4. If start is equal to n, increment count and return.\n5. Loop over all indices i from start to n-1.\n6. Swap the elements at indices start and i using Python\'s tuple unpacking feature.\n7. Check if the current element at index start is divisible by start+1 or if start+1 is divisible by the current element. If so, recursively call backtrack with the argument start+1.\n8. Swap the elements back to restore the original list.\n9. Call backtrack with the argument 0 to start generating all permutations.\n10. Return count.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countArrangement(self, n: int) -> int:\n # Initialize a list of integers from 1 to n\n nums = list(range(1, n+1))\n self.count = 0\n \n # Define a recursive function to generate all possible permutations\n def backtrack(start):\n # Base case: If all elements have been permuted, increment the count\n if start == n:\n self.count += 1\n # Recursive case: Generate all possible permutations\n for i in range(start, n):\n # Swap the current element with the start element\n nums[start], nums[i] = nums[i], nums[start]\n # Check if the current permutation is beautiful\n if nums[start] % (start+1) == 0 or (start+1) % nums[start] == 0:\n # Recurse with the next element\n backtrack(start+1)\n # Swap the current element back to restore the original list\n nums[start], nums[i] = nums[i], nums[start]\n \n # Call the recursive function with the first element\n backtrack(0)\n return self.count\n\n```
| 4
|
Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true:
* `perm[i]` is divisible by `i`.
* `i` is divisible by `perm[i]`.
Given an integer `n`, return _the **number** of the **beautiful arrangements** that you can construct_.
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:**
The first beautiful arrangement is \[1,2\]:
- perm\[1\] = 1 is divisible by i = 1
- perm\[2\] = 2 is divisible by i = 2
The second beautiful arrangement is \[2,1\]:
- perm\[1\] = 2 is divisible by i = 1
- i = 2 is divisible by perm\[2\] = 1
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 15`
| null |
Python Backtracking, the more intuitive way
|
beautiful-arrangement
| 0
| 1
|
```\nclass Solution:\n def countArrangement(self, n: int) -> int:\n self.count = 0\n self.backtrack(n, 1, [])\n return self.count\n \n def backtrack(self, N, idx, temp):\n if len(temp) == N:\n self.count += 1\n return\n \n for i in range(1, N+1):\n if i not in temp and (i % idx == 0 or idx % i == 0):\n temp.append(i)\n self.backtrack(N, idx+1, temp)\n temp.pop()\n```
| 8
|
Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true:
* `perm[i]` is divisible by `i`.
* `i` is divisible by `perm[i]`.
Given an integer `n`, return _the **number** of the **beautiful arrangements** that you can construct_.
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:**
The first beautiful arrangement is \[1,2\]:
- perm\[1\] = 1 is divisible by i = 1
- perm\[2\] = 2 is divisible by i = 2
The second beautiful arrangement is \[2,1\]:
- perm\[1\] = 2 is divisible by i = 1
- i = 2 is divisible by perm\[2\] = 1
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 15`
| null |
Python solution, easy and clear
|
beautiful-arrangement
| 0
| 1
|
```\ndef countArrangement(self, n: int) -> int:\n\tdef solve(i):\n\t\tif(i == n+1):\n\t\t\tans[0] += 1\n\t\t\treturn\n\t\tfor j in range(1, n+1):\n\t\t\tb = 1<<j\n\t\t\tif(vis[0] & b == 0):\n\t\t\t\tif not(i%j and j%i):\n\t\t\t\t\tvis[0] = vis[0] | b\n\t\t\t\t\tsolve(i+1)\n\t\t\t\t\tvis[0] = vis[0] ^ b\n\tvis = [0]\n\tans = [0] \n\tsolve(1)\n\treturn ans[0]\n```
| 1
|
Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true:
* `perm[i]` is divisible by `i`.
* `i` is divisible by `perm[i]`.
Given an integer `n`, return _the **number** of the **beautiful arrangements** that you can construct_.
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:**
The first beautiful arrangement is \[1,2\]:
- perm\[1\] = 1 is divisible by i = 1
- perm\[2\] = 2 is divisible by i = 2
The second beautiful arrangement is \[2,1\]:
- perm\[1\] = 2 is divisible by i = 1
- i = 2 is divisible by perm\[2\] = 1
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 15`
| null |
Statistically sound solution beating most in runtime and space time compelxity.
|
random-pick-with-weight
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nTreat the indices as the possible values of a random variable X. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nUsing the weights, first compute the PMF of X and then its CDF. \n\nGenerate a random value between [0, 1] using random.random(). Then use binary search to find the appropriate index.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(log(n))$$ for each call of pickIndex()\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nimport random\n\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.weights = w\n self.cdf = self.getCDF()\n\n def pickIndex(self) -> int:\n rand = random.random()\n l, r = 0, len(self.weights) - 1\n while l <= r: \n m = (r + l) // 2\n midVal = self.cdf[m]\n if rand > midVal:\n l = m + 1\n elif rand < midVal:\n r = m - 1\n else:\n return m\n return r + 1\n\n \n def getCDF(self) -> List[float]:\n cdf = [0] * len(self.weights)\n norm = sum(self.weights)\n pmf = [weight / norm for weight in self.weights]\n\n for x, p in enumerate(pmf):\n if x == 0: \n cdf[x] = p\n else:\n cdf[x] = pmf[x] + cdf[x - 1]\n\n return cdf\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n```
| 1
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
Statistically sound solution beating most in runtime and space time compelxity.
|
random-pick-with-weight
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nTreat the indices as the possible values of a random variable X. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nUsing the weights, first compute the PMF of X and then its CDF. \n\nGenerate a random value between [0, 1] using random.random(). Then use binary search to find the appropriate index.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(log(n))$$ for each call of pickIndex()\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nimport random\n\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.weights = w\n self.cdf = self.getCDF()\n\n def pickIndex(self) -> int:\n rand = random.random()\n l, r = 0, len(self.weights) - 1\n while l <= r: \n m = (r + l) // 2\n midVal = self.cdf[m]\n if rand > midVal:\n l = m + 1\n elif rand < midVal:\n r = m - 1\n else:\n return m\n return r + 1\n\n \n def getCDF(self) -> List[float]:\n cdf = [0] * len(self.weights)\n norm = sum(self.weights)\n pmf = [weight / norm for weight in self.weights]\n\n for x, p in enumerate(pmf):\n if x == 0: \n cdf[x] = p\n else:\n cdf[x] = pmf[x] + cdf[x - 1]\n\n return cdf\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n```
| 1
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
[Python] Roblox VO Preparation: Prefix Sum + Binary Search / Dichotomy Solution
|
random-pick-with-weight
| 0
| 1
|
Someone says Roblox Virtual Onsite interview includes problems like **528. Random Pick with Weight** in this post [\nRoblox Virtual Onsite | 2 Questions | 1 Hard](https://leetcode.com/discuss/interview-question/1139472/roblox-virtual-onsite-2-questions-1-hardhttp://). So I\'m doing it for practice. Wish me good luck! Fingers crossed! \uD83E\uDD1E\uD83C\uDF40\n\n*Runtime: 553 ms, faster than 35.40% of Python3 online submissions for Random Pick with Weight.\nMemory Usage: 18.8 MB, less than 23.44% of Python3 online submissions for Random Pick with Weight.*\n\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.total = sum(w)\n \n pre_sum = [0 for i in range(len(w))]\n for i in range(len(w)):\n if i == 0:\n pre_sum[i] = w[i]\n else:\n pre_sum[i] = w[i] + pre_sum[i - 1]\n # print(pre_sum)\n self.pre_sum = pre_sum\n \n def pickIndex(self) -> int:\n\t\t# random.randint(1, 3) includes 1, 2, 3\n pick = random.randint(1, self.total) # or (1, self.pre_sum[-1])\n \n l = 0\n r = len(self.pre_sum) - 1\n while l < r:\n mid = (l + r) // 2\n if pick <= self.pre_sum[mid]:\n r = mid\n else:\n l = mid + 1\n \n # while loop ends when l == r\n\t\t# return l is the same as return r\n\t\treturn l\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n```\n\nBeginner\'s solution, hope it can help! (\u25CF\'\u25E1\'\u25CF)\nI have solved 179 problems by now, I know there\'s still a loooong way to go, but I wish I could find a job by 300. (\uFF1B\u2032\u2312`)
| 2
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
[Python] Roblox VO Preparation: Prefix Sum + Binary Search / Dichotomy Solution
|
random-pick-with-weight
| 0
| 1
|
Someone says Roblox Virtual Onsite interview includes problems like **528. Random Pick with Weight** in this post [\nRoblox Virtual Onsite | 2 Questions | 1 Hard](https://leetcode.com/discuss/interview-question/1139472/roblox-virtual-onsite-2-questions-1-hardhttp://). So I\'m doing it for practice. Wish me good luck! Fingers crossed! \uD83E\uDD1E\uD83C\uDF40\n\n*Runtime: 553 ms, faster than 35.40% of Python3 online submissions for Random Pick with Weight.\nMemory Usage: 18.8 MB, less than 23.44% of Python3 online submissions for Random Pick with Weight.*\n\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.total = sum(w)\n \n pre_sum = [0 for i in range(len(w))]\n for i in range(len(w)):\n if i == 0:\n pre_sum[i] = w[i]\n else:\n pre_sum[i] = w[i] + pre_sum[i - 1]\n # print(pre_sum)\n self.pre_sum = pre_sum\n \n def pickIndex(self) -> int:\n\t\t# random.randint(1, 3) includes 1, 2, 3\n pick = random.randint(1, self.total) # or (1, self.pre_sum[-1])\n \n l = 0\n r = len(self.pre_sum) - 1\n while l < r:\n mid = (l + r) // 2\n if pick <= self.pre_sum[mid]:\n r = mid\n else:\n l = mid + 1\n \n # while loop ends when l == r\n\t\t# return l is the same as return r\n\t\treturn l\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n```\n\nBeginner\'s solution, hope it can help! (\u25CF\'\u25E1\'\u25CF)\nI have solved 179 problems by now, I know there\'s still a loooong way to go, but I wish I could find a job by 300. (\uFF1B\u2032\u2312`)
| 2
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
Python 3 simple solution
|
random-pick-with-weight
| 0
| 1
|
**Hello fellow coders! \uD83D\uDE00**\n\nI decided to post this solution because the other python3 solutions, while genius and better, were a bit hard to read. Here is the breakdown of my solution:\n* Normalize the weights in the initial w list to ratios \n\t* i.e. [1,3,3,1] --> [1 / 8, 3 / 8, 3 / 8, 1 / 8], for a general list [...i...] ---> [... i / sum(list) ...]\n\t* This give us the frequency of each index\n* Take these new weights and put them on a number line from 0 --> 1 by adding to each element all of the previous elements \n\t* i.e. [1/8, 3/8, 3/8, 1/8] --> [1/8,4/8,7/8,1], for a general list [...i...] ---> [... i + sum(all previous)...]\n\t* Note this will always mean list[-1] = 1\n\t* This gives us a number line to test a random variable on \n* Generate a random number between 0 ,1 \n* Find the section of the number line the random number falls into and return its index \n\t* I used a while loop here but if anyone has a better idea please reply! \uD83D\uDE00\n\t* This effectively gives us each index with its correct probability\n\nI hope this code makes sense! If you have any question **please** respond! \uD83D\uDE00\n```\n# used for random number generation\nimport random\n\nclass Solution:\n def __init__(self, w: List[int]):\n self.w = w\n\t\t# 1. calculate relative frequency\n denom = sum(self.w)\n for i in range(len(self.w)):\n self.w[i] = self.w[i] / denom\n # 2. put relative frequencies on the number line between 0 and 1\n\t\t# Note self.w[-1] = 1\n for i in range(1,len(self.w)):\n self.w[i] += self.w[i-1]\n \n def pickIndex(self) -> int:\n\t\t\n\t\t# this is where we pick the index\n N = random.uniform(0,1)\n \n flag = 1\n index = -1\n \n\t\t# test each region of the numberline to see if N falls in it, if it \n\t\t# does not then go to the next index and check if N falls in it\n\t\t# this is gaurenteed to break because of previous normalization\n while flag:\n index +=1 \n \n \n \n if N <= self.w[index]:\n flag = 0\n \n \n return index\n\n\n\'\'\'\nPseudocode\n1. Initialize class\n2. Get a list of all unique values\n3. normalize weights\n4. put weights on the number line\n5. If a uniform varialbe falls in the range of a value that value is returned\n\'\'\'\n```\n\n**Happy Coding!**\n\n\n**P.S.:** Looking back on it, there was no need to turn all the weights into their relative weights between [0,1]. I could have just generated a random integer between [1,sum(w)] right off the bat, but my brain immediately jumped to the uniform distribution. Hope you enjoyed! If you liked this please upvote it, so I do it more \uD83D\uDE00. \n\n
| 87
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
Python 3 simple solution
|
random-pick-with-weight
| 0
| 1
|
**Hello fellow coders! \uD83D\uDE00**\n\nI decided to post this solution because the other python3 solutions, while genius and better, were a bit hard to read. Here is the breakdown of my solution:\n* Normalize the weights in the initial w list to ratios \n\t* i.e. [1,3,3,1] --> [1 / 8, 3 / 8, 3 / 8, 1 / 8], for a general list [...i...] ---> [... i / sum(list) ...]\n\t* This give us the frequency of each index\n* Take these new weights and put them on a number line from 0 --> 1 by adding to each element all of the previous elements \n\t* i.e. [1/8, 3/8, 3/8, 1/8] --> [1/8,4/8,7/8,1], for a general list [...i...] ---> [... i + sum(all previous)...]\n\t* Note this will always mean list[-1] = 1\n\t* This gives us a number line to test a random variable on \n* Generate a random number between 0 ,1 \n* Find the section of the number line the random number falls into and return its index \n\t* I used a while loop here but if anyone has a better idea please reply! \uD83D\uDE00\n\t* This effectively gives us each index with its correct probability\n\nI hope this code makes sense! If you have any question **please** respond! \uD83D\uDE00\n```\n# used for random number generation\nimport random\n\nclass Solution:\n def __init__(self, w: List[int]):\n self.w = w\n\t\t# 1. calculate relative frequency\n denom = sum(self.w)\n for i in range(len(self.w)):\n self.w[i] = self.w[i] / denom\n # 2. put relative frequencies on the number line between 0 and 1\n\t\t# Note self.w[-1] = 1\n for i in range(1,len(self.w)):\n self.w[i] += self.w[i-1]\n \n def pickIndex(self) -> int:\n\t\t\n\t\t# this is where we pick the index\n N = random.uniform(0,1)\n \n flag = 1\n index = -1\n \n\t\t# test each region of the numberline to see if N falls in it, if it \n\t\t# does not then go to the next index and check if N falls in it\n\t\t# this is gaurenteed to break because of previous normalization\n while flag:\n index +=1 \n \n \n \n if N <= self.w[index]:\n flag = 0\n \n \n return index\n\n\n\'\'\'\nPseudocode\n1. Initialize class\n2. Get a list of all unique values\n3. normalize weights\n4. put weights on the number line\n5. If a uniform varialbe falls in the range of a value that value is returned\n\'\'\'\n```\n\n**Happy Coding!**\n\n\n**P.S.:** Looking back on it, there was no need to turn all the weights into their relative weights between [0,1]. I could have just generated a random integer between [1,sum(w)] right off the bat, but my brain immediately jumped to the uniform distribution. Hope you enjoyed! If you liked this please upvote it, so I do it more \uD83D\uDE00. \n\n
| 87
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
[Python] 6 lines Solution with Statistics Explanation
|
random-pick-with-weight
| 0
| 1
|
In Statistics, if we nomalize (divided by `self.cdf[-1]`) the `self.cdf` into [0, 1], it\'s actually a discrete distribution `cdf ` sequence. For cdf function, given `X` you can get the Cumulative Probability (aka percentile) of `X`, which is `Prob(x <= X) `.\n\nThe question is actually asking to generate random samples given by a specific statistical distribution. How?\n\nPrinciple is easy, take uniform sample from the `cdf` squence ( which can be realized by `random` ), then use `inverse_cdf` function to find the variable `X`. The binary search here is actually `inverse_cdf` function, that returns the `X` given by a Cumulative Probability.\n\n\nAfter you take enough samples by this way, and plot the histogram of these samples, you will found the plot fits well for the given distribution.\n\n\n- More information and proof can be found in [Wikipedia](https://en.wikipedia.org/wiki/Inverse_transform_sampling) & [StackExchange](https://stats.stackexchange.com/questions/161635/why-is-the-cdf-of-a-sample-uniformly-distributed).\n\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.cdf = [0]\n for weight in w:\n self.cdf.append(self.cdf[-1] + weight)\n\n def pickIndex(self) -> int:\n rand = random.randint(1, self.cdf[-1])\n idx = bisect.bisect_left(self.cdf, rand)\n return idx - 1\n```
| 33
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
[Python] 6 lines Solution with Statistics Explanation
|
random-pick-with-weight
| 0
| 1
|
In Statistics, if we nomalize (divided by `self.cdf[-1]`) the `self.cdf` into [0, 1], it\'s actually a discrete distribution `cdf ` sequence. For cdf function, given `X` you can get the Cumulative Probability (aka percentile) of `X`, which is `Prob(x <= X) `.\n\nThe question is actually asking to generate random samples given by a specific statistical distribution. How?\n\nPrinciple is easy, take uniform sample from the `cdf` squence ( which can be realized by `random` ), then use `inverse_cdf` function to find the variable `X`. The binary search here is actually `inverse_cdf` function, that returns the `X` given by a Cumulative Probability.\n\n\nAfter you take enough samples by this way, and plot the histogram of these samples, you will found the plot fits well for the given distribution.\n\n\n- More information and proof can be found in [Wikipedia](https://en.wikipedia.org/wiki/Inverse_transform_sampling) & [StackExchange](https://stats.stackexchange.com/questions/161635/why-is-the-cdf-of-a-sample-uniformly-distributed).\n\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.cdf = [0]\n for weight in w:\n self.cdf.append(self.cdf[-1] + weight)\n\n def pickIndex(self) -> int:\n rand = random.randint(1, self.cdf[-1])\n idx = bisect.bisect_left(self.cdf, rand)\n return idx - 1\n```
| 33
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
Python, Simple, 6-line code || 97.65% faster || Runtime: 186 ms
|
random-pick-with-weight
| 0
| 1
|
Runtime: 186 ms, faster than 97.65%\nMemory Usage: 18.1 MB, less than 82.77%\n\n\tclass Solution(object):\n\t\tdef __init__(self, w):\n\t\t\t"""\n\t\t\t:type w: List[int]\n\t\t\t"""\n\t\t\t#Cumulative sum\n\t\t\tself.list = [0] * len(w)\n\n\t\t\ts = 0\n\t\t\tfor i, n in enumerate(w):\n\t\t\t\ts += n\n\t\t\t\tself.list[i] = s\n\n\n\t\tdef pickIndex(self):\n\t\t\t"""\n\t\t\t:rtype: int\n\t\t\t"""\n\t\t\treturn bisect_left(self.list, random.randint(1, self.list[-1]))\n\n\n\t# Your Solution object will be instantiated and called as such:\n\t# obj = Solution(w)\n\t# param_1 = obj.pickIndex()\n\t\n\t\n**Python3, 3-line code**:\n\nRuntime: 205 ms, faster than 96.84%\nMemory Usage: 18.5 MB, less than 80.33%\n\n\tclass Solution:\n\t\tdef __init__(self, w: List[int]):\n\t\t\tfrom itertools import accumulate\n\t\t\tself.list = list(accumulate(w))\n\n\n\t\tdef pickIndex(self) -> int:\n\t\t\treturn bisect_left(self.list, random.randint(1, self.list[-1]))\n\n\n\t# Your Solution object will be instantiated and called as such:\n\t# obj = Solution(w)\n\t# param_1 = obj.pickIndex()\n\n\n\n
| 2
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
Python, Simple, 6-line code || 97.65% faster || Runtime: 186 ms
|
random-pick-with-weight
| 0
| 1
|
Runtime: 186 ms, faster than 97.65%\nMemory Usage: 18.1 MB, less than 82.77%\n\n\tclass Solution(object):\n\t\tdef __init__(self, w):\n\t\t\t"""\n\t\t\t:type w: List[int]\n\t\t\t"""\n\t\t\t#Cumulative sum\n\t\t\tself.list = [0] * len(w)\n\n\t\t\ts = 0\n\t\t\tfor i, n in enumerate(w):\n\t\t\t\ts += n\n\t\t\t\tself.list[i] = s\n\n\n\t\tdef pickIndex(self):\n\t\t\t"""\n\t\t\t:rtype: int\n\t\t\t"""\n\t\t\treturn bisect_left(self.list, random.randint(1, self.list[-1]))\n\n\n\t# Your Solution object will be instantiated and called as such:\n\t# obj = Solution(w)\n\t# param_1 = obj.pickIndex()\n\t\n\t\n**Python3, 3-line code**:\n\nRuntime: 205 ms, faster than 96.84%\nMemory Usage: 18.5 MB, less than 80.33%\n\n\tclass Solution:\n\t\tdef __init__(self, w: List[int]):\n\t\t\tfrom itertools import accumulate\n\t\t\tself.list = list(accumulate(w))\n\n\n\t\tdef pickIndex(self) -> int:\n\t\t\treturn bisect_left(self.list, random.randint(1, self.list[-1]))\n\n\n\t# Your Solution object will be instantiated and called as such:\n\t# obj = Solution(w)\n\t# param_1 = obj.pickIndex()\n\n\n\n
| 2
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
Better than 96.5%
|
random-pick-with-weight
| 0
| 1
|
Should be O(N) init and O(1) for pickIndex and O(1) extra space as the list will always be constant size. Definitely went a different approach than the solution\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.li = []\n ma = sum(w)\n \n for i, weight in enumerate(w):\n ratio = ceil(weight / ma * 100)\n self.li += ([i] * ratio)\n \n\n def pickIndex(self) -> int:\n return random.choice(self.li)\n```
| 8
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
Better than 96.5%
|
random-pick-with-weight
| 0
| 1
|
Should be O(N) init and O(1) for pickIndex and O(1) extra space as the list will always be constant size. Definitely went a different approach than the solution\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.li = []\n ma = sum(w)\n \n for i, weight in enumerate(w):\n ratio = ceil(weight / ma * 100)\n self.li += ([i] * ratio)\n \n\n def pickIndex(self) -> int:\n return random.choice(self.li)\n```
| 8
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
528: Solution with step by step explanation
|
random-pick-with-weight
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define an __init__ method that initializes the class with two instance variables:\nprefix_sum: A list that stores the cumulative sum of weights up to each index in w. Initialize prefix_sum to an empty list.\ntotal_sum: The sum of all weights in w. Initialize total_sum to 0.\n2. Use a for loop to iterate through each weight in w and compute the cumulative sum of weights up to that index. Append the cumulative sum to prefix_sum. Also add the current weight to total_sum.\n3. Define a method pickIndex that returns an index randomly chosen according to the distribution of weights in w.\n4. Generate a random integer random_num in the range [1, total_sum] using the random.randint method.\n5. Use the bisect_left function from the bisect module to find the index index in prefix_sum such that prefix_sum[index] >= random_num.\n6. Return index, which corresponds to the chosen index according to the distribution of weights in w.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def __init__(self, w: List[int]):\n self.prefix_sum = []\n prefix_sum = 0\n for weight in w:\n prefix_sum += weight\n self.prefix_sum.append(prefix_sum)\n self.total_sum = prefix_sum\n\n def pickIndex(self) -> int:\n # Generate a random number in the range [1, total_sum]\n random_num = random.randint(1, self.total_sum)\n # Use binary search to find the index of the random number in prefix_sum\n index = bisect_left(self.prefix_sum, random_num)\n # Return the index corresponding to the random number\n return index\n\n```
| 3
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
528: Solution with step by step explanation
|
random-pick-with-weight
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define an __init__ method that initializes the class with two instance variables:\nprefix_sum: A list that stores the cumulative sum of weights up to each index in w. Initialize prefix_sum to an empty list.\ntotal_sum: The sum of all weights in w. Initialize total_sum to 0.\n2. Use a for loop to iterate through each weight in w and compute the cumulative sum of weights up to that index. Append the cumulative sum to prefix_sum. Also add the current weight to total_sum.\n3. Define a method pickIndex that returns an index randomly chosen according to the distribution of weights in w.\n4. Generate a random integer random_num in the range [1, total_sum] using the random.randint method.\n5. Use the bisect_left function from the bisect module to find the index index in prefix_sum such that prefix_sum[index] >= random_num.\n6. Return index, which corresponds to the chosen index according to the distribution of weights in w.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def __init__(self, w: List[int]):\n self.prefix_sum = []\n prefix_sum = 0\n for weight in w:\n prefix_sum += weight\n self.prefix_sum.append(prefix_sum)\n self.total_sum = prefix_sum\n\n def pickIndex(self) -> int:\n # Generate a random number in the range [1, total_sum]\n random_num = random.randint(1, self.total_sum)\n # Use binary search to find the index of the random number in prefix_sum\n index = bisect_left(self.prefix_sum, random_num)\n # Return the index corresponding to the random number\n return index\n\n```
| 3
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
Python | BinarySearch for accumulation of weight
|
random-pick-with-weight
| 0
| 1
|
```python\nfrom bisect import bisect_left\nfrom itertools import accumulate\nfrom random import random\n\nclass Solution:\n def __init__(self, w):\n self.acc = list(accumulate(w))\n\n def pickIndex(self) -> int:\n return bisect_left(self.acc, random() * self.acc[-1])\n```
| 2
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
Python | BinarySearch for accumulation of weight
|
random-pick-with-weight
| 0
| 1
|
```python\nfrom bisect import bisect_left\nfrom itertools import accumulate\nfrom random import random\n\nclass Solution:\n def __init__(self, w):\n self.acc = list(accumulate(w))\n\n def pickIndex(self) -> int:\n return bisect_left(self.acc, random() * self.acc[-1])\n```
| 2
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
Python3 solution || quibler7
|
random-pick-with-weight
| 0
| 1
|
# Code\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n sum = 0\n self.a = []\n for i in w:\n sum += i\n self.a.append(sum)\n self.total = sum \n \n\n def pickIndex(self) -> int:\n ran = random.randint(1, self.total)\n return bisect_left(self.a, ran)\n```
| 2
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
Python3 solution || quibler7
|
random-pick-with-weight
| 0
| 1
|
# Code\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n sum = 0\n self.a = []\n for i in w:\n sum += i\n self.a.append(sum)\n self.total = sum \n \n\n def pickIndex(self) -> int:\n ran = random.randint(1, self.total)\n return bisect_left(self.a, ran)\n```
| 2
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
99.8% faster solution in Python with explanation
|
random-pick-with-weight
| 0
| 1
|
We get a random number (float) from 0 to 1.\nThen, we add the weights cumulatively and divide by the sum of weights and maintain them in an array.\nExample:\nw: [1,2,3,4]\nSum of wlwments in w: 10\nNormalised weights: [0.1, 0.2, 0.3, 0.4]\nCumulative weights: [0.1, 0.3, 0.6, 1.0]\n\nNow, we get a random number between 0 and 1.\nWe do a binary search and find the index where it has to be inserted. That index will be the return value.\n\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.w = w\n self.c = [0] * len(w)\n s = sum(w)\n self.c[0] = w[0]/s\n for i in range(1, len(w)):\n self.c[i] = self.c[i-1] + w[i]/s\n\n def pickIndex(self) -> int:\n pr = random.random()\n return bisect.bisect_left(self.c, pr)\n```
| 6
|
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index.
You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`.
* For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`).
**Example 1:**
**Input**
\[ "Solution ", "pickIndex "\]
\[\[\[1\]\],\[\]\]
**Output**
\[null,0\]
**Explanation**
Solution solution = new Solution(\[1\]);
solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w.
**Example 2:**
**Input**
\[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\]
\[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\]
**Output**
\[null,1,1,1,1,0\]
**Explanation**
Solution solution = new Solution(\[1, 3\]);
solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4.
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 1
solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4.
Since this is a randomization problem, multiple answers are allowed.
All of the following outputs can be considered correct:
\[null,1,1,1,1,0\]
\[null,1,1,1,1,1\]
\[null,1,1,1,0,0\]
\[null,1,1,1,0,1\]
\[null,1,0,1,0,0\]
......
and so on.
**Constraints:**
* `1 <= w.length <= 104`
* `1 <= w[i] <= 105`
* `pickIndex` will be called at most `104` times.
|
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
|
99.8% faster solution in Python with explanation
|
random-pick-with-weight
| 0
| 1
|
We get a random number (float) from 0 to 1.\nThen, we add the weights cumulatively and divide by the sum of weights and maintain them in an array.\nExample:\nw: [1,2,3,4]\nSum of wlwments in w: 10\nNormalised weights: [0.1, 0.2, 0.3, 0.4]\nCumulative weights: [0.1, 0.3, 0.6, 1.0]\n\nNow, we get a random number between 0 and 1.\nWe do a binary search and find the index where it has to be inserted. That index will be the return value.\n\n```\nclass Solution:\n\n def __init__(self, w: List[int]):\n self.w = w\n self.c = [0] * len(w)\n s = sum(w)\n self.c[0] = w[0]/s\n for i in range(1, len(w)):\n self.c[i] = self.c[i-1] + w[i]/s\n\n def pickIndex(self) -> int:\n pr = random.random()\n return bisect.bisect_left(self.c, pr)\n```
| 6
|
Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104`
| null |
529: Solution with step by step explanation
|
minesweeper
| 0
| 1
|
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Check if the clicked cell is a mine.\n2. Define directions to search for mines using a list of tuples containing the row and column offsets.\n3. Define a helper function countMines that takes the row and column of a cell and returns the number of adjacent mines.\n4. Define a helper function dfs that takes the row and column of a cell and performs a depth-first search to reveal empty cells and update adjacent mine counts.\n5. In the dfs function, check if the current cell is out of bounds or already revealed. If so, return.\n6. Count the number of adjacent mines using the countMines function.\n7. If the current cell has adjacent mines, update it with the number of adjacent mines.\n8. If the current cell has no adjacent mines, update it as a blank cell and recursively call dfs on adjacent cells.\n9. Call dfs on the clicked cell and return the updated board.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n # check if clicked cell is a mine\n if board[click[0]][click[1]] == \'M\':\n board[click[0]][click[1]] = \'X\'\n return board\n\n # define directions to search for mines\n dirs = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]\n\n # define a helper function to count adjacent mines\n def countMines(row, col):\n count = 0\n for r, c in dirs:\n if 0 <= row+r < len(board) and 0 <= col+c < len(board[0]) and board[row+r][col+c] == \'M\':\n count += 1\n return count\n\n # define a helper function for dfs to reveal empty cells\n def dfs(row, col):\n # check if current cell is out of bounds or already revealed\n if not 0 <= row < len(board) or not 0 <= col < len(board[0]) or board[row][col] != \'E\':\n return\n\n # count adjacent mines and update current cell\n mines = countMines(row, col)\n if mines > 0:\n board[row][col] = str(mines)\n else:\n board[row][col] = \'B\'\n for r, c in dirs:\n dfs(row+r, col+c)\n\n # call dfs on clicked cell and return board\n dfs(click[0], click[1])\n return board\n\n```
| 3
|
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!
You are given an `m x n` char matrix `board` representing the game board where:
* `'M'` represents an unrevealed mine,
* `'E'` represents an unrevealed empty square,
* `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),
* digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and
* `'X'` represents a revealed mine.
You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`).
Return _the board after revealing this position according to the following rules_:
1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`.
2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively.
3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines.
4. Return the board when no more squares will be revealed.
**Example 1:**
**Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]
**Example 2:**
**Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 50`
* `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`.
* `click.length == 2`
* `0 <= clickr < m`
* `0 <= clickc < n`
* `board[clickr][clickc]` is either `'M'` or `'E'`.
| null |
✅[Python] Simple and Clean, beats 88%✅
|
minesweeper
| 0
| 1
|
### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n# Intuition\nThe Minesweeper problem involves updating a game board based on a given click position. The game board is represented as a matrix of characters, where each character represents a different type of square on the board. The goal is to update the board according to the rules of Minesweeper.\n\n# Approach\n1. First, we check if the clicked position is a mine (\'M\'). If it is, we change it to \'X\' and return the updated board.\n2. If the clicked position is not a mine, we initialize a stack with the clicked position and define a list of directions to check for adjacent mines.\n3. While the stack is not empty, we pop a position from the stack and check if it is an unrevealed empty square (\'E\').\n4. If it is an empty square, we count the number of adjacent mines by checking all 8 directions.\n5. If there are no adjacent mines, we change the square to \'B\' and add all its adjacent unrevealed squares to the stack.\n6. If there are adjacent mines, we change the square to a digit representing the number of adjacent mines.\n7. We continue this process until the stack is empty and all squares have been revealed.\n\n# Complexity\n- Time complexity: $$O(mn)$$ where m and n are the dimensions of the board.\n- Space complexity: $$O(mn)$$ where m and n are the dimensions of the board.\n\n# Code\n```\nclass Solution:\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n # Get the row and column of the click\n i,j = click[0],click[1]\n \n # If the click is on a mine, change it to \'X\' and return the board\n if board[i][j] == \'M\':\n board[i][j] = \'X\'\n return board\n \n # Get the dimensions of the board\n m,n = len(board),len(board[0])\n \n # Initialize a stack with the click position\n st = [(i,j)]\n \n # Define the directions for checking adjacent cells\n dirs = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]\n \n # While the stack is not empty\n while st:\n # Pop a cell from the stack\n x,y = st.pop()\n \n # If the cell is empty\n if board[x][y] == \'E\':\n # Count the number of mines in adjacent cells\n cnt = 0\n for dx,dy in dirs:\n new_x, new_y = x+dx, y+dy\n if 0<=new_x<m and 0<=new_y<n and board[new_x][new_y] == \'M\':\n cnt += 1\n \n # If there are no mines in adjacent cells\n if cnt == 0:\n # Change the cell to \'B\'\n board[x][y] = \'B\'\n \n # Add all adjacent cells to the stack\n for dx,dy in dirs:\n new_x, new_y = x+dx, y+dy\n if 0<=new_x<m and 0<=new_y<n:\n st.append((new_x,new_y))\n else:\n # Change the cell to the number of mines in adjacent cells\n board[x][y] = str(cnt)\n \n # Return the updated board\n return boardd\n```
| 3
|
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))!
You are given an `m x n` char matrix `board` representing the game board where:
* `'M'` represents an unrevealed mine,
* `'E'` represents an unrevealed empty square,
* `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),
* digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and
* `'X'` represents a revealed mine.
You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`).
Return _the board after revealing this position according to the following rules_:
1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`.
2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively.
3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines.
4. Return the board when no more squares will be revealed.
**Example 1:**
**Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]
**Example 2:**
**Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\]
**Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 50`
* `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`.
* `click.length == 2`
* `0 <= clickr < m`
* `0 <= clickc < n`
* `board[clickr][clickc]` is either `'M'` or `'E'`.
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.