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
482: Solution with step by step explanation
license-key-formatting
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. First, we remove any dashes and convert all characters to uppercase:\n```\ns = s.replace("-", "").upper()\n```\n2. Next, we calculate the length of the first group by taking the length of the string modulo k:\n```\nfirst_...
6
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
Solution
license-key-formatting
1
1
```C++ []\nclass Solution {\npublic:\n string licenseKeyFormatting(string s, int k) {\n int n = s.size(), cnt=0;\n string ans = "";\n for(int i = n-1; i>=0;i--){\n if(s[i]== \'-\'){\n continue;\n }\n if(cnt>0 && cnt%k ==0){\n ans.pus...
3
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
PYTHON code faster than 99.18% ❤️‍🔥❤️‍🔥❤️‍🔥
license-key-formatting
0
1
```\nclass Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n s = s.replace("-","")\n \n if len(s) <= k : return s.upper()\n \n if len(s)%k == 0 :\n return "-".join(s[i:i+k].upper() for i in range(0,len(s),k))\n else :\n return s[:len(...
1
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
Python3 O(n) || O(n) # Runtime: 77ms 53.47% ; Memory: 14.7mb 41.07%
license-key-formatting
0
1
```\nclass Solution:\n# O(n) || O(n)\n# Runtime: 77ms 53.47% ; Memory: 14.7mb 41.07%\n def licenseKeyFormatting(self, string: str, k: int) -> str:\n newString = string.upper().replace(\'-\', \'\')[::-1]\n group = []\n for i in range(0, len(newString), k):\n group.append(newString[...
2
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
Clean Python Solution
license-key-formatting
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)$$ --...
5
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
✔Python 3 Solution | 93% lesser memory
license-key-formatting
0
1
```\nclass Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n s = (s.upper()).replace("-","")[::-1]\n ans = str()\n for i in range(0,len(s),k):\n ans += s[i:i+k]+"-"\n return ans[::-1][1:]\n```
7
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
Easy to understand Python 3 solution Beats 90 % in space and complexity
license-key-formatting
0
1
# Code\n```\nclass Solution:\n def licenseKeyFormatting(self, s: str, k: int) -> str:\n s = s.replace("-", "").upper()\n first_seq = len(s) % k\n output = []\n \n if first_seq > 0:\n output.append(s[:first_seq])\n\n for r in range(first_seq, len(s), k):\n ...
1
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
Python 3 short, simple solution with explanation ( and fast)
license-key-formatting
0
1
The idea is to seperate first group and the rest then combine them at the end\nThis code finish between 32ms - 44ms\n```python\nclass Solution:\n def licenseKeyFormatting(self, S: str, K: int) -> str:\n S = S.replace("-", "").upper() # remove "-" and covert string to uppercase\n remainder = len(S) % K ...
18
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
Reformatting License Key - Format and Convert in Python
license-key-formatting
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve the problem, we need to format the license key so that each group contains exactly k characters, except for the first group, which could be shorter than k but still must contain at least one character. Furthermore, there must be ...
2
You are given a license key represented as a string `s` that consists of only alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. We want to reformat the string `s` such that each group contains exactly `k` characters, except for the first g...
null
Solution
smallest-good-base
1
1
```C++ []\nclass Solution {\n public:\n string smallestGoodBase(string n) {\n const long num = stol(n);\n\n for (int m = log2(num); m >= 2; --m) {\n const int k = pow(num, 1.0 / m);\n long sum = 1;\n long prod = 1;\n for (int i = 0; i < m; ++i) {\n prod *= k;\n sum += prod;\n ...
201
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
483: Solution with step by step explanation
smallest-good-base
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Convert input string n to integer num.\n2. Calculate the maximum possible length of a good base for num using math.floor(math.log(num, 2)) + 1. This value represents the maximum possible number of digits in a good base re...
3
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
Short and simple Python solution O(log(n))
smallest-good-base
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking us to find the smallest base k for which n can be represented as (k^(m+1) - 1) / (k-1) for some m. Essentially, we need to find the smallest base k such that the sum of k^i for i in range(m+1) is equal to n.\n# Appro...
3
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
Binary Search
smallest-good-base
0
1
# Code\n```\nclass Solution:\n def smallestGoodBase(self, n: str) -> str:\n n = int(n)\n \n # Binary search\n for length in range(math.floor(math.log2(n)) + 1, 2, -1):\n left, right = 2, n - 1\n while left <= right:\n mid = left + (right - left) // 2\n...
0
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
Smallest Good Base (Python)
smallest-good-base
0
1
Intuition:\nTo find the smallest base in which a given number `n` can be expressed as a sum of at least two positive integers, we need to find the largest possible value of `m` (the number of summands) and the smallest possible value of `k` (the base) that satisfies the equation `n = (k^m) + (k^(m-1)) + ... + k + 1`. W...
0
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
Python binary search O(logn.logn)
smallest-good-base
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe will first find the maximum possible value of the power. Since the lowest base is 2, the maximum power can\'t be more than $$log(n,2)$$.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet the base be r.\nTherefor...
0
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
Python (Simple Maths)
smallest-good-base
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)$$ --...
0
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
Python (Simple Binary Search)
smallest-good-base
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)$$ --...
0
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
Python3 Solution (Clean and Easy)
smallest-good-base
0
1
- Runtime: 32 ms\n- Memory: 13.9 MB\n\n# Code\n```\nclass Solution:\n def smallestGoodBase(self, n: str) -> str:\n n = int(n)\n for m in range(int(math.log(n, 2)), 1, -1):\n k = int(n ** (1 / m))\n if (k ** (m + 1) - 1) // (k - 1) == n:\n return str(k)\n retu...
0
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
[Python3] enumerate powers
smallest-good-base
0
1
\n```\nclass Solution:\n def smallestGoodBase(self, n: str) -> str:\n n = int(n)\n for p in range(int(log2(n)), 1, -1): \n k = int(n**(1/p))\n if (k**(p+1)-1)//(k-1) == n: return str(k)\n return str(n-1)\n```
1
Given an integer `n` represented as a string, return _the smallest **good base** of_ `n`. We call `k >= 2` a **good base** of `n`, if all digits of `n` base `k` are `1`'s. **Example 1:** **Input:** n = "13 " **Output:** "3 " **Explanation:** 13 base 3 is 111. **Example 2:** **Input:** n = "4681 " **Output:** "...
null
Python Easy 98% beats
max-consecutive-ones
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)$$ --...
1
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things...
Python Easy 98% beats
max-consecutive-ones
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)$$ --...
1
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things o...
[Python3] 4 solutions || 277ms || beats 99%
max-consecutive-ones
0
1
##### 1. Sliding window with max window size\nMake window big as possible. When window has zeros just move left window pointer. At the end of processing in the window can be some zeros, but we don\'t care, because need return just window size `r - l + 1`\nExample for:`111001`\n`[1]11001 => l = 0, r = 0 `\n`[11]1001 => ...
5
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things...
[Python3] 4 solutions || 277ms || beats 99%
max-consecutive-ones
0
1
##### 1. Sliding window with max window size\nMake window big as possible. When window has zeros just move left window pointer. At the end of processing in the window can be some zeros, but we don\'t care, because need return just window size `r - l + 1`\nExample for:`111001`\n`[1]11001 => l = 0, r = 0 `\n`[11]1001 => ...
5
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things o...
Python One Liner
max-consecutive-ones
0
1
\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n\n# Code\n```\nclass Solution:\n def findMaxConsecutiveOnes(self, nums: List[int]) -> int:\n return len(max(\'\'.join(list(map(str,nums))).split("0")))\n```
4
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things...
Python One Liner
max-consecutive-ones
0
1
\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n\n# Code\n```\nclass Solution:\n def findMaxConsecutiveOnes(self, nums: List[int]) -> int:\n return len(max(\'\'.join(list(map(str,nums))).split("0")))\n```
4
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things o...
In place, Prefix Sum Method | O(n)->Time | O(1)-> Space | EASY, PYTHON
max-consecutive-ones
0
1
# Intuition\nWe can do a inplace prefix sum for the nums array and return the maximum value from it.\n\n# Approach\nIterate from the 1\'st index, check if nums[i] == 1, if so then take prefix sum(i.e add with i - 1 \'th value).\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass...
2
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things...
In place, Prefix Sum Method | O(n)->Time | O(1)-> Space | EASY, PYTHON
max-consecutive-ones
0
1
# Intuition\nWe can do a inplace prefix sum for the nums array and return the maximum value from it.\n\n# Approach\nIterate from the 1\'st index, check if nums[i] == 1, if so then take prefix sum(i.e add with i - 1 \'th value).\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass...
2
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things o...
Solution
max-consecutive-ones
1
1
```C++ []\nclass Solution {\npublic:\n int findMaxConsecutiveOnes(vector<int>& nums) {\n int ans=0, count=0;\n for(int i=0; i<nums.size(); i++){\n if(nums[i]!=1)\n { ans = max(ans, count); \n count=0;\n }\n else\n count++;\n ...
2
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things...
Solution
max-consecutive-ones
1
1
```C++ []\nclass Solution {\npublic:\n int findMaxConsecutiveOnes(vector<int>& nums) {\n int ans=0, count=0;\n for(int i=0; i<nums.size(); i++){\n if(nums[i]!=1)\n { ans = max(ans, count); \n count=0;\n }\n else\n count++;\n ...
2
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = ...
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things o...
Python3 Solution
predict-the-winner
0
1
\n```\nclass Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n n=len(nums)\n @lru_cache(None)\n def dp(i,j):\n return 0 if i>j else max(-dp(i+1,j)+nums[i],-dp(i,j-1)+nums[j])\n\n return dp(0,n-1)>=0\n```
2
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` ...
null
Python minimax solution
predict-the-winner
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nMinimax\n\n# Code\n```\nclass Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n def min_max(sum_, l, r, f_turn=True):\n if l == r:\n if f_turn:\n return...
1
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` ...
null
Python short and clean. Functional programming.
predict-the-winner
0
1
# Approach 1: Top-Down DP\nTL;DR, Similar to [Editorial solution. Approach 1](https://leetcode.com/problems/predict-the-winner/editorial/) but shorter and functional.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n^2)$$\n\n# Code\n```python\nclass Solution:\n def PredictTheWinner(self, nu...
1
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` ...
null
Python 3, DP and Recursive
predict-the-winner
0
1
# Intuition\nfirst: the score you get when you take the card firstly\nsecond: the score you get when you take the card secondly\n\nFor example,\n[1, 5, 2, 4]\nfirst(0, 3) means the score you get in array[0: 2 inclusive] firstly\nIf you take card [0], your score is nums[0] + second[1: 3]\nIf you take card [3], your scor...
1
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` ...
null
🖼 JavaScript Python3 | Brute force to Top-down dp | picture explanations 🖼
predict-the-winner
0
1
### Solution 1 : Brute Force\n\n<br>\n<img src="https://assets.leetcode.com/users/images/37e15f03-2b02-46ef-8795-066b68acd6ff_1690530487.6518505.jpeg" width="600px" height="auto"/>\n<br>\n<br>\n\n#### JavaScript\n```\n/**\n * @param {number[]} nums\n * @return {boolean}\n */\nvar PredictTheWinner = function(nums) {\n ...
1
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` ...
null
Concise Min-Max Algorithm with Memoization in Python, Faster than 95%
predict-the-winner
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimulate the game playing with min-max algorithm. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nA state of the game can be defined as `play(l, r, turn)` where `l` and `r` denote the remaining elements and `turn`...
1
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` ...
null
Recursive and iterative solutions (Python)
predict-the-winner
0
1
Recursive, with memoization:\n```\nfrom functools import cache\n\nclass Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n @cache\n def score_diff(lo, hi):\n if lo == hi:\n return nums[lo]\n\n return max(nums[lo]-score_diff(lo+1, hi), nums[hi]-score_...
1
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` ...
null
Python | Medium Problem | 486. Predict the Winner
predict-the-winner
0
1
# Python | Medium Problem | 486. Predict the Winner\n```\nclass Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n def calc(i, j, check):\n if i > j:\n return 0\n best = 0\n if check:\n best = calc(i + 1, j, False) + nums[i]\n ...
2
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` ...
null
Python Elegant & Short | Top-Down DP
predict-the-winner
0
1
# Complexity\n- Time complexity: $$O(n^{2})$$\n- Space complexity: $$O(n^{2})$$\n\n# Code\n```\nclass Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n @cache\n def winner(i: int, j: int) -> int:\n if i == j:\n return nums[i]\n return max(\n ...
2
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2. Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` ...
null
488: Solution with step by step explanation
zuma-game
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a function to remove consecutive same balls in a string.\n2. Sort the hand string to make it easier to iterate over.\n3. Initialize a queue and a visited set with a tuple containing the board, hand, and step count....
3
You are playing a variation of the game Zuma. In this variation of Zuma, there is a **single row** of colored balls on a board, where each ball can be colored red `'R'`, yellow `'Y'`, blue `'B'`, green `'G'`, or white `'W'`. You also have several colored balls in your hand. Your goal is to **clear all** of the balls ...
null
[Python] Easy BFS solution with explain
zuma-game
0
1
\n```python\nclass Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n \n # start from i and remove continues ball\n def remove_same(s, i):\n if i < 0:\n return s\n \n left = right = i\n while left > 0 and s[left-1] == s[i...
12
You are playing a variation of the game Zuma. In this variation of Zuma, there is a **single row** of colored balls on a board, where each ball can be colored red `'R'`, yellow `'Y'`, blue `'B'`, green `'G'`, or white `'W'`. You also have several colored balls in your hand. Your goal is to **clear all** of the balls ...
null
[Python3] dp
zuma-game
0
1
\n```\nclass Solution:\n def findMinStep(self, board: str, hand: str) -> int:\n hand = \'\'.join(sorted(hand))\n \n @cache\n def fn(board, hand):\n """Return min number of balls to insert."""\n if not board: return 0\n if not hand: return inf \n ...
5
You are playing a variation of the game Zuma. In this variation of Zuma, there is a **single row** of colored balls on a board, where each ball can be colored red `'R'`, yellow `'Y'`, blue `'B'`, green `'G'`, or white `'W'`. You also have several colored balls in your hand. Your goal is to **clear all** of the balls ...
null
Solution
zuma-game
1
1
```C++ []\nclass Solution {\npublic:\n bool cleanup(string& a) {\n bool b = false;\n for (int i = 0; a.length() > 2 && i < a.length()-2; i++) {\n if (a[i] == a[i+1] && a[i] == a[i+2]) {\n int j = i+3;\n while (j < a.length() && a[i] == a[j]) j++;\n ...
1
You are playing a variation of the game Zuma. In this variation of Zuma, there is a **single row** of colored balls on a board, where each ball can be colored red `'R'`, yellow `'Y'`, blue `'B'`, green `'G'`, or white `'W'`. You also have several colored balls in your hand. Your goal is to **clear all** of the balls ...
null
488. Zuma Game Solutions
zuma-game
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)$$ --...
0
You are playing a variation of the game Zuma. In this variation of Zuma, there is a **single row** of colored balls on a board, where each ball can be colored red `'R'`, yellow `'Y'`, blue `'B'`, green `'G'`, or white `'W'`. You also have several colored balls in your hand. Your goal is to **clear all** of the balls ...
null
Python Generator || Better than 100% Memory
non-decreasing-subsequences
0
1
```\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n def rec(ind, path=[]):\n if len(path) > 1:\n yield path\n for i in range(ind, len(nums)):\n if not path or nums[i] >= path[-1]:\n yield from rec(i+1, ...
4
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
Python - Backtracking - Video Solution
non-decreasing-subsequences
0
1
I have explained the entire solution [here](https://youtu.be/GAEXeExzMWQ).\n\n```\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n \n res = set()\n perm = []\n \n def dfs(i, prev):\n if i==len(nums):\n if len(perm)>=2:\n...
4
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
python3 || backtracking and recursion
non-decreasing-subsequences
0
1
**Recursion** \n\n```\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n N = len(nums)\n ans = {}\n \n def rec(idx, arr):\n if len(arr) > 1: ans[tuple(arr)]= 1\n \n for i in range(idx, N):\n if nums[i] >...
3
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
491: Space 90.58%, Solution with step by step explanation
non-decreasing-subsequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create an empty list to store the answer.\n\n2. Define a recursive function dfs that takes a starting index start and a list path as arguments.\n\n3. If the length of path is greater than 1, append a copy of path to the a...
3
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
MOST SPACE FRIENDLY PYTHON SOLUTION
non-decreasing-subsequences
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(2^N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N^2)\n<!-- Add your space complexity here, e....
3
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
Python, Python3 Solution || 11 lines
non-decreasing-subsequences
0
1
# Code\n```\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n subsequences = set()\n\n for num in nums:\n new_subsequences = set()\n new_subsequences.add((num,))\n for s in subsequences:\n if num >= s[-1]:\n ...
2
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
Commented simple Python solution with explanation
non-decreasing-subsequences
0
1
\n# Code\n```\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n res = set() # used to check if the number has been used or not\n n = len(nums)\n\n def solve(start, cur):\n # if we get the length > 1 we already got our answer since we need atleast 2 e...
2
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
Python BFS
non-decreasing-subsequences
0
1
\n# Code\n```\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n res = []\n memo = defaultdict(int)\n n = len(nums)\n stack = [([nums[i]], i) for i in range(n - 1)]\n while stack:\n candidate, idx = stack.pop(0)\n if len(candi...
2
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
solution
non-decreasing-subsequences
0
1
# Code\n```\nclass Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]] :\n start_idxes = dict.fromkeys( nums )\n subseq_data = [ ]\n for idx , num in enumerate( nums ) :\n start_idx = start_idxes[ num ]\n num_sub = [ num ]\n if start_idx is...
1
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
Solution
non-decreasing-subsequences
1
1
```C++ []\nclass Solution {\npublic:\n void dfs(vector<int>& nums, vector<vector<int>>& ans, vector<int>& sub, int idx) {\n if (sub.size() >= 2) ans.push_back(sub);\n if (idx == nums.size()) return;\n\n bool chk[205] = {};\n for (int i = idx; i < nums.size(); i++) {\n if (!sub.size() || su...
1
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
python the hard way. Using hashmap to store past results
non-decreasing-subsequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse hashmap\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each num. previous subsequence with last element smaller than num will form a possible solution [previous_subsequence, num]\n\nValues in dictionary wi...
1
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
Non-decreasing Subsequences.py
non-decreasing-subsequences
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)$$ --...
1
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
Python 3 liner code, 3 liner explanation
non-decreasing-subsequences
0
1
# Intuition\n\n\n**Create a set of lists**\n* Add the element itselt in new list\n* if new element >= than element in any of the list \n* Add ( copy of old list + new element ) \n\n\n\n# Code\n```\ndef findSubsequences(self, nums: List[int]) -> List[List[int]]:\n \n ans = { () }\n for i in nums:\n an...
1
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[4,6,7,7\] **Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]...
null
1 LINER PYTHON AND 3 LINER CPP
construct-the-rectangle
0
1
```\nFor 64 : The answer is 8, why? sqrt(64) = 8, so 8 * 8 = 64 and the difference between\n 8 and 8 is the minimum than 2 and 32, 4 and 16.\n\nFor 27 : sqrt(27) = 5.1962, so 5.1962 * 5.1962 = 27 (27.000494 44).\n But we need integer number, so from 5 to 1 the first number which can divide 27\n ...
7
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. The area of the rectangular web page you designed must equal to the given target area....
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
Python, a simple for loop
construct-the-rectangle
0
1
```\nclass Solution:\n def constructRectangle(self, area: int) -> List[int]:\n for l in range(int(area**0.5), 0, -1): \n if area % l == 0: \n return [area // l, l]\n```
41
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. The area of the rectangular web page you designed must equal to the given target area....
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
492: Space 92.56%, Solution with step by step explanation
construct-the-rectangle
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Import the math module to use the sqrt() and ceil() functions.\n2. Initialize the width and length of the rectangular web page:\n a. width = int(math.sqrt(area))\n b. length = int(math.ceil(area / width))\n Note:...
6
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. The area of the rectangular web page you designed must equal to the given target area....
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
Python code : 48ms : with explanation
construct-the-rectangle
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nbasically we are finding the factors of the given area i.e,the length and width\nAlso we need to find the length and breadth pair with least difference between them \n# Approach\n<!-- Describe your approach to solving the problem. -->\nw...
2
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. The area of the rectangular web page you designed must equal to the given target area....
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
[ Python ] Easy Solution | Faster Than 92% Submits
construct-the-rectangle
0
1
```\nclass Solution:\n def constructRectangle(self, area: int) -> List[int]:\n \n for i in range(int(area**0.5),0,-1):\n if area % i == 0: return [area//i,i]\n```
3
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. The area of the rectangular web page you designed must equal to the given target area....
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
1️⃣-liner. 82% faster, 92% less mem.
construct-the-rectangle
0
1
# Intuition\nLet\'s have fun with python.\nStart with `int(sqrt(area))` as a `w`.\nDecrease until condistion is satisfied.\nAfter that, compress the code to generator so we have a nice hard to debug one-liner.\n\nIf you like it, please up-vote. Thank you!\n\n# Complexity\n- Time complexity: $$O(\\sqrt{n})$$\n\n- Space ...
1
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. The area of the rectangular web page you designed must equal to the given target area....
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
Solution
construct-the-rectangle
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> constructRectangle(int area) {\n int i=1;\n int w=1;\n for(int i=1;i<=area/i;i++){\n if(area%i!=0){continue;}\n if(i>w){w=i;}\n }\n i=i-1;\n return {area/w,w};\n }\n};\n```\n\n```Python3 []\nclass So...
3
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. The area of the rectangular web page you designed must equal to the given target area....
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
Python Iterative Solution O(sqrt(n)) time, O(n) space complexity beats 90% speed
construct-the-rectangle
0
1
Upvote once you get it thanks\n```\nimport math\n\'\'\'\n area = 16\n for 1,2...sqrt(16) 5\n 16/1\n 16/2\n 16/3\n 16/4\n ad = {\'1\':\'16\', \'2\':\'8\', \'4\':\'4\'}\n temp = [ float(\'inf\'), float(\'-inf\')]\n for k,v in ad:\n if abs(k-v) < abs(temp[0]-temp[1])\n temp[0], temp[1] = min(k, v), max(k,v)\n re...
2
A web developer needs to know how to design a web page's size. So, given a specific rectangular web page's area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements: 1. The area of the rectangular web page you designed must equal to the given target area....
The W is always less than or equal to the square root of the area, so we start searching at sqrt(area) till we find the result.
Segment Tree of Sorted Lists (Merge Sort Tree) - Supports Online Queries (ADVANCED)
reverse-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a common query type. The solution I present is overkill, but highly flexible and can be used to solve a lot of questions. Overall, my solution supports queries of this form:\n\n"Find the # of values in a range [l:r] that are lower...
0
Given an integer array `nums`, return _the number of **reverse pairs** in the array_. A **reverse pair** is a pair `(i, j)` where: * `0 <= i < j < nums.length` and * `nums[i] > 2 * nums[j]`. **Example 1:** **Input:** nums = \[1,3,2,3,1\] **Output:** 2 **Explanation:** The reverse pairs are: (1, 4) --> nums\[1\]...
null
simple N^2
reverse-pairs
0
1
\n\n# Code\n```\nclass Solution:\n def reversePairs(self, nums: List[int]) -> int:\n \n\n \n\n N = len(nums)\n tot = 0\n sorted_right_side = [nums[-1]*2]\n for j in range(N-2,-1,-1):\n\n n = nums[j]\n # count of numbers that are < 2 * n\n tot...
1
Given an integer array `nums`, return _the number of **reverse pairs** in the array_. A **reverse pair** is a pair `(i, j)` where: * `0 <= i < j < nums.length` and * `nums[i] > 2 * nums[j]`. **Example 1:** **Input:** nums = \[1,3,2,3,1\] **Output:** 2 **Explanation:** The reverse pairs are: (1, 4) --> nums\[1\]...
null
493: Solution with step by step explanation
reverse-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a class Solution with a method reversePairs.\n2. Within the reversePairs method, define a function merge_sort which takes in the starting and ending indices of a subarray and returns the count of reverse pairs with...
10
Given an integer array `nums`, return _the number of **reverse pairs** in the array_. A **reverse pair** is a pair `(i, j)` where: * `0 <= i < j < nums.length` and * `nums[i] > 2 * nums[j]`. **Example 1:** **Input:** nums = \[1,3,2,3,1\] **Output:** 2 **Explanation:** The reverse pairs are: (1, 4) --> nums\[1\]...
null
DP || MEMOIZATION ||EASY
target-sum
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)$$ --...
1
You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and ...
null
TABULATION SOLUTION
target-sum
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)$$ --...
1
You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and ...
null
Python | DP | Top-Down | Memoization
target-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n0/1 Knapsack Problem, for each number, either we can use it\'s negative value, or it\'s positive value. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can use recursion with memoization (Top-Down DP) to solve....
2
You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and ...
null
494: Time 92.20% and Space 96.14%, Solution with step by step explanation
target-sum
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Calculate the sum of all elements in the input list.\n2. Check if the target sum is greater than the sum of all elements in the input list or if the absolute difference between the target sum and the sum of all elements i...
10
You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and ...
null
Python easy to understand: building tree top-down
target-sum
0
1
# Intuition\n\nOriginally I built the whole tree of 2^n nodes, then returned the number of leafs who equaled target. This involves possibly redundant calculations, since at some layers we have may multiple nodes with the same value. \n\nWe can\'t just remove duplicates, i.e. by having `next_vals` be a set, as the total...
2
You are given an integer array `nums` and an integer `target`. You want to build an **expression** out of nums by adding one of the symbols `'+'` and `'-'` before each integer in nums and then concatenate all the integers. * For example, if `nums = [2, 1]`, you can add a `'+'` before `2` and a `'-'` before `1` and ...
null
Simple Understandable Python Code
teemo-attacking
0
1
\n\n# Code\n```\nclass Solution:\n def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n total = 0\n l = len(timeSeries)\n for i in range(l):\n \n if i < l - 1:\n\n if timeSeries[i] + duration - 1 < timeSeries[i+1]:\n t...
2
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effe...
null
Python Easy Solution
teemo-attacking
0
1
# Code\n```\nclass Solution:\n def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n tot=0\n for i in range(len(timeSeries)-1):\n if timeSeries[i+1]-timeSeries[i]>duration:\n tot+=duration\n else:\n tot+=timeSeries[i+1]-timeSe...
1
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effe...
null
Easy approach|| O(n)
teemo-attacking
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)$$ --...
3
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effe...
null
495: Solution with step by step explanation
teemo-attacking
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Begin by defining a function findPoisonedDuration that takes in two arguments - a list timeSeries containing non-decreasing integers and an integer duration.\n\n2. Check if the list timeSeries is empty. If it is, return 0...
9
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effe...
null
✅✅✅ 1-line solution
teemo-attacking
0
1
\n```\nclass Solution:\n def findPoisonedDuration(self, t: List[int], d: int) -> int:\n return d+sum(min(t[i+1]-t[i], d) for i in range(len(t)-1))\n```
9
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effe...
null
Python 6 lines O(n) concise solution
teemo-attacking
0
1
The answer is the length of timeSeries multiply the duration with minus the repeat duration.\nRuntime beats 94% and memory usage beats 80% of python solutions.\n\n\n```\nclass Solution(object):\n def findPoisonedDuration(self, timeSeries, duration):\n repeat = 0\n for i in range(len(timeSeries)-1):\n ...
10
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effe...
null
Python fast solution (beats 99%!)
teemo-attacking
0
1
```\nclass Solution:\n def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:\n time_under_poison = 0\n last_time = timeSeries[0]\n \n for time in timeSeries[1:]:\n if last_time + duration - 1 < time:\n time_under_poison += duration\n\n ...
1
Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effe...
null
Easy Understandable Python Code
next-greater-element-i
0
1
\n\n# Approach\n- First search for ```nums1[i] == nums2[j]``` from ```nums1``` and ```nums2```\n- Then take another loop from ```nums2[j+1]``` to ```end```\n- - if next greater element is present append it\n- - else append -1\n\n\n# Code\n```\nclass Solution:\n def nextGreaterElement(self, nums1: List[int], nums2: L...
2
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. For each `0 <= i < nums1.length`, find the index `j` such ...
null
Python 3 -> 94.64% faster. Used stack and dictionary. Explanation added
next-greater-element-i
0
1
**Suggestions to make it better are always welcomed.**\n\nBasically the problem says, if in nums1 we are working on 4, then in nums2 first find where is 4 and from that index find the next number greater than 4 in nums2. We can see that the solution is always coming from the reverse side of the list nums2. This should ...
253
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. For each `0 <= i < nums1.length`, find the index `j` such ...
null
Python || Easy || Stack || Dictionary
next-greater-element-i
0
1
```\nclass Solution:\n def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:\n d={}\n n=len(nums2)\n for i in range(n):\n d[nums2[i]]=i\n a=[nums2[-1]]\n answer=[-1]\n for i in range(n-2,-1,-1):\n if a[-1]>nums2[i]:\n ...
2
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. For each `0 <= i < nums1.length`, find the index `j` such ...
null
Python3 || without using stack.
next-greater-element-i
0
1
# Code\n```\nclass Solution:\n def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:\n final_list = []\n l = []\n for i in nums1:\n for j in range(len(nums2)):\n if i == nums2[j]:\n s=0\n for k in nums2[j+1:...
3
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. For each `0 <= i < nums1.length`, find the index `j` such ...
null
Solution
next-greater-element-i
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {\n int x=nums1.size();\n int y=nums2.size();\n vector<int> res;\n for(int i=0;i<x;i++)\n {\n auto it = find(nums2.begin(),nums2.end(),nums1[i]);\n\n ...
1
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. For each `0 <= i < nums1.length`, find the index `j` such ...
null
Solution
random-point-in-non-overlapping-rectangles
1
1
```C++ []\nclass Solution {\npublic:\n vector<vector<int>> r;\n vector<int> acc;\n Solution(vector<vector<int>>& rects){\n\n std::ios_base::sync_with_stdio(false);\n cin.tie(0);\n\n r = rects;\n int len = rects.size();\n acc = vector<int>(len, 0);\n\n for(int i = 0; i ...
1
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside th...
null
Solution
random-point-in-non-overlapping-rectangles
1
1
```C++ []\nclass Solution {\npublic:\n vector<vector<int>> r;\n vector<int> acc;\n Solution(vector<vector<int>>& rects){\n\n std::ios_base::sync_with_stdio(false);\n cin.tie(0);\n\n r = rects;\n int len = rects.size();\n acc = vector<int>(len, 0);\n\n for(int i = 0; i ...
1
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such pa...
null
Python3 Solution Explained | Easy to understand
random-point-in-non-overlapping-rectangles
0
1
**Solution:**\n1. First find the sum of the area of all the given rectangles\n2. Create a probability list to determine which rectangle should be selected. A rectangle with higher probability will be selected. The ith element of the probability list is the area of the ith rectangle devided by the sum of the area of all...
1
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside th...
null
Python3 Solution Explained | Easy to understand
random-point-in-non-overlapping-rectangles
0
1
**Solution:**\n1. First find the sum of the area of all the given rectangles\n2. Create a probability list to determine which rectangle should be selected. A rectangle with higher probability will be selected. The ith element of the probability list is the area of the ith rectangle devided by the sum of the area of all...
1
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such pa...
null
Help! Why no working for the last 3 case? (Resolved: count the total pts inside each rec not area)
random-point-in-non-overlapping-rectangles
0
1
Now I understand. In order to solve this problem, we assume that the proportion is on the number of total points each rectangle not the area.\nThe difference is as follows\nAssume the rectangle is [x1, y1, x2, y2] where (x1,y1) the bottom left corner and (x2,y2) the top right corner\nThe area of the rectangle is (x2 - ...
1
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside th...
null
Help! Why no working for the last 3 case? (Resolved: count the total pts inside each rec not area)
random-point-in-non-overlapping-rectangles
0
1
Now I understand. In order to solve this problem, we assume that the proportion is on the number of total points each rectangle not the area.\nThe difference is as follows\nAssume the rectangle is [x1, y1, x2, y2] where (x1,y1) the bottom left corner and (x2,y2) the top right corner\nThe area of the rectangle is (x2 - ...
1
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such pa...
null
497: Space 95.52%, Solution with step by step explanation
random-point-in-non-overlapping-rectangles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize the Solution class with a list of non-overlapping axis-aligned rectangles rects.\n\n2. Inside the init function, calculate the total area covered by all the rectangles and store it in a variable called total_ar...
4
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside th...
null
497: Space 95.52%, Solution with step by step explanation
random-point-in-non-overlapping-rectangles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize the Solution class with a list of non-overlapping axis-aligned rectangles rects.\n\n2. Inside the init function, calculate the total area covered by all the rectangles and store it in a variable called total_ar...
4
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such pa...
null
Python O(n) with approach
random-point-in-non-overlapping-rectangles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking us to pick a random point within a given list of rectangles. The key to solving this problem is to understand the concept of weighting. We can assign a weight to each rectangle based on the number of points it contai...
4
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside th...
null
Python O(n) with approach
random-point-in-non-overlapping-rectangles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking us to pick a random point within a given list of rectangles. The key to solving this problem is to understand the concept of weighting. We can assign a weight to each rectangle based on the number of points it contai...
4
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such pa...
null
Python O(n) by pool sampling. [w/ Visualization]
random-point-in-non-overlapping-rectangles
0
1
**Hint**:\n\nThink of **pool sampling**.\n\nTotal **n** pools, and total **P** points\n\n![image](https://assets.leetcode.com/users/images/09745dec-53dc-400f-8b83-b710ec195706_1598089506.3815591.png)\n\nEach **rectangle** acts as **pool_i** with points **p_i** by itself,\nwhere p_i = ( x_i_2 - x_i_1 + 1) * ( y_i_2 - y...
6
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside th...
null
Python O(n) by pool sampling. [w/ Visualization]
random-point-in-non-overlapping-rectangles
0
1
**Hint**:\n\nThink of **pool sampling**.\n\nTotal **n** pools, and total **P** points\n\n![image](https://assets.leetcode.com/users/images/09745dec-53dc-400f-8b83-b710ec195706_1598089506.3815591.png)\n\nEach **rectangle** acts as **pool_i** with points **p_i** by itself,\nwhere p_i = ( x_i_2 - x_i_1 + 1) * ( y_i_2 - y...
6
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such pa...
null
Reservoir Sampling Algorithm, Python3, not fast but it's okay
random-point-in-non-overlapping-rectangles
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: linear for pick, sacrificed runtime for the algorithm implementation.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Sp...
0
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside th...
null
Reservoir Sampling Algorithm, Python3, not fast but it's okay
random-point-in-non-overlapping-rectangles
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: linear for pick, sacrificed runtime for the algorithm implementation.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Sp...
0
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such pa...
null
Equal representatives for equal opportunity; Bigger rectangles need more representatives!
random-point-in-non-overlapping-rectangles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe basic intuition was to select a rectangle randomly and then select a point from that rectangle randomly. However, since all valid points must have an equal probability of being picked up, we have to account for the area/size of the re...
0
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside th...
null
Equal representatives for equal opportunity; Bigger rectangles need more representatives!
random-point-in-non-overlapping-rectangles
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe basic intuition was to select a rectangle randomly and then select a point from that rectangle randomly. However, since all valid points must have an equal probability of being picked up, we have to account for the area/size of the re...
0
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such pa...
null