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
Simple solution
rle-iterator
0
1
```\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.arr = encoding\n self.curr = 0\n self.cnt = self.arr[self.curr]\n\n def next(self, n: int) -> int:\n while self.curr < len(self.arr) and n > 0:\n if n <= self.cnt:\n self.cnt -= n\n return self.arr[self.curr + 1]\n n, self.cnt = n - self.cnt, self.cnt - n\n if self.cnt < 0:\n self.curr += 2\n self.cnt = self.arr[self.curr] if self.curr < len(self.arr) else 0\n return self.arr[self.curr + 1] if self.curr < len(self.arr) else -1\n\n# Your RLEIterator object will be instantiated and called as such:\n# obj = RLEIterator(encoding)\n# param_1 = obj.next(n)\n```
0
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`. Given a run-length encoded array, design an iterator that iterates through it. Implement the `RLEIterator` class: * `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`. * `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead. **Example 1:** **Input** \[ "RLEIterator ", "next ", "next ", "next ", "next "\] \[\[\[3, 8, 0, 9, 2, 5\]\], \[2\], \[1\], \[1\], \[2\]\] **Output** \[null, 8, 8, 5, -1\] **Explanation** RLEIterator rLEIterator = new RLEIterator(\[3, 8, 0, 9, 2, 5\]); // This maps to the sequence \[8,8,8,5,5\]. rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now \[8, 5, 5\]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now \[5, 5\]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now \[5\]. rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5, but the second term did not exist. Since the last term exhausted does not exist, we return -1. **Constraints:** * `2 <= encoding.length <= 1000` * `encoding.length` is even. * `0 <= encoding[i] <= 109` * `1 <= n <= 109` * At most `1000` calls will be made to `next`.
null
Simple solution
rle-iterator
0
1
```\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.arr = encoding\n self.curr = 0\n self.cnt = self.arr[self.curr]\n\n def next(self, n: int) -> int:\n while self.curr < len(self.arr) and n > 0:\n if n <= self.cnt:\n self.cnt -= n\n return self.arr[self.curr + 1]\n n, self.cnt = n - self.cnt, self.cnt - n\n if self.cnt < 0:\n self.curr += 2\n self.cnt = self.arr[self.curr] if self.curr < len(self.arr) else 0\n return self.arr[self.curr + 1] if self.curr < len(self.arr) else -1\n\n# Your RLEIterator object will be instantiated and called as such:\n# obj = RLEIterator(encoding)\n# param_1 = obj.next(n)\n```
0
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, then `s` is `"????? "` initially. In one turn you can: * place `stamp` at index `0` of `s` to obtain `"abc?? "`, * place `stamp` at index `1` of `s` to obtain `"?abc? "`, or * place `stamp` at index `2` of `s` to obtain `"??abc "`. Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`). We want to convert `s` to `target` using **at most** `10 * target.length` turns. Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array. **Example 1:** **Input:** stamp = "abc ", target = "ababc " **Output:** \[0,2\] **Explanation:** Initially s = "????? ". - Place stamp at index 0 to get "abc?? ". - Place stamp at index 2 to get "ababc ". \[1,0,2\] would also be accepted as an answer, as well as some other answers. **Example 2:** **Input:** stamp = "abca ", target = "aabcaca " **Output:** \[3,0,1\] **Explanation:** Initially s = "??????? ". - Place stamp at index 3 to get "???abca ". - Place stamp at index 0 to get "abcabca ". - Place stamp at index 1 to get "aabcaca ". **Constraints:** * `1 <= stamp.length <= target.length <= 1000` * `stamp` and `target` consist of lowercase English letters.
null
Python Solution with Pointer O(n) time where n is len of encoding O(1) space
rle-iterator
0
1
\n# Code\n```\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.encoding = encoding\n self.ptr = 0\n\n def next(self, n: int) -> int:\n if self.ptr > len(self.encoding)-2:\n return -1\n while not self.encoding[self.ptr]:\n self.ptr += 2\n if self.ptr > len(self.encoding)-2:\n return -1\n \n while n > self.encoding[self.ptr]:\n n -= self.encoding[self.ptr]\n self.ptr += 2\n if self.ptr > len(self.encoding)-2:\n return -1\n self.encoding[self.ptr] -= n\n return self.encoding[self.ptr+1]\n\n\n# Your RLEIterator object will be instantiated and called as such:\n# obj = RLEIterator(encoding)\n# param_1 = obj.next(n)\n```
0
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`. Given a run-length encoded array, design an iterator that iterates through it. Implement the `RLEIterator` class: * `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`. * `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead. **Example 1:** **Input** \[ "RLEIterator ", "next ", "next ", "next ", "next "\] \[\[\[3, 8, 0, 9, 2, 5\]\], \[2\], \[1\], \[1\], \[2\]\] **Output** \[null, 8, 8, 5, -1\] **Explanation** RLEIterator rLEIterator = new RLEIterator(\[3, 8, 0, 9, 2, 5\]); // This maps to the sequence \[8,8,8,5,5\]. rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now \[8, 5, 5\]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now \[5, 5\]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now \[5\]. rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5, but the second term did not exist. Since the last term exhausted does not exist, we return -1. **Constraints:** * `2 <= encoding.length <= 1000` * `encoding.length` is even. * `0 <= encoding[i] <= 109` * `1 <= n <= 109` * At most `1000` calls will be made to `next`.
null
Python Solution with Pointer O(n) time where n is len of encoding O(1) space
rle-iterator
0
1
\n# Code\n```\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.encoding = encoding\n self.ptr = 0\n\n def next(self, n: int) -> int:\n if self.ptr > len(self.encoding)-2:\n return -1\n while not self.encoding[self.ptr]:\n self.ptr += 2\n if self.ptr > len(self.encoding)-2:\n return -1\n \n while n > self.encoding[self.ptr]:\n n -= self.encoding[self.ptr]\n self.ptr += 2\n if self.ptr > len(self.encoding)-2:\n return -1\n self.encoding[self.ptr] -= n\n return self.encoding[self.ptr+1]\n\n\n# Your RLEIterator object will be instantiated and called as such:\n# obj = RLEIterator(encoding)\n# param_1 = obj.next(n)\n```
0
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, then `s` is `"????? "` initially. In one turn you can: * place `stamp` at index `0` of `s` to obtain `"abc?? "`, * place `stamp` at index `1` of `s` to obtain `"?abc? "`, or * place `stamp` at index `2` of `s` to obtain `"??abc "`. Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`). We want to convert `s` to `target` using **at most** `10 * target.length` turns. Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array. **Example 1:** **Input:** stamp = "abc ", target = "ababc " **Output:** \[0,2\] **Explanation:** Initially s = "????? ". - Place stamp at index 0 to get "abc?? ". - Place stamp at index 2 to get "ababc ". \[1,0,2\] would also be accepted as an answer, as well as some other answers. **Example 2:** **Input:** stamp = "abca ", target = "aabcaca " **Output:** \[3,0,1\] **Explanation:** Initially s = "??????? ". - Place stamp at index 3 to get "???abca ". - Place stamp at index 0 to get "abcabca ". - Place stamp at index 1 to get "aabcaca ". **Constraints:** * `1 <= stamp.length <= target.length <= 1000` * `stamp` and `target` consist of lowercase English letters.
null
Beats 99.11%of users with Python3 // CLEAN SOL
rle-iterator
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 RLEIterator:\n\n def __init__(self, encoding: List[int]):\n \n self.encode=encoding\n \n def next(self, n: int) -> int:\n \n while self.encode:\n if n>self.encode[0]:\n n-=self.encode[0]\n for _ in range(2):\n self.encode.pop(0)\n elif n<self.encode[0]:\n self.encode[0]-=n\n return self.encode[1]\n else:\n elem=self.encode[1]\n for _ in range(2):\n self.encode.pop(0)\n return elem\n return -1\n# Your RLEIterator object will be instantiated and called as such:\n# obj = RLEIterator(encoding)\n# param_1 = obj.next(n)\n```
0
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`. Given a run-length encoded array, design an iterator that iterates through it. Implement the `RLEIterator` class: * `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`. * `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead. **Example 1:** **Input** \[ "RLEIterator ", "next ", "next ", "next ", "next "\] \[\[\[3, 8, 0, 9, 2, 5\]\], \[2\], \[1\], \[1\], \[2\]\] **Output** \[null, 8, 8, 5, -1\] **Explanation** RLEIterator rLEIterator = new RLEIterator(\[3, 8, 0, 9, 2, 5\]); // This maps to the sequence \[8,8,8,5,5\]. rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now \[8, 5, 5\]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now \[5, 5\]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now \[5\]. rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5, but the second term did not exist. Since the last term exhausted does not exist, we return -1. **Constraints:** * `2 <= encoding.length <= 1000` * `encoding.length` is even. * `0 <= encoding[i] <= 109` * `1 <= n <= 109` * At most `1000` calls will be made to `next`.
null
Beats 99.11%of users with Python3 // CLEAN SOL
rle-iterator
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 RLEIterator:\n\n def __init__(self, encoding: List[int]):\n \n self.encode=encoding\n \n def next(self, n: int) -> int:\n \n while self.encode:\n if n>self.encode[0]:\n n-=self.encode[0]\n for _ in range(2):\n self.encode.pop(0)\n elif n<self.encode[0]:\n self.encode[0]-=n\n return self.encode[1]\n else:\n elem=self.encode[1]\n for _ in range(2):\n self.encode.pop(0)\n return elem\n return -1\n# Your RLEIterator object will be instantiated and called as such:\n# obj = RLEIterator(encoding)\n# param_1 = obj.next(n)\n```
0
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, then `s` is `"????? "` initially. In one turn you can: * place `stamp` at index `0` of `s` to obtain `"abc?? "`, * place `stamp` at index `1` of `s` to obtain `"?abc? "`, or * place `stamp` at index `2` of `s` to obtain `"??abc "`. Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`). We want to convert `s` to `target` using **at most** `10 * target.length` turns. Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array. **Example 1:** **Input:** stamp = "abc ", target = "ababc " **Output:** \[0,2\] **Explanation:** Initially s = "????? ". - Place stamp at index 0 to get "abc?? ". - Place stamp at index 2 to get "ababc ". \[1,0,2\] would also be accepted as an answer, as well as some other answers. **Example 2:** **Input:** stamp = "abca ", target = "aabcaca " **Output:** \[3,0,1\] **Explanation:** Initially s = "??????? ". - Place stamp at index 3 to get "???abca ". - Place stamp at index 0 to get "abcabca ". - Place stamp at index 1 to get "aabcaca ". **Constraints:** * `1 <= stamp.length <= target.length <= 1000` * `stamp` and `target` consist of lowercase English letters.
null
Python3 Easy solution, beat 82%
rle-iterator
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 RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.encoding = []\n self.index = 0\n self.cur_idx_count = 0\n for i in range(1, len(encoding), 2):\n self.encoding.append((encoding[i], encoding[i-1]))\n \n\n def next(self, n: int) -> int:\n if self.index == len(self.encoding): return -1\n \n cur_val, cur_count = self.encoding[self.index]\n\n cur_index_left = cur_count - self.cur_idx_count\n next_index_count = n-cur_index_left\n if next_index_count == 0:\n self.index += 1\n self.cur_idx_count = 0\n return cur_val\n if next_index_count > 0:\n self.index += 1\n self.cur_idx_count = 0\n return self.next(next_index_count)\n # else can finish in this round\n self.cur_idx_count += n\n return cur_val\n \n \n\n\n# Your RLEIterator object will be instantiated and called as such:\n# obj = RLEIterator(encoding)\n# param_1 = obj.next(n)\n```
0
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the sequence `arr = [8,8,8,5,5]` can be encoded to be `encoding = [3,8,2,5]`. `encoding = [3,8,0,9,2,5]` and `encoding = [2,8,1,8,2,5]` are also valid **RLE** of `arr`. Given a run-length encoded array, design an iterator that iterates through it. Implement the `RLEIterator` class: * `RLEIterator(int[] encoded)` Initializes the object with the encoded array `encoded`. * `int next(int n)` Exhausts the next `n` elements and returns the last element exhausted in this way. If there is no element left to exhaust, return `-1` instead. **Example 1:** **Input** \[ "RLEIterator ", "next ", "next ", "next ", "next "\] \[\[\[3, 8, 0, 9, 2, 5\]\], \[2\], \[1\], \[1\], \[2\]\] **Output** \[null, 8, 8, 5, -1\] **Explanation** RLEIterator rLEIterator = new RLEIterator(\[3, 8, 0, 9, 2, 5\]); // This maps to the sequence \[8,8,8,5,5\]. rLEIterator.next(2); // exhausts 2 terms of the sequence, returning 8. The remaining sequence is now \[8, 5, 5\]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 8. The remaining sequence is now \[5, 5\]. rLEIterator.next(1); // exhausts 1 term of the sequence, returning 5. The remaining sequence is now \[5\]. rLEIterator.next(2); // exhausts 2 terms, returning -1. This is because the first term exhausted was 5, but the second term did not exist. Since the last term exhausted does not exist, we return -1. **Constraints:** * `2 <= encoding.length <= 1000` * `encoding.length` is even. * `0 <= encoding[i] <= 109` * `1 <= n <= 109` * At most `1000` calls will be made to `next`.
null
Python3 Easy solution, beat 82%
rle-iterator
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 RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.encoding = []\n self.index = 0\n self.cur_idx_count = 0\n for i in range(1, len(encoding), 2):\n self.encoding.append((encoding[i], encoding[i-1]))\n \n\n def next(self, n: int) -> int:\n if self.index == len(self.encoding): return -1\n \n cur_val, cur_count = self.encoding[self.index]\n\n cur_index_left = cur_count - self.cur_idx_count\n next_index_count = n-cur_index_left\n if next_index_count == 0:\n self.index += 1\n self.cur_idx_count = 0\n return cur_val\n if next_index_count > 0:\n self.index += 1\n self.cur_idx_count = 0\n return self.next(next_index_count)\n # else can finish in this round\n self.cur_idx_count += n\n return cur_val\n \n \n\n\n# Your RLEIterator object will be instantiated and called as such:\n# obj = RLEIterator(encoding)\n# param_1 = obj.next(n)\n```
0
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, then `s` is `"????? "` initially. In one turn you can: * place `stamp` at index `0` of `s` to obtain `"abc?? "`, * place `stamp` at index `1` of `s` to obtain `"?abc? "`, or * place `stamp` at index `2` of `s` to obtain `"??abc "`. Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`). We want to convert `s` to `target` using **at most** `10 * target.length` turns. Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array. **Example 1:** **Input:** stamp = "abc ", target = "ababc " **Output:** \[0,2\] **Explanation:** Initially s = "????? ". - Place stamp at index 0 to get "abc?? ". - Place stamp at index 2 to get "ababc ". \[1,0,2\] would also be accepted as an answer, as well as some other answers. **Example 2:** **Input:** stamp = "abca ", target = "aabcaca " **Output:** \[3,0,1\] **Explanation:** Initially s = "??????? ". - Place stamp at index 3 to get "???abca ". - Place stamp at index 0 to get "abcabca ". - Place stamp at index 1 to get "aabcaca ". **Constraints:** * `1 <= stamp.length <= target.length <= 1000` * `stamp` and `target` consist of lowercase English letters.
null
Python3 - Save timestamp and price into a stack
online-stock-span
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing stack to save local maximum price.\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass StockSpanner:\n\n def __init__(self):\n self.memo = []\n self.timestamp = 0\n \n \n def next(self, price: int) -> int:\n self.timestamp += 1\n record = {\'ts\':self.timestamp, \'price\':price}\n\n while(self.memo and price >= self.memo[-1][\'price\']):\n self.memo.pop()\n \n self.memo.append(record)\n if len(self.memo) > 1:\n return (self.memo[-1][\'ts\'] - self.memo[-2][\'ts\'])\n \n else:\n return self.timestamp\n \n \n \n\n\n# Your StockSpanner object will be instantiated and called as such:\n# obj = StockSpanner()\n# param_1 = obj.next(price)\n```
1
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. * For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days. * Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days. Implement the `StockSpanner` class: * `StockSpanner()` Initializes the object of the class. * `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. **Example 1:** **Input** \[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\] \[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\] **Output** \[null, 1, 1, 1, 2, 1, 4, 6\] **Explanation** StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 **Constraints:** * `1 <= price <= 105` * At most `104` calls will be made to `next`.
null
Python3 - Save timestamp and price into a stack
online-stock-span
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing stack to save local maximum price.\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass StockSpanner:\n\n def __init__(self):\n self.memo = []\n self.timestamp = 0\n \n \n def next(self, price: int) -> int:\n self.timestamp += 1\n record = {\'ts\':self.timestamp, \'price\':price}\n\n while(self.memo and price >= self.memo[-1][\'price\']):\n self.memo.pop()\n \n self.memo.append(record)\n if len(self.memo) > 1:\n return (self.memo[-1][\'ts\'] - self.memo[-2][\'ts\'])\n \n else:\n return self.timestamp\n \n \n \n\n\n# Your StockSpanner object will be instantiated and called as such:\n# obj = StockSpanner()\n# param_1 = obj.next(price)\n```
1
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits. Reorder these logs so that: 1. The **letter-logs** come before all **digit-logs**. 2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. 3. The **digit-logs** maintain their relative ordering. Return _the final order of the logs_. **Example 1:** **Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\] **Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\] **Explanation:** The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ". The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ". **Example 2:** **Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\] **Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\] **Constraints:** * `1 <= logs.length <= 100` * `3 <= logs[i].length <= 100` * All the tokens of `logs[i]` are separated by a **single** space. * `logs[i]` is guaranteed to have an identifier and at least one word after the identifier.
null
Python Solution using Stack || 90%beats
online-stock-span
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nstack\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:90.21%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:53.61%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass StockSpanner:\n\n def __init__(self):\n self.lst=[]\n\n def next(self, price: int) -> int:\n c=1\n while self.lst and self.lst[-1][0]<=price:\n a,b=self.lst.pop()\n c+=b\n self.lst.append((price,c))\n return c\n# Your StockSpanner object will be instantiated and called as such:\n# obj = StockSpanner()\n# param_1 = obj.next(price)\n```
1
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. * For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days. * Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days. Implement the `StockSpanner` class: * `StockSpanner()` Initializes the object of the class. * `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. **Example 1:** **Input** \[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\] \[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\] **Output** \[null, 1, 1, 1, 2, 1, 4, 6\] **Explanation** StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 **Constraints:** * `1 <= price <= 105` * At most `104` calls will be made to `next`.
null
Python Solution using Stack || 90%beats
online-stock-span
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nstack\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:90.21%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:53.61%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass StockSpanner:\n\n def __init__(self):\n self.lst=[]\n\n def next(self, price: int) -> int:\n c=1\n while self.lst and self.lst[-1][0]<=price:\n a,b=self.lst.pop()\n c+=b\n self.lst.append((price,c))\n return c\n# Your StockSpanner object will be instantiated and called as such:\n# obj = StockSpanner()\n# param_1 = obj.next(price)\n```
1
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits. Reorder these logs so that: 1. The **letter-logs** come before all **digit-logs**. 2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. 3. The **digit-logs** maintain their relative ordering. Return _the final order of the logs_. **Example 1:** **Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\] **Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\] **Explanation:** The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ". The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ". **Example 2:** **Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\] **Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\] **Constraints:** * `1 <= logs.length <= 100` * `3 <= logs[i].length <= 100` * All the tokens of `logs[i]` are separated by a **single** space. * `logs[i]` is guaranteed to have an identifier and at least one word after the identifier.
null
EASY PYTHON SOLUTION
online-stock-span
0
1
```\nclass StockSpanner:\n\n def __init__(self):\n self.st=[]\n self.lst=[]\n \n\n def next(self, price: int) -> int:\n if self.st==[]:\n self.st.append(price)\n self.lst.append(1)\n return 1\n ct=1\n while self.st:\n if self.st[-1]<=price:\n ct+=self.lst.pop()\n self.st.pop()\n else:\n break\n self.st.append(price)\n self.lst.append(ct)\n return ct\n
9
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. * For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days. * Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days. Implement the `StockSpanner` class: * `StockSpanner()` Initializes the object of the class. * `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. **Example 1:** **Input** \[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\] \[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\] **Output** \[null, 1, 1, 1, 2, 1, 4, 6\] **Explanation** StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 **Constraints:** * `1 <= price <= 105` * At most `104` calls will be made to `next`.
null
EASY PYTHON SOLUTION
online-stock-span
0
1
```\nclass StockSpanner:\n\n def __init__(self):\n self.st=[]\n self.lst=[]\n \n\n def next(self, price: int) -> int:\n if self.st==[]:\n self.st.append(price)\n self.lst.append(1)\n return 1\n ct=1\n while self.st:\n if self.st[-1]<=price:\n ct+=self.lst.pop()\n self.st.pop()\n else:\n break\n self.st.append(price)\n self.lst.append(ct)\n return ct\n
9
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits. Reorder these logs so that: 1. The **letter-logs** come before all **digit-logs**. 2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. 3. The **digit-logs** maintain their relative ordering. Return _the final order of the logs_. **Example 1:** **Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\] **Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\] **Explanation:** The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ". The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ". **Example 2:** **Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\] **Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\] **Constraints:** * `1 <= logs.length <= 100` * `3 <= logs[i].length <= 100` * All the tokens of `logs[i]` are separated by a **single** space. * `logs[i]` is guaranteed to have an identifier and at least one word after the identifier.
null
Fast and Easy Solution || Leetcode 75
online-stock-span
0
1
\n# Code\n```\nclass StockSpanner:\n\n def __init__(self):\n self.stack=[]\n \n\n def next(self, price: int) -> int:\n counter = 1\n while self.stack and self.stack[-1][0] <= price:\n counter += self.stack.pop()[1]\n\n self.stack.append((price,counter))\n return counter\n\n\n\n# Your StockSpanner object will be instantiated and called as such:\n# obj = StockSpanner()\n# param_1 = obj.next(price)\n```\n# **PLEASE DO UPVOTE!!!**
5
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day. The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day. * For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days. * Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days. Implement the `StockSpanner` class: * `StockSpanner()` Initializes the object of the class. * `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`. **Example 1:** **Input** \[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\] \[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\] **Output** \[null, 1, 1, 1, 2, 1, 4, 6\] **Explanation** StockSpanner stockSpanner = new StockSpanner(); stockSpanner.next(100); // return 1 stockSpanner.next(80); // return 1 stockSpanner.next(60); // return 1 stockSpanner.next(70); // return 2 stockSpanner.next(60); // return 1 stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price. stockSpanner.next(85); // return 6 **Constraints:** * `1 <= price <= 105` * At most `104` calls will be made to `next`.
null
Fast and Easy Solution || Leetcode 75
online-stock-span
0
1
\n# Code\n```\nclass StockSpanner:\n\n def __init__(self):\n self.stack=[]\n \n\n def next(self, price: int) -> int:\n counter = 1\n while self.stack and self.stack[-1][0] <= price:\n counter += self.stack.pop()[1]\n\n self.stack.append((price,counter))\n return counter\n\n\n\n# Your StockSpanner object will be instantiated and called as such:\n# obj = StockSpanner()\n# param_1 = obj.next(price)\n```\n# **PLEASE DO UPVOTE!!!**
5
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits. Reorder these logs so that: 1. The **letter-logs** come before all **digit-logs**. 2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers. 3. The **digit-logs** maintain their relative ordering. Return _the final order of the logs_. **Example 1:** **Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\] **Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\] **Explanation:** The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ". The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ". **Example 2:** **Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\] **Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\] **Constraints:** * `1 <= logs.length <= 100` * `3 <= logs[i].length <= 100` * All the tokens of `logs[i]` are separated by a **single** space. * `logs[i]` is guaranteed to have an identifier and at least one word after the identifier.
null
Solution
numbers-at-most-n-given-digit-set
1
1
```C++ []\nclass Solution {\n public:\n int atMostNGivenDigitSet(vector<string>& D, int N) {\n int ans = 0;\n string num = to_string(N);\n\n for (int i = 1; i < num.length(); ++i)\n ans += pow(D.size(), i);\n\n for (int i = 0; i < num.length(); ++i) {\n bool dHasSameNum = false;\n for (const string& digit : D) {\n if (digit[0] < num[i])\n ans += pow(D.size(), num.length() - i - 1);\n else if (digit[0] == num[i])\n dHasSameNum = true;\n }\n if (!dHasSameNum)\n return ans;\n }\n return ans + 1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n ans = 0\n num = str(n)\n\n for i in range(1, len(num)):\n ans += pow(len(digits), i)\n\n for i, c in enumerate(num):\n dHasSameNum = False\n for digit in digits:\n if digit[0] < c:\n ans += pow(len(digits), len(num) - i - 1)\n elif digit[0] == c:\n dHasSameNum = True\n if not dHasSameNum:\n return ans\n\n return ans + 1\n```\n\n```Java []\nclass Solution {\n public int atMostNGivenDigitSet(String[] digits, int n) {\n String N = Integer.toString(n);\n int ans=0;\n for(int i=1; i<= N.length(); ++i){\n if(N.equals("0")){\n return 0;\n } else if(i < N.length()){\n ans += (int)Math.pow(digits.length , i);\n }\n }\n int i = 0;\n while(i<N.length()){\n int j = 0;\n while(j<digits.length && digits[j].charAt(0)<N.charAt(i)){\n ans += Math.pow(digits.length,N.length()-1-i);\n j++;\n }\n if(j==digits.length || digits[j].charAt(0)>N.charAt(i))\n break;\n i++;\n }\n if(i==N.length())\n ans++;\n return ans;\n }\n}\n```\n
1
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. **Example 1:** **Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100 **Output:** 20 **Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. **Example 2:** **Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000 **Output:** 29523 **Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. **Example 3:** **Input:** digits = \[ "7 "\], n = 8 **Output:** 1 **Constraints:** * `1 <= digits.length <= 9` * `digits[i].length == 1` * `digits[i]` is a digit from `'1'` to `'9'`. * All the values in `digits` are **unique**. * `digits` is sorted in **non-decreasing** order. * `1 <= n <= 109`
null
Solution
numbers-at-most-n-given-digit-set
1
1
```C++ []\nclass Solution {\n public:\n int atMostNGivenDigitSet(vector<string>& D, int N) {\n int ans = 0;\n string num = to_string(N);\n\n for (int i = 1; i < num.length(); ++i)\n ans += pow(D.size(), i);\n\n for (int i = 0; i < num.length(); ++i) {\n bool dHasSameNum = false;\n for (const string& digit : D) {\n if (digit[0] < num[i])\n ans += pow(D.size(), num.length() - i - 1);\n else if (digit[0] == num[i])\n dHasSameNum = true;\n }\n if (!dHasSameNum)\n return ans;\n }\n return ans + 1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n ans = 0\n num = str(n)\n\n for i in range(1, len(num)):\n ans += pow(len(digits), i)\n\n for i, c in enumerate(num):\n dHasSameNum = False\n for digit in digits:\n if digit[0] < c:\n ans += pow(len(digits), len(num) - i - 1)\n elif digit[0] == c:\n dHasSameNum = True\n if not dHasSameNum:\n return ans\n\n return ans + 1\n```\n\n```Java []\nclass Solution {\n public int atMostNGivenDigitSet(String[] digits, int n) {\n String N = Integer.toString(n);\n int ans=0;\n for(int i=1; i<= N.length(); ++i){\n if(N.equals("0")){\n return 0;\n } else if(i < N.length()){\n ans += (int)Math.pow(digits.length , i);\n }\n }\n int i = 0;\n while(i<N.length()){\n int j = 0;\n while(j<digits.length && digits[j].charAt(0)<N.charAt(i)){\n ans += Math.pow(digits.length,N.length()-1-i);\n j++;\n }\n if(j==digits.length || digits[j].charAt(0)>N.charAt(i))\n break;\n i++;\n }\n if(i==N.length())\n ans++;\n return ans;\n }\n}\n```\n
1
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32. **Example 2:** **Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10 **Output:** 23 **Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23. **Constraints:** * The number of nodes in the tree is in the range `[1, 2 * 104]`. * `1 <= Node.val <= 105` * `1 <= low <= high <= 105` * All `Node.val` are **unique**.
null
Python 3 || 8 lines, mostly mathematics || T/M: 97% / 98%
numbers-at-most-n-given-digit-set
0
1
```\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n\n f = lambda x: sum(ch < x for ch in digits)\n\n d, k = len(digits), len(str(n))\n \n ans = k-1 if d == 1 else (d**k - d)//(d - 1)\n \n for i, ch in enumerate(str(n)):\n\n ans += f(ch) * (d ** (k - i - 1))\n if ch not in digits: break\n\n else: ans += 1\n \n return ans \n```\n[https://leetcode.com/problems/numbers-at-most-n-given-digit-set/submissions/890415119/](http://)\n
4
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. **Example 1:** **Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100 **Output:** 20 **Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. **Example 2:** **Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000 **Output:** 29523 **Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. **Example 3:** **Input:** digits = \[ "7 "\], n = 8 **Output:** 1 **Constraints:** * `1 <= digits.length <= 9` * `digits[i].length == 1` * `digits[i]` is a digit from `'1'` to `'9'`. * All the values in `digits` are **unique**. * `digits` is sorted in **non-decreasing** order. * `1 <= n <= 109`
null
Python 3 || 8 lines, mostly mathematics || T/M: 97% / 98%
numbers-at-most-n-given-digit-set
0
1
```\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n\n f = lambda x: sum(ch < x for ch in digits)\n\n d, k = len(digits), len(str(n))\n \n ans = k-1 if d == 1 else (d**k - d)//(d - 1)\n \n for i, ch in enumerate(str(n)):\n\n ans += f(ch) * (d ** (k - i - 1))\n if ch not in digits: break\n\n else: ans += 1\n \n return ans \n```\n[https://leetcode.com/problems/numbers-at-most-n-given-digit-set/submissions/890415119/](http://)\n
4
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32. **Example 2:** **Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10 **Output:** 23 **Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23. **Constraints:** * The number of nodes in the tree is in the range `[1, 2 * 104]`. * `1 <= Node.val <= 105` * `1 <= low <= high <= 105` * All `Node.val` are **unique**.
null
✔️ [Python3] NOT BEGINNER FRIENDLY, Explained
numbers-at-most-n-given-digit-set
0
1
We can approach this as a counting problem. Digits of the integer `n` are just slots where we put elements of `digits` (repetition is allowed). For example, for 2 given `digits` and an integer `n` with 3 digits, we can form 3 slots `_ _ _ `, then put there the number of `digits` and multiply them: `2 * 2 * 2 = 8`. That would be our answer for just 3 slots and `n = 999`. \n\nBut, by the condition of the problem, formed integers can be less or equal to `n`. So for our example, we would have to add to our result the number of integers that can be formed for lower dimensional integers: `len(digits)**1 + len(digits)**2 ...`. \n\nAlso, we have to take into account that `n` does not necessarily contain all `9`s. That is, for the highest dimension, we have to iterate over all digits of `n` and add to the result the number of integers that can be formed for an integer that starts from the `firstDigit - 1` and has a given number of slots. \n\nFor example, for `n=164` (3 slots) and `digits={1, 6, 3}`, the result would be the number of integers for 1 and 2 slot (which is `len(digits) + len(digits)**2`), plus the number of integers that less or equal to `60 - 1` and has 2 slots, plus all elements of `digits` that less or equal to `4`. We don\'t consider here `100 - 1` since we would get `99` that is 2 slots integers that have already been counted on the first step.\n\n### Complexity:\n\nTime: **O(log10(n))** - since for every digit of `n` we iterate over all elements of `digits` (maximum 9). Number of digits in a decimal integer is equal to `log10(n) + 1`. So more precisely that would be `O((log10(n) + 1) * len(digits))`.\nSpace: **O(log10(n))** - since we convert `n` to string\n\nRuntime: 24 ms, faster than **92.59%** of Python3 online submissions for Numbers At Most N Given Digit Set.\nMemory Usage: 14.4 MB, less than **50.93%** of Python3 online submissions for Numbers At Most N Given Digit Set.\n\n```\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n digits = set(int(d) for d in digits)\n dLen = len(digits)\n nStr = str(n)\n nLen = len(nStr)\n \n res = sum(dLen**i for i in range(1, nLen)) # lower dimensions\n \n def helper(firstDigit, slots):\n if slots == 1:\n return sum(d <= firstDigit for d in digits)\n\n return sum(d < firstDigit for d in digits) * dLen**(slots - 1)\n \n for i in range(nLen):\n curDigit = int(nStr[i])\n\n res += helper(curDigit, nLen - i)\n \n if not curDigit in digits: # makes no sense to continue\n break\n \n return res\n```
8
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. **Example 1:** **Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100 **Output:** 20 **Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. **Example 2:** **Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000 **Output:** 29523 **Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. **Example 3:** **Input:** digits = \[ "7 "\], n = 8 **Output:** 1 **Constraints:** * `1 <= digits.length <= 9` * `digits[i].length == 1` * `digits[i]` is a digit from `'1'` to `'9'`. * All the values in `digits` are **unique**. * `digits` is sorted in **non-decreasing** order. * `1 <= n <= 109`
null
✔️ [Python3] NOT BEGINNER FRIENDLY, Explained
numbers-at-most-n-given-digit-set
0
1
We can approach this as a counting problem. Digits of the integer `n` are just slots where we put elements of `digits` (repetition is allowed). For example, for 2 given `digits` and an integer `n` with 3 digits, we can form 3 slots `_ _ _ `, then put there the number of `digits` and multiply them: `2 * 2 * 2 = 8`. That would be our answer for just 3 slots and `n = 999`. \n\nBut, by the condition of the problem, formed integers can be less or equal to `n`. So for our example, we would have to add to our result the number of integers that can be formed for lower dimensional integers: `len(digits)**1 + len(digits)**2 ...`. \n\nAlso, we have to take into account that `n` does not necessarily contain all `9`s. That is, for the highest dimension, we have to iterate over all digits of `n` and add to the result the number of integers that can be formed for an integer that starts from the `firstDigit - 1` and has a given number of slots. \n\nFor example, for `n=164` (3 slots) and `digits={1, 6, 3}`, the result would be the number of integers for 1 and 2 slot (which is `len(digits) + len(digits)**2`), plus the number of integers that less or equal to `60 - 1` and has 2 slots, plus all elements of `digits` that less or equal to `4`. We don\'t consider here `100 - 1` since we would get `99` that is 2 slots integers that have already been counted on the first step.\n\n### Complexity:\n\nTime: **O(log10(n))** - since for every digit of `n` we iterate over all elements of `digits` (maximum 9). Number of digits in a decimal integer is equal to `log10(n) + 1`. So more precisely that would be `O((log10(n) + 1) * len(digits))`.\nSpace: **O(log10(n))** - since we convert `n` to string\n\nRuntime: 24 ms, faster than **92.59%** of Python3 online submissions for Numbers At Most N Given Digit Set.\nMemory Usage: 14.4 MB, less than **50.93%** of Python3 online submissions for Numbers At Most N Given Digit Set.\n\n```\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n digits = set(int(d) for d in digits)\n dLen = len(digits)\n nStr = str(n)\n nLen = len(nStr)\n \n res = sum(dLen**i for i in range(1, nLen)) # lower dimensions\n \n def helper(firstDigit, slots):\n if slots == 1:\n return sum(d <= firstDigit for d in digits)\n\n return sum(d < firstDigit for d in digits) * dLen**(slots - 1)\n \n for i in range(nLen):\n curDigit = int(nStr[i])\n\n res += helper(curDigit, nLen - i)\n \n if not curDigit in digits: # makes no sense to continue\n break\n \n return res\n```
8
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32. **Example 2:** **Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10 **Output:** 23 **Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23. **Constraints:** * The number of nodes in the tree is in the range `[1, 2 * 104]`. * `1 <= Node.val <= 105` * `1 <= low <= high <= 105` * All `Node.val` are **unique**.
null
Python, confidence destroyer
numbers-at-most-n-given-digit-set
0
1
This is one of those seemingly-easy problems, that hit you later on as all of your straightforward solutions fail and you start questioning yourself. After trying the first two obvious solutions that come to mind (DFS and BFS) and failing, I figured out the third one (mathy), much later.\n1. DFS, will result in TLE:\n```\ndef atMostNGivenDigitSetDFS(self, digits: List[str], n: int) -> int:\n\tdigits = list(map(int, digits))\n\n\tdef count_nums_with_prefix(prefix=0):\n\t\tif prefix > n: return 0\n\t\treturn sum(count_nums_with_prefix(prefix * 10 + d) for d in digits) + 1\n\n\treturn count_nums_with_prefix() - 1\n```\n\n2. BFS, will result in TLE:\n```\ndef atMostNGivenDigitSetBFS(self, digits: List[str], n: int) -> int:\n\tdigits = list(map(int, digits))\n\tcnt = 0\n\tqueue = deque(digits)\n\twhile queue:\n\t\tnum = queue.popleft()\n\t\tif num > n: continue\n\t\tcnt += 1\n\t\tfor d in digits:\n\t\t\tqueue.append(num * 10 + d)\n\n\treturn cnt\n```\n3. Math. \na. At first we find out all the numbers that can be constructed that have length of less than n.\nb. Then we count the numbers with the length same as n that can be constructed from digits.\n```\ndef atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n\tdigits = set(map(int, digits))\n\tsn = str(n)\n\tln = len(sn)\n\n\tcnt = 0\n\n\tfor l in range(1, ln):\n\t\tcnt += len(digits) ** l\n\n\tfor i, dn in enumerate(sn):\n\t\tdn = int(dn)\n\t\tless_than = sum(d < dn for d in digits) # all leading digits that are less than current are valid\n\t\tcnt += less_than * len(digits) ** (ln - i - 1)\n\t\tif dn not in digits: break\n\t\telif i == ln - 1: cnt += 1\n\n\treturn cnt\n```
6
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. **Example 1:** **Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100 **Output:** 20 **Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. **Example 2:** **Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000 **Output:** 29523 **Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. **Example 3:** **Input:** digits = \[ "7 "\], n = 8 **Output:** 1 **Constraints:** * `1 <= digits.length <= 9` * `digits[i].length == 1` * `digits[i]` is a digit from `'1'` to `'9'`. * All the values in `digits` are **unique**. * `digits` is sorted in **non-decreasing** order. * `1 <= n <= 109`
null
Python, confidence destroyer
numbers-at-most-n-given-digit-set
0
1
This is one of those seemingly-easy problems, that hit you later on as all of your straightforward solutions fail and you start questioning yourself. After trying the first two obvious solutions that come to mind (DFS and BFS) and failing, I figured out the third one (mathy), much later.\n1. DFS, will result in TLE:\n```\ndef atMostNGivenDigitSetDFS(self, digits: List[str], n: int) -> int:\n\tdigits = list(map(int, digits))\n\n\tdef count_nums_with_prefix(prefix=0):\n\t\tif prefix > n: return 0\n\t\treturn sum(count_nums_with_prefix(prefix * 10 + d) for d in digits) + 1\n\n\treturn count_nums_with_prefix() - 1\n```\n\n2. BFS, will result in TLE:\n```\ndef atMostNGivenDigitSetBFS(self, digits: List[str], n: int) -> int:\n\tdigits = list(map(int, digits))\n\tcnt = 0\n\tqueue = deque(digits)\n\twhile queue:\n\t\tnum = queue.popleft()\n\t\tif num > n: continue\n\t\tcnt += 1\n\t\tfor d in digits:\n\t\t\tqueue.append(num * 10 + d)\n\n\treturn cnt\n```\n3. Math. \na. At first we find out all the numbers that can be constructed that have length of less than n.\nb. Then we count the numbers with the length same as n that can be constructed from digits.\n```\ndef atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n\tdigits = set(map(int, digits))\n\tsn = str(n)\n\tln = len(sn)\n\n\tcnt = 0\n\n\tfor l in range(1, ln):\n\t\tcnt += len(digits) ** l\n\n\tfor i, dn in enumerate(sn):\n\t\tdn = int(dn)\n\t\tless_than = sum(d < dn for d in digits) # all leading digits that are less than current are valid\n\t\tcnt += less_than * len(digits) ** (ln - i - 1)\n\t\tif dn not in digits: break\n\t\telif i == ln - 1: cnt += 1\n\n\treturn cnt\n```
6
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32. **Example 2:** **Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10 **Output:** 23 **Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23. **Constraints:** * The number of nodes in the tree is in the range `[1, 2 * 104]`. * `1 <= Node.val <= 105` * `1 <= low <= high <= 105` * All `Node.val` are **unique**.
null
[Python3] dp
numbers-at-most-n-given-digit-set
0
1
\n```\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n s = str(n)\n prev = 1\n for i, ch in enumerate(reversed(s)): \n k = bisect_left(digits, ch)\n ans = k*len(digits)**i\n if k < len(digits) and digits[k] == ch: ans += prev \n prev = ans\n return ans + sum(len(digits)**i for i in range(1, len(s)))\n```\n\n```\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n s = str(n)\n ans = sum(len(digits) ** i for i in range(1, len(s)))\n for i in range(len(s)): \n ans += sum(c < s[i] for c in digits) * (len(digits) ** (len(s) - i - 1))\n if s[i] not in digits: return ans\n return ans + 1\n```
3
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. **Example 1:** **Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100 **Output:** 20 **Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. **Example 2:** **Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000 **Output:** 29523 **Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. **Example 3:** **Input:** digits = \[ "7 "\], n = 8 **Output:** 1 **Constraints:** * `1 <= digits.length <= 9` * `digits[i].length == 1` * `digits[i]` is a digit from `'1'` to `'9'`. * All the values in `digits` are **unique**. * `digits` is sorted in **non-decreasing** order. * `1 <= n <= 109`
null
[Python3] dp
numbers-at-most-n-given-digit-set
0
1
\n```\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n s = str(n)\n prev = 1\n for i, ch in enumerate(reversed(s)): \n k = bisect_left(digits, ch)\n ans = k*len(digits)**i\n if k < len(digits) and digits[k] == ch: ans += prev \n prev = ans\n return ans + sum(len(digits)**i for i in range(1, len(s)))\n```\n\n```\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n s = str(n)\n ans = sum(len(digits) ** i for i in range(1, len(s)))\n for i in range(len(s)): \n ans += sum(c < s[i] for c in digits) * (len(digits) ** (len(s) - i - 1))\n if s[i] not in digits: return ans\n return ans + 1\n```
3
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32. **Example 2:** **Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10 **Output:** 23 **Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23. **Constraints:** * The number of nodes in the tree is in the range `[1, 2 * 104]`. * `1 <= Node.val <= 105` * `1 <= low <= high <= 105` * All `Node.val` are **unique**.
null
Python simple solution
numbers-at-most-n-given-digit-set
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can clearly observe that any numbers where len(number) is less than n will definitely be accepted. Anything more than will obviously fail. That is if n is 345, any 2 digit or 1 digit will pass but 4 digit or more will fail. So we iterate all possibilities which is just number of digits times the length of the number for each length less than n.\n\nNow, we are just left with one special case where the length of the numbers is same as n. In this case, we keep checking the leftmost integer of n to see if it exists in digits. If it does not, then we can just take everything less than n and multiply it accordingly. If there is an int in digits equal to the leftmost int in n, then we check the next number (but still continuing to just simply multiply everything smaller). We repeat this process until we reach an int that does not exist in digits or we reach the end.\n# Complexity\n- Time complexity: O(max(len(n),10))\n\n- Space complexity: O(10)\n\n# Code\n```\nimport math\n#Sorry about naming of variables\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n hmm = len(str(n))\n ans = 0\n for x in range(1, hmm):\n ans += len(digits)**x\n\n gg = {}\n count = 0\n for x in range(0, 10):\n gg[x] = count\n if str(x) in digits:\n count += 1\n\n\n\n for x in range(0,hmm):\n \n ans += gg[int(str(n)[x])] * len(digits)**(hmm-x-1)\n if str(n)[x] not in digits:\n break\n if x == hmm-1:\n ans+=1\n \n\n\n\n return ans\n\n\n \n```
0
Given an array of `digits` which is sorted in **non-decreasing** order. You can write numbers using each `digits[i]` as many times as we want. For example, if `digits = ['1','3','5']`, we may write numbers such as `'13'`, `'551'`, and `'1351315'`. Return _the number of positive integers that can be generated_ that are less than or equal to a given integer `n`. **Example 1:** **Input:** digits = \[ "1 ", "3 ", "5 ", "7 "\], n = 100 **Output:** 20 **Explanation:** The 20 numbers that can be written are: 1, 3, 5, 7, 11, 13, 15, 17, 31, 33, 35, 37, 51, 53, 55, 57, 71, 73, 75, 77. **Example 2:** **Input:** digits = \[ "1 ", "4 ", "9 "\], n = 1000000000 **Output:** 29523 **Explanation:** We can write 3 one digit numbers, 9 two digit numbers, 27 three digit numbers, 81 four digit numbers, 243 five digit numbers, 729 six digit numbers, 2187 seven digit numbers, 6561 eight digit numbers, and 19683 nine digit numbers. In total, this is 29523 integers that can be written using the digits array. **Example 3:** **Input:** digits = \[ "7 "\], n = 8 **Output:** 1 **Constraints:** * `1 <= digits.length <= 9` * `digits[i].length == 1` * `digits[i]` is a digit from `'1'` to `'9'`. * All the values in `digits` are **unique**. * `digits` is sorted in **non-decreasing** order. * `1 <= n <= 109`
null
Python simple solution
numbers-at-most-n-given-digit-set
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can clearly observe that any numbers where len(number) is less than n will definitely be accepted. Anything more than will obviously fail. That is if n is 345, any 2 digit or 1 digit will pass but 4 digit or more will fail. So we iterate all possibilities which is just number of digits times the length of the number for each length less than n.\n\nNow, we are just left with one special case where the length of the numbers is same as n. In this case, we keep checking the leftmost integer of n to see if it exists in digits. If it does not, then we can just take everything less than n and multiply it accordingly. If there is an int in digits equal to the leftmost int in n, then we check the next number (but still continuing to just simply multiply everything smaller). We repeat this process until we reach an int that does not exist in digits or we reach the end.\n# Complexity\n- Time complexity: O(max(len(n),10))\n\n- Space complexity: O(10)\n\n# Code\n```\nimport math\n#Sorry about naming of variables\nclass Solution:\n def atMostNGivenDigitSet(self, digits: List[str], n: int) -> int:\n hmm = len(str(n))\n ans = 0\n for x in range(1, hmm):\n ans += len(digits)**x\n\n gg = {}\n count = 0\n for x in range(0, 10):\n gg[x] = count\n if str(x) in digits:\n count += 1\n\n\n\n for x in range(0,hmm):\n \n ans += gg[int(str(n)[x])] * len(digits)**(hmm-x-1)\n if str(n)[x] not in digits:\n break\n if x == hmm-1:\n ans+=1\n \n\n\n\n return ans\n\n\n \n```
0
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the range \[7, 15\]. 7 + 10 + 15 = 32. **Example 2:** **Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10 **Output:** 23 **Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23. **Constraints:** * The number of nodes in the tree is in the range `[1, 2 * 104]`. * `1 <= Node.val <= 105` * `1 <= low <= high <= 105` * All `Node.val` are **unique**.
null
DP Solution
valid-permutations-for-di-sequence
0
1
To add a new character to a sequence we only have to consider the last element-\n\nLets say currently DID sequence is 1032- this can form\n\nDIDI - in cases where we end with 3,4\nDIDD - in cases where we end with 0,1,2\n\nSo just use the last element value to create a new sequence.\n\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n mem=defaultdict(int)\n def dfs(i,val=0):\n if i==len(s):\n return 1\n if (i,val) in mem:\n return mem[i,val]\n p=0\n if s[i]=="D":\n for ind in range(0,val+1):\n p+=dfs(i+1,ind)%(10**9+7)\n else:\n for ind in range(val+1,i+2):\n p+=dfs(i+1,ind)%(10**9+7)\n mem[i,val]=p\n return p\n return dfs(0)\n ```\n\t\t\t\t
1
You are given a string `s` of length `n` where `s[i]` is either: * `'D'` means decreasing, or * `'I'` means increasing. A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if for all valid `i`: * If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and * If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. Return _the number of **valid permutations**_ `perm`. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "DID " **Output:** 5 **Explanation:** The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) **Example 2:** **Input:** s = "D " **Output:** 1 **Constraints:** * `n == s.length` * `1 <= n <= 200` * `s[i]` is either `'I'` or `'D'`.
null
DP Solution
valid-permutations-for-di-sequence
0
1
To add a new character to a sequence we only have to consider the last element-\n\nLets say currently DID sequence is 1032- this can form\n\nDIDI - in cases where we end with 3,4\nDIDD - in cases where we end with 0,1,2\n\nSo just use the last element value to create a new sequence.\n\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n mem=defaultdict(int)\n def dfs(i,val=0):\n if i==len(s):\n return 1\n if (i,val) in mem:\n return mem[i,val]\n p=0\n if s[i]=="D":\n for ind in range(0,val+1):\n p+=dfs(i+1,ind)%(10**9+7)\n else:\n for ind in range(val+1,i+2):\n p+=dfs(i+1,ind)%(10**9+7)\n mem[i,val]=p\n return p\n return dfs(0)\n ```\n\t\t\t\t
1
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\] **Output:** 4 **Example 2:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\] **Output:** 2 **Constraints:** * `1 <= points.length <= 500` * `points[i].length == 2` * `0 <= xi, yi <= 4 * 104` * All the given points are **unique**.
null
python DP top down + backtracking
valid-permutations-for-di-sequence
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 numPermsDISequence(self, s: str) -> int:\n n = len(s) + 1\n \n\n visit = set()\n @functools.lru_cache(None)\n def dp(prev, j):\n \n if j == len(s):\n return 1\n ans = 0\n if prev == -1:\n for i in range(n):\n visit.add(i)\n ans += dp(i+1, 0)\n visit.remove(i)\n return ans\n if s[j] == "D":\n\n for i in range(prev-1):\n if i in visit:\n continue\n visit.add(i)\n ans += dp(i+1, j+1)\n visit.remove(i)\n else:\n for i in range(prev, n):\n if i in visit:\n continue\n visit.add(i)\n ans += dp(i+1, j+1)\n visit.remove(i)\n return ans\n \n return dp(-1, 0) % (10**9 + 7)\n\n\n\n\n```
0
You are given a string `s` of length `n` where `s[i]` is either: * `'D'` means decreasing, or * `'I'` means increasing. A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if for all valid `i`: * If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and * If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. Return _the number of **valid permutations**_ `perm`. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "DID " **Output:** 5 **Explanation:** The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) **Example 2:** **Input:** s = "D " **Output:** 1 **Constraints:** * `n == s.length` * `1 <= n <= 200` * `s[i]` is either `'I'` or `'D'`.
null
python DP top down + backtracking
valid-permutations-for-di-sequence
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 numPermsDISequence(self, s: str) -> int:\n n = len(s) + 1\n \n\n visit = set()\n @functools.lru_cache(None)\n def dp(prev, j):\n \n if j == len(s):\n return 1\n ans = 0\n if prev == -1:\n for i in range(n):\n visit.add(i)\n ans += dp(i+1, 0)\n visit.remove(i)\n return ans\n if s[j] == "D":\n\n for i in range(prev-1):\n if i in visit:\n continue\n visit.add(i)\n ans += dp(i+1, j+1)\n visit.remove(i)\n else:\n for i in range(prev, n):\n if i in visit:\n continue\n visit.add(i)\n ans += dp(i+1, j+1)\n visit.remove(i)\n return ans\n \n return dp(-1, 0) % (10**9 + 7)\n\n\n\n\n```
0
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\] **Output:** 4 **Example 2:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\] **Output:** 2 **Constraints:** * `1 <= points.length <= 500` * `points[i].length == 2` * `0 <= xi, yi <= 4 * 104` * All the given points are **unique**.
null
Editorial-like solution, simple to understand with multiple approaches from Brute-force to optimal
valid-permutations-for-di-sequence
0
1
The problem asks what is the number of valid permutations that follow a string of `"DI"` instructions, if a number `i` is used in a podition with `\'D\'` the next number must be in the range `0 <= j < i`, likewise if it\'s in an `\'I\'` position the next number must be `i < j <= n` where `n` is the length if the string provided, the hard part comes in that we cannot repeat the same number, so it seems (but turns out not to be the case) that we need to remember all the previous numbers to solve the problem, let\'s see how we might develop a solution.\n\n\n# Approach #1: Brute-Force\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thing that is recommended to be done in a complex problem like this one is to generate all possible solutions and discard the invalid ones, that can be done via backtracking, we define a helper function `backTrack` that keeps track of where in the string we are and what was the previous number used, and define a set `state` that contains all numbers previously used; at a given index position `i` we check for all numbers bigger/smaller than the previous number, if we can insert it into the permutation we add it to the stack, we we are done generating all it\'s sub-solutions we remove it from the set, (this can also be done with a stack, which may be faster).\nIf we reach `i == n` we finished generating a permutation and add `1` to our count (which I named `ans`).\n\n# Algorithm\n<!-- Describe your approach to solving the problem. -->\n1. Define a set/stack and a counter\n2. Define the `backTrack` function:\n2.1 If we reached the end, increase the counter\n2.2 If not, go through all numbers lower/higher than the previous number and check if they can be added, if yes then add the number tot the set, call `backTrack` with `i+1` and this added number, when the function returns, remove the number from the set\n3. Call `backTrack` for all possible starting number `0` to `n`\n\n# Complexity\n- Time complexity: $$O(n!)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nAt any index `i` we have `i` options to choose from in worst-case, since `n` can go up to `200` this will result in a TLE.\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe use a set/stack that will contain at most `n` numbers when a permutation is complete\n\n# Implementation (only python, sorry)\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n ans = [0]\n state = set()\n def backTrack(i, p):\n if i == n:\n ans[0] += 1\n return\n if s[i] == "I":\n for j in range(p+1, n+1):\n if j not in state:\n state.add(j)\n backTrack(i+1, j)\n state.remove(j)\n else:\n for j in range(0, p):\n if j not in state:\n state.add(j)\n backTrack(i+1, j)\n state.remove(j)\n return \n for i in range(n+1):\n state.add(i)\n backTrack(0, i)\n state.remove(i)\n return ans[0]%(10**9+7)\n```\n\n# Approach #2: Dynamic programming\n\n# Intuition\nThe previous solution was too slow to be accepted, we need to find a faster way to calculate the answer. We first note that we got asked the number of valid permutations, so maybe (for this problem to be possible, we definitely) we don\'t need to generate all possible permutations to know how many there are, usually we can break down a problem into sub-problems to generate an answer faster from solving sub-problems\nAt first it may look like this is impossible to do here, since at each index the number we choose will affect all the possible choices in the future, but remembering we only need to know the quantity we may wonder if maybe the quantities are not dependent directly on the number you choose to place, let\'s do a thought experiment, imagine instead of using the numbers `(1,2,3,4, ...)` to generate our permutatons we use `(1,1,1,1, ...)` only a bunch of ones, and when we use a number like `3` the whole thing turns into `(1,1,0,1, ...)` so we have a certain concept of "order" so that the problem is the same, now think about using `1` or `2` or `3`, in a given index `i` we would get accordingly `(0,1,1,1), (1,0,1,1), (1,1,0,1)` which are different, but look very similar! Why they all look so similar? because they all have the same idea of **relative ordering**, `1` is still smaller than `3` and `4` even when 2 is out of the equation and likewise for all the others, so if we only focus on the relative ordering of the numbers essentially all of the three sub-problems above are **identical**, so we can just represent them all as `(1,1,1)`.\nThis is still not the complete picture, we know that the `"ID"` will limit our choice of next number, so returning to the last example, if the digit is `\'I\'`, then in the case of choosing `1` we would have `(0,1,1,1)` and the next number could be any of the following ones, but if we chose `2` the the sub-problem is `(1,0,1,1)` and we can only choose as the next number the ones to the right of the new zero, likewise if it were a `\'D\'` it would be the ones to the left of the zero, with that in mind we can now define our dynamic programming sub-problem.\n\n`\ndp[i][j] = Solution to sub-problem s[i:n], if we can choose only ones bounded to the j\'th one\n`\n\nBy bounded I mean that if `s[i]` is `\'I\'` we can choose the ones from the `j` one to the right-end and if it is a `\'D\'` we can choose the ones from `j` one to the left-end.\nFor example `dp[2][3]` for the tuple `(1,1,1,1,1,1,1)` is the solution to the sub-string `s[2:n]` using at position `2` any one that is from the inclusive left/right (depending on `s[2]`) of the highlighted one in `(1,1,_1_,1,1)`, notice that the size of the tuple is smaller by 2 than the original because we zero\'ed two other ones in the original tuple, in general, if the original tuple is of size `n`, at index `i` the tuple will have size `n-i`.\n\nNow that we have a table, let\'s see how we can generate answers from sub-problems. The base case is very simple, `s[n-1]` is either `\'I\'` or `\'D\'` and the tuple is simply `(1,1)`, we can define the base cases as follows:\n```\nif s[n-1] == \'I\':\n #If we choose 1, then it is impossible to increase\n dp[n-1][0] = 1\n dp[n-1][1] = 0\nelif s[n-1] == \'D:\n #If we choose 0, then it is impossible to decrease\n dp[n-1][0] = 0\n dp[n-1][1] = 1\n```\nThis idea of choosing the highest number or the lowest, makes it impossible to continue will keep re-occurring in later cases too.\nFor an index `i < n-1` we know that if `s[i] == \'I\'` then the last number will have an answer of zero, if `s[i] == \'D\'` then the first number will have an answer of zero, in general `dp[i][j]\n` will have all the answers that were pre-calculated in that row `i` (from the definition of the dp) and will also contain all the possible answers of the sub-problem at the `i+1` using only one to the left/right of it, which in our table happens that answer turns out to be stored in `dp[i+1][j]` (you can convince yourself of that by imagining how removing a one from a tuple changes the absolute postion of each remaining one), so our final update step looks like this.\n\n```\nif s[n-1] == \'I\':\n if i == n-1:\n #If we choose 1, then it is impossible to increase\n dp[n-1][0] = 1\n dp[n-1][1] = 0\n else:\n if j == n-i:\n dp[i][j] = 0\n else:\n dp[i][j] = dp[i][j+1] + dp[i+1][j]\nelif s[n-1] == \'D:\n if i == n-1:\n #If we choose 0, then it is impossible to decrease\n dp[n-1][0] = 0\n dp[n-1][1] = 1\n else:\n if j == 0:\n dp[i][j] = 0\n else:\n dp[i][j] = dp[i][j-1] + dp[i+1][j]\n```\nPhew! That\'s a pretty complicated update step, make sure you understand it, before writing it down because later on it will get worse! Now at last all that\'s left to do is to write down the solution\n\n# Algorithm\n1. Define our table `dp`\n2. Go from the base case to the original case\n3. Update the table according to the update step\n4. return the `sum` of all possible start choices\n\n# Implementation (only python, sorry)\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n dp = [[None for j in range(n-i+1)] for i in range(n)]\n for j in range(n-1, 0-1, -1):\n if s[j] == "I":\n if j == n-1:\n dp[j][0] = 1\n dp[j][1] = 0\n else:\n dp[j][n-j] = 0\n for i in range((n-j)-1, 0-1, -1):\n dp[j][i] = dp[j+1][i]+dp[j][i+1]\n else:\n if j == n-1:\n dp[j][0] = 0\n dp[j][1] = 1\n else:\n dp[j][0] = 0\n for i in range(1, n-j+1):\n dp[j][i] = dp[j+1][i-1]+dp[j][i-1]\n return sum([dp[0][i] for i in range(n+1)])%(10**9+7)\n```\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nIt only takes $O(1)$ to calculate the update step, we have `n + n-1 + n-2 + ... ` entries in the table, so $n^2$ time to compute every entry.\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe table has size $n^2$\n\n# Approach 3 DP + Double buffer\n\nWe notice that the update step only makes use of the last computed row and the current row being computed, so we can use two arrays and to calculate the whole ordeal, the space complexity will then be $O(n)$\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n dp = None\n for j in range(n-1, 0-1, -1):\n ndp = [None for i in range(n-j+1)]\n if s[j] == "I":\n if j == n-1:\n ndp[0] = 1\n ndp[1] = 0\n else:\n ndp[n-j] = 0\n for i in range((n-j)-1, 0-1, -1):\n ndp[i] = dp[i]+ndp[i+1]\n else:\n if j == n-1:\n ndp[0] = 0\n ndp[1] = 1\n else:\n ndp[0] = 0\n for i in range(1, n-j+1):\n ndp[i] = dp[i-1]+ndp[i-1]\n dp = ndp\n return sum(dp)%(10**9+7)\n```\n\n# Approach 4 Optimized memory\n\nWe can make a solution with only one array, first notice that the update step of `\'I\'` is fairly easy to adapt to one array since the base case is in a completely new index, but in the `\'D` case we need to update `i=0` so we set a variable `last` to remember the last value removed, but we need the last variable to update the next entry so we define an `nlast` to remember the variable that is about to be updated so that we can then update last with the value that was before the update, whew... (see the code, it\'s easier to understand)\n\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n dp = [0 for _ in range(n+1)]\n for j in range(n-1, 0-1, -1):\n if s[j] == "I":\n if j == n-1:\n dp[0] = 1\n dp[1] = 0\n else:\n dp[n-j] = 0\n for i in range((n-j)-1, 0-1, -1):\n dp[i] = dp[i]+dp[i+1]\n else:\n if j == n-1:\n dp[0] = 0\n dp[1] = 1\n else:\n last = dp[0]\n dp[0] = 0\n for i in range(1, n-j+1):\n nlast = dp[i]\n dp[i] = last+dp[i-1]\n last = nlast\n return sum(dp)%(10**9+7)\n```\n\nAny comments or improvements are appreciated, thank you for reading!
0
You are given a string `s` of length `n` where `s[i]` is either: * `'D'` means decreasing, or * `'I'` means increasing. A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if for all valid `i`: * If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and * If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. Return _the number of **valid permutations**_ `perm`. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "DID " **Output:** 5 **Explanation:** The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) **Example 2:** **Input:** s = "D " **Output:** 1 **Constraints:** * `n == s.length` * `1 <= n <= 200` * `s[i]` is either `'I'` or `'D'`.
null
Editorial-like solution, simple to understand with multiple approaches from Brute-force to optimal
valid-permutations-for-di-sequence
0
1
The problem asks what is the number of valid permutations that follow a string of `"DI"` instructions, if a number `i` is used in a podition with `\'D\'` the next number must be in the range `0 <= j < i`, likewise if it\'s in an `\'I\'` position the next number must be `i < j <= n` where `n` is the length if the string provided, the hard part comes in that we cannot repeat the same number, so it seems (but turns out not to be the case) that we need to remember all the previous numbers to solve the problem, let\'s see how we might develop a solution.\n\n\n# Approach #1: Brute-Force\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thing that is recommended to be done in a complex problem like this one is to generate all possible solutions and discard the invalid ones, that can be done via backtracking, we define a helper function `backTrack` that keeps track of where in the string we are and what was the previous number used, and define a set `state` that contains all numbers previously used; at a given index position `i` we check for all numbers bigger/smaller than the previous number, if we can insert it into the permutation we add it to the stack, we we are done generating all it\'s sub-solutions we remove it from the set, (this can also be done with a stack, which may be faster).\nIf we reach `i == n` we finished generating a permutation and add `1` to our count (which I named `ans`).\n\n# Algorithm\n<!-- Describe your approach to solving the problem. -->\n1. Define a set/stack and a counter\n2. Define the `backTrack` function:\n2.1 If we reached the end, increase the counter\n2.2 If not, go through all numbers lower/higher than the previous number and check if they can be added, if yes then add the number tot the set, call `backTrack` with `i+1` and this added number, when the function returns, remove the number from the set\n3. Call `backTrack` for all possible starting number `0` to `n`\n\n# Complexity\n- Time complexity: $$O(n!)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nAt any index `i` we have `i` options to choose from in worst-case, since `n` can go up to `200` this will result in a TLE.\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nWe use a set/stack that will contain at most `n` numbers when a permutation is complete\n\n# Implementation (only python, sorry)\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n ans = [0]\n state = set()\n def backTrack(i, p):\n if i == n:\n ans[0] += 1\n return\n if s[i] == "I":\n for j in range(p+1, n+1):\n if j not in state:\n state.add(j)\n backTrack(i+1, j)\n state.remove(j)\n else:\n for j in range(0, p):\n if j not in state:\n state.add(j)\n backTrack(i+1, j)\n state.remove(j)\n return \n for i in range(n+1):\n state.add(i)\n backTrack(0, i)\n state.remove(i)\n return ans[0]%(10**9+7)\n```\n\n# Approach #2: Dynamic programming\n\n# Intuition\nThe previous solution was too slow to be accepted, we need to find a faster way to calculate the answer. We first note that we got asked the number of valid permutations, so maybe (for this problem to be possible, we definitely) we don\'t need to generate all possible permutations to know how many there are, usually we can break down a problem into sub-problems to generate an answer faster from solving sub-problems\nAt first it may look like this is impossible to do here, since at each index the number we choose will affect all the possible choices in the future, but remembering we only need to know the quantity we may wonder if maybe the quantities are not dependent directly on the number you choose to place, let\'s do a thought experiment, imagine instead of using the numbers `(1,2,3,4, ...)` to generate our permutatons we use `(1,1,1,1, ...)` only a bunch of ones, and when we use a number like `3` the whole thing turns into `(1,1,0,1, ...)` so we have a certain concept of "order" so that the problem is the same, now think about using `1` or `2` or `3`, in a given index `i` we would get accordingly `(0,1,1,1), (1,0,1,1), (1,1,0,1)` which are different, but look very similar! Why they all look so similar? because they all have the same idea of **relative ordering**, `1` is still smaller than `3` and `4` even when 2 is out of the equation and likewise for all the others, so if we only focus on the relative ordering of the numbers essentially all of the three sub-problems above are **identical**, so we can just represent them all as `(1,1,1)`.\nThis is still not the complete picture, we know that the `"ID"` will limit our choice of next number, so returning to the last example, if the digit is `\'I\'`, then in the case of choosing `1` we would have `(0,1,1,1)` and the next number could be any of the following ones, but if we chose `2` the the sub-problem is `(1,0,1,1)` and we can only choose as the next number the ones to the right of the new zero, likewise if it were a `\'D\'` it would be the ones to the left of the zero, with that in mind we can now define our dynamic programming sub-problem.\n\n`\ndp[i][j] = Solution to sub-problem s[i:n], if we can choose only ones bounded to the j\'th one\n`\n\nBy bounded I mean that if `s[i]` is `\'I\'` we can choose the ones from the `j` one to the right-end and if it is a `\'D\'` we can choose the ones from `j` one to the left-end.\nFor example `dp[2][3]` for the tuple `(1,1,1,1,1,1,1)` is the solution to the sub-string `s[2:n]` using at position `2` any one that is from the inclusive left/right (depending on `s[2]`) of the highlighted one in `(1,1,_1_,1,1)`, notice that the size of the tuple is smaller by 2 than the original because we zero\'ed two other ones in the original tuple, in general, if the original tuple is of size `n`, at index `i` the tuple will have size `n-i`.\n\nNow that we have a table, let\'s see how we can generate answers from sub-problems. The base case is very simple, `s[n-1]` is either `\'I\'` or `\'D\'` and the tuple is simply `(1,1)`, we can define the base cases as follows:\n```\nif s[n-1] == \'I\':\n #If we choose 1, then it is impossible to increase\n dp[n-1][0] = 1\n dp[n-1][1] = 0\nelif s[n-1] == \'D:\n #If we choose 0, then it is impossible to decrease\n dp[n-1][0] = 0\n dp[n-1][1] = 1\n```\nThis idea of choosing the highest number or the lowest, makes it impossible to continue will keep re-occurring in later cases too.\nFor an index `i < n-1` we know that if `s[i] == \'I\'` then the last number will have an answer of zero, if `s[i] == \'D\'` then the first number will have an answer of zero, in general `dp[i][j]\n` will have all the answers that were pre-calculated in that row `i` (from the definition of the dp) and will also contain all the possible answers of the sub-problem at the `i+1` using only one to the left/right of it, which in our table happens that answer turns out to be stored in `dp[i+1][j]` (you can convince yourself of that by imagining how removing a one from a tuple changes the absolute postion of each remaining one), so our final update step looks like this.\n\n```\nif s[n-1] == \'I\':\n if i == n-1:\n #If we choose 1, then it is impossible to increase\n dp[n-1][0] = 1\n dp[n-1][1] = 0\n else:\n if j == n-i:\n dp[i][j] = 0\n else:\n dp[i][j] = dp[i][j+1] + dp[i+1][j]\nelif s[n-1] == \'D:\n if i == n-1:\n #If we choose 0, then it is impossible to decrease\n dp[n-1][0] = 0\n dp[n-1][1] = 1\n else:\n if j == 0:\n dp[i][j] = 0\n else:\n dp[i][j] = dp[i][j-1] + dp[i+1][j]\n```\nPhew! That\'s a pretty complicated update step, make sure you understand it, before writing it down because later on it will get worse! Now at last all that\'s left to do is to write down the solution\n\n# Algorithm\n1. Define our table `dp`\n2. Go from the base case to the original case\n3. Update the table according to the update step\n4. return the `sum` of all possible start choices\n\n# Implementation (only python, sorry)\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n dp = [[None for j in range(n-i+1)] for i in range(n)]\n for j in range(n-1, 0-1, -1):\n if s[j] == "I":\n if j == n-1:\n dp[j][0] = 1\n dp[j][1] = 0\n else:\n dp[j][n-j] = 0\n for i in range((n-j)-1, 0-1, -1):\n dp[j][i] = dp[j+1][i]+dp[j][i+1]\n else:\n if j == n-1:\n dp[j][0] = 0\n dp[j][1] = 1\n else:\n dp[j][0] = 0\n for i in range(1, n-j+1):\n dp[j][i] = dp[j+1][i-1]+dp[j][i-1]\n return sum([dp[0][i] for i in range(n+1)])%(10**9+7)\n```\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nIt only takes $O(1)$ to calculate the update step, we have `n + n-1 + n-2 + ... ` entries in the table, so $n^2$ time to compute every entry.\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe table has size $n^2$\n\n# Approach 3 DP + Double buffer\n\nWe notice that the update step only makes use of the last computed row and the current row being computed, so we can use two arrays and to calculate the whole ordeal, the space complexity will then be $O(n)$\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n dp = None\n for j in range(n-1, 0-1, -1):\n ndp = [None for i in range(n-j+1)]\n if s[j] == "I":\n if j == n-1:\n ndp[0] = 1\n ndp[1] = 0\n else:\n ndp[n-j] = 0\n for i in range((n-j)-1, 0-1, -1):\n ndp[i] = dp[i]+ndp[i+1]\n else:\n if j == n-1:\n ndp[0] = 0\n ndp[1] = 1\n else:\n ndp[0] = 0\n for i in range(1, n-j+1):\n ndp[i] = dp[i-1]+ndp[i-1]\n dp = ndp\n return sum(dp)%(10**9+7)\n```\n\n# Approach 4 Optimized memory\n\nWe can make a solution with only one array, first notice that the update step of `\'I\'` is fairly easy to adapt to one array since the base case is in a completely new index, but in the `\'D` case we need to update `i=0` so we set a variable `last` to remember the last value removed, but we need the last variable to update the next entry so we define an `nlast` to remember the variable that is about to be updated so that we can then update last with the value that was before the update, whew... (see the code, it\'s easier to understand)\n\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n = len(s)\n dp = [0 for _ in range(n+1)]\n for j in range(n-1, 0-1, -1):\n if s[j] == "I":\n if j == n-1:\n dp[0] = 1\n dp[1] = 0\n else:\n dp[n-j] = 0\n for i in range((n-j)-1, 0-1, -1):\n dp[i] = dp[i]+dp[i+1]\n else:\n if j == n-1:\n dp[0] = 0\n dp[1] = 1\n else:\n last = dp[0]\n dp[0] = 0\n for i in range(1, n-j+1):\n nlast = dp[i]\n dp[i] = last+dp[i-1]\n last = nlast\n return sum(dp)%(10**9+7)\n```\n\nAny comments or improvements are appreciated, thank you for reading!
0
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\] **Output:** 4 **Example 2:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\] **Output:** 2 **Constraints:** * `1 <= points.length <= 500` * `points[i].length == 2` * `0 <= xi, yi <= 4 * 104` * All the given points are **unique**.
null
Python (Simple DP)
valid-permutations-for-di-sequence
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 numPermsDISequence(self, s):\n n, mod = len(s), 10**9+7\n\n @lru_cache(None)\n def dfs(i,val):\n if i == n:\n return 1\n\n if s[i] == "D":\n if val == 0: return 0\n return dfs(i,val-1) + dfs(i+1,val-1)\n\n if s[i] == "I":\n if val == n-i: return 0\n return dfs(i,val+1) + dfs(i+1,val)\n\n return sum([dfs(0,j) for j in range(n+1)])%mod\n \n```
0
You are given a string `s` of length `n` where `s[i]` is either: * `'D'` means decreasing, or * `'I'` means increasing. A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if for all valid `i`: * If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and * If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. Return _the number of **valid permutations**_ `perm`. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "DID " **Output:** 5 **Explanation:** The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) **Example 2:** **Input:** s = "D " **Output:** 1 **Constraints:** * `n == s.length` * `1 <= n <= 200` * `s[i]` is either `'I'` or `'D'`.
null
Python (Simple DP)
valid-permutations-for-di-sequence
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 numPermsDISequence(self, s):\n n, mod = len(s), 10**9+7\n\n @lru_cache(None)\n def dfs(i,val):\n if i == n:\n return 1\n\n if s[i] == "D":\n if val == 0: return 0\n return dfs(i,val-1) + dfs(i+1,val-1)\n\n if s[i] == "I":\n if val == n-i: return 0\n return dfs(i,val+1) + dfs(i+1,val)\n\n return sum([dfs(0,j) for j in range(n+1)])%mod\n \n```
0
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\] **Output:** 4 **Example 2:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\] **Output:** 2 **Constraints:** * `1 <= points.length <= 500` * `points[i].length == 2` * `0 <= xi, yi <= 4 * 104` * All the given points are **unique**.
null
[Python3] | Top-Down DP O(N^2)
valid-permutations-for-di-sequence
0
1
```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n,ans = len(s),0\n mod = 1_00_00_00_000 + 7\n memo = [[-1] * 201 for i in range(201)]\n def dp(ind,prevNum):\n if ind < 0:\n return 1\n if memo[ind][prevNum] != -1:\n return memo[ind][prevNum]\n val = 0\n if s[ind] == \'D\':\n for more in range(prevNum+1,n+1):\n if more not in vis:\n vis.add(more)\n val += dp(ind-1,more)\n vis.remove(more)\n else:\n for less in range(prevNum):\n if less not in vis:\n vis.add(less)\n val += dp(ind-1,less)\n vis.remove(less)\n memo[ind][prevNum] = val\n return memo[ind][prevNum]\n for i in range(n+1):\n vis = set([i])\n ans += dp(n-1,i)\n return ans % mod\n \n```
0
You are given a string `s` of length `n` where `s[i]` is either: * `'D'` means decreasing, or * `'I'` means increasing. A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if for all valid `i`: * If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and * If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. Return _the number of **valid permutations**_ `perm`. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "DID " **Output:** 5 **Explanation:** The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) **Example 2:** **Input:** s = "D " **Output:** 1 **Constraints:** * `n == s.length` * `1 <= n <= 200` * `s[i]` is either `'I'` or `'D'`.
null
[Python3] | Top-Down DP O(N^2)
valid-permutations-for-di-sequence
0
1
```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n n,ans = len(s),0\n mod = 1_00_00_00_000 + 7\n memo = [[-1] * 201 for i in range(201)]\n def dp(ind,prevNum):\n if ind < 0:\n return 1\n if memo[ind][prevNum] != -1:\n return memo[ind][prevNum]\n val = 0\n if s[ind] == \'D\':\n for more in range(prevNum+1,n+1):\n if more not in vis:\n vis.add(more)\n val += dp(ind-1,more)\n vis.remove(more)\n else:\n for less in range(prevNum):\n if less not in vis:\n vis.add(less)\n val += dp(ind-1,less)\n vis.remove(less)\n memo[ind][prevNum] = val\n return memo[ind][prevNum]\n for i in range(n+1):\n vis = set([i])\n ans += dp(n-1,i)\n return ans % mod\n \n```
0
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\] **Output:** 4 **Example 2:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\] **Output:** 2 **Constraints:** * `1 <= points.length <= 500` * `points[i].length == 2` * `0 <= xi, yi <= 4 * 104` * All the given points are **unique**.
null
[Python3] top-down dp
valid-permutations-for-di-sequence
0
1
\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n \n @cache \n def fn(i, x): \n """Return number of valid permutation given x numbers smaller than previous one."""\n if i == len(s): return 1 \n if s[i] == "D": \n if x == 0: return 0 # cannot decrease\n return fn(i, x-1) + fn(i+1, x-1)\n else: \n if x == len(s)-i: return 0 # cannot increase \n return fn(i, x+1) + fn(i+1, x)\n \n return sum(fn(0, x) for x in range(len(s)+1)) % 1_000_000_007\n```
1
You are given a string `s` of length `n` where `s[i]` is either: * `'D'` means decreasing, or * `'I'` means increasing. A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` is called a **valid permutation** if for all valid `i`: * If `s[i] == 'D'`, then `perm[i] > perm[i + 1]`, and * If `s[i] == 'I'`, then `perm[i] < perm[i + 1]`. Return _the number of **valid permutations**_ `perm`. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "DID " **Output:** 5 **Explanation:** The 5 valid permutations of (0, 1, 2, 3) are: (1, 0, 3, 2) (2, 0, 3, 1) (2, 1, 3, 0) (3, 0, 2, 1) (3, 1, 2, 0) **Example 2:** **Input:** s = "D " **Output:** 1 **Constraints:** * `n == s.length` * `1 <= n <= 200` * `s[i]` is either `'I'` or `'D'`.
null
[Python3] top-down dp
valid-permutations-for-di-sequence
0
1
\n```\nclass Solution:\n def numPermsDISequence(self, s: str) -> int:\n \n @cache \n def fn(i, x): \n """Return number of valid permutation given x numbers smaller than previous one."""\n if i == len(s): return 1 \n if s[i] == "D": \n if x == 0: return 0 # cannot decrease\n return fn(i, x-1) + fn(i+1, x-1)\n else: \n if x == len(s)-i: return 0 # cannot increase \n return fn(i, x+1) + fn(i+1, x)\n \n return sum(fn(0, x) for x in range(len(s)+1)) % 1_000_000_007\n```
1
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[2,2\]\] **Output:** 4 **Example 2:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\] **Output:** 2 **Constraints:** * `1 <= points.length <= 500` * `points[i].length == 2` * `0 <= xi, yi <= 4 * 104` * All the given points are **unique**.
null
Python || Sliding Window Technique
fruit-into-baskets
0
1
```\nfrom collections import Counter\n\nMAX_BASKETS = 2\n\n\nclass Solution:\n def totalFruit(self, fruits: list[int]) -> int:\n # return self.ensure_first_that_fruit_can_be_added(fruits)\n return self.ensure_later_that_fruit_can_be_added(fruits)\n\n @staticmethod\n def ensure_first_that_fruit_can_be_added(fruits: list[int]) -> int:\n cnt = Counter()\n output, w_start = 0, 0\n\n for w_end, t in enumerate(fruits):\n if cnt[t] == 0 and len(cnt) == MAX_BASKETS:\n while len(cnt) >= MAX_BASKETS:\n cnt[x := fruits[w_start]] -= 1\n\n if cnt[x] == 0:\n cnt.pop(x)\n\n w_start += 1\n\n # now that we have resolved any conflict for adding the\n # fruit "t", lets add it\n cnt[t] += 1\n output = max(output, w_end - w_start + 1)\n\n return output\n\n @staticmethod\n def ensure_later_that_fruit_can_be_added(fruits: list[int]) -> int:\n """\n @also see https://leetcode.com/problems/fruit-into-baskets/solutions/170737/python-sliding-window/\n :param fruits:\n :return:\n """\n cnt = Counter()\n output, w_start = 0, 0\n\n for w_end, t in enumerate(fruits):\n cnt[t] += 1\n\n # we added fruit "t", now update "cnt" to make sure, adding\n # fruit is feasible\n while len(cnt) > MAX_BASKETS:\n cnt[x := fruits[w_start]] -= 1\n\n if cnt[x] == 0:\n cnt.pop(x)\n\n w_start += 1\n\n output = max(output, w_end - w_start + 1)\n\n return output\n```
1
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
Python || Sliding Window Technique
fruit-into-baskets
0
1
```\nfrom collections import Counter\n\nMAX_BASKETS = 2\n\n\nclass Solution:\n def totalFruit(self, fruits: list[int]) -> int:\n # return self.ensure_first_that_fruit_can_be_added(fruits)\n return self.ensure_later_that_fruit_can_be_added(fruits)\n\n @staticmethod\n def ensure_first_that_fruit_can_be_added(fruits: list[int]) -> int:\n cnt = Counter()\n output, w_start = 0, 0\n\n for w_end, t in enumerate(fruits):\n if cnt[t] == 0 and len(cnt) == MAX_BASKETS:\n while len(cnt) >= MAX_BASKETS:\n cnt[x := fruits[w_start]] -= 1\n\n if cnt[x] == 0:\n cnt.pop(x)\n\n w_start += 1\n\n # now that we have resolved any conflict for adding the\n # fruit "t", lets add it\n cnt[t] += 1\n output = max(output, w_end - w_start + 1)\n\n return output\n\n @staticmethod\n def ensure_later_that_fruit_can_be_added(fruits: list[int]) -> int:\n """\n @also see https://leetcode.com/problems/fruit-into-baskets/solutions/170737/python-sliding-window/\n :param fruits:\n :return:\n """\n cnt = Counter()\n output, w_start = 0, 0\n\n for w_end, t in enumerate(fruits):\n cnt[t] += 1\n\n # we added fruit "t", now update "cnt" to make sure, adding\n # fruit is feasible\n while len(cnt) > MAX_BASKETS:\n cnt[x := fruits[w_start]] -= 1\n\n if cnt[x] == 0:\n cnt.pop(x)\n\n w_start += 1\n\n output = max(output, w_end - w_start + 1)\n\n return output\n```
1
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not. **Example 1:** **Input:** s = "abc " **Output:** 7 **Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ". **Example 2:** **Input:** s = "aba " **Output:** 6 **Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ". **Example 3:** **Input:** s = "aaa " **Output:** 3 **Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ". **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase English letters.
null
My Solution using Sliding Window
fruit-into-baskets
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSliding Window approach\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use Two Pointers left(i) and right(j)\n2. Keep adding the fruits[j] into the hashmap and keep checking if length of the map is > k(2) \n3. If map length > 2 : then keep deleting the fruits[i] till this condition no longer holds true\n4. In the end, check if map\'s length is <= k, if yes then calculate the fruit_count\n5. Return fruit_count.\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(N)\n# Code\n```\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n \n k = 2\n i = 0 \n j = 0\n fruit_count = 0\n map1 = {}\n\n while j < len(fruits):\n\n if fruits[j] not in map1:\n map1[fruits[j]] = 1\n else:\n map1[fruits[j]] += 1\n \n if len(map1) > k :\n while len(map1) > k:\n map1[fruits[i]] -= 1\n if map1[fruits[i]] == 0:\n del(map1[fruits[i]])\n i += 1\n \n if len(map1) <= k:\n fruit_count = max(fruit_count,j - i + 1)\n \n j += 1\n \n return fruit_count\n```
1
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
My Solution using Sliding Window
fruit-into-baskets
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSliding Window approach\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use Two Pointers left(i) and right(j)\n2. Keep adding the fruits[j] into the hashmap and keep checking if length of the map is > k(2) \n3. If map length > 2 : then keep deleting the fruits[i] till this condition no longer holds true\n4. In the end, check if map\'s length is <= k, if yes then calculate the fruit_count\n5. Return fruit_count.\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(N)\n# Code\n```\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n \n k = 2\n i = 0 \n j = 0\n fruit_count = 0\n map1 = {}\n\n while j < len(fruits):\n\n if fruits[j] not in map1:\n map1[fruits[j]] = 1\n else:\n map1[fruits[j]] += 1\n \n if len(map1) > k :\n while len(map1) > k:\n map1[fruits[i]] -= 1\n if map1[fruits[i]] == 0:\n del(map1[fruits[i]])\n i += 1\n \n if len(map1) <= k:\n fruit_count = max(fruit_count,j - i + 1)\n \n j += 1\n \n return fruit_count\n```
1
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not. **Example 1:** **Input:** s = "abc " **Output:** 7 **Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ". **Example 2:** **Input:** s = "aba " **Output:** 6 **Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ". **Example 3:** **Input:** s = "aaa " **Output:** 3 **Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ". **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase English letters.
null
Solution
fruit-into-baskets
1
1
```C++ []\nconst static auto fastio = [] {\n ios::sync_with_stdio(0);\n cin.tie(0);\n return 0;\n}();\nclass Solution {\npublic:\n int totalFruit(vector<int>& fruits)\n {\n if (fruits.empty())\n return 0;\n int maxSequence = 0;\n int firstType = -1, lastType = -1;\n int firstIndex = 0, lastIndex = 0;\n for (int i = 0; i < fruits.size(); ++i)\n {\n if (lastType != fruits[i])\n {\n if (firstType == fruits[i])\n {\n std::swap(firstType, lastType);\n }\n else\n {\n maxSequence = std::max(maxSequence, i - firstIndex);\n firstType = lastType;\n lastType = fruits[i];\n firstIndex = lastIndex;\n }\n lastIndex = i;\n }\n }\n return std::max(maxSequence, (int)fruits.size() - firstIndex);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n n = len(fruits)\n curr_type = fruits[0]\n curr_index = 0\n other_type = None\n strike = 1\n result = 0\n\n for i in range(1, n):\n new_type = fruits[i]\n if new_type == curr_type:\n strike += 1\n elif new_type == other_type:\n strike += 1\n curr_type, other_type = other_type, curr_type\n curr_index = i\n else:\n result = max(result, strike)\n strike = i - curr_index + 1\n curr_index = i\n curr_type, other_type = new_type, curr_type\n \n result = max(result, strike)\n return result\n```\n\n```Java []\nclass Solution {\n public int totalFruit(int[] tree) {\n int max = 0;\n int curMax = 0;\n int prev = -1;\n int prev2 = -1;\n int prevCount = 0;\n\n for (int fruit: tree) {\n if (fruit == prev || fruit == prev2) {\n curMax++;\n } else {\n max = Math.max(max, curMax);\n curMax = prevCount + 1;\n }\n if (fruit == prev) {\n prevCount++;\n } else {\n prevCount = 1;\n prev2 = prev;\n prev = fruit;\n }\n }\n return Math.max(max, curMax);\n }\n}\n```\n
1
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
Solution
fruit-into-baskets
1
1
```C++ []\nconst static auto fastio = [] {\n ios::sync_with_stdio(0);\n cin.tie(0);\n return 0;\n}();\nclass Solution {\npublic:\n int totalFruit(vector<int>& fruits)\n {\n if (fruits.empty())\n return 0;\n int maxSequence = 0;\n int firstType = -1, lastType = -1;\n int firstIndex = 0, lastIndex = 0;\n for (int i = 0; i < fruits.size(); ++i)\n {\n if (lastType != fruits[i])\n {\n if (firstType == fruits[i])\n {\n std::swap(firstType, lastType);\n }\n else\n {\n maxSequence = std::max(maxSequence, i - firstIndex);\n firstType = lastType;\n lastType = fruits[i];\n firstIndex = lastIndex;\n }\n lastIndex = i;\n }\n }\n return std::max(maxSequence, (int)fruits.size() - firstIndex);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n n = len(fruits)\n curr_type = fruits[0]\n curr_index = 0\n other_type = None\n strike = 1\n result = 0\n\n for i in range(1, n):\n new_type = fruits[i]\n if new_type == curr_type:\n strike += 1\n elif new_type == other_type:\n strike += 1\n curr_type, other_type = other_type, curr_type\n curr_index = i\n else:\n result = max(result, strike)\n strike = i - curr_index + 1\n curr_index = i\n curr_type, other_type = new_type, curr_type\n \n result = max(result, strike)\n return result\n```\n\n```Java []\nclass Solution {\n public int totalFruit(int[] tree) {\n int max = 0;\n int curMax = 0;\n int prev = -1;\n int prev2 = -1;\n int prevCount = 0;\n\n for (int fruit: tree) {\n if (fruit == prev || fruit == prev2) {\n curMax++;\n } else {\n max = Math.max(max, curMax);\n curMax = prevCount + 1;\n }\n if (fruit == prev) {\n prevCount++;\n } else {\n prevCount = 1;\n prev2 = prev;\n prev = fruit;\n }\n }\n return Math.max(max, curMax);\n }\n}\n```\n
1
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not. **Example 1:** **Input:** s = "abc " **Output:** 7 **Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ". **Example 2:** **Input:** s = "aba " **Output:** 6 **Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ". **Example 3:** **Input:** s = "aaa " **Output:** 3 **Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ". **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase English letters.
null
Python solution faster than 97%
fruit-into-baskets
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing a dictionary to store the begining and end index of the fruits stored in the bucket.\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 totalFruit(self, fruits: List[int]) -> int:\n\n fruit_map = collections.defaultdict(list)\n fruit_map[fruits[0]] = [0,0]\n current = 0\n max_length = 1\n\n for idx, fruit in enumerate(fruits[1:], start = 1):\n if (fruit in fruit_map):\n fruit_map[fruit][1] = idx\n elif len(fruit_map) < 2:\n fruit_map[fruit] = [idx, idx]\n else:\n to_remove = min(fruit_map.keys(), key = lambda x: fruit_map[x][1])\n # print(idx, current, fruit, max_length, fruit_map, to_remove)\n max_length = max(max_length, idx - current)\n current = fruit_map[to_remove][1] + 1\n # print(\'after:\', current)\n del fruit_map[to_remove]\n fruit_map[fruit] = [idx, idx]\n\n \n return max(max_length, len(fruits) - current)\n\n\n \n \n\n\n```
1
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
Python solution faster than 97%
fruit-into-baskets
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing a dictionary to store the begining and end index of the fruits stored in the bucket.\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 totalFruit(self, fruits: List[int]) -> int:\n\n fruit_map = collections.defaultdict(list)\n fruit_map[fruits[0]] = [0,0]\n current = 0\n max_length = 1\n\n for idx, fruit in enumerate(fruits[1:], start = 1):\n if (fruit in fruit_map):\n fruit_map[fruit][1] = idx\n elif len(fruit_map) < 2:\n fruit_map[fruit] = [idx, idx]\n else:\n to_remove = min(fruit_map.keys(), key = lambda x: fruit_map[x][1])\n # print(idx, current, fruit, max_length, fruit_map, to_remove)\n max_length = max(max_length, idx - current)\n current = fruit_map[to_remove][1] + 1\n # print(\'after:\', current)\n del fruit_map[to_remove]\n fruit_map[fruit] = [idx, idx]\n\n \n return max(max_length, len(fruits) - current)\n\n\n \n \n\n\n```
1
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not. **Example 1:** **Input:** s = "abc " **Output:** 7 **Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ". **Example 2:** **Input:** s = "aba " **Output:** 6 **Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ". **Example 3:** **Input:** s = "aaa " **Output:** 3 **Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ". **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase English letters.
null
Fastest solution Python
fruit-into-baskets
0
1
# Intuition\nImagine you are standing near the tree `i`. You have to choose between two options:\n 1. Add `fruits[i]` to one of your busket which has the same type of fruits\n 2. Empty one of your busket and put there `fruits[i]`\n\nThink about the information you need to know about the trees `[0, i - 1]` in order to perform one of those possible actions. You need to know the position of the tree where you picked your first fruit in the busket and the position of the tree where you started picking your the fruits of the second type.\n\n# Complexity\n- Time complexity:\n$$O(n)$$ since we go through array only once.\n\n- Space complexity:\n$$O(1)$$ since we don\'t use any externally created arrays, only a few additional integer variables.\n\n# Code\n```\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n i, j = 0, 0\n n = len(fruits)\n while j < n and fruits[i] == fruits[j]:\n j += 1\n if j == n:\n return n\n\n l, r = i, j + 1\n answ = 0\n while r < n:\n if fruits[r] != fruits[j]:\n if fruits[r] == fruits[i]:\n i = j\n j = r\n else:\n answ = max(answ, r - l)\n i = j\n l = j\n j = r\n r += 1\n answ = max(answ, r - l)\n return answ\n```
1
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
Fastest solution Python
fruit-into-baskets
0
1
# Intuition\nImagine you are standing near the tree `i`. You have to choose between two options:\n 1. Add `fruits[i]` to one of your busket which has the same type of fruits\n 2. Empty one of your busket and put there `fruits[i]`\n\nThink about the information you need to know about the trees `[0, i - 1]` in order to perform one of those possible actions. You need to know the position of the tree where you picked your first fruit in the busket and the position of the tree where you started picking your the fruits of the second type.\n\n# Complexity\n- Time complexity:\n$$O(n)$$ since we go through array only once.\n\n- Space complexity:\n$$O(1)$$ since we don\'t use any externally created arrays, only a few additional integer variables.\n\n# Code\n```\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n i, j = 0, 0\n n = len(fruits)\n while j < n and fruits[i] == fruits[j]:\n j += 1\n if j == n:\n return n\n\n l, r = i, j + 1\n answ = 0\n while r < n:\n if fruits[r] != fruits[j]:\n if fruits[r] == fruits[i]:\n i = j\n j = r\n else:\n answ = max(answ, r - l)\n i = j\n l = j\n j = r\n r += 1\n answ = max(answ, r - l)\n return answ\n```
1
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not. **Example 1:** **Input:** s = "abc " **Output:** 7 **Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ". **Example 2:** **Input:** s = "aba " **Output:** 6 **Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ". **Example 3:** **Input:** s = "aaa " **Output:** 3 **Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ". **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase English letters.
null
Sliding window approach , beats 82.41%
fruit-into-baskets
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the question was asking about longest sub array kind of thing so i have selected this approach.Please leave any suggestion if you have any idea to optimize this code. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBasically we are maintaining the dictionary of len(2) with its indices as its value. If the same value is passed again in the dictionary which is already present then it updates the index. And in else if a new element is found we are here comparing whether to insert the element at the begining of the stack or last here are the two test cases which will help you understand better whether to insert the element at the begining or last of the stack we are maintaining [1,0,3,4,3] and [1,1,6,5,6,6,1,1,1,1]\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(k), where k is the maximum number of unique fruits\n# Code\n```\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n ans=0\n fruitdict=defaultdict()\n stack=[]\n i,j=0,0\n\n while j<len(fruits):\n if fruits[j] not in fruitdict and len(fruitdict)<2:\n stack.append(fruits[j])\n fruitdict[fruits[j]]=j\n j+=1\n\n elif fruits[j] in fruitdict:\n fruitdict[fruits[j]]=j\n j+=1\n\n else: \n if fruitdict[stack[0]]>fruitdict[stack[1]] :\n i = fruitdict[stack[1]]+1\n del fruitdict[stack[1]]\n stack.pop()\n else:\n i = fruitdict[stack[0]]+1\n del fruitdict[stack[0]] \n stack.pop(0) \n \n ans=max(ans,j-i)\n return ans\n```
1
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
Sliding window approach , beats 82.41%
fruit-into-baskets
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince the question was asking about longest sub array kind of thing so i have selected this approach.Please leave any suggestion if you have any idea to optimize this code. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBasically we are maintaining the dictionary of len(2) with its indices as its value. If the same value is passed again in the dictionary which is already present then it updates the index. And in else if a new element is found we are here comparing whether to insert the element at the begining of the stack or last here are the two test cases which will help you understand better whether to insert the element at the begining or last of the stack we are maintaining [1,0,3,4,3] and [1,1,6,5,6,6,1,1,1,1]\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(k), where k is the maximum number of unique fruits\n# Code\n```\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n ans=0\n fruitdict=defaultdict()\n stack=[]\n i,j=0,0\n\n while j<len(fruits):\n if fruits[j] not in fruitdict and len(fruitdict)<2:\n stack.append(fruits[j])\n fruitdict[fruits[j]]=j\n j+=1\n\n elif fruits[j] in fruitdict:\n fruitdict[fruits[j]]=j\n j+=1\n\n else: \n if fruitdict[stack[0]]>fruitdict[stack[1]] :\n i = fruitdict[stack[1]]+1\n del fruitdict[stack[1]]\n stack.pop()\n else:\n i = fruitdict[stack[0]]+1\n del fruitdict[stack[0]] \n stack.pop(0) \n \n ans=max(ans,j-i)\n return ans\n```
1
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not. **Example 1:** **Input:** s = "abc " **Output:** 7 **Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ". **Example 2:** **Input:** s = "aba " **Output:** 6 **Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ". **Example 3:** **Input:** s = "aaa " **Output:** 3 **Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ". **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase English letters.
null
|| 🐍 Python3 O(n) Easiest ✔ Solution 🔥 || Beats 97% (Runtime) & 80% (Memory) ||
fruit-into-baskets
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a dictionary where the fruits will be stored as keys and their count as values.\n2. A start variable is initialized pointing to first tree i.e. 0th index.\n3. Iterating through the fruits list, we update the count in the dictionary.\n4. If at any point, there are more than two types of fruits in the basket i.e. length of basket gets more than two, then we decrement the count in basket for the fruit present on the start.\n5. If the count of fruit present on start becomes zero after decrementing then it has to be deleted from the dictionary. And the start will be incremented.\n6. After all the iterations have finished the start variable will be at the index from where the fruits are to picked till the end. So, we will return the difference of length of fruits and the start.\n\n# Complexity\n- Time complexity : $O(n)$\n\n- Space complexity : $O(k)$ (where $k$ is number of fruits picked)\n\n# Code\n```python []\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n basket= {}\n start= 0\n for fruit in fruits:\n basket[fruit]= basket.get(fruit, 0)+ 1\n\n if len(basket)> 2:\n basket[fruits[start]]-= 1\n if basket[fruits[start]]== 0:\n del basket[fruits[start]]\n start+= 1\n return len(fruits)- start\n```\n---\n\n### Happy Coding \uD83D\uDC68\u200D\uD83D\uDCBB\n\n---\n\n### If this solution helped you then do consider Upvoting \u2B06.\n#### Also, you can check me out on LinkedIn : [Om Anand](https://www.linkedin.com/in/om-anand-38341a1ba/)
1
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array `fruits` where `fruits[i]` is the **type** of fruit the `ith` tree produces. You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow: * You only have **two** baskets, and each basket can only hold a **single type** of fruit. There is no limit on the amount of fruit each basket can hold. * Starting from any tree of your choice, you must pick **exactly one fruit** from **every** tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. * Once you reach a tree with fruit that cannot fit in your baskets, you must stop. Given the integer array `fruits`, return _the **maximum** number of fruits you can pick_. **Example 1:** **Input:** fruits = \[1,2,1\] **Output:** 3 **Explanation:** We can pick from all 3 trees. **Example 2:** **Input:** fruits = \[0,1,2,2\] **Output:** 3 **Explanation:** We can pick from trees \[1,2,2\]. If we had started at the first tree, we would only pick from trees \[0,1\]. **Example 3:** **Input:** fruits = \[1,2,3,2,2\] **Output:** 4 **Explanation:** We can pick from trees \[2,3,2,2\]. If we had started at the first tree, we would only pick from trees \[1,2\]. **Constraints:** * `1 <= fruits.length <= 105` * `0 <= fruits[i] < fruits.length`
null
|| 🐍 Python3 O(n) Easiest ✔ Solution 🔥 || Beats 97% (Runtime) & 80% (Memory) ||
fruit-into-baskets
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Create a dictionary where the fruits will be stored as keys and their count as values.\n2. A start variable is initialized pointing to first tree i.e. 0th index.\n3. Iterating through the fruits list, we update the count in the dictionary.\n4. If at any point, there are more than two types of fruits in the basket i.e. length of basket gets more than two, then we decrement the count in basket for the fruit present on the start.\n5. If the count of fruit present on start becomes zero after decrementing then it has to be deleted from the dictionary. And the start will be incremented.\n6. After all the iterations have finished the start variable will be at the index from where the fruits are to picked till the end. So, we will return the difference of length of fruits and the start.\n\n# Complexity\n- Time complexity : $O(n)$\n\n- Space complexity : $O(k)$ (where $k$ is number of fruits picked)\n\n# Code\n```python []\nclass Solution:\n def totalFruit(self, fruits: List[int]) -> int:\n basket= {}\n start= 0\n for fruit in fruits:\n basket[fruit]= basket.get(fruit, 0)+ 1\n\n if len(basket)> 2:\n basket[fruits[start]]-= 1\n if basket[fruits[start]]== 0:\n del basket[fruits[start]]\n start+= 1\n return len(fruits)- start\n```\n---\n\n### Happy Coding \uD83D\uDC68\u200D\uD83D\uDCBB\n\n---\n\n### If this solution helped you then do consider Upvoting \u2B06.\n#### Also, you can check me out on LinkedIn : [Om Anand](https://www.linkedin.com/in/om-anand-38341a1ba/)
1
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not. **Example 1:** **Input:** s = "abc " **Output:** 7 **Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ". **Example 2:** **Input:** s = "aba " **Output:** 6 **Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ". **Example 3:** **Input:** s = "aaa " **Output:** 3 **Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ". **Constraints:** * `1 <= s.length <= 2000` * `s` consists of lowercase English letters.
null
Python3 Solution
sort-array-by-parity
0
1
\n```\nclass Solution:\n def sortArrayByParity(self, nums: List[int]) -> List[int]:\n return sorted(nums,key=lambda x:x%2)\n \n```
2
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. Return _**any array** that satisfies this condition_. **Example 1:** **Input:** nums = \[3,1,2,4\] **Output:** \[2,4,3,1\] **Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted. **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 5000` * `0 <= nums[i] <= 5000`
null
Python3 Solution
sort-array-by-parity
0
1
\n```\nclass Solution:\n def sortArrayByParity(self, nums: List[int]) -> List[int]:\n return sorted(nums,key=lambda x:x%2)\n \n```
2
Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_. Recall that arr is a mountain array if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` **Example 1:** **Input:** arr = \[2,1\] **Output:** false **Example 2:** **Input:** arr = \[3,5,5\] **Output:** false **Example 3:** **Input:** arr = \[0,3,2,1\] **Output:** true **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 104`
null
Solution of sort array by parity problem
sort-array-by-parity
0
1
# Approach\nSolved using two-pointer algorithm\n- Step one: create two_pointers: `left` and `right`\n- Step two: create new list called `answer` \n- Step three: if number is even: `answer[left] = i` and `left += 1`\n- Step four: if number is odd: `answer[right] = i` and `right -= 1`\n- Step five: \u0441ontinue this process until we have completed the entire cycle.\n\n# Complexity\n- Time complexity:\n$$O(n)$$ - as two-pointer algorithm takes linear time \n- Space complexity:\n$$O(n)$$ - as we use extra space for list called `answer`\n\n# Code\n```\nclass Solution:\n def sortArrayByParity(self, nums: List[int]) -> List[int]:\n left, right = 0, len(nums) - 1\n answer = [0] * len(nums)\n for i in nums:\n if i % 2 == 0:\n answer[left] = i\n left += 1\n else:\n answer[right] = i\n right -= 1\n return answer\n```
1
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. Return _**any array** that satisfies this condition_. **Example 1:** **Input:** nums = \[3,1,2,4\] **Output:** \[2,4,3,1\] **Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted. **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 5000` * `0 <= nums[i] <= 5000`
null
Solution of sort array by parity problem
sort-array-by-parity
0
1
# Approach\nSolved using two-pointer algorithm\n- Step one: create two_pointers: `left` and `right`\n- Step two: create new list called `answer` \n- Step three: if number is even: `answer[left] = i` and `left += 1`\n- Step four: if number is odd: `answer[right] = i` and `right -= 1`\n- Step five: \u0441ontinue this process until we have completed the entire cycle.\n\n# Complexity\n- Time complexity:\n$$O(n)$$ - as two-pointer algorithm takes linear time \n- Space complexity:\n$$O(n)$$ - as we use extra space for list called `answer`\n\n# Code\n```\nclass Solution:\n def sortArrayByParity(self, nums: List[int]) -> List[int]:\n left, right = 0, len(nums) - 1\n answer = [0] * len(nums)\n for i in nums:\n if i % 2 == 0:\n answer[left] = i\n left += 1\n else:\n answer[right] = i\n right -= 1\n return answer\n```
1
Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_. Recall that arr is a mountain array if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` **Example 1:** **Input:** arr = \[2,1\] **Output:** false **Example 2:** **Input:** arr = \[3,5,5\] **Output:** false **Example 3:** **Input:** arr = \[0,3,2,1\] **Output:** true **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 104`
null
5 lines || beats 94.30% time complexity ||beats 96.40 % space complexity || simple explanation 💡
sort-array-by-parity
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasic Array traversal is used.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nConsider two arrays as even and odd.Then traverse the array and if the `nums[i]` is even then append it to even array, else append it to odd array.\nThen finally return the combined array as even then odd integers.\n\n# Complexity\n- Time complexity:$$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(2*(N/2)) ==> O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sortArrayByParity(self, nums: List[int]) -> List[int]:\n e = [];o = []\n for i in range(len(nums)):\n if nums[i]%2 == 0:e.append(nums[i])\n else:o.append(nums[i])\n return e+o\n```
1
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. Return _**any array** that satisfies this condition_. **Example 1:** **Input:** nums = \[3,1,2,4\] **Output:** \[2,4,3,1\] **Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted. **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 5000` * `0 <= nums[i] <= 5000`
null
5 lines || beats 94.30% time complexity ||beats 96.40 % space complexity || simple explanation 💡
sort-array-by-parity
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasic Array traversal is used.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nConsider two arrays as even and odd.Then traverse the array and if the `nums[i]` is even then append it to even array, else append it to odd array.\nThen finally return the combined array as even then odd integers.\n\n# Complexity\n- Time complexity:$$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(2*(N/2)) ==> O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sortArrayByParity(self, nums: List[int]) -> List[int]:\n e = [];o = []\n for i in range(len(nums)):\n if nums[i]%2 == 0:e.append(nums[i])\n else:o.append(nums[i])\n return e+o\n```
1
Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_. Recall that arr is a mountain array if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` **Example 1:** **Input:** arr = \[2,1\] **Output:** false **Example 2:** **Input:** arr = \[3,5,5\] **Output:** false **Example 3:** **Input:** arr = \[0,3,2,1\] **Output:** true **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 104`
null
Solution
super-palindromes
1
1
```C++ []\nclass Solution {\npublic:\n int superpalindromesInRange(string left, string right) {\n int ans = 9 >= stol(left) && 9 <= stol(right) ? 1 : 0;\n for (int dig = 1; dig < 10; dig++) {\n bool isOdd = dig % 2 && dig != 1;\n int innerLen = (dig >> 1) - 1,\n innerLim = max(1, (int)pow(2, innerLen)),\n midPos = dig >> 1, midLim = isOdd ? 3 : 1;\n for (int edge = 1; edge < 3; edge++) {\n string pal(dig, \'0\');\n pal[0] = (char)(edge + 48);\n pal[dig-1] = (char)(edge + 48);\n if (edge == 2) innerLim = 1, midLim = min(midLim, 2);\n for (int inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n string innerStr = bitset<3>(inner).to_string();\n innerStr = innerStr.substr(3 - innerLen);\n for (int i = 0; i < innerLen; i++) {\n pal[1+i] = innerStr[i];\n pal[dig-2-i] = innerStr[i];\n }\n }\n for (int mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = (char)(mid + 48);\n long square = stol(pal) * stol(pal);\n if (square > stol(right)) return ans;\n if (square >= stol(left) && isPal(to_string(square))) ans++;\n }\n }\n }\n }\n return ans;\n }\n bool isPal(string str) {\n for (int i = 0, j = str.length() - 1; i < j; i++, j--)\n if (str[i] != str[j]) return false;\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n ans = 1 if 9 >= int(left) and 9 <= int(right) else 0\n \n def isPal(s: str) -> bool:\n return s == s[::-1]\n \n for dig in range(1, 10):\n isOdd = dig % 2 and dig != 1\n innerLen = (dig >> 1) - 1\n innerLim = max(1, 2 ** innerLen)\n midPos = dig >> 1\n midLim = 3 if isOdd else 1\n for edge in range (1, 3):\n pal = [0] * dig\n pal[0], pal[-1] = edge, edge\n if edge == 2: innerLim, midLim = 1, min(midLim, 2)\n for inner in range(innerLim):\n if inner > 0:\n innerStr = list(bin(inner)[2:].zfill(innerLen))\n pal[1:1+innerLen] = innerStr\n pal[-innerLen-1:-1] = reversed(innerStr)\n for mid in range(midLim):\n if isOdd: pal[midPos] = mid\n palin = int("".join([str(n) for n in pal]))\n square = palin * palin\n if square > int(right): return ans\n if square >= int(left) and isPal(str(square)): ans += 1\n return ans\n```\n\n```Java []\nclass Solution {\n public int superpalindromesInRange(String left, String right) {\n int ans = 9 >= Long.parseLong(left) && 9 <= Long.parseLong(right) ? 1 : 0;\n for (int dig = 1; dig < 10; dig++) {\n boolean isOdd = dig % 2 > 0 && dig != 1;\n int innerLen = (dig >> 1) - 1,\n innerLim = Math.max(1, (int)Math.pow(2, innerLen)),\n midPos = dig >> 1, midLim = isOdd ? 3 : 1;\n for (int edge = 1; edge < 3; edge++) {\n char[] pal = new char[dig];\n Arrays.fill(pal, \'0\');\n pal[0] = (char)(edge + 48);\n pal[dig-1] = (char)(edge + 48);\n if (edge == 2) {\n innerLim = 1;\n midLim = Math.min(midLim, 2);\n }\n for (int inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n String innerStr = Integer.toString(inner, 2);\n while (innerStr.length() < innerLen)\n innerStr = "0" + innerStr;\n for (int i = 0; i < innerLen; i++) {\n pal[1+i] = innerStr.charAt(i);\n pal[dig-2-i] = innerStr.charAt(i);\n }\n }\n for (int mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = (char)(mid + 48);\n String palin = new String(pal);\n long square = Long.parseLong(palin) * Long.parseLong(palin);\n if (square > Long.parseLong(right)) return ans;\n if (square >= Long.parseLong(left) && isPal(Long.toString(square))) ans++;\n }\n }\n }\n }\n return ans;\n }\n private boolean isPal(String str) {\n for (int i = 0, j = str.length() - 1; i < j; i++, j--)\n if (str.charAt(i) != str.charAt(j)) return false;\n return true;\n }\n}\n```\n
1
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. **Example 1:** **Input:** left = "4 ", right = "1000 " **Output:** 4 **Explanation**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. **Example 2:** **Input:** left = "1 ", right = "2 " **Output:** 1 **Constraints:** * `1 <= left.length, right.length <= 18` * `left` and `right` consist of only digits. * `left` and `right` cannot have leading zeros. * `left` and `right` represent integers in the range `[1, 1018 - 1]`. * `left` is less than or equal to `right`.
null
Solution
super-palindromes
1
1
```C++ []\nclass Solution {\npublic:\n int superpalindromesInRange(string left, string right) {\n int ans = 9 >= stol(left) && 9 <= stol(right) ? 1 : 0;\n for (int dig = 1; dig < 10; dig++) {\n bool isOdd = dig % 2 && dig != 1;\n int innerLen = (dig >> 1) - 1,\n innerLim = max(1, (int)pow(2, innerLen)),\n midPos = dig >> 1, midLim = isOdd ? 3 : 1;\n for (int edge = 1; edge < 3; edge++) {\n string pal(dig, \'0\');\n pal[0] = (char)(edge + 48);\n pal[dig-1] = (char)(edge + 48);\n if (edge == 2) innerLim = 1, midLim = min(midLim, 2);\n for (int inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n string innerStr = bitset<3>(inner).to_string();\n innerStr = innerStr.substr(3 - innerLen);\n for (int i = 0; i < innerLen; i++) {\n pal[1+i] = innerStr[i];\n pal[dig-2-i] = innerStr[i];\n }\n }\n for (int mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = (char)(mid + 48);\n long square = stol(pal) * stol(pal);\n if (square > stol(right)) return ans;\n if (square >= stol(left) && isPal(to_string(square))) ans++;\n }\n }\n }\n }\n return ans;\n }\n bool isPal(string str) {\n for (int i = 0, j = str.length() - 1; i < j; i++, j--)\n if (str[i] != str[j]) return false;\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n ans = 1 if 9 >= int(left) and 9 <= int(right) else 0\n \n def isPal(s: str) -> bool:\n return s == s[::-1]\n \n for dig in range(1, 10):\n isOdd = dig % 2 and dig != 1\n innerLen = (dig >> 1) - 1\n innerLim = max(1, 2 ** innerLen)\n midPos = dig >> 1\n midLim = 3 if isOdd else 1\n for edge in range (1, 3):\n pal = [0] * dig\n pal[0], pal[-1] = edge, edge\n if edge == 2: innerLim, midLim = 1, min(midLim, 2)\n for inner in range(innerLim):\n if inner > 0:\n innerStr = list(bin(inner)[2:].zfill(innerLen))\n pal[1:1+innerLen] = innerStr\n pal[-innerLen-1:-1] = reversed(innerStr)\n for mid in range(midLim):\n if isOdd: pal[midPos] = mid\n palin = int("".join([str(n) for n in pal]))\n square = palin * palin\n if square > int(right): return ans\n if square >= int(left) and isPal(str(square)): ans += 1\n return ans\n```\n\n```Java []\nclass Solution {\n public int superpalindromesInRange(String left, String right) {\n int ans = 9 >= Long.parseLong(left) && 9 <= Long.parseLong(right) ? 1 : 0;\n for (int dig = 1; dig < 10; dig++) {\n boolean isOdd = dig % 2 > 0 && dig != 1;\n int innerLen = (dig >> 1) - 1,\n innerLim = Math.max(1, (int)Math.pow(2, innerLen)),\n midPos = dig >> 1, midLim = isOdd ? 3 : 1;\n for (int edge = 1; edge < 3; edge++) {\n char[] pal = new char[dig];\n Arrays.fill(pal, \'0\');\n pal[0] = (char)(edge + 48);\n pal[dig-1] = (char)(edge + 48);\n if (edge == 2) {\n innerLim = 1;\n midLim = Math.min(midLim, 2);\n }\n for (int inner = 0; inner < innerLim; inner++) {\n if (inner > 0) {\n String innerStr = Integer.toString(inner, 2);\n while (innerStr.length() < innerLen)\n innerStr = "0" + innerStr;\n for (int i = 0; i < innerLen; i++) {\n pal[1+i] = innerStr.charAt(i);\n pal[dig-2-i] = innerStr.charAt(i);\n }\n }\n for (int mid = 0; mid < midLim; mid++) {\n if (isOdd) pal[midPos] = (char)(mid + 48);\n String palin = new String(pal);\n long square = Long.parseLong(palin) * Long.parseLong(palin);\n if (square > Long.parseLong(right)) return ans;\n if (square >= Long.parseLong(left) && isPal(Long.toString(square))) ans++;\n }\n }\n }\n }\n return ans;\n }\n private boolean isPal(String str) {\n for (int i = 0, j = str.length() - 1; i < j; i++, j--)\n if (str.charAt(i) != str.charAt(j)) return false;\n return true;\n }\n}\n```\n
1
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
Efficient in terms of number of iterations for a very large range
super-palindromes
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. -->\n1. Generate Base palindromes -\n- Iterate over a range of numbers, considering both odd and even lengths. This is done by createing a palindrome from each number by appending it\'s reverse (excluding or including the last digit for odd or even lengths, respectively)\n- The upper bound for this iteration is set based on the square root of the right limit. Since we are interested in the squares of these palindromes, we only need to consider base palindromes up to the square root of the maximum value in the range.\n2. Check for super-palindromes - \n- For each generated palindrome, calculate it\'s square.\n- Check if this square falls within the given range ([left, right])\n- If it does, check if the square is also a palindrome.\n- Count each such number that satisfies these conditions.\n\n# Complexity\n- Time complexity:\n$$O(N*sqrt(N))$$ where N is the number of iterations, which depends on the square root of the right limit.\n\n- Space complexity:\n$$O(N)$$\n\n# Code\n```\nclass Solution:\n def is_palindrome(self, n):\n """\n Check if the given number is a palindrome.\n """\n return str(n) == str(n)[::-1]\n\n def superpalindromesInRange(self, left: str, right: str) -> int:\n left, right = int(left), int(right)\n count = 0\n\n # Generate base palindromes up to 10^5 (since the square root of 10^18 is 10^9, and we generate half)\n for root_len in range(1, 10):\n # Generate half of the palindrome and mirror it to create the full palindrome\n # Start from 1 to avoid leading zeros\n for half_palindrome in range(10**(root_len - 1), 10**root_len):\n # Odd length palindrome\n s = str(half_palindrome)\n odd_palindrome = int(s + s[-2::-1]) # Create palindrome\n square = odd_palindrome ** 2\n if square > right:\n break\n if square >= left and self.is_palindrome(square):\n count += 1\n\n # Even length palindrome\n even_palindrome = int(s + s[::-1]) # Create palindrome\n square = even_palindrome ** 2\n if square > right:\n continue # Changed from \'break\' to \'continue\' to check smaller even palindromes\n if square >= left and self.is_palindrome(square):\n count += 1\n\n return count\n\n```
0
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. **Example 1:** **Input:** left = "4 ", right = "1000 " **Output:** 4 **Explanation**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. **Example 2:** **Input:** left = "1 ", right = "2 " **Output:** 1 **Constraints:** * `1 <= left.length, right.length <= 18` * `left` and `right` consist of only digits. * `left` and `right` cannot have leading zeros. * `left` and `right` represent integers in the range `[1, 1018 - 1]`. * `left` is less than or equal to `right`.
null
Efficient in terms of number of iterations for a very large range
super-palindromes
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. -->\n1. Generate Base palindromes -\n- Iterate over a range of numbers, considering both odd and even lengths. This is done by createing a palindrome from each number by appending it\'s reverse (excluding or including the last digit for odd or even lengths, respectively)\n- The upper bound for this iteration is set based on the square root of the right limit. Since we are interested in the squares of these palindromes, we only need to consider base palindromes up to the square root of the maximum value in the range.\n2. Check for super-palindromes - \n- For each generated palindrome, calculate it\'s square.\n- Check if this square falls within the given range ([left, right])\n- If it does, check if the square is also a palindrome.\n- Count each such number that satisfies these conditions.\n\n# Complexity\n- Time complexity:\n$$O(N*sqrt(N))$$ where N is the number of iterations, which depends on the square root of the right limit.\n\n- Space complexity:\n$$O(N)$$\n\n# Code\n```\nclass Solution:\n def is_palindrome(self, n):\n """\n Check if the given number is a palindrome.\n """\n return str(n) == str(n)[::-1]\n\n def superpalindromesInRange(self, left: str, right: str) -> int:\n left, right = int(left), int(right)\n count = 0\n\n # Generate base palindromes up to 10^5 (since the square root of 10^18 is 10^9, and we generate half)\n for root_len in range(1, 10):\n # Generate half of the palindrome and mirror it to create the full palindrome\n # Start from 1 to avoid leading zeros\n for half_palindrome in range(10**(root_len - 1), 10**root_len):\n # Odd length palindrome\n s = str(half_palindrome)\n odd_palindrome = int(s + s[-2::-1]) # Create palindrome\n square = odd_palindrome ** 2\n if square > right:\n break\n if square >= left and self.is_palindrome(square):\n count += 1\n\n # Even length palindrome\n even_palindrome = int(s + s[::-1]) # Create palindrome\n square = even_palindrome ** 2\n if square > right:\n continue # Changed from \'break\' to \'continue\' to check smaller even palindromes\n if square >= left and self.is_palindrome(square):\n count += 1\n\n return count\n\n```
0
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
easyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
super-palindromes
0
1
# Very easyyyyyyyy\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# kindly upvote\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 superpalindromesInRange(self, left: str, right: str) -> int:\n\n count=0\n for i in range(int(right)):\n a=str(i)\n b=a+a[-2::-1]\n b=int(b)**2\n if b>int(right):\n break\n if b>=int(left) and str(b)==str(b)[::-1]:\n count+=1\n for i in range(int(right)):\n a=str(i)\n b=a+a[::-1]\n b=int(b)**2\n if b>int(right):\n break\n if b>=int(left) and str(b)==str(b)[::-1]:\n count+=1\n return(count)\n```
0
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. **Example 1:** **Input:** left = "4 ", right = "1000 " **Output:** 4 **Explanation**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. **Example 2:** **Input:** left = "1 ", right = "2 " **Output:** 1 **Constraints:** * `1 <= left.length, right.length <= 18` * `left` and `right` consist of only digits. * `left` and `right` cannot have leading zeros. * `left` and `right` represent integers in the range `[1, 1018 - 1]`. * `left` is less than or equal to `right`.
null
easyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
super-palindromes
0
1
# Very easyyyyyyyy\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# kindly upvote\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 superpalindromesInRange(self, left: str, right: str) -> int:\n\n count=0\n for i in range(int(right)):\n a=str(i)\n b=a+a[-2::-1]\n b=int(b)**2\n if b>int(right):\n break\n if b>=int(left) and str(b)==str(b)[::-1]:\n count+=1\n for i in range(int(right)):\n a=str(i)\n b=a+a[::-1]\n b=int(b)**2\n if b>int(right):\n break\n if b>=int(left) and str(b)==str(b)[::-1]:\n count+=1\n return(count)\n```
0
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
Python (Simple Maths)
super-palindromes
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 superpalindromesInRange(self, left, right):\n left, right, limit, total = int(left), int(right), 10**5, 0\n\n def is_pal(num):\n return str(num) == str(num)[::-1]\n\n for i in range(1,limit):\n s = str(i)\n s = s + s[::-1]\n p = int(s)**2\n\n if p > right:\n break\n\n if p >= left and is_pal(p):\n total += 1\n\n\n for i in range(1,limit):\n s = str(i)\n s = s + s[::-1][1:]\n p = int(s)**2\n\n if p > right:\n break\n\n if p >= left and is_pal(p):\n total += 1\n\n return total\n\n\n \n\n\n\n\n\n \n\n\n\n \n```
0
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. **Example 1:** **Input:** left = "4 ", right = "1000 " **Output:** 4 **Explanation**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. **Example 2:** **Input:** left = "1 ", right = "2 " **Output:** 1 **Constraints:** * `1 <= left.length, right.length <= 18` * `left` and `right` consist of only digits. * `left` and `right` cannot have leading zeros. * `left` and `right` represent integers in the range `[1, 1018 - 1]`. * `left` is less than or equal to `right`.
null
Python (Simple Maths)
super-palindromes
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 superpalindromesInRange(self, left, right):\n left, right, limit, total = int(left), int(right), 10**5, 0\n\n def is_pal(num):\n return str(num) == str(num)[::-1]\n\n for i in range(1,limit):\n s = str(i)\n s = s + s[::-1]\n p = int(s)**2\n\n if p > right:\n break\n\n if p >= left and is_pal(p):\n total += 1\n\n\n for i in range(1,limit):\n s = str(i)\n s = s + s[::-1][1:]\n p = int(s)**2\n\n if p > right:\n break\n\n if p >= left and is_pal(p):\n total += 1\n\n return total\n\n\n \n\n\n\n\n\n \n\n\n\n \n```
0
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
Slow and ugly but one of the first genuine solutions?
super-palindromes
0
1
# Intuition\nSeems a bit contrived and like one of those annoying string manipulation challenges.\n\n# Approach\nTake the square root of the target range to have a smaller set of candidates. The difficult/annoying part is generating the palindromes, which involves increasing the innermost digits to get the next largest palindrome.\n\n# Complexity\n$$O(n)$$\n\n# Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n l = floor(int(left) ** 0.5)\n r = floor(int(right) ** 0.5) + 1\n pc = 0\n def inc_str(x):\n return str(int(x) + 1)\n def is_pali(x):\n return x == x[::-1] and int(left) <= int(x) <= int(right)\n def next_pali(x):\n x = [x for x in x]\n l = len(x)\n if all([x == "9" for x in x]):\n return "".join(["1"] + ["0" for _ in range(len(x) - 1)] + ["1"])\n elif len(x) == 1:\n return inc_str(x[0])\n m = m2 = l // 2\n if l % 2 == 0:\n m -= 1\n for i in range(l // 2):\n if not x[m - i] == "9":\n if i != 0 or l % 2 == 0:\n for j in [m - i, m2 + i]:\n x[j] = inc_str(x[j])\n return "".join(x)\n else:\n x[m] = inc_str(x[m])\n return "".join(x)\n else:\n while x[m - i - 1] == "9":\n i += 1\n for j in range(m - i, m2 + i + 1):\n x[j] = "0"\n x[m - i - 1] = inc_str(x[m - i - 1])\n x[m2 + i + 1] = inc_str(x[m2 + i + 1])\n return "".join(x)\n l = str(l)\n l2 = len(l) // 2\n if len(l) % 2 == 0:\n l = l[:l2] + l[:l2][::-1]\n else:\n l = l[:l2 + 1] + l[:l2][::-1]\n while(int(l) < r):\n pc += is_pali(str(int(l) ** 2))\n l = next_pali(l)\n return pc\n\n\n```
0
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. **Example 1:** **Input:** left = "4 ", right = "1000 " **Output:** 4 **Explanation**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. **Example 2:** **Input:** left = "1 ", right = "2 " **Output:** 1 **Constraints:** * `1 <= left.length, right.length <= 18` * `left` and `right` consist of only digits. * `left` and `right` cannot have leading zeros. * `left` and `right` represent integers in the range `[1, 1018 - 1]`. * `left` is less than or equal to `right`.
null
Slow and ugly but one of the first genuine solutions?
super-palindromes
0
1
# Intuition\nSeems a bit contrived and like one of those annoying string manipulation challenges.\n\n# Approach\nTake the square root of the target range to have a smaller set of candidates. The difficult/annoying part is generating the palindromes, which involves increasing the innermost digits to get the next largest palindrome.\n\n# Complexity\n$$O(n)$$\n\n# Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n l = floor(int(left) ** 0.5)\n r = floor(int(right) ** 0.5) + 1\n pc = 0\n def inc_str(x):\n return str(int(x) + 1)\n def is_pali(x):\n return x == x[::-1] and int(left) <= int(x) <= int(right)\n def next_pali(x):\n x = [x for x in x]\n l = len(x)\n if all([x == "9" for x in x]):\n return "".join(["1"] + ["0" for _ in range(len(x) - 1)] + ["1"])\n elif len(x) == 1:\n return inc_str(x[0])\n m = m2 = l // 2\n if l % 2 == 0:\n m -= 1\n for i in range(l // 2):\n if not x[m - i] == "9":\n if i != 0 or l % 2 == 0:\n for j in [m - i, m2 + i]:\n x[j] = inc_str(x[j])\n return "".join(x)\n else:\n x[m] = inc_str(x[m])\n return "".join(x)\n else:\n while x[m - i - 1] == "9":\n i += 1\n for j in range(m - i, m2 + i + 1):\n x[j] = "0"\n x[m - i - 1] = inc_str(x[m - i - 1])\n x[m2 + i + 1] = inc_str(x[m2 + i + 1])\n return "".join(x)\n l = str(l)\n l2 = len(l) // 2\n if len(l) % 2 == 0:\n l = l[:l2] + l[:l2][::-1]\n else:\n l = l[:l2 + 1] + l[:l2][::-1]\n while(int(l) < r):\n pc += is_pali(str(int(l) ** 2))\n l = next_pali(l)\n return pc\n\n\n```
0
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
superpalidrome logic python3
super-palindromes
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 superpalindromesInRange(self, left: str, right: str) -> int:\n count=0\n for i in range(100000):\n a=str(i)\n b=a+a[-2::-1]\n b=int(b)**2\n if b>int(right):\n break\n if b>=int(left) and str(b)==str(b)[::-1]:\n count+=1\n for i in range(100000):\n a=str(i)\n b=a+a[::-1]\n b=int(b)**2\n if b>int(right):\n break\n if b>=int(left) and str(b)==str(b)[::-1]:\n count+=1\n return count\n\n \n```
0
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. **Example 1:** **Input:** left = "4 ", right = "1000 " **Output:** 4 **Explanation**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. **Example 2:** **Input:** left = "1 ", right = "2 " **Output:** 1 **Constraints:** * `1 <= left.length, right.length <= 18` * `left` and `right` consist of only digits. * `left` and `right` cannot have leading zeros. * `left` and `right` represent integers in the range `[1, 1018 - 1]`. * `left` is less than or equal to `right`.
null
superpalidrome logic python3
super-palindromes
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 superpalindromesInRange(self, left: str, right: str) -> int:\n count=0\n for i in range(100000):\n a=str(i)\n b=a+a[-2::-1]\n b=int(b)**2\n if b>int(right):\n break\n if b>=int(left) and str(b)==str(b)[::-1]:\n count+=1\n for i in range(100000):\n a=str(i)\n b=a+a[::-1]\n b=int(b)**2\n if b>int(right):\n break\n if b>=int(left) and str(b)==str(b)[::-1]:\n count+=1\n return count\n\n \n```
0
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
[Python3] Solution with explanation
super-palindromes
0
1
We separately iterate over palindromes with an even and odd number of digits, comparing the value with the square root of the resulting number including some conditions.\nTo form an **odd** digits palindrome we use left part with addition of reversed left part withiout last digit. \n```\npal = num_str + num_str[:-1][::-1]\n```\nFor an **even** digits palindrome we just add a reversed left part to the original left part:\n```\npal = num_str + num_str[::-1]\n```\nWe iterate over the numbers from 1 to **limit**.\nOur search area is limited to 20001 because with the right limit which is 10 ** 18 - 1 the last palindrome that is the square of the palindrome is 40004000900040004 and sqrt of it is 200010002. Since half of the digits are enough for us to form a palindrome, so the **limit** is 20001.\nWe also take into account the following facts:\n1)All palindromic square numbers **can only** start or end with digits: 0, **1**, **4**, **5**, **6**, **9**. \n2)There **exist no** palindromic squares of length: **2**, **4**, **8**, **10**, **14**, **18**, 20, 24, 30, 38, 40.\n\n```\nclass Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n min_num, max_num = int(left), int(right)\n count, limit = 0, 20001\n \n # odd pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[:-1][::-1]\n num_sqr = int(pal) ** 2\n\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n # even pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[::-1]\n num_sqr = int(pal) ** 2\n\n if len(str(num_sqr)) != 2 or len(str(num_sqr)) != 4 or len(str(num_sqr)) != 8 or \\\n len(str(num_sqr)) != 10 or len(str(num_sqr)) != 14 or len(str(num_sqr)) != 18:\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n return count \n```
1
Let's say a positive integer is a **super-palindrome** if it is a palindrome, and it is also the square of a palindrome. Given two positive integers `left` and `right` represented as strings, return _the number of **super-palindromes** integers in the inclusive range_ `[left, right]`. **Example 1:** **Input:** left = "4 ", right = "1000 " **Output:** 4 **Explanation**: 4, 9, 121, and 484 are superpalindromes. Note that 676 is not a superpalindrome: 26 \* 26 = 676, but 26 is not a palindrome. **Example 2:** **Input:** left = "1 ", right = "2 " **Output:** 1 **Constraints:** * `1 <= left.length, right.length <= 18` * `left` and `right` consist of only digits. * `left` and `right` cannot have leading zeros. * `left` and `right` represent integers in the range `[1, 1018 - 1]`. * `left` is less than or equal to `right`.
null
[Python3] Solution with explanation
super-palindromes
0
1
We separately iterate over palindromes with an even and odd number of digits, comparing the value with the square root of the resulting number including some conditions.\nTo form an **odd** digits palindrome we use left part with addition of reversed left part withiout last digit. \n```\npal = num_str + num_str[:-1][::-1]\n```\nFor an **even** digits palindrome we just add a reversed left part to the original left part:\n```\npal = num_str + num_str[::-1]\n```\nWe iterate over the numbers from 1 to **limit**.\nOur search area is limited to 20001 because with the right limit which is 10 ** 18 - 1 the last palindrome that is the square of the palindrome is 40004000900040004 and sqrt of it is 200010002. Since half of the digits are enough for us to form a palindrome, so the **limit** is 20001.\nWe also take into account the following facts:\n1)All palindromic square numbers **can only** start or end with digits: 0, **1**, **4**, **5**, **6**, **9**. \n2)There **exist no** palindromic squares of length: **2**, **4**, **8**, **10**, **14**, **18**, 20, 24, 30, 38, 40.\n\n```\nclass Solution:\n def superpalindromesInRange(self, left: str, right: str) -> int:\n min_num, max_num = int(left), int(right)\n count, limit = 0, 20001\n \n # odd pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[:-1][::-1]\n num_sqr = int(pal) ** 2\n\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n # even pals\n for num in range(limit + 1):\n num_str = str(num)\n if num_str[0] != 1 or num_str[0] != 4 or num_str[0] != 5 or num_str[0] != 6 or num_str[0] != 9:\n pal = num_str + num_str[::-1]\n num_sqr = int(pal) ** 2\n\n if len(str(num_sqr)) != 2 or len(str(num_sqr)) != 4 or len(str(num_sqr)) != 8 or \\\n len(str(num_sqr)) != 10 or len(str(num_sqr)) != 14 or len(str(num_sqr)) != 18:\n if num_sqr > max_num:\n break\n\n if num_sqr >= min_num and str(num_sqr) == str(num_sqr)[::-1]:\n count += 1\n \n return count \n```
1
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
python3 Solution
sum-of-subarray-minimums
0
1
\n```\nclass Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n n=len(arr)\n left=[1]*n\n dec_q=[(arr[0],1)]\n for i in range(1,n):\n while dec_q and arr[i]<=dec_q[-1][0]:\n left[i]+=dec_q.pop()[1]\n \n dec_q.append((arr[i],left[i]))\n right=[1]*n\n dec_q=[(arr[-1],1)]\n for i in range(n-2,-1,-1):\n while dec_q and arr[i]<dec_q[-1][0]:\n right[i]+=dec_q.pop()[1]\n \n dec_q.append((arr[i], right[i]))\n \n ans=0\n for i in range(n):\n ans+=arr[i]*left[i]*right[i]\n \n mod=10**9+7\n return ans%mod\n```
1
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[3,1,2,4\] **Output:** 17 **Explanation:** Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. **Example 2:** **Input:** arr = \[11,81,94,43,3\] **Output:** 444 **Constraints:** * `1 <= arr.length <= 3 * 104` * `1 <= arr[i] <= 3 * 104`
null
python3 Solution
sum-of-subarray-minimums
0
1
\n```\nclass Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n n=len(arr)\n left=[1]*n\n dec_q=[(arr[0],1)]\n for i in range(1,n):\n while dec_q and arr[i]<=dec_q[-1][0]:\n left[i]+=dec_q.pop()[1]\n \n dec_q.append((arr[i],left[i]))\n right=[1]*n\n dec_q=[(arr[-1],1)]\n for i in range(n-2,-1,-1):\n while dec_q and arr[i]<dec_q[-1][0]:\n right[i]+=dec_q.pop()[1]\n \n dec_q.append((arr[i], right[i]))\n \n ans=0\n for i in range(n):\n ans+=arr[i]*left[i]*right[i]\n \n mod=10**9+7\n return ans%mod\n```
1
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
[Python 3]Monotonic stack boundry
sum-of-subarray-minimums
0
1
```\nclass Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n M = 10 ** 9 + 7\n\n # right bound for current number as minimum\n\t\tq = []\n n = len(arr)\n right = [n-1] * n \n \n for i in range(n):\n # must put the equal sign to one of the bound (left or right) for duplicate nums (e.g. [71, 55, 82, 55])\n while q and arr[i] <= arr[q[-1]]:\n right[q.pop()] = i - 1\n q.append(i)\n\n # left bound for current number as minimum\n q = []\n left = [0] * n\n for i in reversed(range(n)):\n while q and arr[i] < arr[q[-1]]:\n left[q.pop()] = i + 1\n q.append(i)\n \n # calculate sum for each number\n ans = 0\n for i in range(n):\n l, r = abs(i - left[i]), abs(i - right[i])\n # for example: xx1xxx\n # left take 0, 1, 2 numbers (3 combs) and right take 0, 1, 2, 3 numbers (4 combs)\n covered = (l + 1) * (r + 1)\n ans = (ans + arr[i] * covered) % M\n \n return ans
11
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[3,1,2,4\] **Output:** 17 **Explanation:** Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. **Example 2:** **Input:** arr = \[11,81,94,43,3\] **Output:** 444 **Constraints:** * `1 <= arr.length <= 3 * 104` * `1 <= arr[i] <= 3 * 104`
null
[Python 3]Monotonic stack boundry
sum-of-subarray-minimums
0
1
```\nclass Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n M = 10 ** 9 + 7\n\n # right bound for current number as minimum\n\t\tq = []\n n = len(arr)\n right = [n-1] * n \n \n for i in range(n):\n # must put the equal sign to one of the bound (left or right) for duplicate nums (e.g. [71, 55, 82, 55])\n while q and arr[i] <= arr[q[-1]]:\n right[q.pop()] = i - 1\n q.append(i)\n\n # left bound for current number as minimum\n q = []\n left = [0] * n\n for i in reversed(range(n)):\n while q and arr[i] < arr[q[-1]]:\n left[q.pop()] = i + 1\n q.append(i)\n \n # calculate sum for each number\n ans = 0\n for i in range(n):\n l, r = abs(i - left[i]), abs(i - right[i])\n # for example: xx1xxx\n # left take 0, 1, 2 numbers (3 combs) and right take 0, 1, 2, 3 numbers (4 combs)\n covered = (l + 1) * (r + 1)\n ans = (ans + arr[i] * covered) % M\n \n return ans
11
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Python3 | Short Solution | Min Stack
sum-of-subarray-minimums
0
1
# Complexity\n- Time complexity: $$O(N)$$\n\n- Space complexity: $$O(N)$$\n\n# Code\n```\nclass Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n MOD = 10**9+7\n ans = 0\n minstack = [(-inf, -1, 0)]\n for i, x in enumerate(arr):\n while minstack[-1][0] >= x:\n minstack.pop()\n sz = i - minstack[-1][1]\n minstack.append((arr[i], i, arr[i]*sz+minstack[-1][2]))\n ans += minstack[-1][2]\n ans %= MOD\n return ans\n```
1
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[3,1,2,4\] **Output:** 17 **Explanation:** Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. **Example 2:** **Input:** arr = \[11,81,94,43,3\] **Output:** 444 **Constraints:** * `1 <= arr.length <= 3 * 104` * `1 <= arr[i] <= 3 * 104`
null
Python3 | Short Solution | Min Stack
sum-of-subarray-minimums
0
1
# Complexity\n- Time complexity: $$O(N)$$\n\n- Space complexity: $$O(N)$$\n\n# Code\n```\nclass Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n MOD = 10**9+7\n ans = 0\n minstack = [(-inf, -1, 0)]\n for i, x in enumerate(arr):\n while minstack[-1][0] >= x:\n minstack.pop()\n sz = i - minstack[-1][1]\n minstack.append((arr[i], i, arr[i]*sz+minstack[-1][2]))\n ans += minstack[-1][2]\n ans %= MOD\n return ans\n```
1
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Simple solution in Python3
smallest-range-i
0
1
# Intuition\nHere we have:\n- `nums` list of integers and `k`\n- we should apply `[x - k, x + k]` operation for each `nums[i]` **optimally** to extract **smallest range** between two integers in `nums`\n\nLet\'s act greedily:\n- define `left` and `right`, then find **difference** between them in range above.\n\nNote that `right` part **cannot be** less than `left`.\n\n# Approach\n1. find the smallest part as `left`\n2. do the same with `right`, and define it as `max(right, left)`\n3. return difference between `right - left`\n\n# Complexity\n- Time complexity: **O(N)**\n\n- Space complexity: **O(1)**\n\n# Code\n```\nclass Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n left = min(nums) + k\n right = max(max(nums) - k, left)\n\n return right - left\n\n```
2
You are given an integer array `nums` and an integer `k`. In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 0 **Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Simple solution in Python3
smallest-range-i
0
1
# Intuition\nHere we have:\n- `nums` list of integers and `k`\n- we should apply `[x - k, x + k]` operation for each `nums[i]` **optimally** to extract **smallest range** between two integers in `nums`\n\nLet\'s act greedily:\n- define `left` and `right`, then find **difference** between them in range above.\n\nNote that `right` part **cannot be** less than `left`.\n\n# Approach\n1. find the smallest part as `left`\n2. do the same with `right`, and define it as `max(right, left)`\n3. return difference between `right - left`\n\n# Complexity\n- Time complexity: **O(N)**\n\n- Space complexity: **O(1)**\n\n# Code\n```\nclass Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n left = min(nums) + k\n right = max(max(nums) - k, left)\n\n return right - left\n\n```
2
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
SIMPLE PYTHON
smallest-range-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 smallestRangeI(self, nums: List[int], k: int) -> int:\n x=max(nums)\n y=min(nums)\n return max(0,(x-k)-(y+k))\n```
1
You are given an integer array `nums` and an integer `k`. In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 0 **Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
SIMPLE PYTHON
smallest-range-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 smallestRangeI(self, nums: List[int], k: int) -> int:\n x=max(nums)\n y=min(nums)\n return max(0,(x-k)-(y+k))\n```
1
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
1 line Python
smallest-range-i
0
1
\n\n# Code\n```\nclass Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n a=max((max(A) - min(A) - 2*K), 0)\n return a\n```
1
You are given an integer array `nums` and an integer `k`. In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 0 **Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
1 line Python
smallest-range-i
0
1
\n\n# Code\n```\nclass Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n a=max((max(A) - min(A) - 2*K), 0)\n return a\n```
1
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
Python O(n) by min & Max. 85%+ [w/ Visualization ]
smallest-range-i
0
1
Python O(n) by min & Max.\n\n---\n\n**Hint**:\n\nThe key factor to determine the gap size is the value of minimum of A (i.e., min(A) ) as well as maximum of A (i.e., max(A) ).\n\nFor B, every point value can go from A[i]-k to A[i]+k\nWhat we want is the smallest gap size between maximum and minimum.\n\n---\n\n**Diagram**&**Abstract model**:\n\n![image](https://assets.leetcode.com/users/brianchiang_tw/image_1583839866.png)\n\n---\n\n**Implementation**:\n\n```\nclass Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n\n M, m = max(A), min(A)\n diff, extension = M - m, 2*K\n \n if diff <= extension:\n return 0\n \n else:\n return diff - extension\n```\n\n---\n\nReference:\n\n[1] [Python official docs about built-in function min( ... )](https://docs.python.org/3/library/functions.html#min)\n\n[2] [Python official docs about built-in function max( ... )](https://docs.python.org/3/library/functions.html#max)
24
You are given an integer array `nums` and an integer `k`. In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 0 **Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Python O(n) by min & Max. 85%+ [w/ Visualization ]
smallest-range-i
0
1
Python O(n) by min & Max.\n\n---\n\n**Hint**:\n\nThe key factor to determine the gap size is the value of minimum of A (i.e., min(A) ) as well as maximum of A (i.e., max(A) ).\n\nFor B, every point value can go from A[i]-k to A[i]+k\nWhat we want is the smallest gap size between maximum and minimum.\n\n---\n\n**Diagram**&**Abstract model**:\n\n![image](https://assets.leetcode.com/users/brianchiang_tw/image_1583839866.png)\n\n---\n\n**Implementation**:\n\n```\nclass Solution:\n def smallestRangeI(self, A: List[int], K: int) -> int:\n\n M, m = max(A), min(A)\n diff, extension = M - m, 2*K\n \n if diff <= extension:\n return 0\n \n else:\n return diff - extension\n```\n\n---\n\nReference:\n\n[1] [Python official docs about built-in function min( ... )](https://docs.python.org/3/library/functions.html#min)\n\n[2] [Python official docs about built-in function max( ... )](https://docs.python.org/3/library/functions.html#max)
24
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
Solution
smallest-range-i
1
1
```C++ []\nclass Solution {\npublic:\n int smallestRangeI(vector<int>& nums, int k) {\n int nsize = nums.size();\n int max=nums[0];\n int min=nums[0];\n for(int i=1; i<nsize; i++)\n {\n if(nums[i]>max)\n {\n max=nums[i];\n }\n if(nums[i]<min)\n {\n min=nums[i];\n }\n }\n int diff=max-min;\n if(diff<=2*k)\n {\n return 0;\n }\n else\n {\n return diff-2*k;\n }\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n if len(nums)==1:\n return 0\n else:\n return max(0,max(nums)-min(nums)-2*k)\n```\n\n```Java []\nclass Solution {\n public int smallestRangeI(int[] nums, int k) {\n int max = Integer.MIN_VALUE;\n int min = Integer.MAX_VALUE;\n for(int i : nums){\n if(i > max){\n max = i;\n }\n if(i < min){\n min = i;\n }\n } \n int temp = max - min - 2 * k;\n if(temp < 0){\n return 0;\n }\n return temp;\n }\n}\n```\n
2
You are given an integer array `nums` and an integer `k`. In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 0 **Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Solution
smallest-range-i
1
1
```C++ []\nclass Solution {\npublic:\n int smallestRangeI(vector<int>& nums, int k) {\n int nsize = nums.size();\n int max=nums[0];\n int min=nums[0];\n for(int i=1; i<nsize; i++)\n {\n if(nums[i]>max)\n {\n max=nums[i];\n }\n if(nums[i]<min)\n {\n min=nums[i];\n }\n }\n int diff=max-min;\n if(diff<=2*k)\n {\n return 0;\n }\n else\n {\n return diff-2*k;\n }\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n if len(nums)==1:\n return 0\n else:\n return max(0,max(nums)-min(nums)-2*k)\n```\n\n```Java []\nclass Solution {\n public int smallestRangeI(int[] nums, int k) {\n int max = Integer.MIN_VALUE;\n int min = Integer.MAX_VALUE;\n for(int i : nums){\n if(i > max){\n max = i;\n }\n if(i < min){\n min = i;\n }\n } \n int temp = max - min - 2 * k;\n if(temp < 0){\n return 0;\n }\n return temp;\n }\n}\n```\n
2
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
Very Easy to Understand 💯💯 | C++, Java, Python, Python, C#, JavaScript, Kotlin
smallest-range-i
1
1
# C++\n```\nclass Solution {\npublic:\n int smallestRangeI(vector<int>& nums, int k) {\n int maxNum=nums[0],minNum=nums[0];\n for(auto pr:nums){\n maxNum=max(maxNum,pr);\n minNum=min(minNum,pr);\n }\n return max(0,(maxNum-minNum)-2*k);\n }\n};\n```\n\n# Java\n```\nclass Solution {\n public int smallestRangeI(int[] nums, int k) {\n int maxNum=nums[0],minNum=nums[0];\n for(int pr:nums){\n maxNum=Math.max(maxNum,pr);\n minNum=Math.min(minNum,pr);\n }\n return Math.max(0,maxNum-minNum-2*k);\n }\n}\n```\n\n# Python\n```\nclass Solution(object):\n def smallestRangeI(self, nums, k):\n return max(0, max(nums) - min(nums) - 2 * k)\n```\n\n# Python3\n```\nclass Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n return max(0, max(nums) - min(nums) - 2 * k)\n```\n\n# JavaScript\n```\nvar smallestRangeI = function(nums, k) {\n if (nums.length <= 1) return 0;\n let biggest = Math.max(...nums), lowBOfBiggest = biggest-k;\n let smallest = Math.min(...nums), uppBOfSmallest = smallest+k;\n if (lowBOfBiggest-uppBOfSmallest <= 0) return 0;\n else return lowBOfBiggest-uppBOfSmallest; \n};\n```\n\n# C#\n```\npublic class Solution {\n public int SmallestRangeI(int[] nums, int k) {\n return Math.Max(0, nums.Max() - nums.Min() - 2 * k);\n }\n}\n```\n\n# Kotlin\n```\nclass Solution {\n fun smallestRangeI(nums: IntArray, k: Int): Int {\n val minNum = (nums.min() ?: 0) + k \n val maxNum = (nums.max() ?: 0) - k \n val diff = maxNum - minNum \n return if(diff >= 0) diff else 0\n }\n}\n```
1
You are given an integer array `nums` and an integer `k`. In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 0 **Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Very Easy to Understand 💯💯 | C++, Java, Python, Python, C#, JavaScript, Kotlin
smallest-range-i
1
1
# C++\n```\nclass Solution {\npublic:\n int smallestRangeI(vector<int>& nums, int k) {\n int maxNum=nums[0],minNum=nums[0];\n for(auto pr:nums){\n maxNum=max(maxNum,pr);\n minNum=min(minNum,pr);\n }\n return max(0,(maxNum-minNum)-2*k);\n }\n};\n```\n\n# Java\n```\nclass Solution {\n public int smallestRangeI(int[] nums, int k) {\n int maxNum=nums[0],minNum=nums[0];\n for(int pr:nums){\n maxNum=Math.max(maxNum,pr);\n minNum=Math.min(minNum,pr);\n }\n return Math.max(0,maxNum-minNum-2*k);\n }\n}\n```\n\n# Python\n```\nclass Solution(object):\n def smallestRangeI(self, nums, k):\n return max(0, max(nums) - min(nums) - 2 * k)\n```\n\n# Python3\n```\nclass Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n return max(0, max(nums) - min(nums) - 2 * k)\n```\n\n# JavaScript\n```\nvar smallestRangeI = function(nums, k) {\n if (nums.length <= 1) return 0;\n let biggest = Math.max(...nums), lowBOfBiggest = biggest-k;\n let smallest = Math.min(...nums), uppBOfSmallest = smallest+k;\n if (lowBOfBiggest-uppBOfSmallest <= 0) return 0;\n else return lowBOfBiggest-uppBOfSmallest; \n};\n```\n\n# C#\n```\npublic class Solution {\n public int SmallestRangeI(int[] nums, int k) {\n return Math.Max(0, nums.Max() - nums.Min() - 2 * k);\n }\n}\n```\n\n# Kotlin\n```\nclass Solution {\n fun smallestRangeI(nums: IntArray, k: Int): Int {\n val minNum = (nums.min() ?: 0) + k \n val maxNum = (nums.max() ?: 0) - k \n val diff = maxNum - minNum \n return if(diff >= 0) diff else 0\n }\n}\n```
1
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
simple and fast solution in python
smallest-range-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: O(n)\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 smallestRangeI(self, nums: List[int], k: int) -> int:\n cur_min = min(nums)\n cur_max = max(nums)\n cur_min+=k\n if cur_max-cur_min<=k:\n return 0\n return (cur_max-k)-cur_min\n```
0
You are given an integer array `nums` and an integer `k`. In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 0 **Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
simple and fast solution in python
smallest-range-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: O(n)\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 smallestRangeI(self, nums: List[int], k: int) -> int:\n cur_min = min(nums)\n cur_max = max(nums)\n cur_min+=k\n if cur_max-cur_min<=k:\n return 0\n return (cur_max-k)-cur_min\n```
0
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
Solution
smallest-range-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. -->\nsimple mathematical approch and logical thinking \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 smallestRangeI(self, nums: List[int], k: int) -> int:\n if max(nums)==min(nums):\n return 0\n else:\n u=max(nums)-k\n v=min(nums)+k\n h=u-v\n if h<0:\n return 0\n else:\n return h\n \n```
0
You are given an integer array `nums` and an integer `k`. In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 0 **Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Solution
smallest-range-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. -->\nsimple mathematical approch and logical thinking \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 smallestRangeI(self, nums: List[int], k: int) -> int:\n if max(nums)==min(nums):\n return 0\n else:\n u=max(nums)-k\n v=min(nums)+k\n h=u-v\n if h<0:\n return 0\n else:\n return h\n \n```
0
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
Very Detailed Python O(n) Solution - Intuition and Approach Explained
smallest-range-i
0
1
# Intuition\n- The goal is to minimize the difference between the maximum and minimum elements in the array after applying the operation at most once for each index.\n- To minimize this difference, you want to decrease the maximum value and increase the minimum value.\n- You are allowed to add any integer in the range [\u2212k,k] to each element of the array.\n\n# Approach\n- Find the current maximum and minimum values in the array.\n- Calculate the potential new maximum and minimum values after applying the operation.\n- If the new minimum value after adding k is greater than or equal to the new maximum value after subtracting k, it means that the operation can make all elements equal. In this case, return 0 as the minimum score.\n- Otherwise, return the difference between the new maximum and minimum values.\n\n# Complexity\n- Time complexity:\nYour solution has a time complexity of O(n), where n is the length of the input array nums. This is because you iterate through the array once to find the maximum and minimum values.\n\n- Space complexity:\nYour solution has a space complexity of O(1) since you are using a constant amount of extra space, regardless of the size of the input.\n\n\n# Code\n```\nclass Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n if len(nums) == 0:\n return 0\n max_value = max(nums) - k\n min_value = min(nums) + k\n\n if min_value >= max_value : \n return 0\n return max_value-min_value\n```
0
You are given an integer array `nums` and an integer `k`. In one operation, you can choose any index `i` where `0 <= i < nums.length` and change `nums[i]` to `nums[i] + x` where `x` is an integer from the range `[-k, k]`. You can apply this operation **at most once** for each index `i`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after applying the mentioned operation at most once for each index in it_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 0 **Explanation:** Change nums to be \[4, 4, 4\]. The score is max(nums) - min(nums) = 4 - 4 = 0. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Very Detailed Python O(n) Solution - Intuition and Approach Explained
smallest-range-i
0
1
# Intuition\n- The goal is to minimize the difference between the maximum and minimum elements in the array after applying the operation at most once for each index.\n- To minimize this difference, you want to decrease the maximum value and increase the minimum value.\n- You are allowed to add any integer in the range [\u2212k,k] to each element of the array.\n\n# Approach\n- Find the current maximum and minimum values in the array.\n- Calculate the potential new maximum and minimum values after applying the operation.\n- If the new minimum value after adding k is greater than or equal to the new maximum value after subtracting k, it means that the operation can make all elements equal. In this case, return 0 as the minimum score.\n- Otherwise, return the difference between the new maximum and minimum values.\n\n# Complexity\n- Time complexity:\nYour solution has a time complexity of O(n), where n is the length of the input array nums. This is because you iterate through the array once to find the maximum and minimum values.\n\n- Space complexity:\nYour solution has a space complexity of O(1) since you are using a constant amount of extra space, regardless of the size of the input.\n\n\n# Code\n```\nclass Solution:\n def smallestRangeI(self, nums: List[int], k: int) -> int:\n if len(nums) == 0:\n return 0\n max_value = max(nums) - k\n min_value = min(nums) + k\n\n if min_value >= max_value : \n return 0\n return max_value-min_value\n```
0
You are given an array of `n` strings `strs`, all of the same length. The strings can be arranged such that there is one on each line, making a grid. * For example, `strs = [ "abc ", "bce ", "cae "]` can be arranged as follows: abc bce cae You want to **delete** the columns that are **not sorted lexicographically**. In the above example (**0-indexed**), columns 0 (`'a'`, `'b'`, `'c'`) and 2 (`'c'`, `'e'`, `'e'`) are sorted, while column 1 (`'b'`, `'c'`, `'a'`) is not, so you would delete column 1. Return _the number of columns that you will delete_. **Example 1:** **Input:** strs = \[ "cba ", "daf ", "ghi "\] **Output:** 1 **Explanation:** The grid looks as follows: cba daf ghi Columns 0 and 2 are sorted, but column 1 is not, so you only need to delete 1 column. **Example 2:** **Input:** strs = \[ "a ", "b "\] **Output:** 0 **Explanation:** The grid looks as follows: a b Column 0 is the only column and is sorted, so you will not delete any columns. **Example 3:** **Input:** strs = \[ "zyx ", "wvu ", "tsr "\] **Output:** 3 **Explanation:** The grid looks as follows: zyx wvu tsr All 3 columns are not sorted, so you will delete all 3. **Constraints:** * `n == strs.length` * `1 <= n <= 100` * `1 <= strs[i].length <= 1000` * `strs[i]` consists of lowercase English letters.
null
BFS solution
snakes-and-ladders
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince BFS can be used to find the shortest part, hence it can be used to find the solution\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAssume the board is a directed graph, with the ladders pointing to an higher number and snakes pointing to a lower no. \nEvery node also have 6 children connected to it( indicating the dice throw)\n\nstart by using the numbers of the board to inidicate the nodes, \nthen calculate bfs with shortest part \n\n```\nft = (n - 1 )// column\nr = row - 1 - ft\nc = (n - 1) % column\nif ft % 2 != 0:\n c = column - c - 1\n\n# print(r,c)\nv = board[r][c]\n```\ndetermines the value of the board inorder to know when theres a ladder or a snake. \n\nEdge cases include, when a snake takes you back to the parent node, which is handled here\n```\nif n in visited or v == node:\n continue\n```\n\nthe final result returns the distance at the last position of the board\n\n# Complexity\n- Time complexity: O(V+E)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 4 arrays that grows as max as the input approximately the input size which is O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n row = len(board)\n column = len(board[0])\n q = deque()\n visited = set()\n parent = [-1] * ((row * column) + 1)\n distance = [-1] * ((row * column) + 1)\n q.append(1)\n distance[1] = 0\n while q:\n node = q.popleft()\n\n for i in range(1, 7):\n n = node + i\n if( n >= len(parent)):\n continue\n # snake and ladder movement\n ft = (n - 1 )// column\n r = row - 1 - ft\n c = (n - 1) % column\n if ft % 2 != 0:\n c = column - c - 1\n \n # print(r,c)\n v = board[r][c]\n\n if v != -1:\n n = v\n if n in visited or v == node:\n continue\n \n q.append(n)\n visited.add(n)\n parent[n] = node\n distance[n] = distance[node] + 1\n \n return distance[-1]\n\n \n```
1
You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. You start on square `1` of the board. In each move, starting from square `curr`, do the following: * Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`. * This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board. * If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`. * The game ends when you reach the square `n2`. A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder. * For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`. Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`. **Example 1:** **Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\] **Output:** 4 **Explanation:** In the beginning, you start at square 1 (at row 5, column 0). You decide to move to square 2 and must take the ladder to square 15. You then decide to move to square 17 and must take the snake to square 13. You then decide to move to square 14 and must take the ladder to square 35. You then decide to move to square 36, ending the game. This is the lowest possible number of moves to reach the last square, so return 4. **Example 2:** **Input:** board = \[\[-1,-1\],\[-1,3\]\] **Output:** 1 **Constraints:** * `n == board.length == board[i].length` * `2 <= n <= 20` * `board[i][j]` is either `-1` or in the range `[1, n2]`. * The squares labeled `1` and `n2` do not have any ladders or snakes.
null
BFS solution
snakes-and-ladders
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince BFS can be used to find the shortest part, hence it can be used to find the solution\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAssume the board is a directed graph, with the ladders pointing to an higher number and snakes pointing to a lower no. \nEvery node also have 6 children connected to it( indicating the dice throw)\n\nstart by using the numbers of the board to inidicate the nodes, \nthen calculate bfs with shortest part \n\n```\nft = (n - 1 )// column\nr = row - 1 - ft\nc = (n - 1) % column\nif ft % 2 != 0:\n c = column - c - 1\n\n# print(r,c)\nv = board[r][c]\n```\ndetermines the value of the board inorder to know when theres a ladder or a snake. \n\nEdge cases include, when a snake takes you back to the parent node, which is handled here\n```\nif n in visited or v == node:\n continue\n```\n\nthe final result returns the distance at the last position of the board\n\n# Complexity\n- Time complexity: O(V+E)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 4 arrays that grows as max as the input approximately the input size which is O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n row = len(board)\n column = len(board[0])\n q = deque()\n visited = set()\n parent = [-1] * ((row * column) + 1)\n distance = [-1] * ((row * column) + 1)\n q.append(1)\n distance[1] = 0\n while q:\n node = q.popleft()\n\n for i in range(1, 7):\n n = node + i\n if( n >= len(parent)):\n continue\n # snake and ladder movement\n ft = (n - 1 )// column\n r = row - 1 - ft\n c = (n - 1) % column\n if ft % 2 != 0:\n c = column - c - 1\n \n # print(r,c)\n v = board[r][c]\n\n if v != -1:\n n = v\n if n in visited or v == node:\n continue\n \n q.append(n)\n visited.add(n)\n parent[n] = node\n distance[n] = distance[node] + 1\n \n return distance[-1]\n\n \n```
1
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input:** nums = \[1,2,2\] **Output:** 1 **Explanation:** After 1 move, the array could be \[1, 2, 3\]. **Example 2:** **Input:** nums = \[3,2,1,2,1,7\] **Output:** 6 **Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values. **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null