title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
✅ [Python] 2-coloring using DFS / BFS
possible-bipartition
0
1
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\n\n**Comment.** The idea of this solution consists in traversing the graph of dislikes and coloring each next vertex into the opposite color. If, on some iteratrion, there is a collision (i.e., coloring second time with a different color) then the bipartition is not possible.\n\n**Python #1.** DFS.\n```\nclass Solution:\n def possibleBipartition(self, n: int, dis: List[List[int]]) -> bool:\n \n G, P = defaultdict(set), {}\n for i,j in dis : G[i].add(j), G[j].add(i)\n \n def dfs(i, p):\n if i in P : return P[i] == p\n P[i] = p\n return all(dfs(j, not p) for j in G[i])\n\n return all(dfs(i, True) for i in range(1,n+1) if i not in P)\n```\n\n**Python #2.** BFS.\n```\nclass Solution:\n def possibleBipartition(self, n: int, dis: List[List[int]]) -> bool:\n \n G = defaultdict(set)\n for i,j in dis : G[i].add(j), G[j].add(i)\n \n seen = dict()\n\n for k in range(1,n+1):\n if k not in seen:\n Q = deque([(k,True)])\n while Q:\n i, g = Q.popleft()\n seen[i] = g\n for j in G[i]:\n if j in seen:\n if seen[j] == g : return False\n else:\n seen[j] = not g\n Q.append((j, not g))\n \n return True\n```
10
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the person labeled `bi`, return `true` _if it is possible to split everyone into two groups in this way_. **Example 1:** **Input:** n = 4, dislikes = \[\[1,2\],\[1,3\],\[2,4\]\] **Output:** true **Explanation:** The first group has \[1,4\], and the second group has \[2,3\]. **Example 2:** **Input:** n = 3, dislikes = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** false **Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups. **Constraints:** * `1 <= n <= 2000` * `0 <= dislikes.length <= 104` * `dislikes[i].length == 2` * `1 <= ai < bi <= n` * All the pairs of `dislikes` are **unique**.
null
✅ [Python] 2-coloring using DFS / BFS
possible-bipartition
0
1
**\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n****\n\n**Comment.** The idea of this solution consists in traversing the graph of dislikes and coloring each next vertex into the opposite color. If, on some iteratrion, there is a collision (i.e., coloring second time with a different color) then the bipartition is not possible.\n\n**Python #1.** DFS.\n```\nclass Solution:\n def possibleBipartition(self, n: int, dis: List[List[int]]) -> bool:\n \n G, P = defaultdict(set), {}\n for i,j in dis : G[i].add(j), G[j].add(i)\n \n def dfs(i, p):\n if i in P : return P[i] == p\n P[i] = p\n return all(dfs(j, not p) for j in G[i])\n\n return all(dfs(i, True) for i in range(1,n+1) if i not in P)\n```\n\n**Python #2.** BFS.\n```\nclass Solution:\n def possibleBipartition(self, n: int, dis: List[List[int]]) -> bool:\n \n G = defaultdict(set)\n for i,j in dis : G[i].add(j), G[j].add(i)\n \n seen = dict()\n\n for k in range(1,n+1):\n if k not in seen:\n Q = deque([(k,True)])\n while Q:\n i, g = Q.popleft()\n seen[i] = g\n for j in G[i]:\n if j in seen:\n if seen[j] == g : return False\n else:\n seen[j] = not g\n Q.append((j, not g))\n \n return True\n```
10
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums = \[4,2,5,7\] **Output:** \[4,5,2,7\] **Explanation:** \[4,7,2,5\], \[2,5,4,7\], \[2,7,4,5\] would also have been accepted. **Example 2:** **Input:** nums = \[2,3\] **Output:** \[2,3\] **Constraints:** * `2 <= nums.length <= 2 * 104` * `nums.length` is even. * Half of the integers in `nums` are even. * `0 <= nums[i] <= 1000` **Follow Up:** Could you solve it in-place?
null
A terrible, iterative Python solution using far too many parallel data structures
possible-bipartition
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI immediately recognized this as a Union-Find problem, then wasted a bunch of time trying to code that from memory. I am trying blind challenges, so not allowing myself to look things up while coming up with a solution. Failing that, I decided to attemp a BFS solution, but iterative instead of just writing a recursive one like I should have. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nSpaghetti. Its pretty logical, but I have $$way$$ too many copies of data: there is an adjacency map for the dislikes, an array for storing which group each node was assigned, a set for each of our two potential groups, $$another$$ set for the union of the dislikes for each member of each group... \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nNo idea. We process each node in the for loop, so thats O(n), and for each of those we touch every neighbor, so O(n**2) worst case?\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nTecnically O(n), but too many copies of len(n). \n\n\n# Code\n```\n\nfrom collections import deque, defaultdict\n\nclass Solution:\n def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:\n if not dislikes:\n return True\n\n hate_dict = collections.defaultdict(list)\n for x,y in dislikes:\n hate_dict[x].append(y) \n hate_dict[y].append(x) \n \n group = ["x"]*(n+1)\n\n for curr in range(1,n+1):\n if group[curr] != "x":\n continue\n group[curr] = "a"\n b_queue = set(hate_dict[curr])\n a_hates = set(hate_dict[curr])\n a_queue = set()\n b_hates = set()\n while a_queue or b_queue:\n while b_queue:\n adj = b_queue.pop()\n if group[adj] == group[curr] or adj in b_hates:\n return False\n elif group[adj] == "x":\n group[adj] = "b"\n a_queue |= set([x for x in hate_dict[adj] if group[x] == "x"])\n b_hates |= set(hate_dict[adj])\n while a_queue:\n adj = a_queue.pop()\n if group[adj] == group[curr] or adj in a_hates:\n return False\n elif group[adj] == "x":\n group[adj] = "a"\n b_queue |= set([x for x in hate_dict[adj] if group[x] == "x"])\n a_hates |= set(hate_dict[adj])\n return True\n```
2
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the person labeled `bi`, return `true` _if it is possible to split everyone into two groups in this way_. **Example 1:** **Input:** n = 4, dislikes = \[\[1,2\],\[1,3\],\[2,4\]\] **Output:** true **Explanation:** The first group has \[1,4\], and the second group has \[2,3\]. **Example 2:** **Input:** n = 3, dislikes = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** false **Explanation:** We need at least 3 groups to divide them. We cannot put them in two groups. **Constraints:** * `1 <= n <= 2000` * `0 <= dislikes.length <= 104` * `dislikes[i].length == 2` * `1 <= ai < bi <= n` * All the pairs of `dislikes` are **unique**.
null
A terrible, iterative Python solution using far too many parallel data structures
possible-bipartition
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI immediately recognized this as a Union-Find problem, then wasted a bunch of time trying to code that from memory. I am trying blind challenges, so not allowing myself to look things up while coming up with a solution. Failing that, I decided to attemp a BFS solution, but iterative instead of just writing a recursive one like I should have. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nSpaghetti. Its pretty logical, but I have $$way$$ too many copies of data: there is an adjacency map for the dislikes, an array for storing which group each node was assigned, a set for each of our two potential groups, $$another$$ set for the union of the dislikes for each member of each group... \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nNo idea. We process each node in the for loop, so thats O(n), and for each of those we touch every neighbor, so O(n**2) worst case?\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nTecnically O(n), but too many copies of len(n). \n\n\n# Code\n```\n\nfrom collections import deque, defaultdict\n\nclass Solution:\n def possibleBipartition(self, n: int, dislikes: List[List[int]]) -> bool:\n if not dislikes:\n return True\n\n hate_dict = collections.defaultdict(list)\n for x,y in dislikes:\n hate_dict[x].append(y) \n hate_dict[y].append(x) \n \n group = ["x"]*(n+1)\n\n for curr in range(1,n+1):\n if group[curr] != "x":\n continue\n group[curr] = "a"\n b_queue = set(hate_dict[curr])\n a_hates = set(hate_dict[curr])\n a_queue = set()\n b_hates = set()\n while a_queue or b_queue:\n while b_queue:\n adj = b_queue.pop()\n if group[adj] == group[curr] or adj in b_hates:\n return False\n elif group[adj] == "x":\n group[adj] = "b"\n a_queue |= set([x for x in hate_dict[adj] if group[x] == "x"])\n b_hates |= set(hate_dict[adj])\n while a_queue:\n adj = a_queue.pop()\n if group[adj] == group[curr] or adj in a_hates:\n return False\n elif group[adj] == "x":\n group[adj] = "a"\n b_queue |= set([x for x in hate_dict[adj] if group[x] == "x"])\n a_hates |= set(hate_dict[adj])\n return True\n```
2
Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return _any answer array that satisfies this condition_. **Example 1:** **Input:** nums = \[4,2,5,7\] **Output:** \[4,5,2,7\] **Explanation:** \[4,7,2,5\], \[2,5,4,7\], \[2,7,4,5\] would also have been accepted. **Example 2:** **Input:** nums = \[2,3\] **Output:** \[2,3\] **Constraints:** * `2 <= nums.length <= 2 * 104` * `nums.length` is even. * Half of the integers in `nums` are even. * `0 <= nums[i] <= 1000` **Follow Up:** Could you solve it in-place?
null
Python | DP | Binary Search
super-egg-drop
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 superEggDrop(self, k: int, n: int) -> int:\n def ed(e,f,dp):\n if f == 0 or f == 1:\n return f\n if e == 1:\n return f\n if dp[e][f] != -1:\n return dp[e][f]\n mini = 10001\n l = 1\n h = f\n while l<=h:\n k = (l+h)//2\n if dp[e-1][k-1] != -1:\n low = dp[e-1][k-1]\n else:\n low = ed(e-1,k-1,dp)\n if dp[e][f-k] != -1:\n high = dp[e][f-k]\n else:\n high = ed(e,f-k,dp)\n temp = max(high,low) + 1\n if high > low:\n l = k+1\n else:\n h = k-1\n mini = min(mini,temp)\n dp[e][f] = mini\n return mini\n dp = [[-1 for i in range(n+1)] for i in range(k+1)]\n ans = ed(k,n,dp)\n return ans\n\n\n```
2
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, you may take an unbroken egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. **Example 1:** **Input:** k = 1, n = 2 **Output:** 2 **Explanation:** Drop the egg from floor 1. If it breaks, we know that f = 0. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. If it does not break, then we know f = 2. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. **Example 2:** **Input:** k = 2, n = 6 **Output:** 3 **Example 3:** **Input:** k = 3, n = 14 **Output:** 4 **Constraints:** * `1 <= k <= 100` * `1 <= n <= 104`
null
Python | DP | Binary Search
super-egg-drop
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 superEggDrop(self, k: int, n: int) -> int:\n def ed(e,f,dp):\n if f == 0 or f == 1:\n return f\n if e == 1:\n return f\n if dp[e][f] != -1:\n return dp[e][f]\n mini = 10001\n l = 1\n h = f\n while l<=h:\n k = (l+h)//2\n if dp[e-1][k-1] != -1:\n low = dp[e-1][k-1]\n else:\n low = ed(e-1,k-1,dp)\n if dp[e][f-k] != -1:\n high = dp[e][f-k]\n else:\n high = ed(e,f-k,dp)\n temp = max(high,low) + 1\n if high > low:\n l = k+1\n else:\n h = k-1\n mini = min(mini,temp)\n dp[e][f] = mini\n return mini\n dp = [[-1 for i in range(n+1)] for i in range(k+1)]\n ans = ed(k,n,dp)\n return ans\n\n\n```
2
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8 **Output:** 20 **Explanation:** Enumerating by the values (arr\[i\], arr\[j\], arr\[k\]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. **Example 2:** **Input:** arr = \[1,1,2,2,2,2\], target = 5 **Output:** 12 **Explanation:** arr\[i\] = 1, arr\[j\] = arr\[k\] = 2 occurs 12 times: We choose one 1 from \[1,1\] in 2 ways, and two 2s from \[2,2,2,2\] in 6 ways. **Example 3:** **Input:** arr = \[2,1,3\], target = 6 **Output:** 1 **Explanation:** (1, 2, 3) occured one time in the array so we return 1. **Constraints:** * `3 <= arr.length <= 3000` * `0 <= arr[i] <= 100` * `0 <= target <= 300`
null
One liner | O(KlogN) Time | O(1) Memory | Intuition + Explanation | Beats 95% time and 100% Memory
super-egg-drop
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe don\'t have to worry about finding the optimal strategy to determine the answer. We just need to find the number of minimum drops (by playing some optimal strategy).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAssume that the answer is m, that is the eggs were dropped m times.\nIn these m tries, what are all the possibilites? That 1 eggs break, or 2 eggs break or k eggs break\n\nProblem : In a sequence of m drops, count the total number of seqeunces where atmost k eggs break.\n\nf(m,k) = mC1 + mC2 ..... + mCk\n\nAnd that is the maximum number of floors that can be searched using k eggs and m drops.\n\nUse Binary search to find the least value for m so that f(m,k) >= n\n\n# Complexity\n- Time complexity:\nO(KlogN)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def superEggDrop(self, k: int, n: int) -> int:\n return bisect_left(range(0,n), n, key = lambda drops : sum(comb(drops, x) for x in range(1,k+1)) )\n \n```
1
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, you may take an unbroken egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. **Example 1:** **Input:** k = 1, n = 2 **Output:** 2 **Explanation:** Drop the egg from floor 1. If it breaks, we know that f = 0. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. If it does not break, then we know f = 2. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. **Example 2:** **Input:** k = 2, n = 6 **Output:** 3 **Example 3:** **Input:** k = 3, n = 14 **Output:** 4 **Constraints:** * `1 <= k <= 100` * `1 <= n <= 104`
null
One liner | O(KlogN) Time | O(1) Memory | Intuition + Explanation | Beats 95% time and 100% Memory
super-egg-drop
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe don\'t have to worry about finding the optimal strategy to determine the answer. We just need to find the number of minimum drops (by playing some optimal strategy).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nAssume that the answer is m, that is the eggs were dropped m times.\nIn these m tries, what are all the possibilites? That 1 eggs break, or 2 eggs break or k eggs break\n\nProblem : In a sequence of m drops, count the total number of seqeunces where atmost k eggs break.\n\nf(m,k) = mC1 + mC2 ..... + mCk\n\nAnd that is the maximum number of floors that can be searched using k eggs and m drops.\n\nUse Binary search to find the least value for m so that f(m,k) >= n\n\n# Complexity\n- Time complexity:\nO(KlogN)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def superEggDrop(self, k: int, n: int) -> int:\n return bisect_left(range(0,n), n, key = lambda drops : sum(comb(drops, x) for x in range(1,k+1)) )\n \n```
1
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8 **Output:** 20 **Explanation:** Enumerating by the values (arr\[i\], arr\[j\], arr\[k\]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. **Example 2:** **Input:** arr = \[1,1,2,2,2,2\], target = 5 **Output:** 12 **Explanation:** arr\[i\] = 1, arr\[j\] = arr\[k\] = 2 occurs 12 times: We choose one 1 from \[1,1\] in 2 ways, and two 2s from \[2,2,2,2\] in 6 ways. **Example 3:** **Input:** arr = \[2,1,3\], target = 6 **Output:** 1 **Explanation:** (1, 2, 3) occured one time in the array so we return 1. **Constraints:** * `3 <= arr.length <= 3000` * `0 <= arr[i] <= 100` * `0 <= target <= 300`
null
Matrix chain multiplication with Python
super-egg-drop
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 superEggDrop(self, k: int, n: int) -> int:\n #Matrix chain multiplication\n t=[[-1 for i in range(n+1)] for j in range(k+1)]\n \n def solve(k,n):\n if n==0 or n==1:\n return n\n if k==1:\n return n\n if t[k][n]!=-1:\n return t[k][n]\n mn=float(\'inf\')\n l=1\n h=n\n while l<=h:\n mid=(l+h)//2\n if t[k-1][mid-1]!=-1:\n left=t[k-1][mid-1]\n else:\n left=solve(k-1,mid-1)\n t[k-1][mid-1]=left\n \n if t[k][n-mid]!=-1:\n right=t[k][n-mid]\n else:\n right=solve(k,n-mid)\n t[k][n-mid]=right\n temp=1+max(left,right)\n if left<right:\n l=mid+1\n else:\n h=mid-1\n mn=min(temp,mn)\n t[k][n]=mn\n return mn\n\n return solve(k,n)\n```
1
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, you may take an unbroken egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. **Example 1:** **Input:** k = 1, n = 2 **Output:** 2 **Explanation:** Drop the egg from floor 1. If it breaks, we know that f = 0. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. If it does not break, then we know f = 2. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. **Example 2:** **Input:** k = 2, n = 6 **Output:** 3 **Example 3:** **Input:** k = 3, n = 14 **Output:** 4 **Constraints:** * `1 <= k <= 100` * `1 <= n <= 104`
null
Matrix chain multiplication with Python
super-egg-drop
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 superEggDrop(self, k: int, n: int) -> int:\n #Matrix chain multiplication\n t=[[-1 for i in range(n+1)] for j in range(k+1)]\n \n def solve(k,n):\n if n==0 or n==1:\n return n\n if k==1:\n return n\n if t[k][n]!=-1:\n return t[k][n]\n mn=float(\'inf\')\n l=1\n h=n\n while l<=h:\n mid=(l+h)//2\n if t[k-1][mid-1]!=-1:\n left=t[k-1][mid-1]\n else:\n left=solve(k-1,mid-1)\n t[k-1][mid-1]=left\n \n if t[k][n-mid]!=-1:\n right=t[k][n-mid]\n else:\n right=solve(k,n-mid)\n t[k][n-mid]=right\n temp=1+max(left,right)\n if left<right:\n l=mid+1\n else:\n h=mid-1\n mn=min(temp,mn)\n t[k][n]=mn\n return mn\n\n return solve(k,n)\n```
1
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8 **Output:** 20 **Explanation:** Enumerating by the values (arr\[i\], arr\[j\], arr\[k\]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. **Example 2:** **Input:** arr = \[1,1,2,2,2,2\], target = 5 **Output:** 12 **Explanation:** arr\[i\] = 1, arr\[j\] = arr\[k\] = 2 occurs 12 times: We choose one 1 from \[1,1\] in 2 ways, and two 2s from \[2,2,2,2\] in 6 ways. **Example 3:** **Input:** arr = \[2,1,3\], target = 6 **Output:** 1 **Explanation:** (1, 2, 3) occured one time in the array so we return 1. **Constraints:** * `3 <= arr.length <= 3000` * `0 <= arr[i] <= 100` * `0 <= target <= 300`
null
Solution
super-egg-drop
1
1
```C++ []\nclass Solution {\npublic:\n int superEggDrop(int K, int N) {\n int dp[N+1][K+1]; memset(dp, 0, sizeof dp);\n int m = 0;\n while (dp[m][K] < N) {\n m++;\n for (int k = 1; k <= K; ++k)\n dp[m][k] = dp[m-1][k- 1] + dp[m-1][k] + 1;\n }\n return m;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def superEggDrop(self, k: int, n: int) -> int:\n @cache\n def move(kk, m):\n if kk == 1: return m\n if kk >= m: return pow(2, m) - 1\n return move(kk-1, m-1) + move(kk, m-1) + 1\n\n for i in range(int(log(n, 2))+1, n+1):\n if move(k, i) >= n:\n return i\n```\n\n```Java []\nclass Solution {\n public int superEggDrop(int k, int n) {\n \n int dp[]=new int[k+1], m;\n for(m=0;dp[k] < n; m++){\n \n for(int x=k;x>0;x--){\n dp[x]+=1+dp[x-1];\n }\n }\n return m;\n }\n}\n```\n
1
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, you may take an unbroken egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. **Example 1:** **Input:** k = 1, n = 2 **Output:** 2 **Explanation:** Drop the egg from floor 1. If it breaks, we know that f = 0. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. If it does not break, then we know f = 2. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. **Example 2:** **Input:** k = 2, n = 6 **Output:** 3 **Example 3:** **Input:** k = 3, n = 14 **Output:** 4 **Constraints:** * `1 <= k <= 100` * `1 <= n <= 104`
null
Solution
super-egg-drop
1
1
```C++ []\nclass Solution {\npublic:\n int superEggDrop(int K, int N) {\n int dp[N+1][K+1]; memset(dp, 0, sizeof dp);\n int m = 0;\n while (dp[m][K] < N) {\n m++;\n for (int k = 1; k <= K; ++k)\n dp[m][k] = dp[m-1][k- 1] + dp[m-1][k] + 1;\n }\n return m;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def superEggDrop(self, k: int, n: int) -> int:\n @cache\n def move(kk, m):\n if kk == 1: return m\n if kk >= m: return pow(2, m) - 1\n return move(kk-1, m-1) + move(kk, m-1) + 1\n\n for i in range(int(log(n, 2))+1, n+1):\n if move(k, i) >= n:\n return i\n```\n\n```Java []\nclass Solution {\n public int superEggDrop(int k, int n) {\n \n int dp[]=new int[k+1], m;\n for(m=0;dp[k] < n; m++){\n \n for(int x=k;x>0;x--){\n dp[x]+=1+dp[x-1];\n }\n }\n return m;\n }\n}\n```\n
1
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8 **Output:** 20 **Explanation:** Enumerating by the values (arr\[i\], arr\[j\], arr\[k\]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. **Example 2:** **Input:** arr = \[1,1,2,2,2,2\], target = 5 **Output:** 12 **Explanation:** arr\[i\] = 1, arr\[j\] = arr\[k\] = 2 occurs 12 times: We choose one 1 from \[1,1\] in 2 ways, and two 2s from \[2,2,2,2\] in 6 ways. **Example 3:** **Input:** arr = \[2,1,3\], target = 6 **Output:** 1 **Explanation:** (1, 2, 3) occured one time in the array so we return 1. **Constraints:** * `3 <= arr.length <= 3000` * `0 <= arr[i] <= 100` * `0 <= target <= 300`
null
Solution
fair-candy-swap
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {\n bitset<200002> bf;\n int sumA = 0, sumB = 0;\n for(auto n: A) {\n sumA += n;\n }\n for(auto n: B) {\n sumB += n;\n bf.set(2*n);\n }\n int diff = sumA - sumB;\n for(auto n: A) {\n int det = 2*n - diff;\n if(det > 0 && det < 200002 && bf.test(det)) {\n return {n, (2*n-diff)/2};\n }\n }\n return {};\n }\n};\nauto gucciGang = []() {std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();\n```\n\n```Python3 []\nclass Solution:\n def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:\n \n x = (sum(aliceSizes)-sum(bobSizes)) / 2\n\n sets = set(aliceSizes)\n\n for y in bobSizes:\n if y + x in sets: \n return [y + x, y]\n```\n\n```Java []\nclass Solution {\n public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {\n int aum = 0;\n boolean[] inAlice = new boolean[100001];\n for (int i = 0; i < aliceSizes.length; i++) {\n aum += aliceSizes[i];\n inAlice[aliceSizes[i]] = true;\n }\n int bum = 0;\n for (int i = 0; i < bobSizes.length; i++) {\n bum += bobSizes[i];\n }\n int diff = aum - bum;\n int[] ans = new int[2];\n for (int i = 0; i < bobSizes.length; i++) {\n int target = bobSizes[i] + diff / 2;\n if (target > 0 && target < 100001) {\n if (inAlice[target]) {\n ans = new int[] {target, bobSizes[i]};\n return ans;\n }\n }\n }\n return ans;\n }\n}\n```\n
1
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
Solution
fair-candy-swap
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> fairCandySwap(vector<int>& A, vector<int>& B) {\n bitset<200002> bf;\n int sumA = 0, sumB = 0;\n for(auto n: A) {\n sumA += n;\n }\n for(auto n: B) {\n sumB += n;\n bf.set(2*n);\n }\n int diff = sumA - sumB;\n for(auto n: A) {\n int det = 2*n - diff;\n if(det > 0 && det < 200002 && bf.test(det)) {\n return {n, (2*n-diff)/2};\n }\n }\n return {};\n }\n};\nauto gucciGang = []() {std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();\n```\n\n```Python3 []\nclass Solution:\n def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:\n \n x = (sum(aliceSizes)-sum(bobSizes)) / 2\n\n sets = set(aliceSizes)\n\n for y in bobSizes:\n if y + x in sets: \n return [y + x, y]\n```\n\n```Java []\nclass Solution {\n public int[] fairCandySwap(int[] aliceSizes, int[] bobSizes) {\n int aum = 0;\n boolean[] inAlice = new boolean[100001];\n for (int i = 0; i < aliceSizes.length; i++) {\n aum += aliceSizes[i];\n inAlice[aliceSizes[i]] = true;\n }\n int bum = 0;\n for (int i = 0; i < bobSizes.length; i++) {\n bum += bobSizes[i];\n }\n int diff = aum - bum;\n int[] ans = new int[2];\n for (int i = 0; i < bobSizes.length; i++) {\n int target = bobSizes[i] + diff / 2;\n if (target > 0 && target < 100001) {\n if (inAlice[target]) {\n ans = new int[] {target, bobSizes[i]};\n return ans;\n }\n }\n }\n return ans;\n }\n}\n```\n
1
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. Note that if a node was removed from the `initial` list of infected nodes, it might still be infected later due to the malware spread. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\], initial = \[0,2\] **Output:** 0 **Example 3:** **Input:** graph = \[\[1,1,1\],\[1,1,1\],\[1,1,1\]\], initial = \[1,2\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length <= n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Math behind lee215's solution
fair-candy-swap
0
1
Assume that alice has sizes $[x_1, x_2, ..., x_m]$, while bob has sizes $[y_1, y_2, ..., y_n]$. Also, we are going to switch $x_a$ and $y_b$ so that they will have some size total at the end. Then, we have\n\n$$\\sum_{i=1}^nx_i - x_a + y_b = \\sum_{j=1}^my_j - y_b + x_a$$\n\nwhich can be rewritten as \n\n$$\\sum_{i=1}^nx_i - \\sum_{j=1}^my_j = 2x_a - 2y_b $$\n\nwhich is\n\n$$diff = \\frac{\\sum_{i=1}^nx_i - \\sum_{j=1}^my_j}{2} = x_a - y_b $$\n\nTherefore, if `diff + bob_size` is in `aliceSizes`, we know that we find the result. \n\nHope this helps.\n\n\n# Code\n```\nclass Solution:\n def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:\n delta = (sum(aliceSizes) - sum(bobSizes)) // 2\n aliceSizes = set(aliceSizes)\n for size in set(bobSizes):\n if delta + size in aliceSizes:\n return [delta + size, size]\n```\n\n
10
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
Math behind lee215's solution
fair-candy-swap
0
1
Assume that alice has sizes $[x_1, x_2, ..., x_m]$, while bob has sizes $[y_1, y_2, ..., y_n]$. Also, we are going to switch $x_a$ and $y_b$ so that they will have some size total at the end. Then, we have\n\n$$\\sum_{i=1}^nx_i - x_a + y_b = \\sum_{j=1}^my_j - y_b + x_a$$\n\nwhich can be rewritten as \n\n$$\\sum_{i=1}^nx_i - \\sum_{j=1}^my_j = 2x_a - 2y_b $$\n\nwhich is\n\n$$diff = \\frac{\\sum_{i=1}^nx_i - \\sum_{j=1}^my_j}{2} = x_a - y_b $$\n\nTherefore, if `diff + bob_size` is in `aliceSizes`, we know that we find the result. \n\nHope this helps.\n\n\n# Code\n```\nclass Solution:\n def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:\n delta = (sum(aliceSizes) - sum(bobSizes)) // 2\n aliceSizes = set(aliceSizes)\n for size in set(bobSizes):\n if delta + size in aliceSizes:\n return [delta + size, size]\n```\n\n
10
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. Note that if a node was removed from the `initial` list of infected nodes, it might still be infected later due to the malware spread. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\], initial = \[0,2\] **Output:** 0 **Example 3:** **Input:** graph = \[\[1,1,1\],\[1,1,1\],\[1,1,1\]\], initial = \[1,2\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length <= n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Python. Super simple solution.
fair-candy-swap
0
1
```\nclass Solution:\n def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:\n difference = (sum(A) - sum(B)) / 2\n A = set(A)\n for candy in set(B):\n if difference + candy in A:\n return [difference + candy, candy]
15
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
Python. Super simple solution.
fair-candy-swap
0
1
```\nclass Solution:\n def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:\n difference = (sum(A) - sum(B)) / 2\n A = set(A)\n for candy in set(B):\n if difference + candy in A:\n return [difference + candy, candy]
15
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. Note that if a node was removed from the `initial` list of infected nodes, it might still be infected later due to the malware spread. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\], initial = \[0,2\] **Output:** 0 **Example 3:** **Input:** graph = \[\[1,1,1\],\[1,1,1\],\[1,1,1\]\], initial = \[1,2\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length <= n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
python3 with explanation
fair-candy-swap
0
1
sum(alice)-i+j=sum(bob)-j+i\n diff=2(i-j)\n diff/2=(i-j)\n diff/2+j=i\n j=i-diff/2\n```\nclass Solution:\n def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:\n total_alice=sum(aliceSizes)\n total_bob=sum(bobSizes)\n diff=(total_alice-total_bob)//2\n \n for i in set(aliceSizes):\n if i-diff in set(bobSizes):\n return [i,i-diff]\n \n\n\t\t```
5
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
python3 with explanation
fair-candy-swap
0
1
sum(alice)-i+j=sum(bob)-j+i\n diff=2(i-j)\n diff/2=(i-j)\n diff/2+j=i\n j=i-diff/2\n```\nclass Solution:\n def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:\n total_alice=sum(aliceSizes)\n total_bob=sum(bobSizes)\n diff=(total_alice-total_bob)//2\n \n for i in set(aliceSizes):\n if i-diff in set(bobSizes):\n return [i,i-diff]\n \n\n\t\t```
5
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. Note that if a node was removed from the `initial` list of infected nodes, it might still be infected later due to the malware spread. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\], initial = \[0,2\] **Output:** 0 **Example 3:** **Input:** graph = \[\[1,1,1\],\[1,1,1\],\[1,1,1\]\], initial = \[1,2\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length <= n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
[Python] Binary Search with explanation
fair-candy-swap
0
1
* This is the first time I posted my solution, and I am a beginner in algorism, hope this simple solution can give you some help. \n* Please feel free to comment, hope to learn more from you!\n```\nclass Solution(object):\n def fairCandySwap(self, aliceSizes, bobSizes):\n """\n :type aliceSizes: List[int]\n :type bobSizes: List[int]\n :rtype: List[int]\n """\n\t\t# Calculate the total value each list should satisfy\n alice, bob = 0, 0\n for i in aliceSizes: alice += i\n for j in bobSizes: bob += j\n each = (alice+bob)/2\n\t\t# Sort each list first to utilize the binary search\n aliceSizes.sort()\n bobSizes.sort()\n for i in range(len(aliceSizes)):\n alice_change = aliceSizes[i]\n bl, br = 0, len(bobSizes)-1\n while bl <= br:\n bm = bl + (br-bl)//2\n bob_change = bobSizes[bm]\n new_alice = alice - alice_change + bob_change\n new_bob = bob + alice_change - bob_change\n\t\t\t\t# If two list have the same value, then break\n if new_alice == new_bob:\n return [alice_change, bob_change]\n break\n\t\t\t\t# If new_alice > new_bob, we should choose a larger value for exchanging\n elif new_alice > new_bob:\n br = bm - 1\n\t\t\t\t# If new_alice < new_bob, we should choose a smaller value for exchanging\n elif new_alice < new_bob:\n bl = bm + 1\n```
6
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have. Return a_n integer array_ `answer` _where_ `answer[0]` _is the number of candies in the box that Alice must exchange, and_ `answer[1]` _is the number of candies in the box that Bob must exchange_. If there are multiple answers, you may **return any** one of them. It is guaranteed that at least one answer exists. **Example 1:** **Input:** aliceSizes = \[1,1\], bobSizes = \[2,2\] **Output:** \[1,2\] **Example 2:** **Input:** aliceSizes = \[1,2\], bobSizes = \[2,3\] **Output:** \[1,2\] **Example 3:** **Input:** aliceSizes = \[2\], bobSizes = \[1,3\] **Output:** \[2,3\] **Constraints:** * `1 <= aliceSizes.length, bobSizes.length <= 104` * `1 <= aliceSizes[i], bobSizes[j] <= 105` * Alice and Bob have a different total number of candies. * There will be at least one valid answer for the given input.
null
[Python] Binary Search with explanation
fair-candy-swap
0
1
* This is the first time I posted my solution, and I am a beginner in algorism, hope this simple solution can give you some help. \n* Please feel free to comment, hope to learn more from you!\n```\nclass Solution(object):\n def fairCandySwap(self, aliceSizes, bobSizes):\n """\n :type aliceSizes: List[int]\n :type bobSizes: List[int]\n :rtype: List[int]\n """\n\t\t# Calculate the total value each list should satisfy\n alice, bob = 0, 0\n for i in aliceSizes: alice += i\n for j in bobSizes: bob += j\n each = (alice+bob)/2\n\t\t# Sort each list first to utilize the binary search\n aliceSizes.sort()\n bobSizes.sort()\n for i in range(len(aliceSizes)):\n alice_change = aliceSizes[i]\n bl, br = 0, len(bobSizes)-1\n while bl <= br:\n bm = bl + (br-bl)//2\n bob_change = bobSizes[bm]\n new_alice = alice - alice_change + bob_change\n new_bob = bob + alice_change - bob_change\n\t\t\t\t# If two list have the same value, then break\n if new_alice == new_bob:\n return [alice_change, bob_change]\n break\n\t\t\t\t# If new_alice > new_bob, we should choose a larger value for exchanging\n elif new_alice > new_bob:\n br = bm - 1\n\t\t\t\t# If new_alice < new_bob, we should choose a smaller value for exchanging\n elif new_alice < new_bob:\n bl = bm + 1\n```
6
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. Note that if a node was removed from the `initial` list of infected nodes, it might still be infected later due to the malware spread. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\], initial = \[0,2\] **Output:** 0 **Example 3:** **Input:** graph = \[\[1,1,1\],\[1,1,1\],\[1,1,1\]\], initial = \[1,2\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length <= n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Solution
construct-binary-tree-from-preorder-and-postorder-traversal
1
1
```C++ []\nclass Solution {\npublic:\n TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {\n int n = preorder.size() - 1;\n return build(preorder, postorder, 0, n, 0, n);\n }\n TreeNode* build(vector<int>& preorder, vector<int>& postorder,\n int preLeft, int preRight, int postLeft, int postRight)\n {\n if (preLeft > preRight || postLeft > postRight) return NULL;\n TreeNode* ans = new TreeNode(preorder[preLeft]);\n if (preLeft == preRight) return ans; \n int len = 1;\n for (;len < preRight - preLeft; len++)\n {\n if (preorder[preLeft + 1] == postorder[postLeft + len - 1])\n break;\n }\n ans->left = build(preorder, postorder, preLeft + 1, preLeft + len, postLeft, postLeft + len - 1);\n ans->right = build(preorder, postorder, preLeft + len + 1, preRight, postLeft + len, postRight - 1);\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n self.post_indices = {v: idx for idx, v in enumerate(postorder)}\n self.pre_index = 0\n\n print(preorder, postorder)\n def buildTree(left, right):\n if left > right:\n return None \n node = TreeNode(val=preorder[self.pre_index])\n self.pre_index +=1 \n if self.pre_index > len(preorder) - 1 or left == right: # critical\n return node \n post_index = self.post_indices[preorder[self.pre_index]]\n node.left = buildTree(left, post_index)\n node.right = buildTree(post_index + 1, right-1)\n return node\n \n return buildTree(0, len(preorder)-1)\n```\n\n```Java []\nclass Solution {\n public TreeNode constructFromPrePost(int[] PRE, int[] POST) {\n return build(PRE, POST);\n }\n int pre = 0, post = 0;\n TreeNode build(int[] PRE, int[] POST) {\n TreeNode n = new TreeNode(PRE[pre]);\n pre++;\n if (n.val != POST[post]) {\n n.left = build(PRE, POST);\n }\n if (n.val != POST[post]) {\n n.right = build(PRE, POST);\n }\n post++;\n return n;\n }\n}\n```\n
1
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. If there exist multiple answers, you can **return any** of them. **Example 1:** **Input:** preorder = \[1,2,4,5,3,6,7\], postorder = \[4,5,2,6,7,3,1\] **Output:** \[1,2,3,4,5,6,7\] **Example 2:** **Input:** preorder = \[1\], postorder = \[1\] **Output:** \[1\] **Constraints:** * `1 <= preorder.length <= 30` * `1 <= preorder[i] <= preorder.length` * All the values of `preorder` are **unique**. * `postorder.length == preorder.length` * `1 <= postorder[i] <= postorder.length` * All the values of `postorder` are **unique**. * It is guaranteed that `preorder` and `postorder` are the preorder traversal and postorder traversal of the same binary tree.
null
Solution
construct-binary-tree-from-preorder-and-postorder-traversal
1
1
```C++ []\nclass Solution {\npublic:\n TreeNode* constructFromPrePost(vector<int>& preorder, vector<int>& postorder) {\n int n = preorder.size() - 1;\n return build(preorder, postorder, 0, n, 0, n);\n }\n TreeNode* build(vector<int>& preorder, vector<int>& postorder,\n int preLeft, int preRight, int postLeft, int postRight)\n {\n if (preLeft > preRight || postLeft > postRight) return NULL;\n TreeNode* ans = new TreeNode(preorder[preLeft]);\n if (preLeft == preRight) return ans; \n int len = 1;\n for (;len < preRight - preLeft; len++)\n {\n if (preorder[preLeft + 1] == postorder[postLeft + len - 1])\n break;\n }\n ans->left = build(preorder, postorder, preLeft + 1, preLeft + len, postLeft, postLeft + len - 1);\n ans->right = build(preorder, postorder, preLeft + len + 1, preRight, postLeft + len, postRight - 1);\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n self.post_indices = {v: idx for idx, v in enumerate(postorder)}\n self.pre_index = 0\n\n print(preorder, postorder)\n def buildTree(left, right):\n if left > right:\n return None \n node = TreeNode(val=preorder[self.pre_index])\n self.pre_index +=1 \n if self.pre_index > len(preorder) - 1 or left == right: # critical\n return node \n post_index = self.post_indices[preorder[self.pre_index]]\n node.left = buildTree(left, post_index)\n node.right = buildTree(post_index + 1, right-1)\n return node\n \n return buildTree(0, len(preorder)-1)\n```\n\n```Java []\nclass Solution {\n public TreeNode constructFromPrePost(int[] PRE, int[] POST) {\n return build(PRE, POST);\n }\n int pre = 0, post = 0;\n TreeNode build(int[] PRE, int[] POST) {\n TreeNode n = new TreeNode(PRE[pre]);\n pre++;\n if (n.val != POST[post]) {\n n.left = build(PRE, POST);\n }\n if (n.val != POST[post]) {\n n.right = build(PRE, POST);\n }\n post++;\n return n;\n }\n}\n```\n
1
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed. **Example 1:** **Input:** name = "alex ", typed = "aaleex " **Output:** true **Explanation:** 'a' and 'e' in 'alex' were long pressed. **Example 2:** **Input:** name = "saeed ", typed = "ssaaedd " **Output:** false **Explanation:** 'e' must have been pressed twice, but it was not in the typed output. **Constraints:** * `1 <= name.length, typed.length <= 1000` * `name` and `typed` consist of only lowercase English letters.
null
🔥🔥 || Beats 100% python Binary search Tree || 🔥🔥
construct-binary-tree-from-preorder-and-postorder-traversal
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```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n \n if not preorder:\n return None \n\n root = TreeNode(preorder[0])\n \n if len(preorder) == 1:\n return root \n\n # Find the left subtree\'s root value in preorder\n left_subtree_root_val = preorder[1]\n \n # Find the left subtree\'s size in postorder\n left_subtree_size = postorder.index(left_subtree_root_val) + 1\n \n root.left = self.constructFromPrePost(preorder[1:left_subtree_size+1], postorder[:left_subtree_size])\n root.right = self.constructFromPrePost(preorder[left_subtree_size+1:], postorder[left_subtree_size:-1])\n\n return root\n```
4
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. If there exist multiple answers, you can **return any** of them. **Example 1:** **Input:** preorder = \[1,2,4,5,3,6,7\], postorder = \[4,5,2,6,7,3,1\] **Output:** \[1,2,3,4,5,6,7\] **Example 2:** **Input:** preorder = \[1\], postorder = \[1\] **Output:** \[1\] **Constraints:** * `1 <= preorder.length <= 30` * `1 <= preorder[i] <= preorder.length` * All the values of `preorder` are **unique**. * `postorder.length == preorder.length` * `1 <= postorder[i] <= postorder.length` * All the values of `postorder` are **unique**. * It is guaranteed that `preorder` and `postorder` are the preorder traversal and postorder traversal of the same binary tree.
null
🔥🔥 || Beats 100% python Binary search Tree || 🔥🔥
construct-binary-tree-from-preorder-and-postorder-traversal
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```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n \n if not preorder:\n return None \n\n root = TreeNode(preorder[0])\n \n if len(preorder) == 1:\n return root \n\n # Find the left subtree\'s root value in preorder\n left_subtree_root_val = preorder[1]\n \n # Find the left subtree\'s size in postorder\n left_subtree_size = postorder.index(left_subtree_root_val) + 1\n \n root.left = self.constructFromPrePost(preorder[1:left_subtree_size+1], postorder[:left_subtree_size])\n root.right = self.constructFromPrePost(preorder[left_subtree_size+1:], postorder[left_subtree_size:-1])\n\n return root\n```
4
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed. **Example 1:** **Input:** name = "alex ", typed = "aaleex " **Output:** true **Explanation:** 'a' and 'e' in 'alex' were long pressed. **Example 2:** **Input:** name = "saeed ", typed = "ssaaedd " **Output:** false **Explanation:** 'e' must have been pressed twice, but it was not in the typed output. **Constraints:** * `1 <= name.length, typed.length <= 1000` * `name` and `typed` consist of only lowercase English letters.
null
Perhaps shortest Python O(n) solution
construct-binary-tree-from-preorder-and-postorder-traversal
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n\nModified from [lee215\'s solution](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/solutions/161268/c-java-python-one-pass-real-o-n/), with two index vars replaced by pop operations.\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$ extra space\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n root = TreeNode(postorder.pop())\n if root.val != preorder[-1]:\n root.right = self.constructFromPrePost(preorder, postorder)\n if root.val != preorder[-1]:\n root.left = self.constructFromPrePost(preorder, postorder)\n preorder.pop()\n return root\n```
1
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. If there exist multiple answers, you can **return any** of them. **Example 1:** **Input:** preorder = \[1,2,4,5,3,6,7\], postorder = \[4,5,2,6,7,3,1\] **Output:** \[1,2,3,4,5,6,7\] **Example 2:** **Input:** preorder = \[1\], postorder = \[1\] **Output:** \[1\] **Constraints:** * `1 <= preorder.length <= 30` * `1 <= preorder[i] <= preorder.length` * All the values of `preorder` are **unique**. * `postorder.length == preorder.length` * `1 <= postorder[i] <= postorder.length` * All the values of `postorder` are **unique**. * It is guaranteed that `preorder` and `postorder` are the preorder traversal and postorder traversal of the same binary tree.
null
Perhaps shortest Python O(n) solution
construct-binary-tree-from-preorder-and-postorder-traversal
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n\nModified from [lee215\'s solution](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/solutions/161268/c-java-python-one-pass-real-o-n/), with two index vars replaced by pop operations.\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$ extra space\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n root = TreeNode(postorder.pop())\n if root.val != preorder[-1]:\n root.right = self.constructFromPrePost(preorder, postorder)\n if root.val != preorder[-1]:\n root.left = self.constructFromPrePost(preorder, postorder)\n preorder.pop()\n return root\n```
1
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed. **Example 1:** **Input:** name = "alex ", typed = "aaleex " **Output:** true **Explanation:** 'a' and 'e' in 'alex' were long pressed. **Example 2:** **Input:** name = "saeed ", typed = "ssaaedd " **Output:** false **Explanation:** 'e' must have been pressed twice, but it was not in the typed output. **Constraints:** * `1 <= name.length, typed.length <= 1000` * `name` and `typed` consist of only lowercase English letters.
null
Python3 Solution with a Detailed Explanation - Construct Binary Tree from
construct-binary-tree-from-preorder-and-postorder-traversal
0
1
Make sure you understand the preorder and postorder traversal and how the nodes are arranged in each, with respect to the other one. [This](https://www.***.org/if-you-are-given-two-traversal-sequences-can-you-construct-the-binary-tree/) might help. I also find [this](https://www.***.org/full-and-complete-binary-tree-from-given-preorder-and-postorder-traversals/) explanation helpful. The solution that I\'ll show below comes from reading different posts on leetcode and elsewhere. \n\nSome relations between the two orders include: 1) the first node of `pre` is root, same as the last node of `post`. 2) The second node of `pre` is left subtree root, while the second to the last node of `post` is the right subtree root. Now think for a moment about `post`. The last number is `root` value, if we do `post.pop()`, what is the last element now? The root of right subtree, right? What if we do that again? The last node now is the root of a deeper subtree on the right side again (`7`). \n\nCheck out this example! `pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]`. This can correspond to a tree like this (note that we can construct many trees given `pre` and `post`): \n\n\t\t\t\t\t 1\n\t\t\t\t2 3\n\t\t\t 4\t 5 6 7\n\nThe node of right subtrees are `3`, and then `7`. If you check the `post`, you\'ll see that they appear from right after `root`. We\'ll use this in the solution. We do some prechecking to see whether tree is empty of not. If there has zero nodes, we return `None`. If there is one node, it\'s root, we `return TreeNode(post.pop())`. Line `#3` adds the last element of `post` to the tree as the `root` of that level. Then, in line `#4`, it finds the index in `pre` corresponding to the last element of `post` after popping (the `root` of right subtree in that level) because that element is the start of right subtree in `pre` (check the example). After we `pop` the root (`1`) from `post`, the root of right subtree is `3`. Now, in `pre`, anything before `3` corresponds to the left subtree with `2` being the root of it. \n\nNow comes the recursive part of solution. We split the `pre` into two parts, one for right subtree (line `#1`) and one for left subtree (line `#2`). We add them to `node.right` and `node.left`, respectively. Imaging you\'re at the `root` level, in line `#3`, you add the root to `node`. Then, line `#1` after recursion produces the whole right subtree, and line `#2` produces the whole left subtree. Finally, `node` is returned which includes all the elements. Keep reading! \n\n\t\t\t\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:\n # read this: https://www.techiedelight.com/construct-full-binary-tree-from-preorder-postorder-sequence/\n def helper(pre,post):\n print(\'pre is: \', pre, \'post is: \', post)\n if not pre:\n return None\n \n if len(pre)==1:\n return TreeNode(post.pop())\n \n \n node=TreeNode(post.pop()) #3\n ind=pre.index(post[-1]) #4\n \n node.right=helper(pre[ind:],post) #1\n node.left=helper(pre[1:ind],post) #2\n return node\n \n return helper(pre,post)\n```\n\nIf you print `pre` and `post` everytime the `helper` function is called, you get something like this: \n\t\t\t\n```\npre is: [1, 2, 4, 5, 3, 6, 7] post is: [4, 5, 2, 6, 7, 3, 1] # initial\npre is: [3, 6, 7] post is: [4, 5, 2, 6, 7, 3] # right subtree depth 1 (right side of root) \npre is: [7] post is: [4, 5, 2, 6, 7] # right subtree depth 2 (right side of root)\npre is: [6] post is: [4, 5, 2, 6] # line 2 is called for left subtree of level 2 (right side of root)\npre is: [2, 4, 5] post is: [4, 5, 2] # line 2 is called for level one left subtree (left side of root)\npre is: [5] post is: [4, 5] # line 1 is called for right subtree of level 2 (left side of root)\npre is: [4] post is: [4] # line 2 is called for left subtree of level 2 (left side of root)\n```\n\nThe `pre` and `post` here show each of the traversals once `helper` is called. For example, at first row, initial `pre` and `post` are shown. Next row, is when `helper` is called in line `#1`. Now, we have a new `pre` and `post`. The `pre` is the one that gets splited in each calling of `helper` while `post` pops its last element every time `helper` is called. As you can see, `post` looses one element at a time. \n\nI hope it\'s clear. Let me know if there is any ambiquity anywhere. \n\n========================================================================\nFinal note: Please let me know if you found any typo/error/etc. I\'ll try to fix them. \n
43
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. If there exist multiple answers, you can **return any** of them. **Example 1:** **Input:** preorder = \[1,2,4,5,3,6,7\], postorder = \[4,5,2,6,7,3,1\] **Output:** \[1,2,3,4,5,6,7\] **Example 2:** **Input:** preorder = \[1\], postorder = \[1\] **Output:** \[1\] **Constraints:** * `1 <= preorder.length <= 30` * `1 <= preorder[i] <= preorder.length` * All the values of `preorder` are **unique**. * `postorder.length == preorder.length` * `1 <= postorder[i] <= postorder.length` * All the values of `postorder` are **unique**. * It is guaranteed that `preorder` and `postorder` are the preorder traversal and postorder traversal of the same binary tree.
null
Python3 Solution with a Detailed Explanation - Construct Binary Tree from
construct-binary-tree-from-preorder-and-postorder-traversal
0
1
Make sure you understand the preorder and postorder traversal and how the nodes are arranged in each, with respect to the other one. [This](https://www.***.org/if-you-are-given-two-traversal-sequences-can-you-construct-the-binary-tree/) might help. I also find [this](https://www.***.org/full-and-complete-binary-tree-from-given-preorder-and-postorder-traversals/) explanation helpful. The solution that I\'ll show below comes from reading different posts on leetcode and elsewhere. \n\nSome relations between the two orders include: 1) the first node of `pre` is root, same as the last node of `post`. 2) The second node of `pre` is left subtree root, while the second to the last node of `post` is the right subtree root. Now think for a moment about `post`. The last number is `root` value, if we do `post.pop()`, what is the last element now? The root of right subtree, right? What if we do that again? The last node now is the root of a deeper subtree on the right side again (`7`). \n\nCheck out this example! `pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]`. This can correspond to a tree like this (note that we can construct many trees given `pre` and `post`): \n\n\t\t\t\t\t 1\n\t\t\t\t2 3\n\t\t\t 4\t 5 6 7\n\nThe node of right subtrees are `3`, and then `7`. If you check the `post`, you\'ll see that they appear from right after `root`. We\'ll use this in the solution. We do some prechecking to see whether tree is empty of not. If there has zero nodes, we return `None`. If there is one node, it\'s root, we `return TreeNode(post.pop())`. Line `#3` adds the last element of `post` to the tree as the `root` of that level. Then, in line `#4`, it finds the index in `pre` corresponding to the last element of `post` after popping (the `root` of right subtree in that level) because that element is the start of right subtree in `pre` (check the example). After we `pop` the root (`1`) from `post`, the root of right subtree is `3`. Now, in `pre`, anything before `3` corresponds to the left subtree with `2` being the root of it. \n\nNow comes the recursive part of solution. We split the `pre` into two parts, one for right subtree (line `#1`) and one for left subtree (line `#2`). We add them to `node.right` and `node.left`, respectively. Imaging you\'re at the `root` level, in line `#3`, you add the root to `node`. Then, line `#1` after recursion produces the whole right subtree, and line `#2` produces the whole left subtree. Finally, `node` is returned which includes all the elements. Keep reading! \n\n\t\t\t\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:\n # read this: https://www.techiedelight.com/construct-full-binary-tree-from-preorder-postorder-sequence/\n def helper(pre,post):\n print(\'pre is: \', pre, \'post is: \', post)\n if not pre:\n return None\n \n if len(pre)==1:\n return TreeNode(post.pop())\n \n \n node=TreeNode(post.pop()) #3\n ind=pre.index(post[-1]) #4\n \n node.right=helper(pre[ind:],post) #1\n node.left=helper(pre[1:ind],post) #2\n return node\n \n return helper(pre,post)\n```\n\nIf you print `pre` and `post` everytime the `helper` function is called, you get something like this: \n\t\t\t\n```\npre is: [1, 2, 4, 5, 3, 6, 7] post is: [4, 5, 2, 6, 7, 3, 1] # initial\npre is: [3, 6, 7] post is: [4, 5, 2, 6, 7, 3] # right subtree depth 1 (right side of root) \npre is: [7] post is: [4, 5, 2, 6, 7] # right subtree depth 2 (right side of root)\npre is: [6] post is: [4, 5, 2, 6] # line 2 is called for left subtree of level 2 (right side of root)\npre is: [2, 4, 5] post is: [4, 5, 2] # line 2 is called for level one left subtree (left side of root)\npre is: [5] post is: [4, 5] # line 1 is called for right subtree of level 2 (left side of root)\npre is: [4] post is: [4] # line 2 is called for left subtree of level 2 (left side of root)\n```\n\nThe `pre` and `post` here show each of the traversals once `helper` is called. For example, at first row, initial `pre` and `post` are shown. Next row, is when `helper` is called in line `#1`. Now, we have a new `pre` and `post`. The `pre` is the one that gets splited in each calling of `helper` while `post` pops its last element every time `helper` is called. As you can see, `post` looses one element at a time. \n\nI hope it\'s clear. Let me know if there is any ambiquity anywhere. \n\n========================================================================\nFinal note: Please let me know if you found any typo/error/etc. I\'ll try to fix them. \n
43
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed. **Example 1:** **Input:** name = "alex ", typed = "aaleex " **Output:** true **Explanation:** 'a' and 'e' in 'alex' were long pressed. **Example 2:** **Input:** name = "saeed ", typed = "ssaaedd " **Output:** false **Explanation:** 'e' must have been pressed twice, but it was not in the typed output. **Constraints:** * `1 <= name.length, typed.length <= 1000` * `name` and `typed` consist of only lowercase English letters.
null
[Python3] Same template to solve 3 Binary tree construction problems
construct-binary-tree-from-preorder-and-postorder-traversal
0
1
**Construct using Preorder and Postorder**\n\n```\nclass Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n if not preorder or not postorder:\n return\n \n root = TreeNode(preorder[0])\n if len(preorder) == 1:\n return root\n index = postorder.index(preorder[1])\n root.left = self.constructFromPrePost(preorder[1:index+2], postorder[:index+1])\n root.right = self.constructFromPrePost(preorder[index+2:], postorder[index+1:-1])\n return root\n```\n\n**Construct using Preorder and Inorder**\n\n```\nclass Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:\n if not preorder or not inorder:\n return\n \n root = TreeNode(preorder[0])\n mid = inorder.index(preorder[0])\n root.left = self.buildTree(preorder[1: mid+1], inorder[:mid])\n root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:])\n return root\n```\n\n**Construct using Postorder and Inorder**\n\n```\nclass Solution:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n if not postorder or not inorder:\n return\n \n root = TreeNode(postorder[-1])\n mid = inorder.index(postorder[-1])\n root.left = self.buildTree(inorder[:mid], postorder[:mid])\n root.right = self.buildTree(inorder[mid+1:], postorder[mid:-1])\n return root\n \n```\n
1
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. If there exist multiple answers, you can **return any** of them. **Example 1:** **Input:** preorder = \[1,2,4,5,3,6,7\], postorder = \[4,5,2,6,7,3,1\] **Output:** \[1,2,3,4,5,6,7\] **Example 2:** **Input:** preorder = \[1\], postorder = \[1\] **Output:** \[1\] **Constraints:** * `1 <= preorder.length <= 30` * `1 <= preorder[i] <= preorder.length` * All the values of `preorder` are **unique**. * `postorder.length == preorder.length` * `1 <= postorder[i] <= postorder.length` * All the values of `postorder` are **unique**. * It is guaranteed that `preorder` and `postorder` are the preorder traversal and postorder traversal of the same binary tree.
null
[Python3] Same template to solve 3 Binary tree construction problems
construct-binary-tree-from-preorder-and-postorder-traversal
0
1
**Construct using Preorder and Postorder**\n\n```\nclass Solution:\n def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n if not preorder or not postorder:\n return\n \n root = TreeNode(preorder[0])\n if len(preorder) == 1:\n return root\n index = postorder.index(preorder[1])\n root.left = self.constructFromPrePost(preorder[1:index+2], postorder[:index+1])\n root.right = self.constructFromPrePost(preorder[index+2:], postorder[index+1:-1])\n return root\n```\n\n**Construct using Preorder and Inorder**\n\n```\nclass Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:\n if not preorder or not inorder:\n return\n \n root = TreeNode(preorder[0])\n mid = inorder.index(preorder[0])\n root.left = self.buildTree(preorder[1: mid+1], inorder[:mid])\n root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:])\n return root\n```\n\n**Construct using Postorder and Inorder**\n\n```\nclass Solution:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:\n if not postorder or not inorder:\n return\n \n root = TreeNode(postorder[-1])\n mid = inorder.index(postorder[-1])\n root.left = self.buildTree(inorder[:mid], postorder[:mid])\n root.right = self.buildTree(inorder[mid+1:], postorder[mid:-1])\n return root\n \n```\n
1
Your friend is typing his `name` into a keyboard. Sometimes, when typing a character `c`, the key might get _long pressed_, and the character will be typed 1 or more times. You examine the `typed` characters of the keyboard. Return `True` if it is possible that it was your friends name, with some characters (possibly none) being long pressed. **Example 1:** **Input:** name = "alex ", typed = "aaleex " **Output:** true **Explanation:** 'a' and 'e' in 'alex' were long pressed. **Example 2:** **Input:** name = "saeed ", typed = "ssaaedd " **Output:** false **Explanation:** 'e' must have been pressed twice, but it was not in the typed output. **Constraints:** * `1 <= name.length, typed.length <= 1000` * `name` and `typed` consist of only lowercase English letters.
null
Beats 95 / 98 % || Simple solution with HashMap + HashSet in Python3 / TypeScript
find-and-replace-pattern
0
1
# Intuition\nLet\'s briefly explain what the problem is:\n- there\'s a list of `words` and `pattern`\n- our goal is to find such words from `words`, that could be replaced by `pattern` and vice-versa\n\nWe\'d like to use **HashMap** to establish **links** between characters from a particular word to `pattern`.\n\n```\n# Ex.1\nword = \'abc\'\npattern = \'def\'\n\n# A word can be replaced by pattern since we match \n# a=>d, b=>e, c=>f.\n\n# Ex.2\nword = \'abc\'\npattern = \'ded\'\n# A word cannot be replaced by pattern since\n# a=>d, b=>e and c !=> d\n``` \n\n# Approach\n1. declare `ans` to store valid words from `words`\n2. declare `cache` to establish links between `words[i]` and `pattern[i]`\n3. declare `matched` as a set of established chars from `pattern`\n4. iterate over `words`\n5. use boolean `isValid` to represent if a word is replacable by `pattern`\n6. check, if link between word and pattern **exists** and continue to move\n7. otherwise check `cache` and `matched` for a word to be **valid**\n8. clear `cache` and `matched` for **each** `words[i]`\n9. return `ans` \n\n# Complexity\n- Time complexity: **O(N * K)**, `N`- size of `words`, `K` - size of `pattern`\n\n- Space complexity: **O(N + K)**\n\n# Code in Python3\n```\nclass Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n ans = []\n cache = dict()\n matched = set()\n \n for word in words:\n isValid = True\n\n for i in range(len(pattern)):\n w, p = word[i], pattern[i]\n\n if w in cache:\n if cache[w] != p:\n isValid = False\n break\n elif p in matched:\n isValid = False\n break\n else: \n cache[w] = p\n matched.add(p)\n\n if isValid: ans.append(word)\n \n cache.clear()\n matched.clear()\n\n return ans\n```\n# Code in TypeScript\n```\nfunction findAndReplacePattern(words, pattern) {\n let ans = [];\n let cache = {};\n let matched = new Set();\n\n for (let word of words) {\n let isValid = true;\n\n for (let i = 0; i < pattern.length; i++) {\n let w = word[i], p = pattern[i];\n\n if (w in cache) {\n if (cache[w] != p) {\n isValid = false;\n break;\n }\n } else if (matched.has(p)) {\n isValid = false;\n break;\n } else {\n cache[w] = p;\n matched.add(p);\n }\n }\n\n if (isValid) ans.push(word);\n\n cache = {};\n matched.clear();\n }\n\n return ans;\n}\n\n```
1
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. **Example 1:** **Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb " **Output:** \[ "mee ", "aqq "\] **Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. **Example 2:** **Input:** words = \[ "a ", "b ", "c "\], pattern = "a " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `1 <= pattern.length <= 20` * `1 <= words.length <= 50` * `words[i].length == pattern.length` * `pattern` and `words[i]` are lowercase English letters.
null
Beats 95 / 98 % || Simple solution with HashMap + HashSet in Python3 / TypeScript
find-and-replace-pattern
0
1
# Intuition\nLet\'s briefly explain what the problem is:\n- there\'s a list of `words` and `pattern`\n- our goal is to find such words from `words`, that could be replaced by `pattern` and vice-versa\n\nWe\'d like to use **HashMap** to establish **links** between characters from a particular word to `pattern`.\n\n```\n# Ex.1\nword = \'abc\'\npattern = \'def\'\n\n# A word can be replaced by pattern since we match \n# a=>d, b=>e, c=>f.\n\n# Ex.2\nword = \'abc\'\npattern = \'ded\'\n# A word cannot be replaced by pattern since\n# a=>d, b=>e and c !=> d\n``` \n\n# Approach\n1. declare `ans` to store valid words from `words`\n2. declare `cache` to establish links between `words[i]` and `pattern[i]`\n3. declare `matched` as a set of established chars from `pattern`\n4. iterate over `words`\n5. use boolean `isValid` to represent if a word is replacable by `pattern`\n6. check, if link between word and pattern **exists** and continue to move\n7. otherwise check `cache` and `matched` for a word to be **valid**\n8. clear `cache` and `matched` for **each** `words[i]`\n9. return `ans` \n\n# Complexity\n- Time complexity: **O(N * K)**, `N`- size of `words`, `K` - size of `pattern`\n\n- Space complexity: **O(N + K)**\n\n# Code in Python3\n```\nclass Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n ans = []\n cache = dict()\n matched = set()\n \n for word in words:\n isValid = True\n\n for i in range(len(pattern)):\n w, p = word[i], pattern[i]\n\n if w in cache:\n if cache[w] != p:\n isValid = False\n break\n elif p in matched:\n isValid = False\n break\n else: \n cache[w] = p\n matched.add(p)\n\n if isValid: ans.append(word)\n \n cache.clear()\n matched.clear()\n\n return ans\n```\n# Code in TypeScript\n```\nfunction findAndReplacePattern(words, pattern) {\n let ans = [];\n let cache = {};\n let matched = new Set();\n\n for (let word of words) {\n let isValid = true;\n\n for (let i = 0; i < pattern.length; i++) {\n let w = word[i], p = pattern[i];\n\n if (w in cache) {\n if (cache[w] != p) {\n isValid = false;\n break;\n }\n } else if (matched.has(p)) {\n isValid = false;\n break;\n } else {\n cache[w] = p;\n matched.add(p);\n }\n }\n\n if (isValid) ans.push(word);\n\n cache = {};\n matched.clear();\n }\n\n return ans;\n}\n\n```
1
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none). You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`. Return _the minimum number of flips to make_ `s` _monotone increasing_. **Example 1:** **Input:** s = "00110 " **Output:** 1 **Explanation:** We flip the last digit to get 00111. **Example 2:** **Input:** s = "010110 " **Output:** 2 **Explanation:** We flip to get 011111, or alternatively 000111. **Example 3:** **Input:** s = "00011000 " **Output:** 2 **Explanation:** We flip to get 00000000. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
null
Solution
find-and-replace-pattern
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> findAndReplacePattern(vector<string>& words, string pattern) {\n vector<string> ans;\n string yash;\n unordered_map<char,char> m;\n int cnt=0;\n for(int i=0;i<pattern.size();i++)\n {\n if(m.find(pattern[i])!=m.end())\n yash.push_back(m[pattern[i]]);\n else\n {\n yash.push_back(\'A\'+cnt);\n m[pattern[i]] = (\'A\'+cnt);\n cnt++;\n } \n }\n for(auto & i : words)\n {\n string temp;\n unordered_map<char,char> m;\n int cnt=0;\n for(int j=0;j<i.size();j++)\n {\n if(m.find(i[j])!=m.end())\n temp.push_back(m[i[j]]);\n else\n {\n temp.push_back(\'A\'+cnt);\n m[i[j]] = (\'A\'+cnt);\n cnt++;\n }\n }\n cout<<temp<<endl;\n if(temp==yash) ans.push_back(i);\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n ans = []\n for i in words:\n mp = {}\n bp = {}\n isPattern = True\n for j in range(len(i)):\n if i[j] not in bp:\n bp[i[j]] = pattern[j]\n else:\n if bp[i[j]] != pattern[j]:\n isPattern = False\n break\n if pattern[j] not in mp:\n mp[pattern[j]] = i[j]\n else:\n if mp[pattern[j]] != i[j]:\n isPattern = False\n break\n if isPattern:\n ans.append(i)\n return ans\n```\n\n```Java []\nclass Solution {\n public List<String> findAndReplacePattern(String[] words, String pattern) {\n List<String> res = new ArrayList<>();\n for (String word : words) {\n if (check(word, pattern)) res.add(word);\n }\n return res;\n }\n boolean check(String a, String b) {\n for (int i = 0; i < a.length(); i++) {\n if (a.indexOf(a.charAt(i)) != b.indexOf(b.charAt(i))) return false;\n }\n return true;\n }\n}\n```\n
1
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. **Example 1:** **Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb " **Output:** \[ "mee ", "aqq "\] **Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. **Example 2:** **Input:** words = \[ "a ", "b ", "c "\], pattern = "a " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `1 <= pattern.length <= 20` * `1 <= words.length <= 50` * `words[i].length == pattern.length` * `pattern` and `words[i]` are lowercase English letters.
null
Solution
find-and-replace-pattern
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> findAndReplacePattern(vector<string>& words, string pattern) {\n vector<string> ans;\n string yash;\n unordered_map<char,char> m;\n int cnt=0;\n for(int i=0;i<pattern.size();i++)\n {\n if(m.find(pattern[i])!=m.end())\n yash.push_back(m[pattern[i]]);\n else\n {\n yash.push_back(\'A\'+cnt);\n m[pattern[i]] = (\'A\'+cnt);\n cnt++;\n } \n }\n for(auto & i : words)\n {\n string temp;\n unordered_map<char,char> m;\n int cnt=0;\n for(int j=0;j<i.size();j++)\n {\n if(m.find(i[j])!=m.end())\n temp.push_back(m[i[j]]);\n else\n {\n temp.push_back(\'A\'+cnt);\n m[i[j]] = (\'A\'+cnt);\n cnt++;\n }\n }\n cout<<temp<<endl;\n if(temp==yash) ans.push_back(i);\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n ans = []\n for i in words:\n mp = {}\n bp = {}\n isPattern = True\n for j in range(len(i)):\n if i[j] not in bp:\n bp[i[j]] = pattern[j]\n else:\n if bp[i[j]] != pattern[j]:\n isPattern = False\n break\n if pattern[j] not in mp:\n mp[pattern[j]] = i[j]\n else:\n if mp[pattern[j]] != i[j]:\n isPattern = False\n break\n if isPattern:\n ans.append(i)\n return ans\n```\n\n```Java []\nclass Solution {\n public List<String> findAndReplacePattern(String[] words, String pattern) {\n List<String> res = new ArrayList<>();\n for (String word : words) {\n if (check(word, pattern)) res.add(word);\n }\n return res;\n }\n boolean check(String a, String b) {\n for (int i = 0; i < a.length(); i++) {\n if (a.indexOf(a.charAt(i)) != b.indexOf(b.charAt(i))) return false;\n }\n return true;\n }\n}\n```\n
1
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none). You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`. Return _the minimum number of flips to make_ `s` _monotone increasing_. **Example 1:** **Input:** s = "00110 " **Output:** 1 **Explanation:** We flip the last digit to get 00111. **Example 2:** **Input:** s = "010110 " **Output:** 2 **Explanation:** We flip to get 011111, or alternatively 000111. **Example 3:** **Input:** s = "00011000 " **Output:** 2 **Explanation:** We flip to get 00000000. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
null
Python | Easy Solution✅
find-and-replace-pattern
0
1
```\ndef findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n # words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb \n output = []\n new_pattern = self.create_new_pattern(pattern)\n for word in words:\n current_pattern = self.create_new_pattern(word)\n if new_pattern == current_pattern:\n output.append(word)\n return output\n \n def create_new_pattern(self, word): # word = "abb", word = "mee"\n current_alpha = "a"\n seen = {}\n new_pattern = ""\n for letter in word:\n if letter not in seen:\n seen[letter] = current_alpha # when word ="abb" seen = {\'a\': \'a\', \'b\': \'b\'}, when word ="mee" seen = {\'m\': \'a\', \'e\': \'b\'} \n current_alpha = chr(ord(current_alpha)+1)\n new_pattern += seen[letter] # when word ="abb" new_pattern = "abb", when word ="abb" new_pattern = "abb"\n return new_pattern\n```
4
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. **Example 1:** **Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb " **Output:** \[ "mee ", "aqq "\] **Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. **Example 2:** **Input:** words = \[ "a ", "b ", "c "\], pattern = "a " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `1 <= pattern.length <= 20` * `1 <= words.length <= 50` * `words[i].length == pattern.length` * `pattern` and `words[i]` are lowercase English letters.
null
Python | Easy Solution✅
find-and-replace-pattern
0
1
```\ndef findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n # words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb \n output = []\n new_pattern = self.create_new_pattern(pattern)\n for word in words:\n current_pattern = self.create_new_pattern(word)\n if new_pattern == current_pattern:\n output.append(word)\n return output\n \n def create_new_pattern(self, word): # word = "abb", word = "mee"\n current_alpha = "a"\n seen = {}\n new_pattern = ""\n for letter in word:\n if letter not in seen:\n seen[letter] = current_alpha # when word ="abb" seen = {\'a\': \'a\', \'b\': \'b\'}, when word ="mee" seen = {\'m\': \'a\', \'e\': \'b\'} \n current_alpha = chr(ord(current_alpha)+1)\n new_pattern += seen[letter] # when word ="abb" new_pattern = "abb", when word ="abb" new_pattern = "abb"\n return new_pattern\n```
4
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none). You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`. Return _the minimum number of flips to make_ `s` _monotone increasing_. **Example 1:** **Input:** s = "00110 " **Output:** 1 **Explanation:** We flip the last digit to get 00111. **Example 2:** **Input:** s = "010110 " **Output:** 2 **Explanation:** We flip to get 011111, or alternatively 000111. **Example 3:** **Input:** s = "00011000 " **Output:** 2 **Explanation:** We flip to get 00000000. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
null
Python3 Solution using Simple approach
find-and-replace-pattern
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 findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n d = dict()\n temp = []\n s = "1"\n flg = ""\n for i in range(len(pattern)):\n if pattern[i] not in d:\n d[pattern[i]]=s\n s = chr(ord(s)+1)\n flg+=d[pattern[i]]\n for i in d.keys():\n temp.append(d[i])\n res = []\n d2 = []\n for i in words:\n d1 = dict()\n s = "1"\n flag = ""\n for j in i:\n if j not in d1:\n d1[j]=s\n s = chr(ord(s)+1)\n flag+=d1[j]\n d2.append(flag)\n for i in range(len(d2)):\n if d2[i] == flg:\n res.append(words[i])\n \n return res\n\n```
1
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. **Example 1:** **Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb " **Output:** \[ "mee ", "aqq "\] **Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. **Example 2:** **Input:** words = \[ "a ", "b ", "c "\], pattern = "a " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `1 <= pattern.length <= 20` * `1 <= words.length <= 50` * `words[i].length == pattern.length` * `pattern` and `words[i]` are lowercase English letters.
null
Python3 Solution using Simple approach
find-and-replace-pattern
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 findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n d = dict()\n temp = []\n s = "1"\n flg = ""\n for i in range(len(pattern)):\n if pattern[i] not in d:\n d[pattern[i]]=s\n s = chr(ord(s)+1)\n flg+=d[pattern[i]]\n for i in d.keys():\n temp.append(d[i])\n res = []\n d2 = []\n for i in words:\n d1 = dict()\n s = "1"\n flag = ""\n for j in i:\n if j not in d1:\n d1[j]=s\n s = chr(ord(s)+1)\n flag+=d1[j]\n d2.append(flag)\n for i in range(len(d2)):\n if d2[i] == flg:\n res.append(words[i])\n \n return res\n\n```
1
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none). You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`. Return _the minimum number of flips to make_ `s` _monotone increasing_. **Example 1:** **Input:** s = "00110 " **Output:** 1 **Explanation:** We flip the last digit to get 00111. **Example 2:** **Input:** s = "010110 " **Output:** 2 **Explanation:** We flip to get 011111, or alternatively 000111. **Example 3:** **Input:** s = "00011000 " **Output:** 2 **Explanation:** We flip to get 00000000. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
null
Python one-line solution
find-and-replace-pattern
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nList comprehension\n\n# Code\n```\nclass Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n return (word for word in words if len(set(word)) == len(set(pattern)) == len(set(zip(word, pattern))))\n```
1
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word. Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. **Example 1:** **Input:** words = \[ "abc ", "deq ", "mee ", "aqq ", "dkd ", "ccc "\], pattern = "abb " **Output:** \[ "mee ", "aqq "\] **Explanation:** "mee " matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc " does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. **Example 2:** **Input:** words = \[ "a ", "b ", "c "\], pattern = "a " **Output:** \[ "a ", "b ", "c "\] **Constraints:** * `1 <= pattern.length <= 20` * `1 <= words.length <= 50` * `words[i].length == pattern.length` * `pattern` and `words[i]` are lowercase English letters.
null
Python one-line solution
find-and-replace-pattern
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nList comprehension\n\n# Code\n```\nclass Solution:\n def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:\n return (word for word in words if len(set(word)) == len(set(pattern)) == len(set(zip(word, pattern))))\n```
1
A binary string is monotone increasing if it consists of some number of `0`'s (possibly none), followed by some number of `1`'s (also possibly none). You are given a binary string `s`. You can flip `s[i]` changing it from `0` to `1` or from `1` to `0`. Return _the minimum number of flips to make_ `s` _monotone increasing_. **Example 1:** **Input:** s = "00110 " **Output:** 1 **Explanation:** We flip the last digit to get 00111. **Example 2:** **Input:** s = "010110 " **Output:** 2 **Explanation:** We flip to get 011111, or alternatively 000111. **Example 3:** **Input:** s = "00011000 " **Output:** 2 **Explanation:** We flip to get 00000000. **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
null
Solution
sum-of-subsequence-widths
1
1
```C++ []\nconst long M=1e9+7;\nclass Solution {\npublic:\n int sumSubseqWidths(vector<int>& nums) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n long sum=0, cnt=1;\n int n=nums.size();\n sort(nums.begin(), nums.end());\n for(int i=0, j=n-1; i<n; sum=(sum+(nums[i++]-nums[j--])*cnt)%M, cnt=cnt*2%M) {}\n return sum;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n mod = 10**9 + 7\n nums.sort()\n ans, pow2 = 0, 1\n for x, y in zip(nums, reversed(nums)):\n ans += (x - y) * pow2\n pow2 = pow2 * 2 % mod\n return ans % mod\n```\n\n```Java []\nclass Solution {\n\tpublic int sumSubseqWidths(int[] nums) {\n\t\tArrays.sort(nums);\n\t\tlong c = 1;\n\t\tlong result = 0;\n\t\tlong mod = 1000000007L;\n\t\tfor (int i = 0, j = nums.length - 1; i < nums.length; i++, j--) {\n\t\t\tresult = (result + (nums[i] * c) - (nums[j] * c)) % mod;\n\t\t\tc = (c * 2) % mod;\n\t\t}\n\t\treturn (int) ((result + mod) % mod);\n\t}\n}\n```\n
1
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 6 Explanation: The subsequences are \[1\], \[2\], \[3\], \[2,1\], \[2,3\], \[1,3\], \[2,1,3\]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. **Example 2:** **Input:** nums = \[2\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
Solution
sum-of-subsequence-widths
1
1
```C++ []\nconst long M=1e9+7;\nclass Solution {\npublic:\n int sumSubseqWidths(vector<int>& nums) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n long sum=0, cnt=1;\n int n=nums.size();\n sort(nums.begin(), nums.end());\n for(int i=0, j=n-1; i<n; sum=(sum+(nums[i++]-nums[j--])*cnt)%M, cnt=cnt*2%M) {}\n return sum;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n mod = 10**9 + 7\n nums.sort()\n ans, pow2 = 0, 1\n for x, y in zip(nums, reversed(nums)):\n ans += (x - y) * pow2\n pow2 = pow2 * 2 % mod\n return ans % mod\n```\n\n```Java []\nclass Solution {\n\tpublic int sumSubseqWidths(int[] nums) {\n\t\tArrays.sort(nums);\n\t\tlong c = 1;\n\t\tlong result = 0;\n\t\tlong mod = 1000000007L;\n\t\tfor (int i = 0, j = nums.length - 1; i < nums.length; i++, j--) {\n\t\t\tresult = (result + (nums[i] * c) - (nums[j] * c)) % mod;\n\t\t\tc = (c * 2) % mod;\n\t\t}\n\t\treturn (int) ((result + mod) % mod);\n\t}\n}\n```\n
1
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
Easiest Solution
sum-of-subsequence-widths
1
1
\n\n# Code\n```java []\nclass Solution {\n long MOD=1000000007;\n public int sumSubseqWidths(int[] nums) {\n int i=0;\n int j=nums.length-1;\n long multi=1;\n long width=0;\n Arrays.sort(nums);\n while(i<nums.length&&j>=0){\n width=(width+nums[i]*multi-nums[j]*multi)%MOD;\n multi=(multi*2)%MOD;\n i++;\n j--;\n }\n return (int)width;\n }\n}\n```\n```c++ []\nclass Solution {\nprivate:\n int mod = 1e9 + 7;\n int power(long long a,long long b){\n long long res = 1;\n while(b){\n if(b&1) res = (res * a) % mod;\n b = b >> 1;\n a = (a * a) % mod;\n }\n return res;\n }\npublic:\n int sumSubseqWidths(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(),nums.end());\n vector<long long> suffix(n);\n for(int i=0,weight=1;i<n;i++){\n suffix[i] = (weight*1LL*nums[i]) % mod;\n weight = (weight * 2LL) % mod;\n }\n\n for(int i=n-2;i>=0;i--) suffix[i] = (suffix[i] + suffix[i+1]) % mod;\n \n long long expanse = 0LL;\n for(int i=0;i<n-1;i++){\n long long diff = ( (suffix[i+1]%mod) * power(power(2,i+1),mod-2)%mod) % mod - (nums[i]*1LL*(power(2,n-i-1)-1)%mod);\n expanse = (expanse + diff + mod) % mod;\n }\n return expanse;\n }\n};\n```\n```python3 []\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n MOD = 1_000_000_007\n nums.sort()\n ans = val = 0 \n p = 1\n for i in range(1, len(nums)): \n p = p * 2 % MOD\n val = (2*val + (nums[i]-nums[i-1])*(p-1)) % MOD \n ans = (ans + val) % MOD \n return ans \n```
0
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 6 Explanation: The subsequences are \[1\], \[2\], \[3\], \[2,1\], \[2,3\], \[1,3\], \[2,1,3\]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. **Example 2:** **Input:** nums = \[2\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
Easiest Solution
sum-of-subsequence-widths
1
1
\n\n# Code\n```java []\nclass Solution {\n long MOD=1000000007;\n public int sumSubseqWidths(int[] nums) {\n int i=0;\n int j=nums.length-1;\n long multi=1;\n long width=0;\n Arrays.sort(nums);\n while(i<nums.length&&j>=0){\n width=(width+nums[i]*multi-nums[j]*multi)%MOD;\n multi=(multi*2)%MOD;\n i++;\n j--;\n }\n return (int)width;\n }\n}\n```\n```c++ []\nclass Solution {\nprivate:\n int mod = 1e9 + 7;\n int power(long long a,long long b){\n long long res = 1;\n while(b){\n if(b&1) res = (res * a) % mod;\n b = b >> 1;\n a = (a * a) % mod;\n }\n return res;\n }\npublic:\n int sumSubseqWidths(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(),nums.end());\n vector<long long> suffix(n);\n for(int i=0,weight=1;i<n;i++){\n suffix[i] = (weight*1LL*nums[i]) % mod;\n weight = (weight * 2LL) % mod;\n }\n\n for(int i=n-2;i>=0;i--) suffix[i] = (suffix[i] + suffix[i+1]) % mod;\n \n long long expanse = 0LL;\n for(int i=0;i<n-1;i++){\n long long diff = ( (suffix[i+1]%mod) * power(power(2,i+1),mod-2)%mod) % mod - (nums[i]*1LL*(power(2,n-i-1)-1)%mod);\n expanse = (expanse + diff + mod) % mod;\n }\n return expanse;\n }\n};\n```\n```python3 []\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n MOD = 1_000_000_007\n nums.sort()\n ans = val = 0 \n p = 1\n for i in range(1, len(nums)): \n p = p * 2 % MOD\n val = (2*val + (nums[i]-nums[i-1])*(p-1)) % MOD \n ans = (ans + val) % MOD \n return ans \n```
0
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
Python Solution, Less than 10 Lines, Faster than 95%
sum-of-subsequence-widths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe input size is large so we find an approach that accumulates the answer at the position `i` with the information from the position `i-1`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort `nums` and compute the answer from the smallest to the largest. \nAt `i` (`nums[0] < nums[1] < ... < nums[i]`), we define $$A_i$$ as the sum of widths of all the subsequences of `nums[0:i]` that ends at `i`. \n\n$$A_i = \\sum_{j=0}^{i-1}\\left( A_j + 2^j (\\textrm{nums}[i] - \\textrm{nums}[j])\\right) = A_{i-1} + \\delta_i$$\n\nwhere $$\\delta_i = \\sum_{j=0}^{i-1}2^j (\\textrm{nums}[i] - \\textrm{nums}[j])$$ that be defined in a recursive way as follows: \n\n$$ \\delta_i = \\delta_{i-1} + \\sum_{k=0}^{i-1}2^k (\\textrm{nums}[i] - \\textrm{nums}[i-1]) $$\n\nIn this way, we can maintain $$A_i$$ and $$\\delta_i$$ iteractively and obtain the final solution in linear time. \n\n# Complexity\n- Time complexity: $$O(n \\log n)$$ for sorting\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: Only $$O(1)$$ extra memory\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n nums.sort()\n ans = delta = 0\n accu_k = k = 1\n for u, v in zip(nums, nums[1:]):\n delta = (delta + accu_k * (v - u)) % 1000000007 \n ans = (ans + ans + delta) % 1000000007\n k = (k * 2) % 1000000007\n accu_k = (accu_k + k) % 1000000007\n return ans\n```
0
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 6 Explanation: The subsequences are \[1\], \[2\], \[3\], \[2,1\], \[2,3\], \[1,3\], \[2,1,3\]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. **Example 2:** **Input:** nums = \[2\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
Python Solution, Less than 10 Lines, Faster than 95%
sum-of-subsequence-widths
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe input size is large so we find an approach that accumulates the answer at the position `i` with the information from the position `i-1`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort `nums` and compute the answer from the smallest to the largest. \nAt `i` (`nums[0] < nums[1] < ... < nums[i]`), we define $$A_i$$ as the sum of widths of all the subsequences of `nums[0:i]` that ends at `i`. \n\n$$A_i = \\sum_{j=0}^{i-1}\\left( A_j + 2^j (\\textrm{nums}[i] - \\textrm{nums}[j])\\right) = A_{i-1} + \\delta_i$$\n\nwhere $$\\delta_i = \\sum_{j=0}^{i-1}2^j (\\textrm{nums}[i] - \\textrm{nums}[j])$$ that be defined in a recursive way as follows: \n\n$$ \\delta_i = \\delta_{i-1} + \\sum_{k=0}^{i-1}2^k (\\textrm{nums}[i] - \\textrm{nums}[i-1]) $$\n\nIn this way, we can maintain $$A_i$$ and $$\\delta_i$$ iteractively and obtain the final solution in linear time. \n\n# Complexity\n- Time complexity: $$O(n \\log n)$$ for sorting\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: Only $$O(1)$$ extra memory\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n nums.sort()\n ans = delta = 0\n accu_k = k = 1\n for u, v in zip(nums, nums[1:]):\n delta = (delta + accu_k * (v - u)) % 1000000007 \n ans = (ans + ans + delta) % 1000000007\n k = (k * 2) % 1000000007\n accu_k = (accu_k + k) % 1000000007\n return ans\n```
0
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
DP
sum-of-subsequence-widths
0
1
\n# Code\n```\nfrom typing import List\n\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n mod = 10**9 + 7\n\n # Calculate powers of 2 modulo mod\n powers_of_2 = [1]\n for i in range(1, n):\n powers_of_2.append((powers_of_2[-1] * 2) % mod)\n\n # Calculate the sum of widths\n ans = 0\n for i in range(n):\n ans = (ans + nums[i] * (powers_of_2[i] - powers_of_2[n-i-1])) % mod\n\n return ans\n```
0
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 6 Explanation: The subsequences are \[1\], \[2\], \[3\], \[2,1\], \[2,3\], \[1,3\], \[2,1,3\]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. **Example 2:** **Input:** nums = \[2\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
DP
sum-of-subsequence-widths
0
1
\n# Code\n```\nfrom typing import List\n\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n mod = 10**9 + 7\n\n # Calculate powers of 2 modulo mod\n powers_of_2 = [1]\n for i in range(1, n):\n powers_of_2.append((powers_of_2[-1] * 2) % mod)\n\n # Calculate the sum of widths\n ans = 0\n for i in range(n):\n ans = (ans + nums[i] * (powers_of_2[i] - powers_of_2[n-i-1])) % mod\n\n return ans\n```
0
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
Easy solution in python
sum-of-subsequence-widths
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\nPhase-1-> ans=0+(1-3)*1\n ans=-2%kmod\n exp=1*2%kmod\nPhase-2-> ans=(-2)+(2-2)*2\n ans=-2%kmod\n exp=2*2%kmod\nPhase-3-> ans=(-2)+(3-1)*4\n ans=6%kmod\n exp=4*2%kmod \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 sumSubseqWidths(self, nums: List[int]) -> int:\n kMod = 10**9+7\n n = len(nums)\n ans = 0\n exp = 1\n nums.sort()\n for i in range(n):\n ans += (nums[i] - nums[n - i - 1]) * exp\n ans %= kMod\n exp = exp * 2 % kMod\n return ans\n\n\n # pass only 19 test cases occer TLE problem\n result = [[]]\n for i in nums:\n n = len(result)\n for j in range(n):\n r = result[j] + [i]\n result.append(r) \n s=[]\n for i in result[1:]:\n a=max(i)\n b=min(i)\n s.append(a-b)\n return sum(s)\n```
0
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 6 Explanation: The subsequences are \[1\], \[2\], \[3\], \[2,1\], \[2,3\], \[1,3\], \[2,1,3\]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. **Example 2:** **Input:** nums = \[2\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
Easy solution in python
sum-of-subsequence-widths
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\nPhase-1-> ans=0+(1-3)*1\n ans=-2%kmod\n exp=1*2%kmod\nPhase-2-> ans=(-2)+(2-2)*2\n ans=-2%kmod\n exp=2*2%kmod\nPhase-3-> ans=(-2)+(3-1)*4\n ans=6%kmod\n exp=4*2%kmod \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 sumSubseqWidths(self, nums: List[int]) -> int:\n kMod = 10**9+7\n n = len(nums)\n ans = 0\n exp = 1\n nums.sort()\n for i in range(n):\n ans += (nums[i] - nums[n - i - 1]) * exp\n ans %= kMod\n exp = exp * 2 % kMod\n return ans\n\n\n # pass only 19 test cases occer TLE problem\n result = [[]]\n for i in nums:\n n = len(result)\n for j in range(n):\n r = result[j] + [i]\n result.append(r) \n s=[]\n for i in result[1:]:\n a=max(i)\n b=min(i)\n s.append(a-b)\n return sum(s)\n```
0
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
O(MAX) Time Complexity | Counting Sort | Python
sum-of-subsequence-widths
0
1
Since the range of numbers are small, we can sort number in ```O(n)``` time complexity with counting sort.\n\n# Code\n```\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n mod = int(1e9 + 7)\n mx = max(nums)\n cnt = [0] * (mx + 1)\n for num in nums:\n cnt[num] += 1\n \n smaller = [0] + list(accumulate(cnt))\n greater = list(accumulate(cnt[::-1]))[::-1] + [0]\n\n ans = 0\n nums = set(nums)\n for num in nums:\n ans += (pow(2, smaller[num], mod) - pow(2, greater[num + 1], mod)) * (pow(2, cnt[num], mod) - 1) * num\n ans %= mod\n return ans\n\n```
0
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 6 Explanation: The subsequences are \[1\], \[2\], \[3\], \[2,1\], \[2,3\], \[1,3\], \[2,1,3\]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. **Example 2:** **Input:** nums = \[2\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
O(MAX) Time Complexity | Counting Sort | Python
sum-of-subsequence-widths
0
1
Since the range of numbers are small, we can sort number in ```O(n)``` time complexity with counting sort.\n\n# Code\n```\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n mod = int(1e9 + 7)\n mx = max(nums)\n cnt = [0] * (mx + 1)\n for num in nums:\n cnt[num] += 1\n \n smaller = [0] + list(accumulate(cnt))\n greater = list(accumulate(cnt[::-1]))[::-1] + [0]\n\n ans = 0\n nums = set(nums)\n for num in nums:\n ans += (pow(2, smaller[num], mod) - pow(2, greater[num + 1], mod)) * (pow(2, cnt[num], mod) - 1) * num\n ans %= mod\n return ans\n\n```
0
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
python3 Solution
sum-of-subsequence-widths
0
1
\n```\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n MOD = 10**9+7\n ans = 0 \n for i, x in enumerate(sorted(nums)): \n ans += x * (pow(2, i, MOD) - pow(2, len(nums)-i-1, MOD))\n return ans % MOD\n```
0
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 6 Explanation: The subsequences are \[1\], \[2\], \[3\], \[2,1\], \[2,3\], \[1,3\], \[2,1,3\]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. **Example 2:** **Input:** nums = \[2\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
python3 Solution
sum-of-subsequence-widths
0
1
\n```\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n MOD = 10**9+7\n ans = 0 \n for i, x in enumerate(sorted(nums)): \n ans += x * (pow(2, i, MOD) - pow(2, len(nums)-i-1, MOD))\n return ans % MOD\n```
0
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
MATH + DP
sum-of-subsequence-widths
0
1
# Code\n```\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n MOD = 10**9 + 7\n n = len(nums)\n nums.sort()\n\n dp = [0] * n\n\n p = 2\n temp = nums[0]\n\n for i in range(1, n):\n dp[i] = ((dp[i-1] + ((p-1)*nums[i])%MOD)%MOD - temp)%MOD\n p = (2*p)%MOD\n temp = ((2*temp)%MOD + nums[i])%MOD\n \n return dp[n-1]\n```
0
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, `[3,6,2,7]` is a subsequence of the array `[0,3,1,6,2,2,7]`. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 6 Explanation: The subsequences are \[1\], \[2\], \[3\], \[2,1\], \[2,3\], \[1,3\], \[2,1,3\]. The corresponding widths are 0, 0, 0, 1, 1, 2, 2. The sum of these widths is 6. **Example 2:** **Input:** nums = \[2\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105`
null
MATH + DP
sum-of-subsequence-widths
0
1
# Code\n```\nclass Solution:\n def sumSubseqWidths(self, nums: List[int]) -> int:\n MOD = 10**9 + 7\n n = len(nums)\n nums.sort()\n\n dp = [0] * n\n\n p = 2\n temp = nums[0]\n\n for i in range(1, n):\n dp[i] = ((dp[i-1] + ((p-1)*nums[i])%MOD)%MOD - temp)%MOD\n p = (2*p)%MOD\n temp = ((2*temp)%MOD + nums[i])%MOD\n \n return dp[n-1]\n```
0
You are given an array `arr` which consists of only zeros and ones, divide the array into **three non-empty parts** such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros **are allowed**, so `[0,1,1]` and `[1,1]` represent the same value. **Example 1:** **Input:** arr = \[1,0,1,0,1\] **Output:** \[0,3\] **Example 2:** **Input:** arr = \[1,1,0,1,1\] **Output:** \[-1,-1\] **Example 3:** **Input:** arr = \[1,1,0,0,1\] **Output:** \[0,2\] **Constraints:** * `3 <= arr.length <= 3 * 104` * `arr[i]` is `0` or `1`
null
Simple Python explained
surface-area-of-3d-shapes
0
1
```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n \n l = len(grid)\n area=0\n for row in range(l):\n for col in range(l):\n if grid[row][col]:\n area += (grid[row][col]*4) +2 #surface area of each block if blocks werent connected\n if row: #row>0\n area -= min(grid[row][col],grid[row-1][col])*2 #subtracting as area is common among two blocks\n if col: #col>0\n area -= min(grid[row][col],grid[row][col-1])*2 #subtracting as area is common among two blocks\n return area\n```
6
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the total surface area of the resulting shapes_. **Note:** The bottom face of each shape counts toward its surface area. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 34 **Example 2:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 32 **Example 3:** **Input:** grid = \[\[2,2,2\],\[2,1,2\],\[2,2,2\]\] **Output:** 46 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Simple Python explained
surface-area-of-3d-shapes
0
1
```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n \n l = len(grid)\n area=0\n for row in range(l):\n for col in range(l):\n if grid[row][col]:\n area += (grid[row][col]*4) +2 #surface area of each block if blocks werent connected\n if row: #row>0\n area -= min(grid[row][col],grid[row-1][col])*2 #subtracting as area is common among two blocks\n if col: #col>0\n area -= min(grid[row][col],grid[row][col-1])*2 #subtracting as area is common among two blocks\n return area\n```
6
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\] **Output:** 1 **Example 3:** **Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length < n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Beatiful Python Solution
surface-area-of-3d-shapes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity : O(n^2) \n- => n is the length or grid[i].length\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 surfaceArea(self, grid) -> int :\n length = len(grid)\n\n def behind(point) :\n array = []\n i , j = point\n # top : \n if length > i > 0 : array.append(min((grid[i-1][j],grid[i][j])))\n # left :\n if j < length-1 : array.append(min((grid[i][j+1] , grid[i][j])))\n # bottom :\n if i < length-1 : array.append(min((grid[i+1][j] , grid[i][j])))\n # right :\n if length > j > 0 : array.append(min((grid[i][j-1],grid[i][j])))\n\n return array\n \n def tower_surface(height) : return height*6-(height-1)*2 if height > 0 else 0\n\n surface = 0\n \n for i in range(length) :\n for j in range(length) :\n surface += tower_surface(grid[i][j]) - sum(behind((i,j)))\n\n return surface\n```
1
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the total surface area of the resulting shapes_. **Note:** The bottom face of each shape counts toward its surface area. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 34 **Example 2:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 32 **Example 3:** **Input:** grid = \[\[2,2,2\],\[2,1,2\],\[2,2,2\]\] **Output:** 46 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Beatiful Python Solution
surface-area-of-3d-shapes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity : O(n^2) \n- => n is the length or grid[i].length\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 surfaceArea(self, grid) -> int :\n length = len(grid)\n\n def behind(point) :\n array = []\n i , j = point\n # top : \n if length > i > 0 : array.append(min((grid[i-1][j],grid[i][j])))\n # left :\n if j < length-1 : array.append(min((grid[i][j+1] , grid[i][j])))\n # bottom :\n if i < length-1 : array.append(min((grid[i+1][j] , grid[i][j])))\n # right :\n if length > j > 0 : array.append(min((grid[i][j-1],grid[i][j])))\n\n return array\n \n def tower_surface(height) : return height*6-(height-1)*2 if height > 0 else 0\n\n surface = 0\n \n for i in range(length) :\n for j in range(length) :\n surface += tower_surface(grid[i][j]) - sum(behind((i,j)))\n\n return surface\n```
1
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\] **Output:** 1 **Example 3:** **Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length < n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Solution
surface-area-of-3d-shapes
1
1
```C++ []\nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int area = 0, n = grid.size();\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++) {\n int v = grid[i][j];\n if (v) {\n area += 2;\n if (j == 0) area += v;\n else if (v > grid[i][j - 1]) area += v - grid[i][j - 1];\n if (i == 0) area += v;\n else if (v > grid[i - 1][j]) area += v - grid[i - 1][j];\n if (j + 1 == n) area += v;\n else if (v > grid[i][j + 1]) area += v - grid[i][j + 1];\n if (i + 1 == n) area += v;\n else if (v > grid[i + 1][j]) area += v - grid[i + 1][j];\n }\n }\n return area;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n n = len(grid)\n res = 0\n for i in range(n):\n rh = 0\n ch = 0\n for j in range(n):\n t = grid[i][j]\n res += 2 if t else 0\n res += abs(t - rh)\n rh = t\n t = grid[j][i]\n res += abs(t - ch)\n ch = t\n res += rh + ch\n return res\n```\n\n```Java []\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int area = 0;\n int n = grid.length;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n area += grid[i][j] > 0 ? 4 * grid[i][j] + 2 : 0;\n }\n }\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n - 1; j++) {\n area -= 2 * Math.min(grid[i][j], grid[i][j + 1]);\n }\n }\n for (int j = 0; j < n; j++) {\n for (int i = 0; i < n - 1; i++) {\n area -= 2 * Math.min(grid[i][j], grid[i + 1][j]);\n }\n }\n return area;\n }\n}\n```\n
1
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the total surface area of the resulting shapes_. **Note:** The bottom face of each shape counts toward its surface area. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 34 **Example 2:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 32 **Example 3:** **Input:** grid = \[\[2,2,2\],\[2,1,2\],\[2,2,2\]\] **Output:** 46 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Solution
surface-area-of-3d-shapes
1
1
```C++ []\nclass Solution {\npublic:\n int surfaceArea(vector<vector<int>>& grid) {\n int area = 0, n = grid.size();\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++) {\n int v = grid[i][j];\n if (v) {\n area += 2;\n if (j == 0) area += v;\n else if (v > grid[i][j - 1]) area += v - grid[i][j - 1];\n if (i == 0) area += v;\n else if (v > grid[i - 1][j]) area += v - grid[i - 1][j];\n if (j + 1 == n) area += v;\n else if (v > grid[i][j + 1]) area += v - grid[i][j + 1];\n if (i + 1 == n) area += v;\n else if (v > grid[i + 1][j]) area += v - grid[i + 1][j];\n }\n }\n return area;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n n = len(grid)\n res = 0\n for i in range(n):\n rh = 0\n ch = 0\n for j in range(n):\n t = grid[i][j]\n res += 2 if t else 0\n res += abs(t - rh)\n rh = t\n t = grid[j][i]\n res += abs(t - ch)\n ch = t\n res += rh + ch\n return res\n```\n\n```Java []\nclass Solution {\n public int surfaceArea(int[][] grid) {\n int area = 0;\n int n = grid.length;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n; j++) {\n area += grid[i][j] > 0 ? 4 * grid[i][j] + 2 : 0;\n }\n }\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < n - 1; j++) {\n area -= 2 * Math.min(grid[i][j], grid[i][j + 1]);\n }\n }\n for (int j = 0; j < n; j++) {\n for (int i = 0; i < n - 1; i++) {\n area -= 2 * Math.min(grid[i][j], grid[i + 1][j]);\n }\n }\n return area;\n }\n}\n```\n
1
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\] **Output:** 1 **Example 3:** **Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length < n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Beats 94% in space! - Python
surface-area-of-3d-shapes
0
1
# Code\n```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n A, s = 0, 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] > 0:\n s += 1\n B = 5 * grid[i][j] - (grid[i][j] - 1)\n A += B\n if not i and not j:\n A = A\n elif i>0 and j>0:\n A -= 2*min(grid[i][j], grid[i][j-1]) + 2*min(grid[i-1][j], grid[i][j])\n elif not i and j > 0:\n A -= 2*min(grid[i][j], grid[i][j-1])\n else:\n A -= 2*min(grid[i][j], grid[i-1][j])\n return A + s\n```\n![surface3D.png](https://assets.leetcode.com/users/images/b0434d79-cd37-4470-905d-add19daeb082_1699707410.5287616.png)
0
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the total surface area of the resulting shapes_. **Note:** The bottom face of each shape counts toward its surface area. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 34 **Example 2:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 32 **Example 3:** **Input:** grid = \[\[2,2,2\],\[2,1,2\],\[2,2,2\]\] **Output:** 46 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Beats 94% in space! - Python
surface-area-of-3d-shapes
0
1
# Code\n```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n A, s = 0, 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] > 0:\n s += 1\n B = 5 * grid[i][j] - (grid[i][j] - 1)\n A += B\n if not i and not j:\n A = A\n elif i>0 and j>0:\n A -= 2*min(grid[i][j], grid[i][j-1]) + 2*min(grid[i-1][j], grid[i][j])\n elif not i and j > 0:\n A -= 2*min(grid[i][j], grid[i][j-1])\n else:\n A -= 2*min(grid[i][j], grid[i-1][j])\n return A + s\n```\n![surface3D.png](https://assets.leetcode.com/users/images/b0434d79-cd37-4470-905d-add19daeb082_1699707410.5287616.png)
0
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\] **Output:** 1 **Example 3:** **Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length < n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Simple python code with explanation
surface-area-of-3d-shapes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncalculating surface area for each cell and adding them up.\n# Complexity\n- Time complexity:O(n^2)\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 surfaceArea(self, grid: List[List[int]]) -> int:\n count = 0\n for i in range(len(grid)):\n for j in range(len(grid)):\n count += self.eachcell(i,j,grid)\n return count\n def eachcell(self,i,j,grid): \n count = 0\n #do four directions:\n #left:j-1\n if j-1 < 0:\n count += grid[i][j]\n elif grid[i][j-1] < grid[i][j]:\n count += (grid[i][j] - grid[i][j-1])\n #right:j+1\n if j + 1 > len(grid)-1:\n count += grid[i][j]\n elif grid[i][j+1] < grid[i][j]:\n count += (grid[i][j] - grid[i][j+1])\n #up:i-1\n if i-1 < 0:\n count += grid[i][j]\n \n elif grid[i-1][j] < grid[i][j]:\n count += (grid[i][j] - grid[i-1][j])\n #down:i+1 \n if i+1 > len(grid)-1:\n count += grid[i][j]\n elif grid[i+1][j] < grid[i][j]:\n count += (grid[i][j] - grid[i+1][j])\n if grid[i][j] > 0:\n count +=2\n return count\n```
0
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the total surface area of the resulting shapes_. **Note:** The bottom face of each shape counts toward its surface area. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 34 **Example 2:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 32 **Example 3:** **Input:** grid = \[\[2,2,2\],\[2,1,2\],\[2,2,2\]\] **Output:** 46 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Simple python code with explanation
surface-area-of-3d-shapes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncalculating surface area for each cell and adding them up.\n# Complexity\n- Time complexity:O(n^2)\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 surfaceArea(self, grid: List[List[int]]) -> int:\n count = 0\n for i in range(len(grid)):\n for j in range(len(grid)):\n count += self.eachcell(i,j,grid)\n return count\n def eachcell(self,i,j,grid): \n count = 0\n #do four directions:\n #left:j-1\n if j-1 < 0:\n count += grid[i][j]\n elif grid[i][j-1] < grid[i][j]:\n count += (grid[i][j] - grid[i][j-1])\n #right:j+1\n if j + 1 > len(grid)-1:\n count += grid[i][j]\n elif grid[i][j+1] < grid[i][j]:\n count += (grid[i][j] - grid[i][j+1])\n #up:i-1\n if i-1 < 0:\n count += grid[i][j]\n \n elif grid[i-1][j] < grid[i][j]:\n count += (grid[i][j] - grid[i-1][j])\n #down:i+1 \n if i+1 > len(grid)-1:\n count += grid[i][j]\n elif grid[i+1][j] < grid[i][j]:\n count += (grid[i][j] - grid[i+1][j])\n if grid[i][j] > 0:\n count +=2\n return count\n```
0
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\] **Output:** 1 **Example 3:** **Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length < n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
[python3] works 👍🏿
surface-area-of-3d-shapes
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 surfaceArea(self, grid: List[List[int]]) -> int:\n n=len(grid)\n totalSurfaceArea=0\n for x in range(n):\n for y in range(n):\n thisCellHeight=grid[x][y]\n if thisCellHeight>0:\n totalSurfaceArea+=2 #1 for top and 1 for bottom\n\n #check the four adjacent\n #left\n if x>0:\n leftDiff=thisCellHeight-grid[x-1][y]\n if leftDiff>0:\n totalSurfaceArea+=leftDiff\n else:\n totalSurfaceArea+=thisCellHeight\n #right\n if x<n-1:\n rightDiff=thisCellHeight-grid[x+1][y]\n if rightDiff>0:\n totalSurfaceArea+=rightDiff\n else:\n totalSurfaceArea+=thisCellHeight\n #up\n if y>0:\n upDiff=thisCellHeight-grid[x][y-1]\n if upDiff>0:\n totalSurfaceArea+=upDiff\n else:\n totalSurfaceArea+=thisCellHeight\n #down\n if y<n-1:\n downDiff=thisCellHeight-grid[x][y+1]\n if downDiff>0:\n totalSurfaceArea+=downDiff\n else:\n totalSurfaceArea+=thisCellHeight\n return totalSurfaceArea\n\n```
0
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the total surface area of the resulting shapes_. **Note:** The bottom face of each shape counts toward its surface area. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 34 **Example 2:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 32 **Example 3:** **Input:** grid = \[\[2,2,2\],\[2,1,2\],\[2,2,2\]\] **Output:** 46 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
[python3] works 👍🏿
surface-area-of-3d-shapes
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 surfaceArea(self, grid: List[List[int]]) -> int:\n n=len(grid)\n totalSurfaceArea=0\n for x in range(n):\n for y in range(n):\n thisCellHeight=grid[x][y]\n if thisCellHeight>0:\n totalSurfaceArea+=2 #1 for top and 1 for bottom\n\n #check the four adjacent\n #left\n if x>0:\n leftDiff=thisCellHeight-grid[x-1][y]\n if leftDiff>0:\n totalSurfaceArea+=leftDiff\n else:\n totalSurfaceArea+=thisCellHeight\n #right\n if x<n-1:\n rightDiff=thisCellHeight-grid[x+1][y]\n if rightDiff>0:\n totalSurfaceArea+=rightDiff\n else:\n totalSurfaceArea+=thisCellHeight\n #up\n if y>0:\n upDiff=thisCellHeight-grid[x][y-1]\n if upDiff>0:\n totalSurfaceArea+=upDiff\n else:\n totalSurfaceArea+=thisCellHeight\n #down\n if y<n-1:\n downDiff=thisCellHeight-grid[x][y+1]\n if downDiff>0:\n totalSurfaceArea+=downDiff\n else:\n totalSurfaceArea+=thisCellHeight\n return totalSurfaceArea\n\n```
0
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\] **Output:** 1 **Example 3:** **Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length < n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Easy Python Solution
surface-area-of-3d-shapes
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nStep 1 : Find the area of each piller on the matrix(First Loop)\nStep 2 : Remove all the walls of two adjence pillers(Second Loop)\nStep 3 : Get the transpose of the matrix\nStep 4 : Repet Step 2. \n# Complexity\n- Time complexity: O(n^2)\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# Runtime\n- 81 ms\n# Code\n```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n area = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] != 0:\n area += 2 * (1 + grid[i][j] + grid[i][j])\n \n for i in range(len(grid)):\n a=0\n while a < len(grid) - 1:\n area -= min(grid[i][a], grid[i][a+1]) * 2\n a += 1\n \n grid = list(zip(*grid))\n\n for i in range(len(grid)):\n a=0\n while a < len(grid) - 1:\n area -= min(grid[i][a], grid[i][a+1]) * 2\n a += 1\n \n return area\n```
0
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the total surface area of the resulting shapes_. **Note:** The bottom face of each shape counts toward its surface area. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 34 **Example 2:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 32 **Example 3:** **Input:** grid = \[\[2,2,2\],\[2,1,2\],\[2,2,2\]\] **Output:** 46 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Easy Python Solution
surface-area-of-3d-shapes
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nStep 1 : Find the area of each piller on the matrix(First Loop)\nStep 2 : Remove all the walls of two adjence pillers(Second Loop)\nStep 3 : Get the transpose of the matrix\nStep 4 : Repet Step 2. \n# Complexity\n- Time complexity: O(n^2)\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# Runtime\n- 81 ms\n# Code\n```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n area = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] != 0:\n area += 2 * (1 + grid[i][j] + grid[i][j])\n \n for i in range(len(grid)):\n a=0\n while a < len(grid) - 1:\n area -= min(grid[i][a], grid[i][a+1]) * 2\n a += 1\n \n grid = list(zip(*grid))\n\n for i in range(len(grid)):\n a=0\n while a < len(grid) - 1:\n area -= min(grid[i][a], grid[i][a+1]) * 2\n a += 1\n \n return area\n```
0
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\] **Output:** 1 **Example 3:** **Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length < n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Python solution
surface-area-of-3d-shapes
0
1
# Code\n```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n n = len(grid)\n neighbors = ((-1, 0), (0, -1), (0, 1), (1, 0))\n res = 0\n for r in range(n):\n for c in range(n):\n for n_r, n_c in neighbors:\n if (0 <= r + n_r < n) and (0 <= c + n_c < n):\n if grid[r][c] > grid[r+n_r][c+n_c]:\n res += grid[r][c] - grid[r+n_r][c+n_c]\n else:\n res += grid[r][c]\n\n res += 2 if grid[r][c] != 0 else 0\n\n return res\n\n```
0
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the total surface area of the resulting shapes_. **Note:** The bottom face of each shape counts toward its surface area. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 34 **Example 2:** **Input:** grid = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** 32 **Example 3:** **Input:** grid = \[\[2,2,2\],\[2,1,2\],\[2,2,2\]\] **Output:** 46 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Python solution
surface-area-of-3d-shapes
0
1
# Code\n```\nclass Solution:\n def surfaceArea(self, grid: List[List[int]]) -> int:\n n = len(grid)\n neighbors = ((-1, 0), (0, -1), (0, 1), (1, 0))\n res = 0\n for r in range(n):\n for c in range(n):\n for n_r, n_c in neighbors:\n if (0 <= r + n_r < n) and (0 <= c + n_c < n):\n if grid[r][c] > grid[r+n_r][c+n_c]:\n res += grid[r][c] - grid[r+n_r][c+n_c]\n else:\n res += grid[r][c]\n\n res += 2 if grid[r][c] != 0 else 0\n\n return res\n\n```
0
You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`. Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner. Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops. We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**. Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**. **Example 1:** **Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\] **Output:** 0 **Example 2:** **Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\] **Output:** 1 **Example 3:** **Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\] **Output:** 1 **Constraints:** * `n == graph.length` * `n == graph[i].length` * `2 <= n <= 300` * `graph[i][j]` is `0` or `1`. * `graph[i][j] == graph[j][i]` * `graph[i][i] == 1` * `1 <= initial.length < n` * `0 <= initial[i] <= n - 1` * All the integers in `initial` are **unique**.
null
Python 3 || 5 lines, w/ example || T/M: 88%/27%
groups-of-special-equivalent-strings
0
1
\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n # Example: \n wSet = set() # words = ["abc","acb","bac","bca","cab","cba"]\n\n for word in words: # sorted((enu- \n word = tuple(sorted((enumerate(word)), # word merate word) wSet\n key = lambda x: (x[0]%2,x[1]))) # \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\n print(wSet) # abc ((0,a),(2,c),(1,b)) {(a,c,b)}\n wSet.add(list(zip(*word))[1]) # acb ((0,a),(2,b),(1,c)) {(a,c,b), (a,b,c)}\n # bac ((0,b),(2,c),(1,a)) {(a,c,b), (a,b,c), (b,c,a)}\n return len(wSet) # bca ((2,a),(0,b),(1,c)) {(a,c,b), (a,b,c), (b,c,a)}\n # cab ((2,b),(0,c),(1,a)) {(a,c,b), (a,b,c), (b,c,a)}\n # cba ((2,a),(0,c),(1,b)) {(a,c,b), (a,b,c), (b,c,a)}\n```\n[https://leetcode.com/problems/groups-of-special-equivalent-strings/submissions/863479817/](http://)\n\n\nI could be wrong, but I think that time is *O*(*NlogN*) and space is *O*(*N*).
3
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Python 3 || 5 lines, w/ example || T/M: 88%/27%
groups-of-special-equivalent-strings
0
1
\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n # Example: \n wSet = set() # words = ["abc","acb","bac","bca","cab","cba"]\n\n for word in words: # sorted((enu- \n word = tuple(sorted((enumerate(word)), # word merate word) wSet\n key = lambda x: (x[0]%2,x[1]))) # \u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013 \u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\u2013\n print(wSet) # abc ((0,a),(2,c),(1,b)) {(a,c,b)}\n wSet.add(list(zip(*word))[1]) # acb ((0,a),(2,b),(1,c)) {(a,c,b), (a,b,c)}\n # bac ((0,b),(2,c),(1,a)) {(a,c,b), (a,b,c), (b,c,a)}\n return len(wSet) # bca ((2,a),(0,b),(1,c)) {(a,c,b), (a,b,c), (b,c,a)}\n # cab ((2,b),(0,c),(1,a)) {(a,c,b), (a,b,c), (b,c,a)}\n # cba ((2,a),(0,c),(1,b)) {(a,c,b), (a,b,c), (b,c,a)}\n```\n[https://leetcode.com/problems/groups-of-special-equivalent-strings/submissions/863479817/](http://)\n\n\nI could be wrong, but I think that time is *O*(*NlogN*) and space is *O*(*N*).
3
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Solution
groups-of-special-equivalent-strings
1
1
```C++ []\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n unordered_set<string> st;\n for (auto& w : words) {\n string odd, even;\n for (int i = 0; i < w.size(); i++) {\n if (i % 2) even += w[i];\n else odd += w[i];\n }\n sort(even.begin(), even.end());\n sort(odd.begin(), odd.end());\n st.insert(even + odd);\n }\n return st.size();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n res = set()\n for s in A:\n sort_odd_even = \'\'.join(sorted(s[1::2]) + sorted(s[::2]))\n res.add(sort_odd_even)\n return len(res)\n```\n\n```Java []\nimport java.util.HashSet;\n\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n HashSet<Integer> uniques = new HashSet<>();\n for (String word : words) uniques.add(customHash(word));\n return uniques.size();\n }\n private int customHash(String word) {\n int[] evenFreqs = new int[26], oddFreqs = new int[26];\n byte[] chars = word.getBytes();\n\n int n = chars.length;\n for (int i = 0, limit = n / 2 * 2; i < limit; i += 2) {\n ++evenFreqs[chars[i] - \'a\'];\n ++oddFreqs[chars[i + 1] - \'a\'];\n }\n if (n % 2 == 1) ++evenFreqs[chars[n - 1] - \'a\'];\n int acc = 0;\n for (int i = 0; i < 26; ++i) {\n acc = 31 * acc + evenFreqs[i];\n acc = 31 * acc + oddFreqs[i];\n }\n return acc;\n }\n}\n```\n
1
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Solution
groups-of-special-equivalent-strings
1
1
```C++ []\nclass Solution {\npublic:\n int numSpecialEquivGroups(vector<string>& words) {\n unordered_set<string> st;\n for (auto& w : words) {\n string odd, even;\n for (int i = 0; i < w.size(); i++) {\n if (i % 2) even += w[i];\n else odd += w[i];\n }\n sort(even.begin(), even.end());\n sort(odd.begin(), odd.end());\n st.insert(even + odd);\n }\n return st.size();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n res = set()\n for s in A:\n sort_odd_even = \'\'.join(sorted(s[1::2]) + sorted(s[::2]))\n res.add(sort_odd_even)\n return len(res)\n```\n\n```Java []\nimport java.util.HashSet;\n\nclass Solution {\n public int numSpecialEquivGroups(String[] words) {\n HashSet<Integer> uniques = new HashSet<>();\n for (String word : words) uniques.add(customHash(word));\n return uniques.size();\n }\n private int customHash(String word) {\n int[] evenFreqs = new int[26], oddFreqs = new int[26];\n byte[] chars = word.getBytes();\n\n int n = chars.length;\n for (int i = 0, limit = n / 2 * 2; i < limit; i += 2) {\n ++evenFreqs[chars[i] - \'a\'];\n ++oddFreqs[chars[i + 1] - \'a\'];\n }\n if (n % 2 == 1) ++evenFreqs[chars[n - 1] - \'a\'];\n int acc = 0;\n for (int i = 0; i < 26; ++i) {\n acc = 31 * acc + evenFreqs[i];\n acc = 31 * acc + oddFreqs[i];\n }\n return acc;\n }\n}\n```\n
1
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Pyton3 easy to understand solution
groups-of-special-equivalent-strings
0
1
# Approach\nSort the odd indices and even indices of the word seperately. Then combine those 2 to get the key value which is the same for special equivalent strings.\n\n\n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n d = defaultdict(list)\n for word in words:\n odd , even = "",\'\'\n for idx,char in enumerate(word):\n if idx%2 == 0:\n even += char\n else:\n odd+= char\n\n odd = sorted(odd)\n even = sorted(even)\n final = "".join(odd+even)\n \n d[final].append(word)\n\n \n return len(d.values())\n```
1
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Pyton3 easy to understand solution
groups-of-special-equivalent-strings
0
1
# Approach\nSort the odd indices and even indices of the word seperately. Then combine those 2 to get the key value which is the same for special equivalent strings.\n\n\n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n d = defaultdict(list)\n for word in words:\n odd , even = "",\'\'\n for idx,char in enumerate(word):\n if idx%2 == 0:\n even += char\n else:\n odd+= char\n\n odd = sorted(odd)\n even = sorted(even)\n final = "".join(odd+even)\n \n d[final].append(word)\n\n \n return len(d.values())\n```
1
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
[python3] detail explanation of special-equivalent
groups-of-special-equivalent-strings
0
1
* The point here is to understand the following requirement:\nA move consists of choosing two indices i and j with i % 2 == j % 2, and swapping S[i] with S[j].\nDon\'t trap your thoughts by the word \'swap\'.\nYour goal is how to identify the equivalent strings. \n* There are two possible outcomes of i%2: 1 or 0. i is the index of the input string.\n\tif i % 2 ==1: i = 1,3,5,7 ... in other words, i is odd number. In other words, the order of the odd index\'s value doesn\'t matter here. You can swap them.\n\tif i % 2 ==0: i = 0,2,4,6 ... in other words, i is even number. In other words, the order of the even index\'s value doesn\'t matter here. You can swap them.\n* So sort the string\'s odd index elements, and sort the string\'s even index elements and combine them to create a new string called "sort_string." If two string has the same "sort_string," they are the special-equivalent strings.\n```\nA = ["abcd","cdab","adcb","cbad"]\n ### sort odd index element | sort even index element\n"abcd" : bd | ac\n"cbad" : bd | ac\n"adcb" : bd | ac\n"cdab" : bd | ac\n# so they are equivalent strings\n```\n\n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n res = set()\n for s in A:\n sort_odd_even = \'\'.join(sorted(s[1::2]) + sorted(s[::2]))\n res.add(sort_odd_even)\n return len(res)\n```
39
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
[python3] detail explanation of special-equivalent
groups-of-special-equivalent-strings
0
1
* The point here is to understand the following requirement:\nA move consists of choosing two indices i and j with i % 2 == j % 2, and swapping S[i] with S[j].\nDon\'t trap your thoughts by the word \'swap\'.\nYour goal is how to identify the equivalent strings. \n* There are two possible outcomes of i%2: 1 or 0. i is the index of the input string.\n\tif i % 2 ==1: i = 1,3,5,7 ... in other words, i is odd number. In other words, the order of the odd index\'s value doesn\'t matter here. You can swap them.\n\tif i % 2 ==0: i = 0,2,4,6 ... in other words, i is even number. In other words, the order of the even index\'s value doesn\'t matter here. You can swap them.\n* So sort the string\'s odd index elements, and sort the string\'s even index elements and combine them to create a new string called "sort_string." If two string has the same "sort_string," they are the special-equivalent strings.\n```\nA = ["abcd","cdab","adcb","cbad"]\n ### sort odd index element | sort even index element\n"abcd" : bd | ac\n"cbad" : bd | ac\n"adcb" : bd | ac\n"cdab" : bd | ac\n# so they are equivalent strings\n```\n\n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n res = set()\n for s in A:\n sort_odd_even = \'\'.join(sorted(s[1::2]) + sorted(s[::2]))\n res.add(sort_odd_even)\n return len(res)\n```
39
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Python O(n * k lg k) sol. by signature. 90%+ [w/ Hint]
groups-of-special-equivalent-strings
0
1
Python sol. by signature. \n\n---\n\n**Hint**:\n\nThink of the concept for **anagram** judgement.\n\nWhat we need in this challenge is to verify the so-called "**special equivalent**", \nwhich means even-indexed substring of input is anagram and odd-indexed substring of input is another anagram.\n\nWe can verify by signature checking.\n\nDefine **signature** as the **sorted even-indexed substring and odd-indexed substring** in alphabetic order.\n\nIf signature( s1 ) == signature( s2 ),\nthen s1 and s2 are special equivalent.\n\n---\n\nFor example:\ns1 = \'**a**b**c**d\', and s2 = \'**c**d**a**b\'\n\nThen, signature( s1 ) is \'acbd\', and signature( s2 ) is the same.\nTherefore, s1 and s2 are special equivalent.\n\n---\n\n**Algorithm**:\n\nRearrange each input string into the form of signature.\n\nThe **number of unique signature** is the **number of grouping** for special equivalent.\n\n---\n\n**Implementation**:\n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n signature = set()\n \n # Use pair of sorted even substring and odd substring as unique key\n \n for idx, s in enumerate(A):\n signature.add( \'\'.join( sorted( s[::2] ) ) + \'\'.join( sorted( s[1::2] ) ) )\n \n return len( signature )\n```\n\n---\n\nRelated challenge:\n\n[Leetcode #49 Group Anagrms](https://leetcode.com/problems/group-anagrams/)\n\n[Leetcode #242 Valid Anagram](https://leetcode.com/problems/valid-anagram/)\n\n[Leetcode #438 Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/)\n\n---\n\nReference:\n\n[1] [Python official docs about hash-set: set()](https://docs.python.org/3/tutorial/datastructures.html#sets)
8
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Python O(n * k lg k) sol. by signature. 90%+ [w/ Hint]
groups-of-special-equivalent-strings
0
1
Python sol. by signature. \n\n---\n\n**Hint**:\n\nThink of the concept for **anagram** judgement.\n\nWhat we need in this challenge is to verify the so-called "**special equivalent**", \nwhich means even-indexed substring of input is anagram and odd-indexed substring of input is another anagram.\n\nWe can verify by signature checking.\n\nDefine **signature** as the **sorted even-indexed substring and odd-indexed substring** in alphabetic order.\n\nIf signature( s1 ) == signature( s2 ),\nthen s1 and s2 are special equivalent.\n\n---\n\nFor example:\ns1 = \'**a**b**c**d\', and s2 = \'**c**d**a**b\'\n\nThen, signature( s1 ) is \'acbd\', and signature( s2 ) is the same.\nTherefore, s1 and s2 are special equivalent.\n\n---\n\n**Algorithm**:\n\nRearrange each input string into the form of signature.\n\nThe **number of unique signature** is the **number of grouping** for special equivalent.\n\n---\n\n**Implementation**:\n```\nclass Solution:\n def numSpecialEquivGroups(self, A: List[str]) -> int:\n \n signature = set()\n \n # Use pair of sorted even substring and odd substring as unique key\n \n for idx, s in enumerate(A):\n signature.add( \'\'.join( sorted( s[::2] ) ) + \'\'.join( sorted( s[1::2] ) ) )\n \n return len( signature )\n```\n\n---\n\nRelated challenge:\n\n[Leetcode #49 Group Anagrms](https://leetcode.com/problems/group-anagrams/)\n\n[Leetcode #242 Valid Anagram](https://leetcode.com/problems/valid-anagram/)\n\n[Leetcode #438 Find All Anagrams in a String](https://leetcode.com/problems/find-all-anagrams-in-a-string/)\n\n---\n\nReference:\n\n[1] [Python official docs about hash-set: set()](https://docs.python.org/3/tutorial/datastructures.html#sets)
8
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Python3 Simple O(N^2 logN) solution with sorting (98.98% Runtime)
groups-of-special-equivalent-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/750b281a-0835-4fda-9afa-f3b3d20d4bc4_1703000186.6886802.png)\nUtilize hash table to store group (unique key) & use sorting to generate unique key\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- For each word, you can exchange freely within odd indexes and even indexes respectively\n- Thus, for each word, you can generate unique key by sorting characters in odd and even index and concatenate them\n- This unique key also means it is belong to some unique group\n- The number of this unique key will be your answer\n\n# Complexity\n- Time complexity: O(N^2 logN) s.t (N words) * (NlogN sorting for each word)\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\nIf this solution is similar to yours or helpful, upvote me if you don\'t mind\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n g = {}\n for w in words:\n e = []\n o = []\n for i, c in enumerate(w):\n if i % 2 == 0:\n e.append(c)\n else:\n o.append(c)\n\n e.sort()\n o.sort()\n key = \'\'.join(e) + "," + \'\'.join(o)\n if key not in g:\n g[key] = 1\n\n return len(g.keys())\n```
0
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Python3 Simple O(N^2 logN) solution with sorting (98.98% Runtime)
groups-of-special-equivalent-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/750b281a-0835-4fda-9afa-f3b3d20d4bc4_1703000186.6886802.png)\nUtilize hash table to store group (unique key) & use sorting to generate unique key\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- For each word, you can exchange freely within odd indexes and even indexes respectively\n- Thus, for each word, you can generate unique key by sorting characters in odd and even index and concatenate them\n- This unique key also means it is belong to some unique group\n- The number of this unique key will be your answer\n\n# Complexity\n- Time complexity: O(N^2 logN) s.t (N words) * (NlogN sorting for each word)\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\nIf this solution is similar to yours or helpful, upvote me if you don\'t mind\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n g = {}\n for w in words:\n e = []\n o = []\n for i, c in enumerate(w):\n if i % 2 == 0:\n e.append(c)\n else:\n o.append(c)\n\n e.sort()\n o.sort()\n key = \'\'.join(e) + "," + \'\'.join(o)\n if key not in g:\n g[key] = 1\n\n return len(g.keys())\n```
0
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Easy to understand using dictionary(HashMap) with Explanation|| Beats 85%
groups-of-special-equivalent-strings
0
1
![image.png](https://assets.leetcode.com/users/images/9fca1cad-8034-4514-b861-4f9d2319aa0c_1701181378.655741.png)\n\n\n# Code\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n d = defaultdict(list)\n for i in words:\n m,v = \'\',\'\'\n for j in range(len(i)):\n if j % 2 == 0: #considering only even index elements\n m += i[j]\n else: #considering only odd index elements\n v += i[j]\n #we are sorting these both elements and placing i values based on their sorted values\n d[\'\'.join(sorted(m)) + \'\'.join(sorted(v))].append(i)\n return len(d)\n```
0
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Easy to understand using dictionary(HashMap) with Explanation|| Beats 85%
groups-of-special-equivalent-strings
0
1
![image.png](https://assets.leetcode.com/users/images/9fca1cad-8034-4514-b861-4f9d2319aa0c_1701181378.655741.png)\n\n\n# Code\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n d = defaultdict(list)\n for i in words:\n m,v = \'\',\'\'\n for j in range(len(i)):\n if j % 2 == 0: #considering only even index elements\n m += i[j]\n else: #considering only odd index elements\n v += i[j]\n #we are sorting these both elements and placing i values based on their sorted values\n d[\'\'.join(sorted(m)) + \'\'.join(sorted(v))].append(i)\n return len(d)\n```
0
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Easy to understand Python3 solution
groups-of-special-equivalent-strings
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 numSpecialEquivGroups(self, words: List[str]) -> int:\n d = {}\n\n for i,word in enumerate(words):\n even, odd = "", ""\n for j in range(len(word)):\n if j % 2 == 0:\n even += word[j]\n else:\n odd += word[j]\n \n even = list(even)\n even.sort()\n even = "".join(even)\n odd = list(odd)\n odd.sort()\n odd = "".join(odd)\n\n if even+odd in d:\n d[even+odd] += 1\n else:\n d[even+odd] = 1\n\n return len(d)\n \n```
0
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Easy to understand Python3 solution
groups-of-special-equivalent-strings
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 numSpecialEquivGroups(self, words: List[str]) -> int:\n d = {}\n\n for i,word in enumerate(words):\n even, odd = "", ""\n for j in range(len(word)):\n if j % 2 == 0:\n even += word[j]\n else:\n odd += word[j]\n \n even = list(even)\n even.sort()\n even = "".join(even)\n odd = list(odd)\n odd.sort()\n odd = "".join(odd)\n\n if even+odd in d:\n d[even+odd] += 1\n else:\n d[even+odd] = 1\n\n return len(d)\n \n```
0
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Python3 - Convert characters at odd and even indices into a hash, count unique hashes
groups-of-special-equivalent-strings
0
1
# Code\n```\nclass Solution:\n # Approach: Form a dictionary (h1, h2) -> [s1,s2...sn]\n # where h1 and h2 are two hashes - sorted characters\n # at the odd and even indices respectively in the word.\n # So (h1,h2) will be the same for all special-equivalent strings.\n # Then count the number of unique hashes.\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n\n def build_hash(s:str) -> Tuple[str, str]:\n odd_chars = []\n even_chars = []\n for idx, c in enumerate(s):\n if idx % 2:\n odd_chars.append(c)\n else:\n even_chars.append(c)\n odd_chars.sort()\n even_chars.sort()\n return (\'\'.join(odd_chars), \'\'.join(even_chars))\n\n word_hash_set = set()\n for w in words:\n word_hash_set.add(build_hash(w))\n return len(word_hash_set)\n```
0
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Python3 - Convert characters at odd and even indices into a hash, count unique hashes
groups-of-special-equivalent-strings
0
1
# Code\n```\nclass Solution:\n # Approach: Form a dictionary (h1, h2) -> [s1,s2...sn]\n # where h1 and h2 are two hashes - sorted characters\n # at the odd and even indices respectively in the word.\n # So (h1,h2) will be the same for all special-equivalent strings.\n # Then count the number of unique hashes.\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n\n def build_hash(s:str) -> Tuple[str, str]:\n odd_chars = []\n even_chars = []\n for idx, c in enumerate(s):\n if idx % 2:\n odd_chars.append(c)\n else:\n even_chars.append(c)\n odd_chars.sort()\n even_chars.sort()\n return (\'\'.join(odd_chars), \'\'.join(even_chars))\n\n word_hash_set = set()\n for w in words:\n word_hash_set.add(build_hash(w))\n return len(word_hash_set)\n```
0
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
BEST & EASIEST SOLUTION ON WEB ROGHT NOW ||| I AM A GENIUS 〠
groups-of-special-equivalent-strings
1
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 numSpecialEquivGroups(self, words: List[str]) -> int:\n odd,even="",""\n final={}\n for i in words:\n for j in range(0,len(i)):\n if j%2==0:\n even = even+i[j]\n else:\n odd=odd+i[j]\n a = "".join(sorted(even)+sorted(odd))\n if a in final:\n final[a] = final[a]+1\n else:\n final[a]=1\n odd,even="",""\n return len(final)\n \n```
0
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
BEST & EASIEST SOLUTION ON WEB ROGHT NOW ||| I AM A GENIUS 〠
groups-of-special-equivalent-strings
1
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 numSpecialEquivGroups(self, words: List[str]) -> int:\n odd,even="",""\n final={}\n for i in words:\n for j in range(0,len(i)):\n if j%2==0:\n even = even+i[j]\n else:\n odd=odd+i[j]\n a = "".join(sorted(even)+sorted(odd))\n if a in final:\n final[a] = final[a]+1\n else:\n final[a]=1\n odd,even="",""\n return len(final)\n \n```
0
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
hashmap python solution
groups-of-special-equivalent-strings
0
1
\n\n# Code\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n gloss = {}\n answer = 0\n for w in words:\n ev = []\n od = []\n for i, ch in enumerate(w):\n if i%2==0:\n ev.append(ch)\n else:\n od.append(ch)\n k_ev = tuple(sorted(ev))\n v_ev = tuple(sorted(od))\n if k_ev in gloss:\n if v_ev not in gloss[k_ev]:\n gloss[k_ev].append(v_ev)\n answer += 1\n else:\n answer += 1\n gloss[k_ev] = [v_ev]\n \n return answer\n```
0
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
hashmap python solution
groups-of-special-equivalent-strings
0
1
\n\n# Code\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n gloss = {}\n answer = 0\n for w in words:\n ev = []\n od = []\n for i, ch in enumerate(w):\n if i%2==0:\n ev.append(ch)\n else:\n od.append(ch)\n k_ev = tuple(sorted(ev))\n v_ev = tuple(sorted(od))\n if k_ev in gloss:\n if v_ev not in gloss[k_ev]:\n gloss[k_ev].append(v_ev)\n answer += 1\n else:\n answer += 1\n gloss[k_ev] = [v_ev]\n \n return answer\n```
0
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Python | Simple | set
groups-of-special-equivalent-strings
0
1
\n# Code\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n res = set()\n for w in words: res.add(\'\'.join(sorted(w[::2]) + sorted(w[1::2])))\n return len(res)\n\n```
0
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`. A **group of special-equivalent strings** from `words` is a non-empty subset of words such that: * Every pair of strings in the group are special equivalent, and * The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group). Return _the number of **groups of special-equivalent strings** from_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\] **Output:** 3 **Explanation:** One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these. The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\]. Note that in particular, "zzxy " is not special equivalent to "zzyx ". **Example 2:** **Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\] **Output:** 3 **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 20` * `words[i]` consist of lowercase English letters. * All the strings are of the same length.
null
Python | Simple | set
groups-of-special-equivalent-strings
0
1
\n# Code\n```\nclass Solution:\n def numSpecialEquivGroups(self, words: List[str]) -> int:\n res = set()\n for w in words: res.add(\'\'.join(sorted(w[::2]) + sorted(w[1::2])))\n return len(res)\n\n```
0
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"[email protected] "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` and `"[email protected] "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"[email protected] "` will be forwarded to `"[email protected] "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 2 **Explanation:** "[email protected] " and "[email protected] " actually receive mails. **Example 2:** **Input:** emails = \[ "[email protected] ", "[email protected] ", "[email protected] "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Unorthodox Combinatorial Search + Backtracking Approach (Python 3)
all-possible-full-binary-trees
0
1
# Intuition\n\nDP solutions are much faster, but the first solution that came to my head is a recursive combinatorial search + backtracking, similar to combinations problem.\n\nJust wanted to include this post as an alternate method of solving the problem albeit with much slower time since it doesn\'t leverage memoization or symmetry.\n\nNote: this solution is only 5% faster speed and memory XD.\n\n# Approach\n\nTry to generate combinations of possible trees starting from the root node using combinatorial search recursively and backtracking. \n\nAt each step, we can choose a candidate from the unprocessed nodes (aka nodes we haven\'t recursed on) to expand. Either choose to include it (add 2 children) or disclude it (no children). Expand upon the unprocessed linearly such that duplicate combinations aren\'t included (similar to combinations problems).\n\n# Complexity\n\n- Time complexity:\n$$O(2^n)$$, based on combinations of largest possible unprocssed array, number of unprocessed each step increases by 1 per level, highest possible number of levels in full binary tree is n + 1 / 2.\n\n- Space complexity:\n$$O(n^2)$$, highest levels is factor of n, number of unprocessed is limited by n also.\n\nNote: Please correct me if I\'m wrong about the complexity, thanks!\n\n# Code\n```\nfrom copy import deepcopy\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n ans = []\n if not n % 2: # impossible to produce even num full tree\n return ans\n # combinatorial search with backtracking, at each step either set two children or set 0 children\n def generate_trees(n, node, unprocessed):\n if n == 0:\n ans.append(deepcopy(head))\n return\n node.left = TreeNode()\n node.right = TreeNode()\n unprocessed.append(node.left)\n unprocessed.append(node.right)\n # go over every combination of dfs expansion based on unprocessed candidates\n for ind, next_node in enumerate(unprocessed):\n generate_trees(n - 2, next_node, unprocessed[ind+1:])\n next_node.left = next_node.right = None # backtrack\n if n - 2 == 0: return # don\'t double count dups\n head = TreeNode()\n unprocessed = []\n generate_trees(n-1, head, unprocessed)\n return ans \n```
1
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tree where each node has exactly `0` or `2` children. **Example 1:** **Input:** n = 7 **Output:** \[\[0,0,0,null,null,0,0,null,null,0,0\],\[0,0,0,null,null,0,0,0,0\],\[0,0,0,0,0,0,0\],\[0,0,0,0,0,null,null,null,null,0,0\],\[0,0,0,0,0,null,null,0,0\]\] **Example 2:** **Input:** n = 3 **Output:** \[\[0,0,0\]\] **Constraints:** * `1 <= n <= 20`
null
Unorthodox Combinatorial Search + Backtracking Approach (Python 3)
all-possible-full-binary-trees
0
1
# Intuition\n\nDP solutions are much faster, but the first solution that came to my head is a recursive combinatorial search + backtracking, similar to combinations problem.\n\nJust wanted to include this post as an alternate method of solving the problem albeit with much slower time since it doesn\'t leverage memoization or symmetry.\n\nNote: this solution is only 5% faster speed and memory XD.\n\n# Approach\n\nTry to generate combinations of possible trees starting from the root node using combinatorial search recursively and backtracking. \n\nAt each step, we can choose a candidate from the unprocessed nodes (aka nodes we haven\'t recursed on) to expand. Either choose to include it (add 2 children) or disclude it (no children). Expand upon the unprocessed linearly such that duplicate combinations aren\'t included (similar to combinations problems).\n\n# Complexity\n\n- Time complexity:\n$$O(2^n)$$, based on combinations of largest possible unprocssed array, number of unprocessed each step increases by 1 per level, highest possible number of levels in full binary tree is n + 1 / 2.\n\n- Space complexity:\n$$O(n^2)$$, highest levels is factor of n, number of unprocessed is limited by n also.\n\nNote: Please correct me if I\'m wrong about the complexity, thanks!\n\n# Code\n```\nfrom copy import deepcopy\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n ans = []\n if not n % 2: # impossible to produce even num full tree\n return ans\n # combinatorial search with backtracking, at each step either set two children or set 0 children\n def generate_trees(n, node, unprocessed):\n if n == 0:\n ans.append(deepcopy(head))\n return\n node.left = TreeNode()\n node.right = TreeNode()\n unprocessed.append(node.left)\n unprocessed.append(node.right)\n # go over every combination of dfs expansion based on unprocessed candidates\n for ind, next_node in enumerate(unprocessed):\n generate_trees(n - 2, next_node, unprocessed[ind+1:])\n next_node.left = next_node.right = None # backtrack\n if n - 2 == 0: return # don\'t double count dups\n head = TreeNode()\n unprocessed = []\n generate_trees(n-1, head, unprocessed)\n return ans \n```
1
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0,1\] \[**1,0,1,0**,1\] \[1,**0,1,0,1**\] \[1,0,**1,0,1**\] **Example 2:** **Input:** nums = \[0,0,0,0,0\], goal = 0 **Output:** 15 **Constraints:** * `1 <= nums.length <= 3 * 104` * `nums[i]` is either `0` or `1`. * `0 <= goal <= nums.length`
null