title
stringlengths 1
100
| titleSlug
stringlengths 3
77
| Java
int64 0
1
| Python3
int64 1
1
| content
stringlengths 28
44.4k
| voteCount
int64 0
3.67k
| question_content
stringlengths 65
5k
| question_hints
stringclasses 970
values |
---|---|---|---|---|---|---|---|
Python solution in 5 lines | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is identical to the classic longest non-decreasing subsequence. \nThe problem can be efficiently solved in binary search. \nDue to the small input size, the solution based on the slower DP algorithm can also be accepted. \nThe implementation can be very short with the `all()` function for comparing two indices. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n^2 * m) where n is the length of indices, and m is the number of strings. \n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0])\n dp = [0] * (n+1)\n for i in range(n):\n dp[i] = 1 + max([dp[j] for j in range(i) if all(strs[k][j] <= strs[k][i] for k in range(m))], default=0)\n return n - max(dp)\n\n\n \n``` | 0 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
Python (Simple DP) | delete-columns-to-make-sorted-iii | 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 minDeletionSize(self, strs):\n n, m = len(strs), len(strs[0])\n\n @lru_cache(None)\n def dfs(k,prev):\n if k == m: return 0\n\n min_val = 1 + dfs(k+1,prev)\n\n if prev == -1 or all(strs[i][prev] <= strs[i][k] for i in range(n)):\n min_val = min(min_val,dfs(k+1,k))\n\n return min_val\n\n return dfs(0,-1)\n\n\n\n\n \n \n\n \n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Python (Simple DP) | delete-columns-to-make-sorted-iii | 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 minDeletionSize(self, strs):\n n, m = len(strs), len(strs[0])\n\n @lru_cache(None)\n def dfs(k,prev):\n if k == m: return 0\n\n min_val = 1 + dfs(k+1,prev)\n\n if prev == -1 or all(strs[i][prev] <= strs[i][k] for i in range(n)):\n min_val = min(min_val,dfs(k+1,k))\n\n return min_val\n\n return dfs(0,-1)\n\n\n\n\n \n \n\n \n``` | 0 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
[Python3] top-down dp | delete-columns-to-make-sorted-iii | 0 | 1 | \n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0]) # dimensions\n \n @cache \n def fn(k, prev):\n """Return min deleted columns to make sorted."""\n if k == n: return 0 \n ans = 1 + fn(k+1, prev) # delete kth column\n if prev == -1 or all(strs[i][prev] <= strs[i][k] for i in range(m)): \n ans = min(ans, fn(k+1, k)) # retain kth column\n return ans \n \n return fn(0, -1)\n``` | 5 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
[Python3] top-down dp | delete-columns-to-make-sorted-iii | 0 | 1 | \n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0]) # dimensions\n \n @cache \n def fn(k, prev):\n """Return min deleted columns to make sorted."""\n if k == n: return 0 \n ans = 1 + fn(k+1, prev) # delete kth column\n if prev == -1 or all(strs[i][prev] <= strs[i][k] for i in range(m)): \n ans = min(ans, fn(k+1, k)) # retain kth column\n return ans \n \n return fn(0, -1)\n``` | 5 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
200 ms Solution beats 85 % in runtime only three lines Deadly simple ! | n-repeated-element-in-size-2n-array | 0 | 1 | PLease UPVOTE\n# Code\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n freq=(max(nums)+1)*[0]\n for i in range(len(nums)):freq[nums[i]]+=1\n return freq.index(max(freq))\n``` | 5 | You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times. | null |
200 ms Solution beats 85 % in runtime only three lines Deadly simple ! | n-repeated-element-in-size-2n-array | 0 | 1 | PLease UPVOTE\n# Code\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n freq=(max(nums)+1)*[0]\n for i in range(len(nums)):freq[nums[i]]+=1\n return freq.index(max(freq))\n``` | 5 | There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp that is initially **turned off**.
You are given a 2D array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][coli]` is **turned on**. Even if the same lamp is listed more than once, it is turned on.
When a lamp is turned on, it **illuminates its cell** and **all other cells** in the same **row, column, or diagonal**.
You are also given another 2D array `queries`, where `queries[j] = [rowj, colj]`. For the `jth` query, determine whether `grid[rowj][colj]` is illuminated or not. After answering the `jth` query, **turn off** the lamp at `grid[rowj][colj]` and its **8 adjacent lamps** if they exist. A lamp is adjacent if its cell shares either a side or corner with `grid[rowj][colj]`.
Return _an array of integers_ `ans`_,_ _where_ `ans[j]` _should be_ `1` _if the cell in the_ `jth` _query was illuminated, or_ `0` _if the lamp was not._
**Example 1:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,0\]\]
**Output:** \[1,0\]
**Explanation:** We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid\[0\]\[0\] then turning on the lamp at grid\[4\]\[4\].
The 0th query asks if the lamp at grid\[1\]\[1\] is illuminated or not (the blue square). It is illuminated, so set ans\[0\] = 1. Then, we turn off all lamps in the red square.
The 1st query asks if the lamp at grid\[1\]\[0\] is illuminated or not (the blue square). It is not illuminated, so set ans\[1\] = 0. Then, we turn off all lamps in the red rectangle.
**Example 2:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,1\]\]
**Output:** \[1,1\]
**Example 3:**
**Input:** n = 5, lamps = \[\[0,0\],\[0,4\]\], queries = \[\[0,4\],\[0,1\],\[1,4\]\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= n <= 109`
* `0 <= lamps.length <= 20000`
* `0 <= queries.length <= 20000`
* `lamps[i].length == 2`
* `0 <= rowi, coli < n`
* `queries[j].length == 2`
* `0 <= rowj, colj < n` | null |
1-liner counter ez | n-repeated-element-in-size-2n-array | 0 | 1 | # Code\n```\nfrom collections import Counter\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n return Counter(nums).most_common(1)[0][0]\n``` | 1 | You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times. | null |
1-liner counter ez | n-repeated-element-in-size-2n-array | 0 | 1 | # Code\n```\nfrom collections import Counter\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n return Counter(nums).most_common(1)[0][0]\n``` | 1 | There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp that is initially **turned off**.
You are given a 2D array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][coli]` is **turned on**. Even if the same lamp is listed more than once, it is turned on.
When a lamp is turned on, it **illuminates its cell** and **all other cells** in the same **row, column, or diagonal**.
You are also given another 2D array `queries`, where `queries[j] = [rowj, colj]`. For the `jth` query, determine whether `grid[rowj][colj]` is illuminated or not. After answering the `jth` query, **turn off** the lamp at `grid[rowj][colj]` and its **8 adjacent lamps** if they exist. A lamp is adjacent if its cell shares either a side or corner with `grid[rowj][colj]`.
Return _an array of integers_ `ans`_,_ _where_ `ans[j]` _should be_ `1` _if the cell in the_ `jth` _query was illuminated, or_ `0` _if the lamp was not._
**Example 1:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,0\]\]
**Output:** \[1,0\]
**Explanation:** We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid\[0\]\[0\] then turning on the lamp at grid\[4\]\[4\].
The 0th query asks if the lamp at grid\[1\]\[1\] is illuminated or not (the blue square). It is illuminated, so set ans\[0\] = 1. Then, we turn off all lamps in the red square.
The 1st query asks if the lamp at grid\[1\]\[0\] is illuminated or not (the blue square). It is not illuminated, so set ans\[1\] = 0. Then, we turn off all lamps in the red rectangle.
**Example 2:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,1\]\]
**Output:** \[1,1\]
**Example 3:**
**Input:** n = 5, lamps = \[\[0,0\],\[0,4\]\], queries = \[\[0,4\],\[0,1\],\[1,4\]\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= n <= 109`
* `0 <= lamps.length <= 20000`
* `0 <= queries.length <= 20000`
* `lamps[i].length == 2`
* `0 <= rowi, coli < n`
* `queries[j].length == 2`
* `0 <= rowj, colj < n` | null |
PYTHON 3 : SUPER EASY 99.52% FASTER | n-repeated-element-in-size-2n-array | 0 | 1 | **184 ms, faster than 99.52%** USING LIST\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n list1 = []\n for i in nums :\n if i in list1 :\n return i\n else :\n list1.append(i)\n```\n**192 ms, faster than 95.77%** USING SET\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n set1 = set()\n for i in nums :\n if i in set1 :\n return i\n else :\n set1.add(i)\n```\n**208 ms, faster than 58.09%** USING COUNT\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n for i in nums :\n if nums.count(i) == len(nums)/2 :\n return i\n```\n**220 ms, faster than 36.92%** USING DICTIONARY\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n dic = {}\n for i in nums :\n if i in dic :\n dic[i] += 1\n if dic[i] == len(nums)/2 :\n return i\n else :\n dic[i] = 1\n```\n**Please upvote if it was helpful : )** | 19 | You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times. | null |
PYTHON 3 : SUPER EASY 99.52% FASTER | n-repeated-element-in-size-2n-array | 0 | 1 | **184 ms, faster than 99.52%** USING LIST\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n list1 = []\n for i in nums :\n if i in list1 :\n return i\n else :\n list1.append(i)\n```\n**192 ms, faster than 95.77%** USING SET\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n set1 = set()\n for i in nums :\n if i in set1 :\n return i\n else :\n set1.add(i)\n```\n**208 ms, faster than 58.09%** USING COUNT\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n for i in nums :\n if nums.count(i) == len(nums)/2 :\n return i\n```\n**220 ms, faster than 36.92%** USING DICTIONARY\n```\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n \n dic = {}\n for i in nums :\n if i in dic :\n dic[i] += 1\n if dic[i] == len(nums)/2 :\n return i\n else :\n dic[i] = 1\n```\n**Please upvote if it was helpful : )** | 19 | There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp that is initially **turned off**.
You are given a 2D array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][coli]` is **turned on**. Even if the same lamp is listed more than once, it is turned on.
When a lamp is turned on, it **illuminates its cell** and **all other cells** in the same **row, column, or diagonal**.
You are also given another 2D array `queries`, where `queries[j] = [rowj, colj]`. For the `jth` query, determine whether `grid[rowj][colj]` is illuminated or not. After answering the `jth` query, **turn off** the lamp at `grid[rowj][colj]` and its **8 adjacent lamps** if they exist. A lamp is adjacent if its cell shares either a side or corner with `grid[rowj][colj]`.
Return _an array of integers_ `ans`_,_ _where_ `ans[j]` _should be_ `1` _if the cell in the_ `jth` _query was illuminated, or_ `0` _if the lamp was not._
**Example 1:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,0\]\]
**Output:** \[1,0\]
**Explanation:** We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid\[0\]\[0\] then turning on the lamp at grid\[4\]\[4\].
The 0th query asks if the lamp at grid\[1\]\[1\] is illuminated or not (the blue square). It is illuminated, so set ans\[0\] = 1. Then, we turn off all lamps in the red square.
The 1st query asks if the lamp at grid\[1\]\[0\] is illuminated or not (the blue square). It is not illuminated, so set ans\[1\] = 0. Then, we turn off all lamps in the red rectangle.
**Example 2:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,1\]\]
**Output:** \[1,1\]
**Example 3:**
**Input:** n = 5, lamps = \[\[0,0\],\[0,4\]\], queries = \[\[0,4\],\[0,1\],\[1,4\]\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= n <= 109`
* `0 <= lamps.length <= 20000`
* `0 <= queries.length <= 20000`
* `lamps[i].length == 2`
* `0 <= rowi, coli < n`
* `queries[j].length == 2`
* `0 <= rowj, colj < n` | null |
Solution | n-repeated-element-in-size-2n-array | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums)\n {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n map<int, int> count;\n for(int i=0; i<nums.size()/2+2; i++)\n {\n if(count[nums[i]] == 1) return nums[i];\n count[nums[i]]++;\n }\n return 0;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n seen = set()\n for n in nums:\n if n in seen: return n\n seen.add(n)\n```\n\n```Java []\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n Set<Integer> elems = new HashSet<>();\n for (int elem : nums) {\n if (!elems.add(elem)) {\n return elem;\n }\n }\n return -1;\n }\n}\n```\n | 2 | You are given an integer array `nums` with the following properties:
* `nums.length == 2 * n`.
* `nums` contains `n + 1` **unique** elements.
* Exactly one element of `nums` is repeated `n` times.
Return _the element that is repeated_ `n` _times_.
**Example 1:**
**Input:** nums = \[1,2,3,3\]
**Output:** 3
**Example 2:**
**Input:** nums = \[2,1,2,5,3,2\]
**Output:** 2
**Example 3:**
**Input:** nums = \[5,1,5,2,5,3,5,4\]
**Output:** 5
**Constraints:**
* `2 <= n <= 5000`
* `nums.length == 2 * n`
* `0 <= nums[i] <= 104`
* `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times. | null |
Solution | n-repeated-element-in-size-2n-array | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int repeatedNTimes(vector<int>& nums)\n {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n\n map<int, int> count;\n for(int i=0; i<nums.size()/2+2; i++)\n {\n if(count[nums[i]] == 1) return nums[i];\n count[nums[i]]++;\n }\n return 0;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def repeatedNTimes(self, nums: List[int]) -> int:\n seen = set()\n for n in nums:\n if n in seen: return n\n seen.add(n)\n```\n\n```Java []\nclass Solution {\n public int repeatedNTimes(int[] nums) {\n Set<Integer> elems = new HashSet<>();\n for (int elem : nums) {\n if (!elems.add(elem)) {\n return elem;\n }\n }\n return -1;\n }\n}\n```\n | 2 | There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp that is initially **turned off**.
You are given a 2D array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][coli]` is **turned on**. Even if the same lamp is listed more than once, it is turned on.
When a lamp is turned on, it **illuminates its cell** and **all other cells** in the same **row, column, or diagonal**.
You are also given another 2D array `queries`, where `queries[j] = [rowj, colj]`. For the `jth` query, determine whether `grid[rowj][colj]` is illuminated or not. After answering the `jth` query, **turn off** the lamp at `grid[rowj][colj]` and its **8 adjacent lamps** if they exist. A lamp is adjacent if its cell shares either a side or corner with `grid[rowj][colj]`.
Return _an array of integers_ `ans`_,_ _where_ `ans[j]` _should be_ `1` _if the cell in the_ `jth` _query was illuminated, or_ `0` _if the lamp was not._
**Example 1:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,0\]\]
**Output:** \[1,0\]
**Explanation:** We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid\[0\]\[0\] then turning on the lamp at grid\[4\]\[4\].
The 0th query asks if the lamp at grid\[1\]\[1\] is illuminated or not (the blue square). It is illuminated, so set ans\[0\] = 1. Then, we turn off all lamps in the red square.
The 1st query asks if the lamp at grid\[1\]\[0\] is illuminated or not (the blue square). It is not illuminated, so set ans\[1\] = 0. Then, we turn off all lamps in the red rectangle.
**Example 2:**
**Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,1\]\]
**Output:** \[1,1\]
**Example 3:**
**Input:** n = 5, lamps = \[\[0,0\],\[0,4\]\], queries = \[\[0,4\],\[0,1\],\[1,4\]\]
**Output:** \[1,1,0\]
**Constraints:**
* `1 <= n <= 109`
* `0 <= lamps.length <= 20000`
* `0 <= queries.length <= 20000`
* `lamps[i].length == 2`
* `0 <= rowi, coli < n`
* `queries[j].length == 2`
* `0 <= rowj, colj < n` | null |
Solution | maximum-width-ramp | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int maxWidthRamp(vector<int>& a) {\n vector<int>st;\n int n=a.size(),ans=0;\n for(int i=0;i<n;i++){\n while(st.empty()||a[st.back()]>a[i]){\n st.push_back(i);\n }\n }\n for(int i=n-1;i>=0;i--){\n while(!st.empty()&&a[st.back()]<=a[i]){\n ans=max(ans,i-st.back());\n st.pop_back();\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxWidthRamp(self, nums: List[int]) -> int:\n lhs = [0]\n for i, e in enumerate(nums):\n if nums[i] < nums[lhs[-1]]:\n lhs.append(i)\n \n max_width = 0\n j = len(nums)-1\n while lhs:\n i = lhs.pop()\n while j-i > max_width:\n if nums[i] <= nums[j]:\n max_width = j-i\n break\n j -= 1\n return max_width\n```\n\n```Java []\nclass Solution {\n public int maxWidthRamp(int[] nums) {\n int n = nums.length, top = 0, ans = 0;\n int[] stack = new int[n];\n for (int i = 1; i < n; i++) {\n if (nums[i] < nums[stack[top]]) {\n stack[++top] = i;\n }\n }\n for (int i = n - 1; i > ans; i--) {\n while (top >= 0 && nums[i] >= nums[stack[top]]) {\n top--;\n }\n ans = Math.max(ans, i - stack[top + 1]);\n }\n return ans;\n }\n}\n```\n | 2 | A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,5\]
**Output:** 4
**Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): nums\[1\] = 0 and nums\[5\] = 5.
**Example 2:**
**Input:** nums = \[9,8,1,0,1,9,4,0,4,1\]
**Output:** 7
**Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): nums\[2\] = 1 and nums\[9\] = 1.
**Constraints:**
* `2 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 5 * 104` | null |
Solution | maximum-width-ramp | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int maxWidthRamp(vector<int>& a) {\n vector<int>st;\n int n=a.size(),ans=0;\n for(int i=0;i<n;i++){\n while(st.empty()||a[st.back()]>a[i]){\n st.push_back(i);\n }\n }\n for(int i=n-1;i>=0;i--){\n while(!st.empty()&&a[st.back()]<=a[i]){\n ans=max(ans,i-st.back());\n st.pop_back();\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def maxWidthRamp(self, nums: List[int]) -> int:\n lhs = [0]\n for i, e in enumerate(nums):\n if nums[i] < nums[lhs[-1]]:\n lhs.append(i)\n \n max_width = 0\n j = len(nums)-1\n while lhs:\n i = lhs.pop()\n while j-i > max_width:\n if nums[i] <= nums[j]:\n max_width = j-i\n break\n j -= 1\n return max_width\n```\n\n```Java []\nclass Solution {\n public int maxWidthRamp(int[] nums) {\n int n = nums.length, top = 0, ans = 0;\n int[] stack = new int[n];\n for (int i = 1; i < n; i++) {\n if (nums[i] < nums[stack[top]]) {\n stack[++top] = i;\n }\n }\n for (int i = n - 1; i > ans; i--) {\n while (top >= 0 && nums[i] >= nums[stack[top]]) {\n top--;\n }\n ans = Math.max(ans, i - stack[top + 1]);\n }\n return ans;\n }\n}\n```\n | 2 | Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l","l"\]
**Example 2:**
**Input:** words = \["cool","lock","cook"\]
**Output:** \["c","o"\]
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters. | null |
Python easy to read and understand | stack | maximum-width-ramp | 0 | 1 | ```\nclass Solution:\n def maxWidthRamp(self, nums: List[int]) -> int:\n stack = []\n n = len(nums)\n for i in range(n):\n if not stack or nums[stack[-1]] > nums[i]:\n stack.append(i)\n ans = 0\n for i in range(n-1, -1, -1):\n while stack and nums[i] >= nums[stack[-1]]:\n idx = stack.pop()\n ans = max(ans, i-idx)\n return ans | 2 | A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,5\]
**Output:** 4
**Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): nums\[1\] = 0 and nums\[5\] = 5.
**Example 2:**
**Input:** nums = \[9,8,1,0,1,9,4,0,4,1\]
**Output:** 7
**Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): nums\[2\] = 1 and nums\[9\] = 1.
**Constraints:**
* `2 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 5 * 104` | null |
Python easy to read and understand | stack | maximum-width-ramp | 0 | 1 | ```\nclass Solution:\n def maxWidthRamp(self, nums: List[int]) -> int:\n stack = []\n n = len(nums)\n for i in range(n):\n if not stack or nums[stack[-1]] > nums[i]:\n stack.append(i)\n ans = 0\n for i in range(n-1, -1, -1):\n while stack and nums[i] >= nums[stack[-1]]:\n idx = stack.pop()\n ans = max(ans, i-idx)\n return ans | 2 | Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l","l"\]
**Example 2:**
**Input:** words = \["cool","lock","cook"\]
**Output:** \["c","o"\]
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters. | null |
[Python3] binary search O(NlogN) & stack O(N) | maximum-width-ramp | 0 | 1 | **Approach 1 - binary search**\nKeep a decreasing stack and binary search the number smaller than or equal to the current one. \n\nImplementation\n```\nclass Solution:\n def maxWidthRamp(self, A: List[int]) -> int:\n ans = 0\n stack = []\n for i in range(len(A)): \n if not stack or A[stack[-1]] > A[i]: stack.append(i)\n else: \n lo, hi = 0, len(stack)\n while lo < hi: \n mid = lo + hi >> 1\n if A[stack[mid]] <= A[i]: hi = mid\n else: lo = mid + 1\n ans = max(ans, i - stack[lo])\n return ans \n```\n\nAnalysis\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`\n\n**Approach 2 - stack**\nKeep a decreasing stack and pop it from the end to update answer. \n\nImplementation\n```\nclass Solution:\n def maxWidthRamp(self, A: List[int]) -> int:\n ans = 0\n stack = []\n for i in range(len(A)): \n if not stack or A[stack[-1]] > A[i]: stack.append(i)\n \n for i in reversed(range(len(A))): \n while stack and A[stack[-1]] <= A[i]: \n ans = max(ans, i - stack.pop())\n return ans \n```\n\nAnalysis\nTime complexity `O(N)`\nSpace complexity `O(N)` | 10 | A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,5\]
**Output:** 4
**Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): nums\[1\] = 0 and nums\[5\] = 5.
**Example 2:**
**Input:** nums = \[9,8,1,0,1,9,4,0,4,1\]
**Output:** 7
**Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): nums\[2\] = 1 and nums\[9\] = 1.
**Constraints:**
* `2 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 5 * 104` | null |
[Python3] binary search O(NlogN) & stack O(N) | maximum-width-ramp | 0 | 1 | **Approach 1 - binary search**\nKeep a decreasing stack and binary search the number smaller than or equal to the current one. \n\nImplementation\n```\nclass Solution:\n def maxWidthRamp(self, A: List[int]) -> int:\n ans = 0\n stack = []\n for i in range(len(A)): \n if not stack or A[stack[-1]] > A[i]: stack.append(i)\n else: \n lo, hi = 0, len(stack)\n while lo < hi: \n mid = lo + hi >> 1\n if A[stack[mid]] <= A[i]: hi = mid\n else: lo = mid + 1\n ans = max(ans, i - stack[lo])\n return ans \n```\n\nAnalysis\nTime complexity `O(NlogN)`\nSpace complexity `O(N)`\n\n**Approach 2 - stack**\nKeep a decreasing stack and pop it from the end to update answer. \n\nImplementation\n```\nclass Solution:\n def maxWidthRamp(self, A: List[int]) -> int:\n ans = 0\n stack = []\n for i in range(len(A)): \n if not stack or A[stack[-1]] > A[i]: stack.append(i)\n \n for i in reversed(range(len(A))): \n while stack and A[stack[-1]] <= A[i]: \n ans = max(ans, i - stack.pop())\n return ans \n```\n\nAnalysis\nTime complexity `O(N)`\nSpace complexity `O(N)` | 10 | Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l","l"\]
**Example 2:**
**Input:** words = \["cool","lock","cook"\]
**Output:** \["c","o"\]
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters. | null |
Easy Python Solution | maximum-width-ramp | 0 | 1 | # Code\n```\nclass Solution:\n def maxWidthRamp(self, nums: List[int]) -> int:\n stack = []\n\n for i in range(len(nums)):\n if not stack or nums[i] < nums[stack[-1]]:\n stack.append(i)\n \n answer = 0\n\n for i in range(len(nums) - 1, -1, -1):\n while stack and nums[i] >= nums[stack[-1]]:\n answer = max(answer, i - stack.pop(-1))\n\n return answer\n\n``` | 0 | A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,5\]
**Output:** 4
**Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): nums\[1\] = 0 and nums\[5\] = 5.
**Example 2:**
**Input:** nums = \[9,8,1,0,1,9,4,0,4,1\]
**Output:** 7
**Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): nums\[2\] = 1 and nums\[9\] = 1.
**Constraints:**
* `2 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 5 * 104` | null |
Easy Python Solution | maximum-width-ramp | 0 | 1 | # Code\n```\nclass Solution:\n def maxWidthRamp(self, nums: List[int]) -> int:\n stack = []\n\n for i in range(len(nums)):\n if not stack or nums[i] < nums[stack[-1]]:\n stack.append(i)\n \n answer = 0\n\n for i in range(len(nums) - 1, -1, -1):\n while stack and nums[i] >= nums[stack[-1]]:\n answer = max(answer, i - stack.pop(-1))\n\n return answer\n\n``` | 0 | Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l","l"\]
**Example 2:**
**Input:** words = \["cool","lock","cook"\]
**Output:** \["c","o"\]
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters. | null |
Sliding Window Solution | maximum-width-ramp | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def maxWidthRamp(self, nums: List[int]) -> int:\n min_arr = [nums[0]] * len(nums)\n for i in range(1, len(nums)):\n min_arr[i] = min(nums[i], min_arr[i - 1])\n max_arr = [nums[-1]] * len(nums)\n for i in range(len(nums) - 2, -1, -1):\n max_arr[i] = max(nums[i], max_arr[i + 1])\n \n left = 0\n right = 0\n best = 0\n while right < len(nums):\n if min_arr[left] <= max_arr[right]:\n best = max(best, right - left)\n right +=1\n continue\n left += 1\n return best\n``` | 0 | A **ramp** in an integer array `nums` is a pair `(i, j)` for which `i < j` and `nums[i] <= nums[j]`. The **width** of such a ramp is `j - i`.
Given an integer array `nums`, return _the maximum width of a **ramp** in_ `nums`. If there is no **ramp** in `nums`, return `0`.
**Example 1:**
**Input:** nums = \[6,0,8,2,1,5\]
**Output:** 4
**Explanation:** The maximum width ramp is achieved at (i, j) = (1, 5): nums\[1\] = 0 and nums\[5\] = 5.
**Example 2:**
**Input:** nums = \[9,8,1,0,1,9,4,0,4,1\]
**Output:** 7
**Explanation:** The maximum width ramp is achieved at (i, j) = (2, 9): nums\[2\] = 1 and nums\[9\] = 1.
**Constraints:**
* `2 <= nums.length <= 5 * 104`
* `0 <= nums[i] <= 5 * 104` | null |
Sliding Window Solution | maximum-width-ramp | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def maxWidthRamp(self, nums: List[int]) -> int:\n min_arr = [nums[0]] * len(nums)\n for i in range(1, len(nums)):\n min_arr[i] = min(nums[i], min_arr[i - 1])\n max_arr = [nums[-1]] * len(nums)\n for i in range(len(nums) - 2, -1, -1):\n max_arr[i] = max(nums[i], max_arr[i + 1])\n \n left = 0\n right = 0\n best = 0\n while right < len(nums):\n if min_arr[left] <= max_arr[right]:\n best = max(best, right - left)\n right +=1\n continue\n left += 1\n return best\n``` | 0 | Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l","l"\]
**Example 2:**
**Input:** words = \["cool","lock","cook"\]
**Output:** \["c","o"\]
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters. | null |
Solution | minimum-area-rectangle-ii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n double minAreaFreeRect(vector<vector<int>>& points) {\n double _Area, minArea = 0.0;\n if (points.size() < 4){\n return 0;\n }\n int x0, y0;\n int x1, y1;\n int x2, y2;\n int x3, y3;\n int Lx1, Ly1;\n int Lx2, Ly2;\n for(int i = 0; i < points.size() - 3; i ++){\n\n x0 = points[i][0];\n y0 = points[i][1];\n\n for (int j = i + 1; j < points.size(); j ++){\n x1 = points[j][0];\n y1 = points[j][1];\n for (int k = j + 1; k < points.size(); k ++){\n x2 = points[k][0];\n y2 = points[k][1];\n\n Lx1 = x1 - x0;\n Ly1 = y1 - y0;\n \n Lx2 = x2 - x0;\n Ly2 = y2 - y0;\n\n int dotProd = Lx1 * Lx2 + Ly1 * Ly2;\n if (dotProd != 0){\n continue;\n }\n bool skip = true;\n for (int n = 0; n < points.size(); n ++){\n x3 = points[n][0];\n y3 = points[n][1];\n if ((x3 == x0 + Lx1 + Lx2) && (y3 == y0 + Ly1 + Ly2)){\n skip = false;\n break;\n }\n }\n if(skip == true){\n continue;\n }\n _Area = (double)abs(Lx1 * Ly2 - Ly1 * Lx2);\n\n if (minArea == 0.0){\n minArea = _Area; \n }else{\n minArea = minArea < _Area ? minArea : _Area;\n }\n }\n }\n }\n return minArea;\n }\n};\n```\n\n```Python3 []\nfrom itertools import combinations\n\nclass Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n x, y = 0, 1\n vec = lambda p, q: [q[x]-p[x], q[y]-p[y]]\n area = lambda p,q: p[x]*q[y] - p[y]*q[x]\n dist = lambda p,q: (p[x]-q[x])**2 + (p[y]-q[y])**2\n mid_to_diagonals = defaultdict(list)\n for p,q in combinations(points, 2):\n key = p[x] + q[x], p[y] + q[y]\n mid_to_diagonals[key].append((p,q))\n res = float(\'inf\')\n for group in mid_to_diagonals.values():\n for (a,b), (c,d) in combinations(group, 2):\n if dist(a,b) == dist(c,d):\n res = min(res, abs(area(vec(a,b), vec(a,d))))\n return res if res != float(\'inf\') else 0\n```\n\n```Java []\nclass Solution {\n public double minAreaFreeRect(int[][] points) {\n HashSet<Point> pointsSet = new HashSet<>();\n for (int i = 0; i < points.length; i++) {\n pointsSet.add(new Point(points[i][0], points[i][1]));\n }\n double minSq = 2.0 * (double)Long.MAX_VALUE;\n boolean hasRects = false;\n for (int i2 = 0; i2 < points.length; i2++) {\n for (int i1 = i2 + 1; i1 < points.length; i1++) {\n long d12 = d2(points[i1], points[i2]);\n for (int i3 = i1 + 1; i3 < points.length; i3++) {\n long d23 = d2(points[i2], points[i3]);\n if (d12 + d23 != d2(points[i1], points[i3])) {\n continue;\n }\n if (pointsSet.contains(new Point(points[i1][0] + points[i3][0] - points[i2][0], points[i1][1] + points[i3][1] - points[i2][1]))) {\n hasRects = true;\n minSq = Math.min(minSq, d12 * d23);\n }\n }\n }\n }\n return hasRects ? Math.sqrt(minSq) : 0.0;\n }\n private long d2(int[] p1, int[] p2) {\n return ((long)p2[0] - (long)p1[0]) * ((long)p2[0] - (long)p1[0]) + ((long)p2[1] - (long)p1[1]) * ((long)p2[1] - (long)p1[1]);\n }\n private static class Point{\n int x;\n int y;\n\n Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n @Override\n public int hashCode() {\n return x + y * 13;\n }\n @Override\n public boolean equals(Object other) {\n Point otherPoint = (Point)other;\n\n return otherPoint.x == x && otherPoint.y == y;\n }\n }\n}\n```\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 any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\]
**Output:** 2.00000
**Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2.
**Example 2:**
**Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\]
**Output:** 1.00000
**Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1.
**Example 3:**
**Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\]
**Output:** 0
**Explanation:** There is no possible rectangle to form from these points.
**Constraints:**
* `1 <= points.length <= 50`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | null |
Solution | minimum-area-rectangle-ii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n double minAreaFreeRect(vector<vector<int>>& points) {\n double _Area, minArea = 0.0;\n if (points.size() < 4){\n return 0;\n }\n int x0, y0;\n int x1, y1;\n int x2, y2;\n int x3, y3;\n int Lx1, Ly1;\n int Lx2, Ly2;\n for(int i = 0; i < points.size() - 3; i ++){\n\n x0 = points[i][0];\n y0 = points[i][1];\n\n for (int j = i + 1; j < points.size(); j ++){\n x1 = points[j][0];\n y1 = points[j][1];\n for (int k = j + 1; k < points.size(); k ++){\n x2 = points[k][0];\n y2 = points[k][1];\n\n Lx1 = x1 - x0;\n Ly1 = y1 - y0;\n \n Lx2 = x2 - x0;\n Ly2 = y2 - y0;\n\n int dotProd = Lx1 * Lx2 + Ly1 * Ly2;\n if (dotProd != 0){\n continue;\n }\n bool skip = true;\n for (int n = 0; n < points.size(); n ++){\n x3 = points[n][0];\n y3 = points[n][1];\n if ((x3 == x0 + Lx1 + Lx2) && (y3 == y0 + Ly1 + Ly2)){\n skip = false;\n break;\n }\n }\n if(skip == true){\n continue;\n }\n _Area = (double)abs(Lx1 * Ly2 - Ly1 * Lx2);\n\n if (minArea == 0.0){\n minArea = _Area; \n }else{\n minArea = minArea < _Area ? minArea : _Area;\n }\n }\n }\n }\n return minArea;\n }\n};\n```\n\n```Python3 []\nfrom itertools import combinations\n\nclass Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n x, y = 0, 1\n vec = lambda p, q: [q[x]-p[x], q[y]-p[y]]\n area = lambda p,q: p[x]*q[y] - p[y]*q[x]\n dist = lambda p,q: (p[x]-q[x])**2 + (p[y]-q[y])**2\n mid_to_diagonals = defaultdict(list)\n for p,q in combinations(points, 2):\n key = p[x] + q[x], p[y] + q[y]\n mid_to_diagonals[key].append((p,q))\n res = float(\'inf\')\n for group in mid_to_diagonals.values():\n for (a,b), (c,d) in combinations(group, 2):\n if dist(a,b) == dist(c,d):\n res = min(res, abs(area(vec(a,b), vec(a,d))))\n return res if res != float(\'inf\') else 0\n```\n\n```Java []\nclass Solution {\n public double minAreaFreeRect(int[][] points) {\n HashSet<Point> pointsSet = new HashSet<>();\n for (int i = 0; i < points.length; i++) {\n pointsSet.add(new Point(points[i][0], points[i][1]));\n }\n double minSq = 2.0 * (double)Long.MAX_VALUE;\n boolean hasRects = false;\n for (int i2 = 0; i2 < points.length; i2++) {\n for (int i1 = i2 + 1; i1 < points.length; i1++) {\n long d12 = d2(points[i1], points[i2]);\n for (int i3 = i1 + 1; i3 < points.length; i3++) {\n long d23 = d2(points[i2], points[i3]);\n if (d12 + d23 != d2(points[i1], points[i3])) {\n continue;\n }\n if (pointsSet.contains(new Point(points[i1][0] + points[i3][0] - points[i2][0], points[i1][1] + points[i3][1] - points[i2][1]))) {\n hasRects = true;\n minSq = Math.min(minSq, d12 * d23);\n }\n }\n }\n }\n return hasRects ? Math.sqrt(minSq) : 0.0;\n }\n private long d2(int[] p1, int[] p2) {\n return ((long)p2[0] - (long)p1[0]) * ((long)p2[0] - (long)p1[0]) + ((long)p2[1] - (long)p1[1]) * ((long)p2[1] - (long)p1[1]);\n }\n private static class Point{\n int x;\n int y;\n\n Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n @Override\n public int hashCode() {\n return x + y * 13;\n }\n @Override\n public boolean equals(Object other) {\n Point otherPoint = (Point)other;\n\n return otherPoint.x == x && otherPoint.y == y;\n }\n }\n}\n```\n | 1 | Given a string `s`, determine if it is **valid**.
A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**:
* Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**.
Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`.
**Example 1:**
**Input:** s = "aabcbc "
**Output:** true
**Explanation:**
" " -> "abc " -> "aabcbc "
Thus, "aabcbc " is valid.
**Example 2:**
**Input:** s = "abcabcababcc "
**Output:** true
**Explanation:**
" " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc "
Thus, "abcabcababcc " is valid.
**Example 3:**
**Input:** s = "abccba "
**Output:** false
**Explanation:** It is impossible to get "abccba " using the operation.
**Constraints:**
* `1 <= s.length <= 2 * 104`
* `s` consists of letters `'a'`, `'b'`, and `'c'` | null |
[Python3] center point O(N^2) | minimum-area-rectangle-ii | 0 | 1 | **Algo**\nUse a 2-layer nested loops to scan through pair of points `(x0, y0)` and `(x1, y1)`. The key features extracted from this pair are center and length `(cx, cy, d2)`. Those points with the same center and length form rectangles. \n\n**Implementation**\n```\nclass Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n ans = inf\n seen = {}\n for i, (x0, y0) in enumerate(points):\n for x1, y1 in points[i+1:]:\n cx = (x0 + x1)/2\n cy = (y0 + y1)/2\n d2 = (x0 - x1)**2 + (y0 - y1)**2\n for xx, yy in seen.get((cx, cy, d2), []): \n area = sqrt(((x0-xx)**2 + (y0-yy)**2) * ((x1-xx)**2 + (y1-yy)**2))\n ans = min(ans, area)\n seen.setdefault((cx, cy, d2), []).append((x0, y0))\n return ans if ans < inf else 0\n```\n\n**Analysis**\nTime complexity `O(N^2)`\nSpace complexity `O(N^2)`\n\nThe worse case of this approach is `O(N^3)`. Imagine that all points are distributed on a circle. In this case, one could find `N/2` pairs whose center is at the center of the circle. In extreme cases like this, one would have `O(N^3)` performance. But on average, `O(N^2)` can be expected. | 30 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\]
**Output:** 2.00000
**Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2.
**Example 2:**
**Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\]
**Output:** 1.00000
**Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1.
**Example 3:**
**Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\]
**Output:** 0
**Explanation:** There is no possible rectangle to form from these points.
**Constraints:**
* `1 <= points.length <= 50`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | null |
[Python3] center point O(N^2) | minimum-area-rectangle-ii | 0 | 1 | **Algo**\nUse a 2-layer nested loops to scan through pair of points `(x0, y0)` and `(x1, y1)`. The key features extracted from this pair are center and length `(cx, cy, d2)`. Those points with the same center and length form rectangles. \n\n**Implementation**\n```\nclass Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n ans = inf\n seen = {}\n for i, (x0, y0) in enumerate(points):\n for x1, y1 in points[i+1:]:\n cx = (x0 + x1)/2\n cy = (y0 + y1)/2\n d2 = (x0 - x1)**2 + (y0 - y1)**2\n for xx, yy in seen.get((cx, cy, d2), []): \n area = sqrt(((x0-xx)**2 + (y0-yy)**2) * ((x1-xx)**2 + (y1-yy)**2))\n ans = min(ans, area)\n seen.setdefault((cx, cy, d2), []).append((x0, y0))\n return ans if ans < inf else 0\n```\n\n**Analysis**\nTime complexity `O(N^2)`\nSpace complexity `O(N^2)`\n\nThe worse case of this approach is `O(N^3)`. Imagine that all points are distributed on a circle. In this case, one could find `N/2` pairs whose center is at the center of the circle. In extreme cases like this, one would have `O(N^3)` performance. But on average, `O(N^2)` can be expected. | 30 | Given a string `s`, determine if it is **valid**.
A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**:
* Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**.
Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`.
**Example 1:**
**Input:** s = "aabcbc "
**Output:** true
**Explanation:**
" " -> "abc " -> "aabcbc "
Thus, "aabcbc " is valid.
**Example 2:**
**Input:** s = "abcabcababcc "
**Output:** true
**Explanation:**
" " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc "
Thus, "abcabcababcc " is valid.
**Example 3:**
**Input:** s = "abccba "
**Output:** false
**Explanation:** It is impossible to get "abccba " using the operation.
**Constraints:**
* `1 <= s.length <= 2 * 104`
* `s` consists of letters `'a'`, `'b'`, and `'c'` | null |
Python 76%+ | Quick Search for Diamond, Determine Rectangle by Diagonal Distances | minimum-area-rectangle-ii | 0 | 1 | ```python\ndef dist_pow2(x1, y1, x2, y2): return (x2 - x1)**2 + (y2 - y1)**2\ndef dist(x1, y1, x2, y2): return dist_pow2(x1, y1, x2, y2)**0.5\n\nclass Solution:\n def minAreaFreeRect(self, points):\n L, m = len(points), float(\'inf\')\n\n quick_search = {(x, y) for x, y in points}\n\n for i in range(L):\n for j in range(i + 1, L):\n for k in range(j + 1, L):\n x1, y1 = points[i] # calculate point4 to form a diamond by previous three\n x2, y2 = points[j] # we only check case when x4 is latter occured than x3\n x3, y3 = points[k] # becourse the case when x4 is earlier occured than x3 will be covered already\n x4, y4 = (x3 + (x2 - x1), y3 + (y2 - y1))\n\n if (x4, y4) in quick_search: # look for existence of dimond shape\n # if two diagonals\' length are equal, we got a rectangel\n if dist_pow2(x1, y1, x4, y4) == dist_pow2(x2, y2, x3, y3):\n # calculate area by multipling any two adjacent edge\'s length\n area = dist(x1, y1, x2, y2) * dist(x1, y1, x3, y3)\n m = min(m, area) # keep track of min_area\n\n return m if m != float(\'inf\') else 0\n``` | 3 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\]
**Output:** 2.00000
**Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2.
**Example 2:**
**Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\]
**Output:** 1.00000
**Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1.
**Example 3:**
**Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\]
**Output:** 0
**Explanation:** There is no possible rectangle to form from these points.
**Constraints:**
* `1 <= points.length <= 50`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | null |
Python 76%+ | Quick Search for Diamond, Determine Rectangle by Diagonal Distances | minimum-area-rectangle-ii | 0 | 1 | ```python\ndef dist_pow2(x1, y1, x2, y2): return (x2 - x1)**2 + (y2 - y1)**2\ndef dist(x1, y1, x2, y2): return dist_pow2(x1, y1, x2, y2)**0.5\n\nclass Solution:\n def minAreaFreeRect(self, points):\n L, m = len(points), float(\'inf\')\n\n quick_search = {(x, y) for x, y in points}\n\n for i in range(L):\n for j in range(i + 1, L):\n for k in range(j + 1, L):\n x1, y1 = points[i] # calculate point4 to form a diamond by previous three\n x2, y2 = points[j] # we only check case when x4 is latter occured than x3\n x3, y3 = points[k] # becourse the case when x4 is earlier occured than x3 will be covered already\n x4, y4 = (x3 + (x2 - x1), y3 + (y2 - y1))\n\n if (x4, y4) in quick_search: # look for existence of dimond shape\n # if two diagonals\' length are equal, we got a rectangel\n if dist_pow2(x1, y1, x4, y4) == dist_pow2(x2, y2, x3, y3):\n # calculate area by multipling any two adjacent edge\'s length\n area = dist(x1, y1, x2, y2) * dist(x1, y1, x3, y3)\n m = min(m, area) # keep track of min_area\n\n return m if m != float(\'inf\') else 0\n``` | 3 | Given a string `s`, determine if it is **valid**.
A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**:
* Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**.
Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`.
**Example 1:**
**Input:** s = "aabcbc "
**Output:** true
**Explanation:**
" " -> "abc " -> "aabcbc "
Thus, "aabcbc " is valid.
**Example 2:**
**Input:** s = "abcabcababcc "
**Output:** true
**Explanation:**
" " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc "
Thus, "abcabcababcc " is valid.
**Example 3:**
**Input:** s = "abccba "
**Output:** false
**Explanation:** It is impossible to get "abccba " using the operation.
**Constraints:**
* `1 <= s.length <= 2 * 104`
* `s` consists of letters `'a'`, `'b'`, and `'c'` | null |
Linear Algebra Review Problem | Commented and Explained | Graduate Level | minimum-area-rectangle-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a linear algebra problem. As such, I decided to finally implement some parts of my much needed personal linear algebra library of lambda functions, which I showcase here. These come up in a variety of problems as linear algebra is a powerful field for both AI and graphics. As such, feel free to use / improve for your own uses. I know my determinant 3D function that utilizes my determinant 2D is not the most efficient way of doing things, but it is a great learning method and a key to how I teach how to override the useful * operator for things like enum assignment for graphical nomenclatures. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFrom the intuition, let\'s break down the key lambda functions in detail. \nFirst, the make vector function takes two points and their size in agreement. This can only be used with two points of equal size, don\'t try it otherwise. \n\nWhat occurs is a generated list of p2[i] - p1[i] for i in range size. \nSaid more generally is that\n- For each axis (basis) of point 2, get the axis based value\n- Subtract from this the axis (basis) of point 1 for the same axis based value \n- This generates a euclidean delta (described later) for this given axis and records the change. This is akin to saying from point 1 go to point 2 \n\nGet determinant 2d is rather involved with needing 2 vectors, an ith power, an index 0 and index 1 as well as a coefficient \nThis is because, when calculating the 2D determinant of an n dimensional matrix, you will utilize a specific cross bar locaton of the matrix to split it into 2D determinants. Take the example below \n\n> a b c \n> d e f -> given matrix to left, consider the top bar and leftmost column \n> g h i\n\n> a b c\n> d [e f] -> this isolates e f h i as shown in brackets \n> g [h i] \n\n> a is at row index 0 and col index 0 -> this means our ith power of -1 is 0\n> this makes the value of -1 to the power of 0 to be 1 \n> a is also our coefficient \n> in that case, our value of the 2D determinant here is ((-1)^0) * a * (e * i - f * h)\n> we then would move across the top row, moving the left column with it \n\n> this would give us for the next term ((-1)^1) * b * (d * i - f * g)\n> try to get the third one. At the end of this explanation section I\'ll write the answer so you can check \n\nTo help with the above, I did add a helper function that will get the n dimensional determinants ith power. It\'s rather simple, so I\'ll leave it unexplained. \n\nTo get the euclidean delta, simply take the difference between a final and initial value \n\nTo get a euclidean distance, this is simply the sum of square euclidean deltas for any two points of a given size (means, for each basis, get the euclidean delta, multiply this by the same euclidean delta, and add them all up)\n\nNotice, we are using the sum of squared differences here, not the square root of the sum of squared differences, which is the true euclidean distance, but may involve complex positive and negative numbers! \n\nA diagonal key is a key set to be unique for any such pairing (hopefully, no gaurantees, but it works here). It is simply a hashing function at the end of the day, and can be improved as needed. \n\nFinally, we make a map of our diagonals as a collection of lists for a given diagonal key (thus avoiding the possibility of matching diagonal keys!) \n\nSo then, first we need to make the combinations of points in points into a diagonal key and then append to the list a given point structure. Combinations is necessarily a filtered permutation of sorted order, check the itertools documentation for more (math is fun also has a great breakdown) \n\nOnce we have done that, we need to then consider each list of values we have mapped. \n\n- For each such list \n - generate combinations of points (a, b) and (c, d) from this list \n - these are points needed for vectors of a to b and c to d \n - These vectors then are useful if the euclidean distance of a to b is equal to the euclidean distance from c to d (we could have used the square root distance, but we would have had to account for negative values coming out of it, which we avoid by sticking with sum of square differences instead of the more rigorous and slightly problem fraught square root of sum of squared distances) \n - if the vectors are useful, update result to the minimum of itself and the absolute area of the 2D determinant, using vectors from a to b of size 2 and a to d of size 2, with 2 as the size of the vectors, 2 as an even power to raise -1 to the power of, 0 as the first index, 1 as the second index, and 1 as the coefficient\n\nAt the end, return result if result is not our default valuation of float of infinity, otherwise return 0 \n\nThe promised answer to the determinant part above is found below \n(-1 ^ (2)) * c * (d * h - g * e)\n\n# Complexity\n- Time complexity : O( D^2 * C(P, D) * C(V, D) )\n - generating the needed combinations for the map is necessarily of time complexity O(r * n choose r) as we need to yield at least r times. \n - Generally this would be D * P choose D where D is the dimensionality of the points and P the number of points \n - We thus have at worst C(P, D) value key lists \n - For which we have to do D * C(V, D) combinations \n - each of which needs 2 * D euclidean distance operations \n - and which then might cost a final 6 multiplications and one addition \n - So D * C(P, D) + C(P, D) * D * C(V, D) * 2D * (6 multi, one add)\n - D^2 * C(V, D) * C(P, D) * (6 multi, one add) + D * C(P, D) \n - Square D term dominates out \n - D^2 * C(P, D) * C(V, D), not accounting additional multiplications or pre-set up\n - CURSE OF DIMENSIONALITY!!! \n\n- Space complexity : O( C(P, D))\n - We store at most P Choose D lists \n - All others are generated / yielded as needed, so will be discounted \n\n# Code\n```\nclass Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float :\n # linear algebra functions \n make_vector = lambda p1, p2, size : list(p2[i] - p1[i] for i in range(size))\n get_determinant_2D = lambda v1, v2, ith_power, index_0, index_1, coefficient : (-1)**(ith_power) * coefficient * (v1[index_0]*v2[index_1] - v2[index_0]*v1[index_1])\n euclidean_delta = lambda val_f, val_i : val_f - val_i \n euclidean_distance = lambda p1, p2, size : sum(list(euclidean_delta(p2[i], p1[i]) * euclidean_delta(p2[i], p1[i]) for i in range(size)))\n # hash key function, could be improved but is geometrically necessary \n diagonal_key = lambda p1, p2, size : tuple(p1[i] + p2[i] for i in range(size))\n # map of hashes \n map_of_diagonals = collections.defaultdict(list)\n # generate combinations. 2 is here for the size of the vectorial dimension space, in this case 2D \n for p1, p2 in itertools.combinations(points, 2) : \n key = diagonal_key(p1, p2, 2)\n map_of_diagonals[key].append((p1, p2))\n # get float valuation \n result = float(\'inf\')\n # loop over C(P, D) value lists \n for value_list in map_of_diagonals.values() : \n # of size V, taking D * C(V, D) items \n for (a, b), (c, d) in itertools.combinations(value_list, 2) : \n # doing D operations 2 times to get euclidean distance \n if euclidean_distance(a, b, 2) == euclidean_distance(c, d, 2) : \n # doing at most 6 multiplications and one addition to get determinant 2D in abs form \n result = min(result, abs(get_determinant_2D(make_vector(a, b, 2), make_vector(a, d, 2), 2, 0, 1, 1)))\n return result if result != float(\'inf\') else 0\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 any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\]
**Output:** 2.00000
**Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2.
**Example 2:**
**Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\]
**Output:** 1.00000
**Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1.
**Example 3:**
**Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\]
**Output:** 0
**Explanation:** There is no possible rectangle to form from these points.
**Constraints:**
* `1 <= points.length <= 50`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | null |
Linear Algebra Review Problem | Commented and Explained | Graduate Level | minimum-area-rectangle-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a linear algebra problem. As such, I decided to finally implement some parts of my much needed personal linear algebra library of lambda functions, which I showcase here. These come up in a variety of problems as linear algebra is a powerful field for both AI and graphics. As such, feel free to use / improve for your own uses. I know my determinant 3D function that utilizes my determinant 2D is not the most efficient way of doing things, but it is a great learning method and a key to how I teach how to override the useful * operator for things like enum assignment for graphical nomenclatures. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFrom the intuition, let\'s break down the key lambda functions in detail. \nFirst, the make vector function takes two points and their size in agreement. This can only be used with two points of equal size, don\'t try it otherwise. \n\nWhat occurs is a generated list of p2[i] - p1[i] for i in range size. \nSaid more generally is that\n- For each axis (basis) of point 2, get the axis based value\n- Subtract from this the axis (basis) of point 1 for the same axis based value \n- This generates a euclidean delta (described later) for this given axis and records the change. This is akin to saying from point 1 go to point 2 \n\nGet determinant 2d is rather involved with needing 2 vectors, an ith power, an index 0 and index 1 as well as a coefficient \nThis is because, when calculating the 2D determinant of an n dimensional matrix, you will utilize a specific cross bar locaton of the matrix to split it into 2D determinants. Take the example below \n\n> a b c \n> d e f -> given matrix to left, consider the top bar and leftmost column \n> g h i\n\n> a b c\n> d [e f] -> this isolates e f h i as shown in brackets \n> g [h i] \n\n> a is at row index 0 and col index 0 -> this means our ith power of -1 is 0\n> this makes the value of -1 to the power of 0 to be 1 \n> a is also our coefficient \n> in that case, our value of the 2D determinant here is ((-1)^0) * a * (e * i - f * h)\n> we then would move across the top row, moving the left column with it \n\n> this would give us for the next term ((-1)^1) * b * (d * i - f * g)\n> try to get the third one. At the end of this explanation section I\'ll write the answer so you can check \n\nTo help with the above, I did add a helper function that will get the n dimensional determinants ith power. It\'s rather simple, so I\'ll leave it unexplained. \n\nTo get the euclidean delta, simply take the difference between a final and initial value \n\nTo get a euclidean distance, this is simply the sum of square euclidean deltas for any two points of a given size (means, for each basis, get the euclidean delta, multiply this by the same euclidean delta, and add them all up)\n\nNotice, we are using the sum of squared differences here, not the square root of the sum of squared differences, which is the true euclidean distance, but may involve complex positive and negative numbers! \n\nA diagonal key is a key set to be unique for any such pairing (hopefully, no gaurantees, but it works here). It is simply a hashing function at the end of the day, and can be improved as needed. \n\nFinally, we make a map of our diagonals as a collection of lists for a given diagonal key (thus avoiding the possibility of matching diagonal keys!) \n\nSo then, first we need to make the combinations of points in points into a diagonal key and then append to the list a given point structure. Combinations is necessarily a filtered permutation of sorted order, check the itertools documentation for more (math is fun also has a great breakdown) \n\nOnce we have done that, we need to then consider each list of values we have mapped. \n\n- For each such list \n - generate combinations of points (a, b) and (c, d) from this list \n - these are points needed for vectors of a to b and c to d \n - These vectors then are useful if the euclidean distance of a to b is equal to the euclidean distance from c to d (we could have used the square root distance, but we would have had to account for negative values coming out of it, which we avoid by sticking with sum of square differences instead of the more rigorous and slightly problem fraught square root of sum of squared distances) \n - if the vectors are useful, update result to the minimum of itself and the absolute area of the 2D determinant, using vectors from a to b of size 2 and a to d of size 2, with 2 as the size of the vectors, 2 as an even power to raise -1 to the power of, 0 as the first index, 1 as the second index, and 1 as the coefficient\n\nAt the end, return result if result is not our default valuation of float of infinity, otherwise return 0 \n\nThe promised answer to the determinant part above is found below \n(-1 ^ (2)) * c * (d * h - g * e)\n\n# Complexity\n- Time complexity : O( D^2 * C(P, D) * C(V, D) )\n - generating the needed combinations for the map is necessarily of time complexity O(r * n choose r) as we need to yield at least r times. \n - Generally this would be D * P choose D where D is the dimensionality of the points and P the number of points \n - We thus have at worst C(P, D) value key lists \n - For which we have to do D * C(V, D) combinations \n - each of which needs 2 * D euclidean distance operations \n - and which then might cost a final 6 multiplications and one addition \n - So D * C(P, D) + C(P, D) * D * C(V, D) * 2D * (6 multi, one add)\n - D^2 * C(V, D) * C(P, D) * (6 multi, one add) + D * C(P, D) \n - Square D term dominates out \n - D^2 * C(P, D) * C(V, D), not accounting additional multiplications or pre-set up\n - CURSE OF DIMENSIONALITY!!! \n\n- Space complexity : O( C(P, D))\n - We store at most P Choose D lists \n - All others are generated / yielded as needed, so will be discounted \n\n# Code\n```\nclass Solution:\n def minAreaFreeRect(self, points: List[List[int]]) -> float :\n # linear algebra functions \n make_vector = lambda p1, p2, size : list(p2[i] - p1[i] for i in range(size))\n get_determinant_2D = lambda v1, v2, ith_power, index_0, index_1, coefficient : (-1)**(ith_power) * coefficient * (v1[index_0]*v2[index_1] - v2[index_0]*v1[index_1])\n euclidean_delta = lambda val_f, val_i : val_f - val_i \n euclidean_distance = lambda p1, p2, size : sum(list(euclidean_delta(p2[i], p1[i]) * euclidean_delta(p2[i], p1[i]) for i in range(size)))\n # hash key function, could be improved but is geometrically necessary \n diagonal_key = lambda p1, p2, size : tuple(p1[i] + p2[i] for i in range(size))\n # map of hashes \n map_of_diagonals = collections.defaultdict(list)\n # generate combinations. 2 is here for the size of the vectorial dimension space, in this case 2D \n for p1, p2 in itertools.combinations(points, 2) : \n key = diagonal_key(p1, p2, 2)\n map_of_diagonals[key].append((p1, p2))\n # get float valuation \n result = float(\'inf\')\n # loop over C(P, D) value lists \n for value_list in map_of_diagonals.values() : \n # of size V, taking D * C(V, D) items \n for (a, b), (c, d) in itertools.combinations(value_list, 2) : \n # doing D operations 2 times to get euclidean distance \n if euclidean_distance(a, b, 2) == euclidean_distance(c, d, 2) : \n # doing at most 6 multiplications and one addition to get determinant 2D in abs form \n result = min(result, abs(get_determinant_2D(make_vector(a, b, 2), make_vector(a, d, 2), 2, 0, 1, 1)))\n return result if result != float(\'inf\') else 0\n\n``` | 0 | Given a string `s`, determine if it is **valid**.
A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**:
* Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**.
Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`.
**Example 1:**
**Input:** s = "aabcbc "
**Output:** true
**Explanation:**
" " -> "abc " -> "aabcbc "
Thus, "aabcbc " is valid.
**Example 2:**
**Input:** s = "abcabcababcc "
**Output:** true
**Explanation:**
" " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc "
Thus, "abcabcababcc " is valid.
**Example 3:**
**Input:** s = "abccba "
**Output:** false
**Explanation:** It is impossible to get "abccba " using the operation.
**Constraints:**
* `1 <= s.length <= 2 * 104`
* `s` consists of letters `'a'`, `'b'`, and `'c'` | null |
O(n^3) worst case python solution by finding parallel vectors and right angle corners | minimum-area-rectangle-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ndef normalize(points) -> []:\n vector = (points[1][0] - points[0][0], points[1][1] - points[0][1])\n l = length(points)\n return (float(vector[0]) / l, float(vector[1]) / l)\n\n\ndef length(points) -> float:\n vector = (points[1][0] - points[0][0], points[1][1] - points[0][1])\n return sqrt(float(vector[0] * vector[0] + vector[1] * vector[1]))\n\nclass Solution:\n\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n n = len(points)\n vectors = {}\n for i in range(n):\n for j in range(i + 1, n):\n a = points[i]\n b = points[j]\n if a[0] > b[0]:\n a, b = b, a\n vec = (b[0] - a[0], b[1] - a[1])\n if not vec in vectors:\n vectors[vec] = []\n vectors[vec].append((a, b))\n min_area = float("inf")\n for vector in vectors.keys():\n sides = vectors[vector]\n for i in range(len(sides)):\n side1 = sides[i]\n for j in range(i + 1, len(sides)):\n perp = (side1[0], sides[j][0])\n if length(side1) > 0 and length(perp) > 0:\n # we have two parallel vectors of same lengths\n # check if we have a right angle corner\n side1_norm = normalize(side1)\n perp_norm = normalize(perp)\n dot = side1_norm[0] * perp_norm[0] + side1_norm[1] * perp_norm[1]\n if abs(dot) < 0.001:\n area = length(side1) * length(perp)\n min_area = min(min_area, area)\n if min_area == float("inf"):\n return 0\n return min_area\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 any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\]
**Output:** 2.00000
**Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2.
**Example 2:**
**Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\]
**Output:** 1.00000
**Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1.
**Example 3:**
**Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\]
**Output:** 0
**Explanation:** There is no possible rectangle to form from these points.
**Constraints:**
* `1 <= points.length <= 50`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | null |
O(n^3) worst case python solution by finding parallel vectors and right angle corners | minimum-area-rectangle-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\ndef normalize(points) -> []:\n vector = (points[1][0] - points[0][0], points[1][1] - points[0][1])\n l = length(points)\n return (float(vector[0]) / l, float(vector[1]) / l)\n\n\ndef length(points) -> float:\n vector = (points[1][0] - points[0][0], points[1][1] - points[0][1])\n return sqrt(float(vector[0] * vector[0] + vector[1] * vector[1]))\n\nclass Solution:\n\n def minAreaFreeRect(self, points: List[List[int]]) -> float:\n n = len(points)\n vectors = {}\n for i in range(n):\n for j in range(i + 1, n):\n a = points[i]\n b = points[j]\n if a[0] > b[0]:\n a, b = b, a\n vec = (b[0] - a[0], b[1] - a[1])\n if not vec in vectors:\n vectors[vec] = []\n vectors[vec].append((a, b))\n min_area = float("inf")\n for vector in vectors.keys():\n sides = vectors[vector]\n for i in range(len(sides)):\n side1 = sides[i]\n for j in range(i + 1, len(sides)):\n perp = (side1[0], sides[j][0])\n if length(side1) > 0 and length(perp) > 0:\n # we have two parallel vectors of same lengths\n # check if we have a right angle corner\n side1_norm = normalize(side1)\n perp_norm = normalize(perp)\n dot = side1_norm[0] * perp_norm[0] + side1_norm[1] * perp_norm[1]\n if abs(dot) < 0.001:\n area = length(side1) * length(perp)\n min_area = min(min_area, area)\n if min_area == float("inf"):\n return 0\n return min_area\n\n``` | 0 | Given a string `s`, determine if it is **valid**.
A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**:
* Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**.
Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`.
**Example 1:**
**Input:** s = "aabcbc "
**Output:** true
**Explanation:**
" " -> "abc " -> "aabcbc "
Thus, "aabcbc " is valid.
**Example 2:**
**Input:** s = "abcabcababcc "
**Output:** true
**Explanation:**
" " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc "
Thus, "abcabcababcc " is valid.
**Example 3:**
**Input:** s = "abccba "
**Output:** false
**Explanation:** It is impossible to get "abccba " using the operation.
**Constraints:**
* `1 <= s.length <= 2 * 104`
* `s` consists of letters `'a'`, `'b'`, and `'c'` | null |
Python Concise explained solution || Dhruv Vavliya | minimum-area-rectangle-ii | 0 | 1 | ```\n# written by : Dhruv Vavliya\n\n\'\'\'\nthe distance between point1 and point2 equals the distance between point3 and point4\nthe midpoint of point1 and point2 equals the midpoint of point3 and point4.\n\'\'\'\n\npoints =[[2,4],[4,2],[1,0],[3,4],[4,4],[2,2],[1,1],[3,0],[1,4],[0,3],[0,1],[2,1],[4,0]]\n\n\ndef rect_area(points):\n from collections import defaultdict\n import math\n dp = defaultdict(list)\n\n for i in range(len(points) - 1):\n for j in range(i + 1, len(points)):\n l = (points[j][1] - points[i][1]) ** 2 + (points[j][0] - points[i][0]) ** 2 # distance\n x = (points[i][0] + points[j][0]) / 2 # midpoint (x,y)\n y = (points[i][1] + points[j][1]) / 2\n dp[(l, x, y)].append((i, j))\n\n print(dp)\n\n ans = float(\'inf\')\n for line in dp.values():\n for i in range(len(line) - 1):\n p0, p2 = points[line[i][0]] ,points[line[i][1]] \n for j in range(i + 1, len(line)):\n p1, p3 = points[line[j][0]], points[line[j][1]]\n d1 = math.sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2) # two adjacent sides\n d2 = math.sqrt((p0[0] - p3[0]) ** 2 + (p0[1] - p3[1]) ** 2)\n ans = min(ans, d1 * d2)\n\n if ans != float(\'inf\'):\n return ans\n else:\n return 0\n\n\nprint(rect_area(points))\n``` | 2 | You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`.
Return _the minimum area of any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\]
**Output:** 2.00000
**Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2.
**Example 2:**
**Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\]
**Output:** 1.00000
**Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1.
**Example 3:**
**Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\]
**Output:** 0
**Explanation:** There is no possible rectangle to form from these points.
**Constraints:**
* `1 <= points.length <= 50`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | null |
Python Concise explained solution || Dhruv Vavliya | minimum-area-rectangle-ii | 0 | 1 | ```\n# written by : Dhruv Vavliya\n\n\'\'\'\nthe distance between point1 and point2 equals the distance between point3 and point4\nthe midpoint of point1 and point2 equals the midpoint of point3 and point4.\n\'\'\'\n\npoints =[[2,4],[4,2],[1,0],[3,4],[4,4],[2,2],[1,1],[3,0],[1,4],[0,3],[0,1],[2,1],[4,0]]\n\n\ndef rect_area(points):\n from collections import defaultdict\n import math\n dp = defaultdict(list)\n\n for i in range(len(points) - 1):\n for j in range(i + 1, len(points)):\n l = (points[j][1] - points[i][1]) ** 2 + (points[j][0] - points[i][0]) ** 2 # distance\n x = (points[i][0] + points[j][0]) / 2 # midpoint (x,y)\n y = (points[i][1] + points[j][1]) / 2\n dp[(l, x, y)].append((i, j))\n\n print(dp)\n\n ans = float(\'inf\')\n for line in dp.values():\n for i in range(len(line) - 1):\n p0, p2 = points[line[i][0]] ,points[line[i][1]] \n for j in range(i + 1, len(line)):\n p1, p3 = points[line[j][0]], points[line[j][1]]\n d1 = math.sqrt((p0[0] - p1[0]) ** 2 + (p0[1] - p1[1]) ** 2) # two adjacent sides\n d2 = math.sqrt((p0[0] - p3[0]) ** 2 + (p0[1] - p3[1]) ** 2)\n ans = min(ans, d1 * d2)\n\n if ans != float(\'inf\'):\n return ans\n else:\n return 0\n\n\nprint(rect_area(points))\n``` | 2 | Given a string `s`, determine if it is **valid**.
A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**:
* Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**.
Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`.
**Example 1:**
**Input:** s = "aabcbc "
**Output:** true
**Explanation:**
" " -> "abc " -> "aabcbc "
Thus, "aabcbc " is valid.
**Example 2:**
**Input:** s = "abcabcababcc "
**Output:** true
**Explanation:**
" " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc "
Thus, "abcabcababcc " is valid.
**Example 3:**
**Input:** s = "abccba "
**Output:** false
**Explanation:** It is impossible to get "abccba " using the operation.
**Constraints:**
* `1 <= s.length <= 2 * 104`
* `s` consists of letters `'a'`, `'b'`, and `'c'` | null |
Clean Python | Iterative Centers | minimum-area-rectangle-ii | 0 | 1 | **Clean Python | Iterative Centers**\n\n```\nclass Solution:\n Inf = float(\'inf\')\n def minAreaFreeRect(self, A):\n #\n L = len(A)\n res = self.Inf\n sqrt = math.sqrt\n #\n dist = lambda x1,y1,x2,y2: sqrt( (x2-x1)**2 + (y2-y1)**2 )\n D = defaultdict(list)\n #\n for i1 in range(L):\n for i2 in range(i1+1,L):\n x1,y1 = A[i1]\n x2,y2 = A[i2]\n C = (x2+x1)/2. , (y2+y1)/2.\n r2 = (x2-x1)**2 + (y2-y1)**2\n #\n if (C,r2) in D:\n for x3,y3 in D[C,r2]:\n res = min(res, dist(x1,y1,x3,y3)*dist(x2,y2,x3,y3) )\n #\n D[C,r2].append( (x1,y1) )\n #\n return 0 if res==self.Inf else res\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 any rectangle formed from these points, with sides **not necessarily parallel** to the X and Y axes_. If there is not any such rectangle, return `0`.
Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** points = \[\[1,2\],\[2,1\],\[1,0\],\[0,1\]\]
**Output:** 2.00000
**Explanation:** The minimum area rectangle occurs at \[1,2\],\[2,1\],\[1,0\],\[0,1\], with an area of 2.
**Example 2:**
**Input:** points = \[\[0,1\],\[2,1\],\[1,1\],\[1,0\],\[2,0\]\]
**Output:** 1.00000
**Explanation:** The minimum area rectangle occurs at \[1,0\],\[1,1\],\[2,1\],\[2,0\], with an area of 1.
**Example 3:**
**Input:** points = \[\[0,3\],\[1,2\],\[3,1\],\[1,3\],\[2,1\]\]
**Output:** 0
**Explanation:** There is no possible rectangle to form from these points.
**Constraints:**
* `1 <= points.length <= 50`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | null |
Clean Python | Iterative Centers | minimum-area-rectangle-ii | 0 | 1 | **Clean Python | Iterative Centers**\n\n```\nclass Solution:\n Inf = float(\'inf\')\n def minAreaFreeRect(self, A):\n #\n L = len(A)\n res = self.Inf\n sqrt = math.sqrt\n #\n dist = lambda x1,y1,x2,y2: sqrt( (x2-x1)**2 + (y2-y1)**2 )\n D = defaultdict(list)\n #\n for i1 in range(L):\n for i2 in range(i1+1,L):\n x1,y1 = A[i1]\n x2,y2 = A[i2]\n C = (x2+x1)/2. , (y2+y1)/2.\n r2 = (x2-x1)**2 + (y2-y1)**2\n #\n if (C,r2) in D:\n for x3,y3 in D[C,r2]:\n res = min(res, dist(x1,y1,x3,y3)*dist(x2,y2,x3,y3) )\n #\n D[C,r2].append( (x1,y1) )\n #\n return 0 if res==self.Inf else res\n``` | 1 | Given a string `s`, determine if it is **valid**.
A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**:
* Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**.
Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`.
**Example 1:**
**Input:** s = "aabcbc "
**Output:** true
**Explanation:**
" " -> "abc " -> "aabcbc "
Thus, "aabcbc " is valid.
**Example 2:**
**Input:** s = "abcabcababcc "
**Output:** true
**Explanation:**
" " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc "
Thus, "abcabcababcc " is valid.
**Example 3:**
**Input:** s = "abccba "
**Output:** false
**Explanation:** It is impossible to get "abccba " using the operation.
**Constraints:**
* `1 <= s.length <= 2 * 104`
* `s` consists of letters `'a'`, `'b'`, and `'c'` | null |
Solution | least-operators-to-express-number | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int leastOpsExpressTarget(int x, int target) {\n int r = target%x, c = x - r;\n int nr = min(2*r, 1 + 2*(x - r));\n int nc = min(2*c, 1 + 2*(x-c));\n return min(nr + dfs(target - r, x), nc + dfs(target + c, x)) - 1;\n }\nprivate:\n unordered_map<long, int> dp;\n int dfs(long target, int x) {\n if (target == 0)\n return 0;\n if (dp.find(target) != dp.end())\n return dp[target];\n \n long num = target;\n int c = 0;\n long lowestPower = 1;\n \n while (num && (num%x == 0)) {\n num /= x;\n ++c;\n lowestPower *= x;\n }\n int lowestPowerCoeff = (target/lowestPower)%x;\n int distToHigherPower = lowestPower*(x - lowestPowerCoeff);\n \n if (lowestPowerCoeff*lowestPower == target) {\n dp[target] = min(lowestPowerCoeff*c, (x - lowestPowerCoeff)*c + c + 1);\n return dp[target];\n }\n int dp1 = lowestPowerCoeff*c + dfs(target - lowestPowerCoeff*lowestPower, x);\n int dp2 = (x - lowestPowerCoeff)*c + dfs(target + distToHigherPower, x);\n \n dp[target] = min(dp1, dp2); \n return dp[target];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n\n pos = neg = k = 0\n while target:\n target, cur = divmod(target, x)\n if k:\n pos, neg = min(cur * k + pos, (cur + 1) * k + neg), min((x - cur) * k + pos, (x - cur - 1) * k + neg)\n else:\n pos, neg = cur * 2, (x - cur) * 2\n k += 1\n return min(pos, k + neg) - 1\n```\n\n```Java []\nclass Solution {\n public int leastOpsExpressTarget(int x, int y) {\n int pos = 0, neg = 0, k = 0, pos2, neg2, cur;\n while (y > 0) {\n cur = y % x;\n y /= x;\n if (k > 0) {\n pos2 = Math.min(cur * k + pos, (cur + 1) * k + neg);\n neg2 = Math.min((x - cur) * k + pos, (x - cur - 1) * k + neg);\n pos = pos2;\n neg = neg2;\n } else {\n pos = cur * 2;\n neg = (x - cur) * 2;\n }\n k++;\n }\n return Math.min(pos, k + neg) - 1;\n }\n}\n```\n | 2 | Given a single positive integer `x`, we will write an expression of the form `x (op1) x (op2) x (op3) x ...` where each operator `op1`, `op2`, etc. is either addition, subtraction, multiplication, or division (`+`, `-`, `*`, or `/)`. For example, with `x = 3`, we might write `3 * 3 / 3 + 3 - 3` which is a value of 3.
When writing such an expression, we adhere to the following conventions:
* The division operator (`/`) returns rational numbers.
* There are no parentheses placed anywhere.
* We use the usual order of operations: multiplication and division happen before addition and subtraction.
* It is not allowed to use the unary negation operator (`-`). For example, "`x - x` " is a valid expression as it only uses subtraction, but "`-x + x` " is not because it uses negation.
We would like to write an expression with the least number of operators such that the expression equals the given `target`. Return the least number of operators used.
**Example 1:**
**Input:** x = 3, target = 19
**Output:** 5
**Explanation:** 3 \* 3 + 3 \* 3 + 3 / 3.
The expression contains 5 operations.
**Example 2:**
**Input:** x = 5, target = 501
**Output:** 8
**Explanation:** 5 \* 5 \* 5 \* 5 - 5 \* 5 \* 5 + 5 / 5.
The expression contains 8 operations.
**Example 3:**
**Input:** x = 100, target = 100000000
**Output:** 3
**Explanation:** 100 \* 100 \* 100 \* 100.
The expression contains 3 operations.
**Constraints:**
* `2 <= x <= 100`
* `1 <= target <= 2 * 108` | null |
Solution | least-operators-to-express-number | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int leastOpsExpressTarget(int x, int target) {\n int r = target%x, c = x - r;\n int nr = min(2*r, 1 + 2*(x - r));\n int nc = min(2*c, 1 + 2*(x-c));\n return min(nr + dfs(target - r, x), nc + dfs(target + c, x)) - 1;\n }\nprivate:\n unordered_map<long, int> dp;\n int dfs(long target, int x) {\n if (target == 0)\n return 0;\n if (dp.find(target) != dp.end())\n return dp[target];\n \n long num = target;\n int c = 0;\n long lowestPower = 1;\n \n while (num && (num%x == 0)) {\n num /= x;\n ++c;\n lowestPower *= x;\n }\n int lowestPowerCoeff = (target/lowestPower)%x;\n int distToHigherPower = lowestPower*(x - lowestPowerCoeff);\n \n if (lowestPowerCoeff*lowestPower == target) {\n dp[target] = min(lowestPowerCoeff*c, (x - lowestPowerCoeff)*c + c + 1);\n return dp[target];\n }\n int dp1 = lowestPowerCoeff*c + dfs(target - lowestPowerCoeff*lowestPower, x);\n int dp2 = (x - lowestPowerCoeff)*c + dfs(target + distToHigherPower, x);\n \n dp[target] = min(dp1, dp2); \n return dp[target];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n\n pos = neg = k = 0\n while target:\n target, cur = divmod(target, x)\n if k:\n pos, neg = min(cur * k + pos, (cur + 1) * k + neg), min((x - cur) * k + pos, (x - cur - 1) * k + neg)\n else:\n pos, neg = cur * 2, (x - cur) * 2\n k += 1\n return min(pos, k + neg) - 1\n```\n\n```Java []\nclass Solution {\n public int leastOpsExpressTarget(int x, int y) {\n int pos = 0, neg = 0, k = 0, pos2, neg2, cur;\n while (y > 0) {\n cur = y % x;\n y /= x;\n if (k > 0) {\n pos2 = Math.min(cur * k + pos, (cur + 1) * k + neg);\n neg2 = Math.min((x - cur) * k + pos, (x - cur - 1) * k + neg);\n pos = pos2;\n neg = neg2;\n } else {\n pos = cur * 2;\n neg = (x - cur) * 2;\n }\n k++;\n }\n return Math.min(pos, k + neg) - 1;\n }\n}\n```\n | 2 | Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length` | null |
[Python3] top-down dp | least-operators-to-express-number | 0 | 1 | \n```\nclass Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n \n @cache\n def fn(val): \n """Return min ops to express val."""\n if val < x: return min(2*val-1, 2*(x-val))\n k = int(log(val)//log(x))\n ans = k + fn(val - x**k)\n if x**(k+1) < 2*val: \n ans = min(ans, k + 1 + fn(x**(k+1) - val))\n return ans \n \n return fn(target)\n``` | 4 | Given a single positive integer `x`, we will write an expression of the form `x (op1) x (op2) x (op3) x ...` where each operator `op1`, `op2`, etc. is either addition, subtraction, multiplication, or division (`+`, `-`, `*`, or `/)`. For example, with `x = 3`, we might write `3 * 3 / 3 + 3 - 3` which is a value of 3.
When writing such an expression, we adhere to the following conventions:
* The division operator (`/`) returns rational numbers.
* There are no parentheses placed anywhere.
* We use the usual order of operations: multiplication and division happen before addition and subtraction.
* It is not allowed to use the unary negation operator (`-`). For example, "`x - x` " is a valid expression as it only uses subtraction, but "`-x + x` " is not because it uses negation.
We would like to write an expression with the least number of operators such that the expression equals the given `target`. Return the least number of operators used.
**Example 1:**
**Input:** x = 3, target = 19
**Output:** 5
**Explanation:** 3 \* 3 + 3 \* 3 + 3 / 3.
The expression contains 5 operations.
**Example 2:**
**Input:** x = 5, target = 501
**Output:** 8
**Explanation:** 5 \* 5 \* 5 \* 5 - 5 \* 5 \* 5 + 5 / 5.
The expression contains 8 operations.
**Example 3:**
**Input:** x = 100, target = 100000000
**Output:** 3
**Explanation:** 100 \* 100 \* 100 \* 100.
The expression contains 3 operations.
**Constraints:**
* `2 <= x <= 100`
* `1 <= target <= 2 * 108` | null |
[Python3] top-down dp | least-operators-to-express-number | 0 | 1 | \n```\nclass Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n \n @cache\n def fn(val): \n """Return min ops to express val."""\n if val < x: return min(2*val-1, 2*(x-val))\n k = int(log(val)//log(x))\n ans = k + fn(val - x**k)\n if x**(k+1) < 2*val: \n ans = min(ans, k + 1 + fn(x**(k+1) - val))\n return ans \n \n return fn(target)\n``` | 4 | Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length` | null |
Python heapq beats 80% time/space | least-operators-to-express-number | 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```\nimport heapq\n\nclass Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n bfs = [(0, target)]\n visited = set()\n def push(operations, remaining):\n heapq.heappush(bfs, (operations, remaining))\n \n while bfs:\n operations, remaining = heapq.heappop(bfs)\n if remaining == 0:\n return operations\n if remaining in visited:\n continue\n visited.add(remaining)\n if x > remaining:\n push(operations + abs(min((x - remaining) * 2, remaining * 2 - 1)), 0)\n continue\n result, current, prev = 0, x, None\n while current < remaining:\n prev = current\n current *= x\n result += 1\n \n push(operations + result + (current != remaining), current - remaining)\n if prev is not None:\n push(operations + result, remaining - prev)\n\n``` | 0 | Given a single positive integer `x`, we will write an expression of the form `x (op1) x (op2) x (op3) x ...` where each operator `op1`, `op2`, etc. is either addition, subtraction, multiplication, or division (`+`, `-`, `*`, or `/)`. For example, with `x = 3`, we might write `3 * 3 / 3 + 3 - 3` which is a value of 3.
When writing such an expression, we adhere to the following conventions:
* The division operator (`/`) returns rational numbers.
* There are no parentheses placed anywhere.
* We use the usual order of operations: multiplication and division happen before addition and subtraction.
* It is not allowed to use the unary negation operator (`-`). For example, "`x - x` " is a valid expression as it only uses subtraction, but "`-x + x` " is not because it uses negation.
We would like to write an expression with the least number of operators such that the expression equals the given `target`. Return the least number of operators used.
**Example 1:**
**Input:** x = 3, target = 19
**Output:** 5
**Explanation:** 3 \* 3 + 3 \* 3 + 3 / 3.
The expression contains 5 operations.
**Example 2:**
**Input:** x = 5, target = 501
**Output:** 8
**Explanation:** 5 \* 5 \* 5 \* 5 - 5 \* 5 \* 5 + 5 / 5.
The expression contains 8 operations.
**Example 3:**
**Input:** x = 100, target = 100000000
**Output:** 3
**Explanation:** 100 \* 100 \* 100 \* 100.
The expression contains 3 operations.
**Constraints:**
* `2 <= x <= 100`
* `1 <= target <= 2 * 108` | null |
Python heapq beats 80% time/space | least-operators-to-express-number | 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```\nimport heapq\n\nclass Solution:\n def leastOpsExpressTarget(self, x: int, target: int) -> int:\n bfs = [(0, target)]\n visited = set()\n def push(operations, remaining):\n heapq.heappush(bfs, (operations, remaining))\n \n while bfs:\n operations, remaining = heapq.heappop(bfs)\n if remaining == 0:\n return operations\n if remaining in visited:\n continue\n visited.add(remaining)\n if x > remaining:\n push(operations + abs(min((x - remaining) * 2, remaining * 2 - 1)), 0)\n continue\n result, current, prev = 0, x, None\n while current < remaining:\n prev = current\n current *= x\n result += 1\n \n push(operations + result + (current != remaining), current - remaining)\n if prev is not None:\n push(operations + result, remaining - prev)\n\n``` | 0 | Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length` | null |
PYTHON SOL || RECURSION + MEMOIZATION || WELL EXPLAINED || APPROACH EXPLAINED || WELL COMMENTED || | least-operators-to-express-number | 0 | 1 | # EXPLANATION\n```\nSay number = x and target = target\n\nWhen target == 1: we can make it by using only one way i.e. x/x\nNow we start with our current value cur = x\n\nNow fastest way to reach the target is via multplication\n\t\tExample x = 5 target = 125\n\t\tWhat is the fastest way to reach 125 with x = 5 and operations = (/,*,+,-)\n\t\tWe can try 5*5*5 using only 2 operators\n\ndeclare op = 0 (operators used )\nSo we multiply cur by x until cur >= target and do op += 1\n\nNow if cur == target : we can reach the target by operations = op\n\nIf op == 0:\n i.e. during the start the target was smaller than x\n example target = 2 and x = 3\n one way to reach the target is : 1 + solve(target - 1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t to make one we do x/x and inluding + operator we have used total 2 operators\n\nelse:\n i.e. we used * operator some no. of times\n so what we do is reach the nearest value to target via * such that reachede value < target\n i.e. say x = 3 and target = 12\n So we do multiply cur like 3*3*3 = 27 \n Now 27/3 is the nearest number smaller than target = 12 that we can reach via multiplication\n Now solve for ( target - cur/x) and 1 operation for + and op\n \nFinal check :\n if cur - target < target :\n i.e. we can reach target by substraction and division from cur\n\tSo tmp = op + 1 + solve(cur-target)\n\tif tmp is smaller than ans then ans = tmp\nfinally store ans of target in dp\nreturn ans\n```\n\n# CODE WITH COMMENTS\n```\nclass Solution:\n def solve(self,x,target):\n if target in self.dp : return self.dp[target]\n \n # when target == 1 we can solve just by doing x/x \n if target == 1: return 1\n \n # current value = x and operations performed = 0\n cur = x\n op = 0\n \n # if cur < target : the best decision is to multiply\n while cur < target: \n cur *= x\n op += 1\n \n # if cur == target : we reached using minimum possible operations \n if cur == target :\n return op\n \n if op == 0:\n # cur is already larger than target\n # x/x + make(target-1) : make 2 operations + solve(target-1)\n ans = 2 + self.solve(x,target - 1)\n else:\n # we try to reach nearest val via multiply less than target\n # and find ans for remaining i.e. target - cur/x \n # here op becomes op - 1 so op - 1 + 1 becomes op\n ans = op + self.solve(x,target-(cur//x))\n \n if cur - target < target :\n # diff between cur and target is less than target\n # i.e. we can make cur and remove cur - target\n tmp = op + 1 + self.solve(x,cur - target)\n if tmp < ans : ans = tmp\n \n # finally use dp for memoization\n self.dp[target] = ans\n return ans\n``` | 3 | Given a single positive integer `x`, we will write an expression of the form `x (op1) x (op2) x (op3) x ...` where each operator `op1`, `op2`, etc. is either addition, subtraction, multiplication, or division (`+`, `-`, `*`, or `/)`. For example, with `x = 3`, we might write `3 * 3 / 3 + 3 - 3` which is a value of 3.
When writing such an expression, we adhere to the following conventions:
* The division operator (`/`) returns rational numbers.
* There are no parentheses placed anywhere.
* We use the usual order of operations: multiplication and division happen before addition and subtraction.
* It is not allowed to use the unary negation operator (`-`). For example, "`x - x` " is a valid expression as it only uses subtraction, but "`-x + x` " is not because it uses negation.
We would like to write an expression with the least number of operators such that the expression equals the given `target`. Return the least number of operators used.
**Example 1:**
**Input:** x = 3, target = 19
**Output:** 5
**Explanation:** 3 \* 3 + 3 \* 3 + 3 / 3.
The expression contains 5 operations.
**Example 2:**
**Input:** x = 5, target = 501
**Output:** 8
**Explanation:** 5 \* 5 \* 5 \* 5 - 5 \* 5 \* 5 + 5 / 5.
The expression contains 8 operations.
**Example 3:**
**Input:** x = 100, target = 100000000
**Output:** 3
**Explanation:** 100 \* 100 \* 100 \* 100.
The expression contains 3 operations.
**Constraints:**
* `2 <= x <= 100`
* `1 <= target <= 2 * 108` | null |
PYTHON SOL || RECURSION + MEMOIZATION || WELL EXPLAINED || APPROACH EXPLAINED || WELL COMMENTED || | least-operators-to-express-number | 0 | 1 | # EXPLANATION\n```\nSay number = x and target = target\n\nWhen target == 1: we can make it by using only one way i.e. x/x\nNow we start with our current value cur = x\n\nNow fastest way to reach the target is via multplication\n\t\tExample x = 5 target = 125\n\t\tWhat is the fastest way to reach 125 with x = 5 and operations = (/,*,+,-)\n\t\tWe can try 5*5*5 using only 2 operators\n\ndeclare op = 0 (operators used )\nSo we multiply cur by x until cur >= target and do op += 1\n\nNow if cur == target : we can reach the target by operations = op\n\nIf op == 0:\n i.e. during the start the target was smaller than x\n example target = 2 and x = 3\n one way to reach the target is : 1 + solve(target - 1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t to make one we do x/x and inluding + operator we have used total 2 operators\n\nelse:\n i.e. we used * operator some no. of times\n so what we do is reach the nearest value to target via * such that reachede value < target\n i.e. say x = 3 and target = 12\n So we do multiply cur like 3*3*3 = 27 \n Now 27/3 is the nearest number smaller than target = 12 that we can reach via multiplication\n Now solve for ( target - cur/x) and 1 operation for + and op\n \nFinal check :\n if cur - target < target :\n i.e. we can reach target by substraction and division from cur\n\tSo tmp = op + 1 + solve(cur-target)\n\tif tmp is smaller than ans then ans = tmp\nfinally store ans of target in dp\nreturn ans\n```\n\n# CODE WITH COMMENTS\n```\nclass Solution:\n def solve(self,x,target):\n if target in self.dp : return self.dp[target]\n \n # when target == 1 we can solve just by doing x/x \n if target == 1: return 1\n \n # current value = x and operations performed = 0\n cur = x\n op = 0\n \n # if cur < target : the best decision is to multiply\n while cur < target: \n cur *= x\n op += 1\n \n # if cur == target : we reached using minimum possible operations \n if cur == target :\n return op\n \n if op == 0:\n # cur is already larger than target\n # x/x + make(target-1) : make 2 operations + solve(target-1)\n ans = 2 + self.solve(x,target - 1)\n else:\n # we try to reach nearest val via multiply less than target\n # and find ans for remaining i.e. target - cur/x \n # here op becomes op - 1 so op - 1 + 1 becomes op\n ans = op + self.solve(x,target-(cur//x))\n \n if cur - target < target :\n # diff between cur and target is less than target\n # i.e. we can make cur and remove cur - target\n tmp = op + 1 + self.solve(x,cur - target)\n if tmp < ans : ans = tmp\n \n # finally use dp for memoization\n self.dp[target] = ans\n return ans\n``` | 3 | Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length` | null |
Python || wow ! what's a Problem || conceptual solution with explanation | least-operators-to-express-number | 1 | 1 | ```\n# written by : Dhruv vavliya\n\nx = 5\ntarget = 501\n\nfrom functools import lru_cache\n@lru_cache(None)\ndef go(x,target):\n if target == 1:\n return 1 # 5/5 (only 1 possible soln)\n\n op =0\n current=x\n while current < target:\n current*=x # 5*5*5*5\n op+=1\n if current == target: # if target achieve\n return op\n\n # almost nearest target ,then increase\n if op == 0: # 5/5 + .... (2 operations)\n ans = 2 + go(x,target-1)\n else:\n ans = op + go(x,target-current//x) # (target-current) but current*5 extra multiplied\n\n # increase than target, then decrease\n if current-target < target: # if (current - target) lies outside of target then,only consider one case\n ans = min(ans ,op+1 + go(x,current-target)) # op+1 for additionally *x then decrease\n return ans\n\n\ndef express_number(x ,target):\n return go(x,target)\n\nprint(express_number(x,target))\n``` | 1 | Given a single positive integer `x`, we will write an expression of the form `x (op1) x (op2) x (op3) x ...` where each operator `op1`, `op2`, etc. is either addition, subtraction, multiplication, or division (`+`, `-`, `*`, or `/)`. For example, with `x = 3`, we might write `3 * 3 / 3 + 3 - 3` which is a value of 3.
When writing such an expression, we adhere to the following conventions:
* The division operator (`/`) returns rational numbers.
* There are no parentheses placed anywhere.
* We use the usual order of operations: multiplication and division happen before addition and subtraction.
* It is not allowed to use the unary negation operator (`-`). For example, "`x - x` " is a valid expression as it only uses subtraction, but "`-x + x` " is not because it uses negation.
We would like to write an expression with the least number of operators such that the expression equals the given `target`. Return the least number of operators used.
**Example 1:**
**Input:** x = 3, target = 19
**Output:** 5
**Explanation:** 3 \* 3 + 3 \* 3 + 3 / 3.
The expression contains 5 operations.
**Example 2:**
**Input:** x = 5, target = 501
**Output:** 8
**Explanation:** 5 \* 5 \* 5 \* 5 - 5 \* 5 \* 5 + 5 / 5.
The expression contains 8 operations.
**Example 3:**
**Input:** x = 100, target = 100000000
**Output:** 3
**Explanation:** 100 \* 100 \* 100 \* 100.
The expression contains 3 operations.
**Constraints:**
* `2 <= x <= 100`
* `1 <= target <= 2 * 108` | null |
Python || wow ! what's a Problem || conceptual solution with explanation | least-operators-to-express-number | 1 | 1 | ```\n# written by : Dhruv vavliya\n\nx = 5\ntarget = 501\n\nfrom functools import lru_cache\n@lru_cache(None)\ndef go(x,target):\n if target == 1:\n return 1 # 5/5 (only 1 possible soln)\n\n op =0\n current=x\n while current < target:\n current*=x # 5*5*5*5\n op+=1\n if current == target: # if target achieve\n return op\n\n # almost nearest target ,then increase\n if op == 0: # 5/5 + .... (2 operations)\n ans = 2 + go(x,target-1)\n else:\n ans = op + go(x,target-current//x) # (target-current) but current*5 extra multiplied\n\n # increase than target, then decrease\n if current-target < target: # if (current - target) lies outside of target then,only consider one case\n ans = min(ans ,op+1 + go(x,current-target)) # op+1 for additionally *x then decrease\n return ans\n\n\ndef express_number(x ,target):\n return go(x,target)\n\nprint(express_number(x,target))\n``` | 1 | Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length` | null |
Solution | univalued-binary-tree | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n bool isUnivalTree(TreeNode* root) {\n if(root==NULL)\n return true;\n if(root->left == NULL && root->right == NULL)\n return true;\n bool left = isUnivalTree(root->left);\n bool right = isUnivalTree(root->right);\n bool curr;\n if(root->left && root->right)\n curr = (root->left->val == root->right->val) && (root->val == root->left->val);\n else if(root->left)\n curr = root->left->val == root->val;\n else\n curr = root->right->val == root->val;\n if(left && right && curr)\n return true;\n return false;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def isUnivalTree(self, root: Optional[TreeNode]) -> bool:\n if not root:\n return True\n\n if root.left:\n if root.val != root.left.val:\n return False\n\n if root.right:\n if root.val != root.right.val:\n return False\n\n return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)\n```\n\n```Java []\nclass Solution {\n int val = -1;\n public boolean isUnivalTree(TreeNode root) {\n if(root == null){\n return true;\n }\n if(val == -1){\n val = root.val;\n }\n if(val != root.val){\n return false;\n }\n if(root.left == null && root.right == null){\n return true;\n }\n return isUnivalTree(root.left) && isUnivalTree(root.right);\n }\n}\n```\n | 1 | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `0 <= Node.val < 100` | null |
Solution | univalued-binary-tree | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n bool isUnivalTree(TreeNode* root) {\n if(root==NULL)\n return true;\n if(root->left == NULL && root->right == NULL)\n return true;\n bool left = isUnivalTree(root->left);\n bool right = isUnivalTree(root->right);\n bool curr;\n if(root->left && root->right)\n curr = (root->left->val == root->right->val) && (root->val == root->left->val);\n else if(root->left)\n curr = root->left->val == root->val;\n else\n curr = root->right->val == root->val;\n if(left && right && curr)\n return true;\n return false;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def isUnivalTree(self, root: Optional[TreeNode]) -> bool:\n if not root:\n return True\n\n if root.left:\n if root.val != root.left.val:\n return False\n\n if root.right:\n if root.val != root.right.val:\n return False\n\n return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)\n```\n\n```Java []\nclass Solution {\n int val = -1;\n public boolean isUnivalTree(TreeNode root) {\n if(root == null){\n return true;\n }\n if(val == -1){\n val = root.val;\n }\n if(val != root.val){\n return false;\n }\n if(root.left == null && root.right == null){\n return true;\n }\n return isUnivalTree(root.left) && isUnivalTree(root.right);\n }\n}\n```\n | 1 | Given an integer array `nums` and an integer `k`, modify the array in the following way:
* choose an index `i` and replace `nums[i]` with `-nums[i]`.
You should apply this process exactly `k` times. You may choose the same index `i` multiple times.
Return _the largest possible sum of the array after modifying it in this way_.
**Example 1:**
**Input:** nums = \[4,2,3\], k = 1
**Output:** 5
**Explanation:** Choose index 1 and nums becomes \[4,-2,3\].
**Example 2:**
**Input:** nums = \[3,-1,0,2\], k = 3
**Output:** 6
**Explanation:** Choose indices (1, 2, 2) and nums becomes \[3,1,0,2\].
**Example 3:**
**Input:** nums = \[2,-3,-1,5,-4\], k = 2
**Output:** 13
**Explanation:** Choose indices (1, 4) and nums becomes \[2,3,-1,5,4\].
**Constraints:**
* `1 <= nums.length <= 104`
* `-100 <= nums[i] <= 100`
* `1 <= k <= 104` | null |
Recursive Approach | univalued-binary-tree | 0 | 1 | \n\n# 1. Recursive Approach\n```\nclass Solution:\n def isUnivalTree(self, root: Optional[TreeNode]) -> bool:\n def unique(root,x):\n if not root:\n return True\n if root.val!=x:\n return False\n return unique(root.left,x) and unique(root.right,x)\n return unique(root,root.val)\n``` | 5 | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `0 <= Node.val < 100` | null |
Recursive Approach | univalued-binary-tree | 0 | 1 | \n\n# 1. Recursive Approach\n```\nclass Solution:\n def isUnivalTree(self, root: Optional[TreeNode]) -> bool:\n def unique(root,x):\n if not root:\n return True\n if root.val!=x:\n return False\n return unique(root.left,x) and unique(root.right,x)\n return unique(root,root.val)\n``` | 5 | Given an integer array `nums` and an integer `k`, modify the array in the following way:
* choose an index `i` and replace `nums[i]` with `-nums[i]`.
You should apply this process exactly `k` times. You may choose the same index `i` multiple times.
Return _the largest possible sum of the array after modifying it in this way_.
**Example 1:**
**Input:** nums = \[4,2,3\], k = 1
**Output:** 5
**Explanation:** Choose index 1 and nums becomes \[4,-2,3\].
**Example 2:**
**Input:** nums = \[3,-1,0,2\], k = 3
**Output:** 6
**Explanation:** Choose indices (1, 2, 2) and nums becomes \[3,1,0,2\].
**Example 3:**
**Input:** nums = \[2,-3,-1,5,-4\], k = 2
**Output:** 13
**Explanation:** Choose indices (1, 4) and nums becomes \[2,3,-1,5,4\].
**Constraints:**
* `1 <= nums.length <= 104`
* `-100 <= nums[i] <= 100`
* `1 <= k <= 104` | null |
Python || Easy To Understand || Inorder Traversal 🔥 | univalued-binary-tree | 0 | 1 | # Code\n```\nclass Solution:\n def isUnivalTree(self, root: Optional[TreeNode]) -> bool:\n val = root.val\n def inorder(root, val):\n if root is None: return True\n if root.val != val: return False\n return inorder(root.left, val) and inorder(root.right, val)\n return True if inorder(root, val)!=False else False\n``` | 3 | A binary tree is **uni-valued** if every node in the tree has the same value.
Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._
**Example 1:**
**Input:** root = \[1,1,1,1,1,null,1\]
**Output:** true
**Example 2:**
**Input:** root = \[2,2,2,5,2\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `0 <= Node.val < 100` | null |
Python || Easy To Understand || Inorder Traversal 🔥 | univalued-binary-tree | 0 | 1 | # Code\n```\nclass Solution:\n def isUnivalTree(self, root: Optional[TreeNode]) -> bool:\n val = root.val\n def inorder(root, val):\n if root is None: return True\n if root.val != val: return False\n return inorder(root.left, val) and inorder(root.right, val)\n return True if inorder(root, val)!=False else False\n``` | 3 | Given an integer array `nums` and an integer `k`, modify the array in the following way:
* choose an index `i` and replace `nums[i]` with `-nums[i]`.
You should apply this process exactly `k` times. You may choose the same index `i` multiple times.
Return _the largest possible sum of the array after modifying it in this way_.
**Example 1:**
**Input:** nums = \[4,2,3\], k = 1
**Output:** 5
**Explanation:** Choose index 1 and nums becomes \[4,-2,3\].
**Example 2:**
**Input:** nums = \[3,-1,0,2\], k = 3
**Output:** 6
**Explanation:** Choose indices (1, 2, 2) and nums becomes \[3,1,0,2\].
**Example 3:**
**Input:** nums = \[2,-3,-1,5,-4\], k = 2
**Output:** 13
**Explanation:** Choose indices (1, 4) and nums becomes \[2,3,-1,5,4\].
**Constraints:**
* `1 <= nums.length <= 104`
* `-100 <= nums[i] <= 100`
* `1 <= k <= 104` | null |
Python 3 || 14 lines, w/ comments || T/M: 95% / 74% | vowel-spellchecker | 0 | 1 | ```\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n\n f = lambda x: \'\'.join(\'$\' if ch in \'aeiou\' else ch for ch in x)\n cap, vow = defaultdict(str), defaultdict(str)\n word_set, ans = set(wordlist), []\n \n for w in wordlist: # Build the dicts\n\n wLow = w.lower()\n if not cap[wLow]: cap[wLow] = w # <\u2013\u2013 Case 1: capital-check\n\n wVow = f(wLow)\n if not vow[wVow]: vow[wVow] = w # <\u2013\u2013 Case 2: vowel-check\n\n for q in queries:\n qLow, qVow, res = q.lower(), f(q.lower()), \'\'\n\n if q in word_set: res = q # <\u2013\u2013 word is in wordlist\n elif qLow in cap: res = cap[qLow] # <\u2013\u2013 cap-checked word is in wordlist\n elif qVow in vow: res = vow[qVow] # <\u2013\u2013 vowel-checked word is in wordlist\n\n ans.append(res)\n```\n[https://leetcode.com/problems/vowel-spellchecker/submissions/859821635/](http://)\n\nI could be wrong, but I think that time is *O*(*N*) and space is *O*(*N*). | 3 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist.
* Example: `wordlist = [ "yellow "]`, `query = "YellOw "`: `correct = "yellow "`
* Example: `wordlist = [ "Yellow "]`, `query = "yellow "`: `correct = "Yellow "`
* Example: `wordlist = [ "yellow "]`, `query = "yellow "`: `correct = "yellow "`
* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist.
* Example: `wordlist = [ "YellOw "]`, `query = "yollow "`: `correct = "YellOw "`
* Example: `wordlist = [ "YellOw "]`, `query = "yeellow "`: `correct = " "` (no match)
* Example: `wordlist = [ "YellOw "]`, `query = "yllw "`: `correct = " "` (no match)
In addition, the spell checker operates under the following precedence rules:
* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back.
* When the query matches a word up to capitlization, you should return the first such match in the wordlist.
* When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
* If the query has no matches in the wordlist, you should return the empty string.
Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`.
**Example 1:**
**Input:** wordlist = \["KiTe","kite","hare","Hare"\], queries = \["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"\]
**Output:** \["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"\]
**Example 2:**
**Input:** wordlist = \["yellow"\], queries = \["YellOw"\]
**Output:** \["yellow"\]
**Constraints:**
* `1 <= wordlist.length, queries.length <= 5000`
* `1 <= wordlist[i].length, queries[i].length <= 7`
* `wordlist[i]` and `queries[i]` consist only of only English letters. | null |
Python 3 || 14 lines, w/ comments || T/M: 95% / 74% | vowel-spellchecker | 0 | 1 | ```\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n\n f = lambda x: \'\'.join(\'$\' if ch in \'aeiou\' else ch for ch in x)\n cap, vow = defaultdict(str), defaultdict(str)\n word_set, ans = set(wordlist), []\n \n for w in wordlist: # Build the dicts\n\n wLow = w.lower()\n if not cap[wLow]: cap[wLow] = w # <\u2013\u2013 Case 1: capital-check\n\n wVow = f(wLow)\n if not vow[wVow]: vow[wVow] = w # <\u2013\u2013 Case 2: vowel-check\n\n for q in queries:\n qLow, qVow, res = q.lower(), f(q.lower()), \'\'\n\n if q in word_set: res = q # <\u2013\u2013 word is in wordlist\n elif qLow in cap: res = cap[qLow] # <\u2013\u2013 cap-checked word is in wordlist\n elif qVow in vow: res = vow[qVow] # <\u2013\u2013 vowel-checked word is in wordlist\n\n ans.append(res)\n```\n[https://leetcode.com/problems/vowel-spellchecker/submissions/859821635/](http://)\n\nI could be wrong, but I think that time is *O*(*N*) and space is *O*(*N*). | 3 | The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.
* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.
We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order.
* For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`.
Given an integer `n`, return _the clumsy factorial of_ `n`.
**Example 1:**
**Input:** n = 4
**Output:** 7
**Explanation:** 7 = 4 \* 3 / 2 + 1
**Example 2:**
**Input:** n = 10
**Output:** 12
**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1
**Constraints:**
* `1 <= n <= 104` | null |
Solution | vowel-spellchecker | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) {\n unordered_set<string> exact;\n unordered_map<string, string> cap, vow;\n \n for(string &s : wordlist){\n exact.insert(s);\n string s2 = s;\n transform(s2.begin(), s2.end(), s2.begin(), ::tolower);\n if(!cap.count(s2)) cap[s2] = s;\n for(char &ch : s2){\n if(ch == \'a\' || ch ==\'e\' || ch == \'i\' || ch == \'o\' || ch == \'u\') ch = \'*\';\n }\n if(!vow.count(s2)) vow[s2] = s;\n }\n vector<string> res(queries.size(), "");\n for(int i = 0; i < queries.size(); i++){\n if(exact.count(queries[i])) {\n res[i] = queries[i];\n continue;\n }\n string s = queries[i];\n transform(s.begin(), s.end(), s.begin(), ::tolower);\n if(cap.count(s)) {\n res[i] = cap[s];\n continue;\n }\n for(char &ch : s){\n if(ch == \'a\' || ch ==\'e\' || ch == \'i\' || ch == \'o\' || ch == \'u\') ch = \'*\';\n }\n if(vow.count(s)) res[i] = vow[s];\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n capital={i.lower():i for i in wordlist[::-1]}\n vovel={\'\'.join([j if j not in "aeiou" else \'.\' for j in i.lower()]):i for i in wordlist[::-1]}\n wordlist=set(wordlist)\n res=[]\n for i in queries:\n if i in wordlist:\n res.append(i)\n elif i.lower() in capital:\n res.append(capital[i.lower()])\n elif \'\'.join([j if j not in "aeiou" else \'.\' for j in i.lower()]) in vovel:\n res.append(vovel[\'\'.join([j if j not in "aeiou" else \'.\' for j in i.lower()])])\n else:\n res.append("")\n return res\n```\n\n```Java []\nclass Solution {\n\t\tstatic final int GAP = \'a\' - \'A\';\n public String[] spellchecker(String[] wordlist, String[] queries) {\n Map<Long, String> wordMap = new HashMap<>(wordlist.length << 1), capMap = new HashMap<>(wordlist.length << 1), vowelMap = new HashMap<>(wordlist.length << 1);\n\t\t\t\tfor (String word : wordlist) {\n\t\t\t\t\tlong hash = 0, capHash = 0, vowelHash = 0;\n\t\t\t\t\tfor (int i = 0, length = word.length(), c; i < length; ) {\n\t\t\t\t\t\thash = (hash << 7) | (c = word.charAt(i++));\n\t\t\t\t\t\tcapHash = (capHash << 7) | (c < \'a\' ? c += GAP : c);\n\t\t\t\t\t\tvowelHash = c == \'a\' || c == \'e\' || c == \'i\' || c == \'o\' || c == \'u\' ? (vowelHash << 7) : (vowelHash << 7) | c;\n\t\t\t\t\t}\n\t\t\t\t\twordMap.put(hash, word);\n\t\t\t\t\tcapMap.putIfAbsent(capHash, word);\n\t\t\t\t\tvowelMap.putIfAbsent(vowelHash, word);\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < queries.length; i++) {\n\t\t\t\t\tlong hash = 0, capHash = 0, vowelHash = 0;\n\t\t\t\t\tfor (int j = 0, length = queries[i].length(), c; j < length; ) {\n\t\t\t\t\t\thash = (hash << 7) | (c = queries[i].charAt(j++));\n\t\t\t\t\t\tcapHash = (capHash << 7) | (c < \'a\' ? c += GAP : c);\n\t\t\t\t\t\tvowelHash = c == \'a\' || c == \'e\' || c == \'i\' || c == \'o\' || c == \'u\' ? (vowelHash << 7) : (vowelHash << 7) | c;\n\t\t\t\t\t}\n if (wordMap.containsKey(hash)) continue;\n\t\t\t\t\tString word = capMap.get(capHash);\n\t\t\t queries[i] = word != null ? word : vowelMap.getOrDefault(vowelHash, "");\n\t\t\t\t}\n\t\t\t\treturn queries;\n }\n}\n```\n | 1 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist.
* Example: `wordlist = [ "yellow "]`, `query = "YellOw "`: `correct = "yellow "`
* Example: `wordlist = [ "Yellow "]`, `query = "yellow "`: `correct = "Yellow "`
* Example: `wordlist = [ "yellow "]`, `query = "yellow "`: `correct = "yellow "`
* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist.
* Example: `wordlist = [ "YellOw "]`, `query = "yollow "`: `correct = "YellOw "`
* Example: `wordlist = [ "YellOw "]`, `query = "yeellow "`: `correct = " "` (no match)
* Example: `wordlist = [ "YellOw "]`, `query = "yllw "`: `correct = " "` (no match)
In addition, the spell checker operates under the following precedence rules:
* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back.
* When the query matches a word up to capitlization, you should return the first such match in the wordlist.
* When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
* If the query has no matches in the wordlist, you should return the empty string.
Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`.
**Example 1:**
**Input:** wordlist = \["KiTe","kite","hare","Hare"\], queries = \["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"\]
**Output:** \["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"\]
**Example 2:**
**Input:** wordlist = \["yellow"\], queries = \["YellOw"\]
**Output:** \["yellow"\]
**Constraints:**
* `1 <= wordlist.length, queries.length <= 5000`
* `1 <= wordlist[i].length, queries[i].length <= 7`
* `wordlist[i]` and `queries[i]` consist only of only English letters. | null |
Solution | vowel-spellchecker | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<string> spellchecker(vector<string>& wordlist, vector<string>& queries) {\n unordered_set<string> exact;\n unordered_map<string, string> cap, vow;\n \n for(string &s : wordlist){\n exact.insert(s);\n string s2 = s;\n transform(s2.begin(), s2.end(), s2.begin(), ::tolower);\n if(!cap.count(s2)) cap[s2] = s;\n for(char &ch : s2){\n if(ch == \'a\' || ch ==\'e\' || ch == \'i\' || ch == \'o\' || ch == \'u\') ch = \'*\';\n }\n if(!vow.count(s2)) vow[s2] = s;\n }\n vector<string> res(queries.size(), "");\n for(int i = 0; i < queries.size(); i++){\n if(exact.count(queries[i])) {\n res[i] = queries[i];\n continue;\n }\n string s = queries[i];\n transform(s.begin(), s.end(), s.begin(), ::tolower);\n if(cap.count(s)) {\n res[i] = cap[s];\n continue;\n }\n for(char &ch : s){\n if(ch == \'a\' || ch ==\'e\' || ch == \'i\' || ch == \'o\' || ch == \'u\') ch = \'*\';\n }\n if(vow.count(s)) res[i] = vow[s];\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n capital={i.lower():i for i in wordlist[::-1]}\n vovel={\'\'.join([j if j not in "aeiou" else \'.\' for j in i.lower()]):i for i in wordlist[::-1]}\n wordlist=set(wordlist)\n res=[]\n for i in queries:\n if i in wordlist:\n res.append(i)\n elif i.lower() in capital:\n res.append(capital[i.lower()])\n elif \'\'.join([j if j not in "aeiou" else \'.\' for j in i.lower()]) in vovel:\n res.append(vovel[\'\'.join([j if j not in "aeiou" else \'.\' for j in i.lower()])])\n else:\n res.append("")\n return res\n```\n\n```Java []\nclass Solution {\n\t\tstatic final int GAP = \'a\' - \'A\';\n public String[] spellchecker(String[] wordlist, String[] queries) {\n Map<Long, String> wordMap = new HashMap<>(wordlist.length << 1), capMap = new HashMap<>(wordlist.length << 1), vowelMap = new HashMap<>(wordlist.length << 1);\n\t\t\t\tfor (String word : wordlist) {\n\t\t\t\t\tlong hash = 0, capHash = 0, vowelHash = 0;\n\t\t\t\t\tfor (int i = 0, length = word.length(), c; i < length; ) {\n\t\t\t\t\t\thash = (hash << 7) | (c = word.charAt(i++));\n\t\t\t\t\t\tcapHash = (capHash << 7) | (c < \'a\' ? c += GAP : c);\n\t\t\t\t\t\tvowelHash = c == \'a\' || c == \'e\' || c == \'i\' || c == \'o\' || c == \'u\' ? (vowelHash << 7) : (vowelHash << 7) | c;\n\t\t\t\t\t}\n\t\t\t\t\twordMap.put(hash, word);\n\t\t\t\t\tcapMap.putIfAbsent(capHash, word);\n\t\t\t\t\tvowelMap.putIfAbsent(vowelHash, word);\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < queries.length; i++) {\n\t\t\t\t\tlong hash = 0, capHash = 0, vowelHash = 0;\n\t\t\t\t\tfor (int j = 0, length = queries[i].length(), c; j < length; ) {\n\t\t\t\t\t\thash = (hash << 7) | (c = queries[i].charAt(j++));\n\t\t\t\t\t\tcapHash = (capHash << 7) | (c < \'a\' ? c += GAP : c);\n\t\t\t\t\t\tvowelHash = c == \'a\' || c == \'e\' || c == \'i\' || c == \'o\' || c == \'u\' ? (vowelHash << 7) : (vowelHash << 7) | c;\n\t\t\t\t\t}\n if (wordMap.containsKey(hash)) continue;\n\t\t\t\t\tString word = capMap.get(capHash);\n\t\t\t queries[i] = word != null ? word : vowelMap.getOrDefault(vowelHash, "");\n\t\t\t\t}\n\t\t\t\treturn queries;\n }\n}\n```\n | 1 | The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.
* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.
We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order.
* For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`.
Given an integer `n`, return _the clumsy factorial of_ `n`.
**Example 1:**
**Input:** n = 4
**Output:** 7
**Explanation:** 7 = 4 \* 3 / 2 + 1
**Example 2:**
**Input:** n = 10
**Output:** 12
**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1
**Constraints:**
* `1 <= n <= 104` | null |
[Python] One Case At A Time | vowel-spellchecker | 0 | 1 | **Approach:**\n\nThere are 4 possible scenarios for each word, we can try them in order of priority:\n1. The word matches a word in `wordlist`\nCreating a set of `wordlist` allows us to check if this is true in O(1) time.\n\n2. The word matches a word in `wordlist` up to capitalization.\nConvert the word to lowercase letters and check if the word is in\n`case_insensitive`, if so, use the first word that matches with case insensitivity.\n\n3. The word matches up to vowel errors.\nMask the word by converting all characters to lower case and all vowels to `\'*\'`.\nCheck if this mask is in `vowel_insensitive`. If so, use the first word that matches with vowel insensitivity.\n\n4. None of the above are true, we add an empty string to res.\n\n```python\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n \n # Convert words and vowels to sets for O(1) lookup times\n words = set(wordlist)\n vowels = set(\'aeiouAEIOU\')\n \n # Create two maps. \n # One for case insensitive word to all words that match "key" -> ["Key", "kEy", "KEY"]\n # The other for vowel insensitive words "k*t*" -> ["Kite", "kato", "KUTA"]\n case_insensitive = collections.defaultdict(list) \n vowel_insensitive = collections.defaultdict(list)\n for word in wordlist:\n case_insensitive[word.lower()].append(word)\n key = \'\'.join(char.lower() if char not in vowels else \'*\' for char in word)\n vowel_insensitive[key].append(word)\n\n res = []\n for word in queries:\n\n # Case 1: When query exactly matches a word\n if word in words:\n res.append(word)\n continue\n\n # Case 2: When query matches a word up to capitalization\n low = word.lower()\n if low in case_insensitive:\n res.append(case_insensitive[low][0])\n continue\n\n # Case 3: When query matches a word up to vowel errors\n key = \'\'.join(char.lower() if char not in vowels else \'*\' for char in word)\n if key in vowel_insensitive:\n res.append(vowel_insensitive[key][0])\n continue\n\n res.append(\'\')\n\n return res\n``` | 5 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist.
* Example: `wordlist = [ "yellow "]`, `query = "YellOw "`: `correct = "yellow "`
* Example: `wordlist = [ "Yellow "]`, `query = "yellow "`: `correct = "Yellow "`
* Example: `wordlist = [ "yellow "]`, `query = "yellow "`: `correct = "yellow "`
* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist.
* Example: `wordlist = [ "YellOw "]`, `query = "yollow "`: `correct = "YellOw "`
* Example: `wordlist = [ "YellOw "]`, `query = "yeellow "`: `correct = " "` (no match)
* Example: `wordlist = [ "YellOw "]`, `query = "yllw "`: `correct = " "` (no match)
In addition, the spell checker operates under the following precedence rules:
* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back.
* When the query matches a word up to capitlization, you should return the first such match in the wordlist.
* When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
* If the query has no matches in the wordlist, you should return the empty string.
Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`.
**Example 1:**
**Input:** wordlist = \["KiTe","kite","hare","Hare"\], queries = \["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"\]
**Output:** \["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"\]
**Example 2:**
**Input:** wordlist = \["yellow"\], queries = \["YellOw"\]
**Output:** \["yellow"\]
**Constraints:**
* `1 <= wordlist.length, queries.length <= 5000`
* `1 <= wordlist[i].length, queries[i].length <= 7`
* `wordlist[i]` and `queries[i]` consist only of only English letters. | null |
[Python] One Case At A Time | vowel-spellchecker | 0 | 1 | **Approach:**\n\nThere are 4 possible scenarios for each word, we can try them in order of priority:\n1. The word matches a word in `wordlist`\nCreating a set of `wordlist` allows us to check if this is true in O(1) time.\n\n2. The word matches a word in `wordlist` up to capitalization.\nConvert the word to lowercase letters and check if the word is in\n`case_insensitive`, if so, use the first word that matches with case insensitivity.\n\n3. The word matches up to vowel errors.\nMask the word by converting all characters to lower case and all vowels to `\'*\'`.\nCheck if this mask is in `vowel_insensitive`. If so, use the first word that matches with vowel insensitivity.\n\n4. None of the above are true, we add an empty string to res.\n\n```python\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n \n # Convert words and vowels to sets for O(1) lookup times\n words = set(wordlist)\n vowels = set(\'aeiouAEIOU\')\n \n # Create two maps. \n # One for case insensitive word to all words that match "key" -> ["Key", "kEy", "KEY"]\n # The other for vowel insensitive words "k*t*" -> ["Kite", "kato", "KUTA"]\n case_insensitive = collections.defaultdict(list) \n vowel_insensitive = collections.defaultdict(list)\n for word in wordlist:\n case_insensitive[word.lower()].append(word)\n key = \'\'.join(char.lower() if char not in vowels else \'*\' for char in word)\n vowel_insensitive[key].append(word)\n\n res = []\n for word in queries:\n\n # Case 1: When query exactly matches a word\n if word in words:\n res.append(word)\n continue\n\n # Case 2: When query matches a word up to capitalization\n low = word.lower()\n if low in case_insensitive:\n res.append(case_insensitive[low][0])\n continue\n\n # Case 3: When query matches a word up to vowel errors\n key = \'\'.join(char.lower() if char not in vowels else \'*\' for char in word)\n if key in vowel_insensitive:\n res.append(vowel_insensitive[key][0])\n continue\n\n res.append(\'\')\n\n return res\n``` | 5 | The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.
* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.
We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order.
* For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`.
Given an integer `n`, return _the clumsy factorial of_ `n`.
**Example 1:**
**Input:** n = 4
**Output:** 7
**Explanation:** 7 = 4 \* 3 / 2 + 1
**Example 2:**
**Input:** n = 10
**Output:** 12
**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1
**Constraints:**
* `1 <= n <= 104` | null |
[Python3] Good enough | vowel-spellchecker | 0 | 1 | ``` Python3 []\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n seen = set()\n lower = {}\n mapping = {}\n final = []\n\n def convert(word: str) -> Tuple[str]:\n word = list(word.lower())\n\n for i in range(len(word)):\n if word[i] in \'aeiou\':\n word[i] = \'\'\n \n return tuple(word)\n\n for x in wordlist:\n seen.add(x)\n if x.lower() not in lower:\n lower[x.lower()] = x\n converted = convert(x)\n mapping[converted] = mapping.get(converted, [])\n mapping[converted].append(x)\n \n for x in queries:\n if x in seen:\n final.append(x)\n elif x.lower() in lower:\n final.append(lower[x.lower()])\n elif convert(x) in mapping:\n final.append(mapping[convert(x)][0])\n else:\n final.append(\'\')\n \n return final\n``` | 0 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist.
* Example: `wordlist = [ "yellow "]`, `query = "YellOw "`: `correct = "yellow "`
* Example: `wordlist = [ "Yellow "]`, `query = "yellow "`: `correct = "Yellow "`
* Example: `wordlist = [ "yellow "]`, `query = "yellow "`: `correct = "yellow "`
* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist.
* Example: `wordlist = [ "YellOw "]`, `query = "yollow "`: `correct = "YellOw "`
* Example: `wordlist = [ "YellOw "]`, `query = "yeellow "`: `correct = " "` (no match)
* Example: `wordlist = [ "YellOw "]`, `query = "yllw "`: `correct = " "` (no match)
In addition, the spell checker operates under the following precedence rules:
* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back.
* When the query matches a word up to capitlization, you should return the first such match in the wordlist.
* When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
* If the query has no matches in the wordlist, you should return the empty string.
Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`.
**Example 1:**
**Input:** wordlist = \["KiTe","kite","hare","Hare"\], queries = \["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"\]
**Output:** \["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"\]
**Example 2:**
**Input:** wordlist = \["yellow"\], queries = \["YellOw"\]
**Output:** \["yellow"\]
**Constraints:**
* `1 <= wordlist.length, queries.length <= 5000`
* `1 <= wordlist[i].length, queries[i].length <= 7`
* `wordlist[i]` and `queries[i]` consist only of only English letters. | null |
[Python3] Good enough | vowel-spellchecker | 0 | 1 | ``` Python3 []\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n seen = set()\n lower = {}\n mapping = {}\n final = []\n\n def convert(word: str) -> Tuple[str]:\n word = list(word.lower())\n\n for i in range(len(word)):\n if word[i] in \'aeiou\':\n word[i] = \'\'\n \n return tuple(word)\n\n for x in wordlist:\n seen.add(x)\n if x.lower() not in lower:\n lower[x.lower()] = x\n converted = convert(x)\n mapping[converted] = mapping.get(converted, [])\n mapping[converted].append(x)\n \n for x in queries:\n if x in seen:\n final.append(x)\n elif x.lower() in lower:\n final.append(lower[x.lower()])\n elif convert(x) in mapping:\n final.append(mapping[convert(x)][0])\n else:\n final.append(\'\')\n \n return final\n``` | 0 | The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.
* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.
We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order.
* For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`.
Given an integer `n`, return _the clumsy factorial of_ `n`.
**Example 1:**
**Input:** n = 4
**Output:** 7
**Explanation:** 7 = 4 \* 3 / 2 + 1
**Example 2:**
**Input:** n = 10
**Output:** 12
**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1
**Constraints:**
* `1 <= n <= 104` | null |
Logical Elimination For Speed Up | Commented and Explained | vowel-spellchecker | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe set of all unique words in wordlist is a subset of all words in wordlist\nThe set of all lower unique words in wordlist is a subset of all unique words in word list \nThe set of all decapitalized and devoweled lower unique words in wordlist is a subset of all lower unique words in word list, BUT these words may be encountered before those in their superset \n\nBy thinking in terms of sets and presence in groupings, we can utilize this to advance our progression through the wordlist. Any word we have encountered before, we can skip. This also can apply to whether or not to update our words lower and words decapitalized \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMake generics for devoweling and in grouping as needed \nMake a collection (faster then set) of Counter for the wordlist \nMake a map of words visited of word -> 0 for word in word list collection\nMake a words lower and words decap devowel listing \n\n- For word in wordlist \n - if you\'ve visited, skip it \n - Otherwise, get the word lower \n - If words visited at word lower is 0\n - mark words lower mapping at word lower to word \n - do similar for decap devowel \n - and update visited \n\nSet result as a list of strings of size queries \n- enumerate index and query in queries \n- if in grouping words perfect \n - result at index is query \n- otherwise \n - get lower \n - if lower in grouping words lower \n - result at index is words lower at lower \n - otherwise \n - result at index is either words decap devowl at decap devowel of lower or "" (use get function and default) \n\nreturn result \n\n# Complexity\n- Time complexity : O(W) to build word list \n\n- Space complexity : O(3W) \n - word list, word lower, word decap devowel \n\n# Code\n```\nclass Solution :\n def spellchecker(self, wordlist : List[ str ], queries : List[ str ]) -> List[ str ] :\n # devowel method as a join of characters \n devowel = lambda word : "".join("_" if c in "aeiou" else c for c in word)\n # in grouping method for various types of containers \n in_grouping = lambda item, grouping : item in grouping \n # get all the words and their frequencies \n words_perfect = collections.Counter(wordlist)\n words_visited = {word_key : 0 for word_key in words_perfect}\n # get lower and lower with no vowels \n words_lower = {}\n words_decap_devowel = {} \n # by looping over words\n for word in wordlist : \n # if we\'ve visited, skip it \n if words_visited[word] > 0 : \n continue \n else : \n # otherwise, do lower first \n wL = word.lower()\n if words_visited.get(wL, 0) == 0 : \n words_lower[wL] = word \n words_visited[wL] = 1 \n # then devowel it \n wLV = devowel(wL) \n if words_visited.get(wLV, 0) == 0 : \n words_decap_devowel[wLV] = word \n words_visited[wLV] = 1 \n # then mark visited \n words_visited[word] = 1 \n\n # build result \n result = [""]*len(queries) \n # by looping over queries \n for index, query in enumerate(queries) : \n # if we have this word exactly, add it \n if in_grouping(query, words_perfect) : \n result[index] = query\n else : \n # if we have the lower form of it, add it\'s lower form \n qL = query.lower()\n if in_grouping(qL, words_lower) : \n result[index] = words_lower[qL]\n else : \n # if we have the devoweld lower form add that \n # otherwise, add "" \n result[index] = words_decap_devowel.get(devowel(qL), "")\n # return result \n return result \n``` | 0 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist.
* Example: `wordlist = [ "yellow "]`, `query = "YellOw "`: `correct = "yellow "`
* Example: `wordlist = [ "Yellow "]`, `query = "yellow "`: `correct = "Yellow "`
* Example: `wordlist = [ "yellow "]`, `query = "yellow "`: `correct = "yellow "`
* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist.
* Example: `wordlist = [ "YellOw "]`, `query = "yollow "`: `correct = "YellOw "`
* Example: `wordlist = [ "YellOw "]`, `query = "yeellow "`: `correct = " "` (no match)
* Example: `wordlist = [ "YellOw "]`, `query = "yllw "`: `correct = " "` (no match)
In addition, the spell checker operates under the following precedence rules:
* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back.
* When the query matches a word up to capitlization, you should return the first such match in the wordlist.
* When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
* If the query has no matches in the wordlist, you should return the empty string.
Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`.
**Example 1:**
**Input:** wordlist = \["KiTe","kite","hare","Hare"\], queries = \["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"\]
**Output:** \["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"\]
**Example 2:**
**Input:** wordlist = \["yellow"\], queries = \["YellOw"\]
**Output:** \["yellow"\]
**Constraints:**
* `1 <= wordlist.length, queries.length <= 5000`
* `1 <= wordlist[i].length, queries[i].length <= 7`
* `wordlist[i]` and `queries[i]` consist only of only English letters. | null |
Logical Elimination For Speed Up | Commented and Explained | vowel-spellchecker | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe set of all unique words in wordlist is a subset of all words in wordlist\nThe set of all lower unique words in wordlist is a subset of all unique words in word list \nThe set of all decapitalized and devoweled lower unique words in wordlist is a subset of all lower unique words in word list, BUT these words may be encountered before those in their superset \n\nBy thinking in terms of sets and presence in groupings, we can utilize this to advance our progression through the wordlist. Any word we have encountered before, we can skip. This also can apply to whether or not to update our words lower and words decapitalized \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMake generics for devoweling and in grouping as needed \nMake a collection (faster then set) of Counter for the wordlist \nMake a map of words visited of word -> 0 for word in word list collection\nMake a words lower and words decap devowel listing \n\n- For word in wordlist \n - if you\'ve visited, skip it \n - Otherwise, get the word lower \n - If words visited at word lower is 0\n - mark words lower mapping at word lower to word \n - do similar for decap devowel \n - and update visited \n\nSet result as a list of strings of size queries \n- enumerate index and query in queries \n- if in grouping words perfect \n - result at index is query \n- otherwise \n - get lower \n - if lower in grouping words lower \n - result at index is words lower at lower \n - otherwise \n - result at index is either words decap devowl at decap devowel of lower or "" (use get function and default) \n\nreturn result \n\n# Complexity\n- Time complexity : O(W) to build word list \n\n- Space complexity : O(3W) \n - word list, word lower, word decap devowel \n\n# Code\n```\nclass Solution :\n def spellchecker(self, wordlist : List[ str ], queries : List[ str ]) -> List[ str ] :\n # devowel method as a join of characters \n devowel = lambda word : "".join("_" if c in "aeiou" else c for c in word)\n # in grouping method for various types of containers \n in_grouping = lambda item, grouping : item in grouping \n # get all the words and their frequencies \n words_perfect = collections.Counter(wordlist)\n words_visited = {word_key : 0 for word_key in words_perfect}\n # get lower and lower with no vowels \n words_lower = {}\n words_decap_devowel = {} \n # by looping over words\n for word in wordlist : \n # if we\'ve visited, skip it \n if words_visited[word] > 0 : \n continue \n else : \n # otherwise, do lower first \n wL = word.lower()\n if words_visited.get(wL, 0) == 0 : \n words_lower[wL] = word \n words_visited[wL] = 1 \n # then devowel it \n wLV = devowel(wL) \n if words_visited.get(wLV, 0) == 0 : \n words_decap_devowel[wLV] = word \n words_visited[wLV] = 1 \n # then mark visited \n words_visited[word] = 1 \n\n # build result \n result = [""]*len(queries) \n # by looping over queries \n for index, query in enumerate(queries) : \n # if we have this word exactly, add it \n if in_grouping(query, words_perfect) : \n result[index] = query\n else : \n # if we have the lower form of it, add it\'s lower form \n qL = query.lower()\n if in_grouping(qL, words_lower) : \n result[index] = words_lower[qL]\n else : \n # if we have the devoweld lower form add that \n # otherwise, add "" \n result[index] = words_decap_devowel.get(devowel(qL), "")\n # return result \n return result \n``` | 0 | The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.
* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.
We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order.
* For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`.
Given an integer `n`, return _the clumsy factorial of_ `n`.
**Example 1:**
**Input:** n = 4
**Output:** 7
**Explanation:** 7 = 4 \* 3 / 2 + 1
**Example 2:**
**Input:** n = 10
**Output:** 12
**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1
**Constraints:**
* `1 <= n <= 104` | null |
[Python] Three dictionary to match the word; Explained | vowel-spellchecker | 0 | 1 | Dictionary 1 record the original form of word in the list, It is used for exactly matching;\n\nDictionary 2 record the lower case form of words in the list, only the location of the first word with the same lower cases form is recorded. It is for lower case matching;\n\nDictionary 3 record the word with vowel replaced form in the list. It is for lower case replacing matching.\n\n```\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n # build three dictionary for word matching\n dict1 = set(wordlist)\n dict2 = dict()\n dict3 = dict()\n \n for index, wd in enumerate(wordlist):\n lower_wd = wd.lower()\n if lower_wd not in dict2:\n # only track the first word\n dict2[lower_wd] = index\n \n ignore_vowel_wd = ""\n for c in lower_wd:\n if c in {\'a\', \'e\', \'i\', \'o\', \'u\'}:\n ignore_vowel_wd += "*"\n else:\n ignore_vowel_wd += c\n if ignore_vowel_wd not in dict3:\n # only track the first word\n dict3[ignore_vowel_wd] = index\n \n \n ans = []\n for q in queries:\n if q in dict1:\n ans.append(q)\n continue\n \n q_lower = q.lower()\n if q_lower in dict2:\n ans.append(wordlist[dict2[q_lower]])\n continue\n \n ignore_vowel_wd = ""\n for c in q_lower:\n if c in {\'a\', \'e\', \'i\', \'o\', \'u\'}:\n ignore_vowel_wd += "*"\n else:\n ignore_vowel_wd += c\n if ignore_vowel_wd in dict3:\n ans.append(wordlist[dict3[ignore_vowel_wd]])\n continue\n \n ans.append("")\n return ans\n``` | 0 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist.
* Example: `wordlist = [ "yellow "]`, `query = "YellOw "`: `correct = "yellow "`
* Example: `wordlist = [ "Yellow "]`, `query = "yellow "`: `correct = "Yellow "`
* Example: `wordlist = [ "yellow "]`, `query = "yellow "`: `correct = "yellow "`
* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist.
* Example: `wordlist = [ "YellOw "]`, `query = "yollow "`: `correct = "YellOw "`
* Example: `wordlist = [ "YellOw "]`, `query = "yeellow "`: `correct = " "` (no match)
* Example: `wordlist = [ "YellOw "]`, `query = "yllw "`: `correct = " "` (no match)
In addition, the spell checker operates under the following precedence rules:
* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back.
* When the query matches a word up to capitlization, you should return the first such match in the wordlist.
* When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
* If the query has no matches in the wordlist, you should return the empty string.
Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`.
**Example 1:**
**Input:** wordlist = \["KiTe","kite","hare","Hare"\], queries = \["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"\]
**Output:** \["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"\]
**Example 2:**
**Input:** wordlist = \["yellow"\], queries = \["YellOw"\]
**Output:** \["yellow"\]
**Constraints:**
* `1 <= wordlist.length, queries.length <= 5000`
* `1 <= wordlist[i].length, queries[i].length <= 7`
* `wordlist[i]` and `queries[i]` consist only of only English letters. | null |
[Python] Three dictionary to match the word; Explained | vowel-spellchecker | 0 | 1 | Dictionary 1 record the original form of word in the list, It is used for exactly matching;\n\nDictionary 2 record the lower case form of words in the list, only the location of the first word with the same lower cases form is recorded. It is for lower case matching;\n\nDictionary 3 record the word with vowel replaced form in the list. It is for lower case replacing matching.\n\n```\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n # build three dictionary for word matching\n dict1 = set(wordlist)\n dict2 = dict()\n dict3 = dict()\n \n for index, wd in enumerate(wordlist):\n lower_wd = wd.lower()\n if lower_wd not in dict2:\n # only track the first word\n dict2[lower_wd] = index\n \n ignore_vowel_wd = ""\n for c in lower_wd:\n if c in {\'a\', \'e\', \'i\', \'o\', \'u\'}:\n ignore_vowel_wd += "*"\n else:\n ignore_vowel_wd += c\n if ignore_vowel_wd not in dict3:\n # only track the first word\n dict3[ignore_vowel_wd] = index\n \n \n ans = []\n for q in queries:\n if q in dict1:\n ans.append(q)\n continue\n \n q_lower = q.lower()\n if q_lower in dict2:\n ans.append(wordlist[dict2[q_lower]])\n continue\n \n ignore_vowel_wd = ""\n for c in q_lower:\n if c in {\'a\', \'e\', \'i\', \'o\', \'u\'}:\n ignore_vowel_wd += "*"\n else:\n ignore_vowel_wd += c\n if ignore_vowel_wd in dict3:\n ans.append(wordlist[dict3[ignore_vowel_wd]])\n continue\n \n ans.append("")\n return ans\n``` | 0 | The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.
* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.
We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order.
* For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`.
Given an integer `n`, return _the clumsy factorial of_ `n`.
**Example 1:**
**Input:** n = 4
**Output:** 7
**Explanation:** 7 = 4 \* 3 / 2 + 1
**Example 2:**
**Input:** n = 10
**Output:** 12
**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1
**Constraints:**
* `1 <= n <= 104` | null |
[Python3] simple solution | vowel-spellchecker | 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$$O(n + m)$$\n- $$n$$ is wordlist length\n- $$m$$ is queries length\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nvowels = set([\'a\', \'e\', \'i\', \'o\', \'u\'])\n\ndef get_word_pattern(word):\n ret = ""\n for ch in word.lower():\n if ch in vowels:\n ret += \'*\'\n else:\n ret += ch\n return ret\n\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n d1 = set(wordlist)\n d2 = {}\n d3 = {}\n for word in wordlist:\n word_lower = word.lower()\n if not (word_lower in d2):\n d2[word_lower] = word\n\n word_pattern = get_word_pattern(word)\n if not (word_pattern in d3):\n d3[word_pattern] = word\n\n ret = []\n for query in queries:\n if query in d1:\n ret.append(query)\n continue\n \n query_lower = query.lower()\n if query_lower in d2:\n ret.append(d2[query_lower])\n continue\n\n query_pattern = get_word_pattern(query) \n if query_pattern in d3:\n ret.append(d3[query_pattern])\n continue\n\n ret.append("") \n\n return ret \n \n \n\n``` | 0 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist.
* Example: `wordlist = [ "yellow "]`, `query = "YellOw "`: `correct = "yellow "`
* Example: `wordlist = [ "Yellow "]`, `query = "yellow "`: `correct = "Yellow "`
* Example: `wordlist = [ "yellow "]`, `query = "yellow "`: `correct = "yellow "`
* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist.
* Example: `wordlist = [ "YellOw "]`, `query = "yollow "`: `correct = "YellOw "`
* Example: `wordlist = [ "YellOw "]`, `query = "yeellow "`: `correct = " "` (no match)
* Example: `wordlist = [ "YellOw "]`, `query = "yllw "`: `correct = " "` (no match)
In addition, the spell checker operates under the following precedence rules:
* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back.
* When the query matches a word up to capitlization, you should return the first such match in the wordlist.
* When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
* If the query has no matches in the wordlist, you should return the empty string.
Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`.
**Example 1:**
**Input:** wordlist = \["KiTe","kite","hare","Hare"\], queries = \["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"\]
**Output:** \["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"\]
**Example 2:**
**Input:** wordlist = \["yellow"\], queries = \["YellOw"\]
**Output:** \["yellow"\]
**Constraints:**
* `1 <= wordlist.length, queries.length <= 5000`
* `1 <= wordlist[i].length, queries[i].length <= 7`
* `wordlist[i]` and `queries[i]` consist only of only English letters. | null |
[Python3] simple solution | vowel-spellchecker | 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$$O(n + m)$$\n- $$n$$ is wordlist length\n- $$m$$ is queries length\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nvowels = set([\'a\', \'e\', \'i\', \'o\', \'u\'])\n\ndef get_word_pattern(word):\n ret = ""\n for ch in word.lower():\n if ch in vowels:\n ret += \'*\'\n else:\n ret += ch\n return ret\n\nclass Solution:\n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n d1 = set(wordlist)\n d2 = {}\n d3 = {}\n for word in wordlist:\n word_lower = word.lower()\n if not (word_lower in d2):\n d2[word_lower] = word\n\n word_pattern = get_word_pattern(word)\n if not (word_pattern in d3):\n d3[word_pattern] = word\n\n ret = []\n for query in queries:\n if query in d1:\n ret.append(query)\n continue\n \n query_lower = query.lower()\n if query_lower in d2:\n ret.append(d2[query_lower])\n continue\n\n query_pattern = get_word_pattern(query) \n if query_pattern in d3:\n ret.append(d3[query_pattern])\n continue\n\n ret.append("") \n\n return ret \n \n \n\n``` | 0 | The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.
* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.
We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order.
* For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`.
Given an integer `n`, return _the clumsy factorial of_ `n`.
**Example 1:**
**Input:** n = 4
**Output:** 7
**Explanation:** 7 = 4 \* 3 / 2 + 1
**Example 2:**
**Input:** n = 10
**Output:** 12
**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1
**Constraints:**
* `1 <= n <= 104` | null |
[Python3] - Readable and Commented Hashmap Solution | vowel-spellchecker | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to identify the priority of the rules and also how to quickly check them.\n\nFor me the most complicated one was: check whether vowel replacement has a match in our wordlist.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe initialize a set for the original words in the wordlist (for fast lookup).\n\nThen we lower all of the characters and keep the first occurence of the lowered words.\n\nThen we replace all vowels with a placeholder and keep the first occurence.\n\nOne needs to consider:\n1) We need to replace the vowels with a placeholder and not delete them entirely. Otherwise oho will be the same as eh\n2) We need to replace the vowels in the lowered version of the word, as this vowel replacement is case insensitive\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N + M), where N is the length of all characters in the wordlist and M is the amount of characters in the queries.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N) as we need to save a set and two dicts.\n\n# Code\n```\nclass Solution:\n\n # a static vowel set so we don\'t initialize it with every quer\n vowel_set = set((\'a\', \'e\', \'i\', \'o\', \'u\'))\n \n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n\n # keep a set of all variations in their original form for fast lookup\n wordset = set(wordlist)\n\n # put all the words into the wordlist (lowercase) and lowercase without vowels\n # we will use these dicts to check for the capitalization errors and vowel errors\n # which are both cas insensitive (so lower both)\n #\n # also we only keep the first occurencce to match the precedence rules\n worddict = dict()\n wrddct = dict()\n for idx, word in enumerate(wordlist):\n lowered = word.lower()\n devoweled = self.devowel(lowered)\n if lowered not in worddict:\n worddict[lowered] = word\n if devoweled not in wrddct:\n wrddct[devoweled] = word\n \n # go through each of the queries and check the rules\n result = []\n for query in queries:\n\n # check if it is in the original wordlist\n # append the word and continue with the next query\n if query in wordset:\n result.append(query)\n continue\n \n # check if the word only has capitalization error\n # append the corrected one and continue with the next query\n lowered = query.lower()\n if lowered in worddict:\n result.append(worddict[lowered])\n continue\n \n # check if the word has vowel errors, append it to the result\n # and go to the next query\n devoweled = self.devowel(lowered)\n if devoweled in wrddct:\n result.append(wrddct[devoweled])\n continue\n \n # no case matched (all quard clauses have been passed)\n result.append("")\n \n return result\n \n def devowel(self, word):\n # replace vowels with unused placeholder\n return "".join(char if char not in self.vowel_set else "_" for char in word)\n \n``` | 0 | Given a `wordlist`, we want to implement a spellchecker that converts a query word into a correct word.
For a given `query` word, the spell checker handles two categories of spelling mistakes:
* Capitalization: If the query matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the case in the wordlist.
* Example: `wordlist = [ "yellow "]`, `query = "YellOw "`: `correct = "yellow "`
* Example: `wordlist = [ "Yellow "]`, `query = "yellow "`: `correct = "Yellow "`
* Example: `wordlist = [ "yellow "]`, `query = "yellow "`: `correct = "yellow "`
* Vowel Errors: If after replacing the vowels `('a', 'e', 'i', 'o', 'u')` of the query word with any vowel individually, it matches a word in the wordlist (**case-insensitive**), then the query word is returned with the same case as the match in the wordlist.
* Example: `wordlist = [ "YellOw "]`, `query = "yollow "`: `correct = "YellOw "`
* Example: `wordlist = [ "YellOw "]`, `query = "yeellow "`: `correct = " "` (no match)
* Example: `wordlist = [ "YellOw "]`, `query = "yllw "`: `correct = " "` (no match)
In addition, the spell checker operates under the following precedence rules:
* When the query exactly matches a word in the wordlist (**case-sensitive**), you should return the same word back.
* When the query matches a word up to capitlization, you should return the first such match in the wordlist.
* When the query matches a word up to vowel errors, you should return the first such match in the wordlist.
* If the query has no matches in the wordlist, you should return the empty string.
Given some `queries`, return a list of words `answer`, where `answer[i]` is the correct word for `query = queries[i]`.
**Example 1:**
**Input:** wordlist = \["KiTe","kite","hare","Hare"\], queries = \["kite","Kite","KiTe","Hare","HARE","Hear","hear","keti","keet","keto"\]
**Output:** \["kite","KiTe","KiTe","Hare","hare","","","KiTe","","KiTe"\]
**Example 2:**
**Input:** wordlist = \["yellow"\], queries = \["YellOw"\]
**Output:** \["yellow"\]
**Constraints:**
* `1 <= wordlist.length, queries.length <= 5000`
* `1 <= wordlist[i].length, queries[i].length <= 7`
* `wordlist[i]` and `queries[i]` consist only of only English letters. | null |
[Python3] - Readable and Commented Hashmap Solution | vowel-spellchecker | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to identify the priority of the rules and also how to quickly check them.\n\nFor me the most complicated one was: check whether vowel replacement has a match in our wordlist.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe initialize a set for the original words in the wordlist (for fast lookup).\n\nThen we lower all of the characters and keep the first occurence of the lowered words.\n\nThen we replace all vowels with a placeholder and keep the first occurence.\n\nOne needs to consider:\n1) We need to replace the vowels with a placeholder and not delete them entirely. Otherwise oho will be the same as eh\n2) We need to replace the vowels in the lowered version of the word, as this vowel replacement is case insensitive\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N + M), where N is the length of all characters in the wordlist and M is the amount of characters in the queries.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N) as we need to save a set and two dicts.\n\n# Code\n```\nclass Solution:\n\n # a static vowel set so we don\'t initialize it with every quer\n vowel_set = set((\'a\', \'e\', \'i\', \'o\', \'u\'))\n \n def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]:\n\n # keep a set of all variations in their original form for fast lookup\n wordset = set(wordlist)\n\n # put all the words into the wordlist (lowercase) and lowercase without vowels\n # we will use these dicts to check for the capitalization errors and vowel errors\n # which are both cas insensitive (so lower both)\n #\n # also we only keep the first occurencce to match the precedence rules\n worddict = dict()\n wrddct = dict()\n for idx, word in enumerate(wordlist):\n lowered = word.lower()\n devoweled = self.devowel(lowered)\n if lowered not in worddict:\n worddict[lowered] = word\n if devoweled not in wrddct:\n wrddct[devoweled] = word\n \n # go through each of the queries and check the rules\n result = []\n for query in queries:\n\n # check if it is in the original wordlist\n # append the word and continue with the next query\n if query in wordset:\n result.append(query)\n continue\n \n # check if the word only has capitalization error\n # append the corrected one and continue with the next query\n lowered = query.lower()\n if lowered in worddict:\n result.append(worddict[lowered])\n continue\n \n # check if the word has vowel errors, append it to the result\n # and go to the next query\n devoweled = self.devowel(lowered)\n if devoweled in wrddct:\n result.append(wrddct[devoweled])\n continue\n \n # no case matched (all quard clauses have been passed)\n result.append("")\n \n return result\n \n def devowel(self, word):\n # replace vowels with unused placeholder\n return "".join(char if char not in self.vowel_set else "_" for char in word)\n \n``` | 0 | The **factorial** of a positive integer `n` is the product of all positive integers less than or equal to `n`.
* For example, `factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1`.
We make a **clumsy factorial** using the integers in decreasing order by swapping out the multiply operations for a fixed rotation of operations with multiply `'*'`, divide `'/'`, add `'+'`, and subtract `'-'` in this order.
* For example, `clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1`.
However, these operations are still applied using the usual order of operations of arithmetic. We do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.
Additionally, the division that we use is floor division such that `10 * 9 / 8 = 90 / 8 = 11`.
Given an integer `n`, return _the clumsy factorial of_ `n`.
**Example 1:**
**Input:** n = 4
**Output:** 7
**Explanation:** 7 = 4 \* 3 / 2 + 1
**Example 2:**
**Input:** n = 10
**Output:** 12
**Explanation:** 12 = 10 \* 9 / 8 + 7 - 6 \* 5 / 4 + 3 - 2 \* 1
**Constraints:**
* `1 <= n <= 104` | null |
Solution | numbers-with-same-consecutive-differences | 1 | 1 | ```C++ []\nclass Solution {\n public:\n vector<int> numsSameConsecDiff(int n, int k) {\n if (n == 1)\n return {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n\n vector<int> ans;\n\n if (k == 0) {\n for (char c = \'1\'; c <= \'9\'; ++c)\n ans.push_back(stoi(string(n, c)));\n return ans;\n }\n\n for (int num = 1; num <= 9; ++num)\n dfs(n - 1, k, num, ans);\n\n return ans;\n }\n\n private:\n void dfs(int n, int k, int num, vector<int>& ans) {\n if (n == 0) {\n ans.push_back(num);\n return;\n }\n\n const int lastDigit = num % 10;\n\n for (const int nextDigit : {lastDigit - k, lastDigit + k})\n if (0 <= nextDigit && nextDigit <= 9)\n dfs(n - 1, k, num * 10 + nextDigit, ans);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n res = []\n\n def dfs(N,num):\n if N==0:\n res.append(num)\n return\n \n last_dig = num%10\n\n next_digs = set([last_dig+k, last_dig-k])\n\n for next_dig in next_digs:\n if 0<= next_dig<10:\n new_num = num*10+next_dig\n dfs(N-1, new_num)\n \n for num in range(1, 10):\n dfs(n-1, num)\n \n return res\n```\n\n```Java []\nclass Solution {\n List<Integer> res;\n public int[] numsSameConsecDiff(int n, int k) {\n res = new ArrayList<>();\n for(int i=1; i<=9; i++)solve(i,1,n,k);\n int len = res.size();\n int[] arr = new int[len];\n for(int i=0; i<len; i++)arr[i] = res.get(i);\n return arr;\n }\n private void solve(int item, int i, int n, int k){\n if(i==n){\n res.add(item);\n return;\n }\n int a = item % 10;\n if(k == 0){\n int temp = (item*10) + a;\n solve(temp,i+1,n,k);\n }\n else{\n if((a+k)<=9){\n int temp = (item*10) + (a+k);\n solve(temp,i+1,n,k);\n }\n if((a-k)>=0){\n int temp = (item*10) + (a-k);\n solve(temp,i+1,n,k);\n } \n }\n }\n}\n```\n | 1 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n = 3, k = 7
**Output:** \[181,292,707,818,929\]
**Explanation:** Note that 070 is not a valid number, because it has leading zeroes.
**Example 2:**
**Input:** n = 2, k = 1
**Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\]
**Constraints:**
* `2 <= n <= 9`
* `0 <= k <= 9` | null |
Solution | numbers-with-same-consecutive-differences | 1 | 1 | ```C++ []\nclass Solution {\n public:\n vector<int> numsSameConsecDiff(int n, int k) {\n if (n == 1)\n return {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n\n vector<int> ans;\n\n if (k == 0) {\n for (char c = \'1\'; c <= \'9\'; ++c)\n ans.push_back(stoi(string(n, c)));\n return ans;\n }\n\n for (int num = 1; num <= 9; ++num)\n dfs(n - 1, k, num, ans);\n\n return ans;\n }\n\n private:\n void dfs(int n, int k, int num, vector<int>& ans) {\n if (n == 0) {\n ans.push_back(num);\n return;\n }\n\n const int lastDigit = num % 10;\n\n for (const int nextDigit : {lastDigit - k, lastDigit + k})\n if (0 <= nextDigit && nextDigit <= 9)\n dfs(n - 1, k, num * 10 + nextDigit, ans);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n res = []\n\n def dfs(N,num):\n if N==0:\n res.append(num)\n return\n \n last_dig = num%10\n\n next_digs = set([last_dig+k, last_dig-k])\n\n for next_dig in next_digs:\n if 0<= next_dig<10:\n new_num = num*10+next_dig\n dfs(N-1, new_num)\n \n for num in range(1, 10):\n dfs(n-1, num)\n \n return res\n```\n\n```Java []\nclass Solution {\n List<Integer> res;\n public int[] numsSameConsecDiff(int n, int k) {\n res = new ArrayList<>();\n for(int i=1; i<=9; i++)solve(i,1,n,k);\n int len = res.size();\n int[] arr = new int[len];\n for(int i=0; i<len; i++)arr[i] = res.get(i);\n return arr;\n }\n private void solve(int item, int i, int n, int k){\n if(i==n){\n res.add(item);\n return;\n }\n int a = item % 10;\n if(k == 0){\n int temp = (item*10) + a;\n solve(temp,i+1,n,k);\n }\n else{\n if((a+k)<=9){\n int temp = (item*10) + (a+k);\n solve(temp,i+1,n,k);\n }\n if((a-k)>=0){\n int temp = (item*10) + (a-k);\n solve(temp,i+1,n,k);\n } \n }\n }\n}\n```\n | 1 | In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6` | null |
🔥 [LeetCode The Hard Way]🔥 Easy BFS 100% Explained Line By Line | numbers-with-same-consecutive-differences | 0 | 1 | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. I\'ll explain my solution line by line daily. \nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n**C++**\n\n```cpp\n// Time Complexity: O(2 ^ n)\n// Space Complexity: O(2 ^ n)\nclass Solution {\npublic:\n // The idea is to use BFS to try appending 0 - 9 to each number \n // starting from a single digit 1 - 9 until the number has n digits\n vector<int> numsSameConsecDiff(int n, int k) {\n // push all numbers with single digit to a deque\n deque<int> q{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n // do the following logic n - 1 times\n while (--n > 0) {\n // get the queue size\n int sz = q.size();\n // for each item in the current queue,\n // do the following logic\n for (int i = 0; i < sz; i++) {\n // get the first number from the queue\n int p = q.front();\n // pop it\n q.pop_front();\n // we can potentially add 0 to 9 to the current number p\n for (int j = 0; j < 10; j++) {\n // we use p % 10 to get the last digit of p\n // then get the difference with j\n // since (p % 10) - j can be negative and positive\n // we use abs to cover both case\n if (abs((p % 10) - j) == k) {\n // if the difference is equal to k\n // we can include digit j \n // so multiply the current number by 10 and add j\n q.push_back(p * 10 + j);\n }\n }\n }\n }\n // return all numbers in deque, return them in vector<int>\n return vector<int>{q.begin(), q.end()};\n }\n};\n```\n\n**Python**\n\n```py\n# Time Complexity: O(2 ^ n)\n# Space Complexity: O(2 ^ n)\nclass Solution:\n # The idea is to use BFS to try appending 0 - 9 to each number \n # starting from a single digit 1 - 9 until the number has n digits\n def numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n # init ans\n ans = []\n # push all numbers with single digit to a deque\n # (1, d) : (current position, number)\n d = deque((1, d) for d in range(1, 10))\n # while the queue is not empty\n while d:\n # pop the first element from the deque\n pos, num = d.pop()\n # if the current position is n, \n if pos == n:\n # then we can append num to ans\n ans.append(num)\n else:\n # otherwise, we can iterate 0 to 9\n for j in range(10):\n # and use num % 10 to get the last digit of num\n # then get the difference with j\n # since (num % 10) - j can be negative and positive\n # we use abs to cover both case\n if abs(num % 10 - j) == k:\n # if the difference is equal to k\n # we can include digit j \n # so multiply the current number by 10 and add j\n d.append((pos + 1, num * 10 + j))\n # return the final ans\n return ans\n``` | 70 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n = 3, k = 7
**Output:** \[181,292,707,818,929\]
**Explanation:** Note that 070 is not a valid number, because it has leading zeroes.
**Example 2:**
**Input:** n = 2, k = 1
**Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\]
**Constraints:**
* `2 <= n <= 9`
* `0 <= k <= 9` | null |
🔥 [LeetCode The Hard Way]🔥 Easy BFS 100% Explained Line By Line | numbers-with-same-consecutive-differences | 0 | 1 | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. I\'ll explain my solution line by line daily. \nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n**C++**\n\n```cpp\n// Time Complexity: O(2 ^ n)\n// Space Complexity: O(2 ^ n)\nclass Solution {\npublic:\n // The idea is to use BFS to try appending 0 - 9 to each number \n // starting from a single digit 1 - 9 until the number has n digits\n vector<int> numsSameConsecDiff(int n, int k) {\n // push all numbers with single digit to a deque\n deque<int> q{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n // do the following logic n - 1 times\n while (--n > 0) {\n // get the queue size\n int sz = q.size();\n // for each item in the current queue,\n // do the following logic\n for (int i = 0; i < sz; i++) {\n // get the first number from the queue\n int p = q.front();\n // pop it\n q.pop_front();\n // we can potentially add 0 to 9 to the current number p\n for (int j = 0; j < 10; j++) {\n // we use p % 10 to get the last digit of p\n // then get the difference with j\n // since (p % 10) - j can be negative and positive\n // we use abs to cover both case\n if (abs((p % 10) - j) == k) {\n // if the difference is equal to k\n // we can include digit j \n // so multiply the current number by 10 and add j\n q.push_back(p * 10 + j);\n }\n }\n }\n }\n // return all numbers in deque, return them in vector<int>\n return vector<int>{q.begin(), q.end()};\n }\n};\n```\n\n**Python**\n\n```py\n# Time Complexity: O(2 ^ n)\n# Space Complexity: O(2 ^ n)\nclass Solution:\n # The idea is to use BFS to try appending 0 - 9 to each number \n # starting from a single digit 1 - 9 until the number has n digits\n def numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n # init ans\n ans = []\n # push all numbers with single digit to a deque\n # (1, d) : (current position, number)\n d = deque((1, d) for d in range(1, 10))\n # while the queue is not empty\n while d:\n # pop the first element from the deque\n pos, num = d.pop()\n # if the current position is n, \n if pos == n:\n # then we can append num to ans\n ans.append(num)\n else:\n # otherwise, we can iterate 0 to 9\n for j in range(10):\n # and use num % 10 to get the last digit of num\n # then get the difference with j\n # since (num % 10) - j can be negative and positive\n # we use abs to cover both case\n if abs(num % 10 - j) == k:\n # if the difference is equal to k\n # we can include digit j \n # so multiply the current number by 10 and add j\n d.append((pos + 1, num * 10 + j))\n # return the final ans\n return ans\n``` | 70 | In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6` | null |
🔥44ms PYTHON 91% Faster 93% Memory Efficient Solution MULTIPLE APPROACHES 🔥 | numbers-with-same-consecutive-differences | 0 | 1 | # DON\'T FORGET TO UPVOTE\n# 1. 91% faster\n\n\tclass Solution:\n\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\tgraph = defaultdict(list)\n\t\t\tfor i in range(0, 10):\n\t\t\t\tif i-k >= 0:\n\t\t\t\t\tgraph[i].append(i-k)\n\t\t\t\tif i +k < 10:\n\t\t\t\t\tgraph[i].append(i+k)\n\t\t\tstart = [i for i in graph if i!= 0]\n\t\t\tfor j in range(n-1):\n\t\t\t\tnew = set()\n\t\t\t\tfor i in start:\n\t\t\t\t\tlast = i%10\n\t\t\t\t\tfor k in graph[last]:\n\t\t\t\t\t\tnew.add(i*10 + k)\n\t\t\t\tstart = new\n\t\t\treturn list(start)\n\t\t\t\n\n# 2.Different approach 76% Faster\n\t\tclass Solution:\n\t\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\t\tnumset = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\t\t\t\tfor i in range(n - 1):\n\t\t\t\t\tres = []\n\t\t\t\t\tfor num in numset:\n\t\t\t\t\t\tcur = num % 10\n\n\t\t\t\t\t\tif cur + k <= 9: res.append(num * 10 + cur + k)\n\t\t\t\t\t\tif k != 0 and cur - k >= 0: res.append(num * 10 + cur - k)\n\n\t\t\t\t\tnumset = res\n\n\t\t\t\treturn res\n\t\t\t\t\n\t\t\t\t\n# 3. Most memory Efficient approach beats 93%:\n\n\t\tclass Solution:\n\t\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\t\tres = []\n\t\t\t\tstack = deque((1, num) for num in range(1, 10))\n\t\t\t\twhile stack:\n\t\t\t\t\tcurr_pos, curr_num = stack.pop()\n\t\t\t\t\tif curr_pos == n:\n\t\t\t\t\t\tres.append(curr_num)\n\t\t\t\t\telse:\n\t\t\t\t\t\tlast_digit = curr_num % 10\n\t\t\t\t\t\tnext_pos = curr_pos + 1\n\t\t\t\t\t\tcandidates = (last_digit + k, last_digit - k) if k else (last_digit,)\n\t\t\t\t\t\tfor digit in candidates:\n\t\t\t\t\t\t\tif digit in range(10):\n\t\t\t\t\t\t\t\tstack.append((next_pos, curr_num * 10 + digit))\n\t\t\t\treturn res\n\t\t\t\t\n | 5 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n = 3, k = 7
**Output:** \[181,292,707,818,929\]
**Explanation:** Note that 070 is not a valid number, because it has leading zeroes.
**Example 2:**
**Input:** n = 2, k = 1
**Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\]
**Constraints:**
* `2 <= n <= 9`
* `0 <= k <= 9` | null |
🔥44ms PYTHON 91% Faster 93% Memory Efficient Solution MULTIPLE APPROACHES 🔥 | numbers-with-same-consecutive-differences | 0 | 1 | # DON\'T FORGET TO UPVOTE\n# 1. 91% faster\n\n\tclass Solution:\n\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\tgraph = defaultdict(list)\n\t\t\tfor i in range(0, 10):\n\t\t\t\tif i-k >= 0:\n\t\t\t\t\tgraph[i].append(i-k)\n\t\t\t\tif i +k < 10:\n\t\t\t\t\tgraph[i].append(i+k)\n\t\t\tstart = [i for i in graph if i!= 0]\n\t\t\tfor j in range(n-1):\n\t\t\t\tnew = set()\n\t\t\t\tfor i in start:\n\t\t\t\t\tlast = i%10\n\t\t\t\t\tfor k in graph[last]:\n\t\t\t\t\t\tnew.add(i*10 + k)\n\t\t\t\tstart = new\n\t\t\treturn list(start)\n\t\t\t\n\n# 2.Different approach 76% Faster\n\t\tclass Solution:\n\t\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\t\tnumset = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\t\t\t\tfor i in range(n - 1):\n\t\t\t\t\tres = []\n\t\t\t\t\tfor num in numset:\n\t\t\t\t\t\tcur = num % 10\n\n\t\t\t\t\t\tif cur + k <= 9: res.append(num * 10 + cur + k)\n\t\t\t\t\t\tif k != 0 and cur - k >= 0: res.append(num * 10 + cur - k)\n\n\t\t\t\t\tnumset = res\n\n\t\t\t\treturn res\n\t\t\t\t\n\t\t\t\t\n# 3. Most memory Efficient approach beats 93%:\n\n\t\tclass Solution:\n\t\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\t\tres = []\n\t\t\t\tstack = deque((1, num) for num in range(1, 10))\n\t\t\t\twhile stack:\n\t\t\t\t\tcurr_pos, curr_num = stack.pop()\n\t\t\t\t\tif curr_pos == n:\n\t\t\t\t\t\tres.append(curr_num)\n\t\t\t\t\telse:\n\t\t\t\t\t\tlast_digit = curr_num % 10\n\t\t\t\t\t\tnext_pos = curr_pos + 1\n\t\t\t\t\t\tcandidates = (last_digit + k, last_digit - k) if k else (last_digit,)\n\t\t\t\t\t\tfor digit in candidates:\n\t\t\t\t\t\t\tif digit in range(10):\n\t\t\t\t\t\t\t\tstack.append((next_pos, curr_num * 10 + digit))\n\t\t\t\treturn res\n\t\t\t\t\n | 5 | In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6` | null |
Python Elegant & Short | DFS + BFS | numbers-with-same-consecutive-differences | 0 | 1 | ## DFS solution\n\n\tfrom typing import Generator, List\n\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(2^n)\n\t\tMemory: O(2^n)\n\t\t"""\n\n\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\tif n == 1:\n\t\t\t\treturn [i for i in range(10)]\n\t\t\treturn [num for digit in range(1, 10) for num in self.dfs(n - 1, k, digit)]\n\n\t\t@classmethod\n\t\tdef dfs(cls, digits: int, diff: int, num: int) -> Generator:\n\t\t\tif digits == 0:\n\t\t\t\tyield num\n\t\t\telse:\n\t\t\t\tlast_digit = num % 10\n\t\t\t\tfor digit in {last_digit + diff, last_digit - diff}:\n\t\t\t\t\tif 0 <= digit < 10:\n\t\t\t\t\t\tyield from cls.dfs(digits - 1, diff, num * 10 + digit)\n\n\n## BFS solution\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(2^n)\n\t\tMemory: O(2^n)\n\t\t"""\n\n\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\tnums = list(range(1, 10))\n\n\t\t\tfor i in range(1, n):\n\t\t\t\tnums = [num * 10 + d for num in nums for d in {num % 10 + k, num % 10 - k} if 0 <= d <= 9]\n\n\t\t\treturn nums\n\n | 2 | Given two integers n and k, return _an array of all the integers of length_ `n` _where the difference between every two consecutive digits is_ `k`. You may return the answer in **any order**.
Note that the integers should not have leading zeros. Integers as `02` and `043` are not allowed.
**Example 1:**
**Input:** n = 3, k = 7
**Output:** \[181,292,707,818,929\]
**Explanation:** Note that 070 is not a valid number, because it has leading zeroes.
**Example 2:**
**Input:** n = 2, k = 1
**Output:** \[10,12,21,23,32,34,43,45,54,56,65,67,76,78,87,89,98\]
**Constraints:**
* `2 <= n <= 9`
* `0 <= k <= 9` | null |
Python Elegant & Short | DFS + BFS | numbers-with-same-consecutive-differences | 0 | 1 | ## DFS solution\n\n\tfrom typing import Generator, List\n\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(2^n)\n\t\tMemory: O(2^n)\n\t\t"""\n\n\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\tif n == 1:\n\t\t\t\treturn [i for i in range(10)]\n\t\t\treturn [num for digit in range(1, 10) for num in self.dfs(n - 1, k, digit)]\n\n\t\t@classmethod\n\t\tdef dfs(cls, digits: int, diff: int, num: int) -> Generator:\n\t\t\tif digits == 0:\n\t\t\t\tyield num\n\t\t\telse:\n\t\t\t\tlast_digit = num % 10\n\t\t\t\tfor digit in {last_digit + diff, last_digit - diff}:\n\t\t\t\t\tif 0 <= digit < 10:\n\t\t\t\t\t\tyield from cls.dfs(digits - 1, diff, num * 10 + digit)\n\n\n## BFS solution\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(2^n)\n\t\tMemory: O(2^n)\n\t\t"""\n\n\t\tdef numsSameConsecDiff(self, n: int, k: int) -> List[int]:\n\t\t\tnums = list(range(1, 10))\n\n\t\t\tfor i in range(1, n):\n\t\t\t\tnums = [num * 10 + d for num in nums for d in {num % 10 + k, num % 10 - k} if 0 <= d <= 9]\n\n\t\t\treturn nums\n\n | 2 | In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6` | null |
Python3 || 46 ms, faster than 91.39% of Python3 || Clean and Easy to Understand | binary-tree-cameras | 0 | 1 | ```\ndef minCameraCover(self, root: Optional[TreeNode]) -> int:\n self.output = 0\n def dfs(node):\n #camera monitor\n if not node:\n return False,True\n c1, m1 = dfs(node.left)\n c2, m2 = dfs(node.right)\n camera = False\n monitor = False\n if c1 or c2:\n monitor = True\n if not m1 or not m2:\n camera = True\n self.output +=1\n monitor = True\n return camera, monitor\n \n c,m = dfs(root)\n if not m: return self.output+1\n return self.output\n``` | 1 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0` | null |
Python3 || 46 ms, faster than 91.39% of Python3 || Clean and Easy to Understand | binary-tree-cameras | 0 | 1 | ```\ndef minCameraCover(self, root: Optional[TreeNode]) -> int:\n self.output = 0\n def dfs(node):\n #camera monitor\n if not node:\n return False,True\n c1, m1 = dfs(node.left)\n c2, m2 = dfs(node.right)\n camera = False\n monitor = False\n if c1 or c2:\n monitor = True\n if not m1 or not m2:\n camera = True\n self.output +=1\n monitor = True\n return camera, monitor\n \n c,m = dfs(root)\n if not m: return self.output+1\n return self.output\n``` | 1 | Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_.
It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases.
A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`.
A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`.
**Example 1:**
**Input:** preorder = \[8,5,1,7,10,12\]
**Output:** \[8,5,10,1,7,null,12\]
**Example 2:**
**Input:** preorder = \[1,3\]
**Output:** \[1,null,3\]
**Constraints:**
* `1 <= preorder.length <= 100`
* `1 <= preorder[i] <= 1000`
* All the values of `preorder` are **unique**. | null |
[Python] Making a Hard Problem Easy! Postorder Traversal with Explanation | binary-tree-cameras | 0 | 1 | ### Introduction\n\nGiven a binary tree, we want to place some cameras on some of the nodes in the tree such that all nodes in the tree are monitored by at least one camera.\n\n---\n\n### Intuition\n\nConsider the following binary tree. Where would you place cameras such that the least number of cameras are used to monitor the tree?\n\n```text\n O\n / \\\nO O\n```\n\nThe answer is obvious: the root node. Placing the camera on either leaf node will result in us not being able to monitor the other leaf node, and since the root (parent) node is adjacent (in a binary tree sense) to both leaf nodes, putting a camera there covers all three nodes.\n\nOk, time for a more difficult tree. Where would you place cameras in this tree?\n\n```text\n A\n / \\\n B C\n / \\ / \\\nD E F G\n```\n\nOk, maybe that wasn\'t so difficult after all. It\'s easy to prove that placing cameras on nodes B and C (i.e., 2 cameras used in total) can monitor the whole tree. Notice however that if we started from the root node and worked our way down, it would be difficult (and get increasingly difficult for more complex trees) to predict whether or not a camera is needed; if we tried placing a camera on A, we\'d end up requiring 5 cameras.\n\nThe trick here is to **use a bottom-up approach equivalent to a postorder traversal**. This becomes apparent if we consider that **each leaf node has only one of two ways it can be monitored**:\n\n1. Place a camera on the leaf node.\n2. Place a camera on the parent node of the leaf node.\n\nSince there are more leaf nodes than there are parents, it is safe to assume that placing cameras on parent nodes would be the best strategy. With the added bonus of its parent node being monitored too, we can then **check to see which remaining unmonitored nodes are in a similar situation; i.e., requiring a camera to be placed on itself or on its parent**. We can then treat these nodes as \'new\' leaf nodes and repeat the process.\n\nOne final question: how do we keep track of which nodes have been monitored? The answer lies in the way the question has been designed: all nodes have been set to 0. Which means, **we can use different values to assign meaning to the nodes**. We can define a priority list as follows:\n\n- Find unmonitored child nodes (which are left as 0s) -> the current (parent) node has to have a camera.\n- Find child nodes with cameras -> the current (parent) node is monitored.\n- Otherwise, the current node is unmonitored, treat as leaf node.\n\nFrom this priority list, I define **0 as unmonitored, 1 as monitored (camera), and 2 as monitored (no camera)**. As I traverse up the binary tree, I can easily obtain the identity of the current node by **obtaining the minimum of the two child nodes** (accounting for leaf nodes as edge cases) and deciding from there based on the list above.\n\n---\n\n### Implementation\n\nPlease let me know in the comments if my code is unclear or can be improved, thank you!\n\n```python\nclass Solution:\n def minCameraCover(self, root: TreeNode) -> int:\n # set the value of camera nodes to 1\n # set the value of monitored parent nodes to 2\n def dfs(node: Optional[TreeNode]) -> int:\n if not node:\n return 0\n res = dfs(node.left)+dfs(node.right)\n # find out if current node is a root node / next node in line to be monitored\n curr = min(node.left.val if node.left else float(\'inf\'), node.right.val if node.right else float(\'inf\'))\n if curr == 0:\n # at least one child node requires monitoring, this node must have a camera\n node.val = 1\n res += 1\n elif curr == 1:\n # at least one child node is a camera, this node is already monitored\n node.val = 2\n # if curr == float(\'inf\'), the current node is a leaf node; let the parent node monitor this node\n # if curr == 2, all child nodes are being monitored; treat the current node as a leaf node\n return res\n # ensure that root node is monitored, otherwise, add a camera onto root node\n return dfs(root)+(root.val == 0)\n```\n\n**TC: O(n)**, where `n` is the number of nodes in the binary tree; the postorder traversal visits each node once.\n**SC: O(h)**, where `h` is the maximum height of the binary tree, used by implicit function stack via recursion.\n\n---\n\nPlease upvote if this has helped you! Appreciate any comments as well :) | 54 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0` | null |
[Python] Making a Hard Problem Easy! Postorder Traversal with Explanation | binary-tree-cameras | 0 | 1 | ### Introduction\n\nGiven a binary tree, we want to place some cameras on some of the nodes in the tree such that all nodes in the tree are monitored by at least one camera.\n\n---\n\n### Intuition\n\nConsider the following binary tree. Where would you place cameras such that the least number of cameras are used to monitor the tree?\n\n```text\n O\n / \\\nO O\n```\n\nThe answer is obvious: the root node. Placing the camera on either leaf node will result in us not being able to monitor the other leaf node, and since the root (parent) node is adjacent (in a binary tree sense) to both leaf nodes, putting a camera there covers all three nodes.\n\nOk, time for a more difficult tree. Where would you place cameras in this tree?\n\n```text\n A\n / \\\n B C\n / \\ / \\\nD E F G\n```\n\nOk, maybe that wasn\'t so difficult after all. It\'s easy to prove that placing cameras on nodes B and C (i.e., 2 cameras used in total) can monitor the whole tree. Notice however that if we started from the root node and worked our way down, it would be difficult (and get increasingly difficult for more complex trees) to predict whether or not a camera is needed; if we tried placing a camera on A, we\'d end up requiring 5 cameras.\n\nThe trick here is to **use a bottom-up approach equivalent to a postorder traversal**. This becomes apparent if we consider that **each leaf node has only one of two ways it can be monitored**:\n\n1. Place a camera on the leaf node.\n2. Place a camera on the parent node of the leaf node.\n\nSince there are more leaf nodes than there are parents, it is safe to assume that placing cameras on parent nodes would be the best strategy. With the added bonus of its parent node being monitored too, we can then **check to see which remaining unmonitored nodes are in a similar situation; i.e., requiring a camera to be placed on itself or on its parent**. We can then treat these nodes as \'new\' leaf nodes and repeat the process.\n\nOne final question: how do we keep track of which nodes have been monitored? The answer lies in the way the question has been designed: all nodes have been set to 0. Which means, **we can use different values to assign meaning to the nodes**. We can define a priority list as follows:\n\n- Find unmonitored child nodes (which are left as 0s) -> the current (parent) node has to have a camera.\n- Find child nodes with cameras -> the current (parent) node is monitored.\n- Otherwise, the current node is unmonitored, treat as leaf node.\n\nFrom this priority list, I define **0 as unmonitored, 1 as monitored (camera), and 2 as monitored (no camera)**. As I traverse up the binary tree, I can easily obtain the identity of the current node by **obtaining the minimum of the two child nodes** (accounting for leaf nodes as edge cases) and deciding from there based on the list above.\n\n---\n\n### Implementation\n\nPlease let me know in the comments if my code is unclear or can be improved, thank you!\n\n```python\nclass Solution:\n def minCameraCover(self, root: TreeNode) -> int:\n # set the value of camera nodes to 1\n # set the value of monitored parent nodes to 2\n def dfs(node: Optional[TreeNode]) -> int:\n if not node:\n return 0\n res = dfs(node.left)+dfs(node.right)\n # find out if current node is a root node / next node in line to be monitored\n curr = min(node.left.val if node.left else float(\'inf\'), node.right.val if node.right else float(\'inf\'))\n if curr == 0:\n # at least one child node requires monitoring, this node must have a camera\n node.val = 1\n res += 1\n elif curr == 1:\n # at least one child node is a camera, this node is already monitored\n node.val = 2\n # if curr == float(\'inf\'), the current node is a leaf node; let the parent node monitor this node\n # if curr == 2, all child nodes are being monitored; treat the current node as a leaf node\n return res\n # ensure that root node is monitored, otherwise, add a camera onto root node\n return dfs(root)+(root.val == 0)\n```\n\n**TC: O(n)**, where `n` is the number of nodes in the binary tree; the postorder traversal visits each node once.\n**SC: O(h)**, where `h` is the maximum height of the binary tree, used by implicit function stack via recursion.\n\n---\n\nPlease upvote if this has helped you! Appreciate any comments as well :) | 54 | Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_.
It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases.
A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`.
A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`.
**Example 1:**
**Input:** preorder = \[8,5,1,7,10,12\]
**Output:** \[8,5,10,1,7,null,12\]
**Example 2:**
**Input:** preorder = \[1,3\]
**Output:** \[1,null,3\]
**Constraints:**
* `1 <= preorder.length <= 100`
* `1 <= preorder[i] <= 1000`
* All the values of `preorder` are **unique**. | null |
✔️ PYTHON || EXPLAINED || ;] | binary-tree-cameras | 0 | 1 | **UPVOTE IF HELPFuuL**\n \n* The root of the tree can be covered by left child, or right child, or itself.\n* One leaf of the tree can be covered by its parent or by itself.\n\n* A camera at the leaf, the camera can cover the leaf and its parent.\n* A camera at its parent, the camera can cover the leaf, its parent and its sibling.\n\nSince Placing a camera at **parent of leaf** is better we consider it as our solution and from there on we make keeping adding as we move from leaf to root.\n\n**UPVOTE IF HELPFuuL**\n\n```\nclass Solution:\n res = 0\n def minCameraCover(self, root: TreeNode) -> int:\n\n def dfs(node: TreeNode) -> int:\n \n if not node: return 0\n val = dfs(node.left) + dfs(node.right)\n \n if val == 0: return 3\n if val < 3: return 0\n \n self.res += 1\n \n return 1\n \n return self.res + 1 if dfs(root) > 2 else self.res\n``` | 8 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0` | null |
✔️ PYTHON || EXPLAINED || ;] | binary-tree-cameras | 0 | 1 | **UPVOTE IF HELPFuuL**\n \n* The root of the tree can be covered by left child, or right child, or itself.\n* One leaf of the tree can be covered by its parent or by itself.\n\n* A camera at the leaf, the camera can cover the leaf and its parent.\n* A camera at its parent, the camera can cover the leaf, its parent and its sibling.\n\nSince Placing a camera at **parent of leaf** is better we consider it as our solution and from there on we make keeping adding as we move from leaf to root.\n\n**UPVOTE IF HELPFuuL**\n\n```\nclass Solution:\n res = 0\n def minCameraCover(self, root: TreeNode) -> int:\n\n def dfs(node: TreeNode) -> int:\n \n if not node: return 0\n val = dfs(node.left) + dfs(node.right)\n \n if val == 0: return 3\n if val < 3: return 0\n \n self.res += 1\n \n return 1\n \n return self.res + 1 if dfs(root) > 2 else self.res\n``` | 8 | Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_.
It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases.
A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`.
A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`.
**Example 1:**
**Input:** preorder = \[8,5,1,7,10,12\]
**Output:** \[8,5,10,1,7,null,12\]
**Example 2:**
**Input:** preorder = \[1,3\]
**Output:** \[1,null,3\]
**Constraints:**
* `1 <= preorder.length <= 100`
* `1 <= preorder[i] <= 1000`
* All the values of `preorder` are **unique**. | null |
📌 Python3 DFS solution | binary-tree-cameras | 0 | 1 | ```\nclass Solution(object):\n def minCameraCover(self, root):\n result = [0]\n \n # 0 indicates that it doesn\'t need cam which might be a leaf node or a parent node which is already covered\n # < 3 indicates that it has already covered\n # >= 3 indicates that it needs a cam\n \n def getResult(root):\n if not root:\n return 0\n needsCam = getResult(root.left) + getResult(root.right)\n \n if needsCam == 0:\n return 3\n if needsCam < 3:\n return 0\n result[0]+=1\n return 1\n \n return result[0] + 1 if getResult(root) >= 3 else result[0]\n``` | 5 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0` | null |
📌 Python3 DFS solution | binary-tree-cameras | 0 | 1 | ```\nclass Solution(object):\n def minCameraCover(self, root):\n result = [0]\n \n # 0 indicates that it doesn\'t need cam which might be a leaf node or a parent node which is already covered\n # < 3 indicates that it has already covered\n # >= 3 indicates that it needs a cam\n \n def getResult(root):\n if not root:\n return 0\n needsCam = getResult(root.left) + getResult(root.right)\n \n if needsCam == 0:\n return 3\n if needsCam < 3:\n return 0\n result[0]+=1\n return 1\n \n return result[0] + 1 if getResult(root) >= 3 else result[0]\n``` | 5 | Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_.
It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases.
A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`.
A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`.
**Example 1:**
**Input:** preorder = \[8,5,1,7,10,12\]
**Output:** \[8,5,10,1,7,null,12\]
**Example 2:**
**Input:** preorder = \[1,3\]
**Output:** \[1,null,3\]
**Constraints:**
* `1 <= preorder.length <= 100`
* `1 <= preorder[i] <= 1000`
* All the values of `preorder` are **unique**. | null |
✅ Python Easy Postorder with explanation | binary-tree-cameras | 0 | 1 | For this problem, we first need to identify which tree traversal should be used(top down or bottom up). \n\nLet\'s take the following example, \n```\n\t A\n\t/ \\\n B C\n / \\ / \\\n D E F G\n```\n\nIf we go with top-down approach, we will start installing the cameras from root node `A`. So if we do that, we would end up with cameras installed at `A`, `D`, `E`, `F` and `G`. So in total `5` cameras. \n\nBut it seems this is not the ideal approach as the nodes `B` and `C` are monitored twice which is not needed. Using this approach, we also observed that the leaf nodes should not be installed with cameras as it helps monitor only the parent node and itself. We can infer that parent of the leaves are a better place to install the cameras as it would cover the two leaves as well its parent. Taking this into account, we can start the installing the cameras from the bottom of the tree and work our way towards the top. If we follow the bottom-up approach, then we would end up with cameras installed at `B` and `C`. So it\'s `2` installations in total instead of `5`.\n\nWe can conclude that the **bottom-up approach is more efficient**.\n\nNow for the next steps, we need a way to track the state of a node. The possible states that I can think of are :\n1. Unmonitored (`0`)\n2. Monitored and has Camera (`1`)\n3. Monitored and doesn\'t have a Camera (`2`)\n4. Leaf nodes (`infinity`)\n\nIn all, we have `4` states and I have assigned unique numeric values to identify these states.\n\nBelow is my implementation based on these observations and inference:\n\n```\nclass Solution:\n def minCameraCover(self, root: Optional[TreeNode]) -> int:\n def postorder(node):\n if not node:\n return (0, math.inf)\n \n l_count, l_state = postorder(node.left)\n r_count, r_state = postorder(node.right)\n \n state = min(l_state, r_state)\n total_cameras = l_count + r_count\n \n if state==0: # children are not monitored\n return (total_cameras + 1, 1) # install camera in current node\n \n if state==1: # one of the children is monitored and has camera\n return (total_cameras, 2) # set current node state as monitored but no camera\n \n return (total_cameras, 0) # set current node as unmonitored\n \n # adding dummy parent for the root for handling cases where root need a camera\n dummy=TreeNode(-1, root) \n \n return postorder(dummy)[0] \n```\n\n**Time - O(n)** - where `n` is number of nodes in the tree\n**Space - O(h)** - where `h` is the height of the tree. The `h` would be `n` if the tree is skewed.\n\n---\n\n***Please upvote if you find it useful***\n\n\n | 19 | You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0` | null |
✅ Python Easy Postorder with explanation | binary-tree-cameras | 0 | 1 | For this problem, we first need to identify which tree traversal should be used(top down or bottom up). \n\nLet\'s take the following example, \n```\n\t A\n\t/ \\\n B C\n / \\ / \\\n D E F G\n```\n\nIf we go with top-down approach, we will start installing the cameras from root node `A`. So if we do that, we would end up with cameras installed at `A`, `D`, `E`, `F` and `G`. So in total `5` cameras. \n\nBut it seems this is not the ideal approach as the nodes `B` and `C` are monitored twice which is not needed. Using this approach, we also observed that the leaf nodes should not be installed with cameras as it helps monitor only the parent node and itself. We can infer that parent of the leaves are a better place to install the cameras as it would cover the two leaves as well its parent. Taking this into account, we can start the installing the cameras from the bottom of the tree and work our way towards the top. If we follow the bottom-up approach, then we would end up with cameras installed at `B` and `C`. So it\'s `2` installations in total instead of `5`.\n\nWe can conclude that the **bottom-up approach is more efficient**.\n\nNow for the next steps, we need a way to track the state of a node. The possible states that I can think of are :\n1. Unmonitored (`0`)\n2. Monitored and has Camera (`1`)\n3. Monitored and doesn\'t have a Camera (`2`)\n4. Leaf nodes (`infinity`)\n\nIn all, we have `4` states and I have assigned unique numeric values to identify these states.\n\nBelow is my implementation based on these observations and inference:\n\n```\nclass Solution:\n def minCameraCover(self, root: Optional[TreeNode]) -> int:\n def postorder(node):\n if not node:\n return (0, math.inf)\n \n l_count, l_state = postorder(node.left)\n r_count, r_state = postorder(node.right)\n \n state = min(l_state, r_state)\n total_cameras = l_count + r_count\n \n if state==0: # children are not monitored\n return (total_cameras + 1, 1) # install camera in current node\n \n if state==1: # one of the children is monitored and has camera\n return (total_cameras, 2) # set current node state as monitored but no camera\n \n return (total_cameras, 0) # set current node as unmonitored\n \n # adding dummy parent for the root for handling cases where root need a camera\n dummy=TreeNode(-1, root) \n \n return postorder(dummy)[0] \n```\n\n**Time - O(n)** - where `n` is number of nodes in the tree\n**Space - O(h)** - where `h` is the height of the tree. The `h` would be `n` if the tree is skewed.\n\n---\n\n***Please upvote if you find it useful***\n\n\n | 19 | Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_.
It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases.
A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`.
A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`.
**Example 1:**
**Input:** preorder = \[8,5,1,7,10,12\]
**Output:** \[8,5,10,1,7,null,12\]
**Example 2:**
**Input:** preorder = \[1,3\]
**Output:** \[1,null,3\]
**Constraints:**
* `1 <= preorder.length <= 100`
* `1 <= preorder[i] <= 1000`
* All the values of `preorder` are **unique**. | null |
Solution | pancake-sorting | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> pancakeSort(vector<int>& arr) {\n vector<int>res;\n for(int i=0;i<arr.size();i++)\n {\n auto mx = max_element(arr.begin(),arr.end()-i);\n\n auto pos = find(arr.begin(),arr.end()-i,*mx);\n\n if((*mx)==pos-arr.begin()+1)\n continue;\n\n if (pos - arr.begin() != 0)\n {\n reverse(arr.begin(), arr.begin() + (pos - arr.begin() + 1));\n res.push_back(pos - arr.begin() + 1);\n }\n if (arr.begin() != arr.end() - 1)\n {\n reverse(arr.begin(), arr.end() - i);\n res.push_back(arr.size() - i);\n }\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def pancakeSort(self, arr: List[int]) -> List[int]:\n res = []\n for i in range(len(arr), 1, -1):\n max_idx = arr.index(i)\n res.extend([max_idx + 1, i])\n first = arr[:max_idx+1][::-1]\n arr = first + arr[max_idx+1:]\n second = arr[:i][::-1]\n arr = second + arr[i:]\n return res\n```\n\n```Java []\nimport java.util.AbstractList;\n\nclass Solution {\n List<Integer> ksequences;\n public List<Integer> pancakeSort(int[] arr) {\n return new AbstractList<Integer>() {\n public Integer get(int index) {\n init(); \n return ksequences.get(index);\n }\n public int size() {\n init(); \n return ksequences.size();\n }\n protected void init() {\n if (ksequences != null)\n return;\n ksequences = new ArrayList<Integer>();\n \n int curRangesize = arr.length;\n while (curRangesize > 0) {\n int[] top = calcIndexAndMaximum(arr, 0, curRangesize);\n int i = top[0];\n int curMax = top[1];\n if (i == curMax-1) {\n curRangesize--;\n continue;\n }\n ksequences.add(i+1); \n arrPartialReversalHelper(arr, 0, i);\n ksequences.add(curMax);\n arrPartialReversalHelper(arr, 0, curMax - 1);\n \n curRangesize--;\n }\n }\n };\n }\n private void arrPartialReversalHelper(int[] arr, int lo, int hi) {\n while (lo < hi) {\n int temp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = temp;\n lo++; hi--;\n }\n }\n private int[] calcIndexAndMaximum(int[] arr, int from, int to) {\n int max = 0;\n int maxI = -1;\n for (int i = from; i < to; i++) {\n if (arr[i] > max) {\n max = arr[i]; maxI = i;\n }\n }\n return new int[]{maxI, max};\n }\n}\n```\n | 2 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | null |
Solution | pancake-sorting | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> pancakeSort(vector<int>& arr) {\n vector<int>res;\n for(int i=0;i<arr.size();i++)\n {\n auto mx = max_element(arr.begin(),arr.end()-i);\n\n auto pos = find(arr.begin(),arr.end()-i,*mx);\n\n if((*mx)==pos-arr.begin()+1)\n continue;\n\n if (pos - arr.begin() != 0)\n {\n reverse(arr.begin(), arr.begin() + (pos - arr.begin() + 1));\n res.push_back(pos - arr.begin() + 1);\n }\n if (arr.begin() != arr.end() - 1)\n {\n reverse(arr.begin(), arr.end() - i);\n res.push_back(arr.size() - i);\n }\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def pancakeSort(self, arr: List[int]) -> List[int]:\n res = []\n for i in range(len(arr), 1, -1):\n max_idx = arr.index(i)\n res.extend([max_idx + 1, i])\n first = arr[:max_idx+1][::-1]\n arr = first + arr[max_idx+1:]\n second = arr[:i][::-1]\n arr = second + arr[i:]\n return res\n```\n\n```Java []\nimport java.util.AbstractList;\n\nclass Solution {\n List<Integer> ksequences;\n public List<Integer> pancakeSort(int[] arr) {\n return new AbstractList<Integer>() {\n public Integer get(int index) {\n init(); \n return ksequences.get(index);\n }\n public int size() {\n init(); \n return ksequences.size();\n }\n protected void init() {\n if (ksequences != null)\n return;\n ksequences = new ArrayList<Integer>();\n \n int curRangesize = arr.length;\n while (curRangesize > 0) {\n int[] top = calcIndexAndMaximum(arr, 0, curRangesize);\n int i = top[0];\n int curMax = top[1];\n if (i == curMax-1) {\n curRangesize--;\n continue;\n }\n ksequences.add(i+1); \n arrPartialReversalHelper(arr, 0, i);\n ksequences.add(curMax);\n arrPartialReversalHelper(arr, 0, curMax - 1);\n \n curRangesize--;\n }\n }\n };\n }\n private void arrPartialReversalHelper(int[] arr, int lo, int hi) {\n while (lo < hi) {\n int temp = arr[lo]; arr[lo] = arr[hi]; arr[hi] = temp;\n lo++; hi--;\n }\n }\n private int[] calcIndexAndMaximum(int[] arr, int from, int to) {\n int max = 0;\n int maxI = -1;\n for (int i = from; i < to; i++) {\n if (arr[i] > max) {\n max = arr[i]; maxI = i;\n }\n }\n return new int[]{maxI, max};\n }\n}\n```\n | 2 | The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `n`, return _its complement_.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 is "101 " in binary, with complement "010 " in binary, which is 2 in base-10.
**Example 2:**
**Input:** n = 7
**Output:** 0
**Explanation:** 7 is "111 " in binary, with complement "000 " in binary, which is 0 in base-10.
**Example 3:**
**Input:** n = 10
**Output:** 5
**Explanation:** 10 is "1010 " in binary, with complement "0101 " in binary, which is 5 in base-10.
**Constraints:**
* `0 <= n < 109`
**Note:** This question is the same as 476: [https://leetcode.com/problems/number-complement/](https://leetcode.com/problems/number-complement/) | null |
Simple python 🐍 solution with comments beats 99% time | pancake-sorting | 0 | 1 | Idea is i put the maximum element at index 0, then flip the whole array to make the max at the **end**, and keep repeating \n\nTime O(n^2) { (reversed is O(n) + index is O(n) + max is O(n)) * while O(n) = O(n^2) }\n```\nclass Solution:\n def pancakeSort(self, A: List[int]) -> List[int]:\n\n end=len(A)\n res=[]\n while end>1:\n maxInd=A.index(end) #step 1 get max\n if maxInd==end-1: #if Max already at the end then its in the right place decrement end and continue\n end-=1\n continue\n\n #making the max element at Index 0, unless if it already was at index 0\n if maxInd!=0:\n A[:maxInd+1]=reversed(A[:maxInd+1])\n res.append(maxInd+1) #append flipping size which is maxInd+1\n \n \n #Now max is at ind=0, flip whole array to make it at the "end"\n A[:end]=reversed(A[:end])\n res.append(end)\n \n end-=1 #decrement end\n return res \n \n \n``` | 11 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | null |
Simple python 🐍 solution with comments beats 99% time | pancake-sorting | 0 | 1 | Idea is i put the maximum element at index 0, then flip the whole array to make the max at the **end**, and keep repeating \n\nTime O(n^2) { (reversed is O(n) + index is O(n) + max is O(n)) * while O(n) = O(n^2) }\n```\nclass Solution:\n def pancakeSort(self, A: List[int]) -> List[int]:\n\n end=len(A)\n res=[]\n while end>1:\n maxInd=A.index(end) #step 1 get max\n if maxInd==end-1: #if Max already at the end then its in the right place decrement end and continue\n end-=1\n continue\n\n #making the max element at Index 0, unless if it already was at index 0\n if maxInd!=0:\n A[:maxInd+1]=reversed(A[:maxInd+1])\n res.append(maxInd+1) #append flipping size which is maxInd+1\n \n \n #Now max is at ind=0, flip whole array to make it at the "end"\n A[:end]=reversed(A[:end])\n res.append(end)\n \n end-=1 #decrement end\n return res \n \n \n``` | 11 | The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `n`, return _its complement_.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 is "101 " in binary, with complement "010 " in binary, which is 2 in base-10.
**Example 2:**
**Input:** n = 7
**Output:** 0
**Explanation:** 7 is "111 " in binary, with complement "000 " in binary, which is 0 in base-10.
**Example 3:**
**Input:** n = 10
**Output:** 5
**Explanation:** 10 is "1010 " in binary, with complement "0101 " in binary, which is 5 in base-10.
**Constraints:**
* `0 <= n < 109`
**Note:** This question is the same as 476: [https://leetcode.com/problems/number-complement/](https://leetcode.com/problems/number-complement/) | null |
Python Simple Solution Explained (video + code) | pancake-sorting | 0 | 1 | [](https://www.youtube.com/watch?v=4WQouWU9XXE)\nhttps://www.youtube.com/watch?v=4WQouWU9XXE\n```\nclass Solution:\n def pancakeSort(self, A: List[int]) -> List[int]:\n x = len(A)\n k = []\n \n for indx in range(x):\n max_ = max(A[:x - indx])\n max_indx = A.index(max_) + 1\n A[:max_indx] = reversed(A[:max_indx])\n k.append(max_indx)\n \n A[:x - indx] = reversed(A[:x - indx])\n k.append(x - indx)\n return k\n``` | 10 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | null |
Python Simple Solution Explained (video + code) | pancake-sorting | 0 | 1 | [](https://www.youtube.com/watch?v=4WQouWU9XXE)\nhttps://www.youtube.com/watch?v=4WQouWU9XXE\n```\nclass Solution:\n def pancakeSort(self, A: List[int]) -> List[int]:\n x = len(A)\n k = []\n \n for indx in range(x):\n max_ = max(A[:x - indx])\n max_indx = A.index(max_) + 1\n A[:max_indx] = reversed(A[:max_indx])\n k.append(max_indx)\n \n A[:x - indx] = reversed(A[:x - indx])\n k.append(x - indx)\n return k\n``` | 10 | The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `n`, return _its complement_.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 is "101 " in binary, with complement "010 " in binary, which is 2 in base-10.
**Example 2:**
**Input:** n = 7
**Output:** 0
**Explanation:** 7 is "111 " in binary, with complement "000 " in binary, which is 0 in base-10.
**Example 3:**
**Input:** n = 10
**Output:** 5
**Explanation:** 10 is "1010 " in binary, with complement "0101 " in binary, which is 5 in base-10.
**Constraints:**
* `0 <= n < 109`
**Note:** This question is the same as 476: [https://leetcode.com/problems/number-complement/](https://leetcode.com/problems/number-complement/) | null |
Easy Understanding||Recursion | pancake-sorting | 0 | 1 | \n# Code\n```\nclass Solution:\n def __init__(self):\n self.result = []\n def pancakeSort(self, arr: List[int]) -> List[int]:\n if len(arr) == 0:\n return self.result\n max_index = arr.index(max(arr))\n left = arr[:max_index+1]\n left.reverse()\n self.result.append(max_index+1)\n\n arr[:max_index+1] = left\n arr.reverse()\n self.result.append(len(arr))\n \n self.pancakeSort(arr[:-1])\n\n return self.result\n \n``` | 0 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | null |
Easy Understanding||Recursion | pancake-sorting | 0 | 1 | \n# Code\n```\nclass Solution:\n def __init__(self):\n self.result = []\n def pancakeSort(self, arr: List[int]) -> List[int]:\n if len(arr) == 0:\n return self.result\n max_index = arr.index(max(arr))\n left = arr[:max_index+1]\n left.reverse()\n self.result.append(max_index+1)\n\n arr[:max_index+1] = left\n arr.reverse()\n self.result.append(len(arr))\n \n self.pancakeSort(arr[:-1])\n\n return self.result\n \n``` | 0 | The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `n`, return _its complement_.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 is "101 " in binary, with complement "010 " in binary, which is 2 in base-10.
**Example 2:**
**Input:** n = 7
**Output:** 0
**Explanation:** 7 is "111 " in binary, with complement "000 " in binary, which is 0 in base-10.
**Example 3:**
**Input:** n = 10
**Output:** 5
**Explanation:** 10 is "1010 " in binary, with complement "0101 " in binary, which is 5 in base-10.
**Constraints:**
* `0 <= n < 109`
**Note:** This question is the same as 476: [https://leetcode.com/problems/number-complement/](https://leetcode.com/problems/number-complement/) | null |
Python Solutions | pancake-sorting | 0 | 1 | # Code\n```\nclass Solution:\n def pancakeSort(self, arr: List[int]) -> List[int]:\n res=[]\n for i in range(len(arr)-1,-1,-1):\n mx=i\n for j in range(i,-1,-1):\n if(arr[mx]<arr[j]):\n mx=j\n self.flip(mx,arr)\n self.flip(i,arr)\n res.append(mx+1)\n res.append(i+1)\n return res\n\n def flip(self,end,arr):\n s=0\n while(s<end):\n arr[s],arr[end]=arr[end],arr[s]\n s+=1\n end-=1\n\n``` | 0 | Given an array of integers `arr`, sort the array by performing a series of **pancake flips**.
In one pancake flip we do the following steps:
* Choose an integer `k` where `1 <= k <= arr.length`.
* Reverse the sub-array `arr[0...k-1]` (**0-indexed**).
For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | null |
Python Solutions | pancake-sorting | 0 | 1 | # Code\n```\nclass Solution:\n def pancakeSort(self, arr: List[int]) -> List[int]:\n res=[]\n for i in range(len(arr)-1,-1,-1):\n mx=i\n for j in range(i,-1,-1):\n if(arr[mx]<arr[j]):\n mx=j\n self.flip(mx,arr)\n self.flip(i,arr)\n res.append(mx+1)\n res.append(i+1)\n return res\n\n def flip(self,end,arr):\n s=0\n while(s<end):\n arr[s],arr[end]=arr[end],arr[s]\n s+=1\n end-=1\n\n``` | 0 | The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `n`, return _its complement_.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation:** 5 is "101 " in binary, with complement "010 " in binary, which is 2 in base-10.
**Example 2:**
**Input:** n = 7
**Output:** 0
**Explanation:** 7 is "111 " in binary, with complement "000 " in binary, which is 0 in base-10.
**Example 3:**
**Input:** n = 10
**Output:** 5
**Explanation:** 10 is "1010 " in binary, with complement "0101 " in binary, which is 5 in base-10.
**Constraints:**
* `0 <= n < 109`
**Note:** This question is the same as 476: [https://leetcode.com/problems/number-complement/](https://leetcode.com/problems/number-complement/) | null |
[Python 3] Using logarithm boundaries || beats 98% || 39ms 🥷🏼 | powerful-integers | 0 | 1 | ```python3 []\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n if bound <= 1: return []\n \n res = set()\n L = int(log(bound, x)) + 1 if x > 1 else 1\n M = int(log(bound, y)) + 1 if y > 1 else 1\n\n for i in range(L):\n for j in range(M):\n s = x**i + y**j\n if s <= bound:\n res.add(s)\n\n return list(res)\n\n```\n\n | 1 | Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`.
An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >= 0`.
You may return the answer in **any order**. In your answer, each value should occur **at most once**.
**Example 1:**
**Input:** x = 2, y = 3, bound = 10
**Output:** \[2,3,4,5,7,9,10\]
**Explanation:**
2 = 20 + 30
3 = 21 + 30
4 = 20 + 31
5 = 21 + 31
7 = 22 + 31
9 = 23 + 30
10 = 20 + 32
**Example 2:**
**Input:** x = 3, y = 5, bound = 15
**Output:** \[2,4,6,8,10,14\]
**Constraints:**
* `1 <= x, y <= 100`
* `0 <= bound <= 106` | null |
[Python 3] Using logarithm boundaries || beats 98% || 39ms 🥷🏼 | powerful-integers | 0 | 1 | ```python3 []\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n if bound <= 1: return []\n \n res = set()\n L = int(log(bound, x)) + 1 if x > 1 else 1\n M = int(log(bound, y)) + 1 if y > 1 else 1\n\n for i in range(L):\n for j in range(M):\n s = x**i + y**j\n if s <= bound:\n res.add(s)\n\n return list(res)\n\n```\n\n | 1 | You are given a list of songs where the `ith` song has a duration of `time[i]` seconds.
Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`.
**Example 1:**
**Input:** time = \[30,20,150,100,40\]
**Output:** 3
**Explanation:** Three pairs have a total duration divisible by 60:
(time\[0\] = 30, time\[2\] = 150): total duration 180
(time\[1\] = 20, time\[3\] = 100): total duration 120
(time\[1\] = 20, time\[4\] = 40): total duration 60
**Example 2:**
**Input:** time = \[60,60,60\]
**Output:** 3
**Explanation:** All three pairs have a total duration of 120, which is divisible by 60.
**Constraints:**
* `1 <= time.length <= 6 * 104`
* `1 <= time[i] <= 500` | null |
Solution | powerful-integers | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> powerfulIntegers(int x, int y, int bound) {\n vector<int>powx;\n vector<int>powy;\n powx.push_back(1);\n powy.push_back(1);\n if(x!=1){\n int pow=x;\n while(pow<bound){\n powx.push_back(pow);\n pow*=x;\n }\n }\n if(y!=1){\n int pow=y;\n while(pow<bound){\n powy.push_back(pow);\n pow*=y;\n }\n }\n set<int>s;\n for(auto i : powx){\n for(auto j : powy){\n if(i+j<=bound)s.insert(i+j);\n }\n }\n vector<int>ans(s.begin(),s.end());\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n\n def getset(num):\n if num == 1:\n return [1]\n cur = 1\n toret = []\n while cur < bound:\n toret.append(cur)\n cur *= num\n return toret\n\n xlist = getset(x)\n\n ylist = getset(y)\n print(xlist)\n print(ylist)\n ans = set()\n for num in xlist:\n for other in ylist:\n if num + other <= bound:\n ans.add(num + other)\n else:\n break\n return ans\n```\n\n```Java []\nclass Solution {\n public List<Integer> powerfulIntegers(int x, int y, int bound) {\n Set<Integer> ans = new HashSet<>();\n for (int xi = 1; xi < bound; xi *= x) {\n for (int yj = 1; xi + yj <= bound; yj *= y) {\n ans.add(xi + yj);\n if (y == 1) break;\n }\n if (x == 1) break;\n }\n return new ArrayList<Integer>(ans);\n }\n}\n```\n | 1 | Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`.
An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >= 0`.
You may return the answer in **any order**. In your answer, each value should occur **at most once**.
**Example 1:**
**Input:** x = 2, y = 3, bound = 10
**Output:** \[2,3,4,5,7,9,10\]
**Explanation:**
2 = 20 + 30
3 = 21 + 30
4 = 20 + 31
5 = 21 + 31
7 = 22 + 31
9 = 23 + 30
10 = 20 + 32
**Example 2:**
**Input:** x = 3, y = 5, bound = 15
**Output:** \[2,4,6,8,10,14\]
**Constraints:**
* `1 <= x, y <= 100`
* `0 <= bound <= 106` | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.