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
BFS||Python solution
snakes-and-ladders
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA simple BFS with the right conditions will determine the shortest path\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBFS\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n# Code\n```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n visited = set()\n bfs = deque()\n bfs.append(1)\n n = len(board)\n steps = 0\n k = 1\n while(len(bfs)!=0):\n for _ in range(k):\n currBox = bfs[0]\n bfs.popleft()\n if currBox == n*n:\n return steps\n if currBox in visited:\n continue\n visited.add(currBox)\n for j in range(currBox+1,min((n*n)+1,currBox + 7)):\n row = ceil(j/n)\n col = j%n\n if row%2 == 1:\n if board[n-row][col-1]!=-1:\n bfs.append(board[n-row][col-1])\n continue\n else:\n if col == 0:\n col = n\n if board[n-row][n-col]!=-1:\n bfs.append(board[n-row][n-col])\n continue\n bfs.append(j)\n k = len(bfs)\n print(k)\n steps+=1\n return -1\n \n\n\n```
1
You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. You start on square `1` of the board. In each move, starting from square `curr`, do the following: * Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`. * This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board. * If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`. * The game ends when you reach the square `n2`. A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder. * For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`. Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`. **Example 1:** **Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\] **Output:** 4 **Explanation:** In the beginning, you start at square 1 (at row 5, column 0). You decide to move to square 2 and must take the ladder to square 15. You then decide to move to square 17 and must take the snake to square 13. You then decide to move to square 14 and must take the ladder to square 35. You then decide to move to square 36, ending the game. This is the lowest possible number of moves to reach the last square, so return 4. **Example 2:** **Input:** board = \[\[-1,-1\],\[-1,3\]\] **Output:** 1 **Constraints:** * `n == board.length == board[i].length` * `2 <= n <= 20` * `board[i][j]` is either `-1` or in the range `[1, n2]`. * The squares labeled `1` and `n2` do not have any ladders or snakes.
null
BFS||Python solution
snakes-and-ladders
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA simple BFS with the right conditions will determine the shortest path\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBFS\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n# Code\n```\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n visited = set()\n bfs = deque()\n bfs.append(1)\n n = len(board)\n steps = 0\n k = 1\n while(len(bfs)!=0):\n for _ in range(k):\n currBox = bfs[0]\n bfs.popleft()\n if currBox == n*n:\n return steps\n if currBox in visited:\n continue\n visited.add(currBox)\n for j in range(currBox+1,min((n*n)+1,currBox + 7)):\n row = ceil(j/n)\n col = j%n\n if row%2 == 1:\n if board[n-row][col-1]!=-1:\n bfs.append(board[n-row][col-1])\n continue\n else:\n if col == 0:\n col = n\n if board[n-row][n-col]!=-1:\n bfs.append(board[n-row][n-col])\n continue\n bfs.append(j)\n k = len(bfs)\n print(k)\n steps+=1\n return -1\n \n\n\n```
1
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input:** nums = \[1,2,2\] **Output:** 1 **Explanation:** After 1 move, the array could be \[1, 2, 3\]. **Example 2:** **Input:** nums = \[3,2,1,2,1,7\] **Output:** 6 **Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values. **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Simplest Way to Deal Complicate Board: O(N) Python BFS Solution
snakes-and-ladders
0
1
# Complexity\n- Time complexity:\n$$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n$$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import deque\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n arr = [-1]\n \n # Simplest way to deal board. [::-1] means reversing list\n for i, b in enumerate(board[::-1]):\n arr += b if i % 2 == 0 else b[::-1]\n \n C = [False] * len(arr)\n\n q = deque()\n q.append((1, 0))\n C[1] = True\n\n # BFS\n while len(q) != 0:\n v, c = q.popleft()\n\n for i in range(1, 6+1):\n # Simple way to get the v value inside the acceptable range \n nv = min(i + v, len(arr)-1) \n\n # Move using snake or ladder\n if arr[nv] != -1:\n nv = arr[nv]\n\n # Find solution\n if nv == len(arr)-1: \n return c+1\n \n # Visit check\n if C[nv]: \n continue\n C[nv] = True\n\n q.append((nv, c+1))\n return -1\n \n \n```
1
You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. You start on square `1` of the board. In each move, starting from square `curr`, do the following: * Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`. * This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board. * If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`. * The game ends when you reach the square `n2`. A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder. * For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`. Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`. **Example 1:** **Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\] **Output:** 4 **Explanation:** In the beginning, you start at square 1 (at row 5, column 0). You decide to move to square 2 and must take the ladder to square 15. You then decide to move to square 17 and must take the snake to square 13. You then decide to move to square 14 and must take the ladder to square 35. You then decide to move to square 36, ending the game. This is the lowest possible number of moves to reach the last square, so return 4. **Example 2:** **Input:** board = \[\[-1,-1\],\[-1,3\]\] **Output:** 1 **Constraints:** * `n == board.length == board[i].length` * `2 <= n <= 20` * `board[i][j]` is either `-1` or in the range `[1, n2]`. * The squares labeled `1` and `n2` do not have any ladders or snakes.
null
Simplest Way to Deal Complicate Board: O(N) Python BFS Solution
snakes-and-ladders
0
1
# Complexity\n- Time complexity:\n$$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n$$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import deque\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n arr = [-1]\n \n # Simplest way to deal board. [::-1] means reversing list\n for i, b in enumerate(board[::-1]):\n arr += b if i % 2 == 0 else b[::-1]\n \n C = [False] * len(arr)\n\n q = deque()\n q.append((1, 0))\n C[1] = True\n\n # BFS\n while len(q) != 0:\n v, c = q.popleft()\n\n for i in range(1, 6+1):\n # Simple way to get the v value inside the acceptable range \n nv = min(i + v, len(arr)-1) \n\n # Move using snake or ladder\n if arr[nv] != -1:\n nv = arr[nv]\n\n # Find solution\n if nv == len(arr)-1: \n return c+1\n \n # Visit check\n if C[nv]: \n continue\n C[nv] = True\n\n q.append((nv, c+1))\n return -1\n \n \n```
1
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input:** nums = \[1,2,2\] **Output:** 1 **Explanation:** After 1 move, the array could be \[1, 2, 3\]. **Example 2:** **Input:** nums = \[3,2,1,2,1,7\] **Output:** 6 **Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values. **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Solution
snakes-and-ladders
1
1
```C++ []\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n const int n = board.size();\n int ans = 0;\n queue<int> q{{1}};\n vector<bool> seen(1 + n * n);\n vector<int> A(1 + n * n); // 2D -> 1D\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n A[(n - 1 - i) * n + (n - i & 1 ? j + 1 : n - j)] = board[i][j];\n\n while (!q.empty()) {\n ++ans;\n for (int sz = q.size(); sz > 0; --sz) {\n const int curr = q.front();\n q.pop();\n for (int next = curr + 1; next <= min(curr + 6, n * n); ++next) {\n const int dest = A[next] > 0 ? A[next] : next;\n if (dest == n * n)\n return ans;\n if (seen[dest])\n continue;\n q.push(dest);\n seen[dest] = true;\n }\n }\n }\n return -1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n target = n * n\n ladder = dict()\n\n for j in range(n):\n for k in range(n):\n if board[j][k] != -1:\n if (n - 1 - j) % 2 == 0:\n num = k + 1\n else:\n num = n - k\n num += (n - 1 - j) * n\n ladder[num] = board[j][k]\n\n visited = [0 for j in range(target + 1)]\n visited[1] = 1\n curr = [1]\n steps = 0\n\n while curr:\n steps += 1\n new = set()\n for j in curr:\n if target - j <= 6:\n return steps\n for k in range(j + 1, j + 7):\n if k in ladder and (not visited[ladder[k]]):\n if ladder[k] == target:\n return steps\n new.add(ladder[k])\n visited[ladder[k]] = 1\n elif k not in ladder and (not visited[k]):\n new.add(k)\n visited[k] = 1\n curr = new\n\n return -1\n```\n\n```Java []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int destination = board.length * board.length;\n boolean[] visited = new boolean[destination+1];\n Deque<Integer> q = new ArrayDeque();\n q.add(1);\n visited[1] = true;\n int ans = 0;\n while(!q.isEmpty()){\n ans++;\n int size = q.size();\n for(int i=0; i < size; i++){\n int f = q.poll();\n boolean added = false;\n for(int j = 6; j > 0; j--){\n int nc = f + j;\n if(nc >= destination)\n return ans;\n if(!visited[nc]){\n int c = getCell(board,nc);\n if(c == destination)\n return ans;\n if((c == -1 || c == nc) && !added){\n q.offer(nc);\n added = true;\n } else if(c > 0) {\n q.offer(c);\n }\n visited[nc] = true;\n }\n }\n }\n }\n return -1;\n }\n int getCell(int[][] board, int k){\n int n = board.length;\n int r = n - 1 - (k-1)/n;\n int c = 0;\n if(n%2 == 1)\n c = (r % 2 == 0 ? (k-1)%n : n-1 - (k-1)%n);\n else\n c = (r % 2 == 0 ? n-1 - (k-1)%n : (k-1)%n);\n return board[r][c];\n }\n}\n```\n
1
You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a [**Boustrophedon style**](https://en.wikipedia.org/wiki/Boustrophedon) starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. You start on square `1` of the board. In each move, starting from square `curr`, do the following: * Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`. * This choice simulates the result of a standard **6-sided die roll**: i.e., there are always at most 6 destinations, regardless of the size of the board. * If `next` has a snake or ladder, you **must** move to the destination of that snake or ladder. Otherwise, you move to `next`. * The game ends when you reach the square `n2`. A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do **not** follow the subsequent snake or ladder. * For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do **not** follow the subsequent ladder to `4`. Return _the least number of moves required to reach the square_ `n2`_. If it is not possible to reach the square, return_ `-1`. **Example 1:** **Input:** board = \[\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,35,-1,-1,13,-1\],\[-1,-1,-1,-1,-1,-1\],\[-1,15,-1,-1,-1,-1\]\] **Output:** 4 **Explanation:** In the beginning, you start at square 1 (at row 5, column 0). You decide to move to square 2 and must take the ladder to square 15. You then decide to move to square 17 and must take the snake to square 13. You then decide to move to square 14 and must take the ladder to square 35. You then decide to move to square 36, ending the game. This is the lowest possible number of moves to reach the last square, so return 4. **Example 2:** **Input:** board = \[\[-1,-1\],\[-1,3\]\] **Output:** 1 **Constraints:** * `n == board.length == board[i].length` * `2 <= n <= 20` * `board[i][j]` is either `-1` or in the range `[1, n2]`. * The squares labeled `1` and `n2` do not have any ladders or snakes.
null
Solution
snakes-and-ladders
1
1
```C++ []\nclass Solution {\npublic:\n int snakesAndLadders(vector<vector<int>>& board) {\n const int n = board.size();\n int ans = 0;\n queue<int> q{{1}};\n vector<bool> seen(1 + n * n);\n vector<int> A(1 + n * n); // 2D -> 1D\n\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n A[(n - 1 - i) * n + (n - i & 1 ? j + 1 : n - j)] = board[i][j];\n\n while (!q.empty()) {\n ++ans;\n for (int sz = q.size(); sz > 0; --sz) {\n const int curr = q.front();\n q.pop();\n for (int next = curr + 1; next <= min(curr + 6, n * n); ++next) {\n const int dest = A[next] > 0 ? A[next] : next;\n if (dest == n * n)\n return ans;\n if (seen[dest])\n continue;\n q.push(dest);\n seen[dest] = true;\n }\n }\n }\n return -1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n target = n * n\n ladder = dict()\n\n for j in range(n):\n for k in range(n):\n if board[j][k] != -1:\n if (n - 1 - j) % 2 == 0:\n num = k + 1\n else:\n num = n - k\n num += (n - 1 - j) * n\n ladder[num] = board[j][k]\n\n visited = [0 for j in range(target + 1)]\n visited[1] = 1\n curr = [1]\n steps = 0\n\n while curr:\n steps += 1\n new = set()\n for j in curr:\n if target - j <= 6:\n return steps\n for k in range(j + 1, j + 7):\n if k in ladder and (not visited[ladder[k]]):\n if ladder[k] == target:\n return steps\n new.add(ladder[k])\n visited[ladder[k]] = 1\n elif k not in ladder and (not visited[k]):\n new.add(k)\n visited[k] = 1\n curr = new\n\n return -1\n```\n\n```Java []\nclass Solution {\n public int snakesAndLadders(int[][] board) {\n int destination = board.length * board.length;\n boolean[] visited = new boolean[destination+1];\n Deque<Integer> q = new ArrayDeque();\n q.add(1);\n visited[1] = true;\n int ans = 0;\n while(!q.isEmpty()){\n ans++;\n int size = q.size();\n for(int i=0; i < size; i++){\n int f = q.poll();\n boolean added = false;\n for(int j = 6; j > 0; j--){\n int nc = f + j;\n if(nc >= destination)\n return ans;\n if(!visited[nc]){\n int c = getCell(board,nc);\n if(c == destination)\n return ans;\n if((c == -1 || c == nc) && !added){\n q.offer(nc);\n added = true;\n } else if(c > 0) {\n q.offer(c);\n }\n visited[nc] = true;\n }\n }\n }\n }\n return -1;\n }\n int getCell(int[][] board, int k){\n int n = board.length;\n int r = n - 1 - (k-1)/n;\n int c = 0;\n if(n%2 == 1)\n c = (r % 2 == 0 ? (k-1)%n : n-1 - (k-1)%n);\n else\n c = (r % 2 == 0 ? n-1 - (k-1)%n : (k-1)%n);\n return board[r][c];\n }\n}\n```\n
1
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input:** nums = \[1,2,2\] **Output:** 1 **Explanation:** After 1 move, the array could be \[1, 2, 3\]. **Example 2:** **Input:** nums = \[3,2,1,2,1,7\] **Output:** 6 **Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values. **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Solution
smallest-range-ii
1
1
```C++ []\nclass Solution {\npublic:\n int smallestRangeII(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int ans = nums.back() - *nums.begin();\n for (int i = 0; i < nums.size() - 1; ++i){\n int smallest = min(nums[0] + k, nums[i + 1] - k);\n int biggest = max(nums[i] + k, nums.back() - k);\n ans = min(ans, biggest - smallest);\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n minima, maxima = min( nums ), max( nums )\n if maxima - minima >= 4 * k:\n return maxima - minima - 2 * k\n if maxima - minima <= k:\n return maxima - minima\n interval = sorted( [i for i in nums if maxima - 2 * k < i < minima + 2 * k] \n + [maxima - 2 * k, minima + 2 * k] )\n return min( a + 2 * k - b for a, b in zip( interval, interval[1:] ) )\n```\n\n```Java []\nclass Solution {\n private int len;\n public int smallestRangeII(int[] nums, int k) {\n len = nums.length;\n Arrays.sort(nums);\n int result = Integer.MAX_VALUE;\n for (int i = 0; i < len; i++)\n result = Math.min(result, getResult(nums, k, i));\n return result;\n }\n private int getResult(int[] nums, int k, int i) {\n if (i == 0)\n return nums[len - 1] - nums[0];\n int max = Math.max(nums[i - 1] + k, nums[len - 1] - k);\n int min = Math.min(nums[0] + k, nums[i] - k);\n return max - min;\n }\n} \n```\n\n```C# []\nclass Solution\n{\n public int SmallestRangeII(int[] nums, int k)\n {\n int n = nums.Length;\n int bound = Int32.MinValue;\n Array.Sort(nums);\n for (int i = 0; i < n; i++)\n {\n nums[i] -= k;\n bound = Math.Max(bound, nums[i]);\n }\n int term = nums[0] + 2 * k;\n int res = Int32.MaxValue;\n for (int t = 0; t < 2; t++)\n {\n for (int idx = 0; idx < n && nums[idx] <= term; idx++)\n {\n res = Math.Min(res, bound - nums[idx]);\n nums[idx] += 2 * k;\n bound = Math.Max(nums[idx], bound);\n }\n }\n return res;\n }\n}\n```\n
1
You are given an integer array `nums` and an integer `k`. For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after changing the values at each index_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 3 **Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Solution
smallest-range-ii
1
1
```C++ []\nclass Solution {\npublic:\n int smallestRangeII(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int ans = nums.back() - *nums.begin();\n for (int i = 0; i < nums.size() - 1; ++i){\n int smallest = min(nums[0] + k, nums[i + 1] - k);\n int biggest = max(nums[i] + k, nums.back() - k);\n ans = min(ans, biggest - smallest);\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n minima, maxima = min( nums ), max( nums )\n if maxima - minima >= 4 * k:\n return maxima - minima - 2 * k\n if maxima - minima <= k:\n return maxima - minima\n interval = sorted( [i for i in nums if maxima - 2 * k < i < minima + 2 * k] \n + [maxima - 2 * k, minima + 2 * k] )\n return min( a + 2 * k - b for a, b in zip( interval, interval[1:] ) )\n```\n\n```Java []\nclass Solution {\n private int len;\n public int smallestRangeII(int[] nums, int k) {\n len = nums.length;\n Arrays.sort(nums);\n int result = Integer.MAX_VALUE;\n for (int i = 0; i < len; i++)\n result = Math.min(result, getResult(nums, k, i));\n return result;\n }\n private int getResult(int[] nums, int k, int i) {\n if (i == 0)\n return nums[len - 1] - nums[0];\n int max = Math.max(nums[i - 1] + k, nums[len - 1] - k);\n int min = Math.min(nums[0] + k, nums[i] - k);\n return max - min;\n }\n} \n```\n\n```C# []\nclass Solution\n{\n public int SmallestRangeII(int[] nums, int k)\n {\n int n = nums.Length;\n int bound = Int32.MinValue;\n Array.Sort(nums);\n for (int i = 0; i < n; i++)\n {\n nums[i] -= k;\n bound = Math.Max(bound, nums[i]);\n }\n int term = nums[0] + 2 * k;\n int res = Int32.MaxValue;\n for (int t = 0; t < 2; t++)\n {\n for (int idx = 0; idx < n && nums[idx] <= term; idx++)\n {\n res = Math.Min(res, bound - nums[idx]);\n nums[idx] += 2 * k;\n bound = Math.Max(nums[idx], bound);\n }\n }\n return res;\n }\n}\n```\n
1
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
𝗪𝗵𝘆 𝗦𝗼𝗿𝘁𝗶𝗻𝗴? Explained with Visualization | 15 Languages | Beginner Level
smallest-range-ii
1
1
---\n\n# \u270D\uD83C\uDFFB Before Starting\n\nThis Solution is long, but it will slowly build the entire logic of solving the problem. Make sure you have\n\n- Time\n- Pen and Paper for visualization! \n\nHere is the Table of Contents for the Solution, although it\'s advisable to **read the solution thoroughly**. \n<!-- no toc -->\n- [Problem Statement and Absolute Brute Force Analysis](#-problem-statement)\n- [Analysis on Two Integers](#-zoom-in-and-analyse-more)\n- [Analysis on N Integers. Thus, Sort it](#-zoom-out-with-fact-in-our-hand)\n- [Code](#-code)\n- [Code in Few Lines](#-fewer-lines-code)\n\n\n\uD83D\uDE0E Tighten your Seat Belt! \n\u2764 *After finishing the journey if you are happy, feel free to upvote. Button on bottom left*\n\n---\n\n# \u2753 Problem Statement \n\nOn every integer from `nums`, we either have to add `k` or subtract `k`. \n\nSince `k` is non-negative, we can say that we either have to "INCREASE integer by `k`", or "DECREASE integer by `k`"\n\nAfter doing this, the **score** of `nums` is the difference between the maximum and minimum element of `nums`. We have to return the **minimum score possible**.\n\nLet there be $N$ elements in `nums`. On every $N$ integer, we have $2$ options, thus there are $2^N$ possible `nums`, corresponding to which there can be at most $2^N$ possible **score**. Brute-Force would be to return a minimum from all scores. This therefore would be highly inefficient as $1 \\leq N \\leq 10^4$.\n\n---\n\n# \uD83D\uDD0D zOOm-In and Analyse More\n\nWhen analysis of a large number of integers is tough, we often zOOm-In and analyze a few integers. \n\nSuppose we have only two integers `x` and `y` such that `x < y`. \n\n\n>![image](https://user-images.githubusercontent.com/81853910/211665582-3388bd78-2b47-422b-a152-2825c6805739.png)\n\n\nHence, now we only have to analyze $2^2$ i.e. $4$ possible cases.\n\n| Case | Diagram | Remarks | Score |\n| :---: | :--- | :--- | :---: |\n| **Case 1:** Increase `x` by `k` and Increase `y` by `k` | ![1](https://user-images.githubusercontent.com/81853910/211670307-5b92c036-2a6f-4be9-b424-9797b7e67d6b.png) | Difference will remain same. Hence, **score** will be unchanged. New Maximum will be `y + k` and the new minimum will be `x + k`. | `y + k - (x + k) = y - x` |\n| **Case 2:** Decrease `x` by `k` and Decrease `y` by `k` | ![2](https://user-images.githubusercontent.com/81853910/211670353-bfc520f4-3eda-494f-b4a0-fc901816763c.png) | Difference will remain same. Hence, **score** will be unchanged. New Maximum will be `y - k` and the new minimum will be `x - k`. | `y - k - (x - k) = y - x` |\n| **Case 3:** Increase `x` by `k` and Decrease `y` by `k` | **a.** ![3a](https://user-images.githubusercontent.com/81853910/211670380-d1261235-e07f-4bdf-8be7-128d68d606be.png) **b.** ![3b](https://user-images.githubusercontent.com/81853910/211670498-228272b4-4e2e-49a9-b151-cb68b2897ed9.png) | Difference might reduce. However, we aren\'t sure if that would be the case because we don\'t know the value of `k`. **b** diagram shows that in this case, the difference might increase as well. Note that in all diagrams, we have to see the difference between arrowheads. | We aren\'t sure of the maximum and minimum. Thus, we cannot comment. **However, one key to the problem is this only**. For the time being, we can write **score** as `max(x + k, y - k) - min(x + k, y - k)` |\n| **Case 4:** Decrease `x` by `k` and Increase `y` by `k` | ![4](https://user-images.githubusercontent.com/81853910/211670404-337bede2-806c-4801-9232-3ac83ab28361.png) | Difference will obviously increase. Hence, **score** will increase. New Maximum will be `y + k` and the new minimum will be `x - k`. | `y + k - (x - k) = y - x + 2k`. Thus **score** increased by `2k` since `k` is non-negative |\n\n\n**What we have gained from the analysis?**\n\n> Since we want to minimize **score**, if we know `x < y`, WE WILL NEVER DECREASE `x` and INCREASE `y` simultaneously! Let\'s save this as **FACT**.\n\nThus, we can ignore Case 4. We are remaining with these cases only.\n\n- Case 3 has both possibilities, we cannot ignore it.\n \n- Case-1 and Case-2, let\'s call them trivial cases since we know that **score** will remain unchanged. However, we cannot ignore these cases, as Case-3 might maximize the **score**.\n\n---\n\n# \uD83D\uDD0E zOOm-Out with FACT in our hand!\n\nLet\'s zOOm out to $N$ integers.\n\nOur **FACT** offers us very important deductions.\n\n- Let\'s assume we are planning to increase $\\alpha$, then WE WILL NEVER decrease number which are less than $\\alpha$. *Here, $\\alpha$ can be interpreted as `y` of Case-4.*\n \n In other words, **if we are adamant to increase a number, we will also increase all numbers less than it**.\n\n- Let\'s assume we are planning to decrease $\\alpha$, then WE WILL NEVER increase number which are greater than $\\alpha$. *Here, $\\alpha$ can be interpreted as `x` of Case-4.*\n\n In other words, **if we are adamant to decrease a number, we will also decrease all numbers greater than it**.\n\n\nNow, as per the problem description, for every integer, we have to either **I**-NCREASE or **D**-ecrease. Hence, we can have two sets. *(Math-oriented readers can think of them as Mutually Exclusive and Collectively Exhaustive sets of `nums`)*.\n\nAny element in `nums` will belong to ONE and ONLY ONE set out of **I** and **D**\n\n- Let `i` be the largest number which is increased. Then, all numbers less than `i` will also be increased (as per the first deduction). Let\'s call their set **I**. Set **I** can be visually represented as \n \n > ![I](https://user-images.githubusercontent.com/81853910/211893500-a93b1e94-757a-4162-9aba-595dce309d20.png)\n\n- Let `d` be the smallest number that is decreased. Then, all numbers greater than `d` will also be decreased (as per the second deduction). Let\'s call their set **D**. Set **D** can be visually represented as \n \n > ![D](https://user-images.githubusercontent.com/81853910/211893745-51d05c83-adc1-4dd0-999c-1de10001b681.png)\n\n\nNow, these **I** and **D** can be thought of as (Discrete) Intervals, and thus can be arranged in **six** different ways as shown below.\n\n| | Diagram | Remarks | \n| :---: | :---: | :--- |\n| **1** | ![1](https://user-images.githubusercontent.com/81853910/211899055-d2e9c4f3-8eb8-4086-9e83-db2b2ffcdefc.png) | **ARRANGEMENT NOT POSSIBLE:** All numbers which were being decreased are also being increased by `k`. We should do ONE and ONLY ONE Operation. |\n| **2** | ![2](https://user-images.githubusercontent.com/81853910/211899094-c7f9e718-cdd1-47c7-b498-6d9748810bde.png) | **ARRANGEMENT NOT POSSIBLE:** All numbers which were being increased are also being decreased by `k`. We should do ONE and ONLY ONE Operation. |\n| **3** | ![3](https://user-images.githubusercontent.com/81853910/211899208-f73e80fd-7694-48df-8c68-6c1aeecc1271.png) | **ARRANGEMENT NOT POSSIBLE :** Two operations on intersecting part. We should do ONE and ONLY ONE Operation. |\n| **4** | ![4](https://user-images.githubusercontent.com/81853910/211899302-f52dbe13-9d3a-4008-b881-a5fb79d8e565.png) | **ARRANGEMENT NOT POSSIBLE :** Two operations on intersecting part. We should do ONE and ONLY ONE Operation. |\n| **5** | ![5](https://user-images.githubusercontent.com/81853910/211899432-1b765d7c-f8b4-4087-82b1-ddd1bb195f22.png) | Well, ONE and ONLY ONE Operation on each number. But is it possible? Turns out it violates both deductions. Few numbers less than `i` are being decreased (connected by `d`), and few numbers greater than `d` are being increased (connected by `i`). Thus, **NOT POSSIBLE** |\n| **6** | ![6](https://user-images.githubusercontent.com/81853910/211899856-dc43fc7e-b4a3-4d69-bc91-d8704a45170c.png) | Well, ONE and ONLY ONE Operation on each number. But, again, is it possible? Well, it fulfills both deductions. And this is the only possible arrangement of **I** and **D** |\n\nLet\'s rephrase ONLY POSSIBLE ARRANGEMENT. \n\n> Every element in `nums` will be either a member of **I** or **D**. As defined before, `i` is $\\max(I)$ and `d` is $\\min(D)$. And due to the only possible arrangement, we have `i < d`. We can imagine a **divider/partition** between `i` and `d`\n\n**By the way, is there any special name given to ONLY POSSIBLE ARRANGEMENT?**\n\nYes, it\'s often called SORTED ORDER, more specifically sorting in non-decreasing order.\n\nThus, SORT THE `nums`. And all these we came to know because of saved **FACT**\n\n---\n\n# \uD83E\uDD39\uD83C\uDFFB\u200D\u2642\uFE0F Sorting\n\nAfter sorting, our task is to find the most optimal **divider**. \n\n> Don\'t confuse it with any Arithmetic Division. It\'s just a wall. The divider can be visualized as a wall between two sets.\n\nThe number immediately before **divider** will be `i` and the number immediately after **divider** will be `d`. All numbers before **divider** have to be incremented by `k`, and after **divider** have to be decremented by `k`.\n\n> **How many Dividers do we have?**\n>\n> A quick zOOm-in by having $N$ as $2$ will reveal that we have $N+1$ dividers. This can be proved by [Principle of Mathematical Induction (Link)](https://ediscretestructures.blogspot.com/2022/03/principle-of-mathematical-induction.html).\n>\n> <img src=https://user-images.githubusercontent.com/81853910/211905004-fe672c5b-8290-4f21-a221-424599c81747.png alt="dividers" width="200px">\n> \n>\n> **Once Again Repeating**, All numbers before **divider** have to be incremented by `k`, and after **divider** have to be decremented by `k`.\n>\n> - Divider C boils down to increment all numbers by `k`. Our trivial Case 1. The difference would remain the same. After sorting, can be computed by `nums[last] - nums[first]`\n> - Divider B means increment `nums[0]` and decrement `nums[1]`. \n> - Divider A boils down to decrement all numbers by `k`. Our trivial Case 2. The difference would remain the same.\n> \n> Thus, out of $N + 1$ cases, $2$ will be trivial. Our focus will be on $N - 1$ non-trivial cases.\n\n\n**Thus, check for the score for all $N-1$ non-trivial dividers!** \n(Non-trivial means both **I** and **D** would be non-empty. In trivial, one of them was empty)\n\nFor **score**, we need **MAXIMUM** and **MINIMUM**.\n\n**MAXIMUM:** Let\'s try to find the maximum from each of the sets. These sets, along with the entire `nums` are also sorted.\n - **I**: Since it is sorted, and `k` has to be added to all numbers, the previous maximum, with added `k` will be the new maximum. Previous Maximum (in **I**) is nothing but a number just before **divider**. Thus, `nums[before Divider] + k`\n - **D**: Since it is sorted, and `k` has to be subtracted from all numbers, the previous maximum, with subtracted `k` will be the new maximum. Previous Maximum (in **D**) is nothing but `nums[last]`. Thus, `nums[last] - k`\n\n Hence, for this particular divider, **MAXIMUM** would be \n `max( nums[before Divider] + k, nums[last] - k )`\n\n**MINIMUM:** Let\'s try to find the minimum from each of the sets. These sets, along with the entire `nums` are also sorted.\n - **I**: Since it is sorted, and `k` has to be added to all numbers, the previous minimum, with added `k` will be the new minimum. The previous Minimum (in **I**) is nothing but `nums[first]`. Thus, `nums[first] + k`\n - **D**: Since it is sorted, and `k` has to be subtracted from all numbers, the previous minimum, with subtracted `k` will be the new minimum. The previous Minimum (in **D**) is nothing but a number just after **divider**. Thus, `nums[after Divider] - k`\n\n Hence, for this particular divider, **MINIMUM** would be\n `min( nums[first] + k, nums[after Divider] - k )`\n\nAnd **score** would be **MAXIMUM** - **MINIMUM**. In terms of `divider`, it would be `max( nums[before Divider] + k, nums[last] - k ) - min( nums[first] + k, nums[after Divider] - k )`\n\nAnd the algorithm!\n\n---\n\n# \uD83E\uDD38\uD83C\uDFFB\u200D\u2642\uFE0F Algorithm\n\n1. Sort the `nums`\n\n2. In a variable `score`, save the score of the trivial case. After sorting, it will be `nums[last] - nums[first]`\n \n3. In a variable `ans`, save `score`. This will be the minimum score.\n \n4. Iterate variable `divider` from index `0` to `N - 2` (both included), where `N` is the length of `nums`.\n \n - Visualize partition as a wall after `divider`. Element before wall/partition is at index `divider`. Element after wall/partition is at index `divider + 1`\n \n - Compute `maximumAfterDivision` as maximum of `nums[divider] + k` and `nums[last] - k`\n \n - Compute `minimumAfterDivision` as minimum of `nums[divider + 1] - k` and `nums[first] + k`\n \n - `score` for this particular partition is `maximumAfterDivision - minimumAfterDivision`\n \n - if `score` is less than `ans`, update `ans` to be this `score`\n\n5. Return `ans` \n\n\n>**Note :** In Explanation, our **divider** is visualized as something between two indices. But we cannot have some variable to point between two indices. Thus, `divider` in implementation means **divider/wall** is after *this index*, and before *next index*. (Moreover, *this index* represents `i` and *next index* represents `d`) \n\n---\n\n# \uD83D\uDDA5 Code\n\nHere is the over-commented code in Python3 for understanding, and better readability.\n\n```python3\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n\n # Number of Elements\n N = len(nums)\n \n # Sort so that we can have partition\n nums.sort()\n\n # Trivial Case, all incremented OR all decremented\n score = nums[-1] - nums[0]\n\n # To store minimum score\n ans = score\n\n # Check all N-1 Non-Trivial partitions/walls. \n # Both sets will be non-empty \n for divider in range(0, N-1):\n\n # Compute maximum and minimum after partitioning\n # Kudos! We only have two candidates for each\n maximumAfterDivision = max(nums[divider] + k , nums[-1] - k)\n minimumAfterDivision = min(nums[divider+1] - k , nums[0] + k)\n\n # Score after dividing here\n score = maximumAfterDivision - minimumAfterDivision\n\n # ans will be minimum score\n ans = min(ans, score)\n \n # return answer\n return ans\n```\n\n----\n\n# \uD83D\uDDB1\uFE0F Your Language\n\nCode in your language!\n\nIf your language is not visible because of UI, [Open Link in New Tab](https://leetcode.com/playground/QX8AzFYa/shared). Come back for Complexity Analysis\n\n<iframe src="https://leetcode.com/playground/QX8AzFYa/shared" frameBorder="0" width="900" height="720"></iframe>\n\n----\n\n# \uD83D\uDCC8 Complexity Analysis\n\n- **Time Complexity :** $O(N \\cdot \\log N)$, where $N$ is number of elements in `nums`.\n\n Because sorting takes $O(N \\cdot \\log N)$, then we are linearly computing the `score` for all $N-1$ dividers. Each computation takes constant time. Thus, $O(N \\cdot \\log N)$ is dominating.\n\n- **Space Complexity:** Well it depends on the method used for sorting the `nums`. It can be $O(N)$, or $O(\\log N)$, or $O(1)$, depending on sorting algorithm. But in the worst case, it would be $O(N)$.\n\n---\n\n\n# \u23F3 Fewer Lines Code\n\nFewer Lines of code with\n**a.** no comments\n**b.** minimum variables\n**c.** no long variable names\n\n```python3 []\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n nums.sort()\n ans = nums[-1] - nums[0]\n\n for i in range(0, len(nums) - 1):\n ans = min(ans, max(nums[i] + k, nums[-1] -\n k) - min(nums[i+1] - k, nums[0] + k))\n\n return ans\n```\n```cpp []\nclass Solution {\npublic:\n int smallestRangeII(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int ans = nums.back() - nums[0];\n for (int i = 0; i < nums.size() - 1; ++i) {\n ans = min(ans, max(nums[i] + k, nums.back() - k) - min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public int smallestRangeII(int[] nums, int k) {\n Arrays.sort(nums);\n int ans = nums[nums.length - 1] - nums[0];\n for (int i = 0; i < nums.length - 1; ++i) {\n ans = Math.min(ans, Math.max(nums[i] + k, nums[nums.length - 1] - k) - Math.min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n }\n}\n```\n```c []\nint cmpfunc (const void * a, const void * b) {\n return ( *(int*)a - *(int*)b );\n}\n\nint smallestRangeII(int* nums, int numsSize, int k){\n qsort(nums, numsSize, sizeof(int), cmpfunc);\n int ans = nums[numsSize - 1] - nums[0];\n for (int i = 0; i < numsSize - 1; ++i) {\n ans = fmin(ans, fmax(nums[i] + k, nums[numsSize - 1] - k) - fmin(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n}\n```\n```csharp []\npublic class Solution {\n public int SmallestRangeII(int[] nums, int k) {\n Array.Sort(nums);\n int ans = nums[nums.Length - 1] - nums[0];\n for (int i = 0; i < nums.Length - 1; ++i) {\n ans = Math.Min(ans, Math.Max(nums[i] + k, nums[nums.Length - 1] - k) - Math.Min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n }\n}\n```\n```javascript []\nvar smallestRangeII = function(nums, k) {\n nums.sort((a, b) => a - b);\n let ans = nums[nums.length - 1] - nums[0];\n for (let i = 0; i < nums.length - 1; ++i) {\n ans = Math.min(ans, Math.max(nums[i] + k, nums[nums.length - 1] - k) - Math.min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n};\n```\n```ruby []\ndef smallest_range_ii(nums, k)\n nums.sort!\n ans = nums[-1] - nums[0]\n for i in 0..nums.size - 2\n ans = [ans, [nums[i] + k, nums[-1] - k].max - [nums[i + 1] - k, nums[0] + k].min].min\n end\n ans\nend\n```\n```swift []\nclass Solution {\n func smallestRangeII(_ nums: [Int], _ k: Int) -> Int {\n var nums = nums.sorted()\n var ans = nums[nums.count - 1] - nums[0]\n for i in 0..<(nums.count - 1) {\n ans = min(ans, max(nums[i] + k, nums[nums.count - 1] - k) - min(nums[i + 1] - k, nums[0] + k))\n }\n return ans\n }\n}\n```\n```golang []\nfunc smallestRangeII(nums []int, k int) int {\n sort.Ints(nums)\n ans := nums[len(nums)-1] - nums[0]\n for i := 0; i < len(nums)-1; i++ {\n ans = min(ans, max(nums[i]+k, nums[len(nums)-1]-k)-min(nums[i+1]-k, nums[0]+k))\n }\n return ans\n}\n\nfunc min(a, b int) int {\n if a < b {\n return a\n }\n return b\n}\n\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n return b\n}\n```\n```scala []\nobject Solution {\n def smallestRangeII(nums: Array[Int], k: Int): Int = {\n val numsSorted = nums.sorted\n var ans = numsSorted.last - numsSorted.head\n for (i <- 0 until numsSorted.length - 1) {\n ans = Math.min(ans, Math.max(numsSorted(i) + k, numsSorted.last - k) - Math.min(numsSorted(i + 1) - k, numsSorted.head + k))\n }\n ans\n }\n}\n```\n```kotlin []\nclass Solution {\n fun smallestRangeII(nums: IntArray, k: Int): Int {\n nums.sort()\n var ans = nums[nums.size - 1] - nums[0]\n for (i in 0 until nums.size - 1) {\n ans = Math.min(ans, Math.max(nums[i] + k, nums[nums.size - 1] - k) - Math.min(nums[i + 1] - k, nums[0] + k))\n }\n return ans\n }\n}\n```\n```rust []\nimpl Solution {\n pub fn smallest_range_ii(nums: Vec<i32>, k: i32) -> i32 {\n let mut nums = nums;\n nums.sort();\n let mut ans = nums[nums.len() - 1] - nums[0];\n for i in 0..nums.len() - 1 {\n ans = ans.min((nums[i] + k).max(nums[nums.len() - 1] - k) - (nums[i + 1] - k).min(nums[0] + k));\n }\n ans\n }\n}\n```\n```php []\nclass Solution {\n function smallestRangeII($nums, $k) {\n sort($nums);\n $ans = $nums[count($nums) - 1] - $nums[0];\n for ($i = 0; $i < count($nums) - 1; ++$i) {\n $ans = min($ans, max($nums[$i] + $k, $nums[count($nums) - 1] - $k) - min($nums[$i + 1] - $k, $nums[0] + $k));\n }\n return $ans;\n }\n}\n```\n```typescript []\nfunction smallestRangeII(nums: number[], k: number): number {\n nums.sort((a, b) => a - b);\n let ans = nums[nums.length - 1] - nums[0];\n for (let i = 0; i < nums.length - 1; ++i) {\n ans = Math.min(ans, Math.max(nums[i] + k, nums[nums.length - 1] - k) - Math.min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n};\n```\n```Dart []\nclass Solution {\n int smallestRangeII(List<int> nums, int k) {\n nums.sort();\n int ans = nums[nums.length - 1] - nums[0];\n for (int i = 0; i < nums.length - 1; ++i) {\n ans = min(ans, max(nums[i] + k, nums[nums.length - 1] - k) - min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n }\n}\n```\n\n\n---\n\n\n# \uD83D\uDCA1 Conclusion\n\nHence, by repeatedly zOOming in and zOOming-out, we analyzed our problem visually and derived a very important **FACT**. The **FACT** offered two important deductions which hint at SORTING. After sorting, we can look at each partition and compute the minimum score. And, slowly we were able to solve the problem!\n\n\n<br>\n\n- \u2B06\uFE0F If you have gained some insights, feel free to upvote. Button Below \n- \u2B50 Feel free to add to your Favorite Solutions by clicking on Star.\n- \uD83D\uDE15 If you are confused, or have some doubts, post comments.\n- \uD83D\uDCA1 Any mistake or Have another idea? Share in Comments. \n\n\n----\n\n# \uD83D\uDCDD Similar Questions\n\n- [926. Flip String to Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing/description/)\n- [2740. Find the Value of the Partition](https://leetcode.com/problems/find-the-value-of-the-partition/description/)\n\n\n----\n\n# \uD83D\uDC99 Edits/Replying to Queries\n\nSpace for your feedback. This Section will take care of Edits and Replies to Comments/Doubts.\n\n\n----
69
You are given an integer array `nums` and an integer `k`. For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after changing the values at each index_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 3 **Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
𝗪𝗵𝘆 𝗦𝗼𝗿𝘁𝗶𝗻𝗴? Explained with Visualization | 15 Languages | Beginner Level
smallest-range-ii
1
1
---\n\n# \u270D\uD83C\uDFFB Before Starting\n\nThis Solution is long, but it will slowly build the entire logic of solving the problem. Make sure you have\n\n- Time\n- Pen and Paper for visualization! \n\nHere is the Table of Contents for the Solution, although it\'s advisable to **read the solution thoroughly**. \n<!-- no toc -->\n- [Problem Statement and Absolute Brute Force Analysis](#-problem-statement)\n- [Analysis on Two Integers](#-zoom-in-and-analyse-more)\n- [Analysis on N Integers. Thus, Sort it](#-zoom-out-with-fact-in-our-hand)\n- [Code](#-code)\n- [Code in Few Lines](#-fewer-lines-code)\n\n\n\uD83D\uDE0E Tighten your Seat Belt! \n\u2764 *After finishing the journey if you are happy, feel free to upvote. Button on bottom left*\n\n---\n\n# \u2753 Problem Statement \n\nOn every integer from `nums`, we either have to add `k` or subtract `k`. \n\nSince `k` is non-negative, we can say that we either have to "INCREASE integer by `k`", or "DECREASE integer by `k`"\n\nAfter doing this, the **score** of `nums` is the difference between the maximum and minimum element of `nums`. We have to return the **minimum score possible**.\n\nLet there be $N$ elements in `nums`. On every $N$ integer, we have $2$ options, thus there are $2^N$ possible `nums`, corresponding to which there can be at most $2^N$ possible **score**. Brute-Force would be to return a minimum from all scores. This therefore would be highly inefficient as $1 \\leq N \\leq 10^4$.\n\n---\n\n# \uD83D\uDD0D zOOm-In and Analyse More\n\nWhen analysis of a large number of integers is tough, we often zOOm-In and analyze a few integers. \n\nSuppose we have only two integers `x` and `y` such that `x < y`. \n\n\n>![image](https://user-images.githubusercontent.com/81853910/211665582-3388bd78-2b47-422b-a152-2825c6805739.png)\n\n\nHence, now we only have to analyze $2^2$ i.e. $4$ possible cases.\n\n| Case | Diagram | Remarks | Score |\n| :---: | :--- | :--- | :---: |\n| **Case 1:** Increase `x` by `k` and Increase `y` by `k` | ![1](https://user-images.githubusercontent.com/81853910/211670307-5b92c036-2a6f-4be9-b424-9797b7e67d6b.png) | Difference will remain same. Hence, **score** will be unchanged. New Maximum will be `y + k` and the new minimum will be `x + k`. | `y + k - (x + k) = y - x` |\n| **Case 2:** Decrease `x` by `k` and Decrease `y` by `k` | ![2](https://user-images.githubusercontent.com/81853910/211670353-bfc520f4-3eda-494f-b4a0-fc901816763c.png) | Difference will remain same. Hence, **score** will be unchanged. New Maximum will be `y - k` and the new minimum will be `x - k`. | `y - k - (x - k) = y - x` |\n| **Case 3:** Increase `x` by `k` and Decrease `y` by `k` | **a.** ![3a](https://user-images.githubusercontent.com/81853910/211670380-d1261235-e07f-4bdf-8be7-128d68d606be.png) **b.** ![3b](https://user-images.githubusercontent.com/81853910/211670498-228272b4-4e2e-49a9-b151-cb68b2897ed9.png) | Difference might reduce. However, we aren\'t sure if that would be the case because we don\'t know the value of `k`. **b** diagram shows that in this case, the difference might increase as well. Note that in all diagrams, we have to see the difference between arrowheads. | We aren\'t sure of the maximum and minimum. Thus, we cannot comment. **However, one key to the problem is this only**. For the time being, we can write **score** as `max(x + k, y - k) - min(x + k, y - k)` |\n| **Case 4:** Decrease `x` by `k` and Increase `y` by `k` | ![4](https://user-images.githubusercontent.com/81853910/211670404-337bede2-806c-4801-9232-3ac83ab28361.png) | Difference will obviously increase. Hence, **score** will increase. New Maximum will be `y + k` and the new minimum will be `x - k`. | `y + k - (x - k) = y - x + 2k`. Thus **score** increased by `2k` since `k` is non-negative |\n\n\n**What we have gained from the analysis?**\n\n> Since we want to minimize **score**, if we know `x < y`, WE WILL NEVER DECREASE `x` and INCREASE `y` simultaneously! Let\'s save this as **FACT**.\n\nThus, we can ignore Case 4. We are remaining with these cases only.\n\n- Case 3 has both possibilities, we cannot ignore it.\n \n- Case-1 and Case-2, let\'s call them trivial cases since we know that **score** will remain unchanged. However, we cannot ignore these cases, as Case-3 might maximize the **score**.\n\n---\n\n# \uD83D\uDD0E zOOm-Out with FACT in our hand!\n\nLet\'s zOOm out to $N$ integers.\n\nOur **FACT** offers us very important deductions.\n\n- Let\'s assume we are planning to increase $\\alpha$, then WE WILL NEVER decrease number which are less than $\\alpha$. *Here, $\\alpha$ can be interpreted as `y` of Case-4.*\n \n In other words, **if we are adamant to increase a number, we will also increase all numbers less than it**.\n\n- Let\'s assume we are planning to decrease $\\alpha$, then WE WILL NEVER increase number which are greater than $\\alpha$. *Here, $\\alpha$ can be interpreted as `x` of Case-4.*\n\n In other words, **if we are adamant to decrease a number, we will also decrease all numbers greater than it**.\n\n\nNow, as per the problem description, for every integer, we have to either **I**-NCREASE or **D**-ecrease. Hence, we can have two sets. *(Math-oriented readers can think of them as Mutually Exclusive and Collectively Exhaustive sets of `nums`)*.\n\nAny element in `nums` will belong to ONE and ONLY ONE set out of **I** and **D**\n\n- Let `i` be the largest number which is increased. Then, all numbers less than `i` will also be increased (as per the first deduction). Let\'s call their set **I**. Set **I** can be visually represented as \n \n > ![I](https://user-images.githubusercontent.com/81853910/211893500-a93b1e94-757a-4162-9aba-595dce309d20.png)\n\n- Let `d` be the smallest number that is decreased. Then, all numbers greater than `d` will also be decreased (as per the second deduction). Let\'s call their set **D**. Set **D** can be visually represented as \n \n > ![D](https://user-images.githubusercontent.com/81853910/211893745-51d05c83-adc1-4dd0-999c-1de10001b681.png)\n\n\nNow, these **I** and **D** can be thought of as (Discrete) Intervals, and thus can be arranged in **six** different ways as shown below.\n\n| | Diagram | Remarks | \n| :---: | :---: | :--- |\n| **1** | ![1](https://user-images.githubusercontent.com/81853910/211899055-d2e9c4f3-8eb8-4086-9e83-db2b2ffcdefc.png) | **ARRANGEMENT NOT POSSIBLE:** All numbers which were being decreased are also being increased by `k`. We should do ONE and ONLY ONE Operation. |\n| **2** | ![2](https://user-images.githubusercontent.com/81853910/211899094-c7f9e718-cdd1-47c7-b498-6d9748810bde.png) | **ARRANGEMENT NOT POSSIBLE:** All numbers which were being increased are also being decreased by `k`. We should do ONE and ONLY ONE Operation. |\n| **3** | ![3](https://user-images.githubusercontent.com/81853910/211899208-f73e80fd-7694-48df-8c68-6c1aeecc1271.png) | **ARRANGEMENT NOT POSSIBLE :** Two operations on intersecting part. We should do ONE and ONLY ONE Operation. |\n| **4** | ![4](https://user-images.githubusercontent.com/81853910/211899302-f52dbe13-9d3a-4008-b881-a5fb79d8e565.png) | **ARRANGEMENT NOT POSSIBLE :** Two operations on intersecting part. We should do ONE and ONLY ONE Operation. |\n| **5** | ![5](https://user-images.githubusercontent.com/81853910/211899432-1b765d7c-f8b4-4087-82b1-ddd1bb195f22.png) | Well, ONE and ONLY ONE Operation on each number. But is it possible? Turns out it violates both deductions. Few numbers less than `i` are being decreased (connected by `d`), and few numbers greater than `d` are being increased (connected by `i`). Thus, **NOT POSSIBLE** |\n| **6** | ![6](https://user-images.githubusercontent.com/81853910/211899856-dc43fc7e-b4a3-4d69-bc91-d8704a45170c.png) | Well, ONE and ONLY ONE Operation on each number. But, again, is it possible? Well, it fulfills both deductions. And this is the only possible arrangement of **I** and **D** |\n\nLet\'s rephrase ONLY POSSIBLE ARRANGEMENT. \n\n> Every element in `nums` will be either a member of **I** or **D**. As defined before, `i` is $\\max(I)$ and `d` is $\\min(D)$. And due to the only possible arrangement, we have `i < d`. We can imagine a **divider/partition** between `i` and `d`\n\n**By the way, is there any special name given to ONLY POSSIBLE ARRANGEMENT?**\n\nYes, it\'s often called SORTED ORDER, more specifically sorting in non-decreasing order.\n\nThus, SORT THE `nums`. And all these we came to know because of saved **FACT**\n\n---\n\n# \uD83E\uDD39\uD83C\uDFFB\u200D\u2642\uFE0F Sorting\n\nAfter sorting, our task is to find the most optimal **divider**. \n\n> Don\'t confuse it with any Arithmetic Division. It\'s just a wall. The divider can be visualized as a wall between two sets.\n\nThe number immediately before **divider** will be `i` and the number immediately after **divider** will be `d`. All numbers before **divider** have to be incremented by `k`, and after **divider** have to be decremented by `k`.\n\n> **How many Dividers do we have?**\n>\n> A quick zOOm-in by having $N$ as $2$ will reveal that we have $N+1$ dividers. This can be proved by [Principle of Mathematical Induction (Link)](https://ediscretestructures.blogspot.com/2022/03/principle-of-mathematical-induction.html).\n>\n> <img src=https://user-images.githubusercontent.com/81853910/211905004-fe672c5b-8290-4f21-a221-424599c81747.png alt="dividers" width="200px">\n> \n>\n> **Once Again Repeating**, All numbers before **divider** have to be incremented by `k`, and after **divider** have to be decremented by `k`.\n>\n> - Divider C boils down to increment all numbers by `k`. Our trivial Case 1. The difference would remain the same. After sorting, can be computed by `nums[last] - nums[first]`\n> - Divider B means increment `nums[0]` and decrement `nums[1]`. \n> - Divider A boils down to decrement all numbers by `k`. Our trivial Case 2. The difference would remain the same.\n> \n> Thus, out of $N + 1$ cases, $2$ will be trivial. Our focus will be on $N - 1$ non-trivial cases.\n\n\n**Thus, check for the score for all $N-1$ non-trivial dividers!** \n(Non-trivial means both **I** and **D** would be non-empty. In trivial, one of them was empty)\n\nFor **score**, we need **MAXIMUM** and **MINIMUM**.\n\n**MAXIMUM:** Let\'s try to find the maximum from each of the sets. These sets, along with the entire `nums` are also sorted.\n - **I**: Since it is sorted, and `k` has to be added to all numbers, the previous maximum, with added `k` will be the new maximum. Previous Maximum (in **I**) is nothing but a number just before **divider**. Thus, `nums[before Divider] + k`\n - **D**: Since it is sorted, and `k` has to be subtracted from all numbers, the previous maximum, with subtracted `k` will be the new maximum. Previous Maximum (in **D**) is nothing but `nums[last]`. Thus, `nums[last] - k`\n\n Hence, for this particular divider, **MAXIMUM** would be \n `max( nums[before Divider] + k, nums[last] - k )`\n\n**MINIMUM:** Let\'s try to find the minimum from each of the sets. These sets, along with the entire `nums` are also sorted.\n - **I**: Since it is sorted, and `k` has to be added to all numbers, the previous minimum, with added `k` will be the new minimum. The previous Minimum (in **I**) is nothing but `nums[first]`. Thus, `nums[first] + k`\n - **D**: Since it is sorted, and `k` has to be subtracted from all numbers, the previous minimum, with subtracted `k` will be the new minimum. The previous Minimum (in **D**) is nothing but a number just after **divider**. Thus, `nums[after Divider] - k`\n\n Hence, for this particular divider, **MINIMUM** would be\n `min( nums[first] + k, nums[after Divider] - k )`\n\nAnd **score** would be **MAXIMUM** - **MINIMUM**. In terms of `divider`, it would be `max( nums[before Divider] + k, nums[last] - k ) - min( nums[first] + k, nums[after Divider] - k )`\n\nAnd the algorithm!\n\n---\n\n# \uD83E\uDD38\uD83C\uDFFB\u200D\u2642\uFE0F Algorithm\n\n1. Sort the `nums`\n\n2. In a variable `score`, save the score of the trivial case. After sorting, it will be `nums[last] - nums[first]`\n \n3. In a variable `ans`, save `score`. This will be the minimum score.\n \n4. Iterate variable `divider` from index `0` to `N - 2` (both included), where `N` is the length of `nums`.\n \n - Visualize partition as a wall after `divider`. Element before wall/partition is at index `divider`. Element after wall/partition is at index `divider + 1`\n \n - Compute `maximumAfterDivision` as maximum of `nums[divider] + k` and `nums[last] - k`\n \n - Compute `minimumAfterDivision` as minimum of `nums[divider + 1] - k` and `nums[first] + k`\n \n - `score` for this particular partition is `maximumAfterDivision - minimumAfterDivision`\n \n - if `score` is less than `ans`, update `ans` to be this `score`\n\n5. Return `ans` \n\n\n>**Note :** In Explanation, our **divider** is visualized as something between two indices. But we cannot have some variable to point between two indices. Thus, `divider` in implementation means **divider/wall** is after *this index*, and before *next index*. (Moreover, *this index* represents `i` and *next index* represents `d`) \n\n---\n\n# \uD83D\uDDA5 Code\n\nHere is the over-commented code in Python3 for understanding, and better readability.\n\n```python3\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n\n # Number of Elements\n N = len(nums)\n \n # Sort so that we can have partition\n nums.sort()\n\n # Trivial Case, all incremented OR all decremented\n score = nums[-1] - nums[0]\n\n # To store minimum score\n ans = score\n\n # Check all N-1 Non-Trivial partitions/walls. \n # Both sets will be non-empty \n for divider in range(0, N-1):\n\n # Compute maximum and minimum after partitioning\n # Kudos! We only have two candidates for each\n maximumAfterDivision = max(nums[divider] + k , nums[-1] - k)\n minimumAfterDivision = min(nums[divider+1] - k , nums[0] + k)\n\n # Score after dividing here\n score = maximumAfterDivision - minimumAfterDivision\n\n # ans will be minimum score\n ans = min(ans, score)\n \n # return answer\n return ans\n```\n\n----\n\n# \uD83D\uDDB1\uFE0F Your Language\n\nCode in your language!\n\nIf your language is not visible because of UI, [Open Link in New Tab](https://leetcode.com/playground/QX8AzFYa/shared). Come back for Complexity Analysis\n\n<iframe src="https://leetcode.com/playground/QX8AzFYa/shared" frameBorder="0" width="900" height="720"></iframe>\n\n----\n\n# \uD83D\uDCC8 Complexity Analysis\n\n- **Time Complexity :** $O(N \\cdot \\log N)$, where $N$ is number of elements in `nums`.\n\n Because sorting takes $O(N \\cdot \\log N)$, then we are linearly computing the `score` for all $N-1$ dividers. Each computation takes constant time. Thus, $O(N \\cdot \\log N)$ is dominating.\n\n- **Space Complexity:** Well it depends on the method used for sorting the `nums`. It can be $O(N)$, or $O(\\log N)$, or $O(1)$, depending on sorting algorithm. But in the worst case, it would be $O(N)$.\n\n---\n\n\n# \u23F3 Fewer Lines Code\n\nFewer Lines of code with\n**a.** no comments\n**b.** minimum variables\n**c.** no long variable names\n\n```python3 []\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n nums.sort()\n ans = nums[-1] - nums[0]\n\n for i in range(0, len(nums) - 1):\n ans = min(ans, max(nums[i] + k, nums[-1] -\n k) - min(nums[i+1] - k, nums[0] + k))\n\n return ans\n```\n```cpp []\nclass Solution {\npublic:\n int smallestRangeII(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int ans = nums.back() - nums[0];\n for (int i = 0; i < nums.size() - 1; ++i) {\n ans = min(ans, max(nums[i] + k, nums.back() - k) - min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public int smallestRangeII(int[] nums, int k) {\n Arrays.sort(nums);\n int ans = nums[nums.length - 1] - nums[0];\n for (int i = 0; i < nums.length - 1; ++i) {\n ans = Math.min(ans, Math.max(nums[i] + k, nums[nums.length - 1] - k) - Math.min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n }\n}\n```\n```c []\nint cmpfunc (const void * a, const void * b) {\n return ( *(int*)a - *(int*)b );\n}\n\nint smallestRangeII(int* nums, int numsSize, int k){\n qsort(nums, numsSize, sizeof(int), cmpfunc);\n int ans = nums[numsSize - 1] - nums[0];\n for (int i = 0; i < numsSize - 1; ++i) {\n ans = fmin(ans, fmax(nums[i] + k, nums[numsSize - 1] - k) - fmin(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n}\n```\n```csharp []\npublic class Solution {\n public int SmallestRangeII(int[] nums, int k) {\n Array.Sort(nums);\n int ans = nums[nums.Length - 1] - nums[0];\n for (int i = 0; i < nums.Length - 1; ++i) {\n ans = Math.Min(ans, Math.Max(nums[i] + k, nums[nums.Length - 1] - k) - Math.Min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n }\n}\n```\n```javascript []\nvar smallestRangeII = function(nums, k) {\n nums.sort((a, b) => a - b);\n let ans = nums[nums.length - 1] - nums[0];\n for (let i = 0; i < nums.length - 1; ++i) {\n ans = Math.min(ans, Math.max(nums[i] + k, nums[nums.length - 1] - k) - Math.min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n};\n```\n```ruby []\ndef smallest_range_ii(nums, k)\n nums.sort!\n ans = nums[-1] - nums[0]\n for i in 0..nums.size - 2\n ans = [ans, [nums[i] + k, nums[-1] - k].max - [nums[i + 1] - k, nums[0] + k].min].min\n end\n ans\nend\n```\n```swift []\nclass Solution {\n func smallestRangeII(_ nums: [Int], _ k: Int) -> Int {\n var nums = nums.sorted()\n var ans = nums[nums.count - 1] - nums[0]\n for i in 0..<(nums.count - 1) {\n ans = min(ans, max(nums[i] + k, nums[nums.count - 1] - k) - min(nums[i + 1] - k, nums[0] + k))\n }\n return ans\n }\n}\n```\n```golang []\nfunc smallestRangeII(nums []int, k int) int {\n sort.Ints(nums)\n ans := nums[len(nums)-1] - nums[0]\n for i := 0; i < len(nums)-1; i++ {\n ans = min(ans, max(nums[i]+k, nums[len(nums)-1]-k)-min(nums[i+1]-k, nums[0]+k))\n }\n return ans\n}\n\nfunc min(a, b int) int {\n if a < b {\n return a\n }\n return b\n}\n\nfunc max(a, b int) int {\n if a > b {\n return a\n }\n return b\n}\n```\n```scala []\nobject Solution {\n def smallestRangeII(nums: Array[Int], k: Int): Int = {\n val numsSorted = nums.sorted\n var ans = numsSorted.last - numsSorted.head\n for (i <- 0 until numsSorted.length - 1) {\n ans = Math.min(ans, Math.max(numsSorted(i) + k, numsSorted.last - k) - Math.min(numsSorted(i + 1) - k, numsSorted.head + k))\n }\n ans\n }\n}\n```\n```kotlin []\nclass Solution {\n fun smallestRangeII(nums: IntArray, k: Int): Int {\n nums.sort()\n var ans = nums[nums.size - 1] - nums[0]\n for (i in 0 until nums.size - 1) {\n ans = Math.min(ans, Math.max(nums[i] + k, nums[nums.size - 1] - k) - Math.min(nums[i + 1] - k, nums[0] + k))\n }\n return ans\n }\n}\n```\n```rust []\nimpl Solution {\n pub fn smallest_range_ii(nums: Vec<i32>, k: i32) -> i32 {\n let mut nums = nums;\n nums.sort();\n let mut ans = nums[nums.len() - 1] - nums[0];\n for i in 0..nums.len() - 1 {\n ans = ans.min((nums[i] + k).max(nums[nums.len() - 1] - k) - (nums[i + 1] - k).min(nums[0] + k));\n }\n ans\n }\n}\n```\n```php []\nclass Solution {\n function smallestRangeII($nums, $k) {\n sort($nums);\n $ans = $nums[count($nums) - 1] - $nums[0];\n for ($i = 0; $i < count($nums) - 1; ++$i) {\n $ans = min($ans, max($nums[$i] + $k, $nums[count($nums) - 1] - $k) - min($nums[$i + 1] - $k, $nums[0] + $k));\n }\n return $ans;\n }\n}\n```\n```typescript []\nfunction smallestRangeII(nums: number[], k: number): number {\n nums.sort((a, b) => a - b);\n let ans = nums[nums.length - 1] - nums[0];\n for (let i = 0; i < nums.length - 1; ++i) {\n ans = Math.min(ans, Math.max(nums[i] + k, nums[nums.length - 1] - k) - Math.min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n};\n```\n```Dart []\nclass Solution {\n int smallestRangeII(List<int> nums, int k) {\n nums.sort();\n int ans = nums[nums.length - 1] - nums[0];\n for (int i = 0; i < nums.length - 1; ++i) {\n ans = min(ans, max(nums[i] + k, nums[nums.length - 1] - k) - min(nums[i + 1] - k, nums[0] + k));\n }\n return ans;\n }\n}\n```\n\n\n---\n\n\n# \uD83D\uDCA1 Conclusion\n\nHence, by repeatedly zOOming in and zOOming-out, we analyzed our problem visually and derived a very important **FACT**. The **FACT** offered two important deductions which hint at SORTING. After sorting, we can look at each partition and compute the minimum score. And, slowly we were able to solve the problem!\n\n\n<br>\n\n- \u2B06\uFE0F If you have gained some insights, feel free to upvote. Button Below \n- \u2B50 Feel free to add to your Favorite Solutions by clicking on Star.\n- \uD83D\uDE15 If you are confused, or have some doubts, post comments.\n- \uD83D\uDCA1 Any mistake or Have another idea? Share in Comments. \n\n\n----\n\n# \uD83D\uDCDD Similar Questions\n\n- [926. Flip String to Monotone Increasing](https://leetcode.com/problems/flip-string-to-monotone-increasing/description/)\n- [2740. Find the Value of the Partition](https://leetcode.com/problems/find-the-value-of-the-partition/description/)\n\n\n----\n\n# \uD83D\uDC99 Edits/Replying to Queries\n\nSpace for your feedback. This Section will take care of Edits and Replies to Comments/Doubts.\n\n\n----
69
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
4 line Python code
smallest-range-ii
0
1
\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n nums.sort()\n res=(nums[-1]-nums[0])\n for i in range(len(nums)-1,0,-1):res=min(res,abs(max(nums[-1]-k,nums[i-1]+k)-min(nums[i]-k,nums[0]+k)))\n return res\n \n\n```
0
You are given an integer array `nums` and an integer `k`. For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after changing the values at each index_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 3 **Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
4 line Python code
smallest-range-ii
0
1
\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n nums.sort()\n res=(nums[-1]-nums[0])\n for i in range(len(nums)-1,0,-1):res=min(res,abs(max(nums[-1]-k,nums[i-1]+k)-min(nums[i]-k,nums[0]+k)))\n return res\n \n\n```
0
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
Python | sort | greedy
smallest-range-ii
0
1
# Code\n```\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n nums.sort()\n # nums[i] -> +k or -k\n # To minimize (max - min), we\'ll have to increase small values while decrease large values.\n # Iterate i [0, N-1), and for each nums[i], try set it up for the `max` by\n # i) +k to nums[0:i+1]\n # ii) -k to nums[i+1:]\n ans = nums[-1] - nums[0]\n for i in range(len(nums) - 1):\n max_val = max(nums[i] + k, nums[-1] - k)\n min_val = min(nums[0] + k, nums[i + 1] - k)\n ans = min(ans, max_val - min_val)\n return ans\n\n```
0
You are given an integer array `nums` and an integer `k`. For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after changing the values at each index_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 3 **Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Python | sort | greedy
smallest-range-ii
0
1
# Code\n```\nclass Solution:\n def smallestRangeII(self, nums: List[int], k: int) -> int:\n nums.sort()\n # nums[i] -> +k or -k\n # To minimize (max - min), we\'ll have to increase small values while decrease large values.\n # Iterate i [0, N-1), and for each nums[i], try set it up for the `max` by\n # i) +k to nums[0:i+1]\n # ii) -k to nums[i+1:]\n ans = nums[-1] - nums[0]\n for i in range(len(nums) - 1):\n max_val = max(nums[i] + k, nums[-1] - k)\n min_val = min(nums[0] + k, nums[i + 1] - k)\n ans = min(ans, max_val - min_val)\n return ans\n\n```
0
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
Python3 solution beats 91.11% 🚀 || quibler7
online-election
0
1
\n\n# Code\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons = []\n self.times = []\n self.dic = collections.defaultdict(int)\n self.m = 0\n self.idx = -1\n\n for i in range(len(times)):\n self.times.append(times[i])\n self.dic[persons[i]] += 1\n if self.dic[persons[i]] >= self.m:\n self.persons.append(persons[i])\n self.m = self.dic[persons[i]]\n else:\n self.persons.append(self.persons[-1])\n\n def q(self, t: int) -> int:\n idx = bisect.bisect_right(self.times,t)\n return self.persons[idx-1]\n\n```
1
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
Python3 solution beats 91.11% 🚀 || quibler7
online-election
0
1
\n\n# Code\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons = []\n self.times = []\n self.dic = collections.defaultdict(int)\n self.m = 0\n self.idx = -1\n\n for i in range(len(times)):\n self.times.append(times[i])\n self.dic[persons[i]] += 1\n if self.dic[persons[i]] >= self.m:\n self.persons.append(persons[i])\n self.m = self.dic[persons[i]]\n else:\n self.persons.append(self.persons[-1])\n\n def q(self, t: int) -> int:\n idx = bisect.bisect_right(self.times,t)\n return self.persons[idx-1]\n\n```
1
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
python3 solution beats 97% 🚀 || quibler7
online-election
0
1
# Code\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons = []\n self.times = []\n self.dic = collections.defaultdict(int)\n self.m = 0\n self.idx = -1\n\n for i in range(len(times)):\n self.times.append(times[i])\n self.dic[persons[i]] += 1\n if self.dic[persons[i]] >= self.m:\n self.persons.append(persons[i])\n self.m = self.dic[persons[i]]\n else:\n self.persons.append(self.persons[-1])\n\n def q(self, t: int) -> int:\n idx = bisect.bisect_right(self.times,t)\n return self.persons[idx-1]\n\n```
1
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
python3 solution beats 97% 🚀 || quibler7
online-election
0
1
# Code\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.persons = []\n self.times = []\n self.dic = collections.defaultdict(int)\n self.m = 0\n self.idx = -1\n\n for i in range(len(times)):\n self.times.append(times[i])\n self.dic[persons[i]] += 1\n if self.dic[persons[i]] >= self.m:\n self.persons.append(persons[i])\n self.m = self.dic[persons[i]]\n else:\n self.persons.append(self.persons[-1])\n\n def q(self, t: int) -> int:\n idx = bisect.bisect_right(self.times,t)\n return self.persons[idx-1]\n\n```
1
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
Solution
online-election
1
1
```C++ []\nclass TopVotedCandidate {\npublic:\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n int max_count = 0, candidate = 0, len = persons.size();\n int count[len + 1];\n memset(count, 0, sizeof count);\n candidates = vector<pair<int, int>>(len);\n for(int i = 0; i < len; i++){\n count[persons[i]]++;\n if(count[persons[i]] >= max_count){\n max_count = count[persons[i]];\n candidate = persons[i];\n }\n candidates[i].first = times[i];\n candidates[i].second = candidate;\n }\n }\n int q(int t) {\n int lo = 0, hi = candidates.size();\n while(lo < hi){\n int m = (lo + hi) / 2;\n if(candidates[m].first <= t){\n lo = m + 1;\n }else{\n hi = m;\n }\n }\n return candidates[lo - 1].second;\n }\nprivate:\n vector<pair<int, int>> candidates;\n };\n```\n\n```Python3 []\nclass TopVotedCandidate:\n \n def __init__(self, persons, times):\n self.leads, self.times, count = [], times, defaultdict(int)\n lead = -1\n for p in persons:\n count[p] += 1\n if count[p] >= count.get(lead, 0): lead = p\n self.leads.append(lead)\n\n def q(self, t):\n return self.leads[bisect.bisect(self.times, t) - 1]\n```\n\n```Java []\nclass TopVotedCandidate {\n private final int[] time;\n private final int[] leader;\n public TopVotedCandidate(int[] persons, int[] times) {\n LeaderChange head = new LeaderChange();\n LeaderChange tail = head;\n int n = persons.length;\n int[] votes = new int[n];\n int currentLeader = -1;\n int maxVotes = 0;\n int changeCount = 0;\n for (int i = 0; i < n; i++) {\n int p = persons[i];\n int v = ++votes[p];\n if (v >= maxVotes) {\n maxVotes = v;\n if (p != currentLeader) {\n tail = new LeaderChange(times[i], currentLeader = p, tail);\n changeCount++;\n }\n }\n }\n time = new int[changeCount];\n leader = new int[changeCount];\n for (int i = 0; i < changeCount; i++) {\n head = head.next;\n time[i] = head.time;\n leader[i] = head.leader;\n }\n }\n public int q(int t) {\n int left = 0;\n int right = time.length;\n while (true) {\n int mid = (left + right) >>> 1;\n if (mid == left)\n break;\n if (time[mid] <= t)\n left = mid;\n else\n right = mid;\n }\n return leader[left];\n }\n private static class LeaderChange {\n final int time;\n final int leader;\n LeaderChange next;\n\n LeaderChange() {\n time = 0;\n leader = 0;\n }\n LeaderChange(int time, int leader, LeaderChange previous) {\n this.time = time;\n this.leader = leader;\n previous.next = this;\n }\n }\n}\n```\n
2
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
Solution
online-election
1
1
```C++ []\nclass TopVotedCandidate {\npublic:\n TopVotedCandidate(vector<int> persons, vector<int> times) {\n int max_count = 0, candidate = 0, len = persons.size();\n int count[len + 1];\n memset(count, 0, sizeof count);\n candidates = vector<pair<int, int>>(len);\n for(int i = 0; i < len; i++){\n count[persons[i]]++;\n if(count[persons[i]] >= max_count){\n max_count = count[persons[i]];\n candidate = persons[i];\n }\n candidates[i].first = times[i];\n candidates[i].second = candidate;\n }\n }\n int q(int t) {\n int lo = 0, hi = candidates.size();\n while(lo < hi){\n int m = (lo + hi) / 2;\n if(candidates[m].first <= t){\n lo = m + 1;\n }else{\n hi = m;\n }\n }\n return candidates[lo - 1].second;\n }\nprivate:\n vector<pair<int, int>> candidates;\n };\n```\n\n```Python3 []\nclass TopVotedCandidate:\n \n def __init__(self, persons, times):\n self.leads, self.times, count = [], times, defaultdict(int)\n lead = -1\n for p in persons:\n count[p] += 1\n if count[p] >= count.get(lead, 0): lead = p\n self.leads.append(lead)\n\n def q(self, t):\n return self.leads[bisect.bisect(self.times, t) - 1]\n```\n\n```Java []\nclass TopVotedCandidate {\n private final int[] time;\n private final int[] leader;\n public TopVotedCandidate(int[] persons, int[] times) {\n LeaderChange head = new LeaderChange();\n LeaderChange tail = head;\n int n = persons.length;\n int[] votes = new int[n];\n int currentLeader = -1;\n int maxVotes = 0;\n int changeCount = 0;\n for (int i = 0; i < n; i++) {\n int p = persons[i];\n int v = ++votes[p];\n if (v >= maxVotes) {\n maxVotes = v;\n if (p != currentLeader) {\n tail = new LeaderChange(times[i], currentLeader = p, tail);\n changeCount++;\n }\n }\n }\n time = new int[changeCount];\n leader = new int[changeCount];\n for (int i = 0; i < changeCount; i++) {\n head = head.next;\n time[i] = head.time;\n leader[i] = head.leader;\n }\n }\n public int q(int t) {\n int left = 0;\n int right = time.length;\n while (true) {\n int mid = (left + right) >>> 1;\n if (mid == left)\n break;\n if (time[mid] <= t)\n left = mid;\n else\n right = mid;\n }\n return leader[left];\n }\n private static class LeaderChange {\n final int time;\n final int leader;\n LeaderChange next;\n\n LeaderChange() {\n time = 0;\n leader = 0;\n }\n LeaderChange(int time, int leader, LeaderChange previous) {\n this.time = time;\n this.leader = leader;\n previous.next = this;\n }\n }\n}\n```\n
2
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
Counter and Binary Search, O(n) time complexity
online-election
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass TopVotedCandidate:\n def calcLeadingElection(self, persons):\n countVote = defaultdict(int)\n countVote[persons[0]] = 1\n currentLeading = [persons[0]]\n n = len(persons)\n for i in range(1, n):\n currentPerson = persons[i]\n countVote[currentPerson] += 1\n if countVote[currentPerson] >= countVote[currentLeading[i - 1]]:\n currentLeading.append(currentPerson)\n else:\n currentLeading.append(currentLeading[i - 1])\n\n return currentLeading\n\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.leadingElection = self.calcLeadingElection(persons)\n\n def q(self, t: int) -> int:\n if t > self.times[-1]:\n return self.leadingElection[-1]\n indexQuery = bisect_left(self.times, t)\n if self.times[indexQuery] > t:\n return self.leadingElection[indexQuery - 1]\n return self.leadingElection[indexQuery]\n \n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n```
0
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
Counter and Binary Search, O(n) time complexity
online-election
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass TopVotedCandidate:\n def calcLeadingElection(self, persons):\n countVote = defaultdict(int)\n countVote[persons[0]] = 1\n currentLeading = [persons[0]]\n n = len(persons)\n for i in range(1, n):\n currentPerson = persons[i]\n countVote[currentPerson] += 1\n if countVote[currentPerson] >= countVote[currentLeading[i - 1]]:\n currentLeading.append(currentPerson)\n else:\n currentLeading.append(currentLeading[i - 1])\n\n return currentLeading\n\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.leadingElection = self.calcLeadingElection(persons)\n\n def q(self, t: int) -> int:\n if t > self.times[-1]:\n return self.leadingElection[-1]\n indexQuery = bisect_left(self.times, t)\n if self.times[indexQuery] > t:\n return self.leadingElection[indexQuery - 1]\n return self.leadingElection[indexQuery]\n \n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n```
0
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
[Python3] Good enough
online-election
0
1
``` Python3 []\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.snapshots = []\n votes = {}\n most = None\n\n for i in range(len(persons)):\n votes[persons[i]] = votes.get(persons[i],0)+1\n most = persons[i] if most is None or votes[persons[i]]>=votes[most] else most\n self.snapshots.append([times[i],most])\n\n def q(self, t: int) -> int:\n left, right = 0, len(self.snapshots)-1\n\n while left<=right:\n middle = (left+right)//2\n snapshot = self.snapshots[middle]\n\n if snapshot[0]==t:\n return snapshot[1]\n elif snapshot[0]>t:\n right = middle-1\n else:\n left = middle+1\n \n return self.snapshots[left-1][1]\n\n\n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n```
0
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
[Python3] Good enough
online-election
0
1
``` Python3 []\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.snapshots = []\n votes = {}\n most = None\n\n for i in range(len(persons)):\n votes[persons[i]] = votes.get(persons[i],0)+1\n most = persons[i] if most is None or votes[persons[i]]>=votes[most] else most\n self.snapshots.append([times[i],most])\n\n def q(self, t: int) -> int:\n left, right = 0, len(self.snapshots)-1\n\n while left<=right:\n middle = (left+right)//2\n snapshot = self.snapshots[middle]\n\n if snapshot[0]==t:\n return snapshot[1]\n elif snapshot[0]>t:\n right = middle-1\n else:\n left = middle+1\n \n return self.snapshots[left-1][1]\n\n\n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n```
0
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
Simplest sol using dict of leading to maintain leading on at each index
online-election
0
1
# Code\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.votes = defaultdict(int)\n self.leading = []\n max_vote_count = 0\n\n for i,p in enumerate(persons):\n self.votes[p] += 1\n\n if not self.leading:\n self.leading.append(p)\n max_vote_count += 1\n elif self.votes[p] >= max_vote_count:\n self.leading.append(p)\n max_vote_count = self.votes[p]\n else:\n self.leading.append(self.leading[-1])\n \n\n def q(self, t: int) -> int:\n index = bisect_right(self.times, t) - 1\n return self.leading[index]\n \n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n```
0
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
Simplest sol using dict of leading to maintain leading on at each index
online-election
0
1
# Code\n```\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n self.times = times\n self.votes = defaultdict(int)\n self.leading = []\n max_vote_count = 0\n\n for i,p in enumerate(persons):\n self.votes[p] += 1\n\n if not self.leading:\n self.leading.append(p)\n max_vote_count += 1\n elif self.votes[p] >= max_vote_count:\n self.leading.append(p)\n max_vote_count = self.votes[p]\n else:\n self.leading.append(self.leading[-1])\n \n\n def q(self, t: int) -> int:\n index = bisect_right(self.times, t) - 1\n return self.leading[index]\n \n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n```
0
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
Details solution with comments | Binary Search
online-election
0
1
# Idea:\n- save an array topCandidate to know which person is leading at a specific time times[i]\n- that array has the same length as persons and times array\n- for each query q, we find the upperBound of q in times array - called it t, then the \ntop candidates person at that q time is topCandidate[t-1]\n\n# # Time complexity: \nN is the length of persons/times arrays\n- init: O(N) \n- q: O(lgN) because we perform a binary search\n\n# Space Complexity: \nO(N) to save the topCandidate array and currentVotes dictionary\n\n# Code\n```\n"""\nProblem Link: https://leetcode.com/problems/online-election/\n\nIdea:\n- save an array topCandidate to know which person is leading at a specific time times[i]\n- that array has the same length as persons and times array\n- for each query q, we find the upperBound of q in times array - called it t, then the \ntop candidates person at that q time is topCandidate[t-1]\n\nTime complexity: N is the length of persons/times arrays\n- init: O(N) \n- q: O(lgN) because we perform a binary search\n\nSpace Complexity: O(N) to save the topCandidate array and currentVotes dictionary\n"""\n\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n n = len(times)\n self.topCandidate = deque()\n self.times = times\n currentVotes = defaultdict(lambda: 0)\n currentMax = 0\n\n for i in range(n):\n votedPerson = persons[i]\n currentVotes[votedPerson] += 1\n currentPersonVotes = currentVotes[votedPerson]\n if currentPersonVotes >= currentMax:\n self.topCandidate.append(persons[i])\n currentMax = currentPersonVotes \n else:\n currentTop = self.topCandidate[-1]\n self.topCandidate.append(currentTop)\n\n def q(self, t: int) -> int:\n # def findUpperBound(arr, target):\n # right = len(arr) - 1\n # left = 0\n # ans = len(arr)\n\n # while left <= right:\n # mid = (left+right) // 2\n # if arr[mid] > target:\n # ans = mid\n # right = mid - 1\n # else:\n # left = mid + 1\n\n # return ans\n\n # upperBound = findUpperBound(self.times, t)\n upperBound = bisect_right(self.times, t)\n return self.topCandidate[upperBound-1]\n \n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n\n```
0
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
Details solution with comments | Binary Search
online-election
0
1
# Idea:\n- save an array topCandidate to know which person is leading at a specific time times[i]\n- that array has the same length as persons and times array\n- for each query q, we find the upperBound of q in times array - called it t, then the \ntop candidates person at that q time is topCandidate[t-1]\n\n# # Time complexity: \nN is the length of persons/times arrays\n- init: O(N) \n- q: O(lgN) because we perform a binary search\n\n# Space Complexity: \nO(N) to save the topCandidate array and currentVotes dictionary\n\n# Code\n```\n"""\nProblem Link: https://leetcode.com/problems/online-election/\n\nIdea:\n- save an array topCandidate to know which person is leading at a specific time times[i]\n- that array has the same length as persons and times array\n- for each query q, we find the upperBound of q in times array - called it t, then the \ntop candidates person at that q time is topCandidate[t-1]\n\nTime complexity: N is the length of persons/times arrays\n- init: O(N) \n- q: O(lgN) because we perform a binary search\n\nSpace Complexity: O(N) to save the topCandidate array and currentVotes dictionary\n"""\n\nclass TopVotedCandidate:\n\n def __init__(self, persons: List[int], times: List[int]):\n n = len(times)\n self.topCandidate = deque()\n self.times = times\n currentVotes = defaultdict(lambda: 0)\n currentMax = 0\n\n for i in range(n):\n votedPerson = persons[i]\n currentVotes[votedPerson] += 1\n currentPersonVotes = currentVotes[votedPerson]\n if currentPersonVotes >= currentMax:\n self.topCandidate.append(persons[i])\n currentMax = currentPersonVotes \n else:\n currentTop = self.topCandidate[-1]\n self.topCandidate.append(currentTop)\n\n def q(self, t: int) -> int:\n # def findUpperBound(arr, target):\n # right = len(arr) - 1\n # left = 0\n # ans = len(arr)\n\n # while left <= right:\n # mid = (left+right) // 2\n # if arr[mid] > target:\n # ans = mid\n # right = mid - 1\n # else:\n # left = mid + 1\n\n # return ans\n\n # upperBound = findUpperBound(self.times, t)\n upperBound = bisect_right(self.times, t)\n return self.topCandidate[upperBound-1]\n \n\n\n# Your TopVotedCandidate object will be instantiated and called as such:\n# obj = TopVotedCandidate(persons, times)\n# param_1 = obj.q(t)\n\n```
0
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
Python 3 (Update the winner in Hashmap)
online-election
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 collections\nimport bisect\nclass TopVotedCandidate:\n\n def __init__(self, persons, times):\n #we will generate a list of (winner , time) we can do it as a list \n self.times = times\n self.persons = persons\n \n self.arr = [0]*len(persons)\n \n curWinner = -1\n #logic to calculate the winner\n self.mp = collections.defaultdict(int) #key =>Time , value == winner\n \n for i in range(0 ,len(persons)):\n person = self.persons[i]\n time = self.times[i]\n \n self.arr[person]+=1\n \n if curWinner != person:\n if self.arr[curWinner] <= self.arr[person]:\n curWinner = person\n #it means we have a new leader in the election\n self.mp[time] = curWinner\n \n \n \n \n \n \n \n def q(self, t: int) -> int:\n #check the map if we have the value present\n if t in self.mp:\n return self.mp[t]\n \n #if not then we need to find next timestamp smaller than the current one\n \n idx = bisect.bisect_right(self.times , t)-1\n \n return self.mp[self.times[idx]]\n \n\n \n\n\n # Your TopVotedCandidate object will be instantiated and called as such:\n # obj = TopVotedCandidate(persons, times)\n # param_1 = obj.q(t)\n\n\n\n```
0
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
Python 3 (Update the winner in Hashmap)
online-election
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 collections\nimport bisect\nclass TopVotedCandidate:\n\n def __init__(self, persons, times):\n #we will generate a list of (winner , time) we can do it as a list \n self.times = times\n self.persons = persons\n \n self.arr = [0]*len(persons)\n \n curWinner = -1\n #logic to calculate the winner\n self.mp = collections.defaultdict(int) #key =>Time , value == winner\n \n for i in range(0 ,len(persons)):\n person = self.persons[i]\n time = self.times[i]\n \n self.arr[person]+=1\n \n if curWinner != person:\n if self.arr[curWinner] <= self.arr[person]:\n curWinner = person\n #it means we have a new leader in the election\n self.mp[time] = curWinner\n \n \n \n \n \n \n \n def q(self, t: int) -> int:\n #check the map if we have the value present\n if t in self.mp:\n return self.mp[t]\n \n #if not then we need to find next timestamp smaller than the current one\n \n idx = bisect.bisect_right(self.times , t)-1\n \n return self.mp[self.times[idx]]\n \n\n \n\n\n # Your TopVotedCandidate object will be instantiated and called as such:\n # obj = TopVotedCandidate(persons, times)\n # param_1 = obj.q(t)\n\n\n\n```
0
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
Solution
sort-an-array
1
1
```C++ []\nint a[50001]={0};\nint b[50001]={0};\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& v) {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n for(auto x:v){\n if(x>=0)\n a[x]++;\n else\n b[-x]++;\n }\n v.clear();\n for(int i=50000;i>=1;i--){\n if(b[i]){\n while(b[i]){\n v.push_back(-i);\n b[i]--;\n }\n }\n }\n for(int i=0;i<=50000;i++){\n if(a[i]){\n while(a[i]){\n v.push_back(i);\n a[i]--;\n }\n }\n }\n return v;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n return nums\n```\n\n```Java []\nclass Solution {\n public int[] sortArray(int[] nums) {\n int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;\n for (int num : nums) {\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n if (min == max) {\n return nums;\n }\n int[] count = new int[max - min + 1];\n for (int num : nums) {\n ++count[num - min];\n }\n int N = nums.length, i = 0;\n int[] res = new int[N];\n for (int num = min; num <= max; ++num) {\n while (count[num - min] > 0) {\n res[i++] = num;\n --count[num - min];\n }\n }\n return res;\n }\n}\n```\n
1
Given an array of integers `nums`, sort the array in ascending order and return it. You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible. **Example 1:** **Input:** nums = \[5,2,3,1\] **Output:** \[1,2,3,5\] **Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). **Example 2:** **Input:** nums = \[5,1,1,2,0,0\] **Output:** \[0,0,1,1,2,5\] **Explanation:** Note that the values of nums are not necessairly unique. **Constraints:** * `1 <= nums.length <= 5 * 104` * `-5 * 104 <= nums[i] <= 5 * 104`
null
Solution
sort-an-array
1
1
```C++ []\nint a[50001]={0};\nint b[50001]={0};\nclass Solution {\npublic:\n vector<int> sortArray(vector<int>& v) {\n ios_base::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n for(auto x:v){\n if(x>=0)\n a[x]++;\n else\n b[-x]++;\n }\n v.clear();\n for(int i=50000;i>=1;i--){\n if(b[i]){\n while(b[i]){\n v.push_back(-i);\n b[i]--;\n }\n }\n }\n for(int i=0;i<=50000;i++){\n if(a[i]){\n while(a[i]){\n v.push_back(i);\n a[i]--;\n }\n }\n }\n return v;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n nums.sort()\n return nums\n```\n\n```Java []\nclass Solution {\n public int[] sortArray(int[] nums) {\n int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;\n for (int num : nums) {\n min = Math.min(min, num);\n max = Math.max(max, num);\n }\n if (min == max) {\n return nums;\n }\n int[] count = new int[max - min + 1];\n for (int num : nums) {\n ++count[num - min];\n }\n int N = nums.length, i = 0;\n int[] res = new int[N];\n for (int num = min; num <= max; ++num) {\n while (count[num - min] > 0) {\n res[i++] = num;\n --count[num - min];\n }\n }\n return res;\n }\n}\n```\n
1
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
RADIX SORT PYTHON
sort-an-array
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```\nfrom functools import reduce\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n l=[]\n l2=[]\n for x in nums:\n if x <0:\n l.append(x)\n else:\n l2.append(x)\n A=Solution.neg(l2)\n c=Solution.neg(l)\n d=[-x for x in c][::-1]\n return d+A\n \n def neg(nums):\n if nums==[]:return []\n nums=[abs(x) for x in nums]\n a=max(nums)\n b=len(str(a))\n for x in range(0,b):\n B=[[] for x in range(10)]\n for y in range(len(nums)):\n num=nums[y]//10**(x) % 10\n B[num].append(nums[y])\n print(B)\n nums=reduce(lambda x,y:x+y,B)\n return [int(x) for x in nums]\n \n \n```
1
Given an array of integers `nums`, sort the array in ascending order and return it. You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible. **Example 1:** **Input:** nums = \[5,2,3,1\] **Output:** \[1,2,3,5\] **Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5). **Example 2:** **Input:** nums = \[5,1,1,2,0,0\] **Output:** \[0,0,1,1,2,5\] **Explanation:** Note that the values of nums are not necessairly unique. **Constraints:** * `1 <= nums.length <= 5 * 104` * `-5 * 104 <= nums[i] <= 5 * 104`
null
RADIX SORT PYTHON
sort-an-array
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```\nfrom functools import reduce\nclass Solution:\n def sortArray(self, nums: List[int]) -> List[int]:\n l=[]\n l2=[]\n for x in nums:\n if x <0:\n l.append(x)\n else:\n l2.append(x)\n A=Solution.neg(l2)\n c=Solution.neg(l)\n d=[-x for x in c][::-1]\n return d+A\n \n def neg(nums):\n if nums==[]:return []\n nums=[abs(x) for x in nums]\n a=max(nums)\n b=len(str(a))\n for x in range(0,b):\n B=[[] for x in range(10)]\n for y in range(len(nums)):\n num=nums[y]//10**(x) % 10\n B[num].append(nums[y])\n print(B)\n nums=reduce(lambda x,y:x+y,B)\n return [int(x) for x in nums]\n \n \n```
1
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Solution
cat-and-mouse
1
1
```C++ []\nclass Solution {\npublic:\n int catMouseGame(vector<vector<int>>& graph) {\n enum class State { Draw, MouseWin, CatWin };\n const int n = static_cast<int>(graph.size());\n State states[50][50][2];\n int out_degree[50][50][2] = {};\n std::memset(states, 0, sizeof(states));\n std::queue<std::tuple<int, int, int, State> > q;\n for (int cat = 0; cat < n; ++cat)\n {\n for (int mouse = 0; mouse < n; ++mouse)\n {\n auto hole = std::count(graph[cat].begin(), graph[cat].end(), 0);\n out_degree[cat][mouse][0] = static_cast<int>(graph[mouse].size());\n out_degree[cat][mouse][1] = static_cast<int>(graph[cat].size())\n - static_cast<int>(hole);\n }\n }\n for (int cat = 1; cat < n; ++cat)\n for (int move = 0; move < 2; ++move)\n q.emplace(cat, 0, move, states[cat][0][move] = State::MouseWin),\n q.emplace(cat, cat, move, states[cat][cat][move] = State::CatWin);\n while (!q.empty())\n {\n const auto [cat, mouse, move, state] = q.front();\n q.pop();\n if ((cat == 2) && (mouse == 1) && (move == 0))\n return static_cast<int>(state);\n const int prevMove = move ^ 1;\n for (const int prev : graph[prevMove?cat:mouse])\n {\n const int prevCat = prevMove?prev:cat;\n if (prevCat == 0) continue;\n const int prevMouse = prevMove?mouse:prev;\n if (states[prevCat][prevMouse][prevMove] != State::Draw) continue;\n if (((prevMove == 0) && (state == State::MouseWin))\n || ((prevMove == 1) && (state == State::CatWin))\n || (--out_degree[prevCat][prevMouse][prevMove] == 0))\n states[prevCat][prevMouse][prevMove] = state,\n q.emplace(prevCat, prevMouse, prevMove, state);\n }\n }\n return static_cast<int>(states[2][1][0]);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n n = len(graph)\n dp = [ [{"c":0, "m":0} for j in range(n)] for i in range(n) ]\n outdegree = [ [{"c":len(graph[j])-(0 in graph[j]), "m":len(graph[i])} for j in range(n)] for i in range(n) ]\n nodes = []\n for j in range(1,n):\n dp[0][j]["m"] = dp[0][j]["c"] = 1\n nodes.extend( [(0,j,"m",1), (0,j,"c",1)] )\n dp[j][j]["m"] = dp[j][j]["c"] = 2\n nodes.extend( [(j,j,"m",2), (j,j,"c",2)])\n \n while nodes:\n nodes_new = []\n for i, j, move, result in nodes:\n if i==1 and j==2 and move=="m": return result\n premove = "c" if move=="m" else "m"\n if premove=="c":\n for j_ in graph[j]:\n if j_==0: continue\n if dp[i][j_]["c"]: continue\n if result==2:\n dp[i][j_]["c"] = 2; nodes_new.append((i,j_,"c",2))\n else:\n outdegree[i][j_]["c"]-=1\n if outdegree[i][j_]["c"]==0:\n dp[i][j_]["c"] = 1; nodes_new.append((i,j_,"c",1))\n else: # premove=="m"\n for i_ in graph[i]:\n if dp[i_][j]["m"]: continue\n if result==1:\n dp[i_][j]["m"] = 1; nodes_new.append((i_,j,"m",1))\n else:\n outdegree[i_][j]["m"]-=1\n if outdegree[i_][j]["m"]==0:\n dp[i_][j]["m"] = 2; nodes_new.append((i_,j,"m",2))\n nodes = nodes_new\n return dp[1][2]["m"]\n```\n\n```Java []\nclass Solution {\n public int catMouseGame(int[][] graph) {\n int n = graph.length;\n\n int[] nonZeroNeighbor = new int[n];\n for(int i = 0; i < n; i++){\n nonZeroNeighbor[i] = graph[i].length;\n for(int neighbor : graph[i]){\n if(neighbor == 0){\n nonZeroNeighbor[i]--;\n break;\n }\n }\n }\n int[][][] nextStateCount = new int[n][n][2];\n for(int mousePos = 0; mousePos < n; mousePos++){\n for(int catPos = 0; catPos < n; catPos++){\n nextStateCount[mousePos][catPos][0] = graph[mousePos].length;\n nextStateCount[mousePos][catPos][1] = nonZeroNeighbor[catPos];\n }\n }\n int[][][] dp = new int[n][n][2];\n Queue<int[]> queue = new ArrayDeque<>();\n for(int catPos = 1; catPos < n; catPos++){\n for(int turn = 0; turn <= 1; turn++){\n dp[0][catPos][turn] = 1;\n queue.offer(new int[]{0, catPos, turn, 1});\n dp[catPos][catPos][turn] = 2;\n queue.offer(new int[]{catPos, catPos, turn, 2});\n }\n }\n while(!queue.isEmpty()){\n int[] curr = queue.poll();\n int mousePos = curr[0], catPos = curr[1], turn = curr[2], result = curr[3];\n if(turn == 0){\n if(mousePos == 1 && catPos == 2)\n return result;\n for(int prev : graph[catPos]){\n if(prev == 0 || dp[mousePos][prev][1] != 0)\n continue;\n if(result == 2 || --nextStateCount[mousePos][prev][1] == 0){\n dp[mousePos][prev][1] = result;\n queue.offer(new int[]{mousePos, prev, 1, result});\n }\n }\n } else {\n for(int prev : graph[mousePos]){\n if(dp[prev][catPos][0] != 0)\n continue;\n if(result == 1 || --nextStateCount[prev][catPos][0] == 0){\n dp[prev][catPos][0] = result;\n queue.offer(new int[]{prev, catPos, 0, result});\n }\n }\n }\n }\n return dp[1][2][0];\n }\n}\n```\n
1
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`. During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`. Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: * If ever the Cat occupies the same node as the Mouse, the Cat wins. * If ever the Mouse reaches the Hole, the Mouse wins. * If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a `graph`, and assuming both players play optimally, return * `1` if the mouse wins the game, * `2` if the cat wins the game, or * `0` if the game is a draw. **Example 1:** **Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\] **Output:** 1 **Constraints:** * `3 <= graph.length <= 50` * `1 <= graph[i].length < graph.length` * `0 <= graph[i][j] < graph.length` * `graph[i][j] != i` * `graph[i]` is unique. * The mouse and the cat can always move.
null
Solution
cat-and-mouse
1
1
```C++ []\nclass Solution {\npublic:\n int catMouseGame(vector<vector<int>>& graph) {\n enum class State { Draw, MouseWin, CatWin };\n const int n = static_cast<int>(graph.size());\n State states[50][50][2];\n int out_degree[50][50][2] = {};\n std::memset(states, 0, sizeof(states));\n std::queue<std::tuple<int, int, int, State> > q;\n for (int cat = 0; cat < n; ++cat)\n {\n for (int mouse = 0; mouse < n; ++mouse)\n {\n auto hole = std::count(graph[cat].begin(), graph[cat].end(), 0);\n out_degree[cat][mouse][0] = static_cast<int>(graph[mouse].size());\n out_degree[cat][mouse][1] = static_cast<int>(graph[cat].size())\n - static_cast<int>(hole);\n }\n }\n for (int cat = 1; cat < n; ++cat)\n for (int move = 0; move < 2; ++move)\n q.emplace(cat, 0, move, states[cat][0][move] = State::MouseWin),\n q.emplace(cat, cat, move, states[cat][cat][move] = State::CatWin);\n while (!q.empty())\n {\n const auto [cat, mouse, move, state] = q.front();\n q.pop();\n if ((cat == 2) && (mouse == 1) && (move == 0))\n return static_cast<int>(state);\n const int prevMove = move ^ 1;\n for (const int prev : graph[prevMove?cat:mouse])\n {\n const int prevCat = prevMove?prev:cat;\n if (prevCat == 0) continue;\n const int prevMouse = prevMove?mouse:prev;\n if (states[prevCat][prevMouse][prevMove] != State::Draw) continue;\n if (((prevMove == 0) && (state == State::MouseWin))\n || ((prevMove == 1) && (state == State::CatWin))\n || (--out_degree[prevCat][prevMouse][prevMove] == 0))\n states[prevCat][prevMouse][prevMove] = state,\n q.emplace(prevCat, prevMouse, prevMove, state);\n }\n }\n return static_cast<int>(states[2][1][0]);\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n n = len(graph)\n dp = [ [{"c":0, "m":0} for j in range(n)] for i in range(n) ]\n outdegree = [ [{"c":len(graph[j])-(0 in graph[j]), "m":len(graph[i])} for j in range(n)] for i in range(n) ]\n nodes = []\n for j in range(1,n):\n dp[0][j]["m"] = dp[0][j]["c"] = 1\n nodes.extend( [(0,j,"m",1), (0,j,"c",1)] )\n dp[j][j]["m"] = dp[j][j]["c"] = 2\n nodes.extend( [(j,j,"m",2), (j,j,"c",2)])\n \n while nodes:\n nodes_new = []\n for i, j, move, result in nodes:\n if i==1 and j==2 and move=="m": return result\n premove = "c" if move=="m" else "m"\n if premove=="c":\n for j_ in graph[j]:\n if j_==0: continue\n if dp[i][j_]["c"]: continue\n if result==2:\n dp[i][j_]["c"] = 2; nodes_new.append((i,j_,"c",2))\n else:\n outdegree[i][j_]["c"]-=1\n if outdegree[i][j_]["c"]==0:\n dp[i][j_]["c"] = 1; nodes_new.append((i,j_,"c",1))\n else: # premove=="m"\n for i_ in graph[i]:\n if dp[i_][j]["m"]: continue\n if result==1:\n dp[i_][j]["m"] = 1; nodes_new.append((i_,j,"m",1))\n else:\n outdegree[i_][j]["m"]-=1\n if outdegree[i_][j]["m"]==0:\n dp[i_][j]["m"] = 2; nodes_new.append((i_,j,"m",2))\n nodes = nodes_new\n return dp[1][2]["m"]\n```\n\n```Java []\nclass Solution {\n public int catMouseGame(int[][] graph) {\n int n = graph.length;\n\n int[] nonZeroNeighbor = new int[n];\n for(int i = 0; i < n; i++){\n nonZeroNeighbor[i] = graph[i].length;\n for(int neighbor : graph[i]){\n if(neighbor == 0){\n nonZeroNeighbor[i]--;\n break;\n }\n }\n }\n int[][][] nextStateCount = new int[n][n][2];\n for(int mousePos = 0; mousePos < n; mousePos++){\n for(int catPos = 0; catPos < n; catPos++){\n nextStateCount[mousePos][catPos][0] = graph[mousePos].length;\n nextStateCount[mousePos][catPos][1] = nonZeroNeighbor[catPos];\n }\n }\n int[][][] dp = new int[n][n][2];\n Queue<int[]> queue = new ArrayDeque<>();\n for(int catPos = 1; catPos < n; catPos++){\n for(int turn = 0; turn <= 1; turn++){\n dp[0][catPos][turn] = 1;\n queue.offer(new int[]{0, catPos, turn, 1});\n dp[catPos][catPos][turn] = 2;\n queue.offer(new int[]{catPos, catPos, turn, 2});\n }\n }\n while(!queue.isEmpty()){\n int[] curr = queue.poll();\n int mousePos = curr[0], catPos = curr[1], turn = curr[2], result = curr[3];\n if(turn == 0){\n if(mousePos == 1 && catPos == 2)\n return result;\n for(int prev : graph[catPos]){\n if(prev == 0 || dp[mousePos][prev][1] != 0)\n continue;\n if(result == 2 || --nextStateCount[mousePos][prev][1] == 0){\n dp[mousePos][prev][1] = result;\n queue.offer(new int[]{mousePos, prev, 1, result});\n }\n }\n } else {\n for(int prev : graph[mousePos]){\n if(dp[prev][catPos][0] != 0)\n continue;\n if(result == 1 || --nextStateCount[prev][catPos][0] == 0){\n dp[prev][catPos][0] = result;\n queue.offer(new int[]{prev, catPos, 0, result});\n }\n }\n }\n }\n return dp[1][2][0];\n }\n}\n```\n
1
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Python3 FT 90%, Basically SPFA to Address the Pitfalls of Naive DFS
cat-and-mouse
0
1
# Intro\n\nThis problem took me FOREVER to solve, but it really clarified a lot of things about how game problems, DFS, and SPFA relate to each other. And what assumptions must hold to use DFS to solve problems in general. So I hope it helps.\n\nHopefully this solution helps. As a TLDR/summary:\n* DFS doesn\'t work because of draws (infinite loops of repeating moves) and because the graph has cycles (so there are no obvious base cases in top-down DFS in general)\n* so instead we use what is basically SPFA to solve the problem from the bottom up\n * we label game states that result in a mouse or cat victory with their winner, the base cases of DFS\n * then we enqueue all "adjacent" states, i.e. those where a player can make a move that results in the base case\n * then we keep popping elements from the queue and processing them. if we now know the solution, then we enqueue their neighbors\n* eventually for every state we end up with\n * a known winner for that state\n * or we *still* don\'t know the answer - this means neither player was able to force a win from that state, so optimal play means they draw.\n\n# Intuition\n\nThe basic pattern behind all "who wins if both players play optimally" problems is this:\n* let the state of the game be `s`, in this case coordinates `(m, c, player)` that tell us where the mouse and cat are, and who\'s going next. I use `p` instead of `player` to keep things shorter\n * many game problems on LC don\'t need `p` because both players can make the same moves. But in this game, the cat can\'t move to 0 so we need to know who\'s playing when iterating over moves (see below)\n* conceptually (and often literally, but not in this case) we have a function `result(s)` that tells the result of the game starting from state `s` if both players play optimally\n* to play optimally from state `s`, the player looks at all possible moves they can make, each resulting in a new state `s\'`\n * if `result(s\')` is `p` winning for ANY of the `s\'`, then this means `p` can force a win by making that play. So the `result(s) == p wins`\n * otherwise `p` can\'t win starting at `s`. If at least one `result(s\')` is a draw, then `p` can avoid losing though. So `result(s) == draw`\n * otherwise, `p` loses no matter what move they make. `result(s) == p\' wins`\n\nDefinitely check out some easier game problems first if this is confusing - you\'ll find that all of the straightforward Nim game solutions follow this pattern! (some have fancy math solutions, which is great for speed but terrible for understanding how to approach these problems in general).\n\n**Usually** you can use top-down DFS with caching to solve the problem.\n* write your `result(s)` function\n* add caching so you only compute `result(s)` once for each state `s`\n* and then you\'re done!\n\n**But there\'s a catch:** in most game theory problems, the sequences of moves `s -> s\' -> s\'\' -> ...` never forms a loop. That\'s because some player is removing an element from a pile, moving forward toward a goal, etc.\n\nBut in this problem, the players move on a graph. And that graph can have loops.\n\nSo if you try the usual DFS+caching, you\'ll end up with an infinite loop. The reason for this is the players draw by repeating moves forever in a cycle `s -> s\' -> s\'\' -> .. -> s`. In the DFS approach, that means `s` calls `result(s\')`. Which calls `result(s\'\')`, etc.\n\nAnother problem you get with the DFS approach is that the graph has loops, so as you apply DFS, you\'ll call `result(s\')` for some state you haven\'t solved yet.\n* if you mark it as a draw, it might be wrong. It might be a draw, or it might be a win for either play but you just don\'t know that yet because you haven\'t explored the whole graph\n* if you leave it as "unknown" (`UNK` in the code) then DFS may not return to that node later, after more states have been solved, to see if it has an answer yet.\n\n# Approach\n\nThe problems with DFS are\n* you can end up in an infinite loop\n* `result(s)` depends on the `result(s\')` for each next state `s\'`. If the states for some `s\'` aren\'t known yet, then we can\'t know `result(s)` yet. But we have to make sure we revisit `result(s)` when we learn more of the `result(s)`\n\nTo address both of these we basically apply DFS "backwards:"\n* we start with the base cases: situations where the cat and mouse win. So we\'ll set `cache(s\')` to the result\n* we\'ll also mark some situations as `BAD`, i.e. where the cat is at the hole, so they are ignored\n* then we\'ll enqueue `s` such that there is a valid move `s -> s\'` and `s\'` is our base case. This is the "backwards" part of "apply DFS backwards"\n* each time we pop a state with unknown `result(s\')` we check if we can now determine who wins (we look at all moves `s\' -> s\'\'` as explained above)\n * if we find out that someone can win, we set `cache(s\')` to the result, and enqueue all `s` where `s -> s\'` is a valid move to the queue if we don\'t already know `result(s)`\n * otherwise we do nothing. if later iterations discover someone wins or loses from a next state we need, then this will be re-enqueued. If not, then we\'ll reach the end of the algorithm without determining a winner. This means there is a draw.\n\nSo in other words, the idea is to start with our base cases `s\'`, then see which "adjacent" states `s` where `s -> s\'` we can solve. Each time we solve a new state, we enqueue *its* adjacent states to solve them, and so on.\n\n**The connection to SPFA:** suprisingly it\'s almost identical. In SPFA we \n* start with the distance to the source node being 0 (the base case),* then iterate over all possible edges (the possible moves).\n* if an edge results in a new shortest path to the other node (or in this case, a known winner for the next state), then we enqueue it to revisit that node to discover shorter paths (or in this case, revisit adjacent states to see if either player can force a win from that state).\n* repeat this process forever until the queue is exhausted\n\nTo summarize, the algorithm has the following:\n* a queue of unsolved states `(m, c, p)` that has the mouse and cat coordinates `m` and `c`, and the current player `p`\n* a set that lets us check in `O(1)` if some state is already enqueued\n* a table `W[p][m][c]` that contains the winner if known, otherwise `UNK`\n* a helper method `updateNeighbors` that handles enqueuing things\n* and a main SPFA-like loop that checks if we now know the solution for each unknown state `s\'`, and if so, enqueing the neighbors `s` that depend on it - now that we solved `s\'`, we may be able to solve `s` now.\n\n# Complexity\n\nTC for the base cases is $O(V+E)$ for $V$ nodes and $E$ edges. The main loop is basically SPFA, which has a worst-case running time of $O(V E)$.\n\n$V$ and $E$ are the nodes and edges in the state graph, not the number of nodes in the input graph. $V = 2 N^2$ because for each node in the input, there are two players and all pairwise combinations of those nodes for the state. Same thing I think for the edges, for each input edge we have all possible other nodes and edges for the other player.\n\nSo in terms of the input values I think the complexity is $O(N^2 E^2)$ for $N$ input nodes and $E$ input edges.\n\nSC is mainly the giant cache/table we make, with all `2 N^2` states. So $O(N^2)$.\n\n\n# Code\n```\nclass Solution:\n def catMouseGame(self, adj: List[List[int]]) -> int:\n # What I tried:\n # BFS/DFS (considered only) - we need to play optimally, not explore all paths. NEXT.\n # "dual DFS," a mouseResult(m, c) and catResult(m, c) function that call each other.\n # If we encounter a state that we\'ve already seen that means it\'s a draw***.\n\n # Spoiler alert: *** is WRONG. If we\'ve seen the state in DFS, it means that we don\'t\n # have an answer yet. NOT that it\'s necessarily a loop.\n\n # Example: suppose the state is (m, c, player) where\n # m, c are the mouse and cat locations\n # player is whose turn it is to play\n\n # Some states are easy, like (m, c, mouse) where m is adjacent to zero.\n # Mouse moves to 0 and wins.\n\n # Or anything of the form (m, c, cat) where m is adjacent to cat\n\n # For DP we have a table and fill it out deterministically in a known pattern\n # For DFS we automatically fill in the table (the code determines the recurrence rel.)\n # but we know that all the calls will terminate in a base case.\n\n # But in this case we can have loops, or things where we don\'t know the result for (m, c, p) *yet*,\n # but will know later as we fill in more of the graph\n\n UNK = 0 # for easy "if not state: <fill in that state>"\n MOUSE_WINS = 1\n CAT_WINS = 2\n BAD = 3 # mainly for cat-is-at-0 stuff\n\n MOUSE = 0\n CAT = 1\n\n # we\'ll use BFS in SPFA style, basically graph coloring/relaxation\n # 1. we\'ll fill in some easy base cases: mouse victory and cat victory, and the illegal states\n # 2. queue adjacent nodes\n # 3. then process the queue - if a state\'s result (mouse/cat/draw) is known, we fill it in an enqueue\n # its neighbors. otherwise just drop it - either we\'ll enqueue it again when we learn more, or discard it\n\n n = len(adj)\n q = deque()\n enq = set()\n W = [[[UNK]*n for _ in range(n)] for _ in range(2)] # W[p][m][c]; p==0 is mouse, p == 1 is cat\n \n def updateNeighbors(m, c, p):\n """Enqueues unsolved problems (m\', c\', 1-p) that depend on the result of m,c,p."""\n if p == MOUSE:\n # things depending on this are states (m, c\', CAT): after the cat moves from c\' to c,\n # the result is W[p][m][c] \n for c2 in adj[c]:\n if c2 == 0:\n continue\n\n if W[CAT][m][c2] == UNK:\n state = (m, c2, CAT)\n if state not in enq:\n enq.add(state)\n q.append(state)\n else:\n for m2 in adj[m]:\n if W[MOUSE][m2][c] == UNK:\n state = (m2, c, MOUSE)\n if state not in enq:\n enq.add(state)\n q.append(state)\n\n # set results for base cases and enqueue neighbors\n\n # if the mouse reaches the hole it wins\n for c in range(1, n):\n for p in [MOUSE, CAT]: # BUG 1: NEED TO ADD ALL BASE CASES, before was just mouse. Need to make sure mouse knows moving to (c, c, cat) is a loss\n W[p][0][c] = MOUSE_WINS # ..[CAT] because it\'s the cat\'s turn after the mouse moves to the hole\n updateNeighbors(0, c, p)\n\n # if the cat reaches the mouse, the cat wins\n for m in range(1, n):\n for p in [MOUSE, CAT]: # BUG 1: same thing\n W[p][m][m] = CAT_WINS\n updateNeighbors(m, m, p)\n\n # cat isn\'t allowed to be at the hole node on anyone\'s turn\n for m in range(1, n):\n for p in [MOUSE, CAT]:\n W[p][m][0] = BAD\n\n # and now for the heavy lifting\n while q:\n state = q.popleft()\n enq.remove(state)\n m, c, p = state\n\n if W[p][m][c]:\n # this can occur at the beginning when we enqueue neighbors of\n # the base cases - those neighbors themselves may also be base cases\n continue\n\n if m == c:\n raise RuntimeError("m == c: (m, c, p) =", (m, c, p))\n\n if p == MOUSE:\n # consider all moves, and the result of the game from there\n # if any of those states is MOUSE_WINS, then the mouse can force a win\n # if all valid adj states are CAT_WINS, then the cat wins\n # otherwise either\n # - it\'s a draw: cat and mouse can repeat moves forever\n # - or we still don\'t know enough. this state will be re-enqueued if/when we learn more\n foundUnk = False\n for m2 in adj[m]:\n if W[CAT][m2][c] == MOUSE_WINS:\n if m == 1 and c == 2:\n return MOUSE_WINS\n W[MOUSE][m][c] = MOUSE_WINS\n updateNeighbors(m, c, MOUSE) # BUG 2: FORGOT TO UPDATE NEIGHBORS\n\n break\n elif W[CAT][m2][c] == UNK:\n foundUnk = True # record that there\'s at least one state we don\'t know\n # can\'t mark it as a draw or CAT_WINS yet because we don\'t know this\n # node. We may determine its value later as we keep relaxing/coloring\n # the graph\n # else: CAT_WINS or BAD\n\n if W[MOUSE][m][c] == UNK and not foundUnk:\n # we visited all neighbors of this node, and all valid neighbors were CAT_WINS. So CAT_WINS\n if m == 1 and c == 2:\n return CAT_WINS\n W[MOUSE][m][c] = CAT_WINS\n updateNeighbors(m, c, MOUSE)\n # else: need to know 1+ neighbor before we know this state. So\n # hold off until this state is re-enqueued via learning the result\n # of a neighbor\n else: # p == CAT:\n foundUnk = False\n for c2 in adj[c]:\n if c2 == 0:\n continue\n elif W[MOUSE][m][c2] == CAT_WINS:\n W[CAT][m][c] = CAT_WINS # cat can force a win by moving here\n updateNeighbors(m, c, CAT)\n break\n elif W[MOUSE][m][c2] == UNK:\n foundUnk = True\n\n if W[CAT][m][c] == UNK and not foundUnk:\n W[CAT][m][c] = MOUSE_WINS\n updateNeighbors(m, c, CAT)\n\n for p in [MOUSE, CAT]:\n for m in range(n):\n for c in range(n):\n if W[p][m][c] in [MOUSE_WINS, CAT_WINS]:\n print(m, c, \'cat\' if p else \'mouse\', \'->\', \'MOUSE\' if W[p][m][c] == MOUSE_WINS else \'CAT\')\n\n # we solved all states we can solve. the rest are states where neither player can force\n # a win, i.e. a draw\n return 0\n```
0
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`. During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`. Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: * If ever the Cat occupies the same node as the Mouse, the Cat wins. * If ever the Mouse reaches the Hole, the Mouse wins. * If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a `graph`, and assuming both players play optimally, return * `1` if the mouse wins the game, * `2` if the cat wins the game, or * `0` if the game is a draw. **Example 1:** **Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\] **Output:** 1 **Constraints:** * `3 <= graph.length <= 50` * `1 <= graph[i].length < graph.length` * `0 <= graph[i][j] < graph.length` * `graph[i][j] != i` * `graph[i]` is unique. * The mouse and the cat can always move.
null
Python3 FT 90%, Basically SPFA to Address the Pitfalls of Naive DFS
cat-and-mouse
0
1
# Intro\n\nThis problem took me FOREVER to solve, but it really clarified a lot of things about how game problems, DFS, and SPFA relate to each other. And what assumptions must hold to use DFS to solve problems in general. So I hope it helps.\n\nHopefully this solution helps. As a TLDR/summary:\n* DFS doesn\'t work because of draws (infinite loops of repeating moves) and because the graph has cycles (so there are no obvious base cases in top-down DFS in general)\n* so instead we use what is basically SPFA to solve the problem from the bottom up\n * we label game states that result in a mouse or cat victory with their winner, the base cases of DFS\n * then we enqueue all "adjacent" states, i.e. those where a player can make a move that results in the base case\n * then we keep popping elements from the queue and processing them. if we now know the solution, then we enqueue their neighbors\n* eventually for every state we end up with\n * a known winner for that state\n * or we *still* don\'t know the answer - this means neither player was able to force a win from that state, so optimal play means they draw.\n\n# Intuition\n\nThe basic pattern behind all "who wins if both players play optimally" problems is this:\n* let the state of the game be `s`, in this case coordinates `(m, c, player)` that tell us where the mouse and cat are, and who\'s going next. I use `p` instead of `player` to keep things shorter\n * many game problems on LC don\'t need `p` because both players can make the same moves. But in this game, the cat can\'t move to 0 so we need to know who\'s playing when iterating over moves (see below)\n* conceptually (and often literally, but not in this case) we have a function `result(s)` that tells the result of the game starting from state `s` if both players play optimally\n* to play optimally from state `s`, the player looks at all possible moves they can make, each resulting in a new state `s\'`\n * if `result(s\')` is `p` winning for ANY of the `s\'`, then this means `p` can force a win by making that play. So the `result(s) == p wins`\n * otherwise `p` can\'t win starting at `s`. If at least one `result(s\')` is a draw, then `p` can avoid losing though. So `result(s) == draw`\n * otherwise, `p` loses no matter what move they make. `result(s) == p\' wins`\n\nDefinitely check out some easier game problems first if this is confusing - you\'ll find that all of the straightforward Nim game solutions follow this pattern! (some have fancy math solutions, which is great for speed but terrible for understanding how to approach these problems in general).\n\n**Usually** you can use top-down DFS with caching to solve the problem.\n* write your `result(s)` function\n* add caching so you only compute `result(s)` once for each state `s`\n* and then you\'re done!\n\n**But there\'s a catch:** in most game theory problems, the sequences of moves `s -> s\' -> s\'\' -> ...` never forms a loop. That\'s because some player is removing an element from a pile, moving forward toward a goal, etc.\n\nBut in this problem, the players move on a graph. And that graph can have loops.\n\nSo if you try the usual DFS+caching, you\'ll end up with an infinite loop. The reason for this is the players draw by repeating moves forever in a cycle `s -> s\' -> s\'\' -> .. -> s`. In the DFS approach, that means `s` calls `result(s\')`. Which calls `result(s\'\')`, etc.\n\nAnother problem you get with the DFS approach is that the graph has loops, so as you apply DFS, you\'ll call `result(s\')` for some state you haven\'t solved yet.\n* if you mark it as a draw, it might be wrong. It might be a draw, or it might be a win for either play but you just don\'t know that yet because you haven\'t explored the whole graph\n* if you leave it as "unknown" (`UNK` in the code) then DFS may not return to that node later, after more states have been solved, to see if it has an answer yet.\n\n# Approach\n\nThe problems with DFS are\n* you can end up in an infinite loop\n* `result(s)` depends on the `result(s\')` for each next state `s\'`. If the states for some `s\'` aren\'t known yet, then we can\'t know `result(s)` yet. But we have to make sure we revisit `result(s)` when we learn more of the `result(s)`\n\nTo address both of these we basically apply DFS "backwards:"\n* we start with the base cases: situations where the cat and mouse win. So we\'ll set `cache(s\')` to the result\n* we\'ll also mark some situations as `BAD`, i.e. where the cat is at the hole, so they are ignored\n* then we\'ll enqueue `s` such that there is a valid move `s -> s\'` and `s\'` is our base case. This is the "backwards" part of "apply DFS backwards"\n* each time we pop a state with unknown `result(s\')` we check if we can now determine who wins (we look at all moves `s\' -> s\'\'` as explained above)\n * if we find out that someone can win, we set `cache(s\')` to the result, and enqueue all `s` where `s -> s\'` is a valid move to the queue if we don\'t already know `result(s)`\n * otherwise we do nothing. if later iterations discover someone wins or loses from a next state we need, then this will be re-enqueued. If not, then we\'ll reach the end of the algorithm without determining a winner. This means there is a draw.\n\nSo in other words, the idea is to start with our base cases `s\'`, then see which "adjacent" states `s` where `s -> s\'` we can solve. Each time we solve a new state, we enqueue *its* adjacent states to solve them, and so on.\n\n**The connection to SPFA:** suprisingly it\'s almost identical. In SPFA we \n* start with the distance to the source node being 0 (the base case),* then iterate over all possible edges (the possible moves).\n* if an edge results in a new shortest path to the other node (or in this case, a known winner for the next state), then we enqueue it to revisit that node to discover shorter paths (or in this case, revisit adjacent states to see if either player can force a win from that state).\n* repeat this process forever until the queue is exhausted\n\nTo summarize, the algorithm has the following:\n* a queue of unsolved states `(m, c, p)` that has the mouse and cat coordinates `m` and `c`, and the current player `p`\n* a set that lets us check in `O(1)` if some state is already enqueued\n* a table `W[p][m][c]` that contains the winner if known, otherwise `UNK`\n* a helper method `updateNeighbors` that handles enqueuing things\n* and a main SPFA-like loop that checks if we now know the solution for each unknown state `s\'`, and if so, enqueing the neighbors `s` that depend on it - now that we solved `s\'`, we may be able to solve `s` now.\n\n# Complexity\n\nTC for the base cases is $O(V+E)$ for $V$ nodes and $E$ edges. The main loop is basically SPFA, which has a worst-case running time of $O(V E)$.\n\n$V$ and $E$ are the nodes and edges in the state graph, not the number of nodes in the input graph. $V = 2 N^2$ because for each node in the input, there are two players and all pairwise combinations of those nodes for the state. Same thing I think for the edges, for each input edge we have all possible other nodes and edges for the other player.\n\nSo in terms of the input values I think the complexity is $O(N^2 E^2)$ for $N$ input nodes and $E$ input edges.\n\nSC is mainly the giant cache/table we make, with all `2 N^2` states. So $O(N^2)$.\n\n\n# Code\n```\nclass Solution:\n def catMouseGame(self, adj: List[List[int]]) -> int:\n # What I tried:\n # BFS/DFS (considered only) - we need to play optimally, not explore all paths. NEXT.\n # "dual DFS," a mouseResult(m, c) and catResult(m, c) function that call each other.\n # If we encounter a state that we\'ve already seen that means it\'s a draw***.\n\n # Spoiler alert: *** is WRONG. If we\'ve seen the state in DFS, it means that we don\'t\n # have an answer yet. NOT that it\'s necessarily a loop.\n\n # Example: suppose the state is (m, c, player) where\n # m, c are the mouse and cat locations\n # player is whose turn it is to play\n\n # Some states are easy, like (m, c, mouse) where m is adjacent to zero.\n # Mouse moves to 0 and wins.\n\n # Or anything of the form (m, c, cat) where m is adjacent to cat\n\n # For DP we have a table and fill it out deterministically in a known pattern\n # For DFS we automatically fill in the table (the code determines the recurrence rel.)\n # but we know that all the calls will terminate in a base case.\n\n # But in this case we can have loops, or things where we don\'t know the result for (m, c, p) *yet*,\n # but will know later as we fill in more of the graph\n\n UNK = 0 # for easy "if not state: <fill in that state>"\n MOUSE_WINS = 1\n CAT_WINS = 2\n BAD = 3 # mainly for cat-is-at-0 stuff\n\n MOUSE = 0\n CAT = 1\n\n # we\'ll use BFS in SPFA style, basically graph coloring/relaxation\n # 1. we\'ll fill in some easy base cases: mouse victory and cat victory, and the illegal states\n # 2. queue adjacent nodes\n # 3. then process the queue - if a state\'s result (mouse/cat/draw) is known, we fill it in an enqueue\n # its neighbors. otherwise just drop it - either we\'ll enqueue it again when we learn more, or discard it\n\n n = len(adj)\n q = deque()\n enq = set()\n W = [[[UNK]*n for _ in range(n)] for _ in range(2)] # W[p][m][c]; p==0 is mouse, p == 1 is cat\n \n def updateNeighbors(m, c, p):\n """Enqueues unsolved problems (m\', c\', 1-p) that depend on the result of m,c,p."""\n if p == MOUSE:\n # things depending on this are states (m, c\', CAT): after the cat moves from c\' to c,\n # the result is W[p][m][c] \n for c2 in adj[c]:\n if c2 == 0:\n continue\n\n if W[CAT][m][c2] == UNK:\n state = (m, c2, CAT)\n if state not in enq:\n enq.add(state)\n q.append(state)\n else:\n for m2 in adj[m]:\n if W[MOUSE][m2][c] == UNK:\n state = (m2, c, MOUSE)\n if state not in enq:\n enq.add(state)\n q.append(state)\n\n # set results for base cases and enqueue neighbors\n\n # if the mouse reaches the hole it wins\n for c in range(1, n):\n for p in [MOUSE, CAT]: # BUG 1: NEED TO ADD ALL BASE CASES, before was just mouse. Need to make sure mouse knows moving to (c, c, cat) is a loss\n W[p][0][c] = MOUSE_WINS # ..[CAT] because it\'s the cat\'s turn after the mouse moves to the hole\n updateNeighbors(0, c, p)\n\n # if the cat reaches the mouse, the cat wins\n for m in range(1, n):\n for p in [MOUSE, CAT]: # BUG 1: same thing\n W[p][m][m] = CAT_WINS\n updateNeighbors(m, m, p)\n\n # cat isn\'t allowed to be at the hole node on anyone\'s turn\n for m in range(1, n):\n for p in [MOUSE, CAT]:\n W[p][m][0] = BAD\n\n # and now for the heavy lifting\n while q:\n state = q.popleft()\n enq.remove(state)\n m, c, p = state\n\n if W[p][m][c]:\n # this can occur at the beginning when we enqueue neighbors of\n # the base cases - those neighbors themselves may also be base cases\n continue\n\n if m == c:\n raise RuntimeError("m == c: (m, c, p) =", (m, c, p))\n\n if p == MOUSE:\n # consider all moves, and the result of the game from there\n # if any of those states is MOUSE_WINS, then the mouse can force a win\n # if all valid adj states are CAT_WINS, then the cat wins\n # otherwise either\n # - it\'s a draw: cat and mouse can repeat moves forever\n # - or we still don\'t know enough. this state will be re-enqueued if/when we learn more\n foundUnk = False\n for m2 in adj[m]:\n if W[CAT][m2][c] == MOUSE_WINS:\n if m == 1 and c == 2:\n return MOUSE_WINS\n W[MOUSE][m][c] = MOUSE_WINS\n updateNeighbors(m, c, MOUSE) # BUG 2: FORGOT TO UPDATE NEIGHBORS\n\n break\n elif W[CAT][m2][c] == UNK:\n foundUnk = True # record that there\'s at least one state we don\'t know\n # can\'t mark it as a draw or CAT_WINS yet because we don\'t know this\n # node. We may determine its value later as we keep relaxing/coloring\n # the graph\n # else: CAT_WINS or BAD\n\n if W[MOUSE][m][c] == UNK and not foundUnk:\n # we visited all neighbors of this node, and all valid neighbors were CAT_WINS. So CAT_WINS\n if m == 1 and c == 2:\n return CAT_WINS\n W[MOUSE][m][c] = CAT_WINS\n updateNeighbors(m, c, MOUSE)\n # else: need to know 1+ neighbor before we know this state. So\n # hold off until this state is re-enqueued via learning the result\n # of a neighbor\n else: # p == CAT:\n foundUnk = False\n for c2 in adj[c]:\n if c2 == 0:\n continue\n elif W[MOUSE][m][c2] == CAT_WINS:\n W[CAT][m][c] = CAT_WINS # cat can force a win by moving here\n updateNeighbors(m, c, CAT)\n break\n elif W[MOUSE][m][c2] == UNK:\n foundUnk = True\n\n if W[CAT][m][c] == UNK and not foundUnk:\n W[CAT][m][c] = MOUSE_WINS\n updateNeighbors(m, c, CAT)\n\n for p in [MOUSE, CAT]:\n for m in range(n):\n for c in range(n):\n if W[p][m][c] in [MOUSE_WINS, CAT_WINS]:\n print(m, c, \'cat\' if p else \'mouse\', \'->\', \'MOUSE\' if W[p][m][c] == MOUSE_WINS else \'CAT\')\n\n # we solved all states we can solve. the rest are states where neither player can force\n # a win, i.e. a draw\n return 0\n```
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
[Python] Clean Solution with Comments | O(N^3)
cat-and-mouse
0
1
# Code\n```\nclass Solution:\n def catMouseGame(self, g: List[List[int]]) -> int:\n n = len(g)\n dq = deque()\n dp = defaultdict(int) # store who will win 1-mouse, 2-cat\n for t in [1,2]: # start from known states\n for k in range(n):\n dp[(0,k,t)] = 1\n dq.append((0,k,t))\n dp[(k,k,t)] = 2\n dq.append((k,k,t))\n nxt_sc = [[[0]*n for m in range(n)] for t in range(3)] # next state count: outdegree, number of states possible from this state\n for t in range(1,3):\n for m in range(n):\n for c in range(1,n):\n if(t==1): nxt_sc[t][m][c] = len(g[m]);\n else: nxt_sc[t][m][c] = len(g[c]) - (0 in g[c]);\n def parents(m,c,t): # get prev state from given state\n res = []\n for v in g[m if t==2 else c]: # opposite turn, so if current turn is cat then prev should be mouse & viceversa\n if(t==1 and v==0): continue \n if(t==1): res.append((m,v,2))\n if(t==2): res.append((v,c,1))\n return res\n while(dq):\n m,c,t = dq.popleft() # this is nxt state, of which we know the result dp\n r = dp[(m,c,t)]\n for m1,c1,t1 in parents(m,c,t): # prev state which we want to calculate\n if((m1,c1,t1) in dp): continue # if already calculated skip\n if(r==t1): # if nxt state is winning for this animate\n dp[(m1,c1,t1)] = r\n dq.append((m1,c1,t1))\n else:\n nxt_sc[t1][m1][c1] -=1 # decreease the outdegree from next state to this state\n if(nxt_sc[t1][m1][c1]==0): # if all next nodes are losing then no choice but to give up :(\n dp[(m1,c1,t1)] = 3-t1\n dq.append((m1,c1,t1))\n \n \n return dp[(1,2,1)]\n```
0
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`. During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`. Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: * If ever the Cat occupies the same node as the Mouse, the Cat wins. * If ever the Mouse reaches the Hole, the Mouse wins. * If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a `graph`, and assuming both players play optimally, return * `1` if the mouse wins the game, * `2` if the cat wins the game, or * `0` if the game is a draw. **Example 1:** **Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\] **Output:** 1 **Constraints:** * `3 <= graph.length <= 50` * `1 <= graph[i].length < graph.length` * `0 <= graph[i][j] < graph.length` * `graph[i][j] != i` * `graph[i]` is unique. * The mouse and the cat can always move.
null
[Python] Clean Solution with Comments | O(N^3)
cat-and-mouse
0
1
# Code\n```\nclass Solution:\n def catMouseGame(self, g: List[List[int]]) -> int:\n n = len(g)\n dq = deque()\n dp = defaultdict(int) # store who will win 1-mouse, 2-cat\n for t in [1,2]: # start from known states\n for k in range(n):\n dp[(0,k,t)] = 1\n dq.append((0,k,t))\n dp[(k,k,t)] = 2\n dq.append((k,k,t))\n nxt_sc = [[[0]*n for m in range(n)] for t in range(3)] # next state count: outdegree, number of states possible from this state\n for t in range(1,3):\n for m in range(n):\n for c in range(1,n):\n if(t==1): nxt_sc[t][m][c] = len(g[m]);\n else: nxt_sc[t][m][c] = len(g[c]) - (0 in g[c]);\n def parents(m,c,t): # get prev state from given state\n res = []\n for v in g[m if t==2 else c]: # opposite turn, so if current turn is cat then prev should be mouse & viceversa\n if(t==1 and v==0): continue \n if(t==1): res.append((m,v,2))\n if(t==2): res.append((v,c,1))\n return res\n while(dq):\n m,c,t = dq.popleft() # this is nxt state, of which we know the result dp\n r = dp[(m,c,t)]\n for m1,c1,t1 in parents(m,c,t): # prev state which we want to calculate\n if((m1,c1,t1) in dp): continue # if already calculated skip\n if(r==t1): # if nxt state is winning for this animate\n dp[(m1,c1,t1)] = r\n dq.append((m1,c1,t1))\n else:\n nxt_sc[t1][m1][c1] -=1 # decreease the outdegree from next state to this state\n if(nxt_sc[t1][m1][c1]==0): # if all next nodes are losing then no choice but to give up :(\n dp[(m1,c1,t1)] = 3-t1\n dq.append((m1,c1,t1))\n \n \n return dp[(1,2,1)]\n```
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Python3 solution
cat-and-mouse
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 catMouseGame(self, graph: List[List[int]]) -> int:\n def getprestates(m ,c ,t):\n ans = []\n if t == 1:\n for c2 in graph[c]:\n if not c2: continue\n ans.append((m, c2, 2))\n else:\n for m2 in graph[m]:\n ans.append((m2, c, 1))\n return ans\n\n def nextfails(m, c, t):\n if t == 1:\n for m2 in graph[m]:\n if res[(m2, c, 2)] != 2: return False\n else:\n for c2 in graph[c]:\n if not c2: continue\n if res[(m, c2, 1)] != 1: return False\n \n return True\n\n res = defaultdict(int) # mouse, cat, turns\n q = deque()\n\n for t in range(1, 3):\n for i in range(1, len(graph)):\n #mouse wins\n res[(0, i, t)] = 1\n q.append((0, i, t))\n\n #cat wins\n res[(i, i, t)] = 2\n q.append((i, i, t))\n \n while q:\n mouse, cat, turn = q.popleft()\n r = res[(mouse, cat, turn)]\n\n for m, c, t in getprestates(mouse, cat, turn):\n r2 = res[(m, c, t)]\n if r2:\n continue\n \n #populate prestate\n if r == 3 - turn:\n res[(m, c, t)] = r\n q.append((m, c, r))\n elif nextfails(m, c, t):\n res[(m, c, t)] = 3 - t\n q.append((m, c, t))\n\n\n return res[(1, 2, 1)]\n\n\n # @lru_cache(None)\n # def play(mouse, cat, moves):\n # if moves > len(graph) * 2: return 0 # This is if we have a cycle\n # if mouse == cat: return 2 # cat wins\n # if not mouse: return 1 # mouse wins\n\n # #mouse turn\n # if not moves % 2:\n # can_draw = False\n # for nei in graph[mouse]:\n # endgame = play(nei, cat, moves + 1)\n # if endgame == 1: return 1\n # if not endgame: can_draw = True\n # return 0 if can_draw else 2\n\n # #cat turn\n # else:\n # can_draw = False\n # for nei in graph[cat]:\n # if not nei: continue # Cat cannot go to zero node\n # endgame = play(mouse, nei, moves + 1)\n # if endgame == 2: return 2\n # if not endgame: can_draw = True\n # return 0 if can_draw else 1\n \n # return play(1, 2, 0)\n \n\n \n```
0
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`. During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`. Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: * If ever the Cat occupies the same node as the Mouse, the Cat wins. * If ever the Mouse reaches the Hole, the Mouse wins. * If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a `graph`, and assuming both players play optimally, return * `1` if the mouse wins the game, * `2` if the cat wins the game, or * `0` if the game is a draw. **Example 1:** **Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\] **Output:** 1 **Constraints:** * `3 <= graph.length <= 50` * `1 <= graph[i].length < graph.length` * `0 <= graph[i][j] < graph.length` * `graph[i][j] != i` * `graph[i]` is unique. * The mouse and the cat can always move.
null
Python3 solution
cat-and-mouse
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 catMouseGame(self, graph: List[List[int]]) -> int:\n def getprestates(m ,c ,t):\n ans = []\n if t == 1:\n for c2 in graph[c]:\n if not c2: continue\n ans.append((m, c2, 2))\n else:\n for m2 in graph[m]:\n ans.append((m2, c, 1))\n return ans\n\n def nextfails(m, c, t):\n if t == 1:\n for m2 in graph[m]:\n if res[(m2, c, 2)] != 2: return False\n else:\n for c2 in graph[c]:\n if not c2: continue\n if res[(m, c2, 1)] != 1: return False\n \n return True\n\n res = defaultdict(int) # mouse, cat, turns\n q = deque()\n\n for t in range(1, 3):\n for i in range(1, len(graph)):\n #mouse wins\n res[(0, i, t)] = 1\n q.append((0, i, t))\n\n #cat wins\n res[(i, i, t)] = 2\n q.append((i, i, t))\n \n while q:\n mouse, cat, turn = q.popleft()\n r = res[(mouse, cat, turn)]\n\n for m, c, t in getprestates(mouse, cat, turn):\n r2 = res[(m, c, t)]\n if r2:\n continue\n \n #populate prestate\n if r == 3 - turn:\n res[(m, c, t)] = r\n q.append((m, c, r))\n elif nextfails(m, c, t):\n res[(m, c, t)] = 3 - t\n q.append((m, c, t))\n\n\n return res[(1, 2, 1)]\n\n\n # @lru_cache(None)\n # def play(mouse, cat, moves):\n # if moves > len(graph) * 2: return 0 # This is if we have a cycle\n # if mouse == cat: return 2 # cat wins\n # if not mouse: return 1 # mouse wins\n\n # #mouse turn\n # if not moves % 2:\n # can_draw = False\n # for nei in graph[mouse]:\n # endgame = play(nei, cat, moves + 1)\n # if endgame == 1: return 1\n # if not endgame: can_draw = True\n # return 0 if can_draw else 2\n\n # #cat turn\n # else:\n # can_draw = False\n # for nei in graph[cat]:\n # if not nei: continue # Cat cannot go to zero node\n # endgame = play(mouse, nei, moves + 1)\n # if endgame == 2: return 2\n # if not endgame: can_draw = True\n # return 0 if can_draw else 1\n \n # return play(1, 2, 0)\n \n\n \n```
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Simple Explained Solution
cat-and-mouse
0
1
\n```\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n def getPreStates(m,c,t):\n ans = []\n if t == 1:\n for c2 in graph[c]:\n if c2 == 0:continue\n ans.append((m,c2,2))\n else:\n for m2 in graph[m]:\n ans.append((m2,c,1))\n return ans\n \n def ifAllNextMovesFailed(m,c,t):\n if t == 1:\n for m2 in graph[m]:\n if result[(m2,c,2)] != 2:return False\n else:\n for c2 in graph[c]:\n if c2 == 0:continue\n if result[(m,c2,1)] != 1:return False\n return True\n \n result = defaultdict(lambda:0) \n # key = (m,c,turn) value = (0/1/2)\n n = len(graph)\n queue = deque()\n \n for t in range(1,3):\n for i in range(1,n):\n # mouse win \n result[(0,i,t)] = 1\n queue.append((0,i,t))\n # cat win\n result[(i,i,t)] = 2\n queue.append((i,i,t))\n \n while queue:\n m,c,t = queue.popleft()\n r = result[(m,c,t)]\n for m2,c2,t2 in getPreStates(m,c,t):\n r2 = result[(m2,c2,t2)]\n if r2 > 0:continue\n # populate prestate\n if r == 3-t: # can always win\n result[(m2,c2,t2)] = r\n queue.append((m2,c2,t2))\n elif ifAllNextMovesFailed(m2,c2,t2):\n result[(m2,c2,t2)] =3-t2\n queue.append((m2,c2,t2))\n return result[(1,2,1)]\n```
0
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`. During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`. Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: * If ever the Cat occupies the same node as the Mouse, the Cat wins. * If ever the Mouse reaches the Hole, the Mouse wins. * If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a `graph`, and assuming both players play optimally, return * `1` if the mouse wins the game, * `2` if the cat wins the game, or * `0` if the game is a draw. **Example 1:** **Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\] **Output:** 1 **Constraints:** * `3 <= graph.length <= 50` * `1 <= graph[i].length < graph.length` * `0 <= graph[i][j] < graph.length` * `graph[i][j] != i` * `graph[i]` is unique. * The mouse and the cat can always move.
null
Simple Explained Solution
cat-and-mouse
0
1
\n```\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n def getPreStates(m,c,t):\n ans = []\n if t == 1:\n for c2 in graph[c]:\n if c2 == 0:continue\n ans.append((m,c2,2))\n else:\n for m2 in graph[m]:\n ans.append((m2,c,1))\n return ans\n \n def ifAllNextMovesFailed(m,c,t):\n if t == 1:\n for m2 in graph[m]:\n if result[(m2,c,2)] != 2:return False\n else:\n for c2 in graph[c]:\n if c2 == 0:continue\n if result[(m,c2,1)] != 1:return False\n return True\n \n result = defaultdict(lambda:0) \n # key = (m,c,turn) value = (0/1/2)\n n = len(graph)\n queue = deque()\n \n for t in range(1,3):\n for i in range(1,n):\n # mouse win \n result[(0,i,t)] = 1\n queue.append((0,i,t))\n # cat win\n result[(i,i,t)] = 2\n queue.append((i,i,t))\n \n while queue:\n m,c,t = queue.popleft()\n r = result[(m,c,t)]\n for m2,c2,t2 in getPreStates(m,c,t):\n r2 = result[(m2,c2,t2)]\n if r2 > 0:continue\n # populate prestate\n if r == 3-t: # can always win\n result[(m2,c2,t2)] = r\n queue.append((m2,c2,t2))\n elif ifAllNextMovesFailed(m2,c2,t2):\n result[(m2,c2,t2)] =3-t2\n queue.append((m2,c2,t2))\n return result[(1,2,1)]\n```
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
PYTHON SOLUTION || MEMOIZATION || BOTTOM UP DP ||
cat-and-mouse
0
1
```\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n def getPreStates(m,c,t):\n ans = []\n if t == 1:\n for c2 in graph[c]:\n if c2 == 0:continue\n ans.append((m,c2,2))\n else:\n for m2 in graph[m]:\n ans.append((m2,c,1))\n return ans\n \n def ifAllNextMovesFailed(m,c,t):\n if t == 1:\n for m2 in graph[m]:\n if result[(m2,c,2)] != 2:return False\n else:\n for c2 in graph[c]:\n if c2 == 0:continue\n if result[(m,c2,1)] != 1:return False\n return True\n \n result = defaultdict(lambda:0) \n # key = (m,c,turn) value = (0/1/2)\n n = len(graph)\n queue = deque()\n \n for t in range(1,3):\n for i in range(1,n):\n # mouse win \n result[(0,i,t)] = 1\n queue.append((0,i,t))\n # cat win\n result[(i,i,t)] = 2\n queue.append((i,i,t))\n \n while queue:\n m,c,t = queue.popleft()\n r = result[(m,c,t)]\n for m2,c2,t2 in getPreStates(m,c,t):\n r2 = result[(m2,c2,t2)]\n if r2 > 0:continue\n # populate prestate\n if r == 3-t: # can always win\n result[(m2,c2,t2)] = r\n queue.append((m2,c2,t2))\n elif ifAllNextMovesFailed(m2,c2,t2):\n result[(m2,c2,t2)] =3-t2\n queue.append((m2,c2,t2))\n return result[(1,2,1)]\n \n```
1
A game on an **undirected** graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`. During each player's turn, they **must** travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it **must** travel to any node in `graph[1]`. Additionally, it is not allowed for the Cat to travel to the Hole (node 0.) Then, the game can end in three ways: * If ever the Cat occupies the same node as the Mouse, the Cat wins. * If ever the Mouse reaches the Hole, the Mouse wins. * If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a `graph`, and assuming both players play optimally, return * `1` if the mouse wins the game, * `2` if the cat wins the game, or * `0` if the game is a draw. **Example 1:** **Input:** graph = \[\[2,5\],\[3\],\[0,4,5\],\[1,4,5\],\[2,3\],\[0,2,3\]\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,3\],\[0\],\[3\],\[0,2\]\] **Output:** 1 **Constraints:** * `3 <= graph.length <= 50` * `1 <= graph[i].length < graph.length` * `0 <= graph[i][j] < graph.length` * `graph[i][j] != i` * `graph[i]` is unique. * The mouse and the cat can always move.
null
PYTHON SOLUTION || MEMOIZATION || BOTTOM UP DP ||
cat-and-mouse
0
1
```\nclass Solution:\n def catMouseGame(self, graph: List[List[int]]) -> int:\n def getPreStates(m,c,t):\n ans = []\n if t == 1:\n for c2 in graph[c]:\n if c2 == 0:continue\n ans.append((m,c2,2))\n else:\n for m2 in graph[m]:\n ans.append((m2,c,1))\n return ans\n \n def ifAllNextMovesFailed(m,c,t):\n if t == 1:\n for m2 in graph[m]:\n if result[(m2,c,2)] != 2:return False\n else:\n for c2 in graph[c]:\n if c2 == 0:continue\n if result[(m,c2,1)] != 1:return False\n return True\n \n result = defaultdict(lambda:0) \n # key = (m,c,turn) value = (0/1/2)\n n = len(graph)\n queue = deque()\n \n for t in range(1,3):\n for i in range(1,n):\n # mouse win \n result[(0,i,t)] = 1\n queue.append((0,i,t))\n # cat win\n result[(i,i,t)] = 2\n queue.append((i,i,t))\n \n while queue:\n m,c,t = queue.popleft()\n r = result[(m,c,t)]\n for m2,c2,t2 in getPreStates(m,c,t):\n r2 = result[(m2,c2,t2)]\n if r2 > 0:continue\n # populate prestate\n if r == 3-t: # can always win\n result[(m2,c2,t2)] = r\n queue.append((m2,c2,t2))\n elif ifAllNextMovesFailed(m2,c2,t2):\n result[(m2,c2,t2)] =3-t2\n queue.append((m2,c2,t2))\n return result[(1,2,1)]\n \n```
1
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Python || Easy solution || Faster than 99.22%
x-of-a-kind-in-a-deck-of-cards
0
1
\n\n# Code\n```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n count = collections.Counter(deck)\n val = count.values()\n import math\n m = math.gcd(*val)\n if m >= 2:\n return True \n else:\n return False\n\n```
2
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
Python || Easy solution || Faster than 99.22%
x-of-a-kind-in-a-deck-of-cards
0
1
\n\n# Code\n```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n count = collections.Counter(deck)\n val = count.values()\n import math\n m = math.gcd(*val)\n if m >= 2:\n return True \n else:\n return False\n\n```
2
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
[Python3] Greatest Common Divisor | O(n)
x-of-a-kind-in-a-deck-of-cards
0
1
# Approach\nTo cover all the cases involved in this problem we need to find a baseline count of the elements. This can be facilitated with a dictionary as represented by \'dict\' in the code.\n\nOnce we have the counts, we have to understand if making partitions, single even multiple of the same element, is actually possible or not. This can be as simple as finding the HCF of the numbers. \n\nIf the HCF is greater than 1, we can return True. \uD83D\uDE04\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n dict = {}\n for i in deck:\n if i in dict: dict[i] += 1\n else: dict[i] = 1\n\n from math import gcd\n def solve(nums):\n if len(nums) == 1:\n return nums[0]\n\n div = gcd(nums[0], nums[1])\n\n if len(nums) == 2:\n return div\n\n for i in range(1, len(nums) - 1):\n div = gcd(div, nums[i + 1])\n if div == 1:\n return div\n return div\n\n hcf = solve(list(dict.values()))\n\n if hcf > 1: return True\n else: return False\n```
2
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
[Python3] Greatest Common Divisor | O(n)
x-of-a-kind-in-a-deck-of-cards
0
1
# Approach\nTo cover all the cases involved in this problem we need to find a baseline count of the elements. This can be facilitated with a dictionary as represented by \'dict\' in the code.\n\nOnce we have the counts, we have to understand if making partitions, single even multiple of the same element, is actually possible or not. This can be as simple as finding the HCF of the numbers. \n\nIf the HCF is greater than 1, we can return True. \uD83D\uDE04\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n dict = {}\n for i in deck:\n if i in dict: dict[i] += 1\n else: dict[i] = 1\n\n from math import gcd\n def solve(nums):\n if len(nums) == 1:\n return nums[0]\n\n div = gcd(nums[0], nums[1])\n\n if len(nums) == 2:\n return div\n\n for i in range(1, len(nums) - 1):\n div = gcd(div, nums[i + 1])\n if div == 1:\n return div\n return div\n\n hcf = solve(list(dict.values()))\n\n if hcf > 1: return True\n else: return False\n```
2
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
python solution easy one
x-of-a-kind-in-a-deck-of-cards
0
1
```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n \n f=defaultdict(int)\n \n for j in deck:\n f[j]+=1\n \n \n import math\n \n u=list(f.values())\n \n g=u[0]\n \n for j in range(1,len(u)):\n g=math.gcd(g,u[j])\n return g!=1\n \n \n```
7
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
python solution easy one
x-of-a-kind-in-a-deck-of-cards
0
1
```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n \n \n f=defaultdict(int)\n \n for j in deck:\n f[j]+=1\n \n \n import math\n \n u=list(f.values())\n \n g=u[0]\n \n for j in range(1,len(u)):\n g=math.gcd(g,u[j])\n return g!=1\n \n \n```
7
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
Simple Solution using GCD and Hash Table
x-of-a-kind-in-a-deck-of-cards
0
1
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n-> Find the occurences of all the elements .\n-> If GCD of those occurences is >1 then return 1, else return 0.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n dic=Counter(deck)\n a=list(dic.values())\n if gcd(*a)>1:\n return 1\n return 0\n```
2
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
Simple Solution using GCD and Hash Table
x-of-a-kind-in-a-deck-of-cards
0
1
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n-> Find the occurences of all the elements .\n-> If GCD of those occurences is >1 then return 1, else return 0.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n dic=Counter(deck)\n a=list(dic.values())\n if gcd(*a)>1:\n return 1\n return 0\n```
2
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
Solution in Python 3 (beats ~99%) (one line)
x-of-a-kind-in-a-deck-of-cards
0
1
```\nfrom functools import reduce\nfrom math import gcd\nfrom collections import Counter\n\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n return reduce(gcd,Counter(deck).values()) != 1\n\t\t\n\t\t\n- Junaid Mansuri
18
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
Solution in Python 3 (beats ~99%) (one line)
x-of-a-kind-in-a-deck-of-cards
0
1
```\nfrom functools import reduce\nfrom math import gcd\nfrom collections import Counter\n\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n return reduce(gcd,Counter(deck).values()) != 1\n\t\t\n\t\t\n- Junaid Mansuri
18
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
Solution
x-of-a-kind-in-a-deck-of-cards
1
1
```C++ []\nclass Solution {\npublic:\n bool hasGroupsSizeX(vector<int>& deck) {\n map <int,int> mp;\n vector <int> v;\n if(deck.size()==1)\n return false;\n for (int i:deck)\n mp[i+1]++;\n for(auto it:mp){\n v.push_back(it.second);\n }\n if(v.size()==1 && deck.size()!=1)\n return true;\n int a=__gcd(v[0],v[1]);\n if(a==1)\n return false;\n \n for(int i=2;i<v.size();i++){\n if((__gcd(v[i],v[i-1]))==1)\n return false;\n else \n a=(__gcd(v[i],v[i-1]));\n }\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n a=Counter(deck)\n w=list(set(a.values()))\n div=0\n if len(w)==1:\n div=w[0]\n else:\n div=math.gcd(w[0],w[1])\n \n for i in range(1,len(w)-1):\n div=math.gcd(div,w[i+1])\n return div>1\n```\n\n```Java []\nimport java.util.*;\n\nclass Solution {\n public int gcd(int a,int b){\n if(b==0){\n return a;\n }\n else{\n return gcd(b,a%b);\n }\n }\n public boolean hasGroupsSizeX(int[] deck) {\n if(deck.length<=1){\n return false;\n }\n int max=0;\n for(int i:deck){\n if(i>max){\n max=i;\n }\n }\n int[] a=new int[max+1];\n for(int i:deck){\n a[i]++;\n }\n int g=0;\n for(int i:a){\n if(i!=0)\n g=gcd(g,i);\n }\n return g>1;\n }\n}\n```\n
2
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
Solution
x-of-a-kind-in-a-deck-of-cards
1
1
```C++ []\nclass Solution {\npublic:\n bool hasGroupsSizeX(vector<int>& deck) {\n map <int,int> mp;\n vector <int> v;\n if(deck.size()==1)\n return false;\n for (int i:deck)\n mp[i+1]++;\n for(auto it:mp){\n v.push_back(it.second);\n }\n if(v.size()==1 && deck.size()!=1)\n return true;\n int a=__gcd(v[0],v[1]);\n if(a==1)\n return false;\n \n for(int i=2;i<v.size();i++){\n if((__gcd(v[i],v[i-1]))==1)\n return false;\n else \n a=(__gcd(v[i],v[i-1]));\n }\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n a=Counter(deck)\n w=list(set(a.values()))\n div=0\n if len(w)==1:\n div=w[0]\n else:\n div=math.gcd(w[0],w[1])\n \n for i in range(1,len(w)-1):\n div=math.gcd(div,w[i+1])\n return div>1\n```\n\n```Java []\nimport java.util.*;\n\nclass Solution {\n public int gcd(int a,int b){\n if(b==0){\n return a;\n }\n else{\n return gcd(b,a%b);\n }\n }\n public boolean hasGroupsSizeX(int[] deck) {\n if(deck.length<=1){\n return false;\n }\n int max=0;\n for(int i:deck){\n if(i>max){\n max=i;\n }\n }\n int[] a=new int[max+1];\n for(int i:deck){\n a[i]++;\n }\n int g=0;\n for(int i:a){\n if(i!=0)\n g=gcd(g,i);\n }\n return g>1;\n }\n}\n```\n
2
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
[Python3] with least common divisor and reduce()
x-of-a-kind-in-a-deck-of-cards
0
1
# Code\n```\nfrom collections import Counter\nfrom functools import reduce\n\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n counts = set(Counter(deck).values())\n return reduce(self.least_common_divisor, counts) > 1\n \n def least_common_divisor(self, a, b):\n div = a if a > b else b\n while div:\n if a % div == 0 and b % div == 0:\n return div\n div -= 1\n return div\n\n\n\n \n```
0
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
[Python3] with least common divisor and reduce()
x-of-a-kind-in-a-deck-of-cards
0
1
# Code\n```\nfrom collections import Counter\nfrom functools import reduce\n\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n counts = set(Counter(deck).values())\n return reduce(self.least_common_divisor, counts) > 1\n \n def least_common_divisor(self, a, b):\n div = a if a > b else b\n while div:\n if a % div == 0 and b % div == 0:\n return div\n div -= 1\n return div\n\n\n\n \n```
0
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
Python one liner
x-of-a-kind-in-a-deck-of-cards
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 hasGroupsSizeX(self, deck: List[int]) -> bool:\n return reduce(gcd, Counter(deck).values()) > 1\n\n```
0
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
Python one liner
x-of-a-kind-in-a-deck-of-cards
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 hasGroupsSizeX(self, deck: List[int]) -> bool:\n return reduce(gcd, Counter(deck).values()) > 1\n\n```
0
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
x-of-a-kind-in-a-deck-of-cards
x-of-a-kind-in-a-deck-of-cards
0
1
# Code\n```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n if len(deck)==1:\n return False\n d = {}\n for i in deck:\n if i not in d:\n d[i] = 1\n else:\n d[i] +=1\n t = sorted(d.items(), key = lambda x:x[1])\n a = t[0][1]\n if a%2!=0:\n l = []\n for i in range(2,a+1):\n if a%i==0:\n l.append(i)\n for i in l:\n count=0\n for j in d:\n if d[j]%i==0:\n count+=1\n if count==len(d):\n return True\n return False\n else:\n for i in range(2,a+1):\n if a%i==0 and i%2!=0:\n break\n count = 0\n for j in d:\n if d[j]%i==0:\n count+=1\n if count==len(d):\n return True\n count = 0\n for j in d:\n if d[j]%2==0:\n count+=1\n if count==len(d):\n return True\n return False\n \n \n \n\n\n \n\n\n```
0
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
x-of-a-kind-in-a-deck-of-cards
x-of-a-kind-in-a-deck-of-cards
0
1
# Code\n```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n if len(deck)==1:\n return False\n d = {}\n for i in deck:\n if i not in d:\n d[i] = 1\n else:\n d[i] +=1\n t = sorted(d.items(), key = lambda x:x[1])\n a = t[0][1]\n if a%2!=0:\n l = []\n for i in range(2,a+1):\n if a%i==0:\n l.append(i)\n for i in l:\n count=0\n for j in d:\n if d[j]%i==0:\n count+=1\n if count==len(d):\n return True\n return False\n else:\n for i in range(2,a+1):\n if a%i==0 and i%2!=0:\n break\n count = 0\n for j in d:\n if d[j]%i==0:\n count+=1\n if count==len(d):\n return True\n count = 0\n for j in d:\n if d[j]%2==0:\n count+=1\n if count==len(d):\n return True\n return False\n \n \n \n\n\n \n\n\n```
0
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
Beats 93.55% of users with Python3
x-of-a-kind-in-a-deck-of-cards
0
1
# Code\n```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n # straight forward logic\n # 115ms\n # Beats 93.55% of users with Python3\n if len(deck) == 1:\n return False\n \n import math\n from collections import Counter\n return math.gcd(*Counter(deck).values()) > 1\n\n\n```
0
You are given an integer array `deck` where `deck[i]` represents the number written on the `ith` card. Partition the cards into **one or more groups** such that: * Each group has **exactly** `x` cards where `x > 1`, and * All the cards in one group have the same integer written on them. Return `true` _if such partition is possible, or_ `false` _otherwise_. **Example 1:** **Input:** deck = \[1,2,3,4,4,3,2,1\] **Output:** true **Explanation**: Possible partition \[1,1\],\[2,2\],\[3,3\],\[4,4\]. **Example 2:** **Input:** deck = \[1,1,1,2,2,2,3,3\] **Output:** false **Explanation**: No possible partition. **Constraints:** * `1 <= deck.length <= 104` * `0 <= deck[i] < 104`
null
Beats 93.55% of users with Python3
x-of-a-kind-in-a-deck-of-cards
0
1
# Code\n```\nclass Solution:\n def hasGroupsSizeX(self, deck: List[int]) -> bool:\n # straight forward logic\n # 115ms\n # Beats 93.55% of users with Python3\n if len(deck) == 1:\n return False\n \n import math\n from collections import Counter\n return math.gcd(*Counter(deck).values()) > 1\n\n\n```
0
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
Solution
partition-array-into-disjoint-intervals
1
1
```C++ []\nclass Solution {\npublic:\n int partitionDisjoint(vector<int>& a) {\n ios::sync_with_stdio(false);\n cin.tie(0);\n int minNum=a[0],maxNum=a[0];\n int ans=0;\n for(int i=1;i<a.size();i++){\n if(a[i]<minNum){\n ans=i;\n minNum=maxNum;\n }\n maxNum=max(a[i],maxNum);\n }\n return ans+1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n ret = 1\n cur_max = max_ = nums[0]\n for i, n in enumerate(nums):\n if n < cur_max:\n cur_max = max_\n ret = i + 1\n if n > max_:\n max_ = n\n return ret\n```\n\n```Java []\nclass Solution {\n public int partitionDisjoint(int[] nums) {\n int leftmax=nums[0];\n int max=nums[0];\n int length=1;\n for(int i=0;i<nums.length;i++){\n if(nums[i]<leftmax){\n length=i+1;\n leftmax=max;\n } else {\n max = Math.max(nums[i],max);\n }\n }\n return length;\n }\n}\n```\n
1
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioning_. Test cases are generated such that partitioning exists. **Example 1:** **Input:** nums = \[5,0,3,8,6\] **Output:** 3 **Explanation:** left = \[5,0,3\], right = \[8,6\] **Example 2:** **Input:** nums = \[1,1,1,0,6,12\] **Output:** 4 **Explanation:** left = \[1,1,1,0\], right = \[6,12\] **Constraints:** * `2 <= nums.length <= 105` * `0 <= nums[i] <= 106` * There is at least one valid answer for the given input.
null
Solution
partition-array-into-disjoint-intervals
1
1
```C++ []\nclass Solution {\npublic:\n int partitionDisjoint(vector<int>& a) {\n ios::sync_with_stdio(false);\n cin.tie(0);\n int minNum=a[0],maxNum=a[0];\n int ans=0;\n for(int i=1;i<a.size();i++){\n if(a[i]<minNum){\n ans=i;\n minNum=maxNum;\n }\n maxNum=max(a[i],maxNum);\n }\n return ans+1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n ret = 1\n cur_max = max_ = nums[0]\n for i, n in enumerate(nums):\n if n < cur_max:\n cur_max = max_\n ret = i + 1\n if n > max_:\n max_ = n\n return ret\n```\n\n```Java []\nclass Solution {\n public int partitionDisjoint(int[] nums) {\n int leftmax=nums[0];\n int max=nums[0];\n int length=1;\n for(int i=0;i<nums.length;i++){\n if(nums[i]<leftmax){\n length=i+1;\n leftmax=max;\n } else {\n max = Math.max(nums[i],max);\n }\n }\n return length;\n }\n}\n```\n
1
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
[PYTHON] Best solution yet! EXPLAINED with comments to make life easier. O(n) & O(1)
partition-array-into-disjoint-intervals
0
1
```\nclass Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n """\n Intuition(logic) is to find two maximums.\n One maximum is for left array and other maximum is for right array.\n \n But the condition is that, the right maximum should be such that, \n no element after that right maximum should be less than the left maximum. \n \n If there is any element after right maximum which is less than left maximum,\n that means there is another right maximum possible and therefore in that case assign\n left maximum to right maximum and keep searching the array for correct right\n maximum till the end.\n """\n #start with both left maximum and right maximum with first element.\n left_max = right_max = nums[0]\n # our current index\n partition_ind = 0\n # Iterate from 1 to end of the array\n for i in range(1,len(nums)):\n #update right_max always after comparing with each nums\n #in order to find our correct right maximum\n right_max = max(nums[i], right_max)\n """\n\t\t\tif current element is less than left maximum, that means this \n element must belong to the left subarray. \n * so our partition index will be updated to current index \n * and left maximum will be updated to right maximum. \n Why left maximum updated to right maximum ?\n Because when we find any element less than left_maximum, that \n means the right maximum which we had till now is not valid and we have\n to find the valid right maximum again while iterating through the end of the loop.\n\t\t\t"""\n if nums[i] < left_max:\n left_max = right_max\n partition_ind = i\n \n return partition_ind+1\n\n\n\n```
9
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioning_. Test cases are generated such that partitioning exists. **Example 1:** **Input:** nums = \[5,0,3,8,6\] **Output:** 3 **Explanation:** left = \[5,0,3\], right = \[8,6\] **Example 2:** **Input:** nums = \[1,1,1,0,6,12\] **Output:** 4 **Explanation:** left = \[1,1,1,0\], right = \[6,12\] **Constraints:** * `2 <= nums.length <= 105` * `0 <= nums[i] <= 106` * There is at least one valid answer for the given input.
null
[PYTHON] Best solution yet! EXPLAINED with comments to make life easier. O(n) & O(1)
partition-array-into-disjoint-intervals
0
1
```\nclass Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n """\n Intuition(logic) is to find two maximums.\n One maximum is for left array and other maximum is for right array.\n \n But the condition is that, the right maximum should be such that, \n no element after that right maximum should be less than the left maximum. \n \n If there is any element after right maximum which is less than left maximum,\n that means there is another right maximum possible and therefore in that case assign\n left maximum to right maximum and keep searching the array for correct right\n maximum till the end.\n """\n #start with both left maximum and right maximum with first element.\n left_max = right_max = nums[0]\n # our current index\n partition_ind = 0\n # Iterate from 1 to end of the array\n for i in range(1,len(nums)):\n #update right_max always after comparing with each nums\n #in order to find our correct right maximum\n right_max = max(nums[i], right_max)\n """\n\t\t\tif current element is less than left maximum, that means this \n element must belong to the left subarray. \n * so our partition index will be updated to current index \n * and left maximum will be updated to right maximum. \n Why left maximum updated to right maximum ?\n Because when we find any element less than left_maximum, that \n means the right maximum which we had till now is not valid and we have\n to find the valid right maximum again while iterating through the end of the loop.\n\t\t\t"""\n if nums[i] < left_max:\n left_max = right_max\n partition_ind = i\n \n return partition_ind+1\n\n\n\n```
9
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
Step By Step iteration & Explanation O(n) Space and time Comp
partition-array-into-disjoint-intervals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasic Idea was to observe the condition that min of left subarray is less than equal to max of right subarray .\nSo we have to compare left max with right min for every element .\n \n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate two arrays which stores prefix max and suffix min\nEg:- for arr 5 0 3 8 6\n prefix max 5 5 5 8 8\n suffix min 0 0 3 6 6\nnow as he asked least left subarray\nreq condn is -> prefix max[i] <= suffix min[i+1] then return i+1\n\n1st iter -> i = 0 -> left subarr 5 , right subarr 0 3 8 6\n prefix max -> 5 \n suffix min -> 0 \n not satisfied\n\n2nd iter -> i = 1 -> left subarr 5 0 , right subarr 3 8 6\n prefix max -> 5 \n suffix min -> 0\n not satisfied\n\n3rd iter -> i = 2 -> left subarr 5 0 3, right subarr 8 6\n prefix max -> 5 \n suffix min -> 6\n satisfied\n\nSo return (i+1) as you have considered left sub arr [5 0 3] (i->0 Based indexing)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nDid three traversals of O(n) time so O(n) is the time complextiy\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nUsed two arrays prefix max and suffix min so O(n)\n# Code\n```\nclass Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n \n #prefix max\n pref_max = [-1]*len(nums)\n #suffix min\n suff_min = [-1]*len(nums)\n pref_max[0] = nums[0]\n suff_min[-1] = nums[-1]\n #building the prefix max arr\n for i in range(1,len(nums)):\n pref_max[i] = max(pref_max[i-1],nums[i])\n #building the suffix min arr\n for i in range(len(nums)-2,-1,-1):\n suff_min[i] = min(suff_min[i+1],nums[i])\n \n #finding the req partition\n for i in range(len(nums)-1):\n if (pref_max[i] <= suff_min[i+1]):\n return i+1\n```
0
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioning_. Test cases are generated such that partitioning exists. **Example 1:** **Input:** nums = \[5,0,3,8,6\] **Output:** 3 **Explanation:** left = \[5,0,3\], right = \[8,6\] **Example 2:** **Input:** nums = \[1,1,1,0,6,12\] **Output:** 4 **Explanation:** left = \[1,1,1,0\], right = \[6,12\] **Constraints:** * `2 <= nums.length <= 105` * `0 <= nums[i] <= 106` * There is at least one valid answer for the given input.
null
Step By Step iteration & Explanation O(n) Space and time Comp
partition-array-into-disjoint-intervals
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBasic Idea was to observe the condition that min of left subarray is less than equal to max of right subarray .\nSo we have to compare left max with right min for every element .\n \n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate two arrays which stores prefix max and suffix min\nEg:- for arr 5 0 3 8 6\n prefix max 5 5 5 8 8\n suffix min 0 0 3 6 6\nnow as he asked least left subarray\nreq condn is -> prefix max[i] <= suffix min[i+1] then return i+1\n\n1st iter -> i = 0 -> left subarr 5 , right subarr 0 3 8 6\n prefix max -> 5 \n suffix min -> 0 \n not satisfied\n\n2nd iter -> i = 1 -> left subarr 5 0 , right subarr 3 8 6\n prefix max -> 5 \n suffix min -> 0\n not satisfied\n\n3rd iter -> i = 2 -> left subarr 5 0 3, right subarr 8 6\n prefix max -> 5 \n suffix min -> 6\n satisfied\n\nSo return (i+1) as you have considered left sub arr [5 0 3] (i->0 Based indexing)\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nDid three traversals of O(n) time so O(n) is the time complextiy\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nUsed two arrays prefix max and suffix min so O(n)\n# Code\n```\nclass Solution:\n def partitionDisjoint(self, nums: List[int]) -> int:\n \n #prefix max\n pref_max = [-1]*len(nums)\n #suffix min\n suff_min = [-1]*len(nums)\n pref_max[0] = nums[0]\n suff_min[-1] = nums[-1]\n #building the prefix max arr\n for i in range(1,len(nums)):\n pref_max[i] = max(pref_max[i-1],nums[i])\n #building the suffix min arr\n for i in range(len(nums)-2,-1,-1):\n suff_min[i] = min(suff_min[i+1],nums[i])\n \n #finding the req partition\n for i in range(len(nums)-1):\n if (pref_max[i] <= suff_min[i+1]):\n return i+1\n```
0
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
easy python approach
partition-array-into-disjoint-intervals
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 partitionDisjoint(self, nums: List[int]) -> int:\n lmax=rmax=nums[0]\n count=0\n for i in range(1,len(nums)):\n rmax=max(nums[i],rmax)\n if nums[i]<lmax:\n lmax=rmax\n count=i\n return count+1\n \n\n \n```
0
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioning_. Test cases are generated such that partitioning exists. **Example 1:** **Input:** nums = \[5,0,3,8,6\] **Output:** 3 **Explanation:** left = \[5,0,3\], right = \[8,6\] **Example 2:** **Input:** nums = \[1,1,1,0,6,12\] **Output:** 4 **Explanation:** left = \[1,1,1,0\], right = \[6,12\] **Constraints:** * `2 <= nums.length <= 105` * `0 <= nums[i] <= 106` * There is at least one valid answer for the given input.
null
easy python approach
partition-array-into-disjoint-intervals
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 partitionDisjoint(self, nums: List[int]) -> int:\n lmax=rmax=nums[0]\n count=0\n for i in range(1,len(nums)):\n rmax=max(nums[i],rmax)\n if nums[i]<lmax:\n lmax=rmax\n count=i\n return count+1\n \n\n \n```
0
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
python3 solution for partition of array
partition-array-into-disjoint-intervals
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 partitionDisjoint(self, nums: List[int]) -> int:\n ret = 1\n cur_max = max_ = nums[0]\n for i, n in enumerate(nums):\n if n < cur_max:\n cur_max = max_\n ret = i + 1\n if n > max_:\n max_ = n\n return ret\n \n```
0
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioning_. Test cases are generated such that partitioning exists. **Example 1:** **Input:** nums = \[5,0,3,8,6\] **Output:** 3 **Explanation:** left = \[5,0,3\], right = \[8,6\] **Example 2:** **Input:** nums = \[1,1,1,0,6,12\] **Output:** 4 **Explanation:** left = \[1,1,1,0\], right = \[6,12\] **Constraints:** * `2 <= nums.length <= 105` * `0 <= nums[i] <= 106` * There is at least one valid answer for the given input.
null
python3 solution for partition of array
partition-array-into-disjoint-intervals
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 partitionDisjoint(self, nums: List[int]) -> int:\n ret = 1\n cur_max = max_ = nums[0]\n for i, n in enumerate(nums):\n if n < cur_max:\n cur_max = max_\n ret = i + 1\n if n > max_:\n max_ = n\n return ret\n \n```
0
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
Intuitive 2-pointer O(N) solution
partition-array-into-disjoint-intervals
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 partitionDisjoint(self, nums: List[int]) -> int:\n c_h, c_l, min_greater, max_smaller=0, 1, math.inf, nums[0]\n max_greater= -math.inf\n for i, num in enumerate(nums[1:]):\n if num<min_greater and num<max_smaller:\n c_l+=c_h+1\n if c_h:\n max_smaller = max(max_smaller, max_greater)\n c_h =0\n min_greater = max_greater\n max_smaller = max(max_smaller, num)\n else:\n c_h +=1\n max_greater= max(max_greater, num)\n min_greater = min(min_greater, num) \n return c_l\n\n \n \n```
0
Given an integer array `nums`, partition it into two (contiguous) subarrays `left` and `right` so that: * Every element in `left` is less than or equal to every element in `right`. * `left` and `right` are non-empty. * `left` has the smallest possible size. Return _the length of_ `left` _after such a partitioning_. Test cases are generated such that partitioning exists. **Example 1:** **Input:** nums = \[5,0,3,8,6\] **Output:** 3 **Explanation:** left = \[5,0,3\], right = \[8,6\] **Example 2:** **Input:** nums = \[1,1,1,0,6,12\] **Output:** 4 **Explanation:** left = \[1,1,1,0\], right = \[6,12\] **Constraints:** * `2 <= nums.length <= 105` * `0 <= nums[i] <= 106` * There is at least one valid answer for the given input.
null
Intuitive 2-pointer O(N) solution
partition-array-into-disjoint-intervals
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 partitionDisjoint(self, nums: List[int]) -> int:\n c_h, c_l, min_greater, max_smaller=0, 1, math.inf, nums[0]\n max_greater= -math.inf\n for i, num in enumerate(nums[1:]):\n if num<min_greater and num<max_smaller:\n c_l+=c_h+1\n if c_h:\n max_smaller = max(max_smaller, max_greater)\n c_h =0\n min_greater = max_greater\n max_smaller = max(max_smaller, num)\n else:\n c_h +=1\n max_greater= max(max_greater, num)\n min_greater = min(min_greater, num) \n return c_l\n\n \n \n```
0
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
Solution
word-subsets
1
1
```C++ []\nclass Solution {\npublic:\n Solution() {\n ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);\n }\n vector<string> wordSubsets(vector<string>& words1, vector<string>& words2) {\n int maxWord2[26]={0};\n for(auto x:words2){\n int temp[26]={0};\n for(auto xx:x)\n temp[xx-\'a\']++;\n \n for(int i =0;i<26;++i){\n maxWord2[i]=max(temp[i],maxWord2[i]);\n }}\n vector<string> s;\n for(auto x:words1){\n int temp[26]={0};\n for(auto xx:x)temp[xx-\'a\']++;\nint f=0;\n for(int i =0;i<26;++i){\n if(temp[i]<maxWord2[i])\n {\n f=1;\n break;\n }\n }\n if(f==0)\n s.push_back(x);\n }\n return s;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n ans = set(words1)\n letters = {}\n for i in words2:\n for j in i:\n count = i.count(j)\n if j not in letters or count > letters[j]:\n letters[j] = count\n for i in words1:\n for j in letters:\n if i.count(j) < letters[j]:\n ans.remove(i)\n break\n return list(ans)\n```\n\n```Java []\nclass Solution {\n public List<String> wordSubsets(String[] words1, String[] words2) {\n List<String> res = new ArrayList<>();\n int[] arr = new int[26];\n for (String w : words2) {\n int[] tmp = new int[26];\n for (char c : w.toCharArray()) {\n tmp[c - \'a\']++;\n if (arr[c - \'a\'] < tmp[c - \'a\']) {\n arr[c - \'a\'] = tmp[c - \'a\'];\n }\n }\n }\n for (String w : words1) {\n int[] tmp = new int[26];\n for (char c : w.toCharArray()) {\n tmp[c - \'a\']++;\n }\n if (issubset(arr, tmp)) {\n res.add(w);\n }\n }\n return res;\n }\n private boolean issubset(int[] arr, int[] tmp) {\n for (int i = 0; i < 26; i++) {\n if (arr[i] > tmp[i]) return false;\n }\n return true;\n }\n}\n```\n
1
You are given two string arrays `words1` and `words2`. A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. * For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`. A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. **Example 1:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\] **Output:** \[ "facebook ", "google ", "leetcode "\] **Example 2:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\] **Output:** \[ "apple ", "google ", "leetcode "\] **Constraints:** * `1 <= words1.length, words2.length <= 104` * `1 <= words1[i].length, words2[i].length <= 10` * `words1[i]` and `words2[i]` consist only of lowercase English letters. * All the strings of `words1` are **unique**.
null
Solution
word-subsets
1
1
```C++ []\nclass Solution {\npublic:\n Solution() {\n ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);\n }\n vector<string> wordSubsets(vector<string>& words1, vector<string>& words2) {\n int maxWord2[26]={0};\n for(auto x:words2){\n int temp[26]={0};\n for(auto xx:x)\n temp[xx-\'a\']++;\n \n for(int i =0;i<26;++i){\n maxWord2[i]=max(temp[i],maxWord2[i]);\n }}\n vector<string> s;\n for(auto x:words1){\n int temp[26]={0};\n for(auto xx:x)temp[xx-\'a\']++;\nint f=0;\n for(int i =0;i<26;++i){\n if(temp[i]<maxWord2[i])\n {\n f=1;\n break;\n }\n }\n if(f==0)\n s.push_back(x);\n }\n return s;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n ans = set(words1)\n letters = {}\n for i in words2:\n for j in i:\n count = i.count(j)\n if j not in letters or count > letters[j]:\n letters[j] = count\n for i in words1:\n for j in letters:\n if i.count(j) < letters[j]:\n ans.remove(i)\n break\n return list(ans)\n```\n\n```Java []\nclass Solution {\n public List<String> wordSubsets(String[] words1, String[] words2) {\n List<String> res = new ArrayList<>();\n int[] arr = new int[26];\n for (String w : words2) {\n int[] tmp = new int[26];\n for (char c : w.toCharArray()) {\n tmp[c - \'a\']++;\n if (arr[c - \'a\'] < tmp[c - \'a\']) {\n arr[c - \'a\'] = tmp[c - \'a\'];\n }\n }\n }\n for (String w : words1) {\n int[] tmp = new int[26];\n for (char c : w.toCharArray()) {\n tmp[c - \'a\']++;\n }\n if (issubset(arr, tmp)) {\n res.add(w);\n }\n }\n return res;\n }\n private boolean issubset(int[] arr, int[] tmp) {\n for (int i = 0; i < 26; i++) {\n if (arr[i] > tmp[i]) return false;\n }\n return true;\n }\n}\n```\n
1
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
Solution Using Counter in Python
word-subsets
0
1
In this the order of characters in words2 does not matter what only matters is the character and its max count in all the words, so we create a dictionary and update the count for each character in words2.\n\nExample: words1 = ["acaac","cccbb","aacbb","caacc","bcbbb"]\nwords2 = *["c","cc","b"]*\n\nso our dictonary for word2 is = { c -> 2, b -> 1 } (c is 2 because max number of *c* in words2 is 2)\n\nhere for character *c*, a word in words1 should have atleast count of 2 bcoz max count of *c* is 2.\nso output will only be [,"cccbb"] it satisfies all the values in dictionary that is it has atleast 2 *c* and atleast 1 *b* in it.\n\n----\nSteps:\n\n1. we create an empty Counter() (This dictionary subclass provides efficient counting capabilities)\n\n2. now we iterate through each word in words2 and use update operator ( |= ) to update left side of dictionary with the values on the right dictionary. If dictionary have common keys, then the rightmost dict values wil prevail. We call this dictionary *tempDict*.\n\n3. now we iterate through each word in words1 and create a Counter() for each word and substract all the value from *tempDict* and if no values are left in *tempDict* that means we found the word so we append it into the results.\n\n4. Finally return the results\n-------------------------------------------------------------------------\n```\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n result = []\n tempDict = Counter()\n for w in words2:\n tempDict |= Counter(w)\n print(tempDict)\n \n for w in words1:\n if not tempDict - Counter(w):\n result.append(w)\n return result\n```\n----\n***Please Do Upvote If you liked the solution. Thanks.!***
32
You are given two string arrays `words1` and `words2`. A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. * For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`. A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. **Example 1:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\] **Output:** \[ "facebook ", "google ", "leetcode "\] **Example 2:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\] **Output:** \[ "apple ", "google ", "leetcode "\] **Constraints:** * `1 <= words1.length, words2.length <= 104` * `1 <= words1[i].length, words2[i].length <= 10` * `words1[i]` and `words2[i]` consist only of lowercase English letters. * All the strings of `words1` are **unique**.
null
Solution Using Counter in Python
word-subsets
0
1
In this the order of characters in words2 does not matter what only matters is the character and its max count in all the words, so we create a dictionary and update the count for each character in words2.\n\nExample: words1 = ["acaac","cccbb","aacbb","caacc","bcbbb"]\nwords2 = *["c","cc","b"]*\n\nso our dictonary for word2 is = { c -> 2, b -> 1 } (c is 2 because max number of *c* in words2 is 2)\n\nhere for character *c*, a word in words1 should have atleast count of 2 bcoz max count of *c* is 2.\nso output will only be [,"cccbb"] it satisfies all the values in dictionary that is it has atleast 2 *c* and atleast 1 *b* in it.\n\n----\nSteps:\n\n1. we create an empty Counter() (This dictionary subclass provides efficient counting capabilities)\n\n2. now we iterate through each word in words2 and use update operator ( |= ) to update left side of dictionary with the values on the right dictionary. If dictionary have common keys, then the rightmost dict values wil prevail. We call this dictionary *tempDict*.\n\n3. now we iterate through each word in words1 and create a Counter() for each word and substract all the value from *tempDict* and if no values are left in *tempDict* that means we found the word so we append it into the results.\n\n4. Finally return the results\n-------------------------------------------------------------------------\n```\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n result = []\n tempDict = Counter()\n for w in words2:\n tempDict |= Counter(w)\n print(tempDict)\n \n for w in words1:\n if not tempDict - Counter(w):\n result.append(w)\n return result\n```\n----\n***Please Do Upvote If you liked the solution. Thanks.!***
32
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
Python | SImple and Easy | Using dictionaries | Count
word-subsets
0
1
```\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n ans = set(words1)\n letters = {}\n for i in words2:\n for j in i:\n count = i.count(j)\n if j not in letters or count > letters[j]:\n letters[j] = count\n for i in words1:\n for j in letters:\n if i.count(j) < letters[j]:\n ans.remove(i)\n break\n return list(ans)\n```\n**I hope that you\'ve found this useful.**\n**In that case, please upvote. It motivates me to write more such posts\uD83D\uDE03**\nComment below if you have any queries.
15
You are given two string arrays `words1` and `words2`. A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. * For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`. A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. **Example 1:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\] **Output:** \[ "facebook ", "google ", "leetcode "\] **Example 2:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\] **Output:** \[ "apple ", "google ", "leetcode "\] **Constraints:** * `1 <= words1.length, words2.length <= 104` * `1 <= words1[i].length, words2[i].length <= 10` * `words1[i]` and `words2[i]` consist only of lowercase English letters. * All the strings of `words1` are **unique**.
null
Python | SImple and Easy | Using dictionaries | Count
word-subsets
0
1
```\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n ans = set(words1)\n letters = {}\n for i in words2:\n for j in i:\n count = i.count(j)\n if j not in letters or count > letters[j]:\n letters[j] = count\n for i in words1:\n for j in letters:\n if i.count(j) < letters[j]:\n ans.remove(i)\n break\n return list(ans)\n```\n**I hope that you\'ve found this useful.**\n**In that case, please upvote. It motivates me to write more such posts\uD83D\uDE03**\nComment below if you have any queries.
15
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
Python3 || 12 lines, dict & counter w/ explanation || T/M: 84%/73%
word-subsets
0
1
```\nclass Solution: # Suppose for example:\n # words1 = [\'food\', \'coffee\', \'foofy\']\n # words2 = [\'foo\', \'off\']\n # \n # Here\'s the plan:\n # 1) Construct a dict in which the key is a char in\n # one or more words in words2, and the key\'s max\n # count in those words.\n # for \'foo\': c2 = {\'o\': 2, \'f\': 1}\n # for \'off\': c2 = {\'o\': 1, \'f\': 2}\n # so: d = {\'o\': 2, \'f\': 2}\n #\n # 2) Use a counter for each word in words1 to determine \n # whether the word has at least the quantity of each char\n # in d:\n # for \'food\' : c1 = {\'o\': 2, \'f\': 1, \'d\': 1} (fails at \'f\')\n # for \'coffee\': c1 = {\'f\': 2, \'e\': 2, \'o\': 1, \'c\': 1 } (fails at \'o\')\n # for \'foofy \': c1 = {\'f\': 2, \'o\': 2, \'y\': 1} (success)\n #\n # 3) return answer:\n # answer = [\'foofy\'] \n #\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n d, ans = defaultdict(int), []\n\n for word in words2: # <-- 1)\n c2 = Counter(word)\n for ch in c2:\n d[ch] = max(d[ch], c2[ch])\n\n for word in words1: # <-- 2)\n c1 = Counter(word)\n\n for ch in d:\n if c1[ch] < d[ch]: break\n else:\n ans.append(word) # <-- else executes only if the for-loop\n # completes without break\n\n return ans # <-- 3)
10
You are given two string arrays `words1` and `words2`. A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. * For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`. A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. **Example 1:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\] **Output:** \[ "facebook ", "google ", "leetcode "\] **Example 2:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\] **Output:** \[ "apple ", "google ", "leetcode "\] **Constraints:** * `1 <= words1.length, words2.length <= 104` * `1 <= words1[i].length, words2[i].length <= 10` * `words1[i]` and `words2[i]` consist only of lowercase English letters. * All the strings of `words1` are **unique**.
null
Python3 || 12 lines, dict & counter w/ explanation || T/M: 84%/73%
word-subsets
0
1
```\nclass Solution: # Suppose for example:\n # words1 = [\'food\', \'coffee\', \'foofy\']\n # words2 = [\'foo\', \'off\']\n # \n # Here\'s the plan:\n # 1) Construct a dict in which the key is a char in\n # one or more words in words2, and the key\'s max\n # count in those words.\n # for \'foo\': c2 = {\'o\': 2, \'f\': 1}\n # for \'off\': c2 = {\'o\': 1, \'f\': 2}\n # so: d = {\'o\': 2, \'f\': 2}\n #\n # 2) Use a counter for each word in words1 to determine \n # whether the word has at least the quantity of each char\n # in d:\n # for \'food\' : c1 = {\'o\': 2, \'f\': 1, \'d\': 1} (fails at \'f\')\n # for \'coffee\': c1 = {\'f\': 2, \'e\': 2, \'o\': 1, \'c\': 1 } (fails at \'o\')\n # for \'foofy \': c1 = {\'f\': 2, \'o\': 2, \'y\': 1} (success)\n #\n # 3) return answer:\n # answer = [\'foofy\'] \n #\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n d, ans = defaultdict(int), []\n\n for word in words2: # <-- 1)\n c2 = Counter(word)\n for ch in c2:\n d[ch] = max(d[ch], c2[ch])\n\n for word in words1: # <-- 2)\n c1 = Counter(word)\n\n for ch in d:\n if c1[ch] < d[ch]: break\n else:\n ans.append(word) # <-- else executes only if the for-loop\n # completes without break\n\n return ans # <-- 3)
10
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
Python two-liner
word-subsets
0
1
```\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n w2 = reduce(operator.or_, map(Counter, words2))\n return [w1 for w1 in words1 if Counter(w1) >= w2]\n```
8
You are given two string arrays `words1` and `words2`. A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. * For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`. A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. **Example 1:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\] **Output:** \[ "facebook ", "google ", "leetcode "\] **Example 2:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\] **Output:** \[ "apple ", "google ", "leetcode "\] **Constraints:** * `1 <= words1.length, words2.length <= 104` * `1 <= words1[i].length, words2[i].length <= 10` * `words1[i]` and `words2[i]` consist only of lowercase English letters. * All the strings of `words1` are **unique**.
null
Python two-liner
word-subsets
0
1
```\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n w2 = reduce(operator.or_, map(Counter, words2))\n return [w1 for w1 in words1 if Counter(w1) >= w2]\n```
8
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
python || counter
word-subsets
0
1
```\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n res = []\n word2Counter = Counter()\n \n for word in words2:\n word2Counter |= Counter(word)\n \n for word in words1:\n tempCounter = Counter(word)\n tempCounter.subtract(word2Counter)\n \n if min(tempCounter.values()) >= 0:\n res.append(word)\n\n return res\n```
1
You are given two string arrays `words1` and `words2`. A string `b` is a **subset** of string `a` if every letter in `b` occurs in `a` including multiplicity. * For example, `"wrr "` is a subset of `"warrior "` but is not a subset of `"world "`. A string `a` from `words1` is **universal** if for every string `b` in `words2`, `b` is a subset of `a`. Return an array of all the **universal** strings in `words1`. You may return the answer in **any order**. **Example 1:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "e ", "o "\] **Output:** \[ "facebook ", "google ", "leetcode "\] **Example 2:** **Input:** words1 = \[ "amazon ", "apple ", "facebook ", "google ", "leetcode "\], words2 = \[ "l ", "e "\] **Output:** \[ "apple ", "google ", "leetcode "\] **Constraints:** * `1 <= words1.length, words2.length <= 104` * `1 <= words1[i].length, words2[i].length <= 10` * `words1[i]` and `words2[i]` consist only of lowercase English letters. * All the strings of `words1` are **unique**.
null
python || counter
word-subsets
0
1
```\nclass Solution:\n def wordSubsets(self, words1: List[str], words2: List[str]) -> List[str]:\n res = []\n word2Counter = Counter()\n \n for word in words2:\n word2Counter |= Counter(word)\n \n for word in words1:\n tempCounter = Counter(word)\n tempCounter.subtract(word2Counter)\n \n if min(tempCounter.values()) >= 0:\n res.append(word)\n\n return res\n```
1
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
Solution
reverse-only-letters
1
1
```C++ []\nclass Solution {\npublic:\n string reverseOnlyLetters(string str) {\n int s=0;\n int e=str.length()-1;\n while(s<e){\n if(((str[s]>=\'A\' && str[s]<=\'Z\') || str[s]>=\'a\' && str[s]<=\'z\') && ((str[e]>=\'A\' && str[e]<=\'Z\') || str[e]>=\'a\' && str[e]<=\'z\') ){\n swap(str[s],str[e]);\n s++;\n e--;\n }\n else if(((str[s]>=\'A\' && str[s]<=\'Z\') || str[s]>=\'a\' && str[s]<=\'z\') && ((str[e]<\'A\') || ((str[e]>\'Z\')&&(str[e]<\'a\')) || (str[e]>\'z\') )){\n e--;\n } else {\n s++;\n }\n }\n return str; \n }\n};\n```\n\n```Python3 []\nclass Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n left = 0 \n right = len(s)-1\n rev_arr = [""]*len(s)\n\n while left <= right :\n if not s[left].isalpha() :\n rev_arr[left] = s[left]\n left += 1\n continue\n if not s[right].isalpha() :\n rev_arr[right] = s[right]\n right -= 1\n continue\n \n rev_arr[left] = s[right]\n rev_arr[right] = s[left]\n left+=1\n right-=1\n \n return "".join(rev_arr)\n```\n\n```Java []\nclass Solution {\n public String reverseOnlyLetters(String s) {\n char[] arr = s.toCharArray();\n for (int i = 0, j = arr.length - 1; i < j;) {\n if (Character.isLetter(arr[i]) && Character.isLetter(arr[j])) {\n char temp = arr[i];\n arr[i++] = arr[j];\n arr[j--] = temp;\n } else if (!Character.isLetter(arr[i])) {\n i++;\n } else {\n j--;\n }\n }\n return String.valueOf(arr);\n }\n}\n```\n
2
Given a string `s`, reverse the string according to the following rules: * All the characters that are not English letters remain in the same position. * All the English letters (lowercase or uppercase) should be reversed. Return `s` _after reversing it_. **Example 1:** **Input:** s = "ab-cd" **Output:** "dc-ba" **Example 2:** **Input:** s = "a-bC-dEf-ghIj" **Output:** "j-Ih-gfE-dCba" **Example 3:** **Input:** s = "Test1ng-Leet=code-Q!" **Output:** "Qedo1ct-eeLg=ntse-T!" **Constraints:** * `1 <= s.length <= 100` * `s` consists of characters with ASCII values in the range `[33, 122]`. * `s` does not contain `'\ "'` or `'\\'`.
null
Solution
reverse-only-letters
1
1
```C++ []\nclass Solution {\npublic:\n string reverseOnlyLetters(string str) {\n int s=0;\n int e=str.length()-1;\n while(s<e){\n if(((str[s]>=\'A\' && str[s]<=\'Z\') || str[s]>=\'a\' && str[s]<=\'z\') && ((str[e]>=\'A\' && str[e]<=\'Z\') || str[e]>=\'a\' && str[e]<=\'z\') ){\n swap(str[s],str[e]);\n s++;\n e--;\n }\n else if(((str[s]>=\'A\' && str[s]<=\'Z\') || str[s]>=\'a\' && str[s]<=\'z\') && ((str[e]<\'A\') || ((str[e]>\'Z\')&&(str[e]<\'a\')) || (str[e]>\'z\') )){\n e--;\n } else {\n s++;\n }\n }\n return str; \n }\n};\n```\n\n```Python3 []\nclass Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n left = 0 \n right = len(s)-1\n rev_arr = [""]*len(s)\n\n while left <= right :\n if not s[left].isalpha() :\n rev_arr[left] = s[left]\n left += 1\n continue\n if not s[right].isalpha() :\n rev_arr[right] = s[right]\n right -= 1\n continue\n \n rev_arr[left] = s[right]\n rev_arr[right] = s[left]\n left+=1\n right-=1\n \n return "".join(rev_arr)\n```\n\n```Java []\nclass Solution {\n public String reverseOnlyLetters(String s) {\n char[] arr = s.toCharArray();\n for (int i = 0, j = arr.length - 1; i < j;) {\n if (Character.isLetter(arr[i]) && Character.isLetter(arr[j])) {\n char temp = arr[i];\n arr[i++] = arr[j];\n arr[j--] = temp;\n } else if (!Character.isLetter(arr[i])) {\n i++;\n } else {\n j--;\n }\n }\n return String.valueOf(arr);\n }\n}\n```\n
2
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. **Example 1:** **Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz " **Output:** true **Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. **Example 2:** **Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz " **Output:** false **Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted. **Example 3:** **Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz " **Output:** false **Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `order.length == 26` * All characters in `words[i]` and `order` are English lowercase letters.
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
python3 code beats 97%
reverse-only-letters
0
1
# Intuition\nThe method first reverses the input string s and stores it in a variable u. It then iterates through each character of the reversed string u and checks if it is an alphabet using the isalpha() method. If it is, it appends the character to a list called l.\n\nNext, it iterates through each character of the original string s and checks if it is not an alphabet using the isalpha() method. If it is not, it inserts the character at the corresponding index in the list l.\n\nFinally, it joins the characters in the list l to form a string and returns it. The resulting string has all the alphabets in the original string s reversed while keeping the non-alphabetic characters in their original positions.\n# Approach\nThe code takes an input string s and reverses it to get a new string u. It then iterates through the reversed string u and checks if each character is an alphabet or not. If it is an alphabet, it appends it to a list l.\n\nNext, it iterates through the original string s and checks if each character is not an alphabet. If it is not an alphabet, it inserts the character at the corresponding index in the list l.\n\nFinally, it joins the characters in the list l to form a string and returns it. This resulting string has all the alphabets in the original string s reversed while keeping the non-alphabetic characters in their original positions.\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n u=s[::-1]\n l=[]\n for i in range(len(u)):\n if u[i].isalpha():\n l.append(u[i])\n for i in range(len(s)):\n if not s[i].isalpha():\n l.insert(i,s[i])\n p = \'\'.join(l)\n return p\n \n```
2
Given a string `s`, reverse the string according to the following rules: * All the characters that are not English letters remain in the same position. * All the English letters (lowercase or uppercase) should be reversed. Return `s` _after reversing it_. **Example 1:** **Input:** s = "ab-cd" **Output:** "dc-ba" **Example 2:** **Input:** s = "a-bC-dEf-ghIj" **Output:** "j-Ih-gfE-dCba" **Example 3:** **Input:** s = "Test1ng-Leet=code-Q!" **Output:** "Qedo1ct-eeLg=ntse-T!" **Constraints:** * `1 <= s.length <= 100` * `s` consists of characters with ASCII values in the range `[33, 122]`. * `s` does not contain `'\ "'` or `'\\'`.
null
python3 code beats 97%
reverse-only-letters
0
1
# Intuition\nThe method first reverses the input string s and stores it in a variable u. It then iterates through each character of the reversed string u and checks if it is an alphabet using the isalpha() method. If it is, it appends the character to a list called l.\n\nNext, it iterates through each character of the original string s and checks if it is not an alphabet using the isalpha() method. If it is not, it inserts the character at the corresponding index in the list l.\n\nFinally, it joins the characters in the list l to form a string and returns it. The resulting string has all the alphabets in the original string s reversed while keeping the non-alphabetic characters in their original positions.\n# Approach\nThe code takes an input string s and reverses it to get a new string u. It then iterates through the reversed string u and checks if each character is an alphabet or not. If it is an alphabet, it appends it to a list l.\n\nNext, it iterates through the original string s and checks if each character is not an alphabet. If it is not an alphabet, it inserts the character at the corresponding index in the list l.\n\nFinally, it joins the characters in the list l to form a string and returns it. This resulting string has all the alphabets in the original string s reversed while keeping the non-alphabetic characters in their original positions.\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n u=s[::-1]\n l=[]\n for i in range(len(u)):\n if u[i].isalpha():\n l.append(u[i])\n for i in range(len(s)):\n if not s[i].isalpha():\n l.insert(i,s[i])\n p = \'\'.join(l)\n return p\n \n```
2
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. **Example 1:** **Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz " **Output:** true **Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. **Example 2:** **Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz " **Output:** false **Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted. **Example 3:** **Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz " **Output:** false **Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `order.length == 26` * All characters in `words[i]` and `order` are English lowercase letters.
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
Python code for reversing only letters (TC&SC: O(n))
reverse-only-letters
0
1
\n\n# Approach\nHere\'s the step-by-step approach taken by the function:\n\nInitialize an empty list l1 to store the alphabetic characters from the input string s.\n\nConvert the input string s into a list of characters, denoted as l.\n\nIterate through the characters of s to identify and store the alphabetic characters in l1. This is done by checking if a character is alphabetic using the isalpha() method.\n\nReverse the order of characters in the list l1 using the reverse() method.\n\nIterate through the characters of the input string s again and, for each character, if it is alphabetic, replace it with the corresponding character from the reversed list l1. This effectively reverses the alphabetic characters while keeping the non-alphabetic characters in their original positions.\n\nFinally, join the modified list l back into a string to obtain the desired result.\n\nThe key idea is to separate the alphabetic characters from the rest of the string, reverse the alphabetic characters, and then merge them back into the original string with the reversed order of letters while preserving the positions of non-alphabetic characters.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution(object):\n def reverseOnlyLetters(self, s):\n l1 = []\n l = list(s)\n x = 0\n for i in range(len(s)):\n if s[i].isalpha():\n l1.append(s[i])\n l1.reverse()\n for i in range(len(s)):\n if l[i].isalpha():\n l[i] = l1[x]\n x = x+1\n return \'\'.join(l)\n```
2
Given a string `s`, reverse the string according to the following rules: * All the characters that are not English letters remain in the same position. * All the English letters (lowercase or uppercase) should be reversed. Return `s` _after reversing it_. **Example 1:** **Input:** s = "ab-cd" **Output:** "dc-ba" **Example 2:** **Input:** s = "a-bC-dEf-ghIj" **Output:** "j-Ih-gfE-dCba" **Example 3:** **Input:** s = "Test1ng-Leet=code-Q!" **Output:** "Qedo1ct-eeLg=ntse-T!" **Constraints:** * `1 <= s.length <= 100` * `s` consists of characters with ASCII values in the range `[33, 122]`. * `s` does not contain `'\ "'` or `'\\'`.
null
Python code for reversing only letters (TC&SC: O(n))
reverse-only-letters
0
1
\n\n# Approach\nHere\'s the step-by-step approach taken by the function:\n\nInitialize an empty list l1 to store the alphabetic characters from the input string s.\n\nConvert the input string s into a list of characters, denoted as l.\n\nIterate through the characters of s to identify and store the alphabetic characters in l1. This is done by checking if a character is alphabetic using the isalpha() method.\n\nReverse the order of characters in the list l1 using the reverse() method.\n\nIterate through the characters of the input string s again and, for each character, if it is alphabetic, replace it with the corresponding character from the reversed list l1. This effectively reverses the alphabetic characters while keeping the non-alphabetic characters in their original positions.\n\nFinally, join the modified list l back into a string to obtain the desired result.\n\nThe key idea is to separate the alphabetic characters from the rest of the string, reverse the alphabetic characters, and then merge them back into the original string with the reversed order of letters while preserving the positions of non-alphabetic characters.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution(object):\n def reverseOnlyLetters(self, s):\n l1 = []\n l = list(s)\n x = 0\n for i in range(len(s)):\n if s[i].isalpha():\n l1.append(s[i])\n l1.reverse()\n for i in range(len(s)):\n if l[i].isalpha():\n l[i] = l1[x]\n x = x+1\n return \'\'.join(l)\n```
2
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. **Example 1:** **Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz " **Output:** true **Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. **Example 2:** **Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz " **Output:** false **Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted. **Example 3:** **Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz " **Output:** false **Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `order.length == 26` * All characters in `words[i]` and `order` are English lowercase letters.
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
🔥 Beats 100% 💥 O(n) 🙌 Python 🌟 Two Pointer 📢 Easiest Approach 💡
reverse-only-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe simply convert the string to a list. Then, need to find if there are characters at both ends. If they are then we simple swap them by swapping their index. \n\nLastly, we convet the lis to a string again and return.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTwo pointer approach\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution(object):\n def reverseOnlyLetters(self, s):\n """\n :type s: str\n :rtype: str\n """\n s = list(s)\n\n left, right = 0, len(s)-1\n while left < right:\n if s[left].isalpha() and s[right].isalpha():\n\n s[left], s[right] = s[right], s[left]\n left += 1\n right -= 1\n elif s[left].isalpha() and not s[right].isalpha():\n right -=1\n else:\n left+=1\n\n\n return \'\'.join(s)\n\n```
2
Given a string `s`, reverse the string according to the following rules: * All the characters that are not English letters remain in the same position. * All the English letters (lowercase or uppercase) should be reversed. Return `s` _after reversing it_. **Example 1:** **Input:** s = "ab-cd" **Output:** "dc-ba" **Example 2:** **Input:** s = "a-bC-dEf-ghIj" **Output:** "j-Ih-gfE-dCba" **Example 3:** **Input:** s = "Test1ng-Leet=code-Q!" **Output:** "Qedo1ct-eeLg=ntse-T!" **Constraints:** * `1 <= s.length <= 100` * `s` consists of characters with ASCII values in the range `[33, 122]`. * `s` does not contain `'\ "'` or `'\\'`.
null
🔥 Beats 100% 💥 O(n) 🙌 Python 🌟 Two Pointer 📢 Easiest Approach 💡
reverse-only-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe simply convert the string to a list. Then, need to find if there are characters at both ends. If they are then we simple swap them by swapping their index. \n\nLastly, we convet the lis to a string again and return.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTwo pointer approach\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution(object):\n def reverseOnlyLetters(self, s):\n """\n :type s: str\n :rtype: str\n """\n s = list(s)\n\n left, right = 0, len(s)-1\n while left < right:\n if s[left].isalpha() and s[right].isalpha():\n\n s[left], s[right] = s[right], s[left]\n left += 1\n right -= 1\n elif s[left].isalpha() and not s[right].isalpha():\n right -=1\n else:\n left+=1\n\n\n return \'\'.join(s)\n\n```
2
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. **Example 1:** **Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz " **Output:** true **Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. **Example 2:** **Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz " **Output:** false **Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted. **Example 3:** **Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz " **Output:** false **Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `order.length == 26` * All characters in `words[i]` and `order` are English lowercase letters.
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.
Easy and Simple | Most Memory efficient more than 95%
reverse-only-letters
0
1
\n\n# Code\n```\nclass Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n alphabets = [i for i in s if i.isalpha()][-1::-1]\n for i in range(len(s)):\n if not(s[i].isalpha()):\n alphabets.insert(i,s[i])\n alphabets = \'\'.join(alphabets)\n return alphabets\n \n```\n\nIf u like the solution, **Pls Upvote**\n\n![dog.jpg](https://assets.leetcode.com/users/images/8e9aec85-0ebb-405a-a47c-1c64b64ee1a9_1682146061.7348528.jpeg)\n
8
Given a string `s`, reverse the string according to the following rules: * All the characters that are not English letters remain in the same position. * All the English letters (lowercase or uppercase) should be reversed. Return `s` _after reversing it_. **Example 1:** **Input:** s = "ab-cd" **Output:** "dc-ba" **Example 2:** **Input:** s = "a-bC-dEf-ghIj" **Output:** "j-Ih-gfE-dCba" **Example 3:** **Input:** s = "Test1ng-Leet=code-Q!" **Output:** "Qedo1ct-eeLg=ntse-T!" **Constraints:** * `1 <= s.length <= 100` * `s` consists of characters with ASCII values in the range `[33, 122]`. * `s` does not contain `'\ "'` or `'\\'`.
null
Easy and Simple | Most Memory efficient more than 95%
reverse-only-letters
0
1
\n\n# Code\n```\nclass Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n alphabets = [i for i in s if i.isalpha()][-1::-1]\n for i in range(len(s)):\n if not(s[i].isalpha()):\n alphabets.insert(i,s[i])\n alphabets = \'\'.join(alphabets)\n return alphabets\n \n```\n\nIf u like the solution, **Pls Upvote**\n\n![dog.jpg](https://assets.leetcode.com/users/images/8e9aec85-0ebb-405a-a47c-1c64b64ee1a9_1682146061.7348528.jpeg)\n
8
In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters. Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language. **Example 1:** **Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz " **Output:** true **Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted. **Example 2:** **Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz " **Output:** false **Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted. **Example 3:** **Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz " **Output:** false **Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)). **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `order.length == 26` * All characters in `words[i]` and `order` are English lowercase letters.
This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach.