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 |
---|---|---|---|---|---|---|---|
[Python3] union-find | largest-component-size-by-common-factor | 0 | 1 | \n`O(MlogM)` using sieve\n```\nclass UnionFind: \n \n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [1]*n\n \n def find(self, p): \n if p != self.parent[p]: \n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n \n def union(self, p, q): \n prt, qrt = self.find(p), self.find(q)\n if prt == qrt: return False \n if self.rank[prt] > self.rank[qrt]: prt, qrt = qrt, prt\n self.parent[prt] = qrt\n self.rank[qrt] += self.rank[prt]\n return True \n\n\nclass Solution:\n def largestComponentSize(self, A: List[int]) -> int:\n m = max(A)\n uf = UnionFind(m+1)\n seen = set(A)\n \n # modified sieve of eratosthenes \n sieve = [1]*(m+1)\n sieve[0] = sieve[1] = 0 \n for k in range(m//2+1): \n if sieve[k]: \n prev = k if k in seen else 0\n for x in range(2*k, m+1, k): \n sieve[x] = 0\n if x in seen: \n if prev: uf.union(prev, x)\n else: prev = x\n return max(uf.rank)\n```\n\n**Related problems**\n[952. Largest Component Size by Common Factor](https://leetcode.com/problems/largest-component-size-by-common-factor/discuss/1546345/Python3-union-find)\n[1998. GCD Sort of an Array](https://leetcode.com/problems/gcd-sort-of-an-array/discuss/1445278/Python3-union-find)\n\nAlternative implemetation `O(Nsqrt(M))` assuming `O(1)` union & find.\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n m = max(nums)\n uf = UnionFind(m+1)\n for x in nums: \n for p in range(2, int(sqrt(x))+1): \n if x%p == 0: \n uf.union(x, p)\n uf.union(x, x//p)\n freq = Counter(uf.find(x) for x in nums)\n return max(freq.values())\n```\n\nAlternative implementation using `spf` `O((M+N)logM)`\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n m = max(nums)\n spf = list(range(m+1))\n for x in range(4, m+1, 2): spf[x] = 2\n for x in range(3, int(sqrt(m+1))+1): \n if spf[x] == x: \n for xx in range(x*x, m+1, x): \n spf[xx] = x \n \n uf = UnionFind(len(nums))\n mp = {}\n for i, x in enumerate(nums): \n while x > 1: \n if spf[x] in mp: uf.union(i, mp[spf[x]])\n else: mp[spf[x]] = i\n x //= spf[x]\n return max(uf.rank)\n``` | 4 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
[Python] Union Find - Nov., Day 22 Daily leetcode | largest-component-size-by-common-factor | 0 | 1 | # Intuition\n\ndescription:\n> There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.\n\nwe can see that what we really care is **common factor**.\ntransfrom nums[i] into a set of factors and union their factors together, because node\'s factor is the key and node itself is the bridge to connect each factor\'s group together.\n\nsee example1.\n\n4 = 2*2\n6 = 2*3 => connect group-2 and group-3\n15 = 3*5 => connect group-3 and group-5\n35 = 5*7 => connect group-5 and group-7\nthus if x = a*b*c*d*e => x will connect group-a, group-b, group-c, group-d, group-e together\n\nthus, turn nums[i] into a*b*c*d...\nthen union factors: union(a, b), union(a, c), union(a, d), ...\nafter all, connected component size += 1 (nums[i] itself) => rank[find(a)] += 1\n\nthe final answer should be max(rank)\n\n# Complexity\n- Time complexity:\n$$O(n * sqrt(n))$$\n\n- Space complexity:\n$$O(max(nums[i]))$$\n\n# Code\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n arr = []\n maxNum = nums[0]\n for num in nums:\n maxNum = max(maxNum, num)\n factors = []\n for x in range(2, int(sqrt(num))+1):\n if num%x == 0:\n factors.append(x)\n while num%x == 0:\n num //= x\n if num > 1:\n factors.append(num)\n \n # edge case: num=1 => factors = []\n if factors:\n arr.append(factors)\n \n n = len(nums)\n parent = list(range((maxNum+1)))\n rank = [0] * (maxNum+1)\n\n def find(x):\n if parent[x] != x:\n parent[x] = find(parent[x])\n return parent[x]\n\n def union(x, y):\n px, py = find(x), find(y)\n if px == py: return\n\n if rank[px] <= rank[py]:\n parent[px] = py\n rank[py] += rank[px]\n else:\n parent[py] = px\n rank[px] += rank[py]\n\n for factors in arr:\n x = factors[0]\n for y in factors[1:]:\n union(x, y)\n rank[find(x)] += 1\n \n return max(rank)\n``` | 0 | You are given an integer array of unique positive integers `nums`. Consider the following graph:
* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,
* There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`.
Return _the size of the largest connected component in the graph_.
**Example 1:**
**Input:** nums = \[4,6,15,35\]
**Output:** 4
**Example 2:**
**Input:** nums = \[20,50,9,63\]
**Output:** 2
**Example 3:**
**Input:** nums = \[2,3,6,7,4,12,21,39\]
**Output:** 8
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 105`
* All the values of `nums` are **unique**. | null |
[Python] Union Find - Nov., Day 22 Daily leetcode | largest-component-size-by-common-factor | 0 | 1 | # Intuition\n\ndescription:\n> There is an undirected edge between nums[i] and nums[j] if nums[i] and nums[j] share a common factor greater than 1.\n\nwe can see that what we really care is **common factor**.\ntransfrom nums[i] into a set of factors and union their factors together, because node\'s factor is the key and node itself is the bridge to connect each factor\'s group together.\n\nsee example1.\n\n4 = 2*2\n6 = 2*3 => connect group-2 and group-3\n15 = 3*5 => connect group-3 and group-5\n35 = 5*7 => connect group-5 and group-7\nthus if x = a*b*c*d*e => x will connect group-a, group-b, group-c, group-d, group-e together\n\nthus, turn nums[i] into a*b*c*d...\nthen union factors: union(a, b), union(a, c), union(a, d), ...\nafter all, connected component size += 1 (nums[i] itself) => rank[find(a)] += 1\n\nthe final answer should be max(rank)\n\n# Complexity\n- Time complexity:\n$$O(n * sqrt(n))$$\n\n- Space complexity:\n$$O(max(nums[i]))$$\n\n# Code\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n arr = []\n maxNum = nums[0]\n for num in nums:\n maxNum = max(maxNum, num)\n factors = []\n for x in range(2, int(sqrt(num))+1):\n if num%x == 0:\n factors.append(x)\n while num%x == 0:\n num //= x\n if num > 1:\n factors.append(num)\n \n # edge case: num=1 => factors = []\n if factors:\n arr.append(factors)\n \n n = len(nums)\n parent = list(range((maxNum+1)))\n rank = [0] * (maxNum+1)\n\n def find(x):\n if parent[x] != x:\n parent[x] = find(parent[x])\n return parent[x]\n\n def union(x, y):\n px, py = find(x), find(y)\n if px == py: return\n\n if rank[px] <= rank[py]:\n parent[px] = py\n rank[py] += rank[px]\n else:\n parent[py] = px\n rank[px] += rank[py]\n\n for factors in arr:\n x = factors[0]\n for y in factors[1:]:\n union(x, y)\n rank[find(x)] += 1\n \n return max(rank)\n``` | 0 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
Python 3 FT 90%: Link Numbers to Prime Factors, Sieve of Eratosthenes, Trial Divide by <= Sqrt(n) | largest-component-size-by-common-factor | 0 | 1 | # Intuition\n\nThis is basically the same solution as DBabichev\'s, just wanted to share the key insights needed to avoid TLE. There are lots of ways to get the right answer, but there are some nontrivial things you must do to avoid TLE. In my opinion the max runtime is bit too strict for this problem - this is more of a Project Euler problem than a LC problem!\n\nIn order of least obvious to most obvious, here\'s what matters for performance:\n* you MUST find unique prime factors of each number `n` with a method that only checks up to `sqrt(n)`. Otherwise you check up to `O(n)` which will give you TLE.\n* instead of literally adding `O(N^2)` edges, instead add an edge from each number `n` to each of its unique prime factors `p`. This way all numbers that share 1 or more prime factors are in the same component, but you add `log(n)` edges instead of `O(N)` edges for each number.\n * union-find makes it easy to effectively add these edges, and nicely updates the clusters as you go\n* you benenfit from using the Sieve of Erathosthenes to memoize all primes you would do trial division with, a lot faster than trying 2, 3, 4, .., sqrt(n) every time. Saves a lot of divisions\n\n\n## Union Find\n\nSince the solution involves clusters, we can infer that union-find is going to be the cornerstone of our solution. If you\'re not familiar with union-find, PLEASE do yourself a favor and research it! It\'s a very important algorithm to know for interviews. Here are the highlights:\n* union-find finds connected components in a graph with N vertices and E edges in O(N+E) time. Same time complexity as DFS, but faster (less recursion overhead) and simpler\n* each node starts off in its own cluster, with no parent. Each node is its own root\n* a root node has no parent\n* to union two nodes, i.e. add an edge and unify their components\n * find the roots of both nodes\n * if the roots aren\'t the same, add the size of the smaller component to the larger component. This is called "union by rank" and is essential to guaranteeing O(N+E) time.\n* when finding the root of a node, we shortest the existing path of parent pointers as much as possible. This is called "path compression." It too is essential to guaranteenig O(N+E) time.\n * the easiest way to to use recursion to find the root, then set `parent[node] = root`. This is easiest to write and it results in the shortest possible path at all times\n * if you run out of stack space, you can switch to another approach where you set each node\'s parent to its grandparent in a loop. This only cuts the path length in half, but avoids recursion and any stack limit exceeded errors\n\n## What are the Nodes?\n\nWhile we could call `union(m, n)` for every pair of numbers with a common prime factor, that\'s `O(N^2)` calls so you\'ll get TLE.\n\nSo the solution instead is to use the transitive property:\n* instead of linking `m` directly to all other numbers `n` that share a prime factor, we\n* link each number `n` to its unique prime factors\n* that way each number `m` is connected via its prime factors to all other numbers `n` that share at least one prime factor\n\nSo we have a node for every number from 1 to `max(nums)`.\n\n## Finding Unique Prime Factors\n\n**This is IMO the hardest part:** if you don\'t do this exactly right then you\'ll get TLE, even using union-find.\n\nThere are two relatively simple ways to get all unqiue prime factors:\n* easiest: loop over primes from 2 until `n//2` and append them. If you don\'t find any primes, `n` itself is prime.\n* harder: the recursive version. If `n` is _not_ prime, it has a prime factor less than or equal to `sqrt(n)`.\n * so do trial division by prime factors up to `sqrt(n)`\n * if you find a prime, return the union of the prime and the prime factors of `n//prime` (recursion)\n * if you don\'t find a prime less than or equal to `sqrt(n)`, then `n` itself is prime so return `{n}`\n\n**You have to use a variant of the second one.** The first one is $O(max(nums))$. Way too slow. The second one is $O(sqrt(max(nums)))$ which is obviously way faster since the max number is $10^5$.\n\nThe version I wrote does the following:\n* `uniqueFactors(i, n)` finds all unique factors in `primes[i:]` that divide `n`\n* if there is a prime less than `sqrt(n)` that divides `n`, I call `uniqueFactors(j, r)` to find all larger unique factors. Then I append `primes[i]` and return\n* if there is no prime factor up to `sqrt(n)` then `n` itself is prime\n\n## Getting Primes Up to sqrt(max(nums)) in the First Place\n\nTechnically yout don\'t need to do this: n the `uniqueFactors` function, you can trial divide by all integers in `2..sqrt(n)`.\n\nBut we know for example that all even numbers above 2 are not prime. Every multiple of 3 above 3 is not prime either. In general, every multiple of prime `p` above `p` is not prime.\n\nSo to speed that part up I did two things\n* to get all primes we\'d trial divide by in the first place, I used the Sieve of Eratosthenes. It\'s a pretty literal version of "for each prime `p`, record that all multiples of `p` above `p` are not prime."\n * **IMPORTANT:** In the Sieve code, you only mark off multiples of `p` above `p*p`. This is because any lower multiple of `p` can be written as `p*f` where `f < p`. The Sieve algorithm already marked off multiples of `f < p` in earlier iterations. This is really important for not getting TLE in time-constrained problems relating to primes\n* the `uniqueFactors` code divides out all factors of the current prime `p`, then recurses with all larger factors. That way we don\'t re-check division by 2, 3, 5, etc. if we\'ve already checked primes up to some larger number.\n\n# Code\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n \n # This problem\'s TLE threshold seems too low, you have to do the problem\n # EXACTLY RIGHT (tm) or you fail.\n # In particular: you need to use the recursive form of finding unique\n # factors so you only need to check up to sqrt(n). That\'s knowledge that\'s\n # past what I consider to be good for LC.\n\n # Overall idea:\n # > we want to link numbers together if they share a prime factor\n # > cluster questions are almost always union-find questions\n # > we can "transitively link" numbers as follows:\n # > link each number n to its first prime factor\n # > then link its prime factors together\n # > this looks like a 1D chain: n -- firstFactor -- secondFactor -- .. -- lastFactor\n # > by doing this for each number, n will be linked via its prime factor(s) to all\n # other n\' with the same factor\n # > using union-find lets us get away with adding fewer factors\n\n M = max(nums)\n U = M//2\n P = [True]*(M+1)\n primes = [2]\n for c in range(3, U+1, 2):\n if P[c]:\n primes.append(c)\n for m in range(c*c, U+1, 2*c):\n P[m] = False\n\n print(primes)\n\n def uniqueFactors(i: int, n: int) -> List[int]:\n """\n Returns unique prime factors in primes[i:] that divide n. \n \n PRE: n is not divisible by primes[:i]\n \n Factors are returned in descending order.\n """\n if n == 1:\n return []\n\n for j in range(i, len(primes)):\n p = primes[j]\n\n if p*p > n:\n break\n\n if n % p == 0:\n r = n//p\n while r % p == 0:\n r //= p\n factors = uniqueFactors(j+1, r)\n factors.append(p)\n return factors\n\n return [n]\n\n parent = [-1]*(M+1)\n\n def find(n: int) -> int:\n if parent[n] < 0:\n return n\n else:\n parent[n] = find(parent[n])\n return parent[n]\n\n def union(m: int, n: int) -> None:\n rm = find(m)\n rn = find(n)\n\n if rm == rn:\n return\n\n if parent[rm] > parent[rn]:\n rm, rn = rn, rm\n\n parent[rm] += parent[rn]\n parent[rn] = rm\n\n for n in nums:\n if n == 1:\n continue\n\n # link n to each of its prime factors, transitively linking it to\n # all numbers that share a factor\n fs = uniqueFactors(0, n)\n # print(f"uniqueFactors(0, {n}) = {fs}")\n prev = n\n for f in fs:\n union(f, prev)\n prev = f\n\n # find cluster with the largest membership\n sizes = Counter(find(n) for n in nums)\n return max(sizes.values())\n``` | 0 | You are given an integer array of unique positive integers `nums`. Consider the following graph:
* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,
* There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`.
Return _the size of the largest connected component in the graph_.
**Example 1:**
**Input:** nums = \[4,6,15,35\]
**Output:** 4
**Example 2:**
**Input:** nums = \[20,50,9,63\]
**Output:** 2
**Example 3:**
**Input:** nums = \[2,3,6,7,4,12,21,39\]
**Output:** 8
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 105`
* All the values of `nums` are **unique**. | null |
Python 3 FT 90%: Link Numbers to Prime Factors, Sieve of Eratosthenes, Trial Divide by <= Sqrt(n) | largest-component-size-by-common-factor | 0 | 1 | # Intuition\n\nThis is basically the same solution as DBabichev\'s, just wanted to share the key insights needed to avoid TLE. There are lots of ways to get the right answer, but there are some nontrivial things you must do to avoid TLE. In my opinion the max runtime is bit too strict for this problem - this is more of a Project Euler problem than a LC problem!\n\nIn order of least obvious to most obvious, here\'s what matters for performance:\n* you MUST find unique prime factors of each number `n` with a method that only checks up to `sqrt(n)`. Otherwise you check up to `O(n)` which will give you TLE.\n* instead of literally adding `O(N^2)` edges, instead add an edge from each number `n` to each of its unique prime factors `p`. This way all numbers that share 1 or more prime factors are in the same component, but you add `log(n)` edges instead of `O(N)` edges for each number.\n * union-find makes it easy to effectively add these edges, and nicely updates the clusters as you go\n* you benenfit from using the Sieve of Erathosthenes to memoize all primes you would do trial division with, a lot faster than trying 2, 3, 4, .., sqrt(n) every time. Saves a lot of divisions\n\n\n## Union Find\n\nSince the solution involves clusters, we can infer that union-find is going to be the cornerstone of our solution. If you\'re not familiar with union-find, PLEASE do yourself a favor and research it! It\'s a very important algorithm to know for interviews. Here are the highlights:\n* union-find finds connected components in a graph with N vertices and E edges in O(N+E) time. Same time complexity as DFS, but faster (less recursion overhead) and simpler\n* each node starts off in its own cluster, with no parent. Each node is its own root\n* a root node has no parent\n* to union two nodes, i.e. add an edge and unify their components\n * find the roots of both nodes\n * if the roots aren\'t the same, add the size of the smaller component to the larger component. This is called "union by rank" and is essential to guaranteeing O(N+E) time.\n* when finding the root of a node, we shortest the existing path of parent pointers as much as possible. This is called "path compression." It too is essential to guaranteenig O(N+E) time.\n * the easiest way to to use recursion to find the root, then set `parent[node] = root`. This is easiest to write and it results in the shortest possible path at all times\n * if you run out of stack space, you can switch to another approach where you set each node\'s parent to its grandparent in a loop. This only cuts the path length in half, but avoids recursion and any stack limit exceeded errors\n\n## What are the Nodes?\n\nWhile we could call `union(m, n)` for every pair of numbers with a common prime factor, that\'s `O(N^2)` calls so you\'ll get TLE.\n\nSo the solution instead is to use the transitive property:\n* instead of linking `m` directly to all other numbers `n` that share a prime factor, we\n* link each number `n` to its unique prime factors\n* that way each number `m` is connected via its prime factors to all other numbers `n` that share at least one prime factor\n\nSo we have a node for every number from 1 to `max(nums)`.\n\n## Finding Unique Prime Factors\n\n**This is IMO the hardest part:** if you don\'t do this exactly right then you\'ll get TLE, even using union-find.\n\nThere are two relatively simple ways to get all unqiue prime factors:\n* easiest: loop over primes from 2 until `n//2` and append them. If you don\'t find any primes, `n` itself is prime.\n* harder: the recursive version. If `n` is _not_ prime, it has a prime factor less than or equal to `sqrt(n)`.\n * so do trial division by prime factors up to `sqrt(n)`\n * if you find a prime, return the union of the prime and the prime factors of `n//prime` (recursion)\n * if you don\'t find a prime less than or equal to `sqrt(n)`, then `n` itself is prime so return `{n}`\n\n**You have to use a variant of the second one.** The first one is $O(max(nums))$. Way too slow. The second one is $O(sqrt(max(nums)))$ which is obviously way faster since the max number is $10^5$.\n\nThe version I wrote does the following:\n* `uniqueFactors(i, n)` finds all unique factors in `primes[i:]` that divide `n`\n* if there is a prime less than `sqrt(n)` that divides `n`, I call `uniqueFactors(j, r)` to find all larger unique factors. Then I append `primes[i]` and return\n* if there is no prime factor up to `sqrt(n)` then `n` itself is prime\n\n## Getting Primes Up to sqrt(max(nums)) in the First Place\n\nTechnically yout don\'t need to do this: n the `uniqueFactors` function, you can trial divide by all integers in `2..sqrt(n)`.\n\nBut we know for example that all even numbers above 2 are not prime. Every multiple of 3 above 3 is not prime either. In general, every multiple of prime `p` above `p` is not prime.\n\nSo to speed that part up I did two things\n* to get all primes we\'d trial divide by in the first place, I used the Sieve of Eratosthenes. It\'s a pretty literal version of "for each prime `p`, record that all multiples of `p` above `p` are not prime."\n * **IMPORTANT:** In the Sieve code, you only mark off multiples of `p` above `p*p`. This is because any lower multiple of `p` can be written as `p*f` where `f < p`. The Sieve algorithm already marked off multiples of `f < p` in earlier iterations. This is really important for not getting TLE in time-constrained problems relating to primes\n* the `uniqueFactors` code divides out all factors of the current prime `p`, then recurses with all larger factors. That way we don\'t re-check division by 2, 3, 5, etc. if we\'ve already checked primes up to some larger number.\n\n# Code\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n \n # This problem\'s TLE threshold seems too low, you have to do the problem\n # EXACTLY RIGHT (tm) or you fail.\n # In particular: you need to use the recursive form of finding unique\n # factors so you only need to check up to sqrt(n). That\'s knowledge that\'s\n # past what I consider to be good for LC.\n\n # Overall idea:\n # > we want to link numbers together if they share a prime factor\n # > cluster questions are almost always union-find questions\n # > we can "transitively link" numbers as follows:\n # > link each number n to its first prime factor\n # > then link its prime factors together\n # > this looks like a 1D chain: n -- firstFactor -- secondFactor -- .. -- lastFactor\n # > by doing this for each number, n will be linked via its prime factor(s) to all\n # other n\' with the same factor\n # > using union-find lets us get away with adding fewer factors\n\n M = max(nums)\n U = M//2\n P = [True]*(M+1)\n primes = [2]\n for c in range(3, U+1, 2):\n if P[c]:\n primes.append(c)\n for m in range(c*c, U+1, 2*c):\n P[m] = False\n\n print(primes)\n\n def uniqueFactors(i: int, n: int) -> List[int]:\n """\n Returns unique prime factors in primes[i:] that divide n. \n \n PRE: n is not divisible by primes[:i]\n \n Factors are returned in descending order.\n """\n if n == 1:\n return []\n\n for j in range(i, len(primes)):\n p = primes[j]\n\n if p*p > n:\n break\n\n if n % p == 0:\n r = n//p\n while r % p == 0:\n r //= p\n factors = uniqueFactors(j+1, r)\n factors.append(p)\n return factors\n\n return [n]\n\n parent = [-1]*(M+1)\n\n def find(n: int) -> int:\n if parent[n] < 0:\n return n\n else:\n parent[n] = find(parent[n])\n return parent[n]\n\n def union(m: int, n: int) -> None:\n rm = find(m)\n rn = find(n)\n\n if rm == rn:\n return\n\n if parent[rm] > parent[rn]:\n rm, rn = rn, rm\n\n parent[rm] += parent[rn]\n parent[rn] = rm\n\n for n in nums:\n if n == 1:\n continue\n\n # link n to each of its prime factors, transitively linking it to\n # all numbers that share a factor\n fs = uniqueFactors(0, n)\n # print(f"uniqueFactors(0, {n}) = {fs}")\n prev = n\n for f in fs:\n union(f, prev)\n prev = f\n\n # find cluster with the largest membership\n sizes = Counter(find(n) for n in nums)\n return max(sizes.values())\n``` | 0 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
Easy to understand Sieve and Union find | largest-component-size-by-common-factor | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### Use sieve algorithm to find the smallest prime factor (spf) for each number in 1 to 10**5\n1. finding the spf of all numbers also gives us all the prime factors of the number, this is because by successively dividing by the spf we get a smaller number with potentially a differnt spf and continuing we would encounter all the prime factors.\n\n##### Union Find\n1. Create a list for each prime where the list would contain multiples of the prime that belong to the array\n2. union over all the elements for each prime\n3. count the frequency of each representative element of union find\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(M\\log(M) + N\\log(M))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(M + N\\log(M))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nM = 10**5 + 1\nspf = [x for x in range(M)]\nfor i in range(2, M):\n if spf[i] != i:\n continue\n j = i ** 2\n while j < M:\n spf[j] = min(spf[j], i)\n j += i\n\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n \n # Use sieve algorithm to find the smallest prime factor (spf) for each number in 1 to 10**5\n # finding the spf of all numbers also gives us all the prime factors of the number\n # this is because by successivel divifing by the spf gives us smaller number with potentially \n # a differnt spf and so on\n\n # create a list for each prime where the list would contain multiples of the prime that belong to the array\n # union over all the elements for each prime\n # count the number of times each representative element of the union find\n \n n = len(nums)\n divides = defaultdict(set)\n for i, x in enumerate(nums):\n num = x\n while num > 1:\n divides[spf[num]].add(i)\n num //= spf[num]\n parents = [x for x in range(n)]\n def find(a):\n if parents[a] != a:\n parents[a] = find(parents[a])\n return parents[a]\n \n def union(a, b):\n ua, ub = find(a), find(b)\n parents[ua] = ub\n \n for prime in divides:\n arr = list(divides[prime])\n for x in arr:\n union(x, arr[0])\n \n counts = defaultdict(int)\n for i in range(n):\n counts[find(i)] += 1\n \n return max(counts.values())\n``` | 0 | You are given an integer array of unique positive integers `nums`. Consider the following graph:
* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,
* There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`.
Return _the size of the largest connected component in the graph_.
**Example 1:**
**Input:** nums = \[4,6,15,35\]
**Output:** 4
**Example 2:**
**Input:** nums = \[20,50,9,63\]
**Output:** 2
**Example 3:**
**Input:** nums = \[2,3,6,7,4,12,21,39\]
**Output:** 8
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 105`
* All the values of `nums` are **unique**. | null |
Easy to understand Sieve and Union find | largest-component-size-by-common-factor | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n##### Use sieve algorithm to find the smallest prime factor (spf) for each number in 1 to 10**5\n1. finding the spf of all numbers also gives us all the prime factors of the number, this is because by successively dividing by the spf we get a smaller number with potentially a differnt spf and continuing we would encounter all the prime factors.\n\n##### Union Find\n1. Create a list for each prime where the list would contain multiples of the prime that belong to the array\n2. union over all the elements for each prime\n3. count the frequency of each representative element of union find\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(M\\log(M) + N\\log(M))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(M + N\\log(M))$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nM = 10**5 + 1\nspf = [x for x in range(M)]\nfor i in range(2, M):\n if spf[i] != i:\n continue\n j = i ** 2\n while j < M:\n spf[j] = min(spf[j], i)\n j += i\n\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n \n # Use sieve algorithm to find the smallest prime factor (spf) for each number in 1 to 10**5\n # finding the spf of all numbers also gives us all the prime factors of the number\n # this is because by successivel divifing by the spf gives us smaller number with potentially \n # a differnt spf and so on\n\n # create a list for each prime where the list would contain multiples of the prime that belong to the array\n # union over all the elements for each prime\n # count the number of times each representative element of the union find\n \n n = len(nums)\n divides = defaultdict(set)\n for i, x in enumerate(nums):\n num = x\n while num > 1:\n divides[spf[num]].add(i)\n num //= spf[num]\n parents = [x for x in range(n)]\n def find(a):\n if parents[a] != a:\n parents[a] = find(parents[a])\n return parents[a]\n \n def union(a, b):\n ua, ub = find(a), find(b)\n parents[ua] = ub\n \n for prime in divides:\n arr = list(divides[prime])\n for x in arr:\n union(x, arr[0])\n \n counts = defaultdict(int)\n for i in range(n):\n counts[find(i)] += 1\n \n return max(counts.values())\n``` | 0 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
Using sieve and dfs/union-find | largest-component-size-by-common-factor | 0 | 1 | **Using DFS and sieve** \n\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n n,prime,isPresent = max(nums) + 11,[],set(nums) \n g,ans,curr = [[] for _ in range(n)],0,0\n \n \n def sieve(n):\n primes = [True for _ in range(n)] \n for i in range(2,n):\n if primes[i] : \n for j in range(i*i,n,i): primes[j] = False\n prime.append(i) \n\n sieve(n) \n for number in prime : \n for x in range(2*number,n,number):\n if x in isPresent : \n g[x].append(number) \n g[number].append(x) \n\n visited = [False for _ in range(n)] \n def dfs(x):\n nonlocal curr\n if x in isPresent : curr += 1 \n visited[x] = True \n for i in g[x] : \n if not visited[i] : dfs(i) \n \n for i in range(n):\n curr = 0 \n if not visited[i]:\n dfs(i) \n ans = max(ans ,curr) \n \n return ans\n\n \n\n``` | 0 | You are given an integer array of unique positive integers `nums`. Consider the following graph:
* There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`,
* There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`.
Return _the size of the largest connected component in the graph_.
**Example 1:**
**Input:** nums = \[4,6,15,35\]
**Output:** 4
**Example 2:**
**Input:** nums = \[20,50,9,63\]
**Output:** 2
**Example 3:**
**Input:** nums = \[2,3,6,7,4,12,21,39\]
**Output:** 8
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 105`
* All the values of `nums` are **unique**. | null |
Using sieve and dfs/union-find | largest-component-size-by-common-factor | 0 | 1 | **Using DFS and sieve** \n\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n n,prime,isPresent = max(nums) + 11,[],set(nums) \n g,ans,curr = [[] for _ in range(n)],0,0\n \n \n def sieve(n):\n primes = [True for _ in range(n)] \n for i in range(2,n):\n if primes[i] : \n for j in range(i*i,n,i): primes[j] = False\n prime.append(i) \n\n sieve(n) \n for number in prime : \n for x in range(2*number,n,number):\n if x in isPresent : \n g[x].append(number) \n g[number].append(x) \n\n visited = [False for _ in range(n)] \n def dfs(x):\n nonlocal curr\n if x in isPresent : curr += 1 \n visited[x] = True \n for i in g[x] : \n if not visited[i] : dfs(i) \n \n for i in range(n):\n curr = 0 \n if not visited[i]:\n dfs(i) \n ans = max(ans ,curr) \n \n return ans\n\n \n\n``` | 0 | The **array-form** of an integer `num` is an array representing its digits in left to right order.
* For example, for `num = 1321`, the array form is `[1,3,2,1]`.
Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`.
**Example 1:**
**Input:** num = \[1,2,0,0\], k = 34
**Output:** \[1,2,3,4\]
**Explanation:** 1200 + 34 = 1234
**Example 2:**
**Input:** num = \[2,7,4\], k = 181
**Output:** \[4,5,5\]
**Explanation:** 274 + 181 = 455
**Example 3:**
**Input:** num = \[2,1,5\], k = 806
**Output:** \[1,0,2,1\]
**Explanation:** 215 + 806 = 1021
**Constraints:**
* `1 <= num.length <= 104`
* `0 <= num[i] <= 9`
* `num` does not contain any leading zeros except for the zero itself.
* `1 <= k <= 104` | null |
Python solution: explained in detail | verifying-an-alien-dictionary | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n- In lexicographically ordered dictionary we don\'t have any words less in value after greater.\n- So we don\'t need to traverse $$words$$ array $$n^2$$ times just check it for $$n$$ times.\n- if $$current word[i]$$ is greater in size of $$currentword[i+1]$$ and next word is having less value according to orders then return false\n- else check for every word pair in one iteration from i=0 to i=n-1\n- because for $$nth$$ word we will check at $$n-1\'th$$ tearm\n- proceed further till we match in pair of $$words[i]$$ and $$words[i+1]$$\n- when not matched check $$current$$ $$alphabet$$ $$order$$ in $$words[i]$$ and $$words[i+1]$$\n- if it\'s not according to given order then return false\n- else at last return true\n\n# Code\n```\nclass Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n mapper = {chr(i):-1 for i in range(97,97+26)}\n def map_value():\n nonlocal order\n nonlocal mapper\n for i in range(len(order)):\n mapper[order[i]] = i\n map_value()\n def helper():\n for i in range(len(words)-1):\n if len(words[i+1])<len(words[i]) and mapper[words[i+1][0]] <= mapper[words[i][0]] and words[i+1] in words[i]:\n return False\n else:\n for j in range(min(len(words[i]), len(words[i+1]))):\n if words[i][j] != words[i+1][j]:\n if mapper[words[i+1][j]] < mapper[words[i][j]]:\n return False\n break\n return True\n return helper()\n``` | 3 | In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different `order`. The `order` of the alphabet is some permutation of lowercase letters.
Given a sequence of `words` written in the alien language, and the `order` of the alphabet, return `true` if and only if the given `words` are sorted lexicographically in this alien language.
**Example 1:**
**Input:** words = \[ "hello ", "leetcode "\], order = "hlabcdefgijkmnopqrstuvwxyz "
**Output:** true
**Explanation:** As 'h' comes before 'l' in this language, then the sequence is sorted.
**Example 2:**
**Input:** words = \[ "word ", "world ", "row "\], order = "worldabcefghijkmnpqstuvxyz "
**Output:** false
**Explanation:** As 'd' comes after 'l' in this language, then words\[0\] > words\[1\], hence the sequence is unsorted.
**Example 3:**
**Input:** words = \[ "apple ", "app "\], order = "abcdefghijklmnopqrstuvwxyz "
**Output:** false
**Explanation:** The first three characters "app " match, and the second string is shorter (in size.) According to lexicographical rules "apple " > "app ", because 'l' > '∅', where '∅' is defined as the blank character which is less than any other character ([More info](https://en.wikipedia.org/wiki/Lexicographical_order)).
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 20`
* `order.length == 26`
* All characters in `words[i]` and `order` are English lowercase letters. | This problem is exactly like reversing a normal string except that there are certain characters that we have to simply skip. That should be easy enough to do if you know how to reverse a string using the two-pointer approach. |
Python solution: explained in detail | verifying-an-alien-dictionary | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n- In lexicographically ordered dictionary we don\'t have any words less in value after greater.\n- So we don\'t need to traverse $$words$$ array $$n^2$$ times just check it for $$n$$ times.\n- if $$current word[i]$$ is greater in size of $$currentword[i+1]$$ and next word is having less value according to orders then return false\n- else check for every word pair in one iteration from i=0 to i=n-1\n- because for $$nth$$ word we will check at $$n-1\'th$$ tearm\n- proceed further till we match in pair of $$words[i]$$ and $$words[i+1]$$\n- when not matched check $$current$$ $$alphabet$$ $$order$$ in $$words[i]$$ and $$words[i+1]$$\n- if it\'s not according to given order then return false\n- else at last return true\n\n# Code\n```\nclass Solution:\n def isAlienSorted(self, words: List[str], order: str) -> bool:\n mapper = {chr(i):-1 for i in range(97,97+26)}\n def map_value():\n nonlocal order\n nonlocal mapper\n for i in range(len(order)):\n mapper[order[i]] = i\n map_value()\n def helper():\n for i in range(len(words)-1):\n if len(words[i+1])<len(words[i]) and mapper[words[i+1][0]] <= mapper[words[i][0]] and words[i+1] in words[i]:\n return False\n else:\n for j in range(min(len(words[i]), len(words[i+1]))):\n if words[i][j] != words[i+1][j]:\n if mapper[words[i+1][j]] < mapper[words[i][j]]:\n return False\n break\n return True\n return helper()\n``` | 3 | You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi "` or `"xi!=yi "`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names.
Return `true` _if it is possible to assign integers to variable names so as to satisfy all the given equations, or_ `false` _otherwise_.
**Example 1:**
**Input:** equations = \[ "a==b ", "b!=a "\]
**Output:** false
**Explanation:** If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
**Example 2:**
**Input:** equations = \[ "b==a ", "a==b "\]
**Output:** true
**Explanation:** We could assign a = 1 and b = 1 to satisfy both equations.
**Constraints:**
* `1 <= equations.length <= 500`
* `equations[i].length == 4`
* `equations[i][0]` is a lowercase letter.
* `equations[i][1]` is either `'='` or `'!'`.
* `equations[i][2]` is `'='`.
* `equations[i][3]` is a lowercase letter. | null |
Solution | array-of-doubled-pairs | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n bool canReorderDoubled(vector<int>& arr) {\n unordered_map<int,int> mp;\n for(int i: arr) mp[i]++;\n vector<int> k;\n for(auto x: mp) k.push_back(x.first);\n sort(k.begin(),k.end(),[](int a, int b){\n return abs(a) < abs(b);\n });\n for(int x:k){\n if(mp[x] > mp[2*x]) return false;\n mp[2*x] -= mp[x];\n }\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n freq = Counter(arr)\n pos = []\n neg = []\n zero = 0\n for k, v in freq.items():\n if k > 0:\n pos.append(k)\n elif k < 0:\n neg.append(k)\n else:\n zero = v\n if zero % 2 == 1:\n return False\n pos.sort()\n neg.sort(reverse=True)\n for x in pos:\n if freq[x] == 0:\n continue\n if 2 * x not in freq or freq[2 * x] < freq[x]:\n return False\n freq[2 * x] -= freq[x]\n for x in neg:\n if freq[x] == 0:\n continue\n if 2 * x not in freq or freq[2 * x] < freq[x]:\n return False\n freq[2 * x] -= freq[x]\n return True\n```\n\n```Java []\nimport java.util.*;\n\nclass Solution {\n public boolean canReorderDoubled(int[] arr) {\n int [] plus = new int [100011];\n int [] minus = new int [100011];\n for (int i : arr) {\n \tif (i>=0) {\n \t\tplus[i]++;\n \t} else {\n \t\tminus[-i]++;\n \t}\n }\n if (plus[0]%2!=0) return false;\n int res = arr.length-plus[0];\n for (int i = 1; i<plus.length/2; i++) {\n \tif (plus[i]>0) {\n \tplus[2*i]-=plus[i];\n \tres-=plus[i]*2;\n \tif (plus[2*i] <0) return false;\n \tplus[i] = 0;\n \t}\n }\n for (int i = 1; i<minus.length/2; i++) {\n \tif (minus[i]>0) {\n \tminus[2*i]-=minus[i];\n \tres-=minus[i]*2;\n \tif (minus[2*i] <0) return false;\n \tminus[i] = 0;\n \t}\n }\n if (res != 0) return false;\n return true;\n }\n}\n```\n | 2 | Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** arr = \[3,1,3,6\]
**Output:** false
**Example 2:**
**Input:** arr = \[2,1,2,6\]
**Output:** false
**Example 3:**
**Input:** arr = \[4,-2,2,-4\]
**Output:** true
**Explanation:** We can take two groups, \[-2,-4\] and \[2,4\] to form \[-2,-4,2,4\] or \[2,4,-2,-4\].
**Constraints:**
* `2 <= arr.length <= 3 * 104`
* `arr.length` is even.
* `-105 <= arr[i] <= 105` | For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you already have a great algorithm brewing up in your mind in which case, go right ahead! What is an alternate way of representing a circular array so that it appears to be a straight array?
Essentially, there are two cases of this problem that we need to take care of. Let's look at the figure below to understand those two cases: The first case can be handled by the good old Kadane's algorithm. However, is there a smarter way of going about handling the second case as well? |
Solution | array-of-doubled-pairs | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n bool canReorderDoubled(vector<int>& arr) {\n unordered_map<int,int> mp;\n for(int i: arr) mp[i]++;\n vector<int> k;\n for(auto x: mp) k.push_back(x.first);\n sort(k.begin(),k.end(),[](int a, int b){\n return abs(a) < abs(b);\n });\n for(int x:k){\n if(mp[x] > mp[2*x]) return false;\n mp[2*x] -= mp[x];\n }\n return true;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n freq = Counter(arr)\n pos = []\n neg = []\n zero = 0\n for k, v in freq.items():\n if k > 0:\n pos.append(k)\n elif k < 0:\n neg.append(k)\n else:\n zero = v\n if zero % 2 == 1:\n return False\n pos.sort()\n neg.sort(reverse=True)\n for x in pos:\n if freq[x] == 0:\n continue\n if 2 * x not in freq or freq[2 * x] < freq[x]:\n return False\n freq[2 * x] -= freq[x]\n for x in neg:\n if freq[x] == 0:\n continue\n if 2 * x not in freq or freq[2 * x] < freq[x]:\n return False\n freq[2 * x] -= freq[x]\n return True\n```\n\n```Java []\nimport java.util.*;\n\nclass Solution {\n public boolean canReorderDoubled(int[] arr) {\n int [] plus = new int [100011];\n int [] minus = new int [100011];\n for (int i : arr) {\n \tif (i>=0) {\n \t\tplus[i]++;\n \t} else {\n \t\tminus[-i]++;\n \t}\n }\n if (plus[0]%2!=0) return false;\n int res = arr.length-plus[0];\n for (int i = 1; i<plus.length/2; i++) {\n \tif (plus[i]>0) {\n \tplus[2*i]-=plus[i];\n \tres-=plus[i]*2;\n \tif (plus[2*i] <0) return false;\n \tplus[i] = 0;\n \t}\n }\n for (int i = 1; i<minus.length/2; i++) {\n \tif (minus[i]>0) {\n \tminus[2*i]-=minus[i];\n \tres-=minus[i]*2;\n \tif (minus[2*i] <0) return false;\n \tminus[i] = 0;\n \t}\n }\n if (res != 0) return false;\n return true;\n }\n}\n```\n | 2 | There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_.
**Example 1:**
**Input:** startValue = 2, target = 3
**Output:** 2
**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}.
**Example 2:**
**Input:** startValue = 5, target = 8
**Output:** 2
**Explanation:** Use decrement and then double {5 -> 4 -> 8}.
**Example 3:**
**Input:** startValue = 3, target = 10
**Output:** 3
**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}.
**Constraints:**
* `1 <= startValue, target <= 109` | null |
Python solution using Counter | array-of-doubled-pairs | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Keep a count of each number in the arr in counts.\n2. Sort the arr.\n3. For each number in arr:\n a. If count of number has become 0 then skip.\n b. If (number * 2) is present in counts then decrement number and (number * 2)\n4. At the end if count of all the numbers in counts has become 0 then return True else False.\n\n\n# Code\n```\nclass Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n counts = collections.Counter(arr)\n\n for num in sorted(arr, key=abs):\n if counts[num] == 0:\n continue\n if num*2 in counts:\n counts[num] -= 1\n counts[num*2] -= 1\n \n return all([True if counts[x] == 0 else False for x in counts])\n``` | 2 | Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** arr = \[3,1,3,6\]
**Output:** false
**Example 2:**
**Input:** arr = \[2,1,2,6\]
**Output:** false
**Example 3:**
**Input:** arr = \[4,-2,2,-4\]
**Output:** true
**Explanation:** We can take two groups, \[-2,-4\] and \[2,4\] to form \[-2,-4,2,4\] or \[2,4,-2,-4\].
**Constraints:**
* `2 <= arr.length <= 3 * 104`
* `arr.length` is even.
* `-105 <= arr[i] <= 105` | For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you already have a great algorithm brewing up in your mind in which case, go right ahead! What is an alternate way of representing a circular array so that it appears to be a straight array?
Essentially, there are two cases of this problem that we need to take care of. Let's look at the figure below to understand those two cases: The first case can be handled by the good old Kadane's algorithm. However, is there a smarter way of going about handling the second case as well? |
Python solution using Counter | array-of-doubled-pairs | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1. Keep a count of each number in the arr in counts.\n2. Sort the arr.\n3. For each number in arr:\n a. If count of number has become 0 then skip.\n b. If (number * 2) is present in counts then decrement number and (number * 2)\n4. At the end if count of all the numbers in counts has become 0 then return True else False.\n\n\n# Code\n```\nclass Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n counts = collections.Counter(arr)\n\n for num in sorted(arr, key=abs):\n if counts[num] == 0:\n continue\n if num*2 in counts:\n counts[num] -= 1\n counts[num*2] -= 1\n \n return all([True if counts[x] == 0 else False for x in counts])\n``` | 2 | There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_.
**Example 1:**
**Input:** startValue = 2, target = 3
**Output:** 2
**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}.
**Example 2:**
**Input:** startValue = 5, target = 8
**Output:** 2
**Explanation:** Use decrement and then double {5 -> 4 -> 8}.
**Example 3:**
**Input:** startValue = 3, target = 10
**Output:** 3
**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}.
**Constraints:**
* `1 <= startValue, target <= 109` | null |
From O(n*log n) to O(n) - 3 approaches summarized (updated) | array-of-doubled-pairs | 0 | 1 | ### Approach # 1 - Match using a hashmap\nProcess numbers in sorted order of the absolute value. Use a hashmap to remember what numbers (`2*x`) you expect to see. If you see an expected number, decrement its count, otherwise increment the count of the expected number (`2*x`). At the end all values in the expected hashmap should be zero.\n\n* Optimization: Since we expect to have 2*x for every x in the input, the sum of all the values should be a multiple of 3.\n \n* Time: `O(n * log n)`\n* Space: `O(n)`\n\n### Python \n\n``` \n def canReorderDoubled(self, arr: List[int]) -> bool:\n if sum(arr)%3 != 0: return False\n \n expected = defaultdict(int)\n for a in sorted(arr, key = abs):\n if expected[a] > 0:\n expected[a] -= 1\n else:\n expected[2*a] += 1\n \n return all(x == 0 for x in expected.values())\n```\n\n### Approach # 2 - Match using a frequency counter\n\nBasically the same underlying logic. Start with a frequency of all values in a hashmap. Match all duplicate values at once i.e. reduce frequency of `2*key` by frequency of `key`. If, at any point, we don\'t have enough `2*key` to match with `key`, we return `False`. At the end we can just return `True`, however the hashmap would still contain redundant values. Same running time as the first approach, except that this approach will run faster if there are many duplicates.\n\n* Time: `O(n * log n)`\n* Space: `O(n)`\n\n### Python\n```\n def canReorderDoubled(self, arr: List[int]) -> bool:\n if sum(arr)%3 != 0: return False\n counter = Counter(arr)\n for key in sorted(counter, key = abs):\n if counter[key] > counter[2*key]: return False\n counter[2*key] -= counter[key]\n return True\n```\n\n### Approach # 3 - Match all in groups, without sorting\nCredits to @g27as\nApproach is explained here: https://leetcode.com/problems/array-of-doubled-pairs/discuss/205960/JAVA-O(N)-time-O(N)-space-Solution\n\n### Summary:\nWe use sort in the first two approaches to deal with the confusion of matching even values, say `2*x` with `x` or `4*x`. E.g. if we encounter `2`, we don\'t know whether to match it with `1` or with `4`. Processing them in sorted order, we ensure that we always deal with smaller values first. So if we ever encounter `2`, we know `1` is already dealt with, so we always match with `4`.\n\nHowever, we can deal with this without having to sort the input or the keys of the hashmap, if we process such numbers in groups. If we have `1`, `2`, `4` and `8` in our hashmap and we encounter `4`, we reduce it to `1` and then start matching `1` to `2`, then `2` to `4` and then `4` to `8`. We do need to deal with `0` separately though, which is trivial.\n\n* `n = len(arr)` and `N = max(arr)`\n* Time: `O(n * log N)` in theory but practically runs as fast as `O(n)`\n* Space: `O(n)`\n\n```\n def canReorderDoubled(self, arr: List[int]) -> bool:\n if sum(arr)%3 != 0: return False\n counter = Counter(arr)\n \n if 0 in counter:\n if counter[0]%2: return False\n counter.pop(0)\n \n for num in list(counter.keys()):\n if num not in counter: \n continue\n while num % 2 == 0 and num//2 in counter: \n num = num // 2\n while counter[num] > 0 and 2*num in counter:\n counter[2*num] -= counter[num]\n counter.pop(num)\n num = 2*num\n if counter[num] != 0: return False\n\n return True\n```\n\n### Update\nHere is a slightly different implementation of the Approach#3. It is easy to argue that every entry in `counter` is popped exactly once and every iteration of the loop will pop at least one entry from `counter`. Hence this approach is `O(n)`.\n\n```\n def canReorderDoubled(self, arr: List[int]) -> bool:\n if sum(arr)%3 != 0: return False\n counter = Counter(arr)\n \n if 0 in counter:\n if counter[0]%2: return False\n counter.pop(0)\n \n while counter:\n num = next(iter(counter))\n while num % 2 == 0 and num//2 in counter: \n num = num // 2\n while counter[num] > 0 and 2*num in counter:\n counter[2*num] -= counter[num]\n counter.pop(num)\n num = 2*num\n if counter[num] != 0: return False\n counter.pop(num)\n\n return True\n```\n\n*The above indeed consistently runs faster than 100% all python3 submissions at the time of writing this.*\n | 10 | Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** arr = \[3,1,3,6\]
**Output:** false
**Example 2:**
**Input:** arr = \[2,1,2,6\]
**Output:** false
**Example 3:**
**Input:** arr = \[4,-2,2,-4\]
**Output:** true
**Explanation:** We can take two groups, \[-2,-4\] and \[2,4\] to form \[-2,-4,2,4\] or \[2,4,-2,-4\].
**Constraints:**
* `2 <= arr.length <= 3 * 104`
* `arr.length` is even.
* `-105 <= arr[i] <= 105` | For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you already have a great algorithm brewing up in your mind in which case, go right ahead! What is an alternate way of representing a circular array so that it appears to be a straight array?
Essentially, there are two cases of this problem that we need to take care of. Let's look at the figure below to understand those two cases: The first case can be handled by the good old Kadane's algorithm. However, is there a smarter way of going about handling the second case as well? |
From O(n*log n) to O(n) - 3 approaches summarized (updated) | array-of-doubled-pairs | 0 | 1 | ### Approach # 1 - Match using a hashmap\nProcess numbers in sorted order of the absolute value. Use a hashmap to remember what numbers (`2*x`) you expect to see. If you see an expected number, decrement its count, otherwise increment the count of the expected number (`2*x`). At the end all values in the expected hashmap should be zero.\n\n* Optimization: Since we expect to have 2*x for every x in the input, the sum of all the values should be a multiple of 3.\n \n* Time: `O(n * log n)`\n* Space: `O(n)`\n\n### Python \n\n``` \n def canReorderDoubled(self, arr: List[int]) -> bool:\n if sum(arr)%3 != 0: return False\n \n expected = defaultdict(int)\n for a in sorted(arr, key = abs):\n if expected[a] > 0:\n expected[a] -= 1\n else:\n expected[2*a] += 1\n \n return all(x == 0 for x in expected.values())\n```\n\n### Approach # 2 - Match using a frequency counter\n\nBasically the same underlying logic. Start with a frequency of all values in a hashmap. Match all duplicate values at once i.e. reduce frequency of `2*key` by frequency of `key`. If, at any point, we don\'t have enough `2*key` to match with `key`, we return `False`. At the end we can just return `True`, however the hashmap would still contain redundant values. Same running time as the first approach, except that this approach will run faster if there are many duplicates.\n\n* Time: `O(n * log n)`\n* Space: `O(n)`\n\n### Python\n```\n def canReorderDoubled(self, arr: List[int]) -> bool:\n if sum(arr)%3 != 0: return False\n counter = Counter(arr)\n for key in sorted(counter, key = abs):\n if counter[key] > counter[2*key]: return False\n counter[2*key] -= counter[key]\n return True\n```\n\n### Approach # 3 - Match all in groups, without sorting\nCredits to @g27as\nApproach is explained here: https://leetcode.com/problems/array-of-doubled-pairs/discuss/205960/JAVA-O(N)-time-O(N)-space-Solution\n\n### Summary:\nWe use sort in the first two approaches to deal with the confusion of matching even values, say `2*x` with `x` or `4*x`. E.g. if we encounter `2`, we don\'t know whether to match it with `1` or with `4`. Processing them in sorted order, we ensure that we always deal with smaller values first. So if we ever encounter `2`, we know `1` is already dealt with, so we always match with `4`.\n\nHowever, we can deal with this without having to sort the input or the keys of the hashmap, if we process such numbers in groups. If we have `1`, `2`, `4` and `8` in our hashmap and we encounter `4`, we reduce it to `1` and then start matching `1` to `2`, then `2` to `4` and then `4` to `8`. We do need to deal with `0` separately though, which is trivial.\n\n* `n = len(arr)` and `N = max(arr)`\n* Time: `O(n * log N)` in theory but practically runs as fast as `O(n)`\n* Space: `O(n)`\n\n```\n def canReorderDoubled(self, arr: List[int]) -> bool:\n if sum(arr)%3 != 0: return False\n counter = Counter(arr)\n \n if 0 in counter:\n if counter[0]%2: return False\n counter.pop(0)\n \n for num in list(counter.keys()):\n if num not in counter: \n continue\n while num % 2 == 0 and num//2 in counter: \n num = num // 2\n while counter[num] > 0 and 2*num in counter:\n counter[2*num] -= counter[num]\n counter.pop(num)\n num = 2*num\n if counter[num] != 0: return False\n\n return True\n```\n\n### Update\nHere is a slightly different implementation of the Approach#3. It is easy to argue that every entry in `counter` is popped exactly once and every iteration of the loop will pop at least one entry from `counter`. Hence this approach is `O(n)`.\n\n```\n def canReorderDoubled(self, arr: List[int]) -> bool:\n if sum(arr)%3 != 0: return False\n counter = Counter(arr)\n \n if 0 in counter:\n if counter[0]%2: return False\n counter.pop(0)\n \n while counter:\n num = next(iter(counter))\n while num % 2 == 0 and num//2 in counter: \n num = num // 2\n while counter[num] > 0 and 2*num in counter:\n counter[2*num] -= counter[num]\n counter.pop(num)\n num = 2*num\n if counter[num] != 0: return False\n counter.pop(num)\n\n return True\n```\n\n*The above indeed consistently runs faster than 100% all python3 submissions at the time of writing this.*\n | 10 | There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_.
**Example 1:**
**Input:** startValue = 2, target = 3
**Output:** 2
**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}.
**Example 2:**
**Input:** startValue = 5, target = 8
**Output:** 2
**Explanation:** Use decrement and then double {5 -> 4 -> 8}.
**Example 3:**
**Input:** startValue = 3, target = 10
**Output:** 3
**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}.
**Constraints:**
* `1 <= startValue, target <= 109` | null |
Simple Solution Using Dictionary | array-of-doubled-pairs | 0 | 1 | # Explanation\nFrom smallest to largest number (sort input array), check if we\'ve "seen" $$x/2$$ or $$2*x$$. Decrement the count at each encounter.\n\nAt the end of our count, the length of the input array should be twice the the number of pairs: $$count*2 == len(arr)$$\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n \n seen = defaultdict(int)\n count = 0\n\n for num in sorted(arr):\n\n if seen[2*num] > 0: \n count += 1\n seen[2*num] -= 1\n elif seen[num/2] > 0:\n count += 1\n seen[num/2] -= 1\n else:\n seen[num] += 1\n\n return count*2 == len(arr)\n``` | 0 | Given an integer array of even length `arr`, return `true` _if it is possible to reorder_ `arr` _such that_ `arr[2 * i + 1] = 2 * arr[2 * i]` _for every_ `0 <= i < len(arr) / 2`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** arr = \[3,1,3,6\]
**Output:** false
**Example 2:**
**Input:** arr = \[2,1,2,6\]
**Output:** false
**Example 3:**
**Input:** arr = \[4,-2,2,-4\]
**Output:** true
**Explanation:** We can take two groups, \[-2,-4\] and \[2,4\] to form \[-2,-4,2,4\] or \[2,4,-2,-4\].
**Constraints:**
* `2 <= arr.length <= 3 * 104`
* `arr.length` is even.
* `-105 <= arr[i] <= 105` | For those of you who are familiar with the Kadane's algorithm, think in terms of that. For the newbies, Kadane's algorithm is used to finding the maximum sum subarray from a given array. This problem is a twist on that idea and it is advisable to read up on that algorithm first before starting this problem. Unless you already have a great algorithm brewing up in your mind in which case, go right ahead! What is an alternate way of representing a circular array so that it appears to be a straight array?
Essentially, there are two cases of this problem that we need to take care of. Let's look at the figure below to understand those two cases: The first case can be handled by the good old Kadane's algorithm. However, is there a smarter way of going about handling the second case as well? |
Simple Solution Using Dictionary | array-of-doubled-pairs | 0 | 1 | # Explanation\nFrom smallest to largest number (sort input array), check if we\'ve "seen" $$x/2$$ or $$2*x$$. Decrement the count at each encounter.\n\nAt the end of our count, the length of the input array should be twice the the number of pairs: $$count*2 == len(arr)$$\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nfrom collections import defaultdict\n\nclass Solution:\n def canReorderDoubled(self, arr: List[int]) -> bool:\n \n seen = defaultdict(int)\n count = 0\n\n for num in sorted(arr):\n\n if seen[2*num] > 0: \n count += 1\n seen[2*num] -= 1\n elif seen[num/2] > 0:\n count += 1\n seen[num/2] -= 1\n else:\n seen[num] += 1\n\n return count*2 == len(arr)\n``` | 0 | There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can:
* multiply the number on display by `2`, or
* subtract `1` from the number on display.
Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_.
**Example 1:**
**Input:** startValue = 2, target = 3
**Output:** 2
**Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}.
**Example 2:**
**Input:** startValue = 5, target = 8
**Output:** 2
**Explanation:** Use decrement and then double {5 -> 4 -> 8}.
**Example 3:**
**Input:** startValue = 3, target = 10
**Output:** 3
**Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}.
**Constraints:**
* `1 <= startValue, target <= 109` | null |
Solution | delete-columns-to-make-sorted-ii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minDeletionSize(vector<string>& strs) {\n auto strsLength = strs.size();\n auto strLength = strs[0].size();\n\n auto sortedStrs = vector<string>(strsLength, "");\n\n for (size_t i = 0u; i < strLength; ++i) {\n for (size_t j = 0u; j < strsLength; ++j) {\n sortedStrs[j] += strs[j][i];\n }\n auto prev = sortedStrs[0];\n auto sortStatus = 1;\n for (size_t j = 1u; j < sortedStrs.size(); ++j) {\n const auto current = sortedStrs[j];\n if (prev > current) {\n sortStatus = -1;\n break;\n } else if (prev == current) {\n sortStatus = 0;\n }\n prev = current;\n }\n if (sortStatus == -1) {\n for (int j = 0; j < strsLength; j++) {\n sortedStrs[j].pop_back();\n }\n } else if (sortStatus == 1) {\n return i - sortedStrs[0].size() + 1;\n }\n }\n return strLength - sortedStrs[0].size();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0])\n res = 0\n unsorted = set(range(m - 1))\n for j in range(n):\n if any(strs[i][j] > strs[i+1][j] for i in unsorted):\n res += 1\n else:\n unsorted -= {i for i in unsorted if strs[i][j] < strs[i+1][j]}\n return res\n```\n\n```Java []\nclass Solution {\n public int minDeletionSize(String[] strs) {\n int cnt=0,j=0;\n boolean compared[]=new boolean[strs.length];\n for(int i=0;i<strs[0].length();i++){\n boolean currCompared[]=new boolean[strs.length];\n for(j=0;j<strs.length-1;j++){\n if(!compared[j]){ \n if(strs[j].charAt(i)>strs[j+1].charAt(i)){\n cnt++;\n break;\n }\n else if(strs[j].charAt(i)<strs[j+1].charAt(i))\n currCompared[j]=true;\n }\n }\n if(j==strs.length-1)\n for(;j>0;j--) compared[j-1]|=currCompared[j-1];\n }\n return cnt;\n }\n}\n```\n | 2 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has its elements in **lexicographic** order (i.e., `strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]`). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "ca ", "bb ", "ac "\]
**Output:** 1
**Explanation:**
After deleting the first column, strs = \[ "a ", "b ", "c "\].
Now strs is in lexicographic order (ie. strs\[0\] <= strs\[1\] <= strs\[2\]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
**Example 2:**
**Input:** strs = \[ "xc ", "yb ", "za "\]
**Output:** 0
**Explanation:**
strs is already in lexicographic order, so we do not need to delete anything.
Note that the rows of strs are not necessarily in lexicographic order:
i.e., it is NOT necessarily true that (strs\[0\]\[0\] <= strs\[0\]\[1\] <= ...)
**Example 3:**
**Input:** strs = \[ "zyx ", "wvu ", "tsr "\]
**Output:** 3
**Explanation:** We have to delete every column.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Solution | delete-columns-to-make-sorted-ii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minDeletionSize(vector<string>& strs) {\n auto strsLength = strs.size();\n auto strLength = strs[0].size();\n\n auto sortedStrs = vector<string>(strsLength, "");\n\n for (size_t i = 0u; i < strLength; ++i) {\n for (size_t j = 0u; j < strsLength; ++j) {\n sortedStrs[j] += strs[j][i];\n }\n auto prev = sortedStrs[0];\n auto sortStatus = 1;\n for (size_t j = 1u; j < sortedStrs.size(); ++j) {\n const auto current = sortedStrs[j];\n if (prev > current) {\n sortStatus = -1;\n break;\n } else if (prev == current) {\n sortStatus = 0;\n }\n prev = current;\n }\n if (sortStatus == -1) {\n for (int j = 0; j < strsLength; j++) {\n sortedStrs[j].pop_back();\n }\n } else if (sortStatus == 1) {\n return i - sortedStrs[0].size() + 1;\n }\n }\n return strLength - sortedStrs[0].size();\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0])\n res = 0\n unsorted = set(range(m - 1))\n for j in range(n):\n if any(strs[i][j] > strs[i+1][j] for i in unsorted):\n res += 1\n else:\n unsorted -= {i for i in unsorted if strs[i][j] < strs[i+1][j]}\n return res\n```\n\n```Java []\nclass Solution {\n public int minDeletionSize(String[] strs) {\n int cnt=0,j=0;\n boolean compared[]=new boolean[strs.length];\n for(int i=0;i<strs[0].length();i++){\n boolean currCompared[]=new boolean[strs.length];\n for(j=0;j<strs.length-1;j++){\n if(!compared[j]){ \n if(strs[j].charAt(i)>strs[j+1].charAt(i)){\n cnt++;\n break;\n }\n else if(strs[j].charAt(i)<strs[j+1].charAt(i))\n currCompared[j]=true;\n }\n }\n if(j==strs.length-1)\n for(;j>0;j--) compared[j-1]|=currCompared[j-1];\n }\n return cnt;\n }\n}\n```\n | 2 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,2,1,2,3\], k = 2
**Output:** 7
**Explanation:** Subarrays formed with exactly 2 different integers: \[1,2\], \[2,1\], \[1,2\], \[2,3\], \[1,2,1\], \[2,1,2\], \[1,2,1,2\]
**Example 2:**
**Input:** nums = \[1,2,1,3,4\], k = 3
**Output:** 3
**Explanation:** Subarrays formed with exactly 3 different integers: \[1,2,1,3\], \[2,1,3\], \[1,3,4\].
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i], k <= nums.length` | null |
Python 3 || 6 lines, w/ explanation || T/M: 81% / 87% | delete-columns-to-make-sorted-ii | 0 | 1 | Here\'s the plan:\n\nWe start with a blank slate and build each of the elements of `strs` uniformly, character by character, as long as`strs` remains lexographically correct.\n```\nclass Solution: \n def minDeletionSize(self, strs: List[str]) -> int:\n\n tpse, n, m = zip(*strs), len(strs), len(strs[0])\n strs = [\'\'] * n\n\n for nxt in tpse:\n temp = [strs[i]+nxt[i] for i in range(n)]\n if temp == sorted(temp): strs = temp\n \n return m - len(strs[0])\n```\n[](http://)\n\nI could be wrong, but I think that time complexity is *O*(*MN* log*M*) and space complexity is *O*(*MN*), , in which *M* ~ `len(strs[0])` and *N* ~ `len(strs)`. | 4 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has its elements in **lexicographic** order (i.e., `strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]`). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "ca ", "bb ", "ac "\]
**Output:** 1
**Explanation:**
After deleting the first column, strs = \[ "a ", "b ", "c "\].
Now strs is in lexicographic order (ie. strs\[0\] <= strs\[1\] <= strs\[2\]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
**Example 2:**
**Input:** strs = \[ "xc ", "yb ", "za "\]
**Output:** 0
**Explanation:**
strs is already in lexicographic order, so we do not need to delete anything.
Note that the rows of strs are not necessarily in lexicographic order:
i.e., it is NOT necessarily true that (strs\[0\]\[0\] <= strs\[0\]\[1\] <= ...)
**Example 3:**
**Input:** strs = \[ "zyx ", "wvu ", "tsr "\]
**Output:** 3
**Explanation:** We have to delete every column.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Python 3 || 6 lines, w/ explanation || T/M: 81% / 87% | delete-columns-to-make-sorted-ii | 0 | 1 | Here\'s the plan:\n\nWe start with a blank slate and build each of the elements of `strs` uniformly, character by character, as long as`strs` remains lexographically correct.\n```\nclass Solution: \n def minDeletionSize(self, strs: List[str]) -> int:\n\n tpse, n, m = zip(*strs), len(strs), len(strs[0])\n strs = [\'\'] * n\n\n for nxt in tpse:\n temp = [strs[i]+nxt[i] for i in range(n)]\n if temp == sorted(temp): strs = temp\n \n return m - len(strs[0])\n```\n[](http://)\n\nI could be wrong, but I think that time complexity is *O*(*MN* log*M*) and space complexity is *O*(*MN*), , in which *M* ~ `len(strs[0])` and *N* ~ `len(strs)`. | 4 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,2,1,2,3\], k = 2
**Output:** 7
**Explanation:** Subarrays formed with exactly 2 different integers: \[1,2\], \[2,1\], \[1,2\], \[2,3\], \[1,2,1\], \[2,1,2\], \[1,2,1,2\]
**Example 2:**
**Input:** nums = \[1,2,1,3,4\], k = 3
**Output:** 3
**Explanation:** Subarrays formed with exactly 3 different integers: \[1,2,1,3\], \[2,1,3\], \[1,3,4\].
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i], k <= nums.length` | null |
Python3 | Beats 100% | O(n * str_len) | delete-columns-to-make-sorted-ii | 0 | 1 | # Complexity\n- Time complexity:\n$$ O(n * len(strs[0])) $$\n\n\n# Code\n```\nfrom typing import List\n\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n ans = 0\n not_okay_set = set[int](range(len(strs)))\n i = 0\n while i < len(strs[0]):\n column_okay = True\n new_not_okay_set = set[int]()\n for j in not_okay_set:\n if j + 1 < len(strs) and strs[j][i] > strs[j + 1][i]:\n column_okay = False\n break\n elif j + 1 < len(strs) and strs[j][i] == strs[j + 1][i]:\n new_not_okay_set.add(j)\n if not column_okay:\n ans += 1\n else:\n if len(new_not_okay_set) == 0:\n return ans\n not_okay_set = new_not_okay_set\n i += 1\n return ans\n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has its elements in **lexicographic** order (i.e., `strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]`). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "ca ", "bb ", "ac "\]
**Output:** 1
**Explanation:**
After deleting the first column, strs = \[ "a ", "b ", "c "\].
Now strs is in lexicographic order (ie. strs\[0\] <= strs\[1\] <= strs\[2\]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
**Example 2:**
**Input:** strs = \[ "xc ", "yb ", "za "\]
**Output:** 0
**Explanation:**
strs is already in lexicographic order, so we do not need to delete anything.
Note that the rows of strs are not necessarily in lexicographic order:
i.e., it is NOT necessarily true that (strs\[0\]\[0\] <= strs\[0\]\[1\] <= ...)
**Example 3:**
**Input:** strs = \[ "zyx ", "wvu ", "tsr "\]
**Output:** 3
**Explanation:** We have to delete every column.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Python3 | Beats 100% | O(n * str_len) | delete-columns-to-make-sorted-ii | 0 | 1 | # Complexity\n- Time complexity:\n$$ O(n * len(strs[0])) $$\n\n\n# Code\n```\nfrom typing import List\n\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n ans = 0\n not_okay_set = set[int](range(len(strs)))\n i = 0\n while i < len(strs[0]):\n column_okay = True\n new_not_okay_set = set[int]()\n for j in not_okay_set:\n if j + 1 < len(strs) and strs[j][i] > strs[j + 1][i]:\n column_okay = False\n break\n elif j + 1 < len(strs) and strs[j][i] == strs[j + 1][i]:\n new_not_okay_set.add(j)\n if not column_okay:\n ans += 1\n else:\n if len(new_not_okay_set) == 0:\n return ans\n not_okay_set = new_not_okay_set\n i += 1\n return ans\n``` | 0 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,2,1,2,3\], k = 2
**Output:** 7
**Explanation:** Subarrays formed with exactly 2 different integers: \[1,2\], \[2,1\], \[1,2\], \[2,3\], \[1,2,1\], \[2,1,2\], \[1,2,1,2\]
**Example 2:**
**Input:** nums = \[1,2,1,3,4\], k = 3
**Output:** 3
**Explanation:** Subarrays formed with exactly 3 different integers: \[1,2,1,3\], \[2,1,3\], \[1,3,4\].
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i], k <= nums.length` | null |
Python Greedy Solution | delete-columns-to-make-sorted-ii | 0 | 1 | ```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m = len(strs)\n n = len(strs[0])\n\n cur = ["" for i in range(m)]\n res = 0\n\n for i in range(n):\n temp = [x for x in cur]\n valid = True\n \n temp[0] += strs[0][i]\n for j in range(1,m):\n temp[j] += strs[j][i]\n if temp[j] < temp[j-1]:\n res += 1\n valid = False\n break\n \n if valid:cur = temp\n \n return res\n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has its elements in **lexicographic** order (i.e., `strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]`). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "ca ", "bb ", "ac "\]
**Output:** 1
**Explanation:**
After deleting the first column, strs = \[ "a ", "b ", "c "\].
Now strs is in lexicographic order (ie. strs\[0\] <= strs\[1\] <= strs\[2\]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
**Example 2:**
**Input:** strs = \[ "xc ", "yb ", "za "\]
**Output:** 0
**Explanation:**
strs is already in lexicographic order, so we do not need to delete anything.
Note that the rows of strs are not necessarily in lexicographic order:
i.e., it is NOT necessarily true that (strs\[0\]\[0\] <= strs\[0\]\[1\] <= ...)
**Example 3:**
**Input:** strs = \[ "zyx ", "wvu ", "tsr "\]
**Output:** 3
**Explanation:** We have to delete every column.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Python Greedy Solution | delete-columns-to-make-sorted-ii | 0 | 1 | ```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m = len(strs)\n n = len(strs[0])\n\n cur = ["" for i in range(m)]\n res = 0\n\n for i in range(n):\n temp = [x for x in cur]\n valid = True\n \n temp[0] += strs[0][i]\n for j in range(1,m):\n temp[j] += strs[j][i]\n if temp[j] < temp[j-1]:\n res += 1\n valid = False\n break\n \n if valid:cur = temp\n \n return res\n``` | 0 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,2,1,2,3\], k = 2
**Output:** 7
**Explanation:** Subarrays formed with exactly 2 different integers: \[1,2\], \[2,1\], \[1,2\], \[2,3\], \[1,2,1\], \[2,1,2\], \[1,2,1,2\]
**Example 2:**
**Input:** nums = \[1,2,1,3,4\], k = 3
**Output:** 3
**Explanation:** Subarrays formed with exactly 3 different integers: \[1,2,1,3\], \[2,1,3\], \[1,3,4\].
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i], k <= nums.length` | null |
Python3 🐍 concise solution beats 99% | delete-columns-to-make-sorted-ii | 0 | 1 | # Code\n```\nclass Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n m, n = len(A), len(A[0])\n ans, in_order = 0, [False] * (m-1)\n for j in range(n):\n tmp_in_order = in_order[:]\n for i in range(m-1):\n\t\t\t\t# previous step, rows are not in order; and current step rows are not in order, remove this column\n if not in_order[i] and A[i][j] > A[i+1][j]: ans += 1; break \n\t\t\t\t# previous step, rows are not in order, but they are in order now\n elif A[i][j] < A[i+1][j] and not in_order[i]: tmp_in_order[i] = True\n\t\t\t# if column wasn\'t removed, update the row order information\n else: in_order = tmp_in_order \n # not necessary, but speed things up\n if all(in_order): return ans \n return ans\n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has its elements in **lexicographic** order (i.e., `strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]`). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "ca ", "bb ", "ac "\]
**Output:** 1
**Explanation:**
After deleting the first column, strs = \[ "a ", "b ", "c "\].
Now strs is in lexicographic order (ie. strs\[0\] <= strs\[1\] <= strs\[2\]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
**Example 2:**
**Input:** strs = \[ "xc ", "yb ", "za "\]
**Output:** 0
**Explanation:**
strs is already in lexicographic order, so we do not need to delete anything.
Note that the rows of strs are not necessarily in lexicographic order:
i.e., it is NOT necessarily true that (strs\[0\]\[0\] <= strs\[0\]\[1\] <= ...)
**Example 3:**
**Input:** strs = \[ "zyx ", "wvu ", "tsr "\]
**Output:** 3
**Explanation:** We have to delete every column.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Python3 🐍 concise solution beats 99% | delete-columns-to-make-sorted-ii | 0 | 1 | # Code\n```\nclass Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n m, n = len(A), len(A[0])\n ans, in_order = 0, [False] * (m-1)\n for j in range(n):\n tmp_in_order = in_order[:]\n for i in range(m-1):\n\t\t\t\t# previous step, rows are not in order; and current step rows are not in order, remove this column\n if not in_order[i] and A[i][j] > A[i+1][j]: ans += 1; break \n\t\t\t\t# previous step, rows are not in order, but they are in order now\n elif A[i][j] < A[i+1][j] and not in_order[i]: tmp_in_order[i] = True\n\t\t\t# if column wasn\'t removed, update the row order information\n else: in_order = tmp_in_order \n # not necessary, but speed things up\n if all(in_order): return ans \n return ans\n``` | 0 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,2,1,2,3\], k = 2
**Output:** 7
**Explanation:** Subarrays formed with exactly 2 different integers: \[1,2\], \[2,1\], \[1,2\], \[2,3\], \[1,2,1\], \[2,1,2\], \[1,2,1,2\]
**Example 2:**
**Input:** nums = \[1,2,1,3,4\], k = 3
**Output:** 3
**Explanation:** Subarrays formed with exactly 3 different integers: \[1,2,1,3\], \[2,1,3\], \[1,3,4\].
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i], k <= nums.length` | null |
Python 3 | Greedy, DP (28 ms) | Explanation | delete-columns-to-make-sorted-ii | 0 | 1 | ### Explanation\n- This idea is simple but there are some thing we need to be careful about\n- For each column, if we found any row pairs `(i, i+1)` not in order, then we need to remove this column\n\t- but we do this only if their previous column is not in order, e.g.\n\t- There is a tie in column 1, so we can\'t say they are in order, then we compare column 2 \n\t\t- `ak`\n\t\t- `ab`\n\t- There is no tie in column 1, we don\'t care about column 2\n\t\t- `ak`\n\t\t- `bb`\n\t- use `in_order` to store relation between rows\n### Implementation\n```\nclass Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n m, n = len(A), len(A[0])\n ans, in_order = 0, [False] * (m-1)\n for j in range(n):\n tmp_in_order = in_order[:]\n for i in range(m-1):\n\t\t\t\t# previous step, rows are not in order; and current step rows are not in order, remove this column\n if not in_order[i] and A[i][j] > A[i+1][j]: ans += 1; break \n\t\t\t\t# previous step, rows are not in order, but they are in order now\n elif A[i][j] < A[i+1][j] and not in_order[i]: tmp_in_order[i] = True\n\t\t\t# if column wasn\'t removed, update the row order information\n else: in_order = tmp_in_order \n # not necessary, but speed things up\n if all(in_order): return ans \n return ans\n``` | 8 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has its elements in **lexicographic** order (i.e., `strs[0] <= strs[1] <= strs[2] <= ... <= strs[n - 1]`). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "ca ", "bb ", "ac "\]
**Output:** 1
**Explanation:**
After deleting the first column, strs = \[ "a ", "b ", "c "\].
Now strs is in lexicographic order (ie. strs\[0\] <= strs\[1\] <= strs\[2\]).
We require at least 1 deletion since initially strs was not in lexicographic order, so the answer is 1.
**Example 2:**
**Input:** strs = \[ "xc ", "yb ", "za "\]
**Output:** 0
**Explanation:**
strs is already in lexicographic order, so we do not need to delete anything.
Note that the rows of strs are not necessarily in lexicographic order:
i.e., it is NOT necessarily true that (strs\[0\]\[0\] <= strs\[0\]\[1\] <= ...)
**Example 3:**
**Input:** strs = \[ "zyx ", "wvu ", "tsr "\]
**Output:** 3
**Explanation:** We have to delete every column.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Python 3 | Greedy, DP (28 ms) | Explanation | delete-columns-to-make-sorted-ii | 0 | 1 | ### Explanation\n- This idea is simple but there are some thing we need to be careful about\n- For each column, if we found any row pairs `(i, i+1)` not in order, then we need to remove this column\n\t- but we do this only if their previous column is not in order, e.g.\n\t- There is a tie in column 1, so we can\'t say they are in order, then we compare column 2 \n\t\t- `ak`\n\t\t- `ab`\n\t- There is no tie in column 1, we don\'t care about column 2\n\t\t- `ak`\n\t\t- `bb`\n\t- use `in_order` to store relation between rows\n### Implementation\n```\nclass Solution:\n def minDeletionSize(self, A: List[str]) -> int:\n m, n = len(A), len(A[0])\n ans, in_order = 0, [False] * (m-1)\n for j in range(n):\n tmp_in_order = in_order[:]\n for i in range(m-1):\n\t\t\t\t# previous step, rows are not in order; and current step rows are not in order, remove this column\n if not in_order[i] and A[i][j] > A[i+1][j]: ans += 1; break \n\t\t\t\t# previous step, rows are not in order, but they are in order now\n elif A[i][j] < A[i+1][j] and not in_order[i]: tmp_in_order[i] = True\n\t\t\t# if column wasn\'t removed, update the row order information\n else: in_order = tmp_in_order \n # not necessary, but speed things up\n if all(in_order): return ans \n return ans\n``` | 8 | Given an integer array `nums` and an integer `k`, return _the number of **good subarrays** of_ `nums`.
A **good array** is an array where the number of different integers in that array is exactly `k`.
* For example, `[1,2,3,1,2]` has `3` different integers: `1`, `2`, and `3`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1,2,1,2,3\], k = 2
**Output:** 7
**Explanation:** Subarrays formed with exactly 2 different integers: \[1,2\], \[2,1\], \[1,2\], \[2,3\], \[1,2,1\], \[2,1,2\], \[1,2,1,2\]
**Example 2:**
**Input:** nums = \[1,2,1,3,4\], k = 3
**Output:** 3
**Explanation:** Subarrays formed with exactly 3 different integers: \[1,2,1,3\], \[2,1,3\], \[1,3,4\].
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i], k <= nums.length` | null |
Solution | tallest-billboard | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int tallestBillboard(vector<int>& rods) {\n int sum = 0;\n for (int rod : rods) {\n sum += rod;\n }\n int dp[sum + 1];\n dp[0] = 0;\n for (int i = 1; i <= sum; i++) {\n dp[i] = -1;\n }\n for (int rod : rods) {\n int dpCopy[sum + 1];\n copy(dp, dp + (sum + 1), dpCopy);\n for (int i = 0; i <= sum - rod; i++) {\n if (dpCopy[i] < 0) continue;\n dp[i + rod] = max(dp[i + rod], dpCopy[i]);\n dp[abs(i - rod)] = max(dp[abs(i - rod)], dpCopy[i] + min(i, rod));\n }\n }\n return dp[0];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def tallestBillboard(self, rods: list[int]) -> int:\n def diff_h(rods: list[int]) -> dict[int, int]:\n dh = {0: 0}\n for rod in rods:\n for d, h in list(dh.items()):\n dh[d + rod] = max(dh.get(d + rod, 0), h)\n dh[abs(d - rod)] = max(dh.get(abs(d - rod), 0), h + min(d, rod))\n return dh\n\n d1, d2 = diff_h(rods[: len(rods) // 2]), diff_h(rods[len(rods) // 2 :])\n return max(v1 + d2[k1] + k1 for k1, v1 in d1.items() if k1 in d2)\n```\n\n```Java []\nclass Solution {\n public int tallestBillboard(int[] rods) {\n int sum = 0;\n for (int rod : rods) {\n sum += rod;\n }\n int[][] dp = new int[rods.length + 1][sum + 1];\n for (int i = 1; i <= rods.length; i++) {\n for (int j = 0; j <= sum; j++) {\n if (dp[i - 1][j] < j) {\n continue;\n }\n dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);\n int k = j + rods[i - 1];\n dp[i][k] = Math.max(dp[i][k], dp[i - 1][j] + rods[i - 1]);\n k = Math.abs(j - rods[i - 1]);\n dp[i][k] = Math.max(dp[i][k], dp[i - 1][j] + rods[i - 1]);\n }\n }\n return dp[rods.length][0] / 2;\n }\n}\n```\n | 440 | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000` | null |
Solution | tallest-billboard | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int tallestBillboard(vector<int>& rods) {\n int sum = 0;\n for (int rod : rods) {\n sum += rod;\n }\n int dp[sum + 1];\n dp[0] = 0;\n for (int i = 1; i <= sum; i++) {\n dp[i] = -1;\n }\n for (int rod : rods) {\n int dpCopy[sum + 1];\n copy(dp, dp + (sum + 1), dpCopy);\n for (int i = 0; i <= sum - rod; i++) {\n if (dpCopy[i] < 0) continue;\n dp[i + rod] = max(dp[i + rod], dpCopy[i]);\n dp[abs(i - rod)] = max(dp[abs(i - rod)], dpCopy[i] + min(i, rod));\n }\n }\n return dp[0];\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def tallestBillboard(self, rods: list[int]) -> int:\n def diff_h(rods: list[int]) -> dict[int, int]:\n dh = {0: 0}\n for rod in rods:\n for d, h in list(dh.items()):\n dh[d + rod] = max(dh.get(d + rod, 0), h)\n dh[abs(d - rod)] = max(dh.get(abs(d - rod), 0), h + min(d, rod))\n return dh\n\n d1, d2 = diff_h(rods[: len(rods) // 2]), diff_h(rods[len(rods) // 2 :])\n return max(v1 + d2[k1] + k1 for k1, v1 in d1.items() if k1 in d2)\n```\n\n```Java []\nclass Solution {\n public int tallestBillboard(int[] rods) {\n int sum = 0;\n for (int rod : rods) {\n sum += rod;\n }\n int[][] dp = new int[rods.length + 1][sum + 1];\n for (int i = 1; i <= rods.length; i++) {\n for (int j = 0; j <= sum; j++) {\n if (dp[i - 1][j] < j) {\n continue;\n }\n dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);\n int k = j + rods[i - 1];\n dp[i][k] = Math.max(dp[i][k], dp[i - 1][j] + rods[i - 1]);\n k = Math.abs(j - rods[i - 1]);\n dp[i][k] = Math.max(dp[i][k], dp[i - 1][j] + rods[i - 1]);\n }\n }\n return dp[rods.length][0] / 2;\n }\n}\n```\n | 440 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree. | null |
[Python3] Clean & Concise, DP Top-down Memoization with Cache | tallest-billboard | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can have `dp(i, left, right)`, and the recurrence relationship will be:\n1. adding to the left side `dp(i + 1, left + rods[i], right)`\n2. or, adding to the right `dp(i + 1, left, right + rods[i])`\n3. or, skip `dp(i + 1, left, right)`\n\nHowever, this will give us a worst case of dp[200][5000][5000], and cause TLE\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo, do we really need to store both left and right? Instead, we can store the delta (d) `left - right`. This would reduce the time complexity to `O(200 * 5000)`.\n\nNow, we have `dp(i, d) = max(left)` represents the maximum length of the left support. And the recurrence relationship will be:\n1. adding to the left side `rods[i] + dp(i + 1, d + rods[i])`\n2. or, adding to the right `dp(i + 1, d - rods[i])`\n3. or skip `dp(i + 1, d)`\n\n# Complexity\n- Time complexity: $$O(n * sum)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n @lru_cache(None)\n def dp(i, d):\n if i == len(rods): return 0 if d == 0 else -inf\n return max(dp(i + 1, d), rods[i] + dp(i + 1, d + rods[i]), dp(i + 1, d - rods[i]))\n return dp(0, 0)\n\n \n``` | 1 | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000` | null |
[Python3] Clean & Concise, DP Top-down Memoization with Cache | tallest-billboard | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can have `dp(i, left, right)`, and the recurrence relationship will be:\n1. adding to the left side `dp(i + 1, left + rods[i], right)`\n2. or, adding to the right `dp(i + 1, left, right + rods[i])`\n3. or, skip `dp(i + 1, left, right)`\n\nHowever, this will give us a worst case of dp[200][5000][5000], and cause TLE\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo, do we really need to store both left and right? Instead, we can store the delta (d) `left - right`. This would reduce the time complexity to `O(200 * 5000)`.\n\nNow, we have `dp(i, d) = max(left)` represents the maximum length of the left support. And the recurrence relationship will be:\n1. adding to the left side `rods[i] + dp(i + 1, d + rods[i])`\n2. or, adding to the right `dp(i + 1, d - rods[i])`\n3. or skip `dp(i + 1, d)`\n\n# Complexity\n- Time complexity: $$O(n * sum)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n @lru_cache(None)\n def dp(i, d):\n if i == len(rods): return 0 if d == 0 else -inf\n return max(dp(i + 1, d), rods[i] + dp(i + 1, d + rods[i]), dp(i + 1, d - rods[i]))\n return dp(0, 0)\n\n \n``` | 1 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree. | null |
SIMPLE PYTHON SOLUTION USING DP | tallest-billboard | 0 | 1 | \n# Code\n```\nclass Solution:\n def dp(self,i,rods,sm,dct):\n if i<0:\n if sm==0:\n return 0\n return float("-infinity")\n if (i,sm) in dct:\n return dct[(i,sm)]\n x=self.dp(i-1,rods,sm-rods[i],dct)\n y=self.dp(i-1,rods,sm+rods[i],dct)+rods[i]\n z=self.dp(i-1,rods,sm,dct)\n dct[(i,sm)]=max(x,y,z)\n return max(x,y,z)\n\n def tallestBillboard(self, rods: List[int]) -> int:\n n=len(rods)\n x=self.dp(n-1,rods,0,{})\n if x==float("-infinity"):\n return 0\n return x\n``` | 1 | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000` | null |
SIMPLE PYTHON SOLUTION USING DP | tallest-billboard | 0 | 1 | \n# Code\n```\nclass Solution:\n def dp(self,i,rods,sm,dct):\n if i<0:\n if sm==0:\n return 0\n return float("-infinity")\n if (i,sm) in dct:\n return dct[(i,sm)]\n x=self.dp(i-1,rods,sm-rods[i],dct)\n y=self.dp(i-1,rods,sm+rods[i],dct)+rods[i]\n z=self.dp(i-1,rods,sm,dct)\n dct[(i,sm)]=max(x,y,z)\n return max(x,y,z)\n\n def tallestBillboard(self, rods: List[int]) -> int:\n n=len(rods)\n x=self.dp(n-1,rods,0,{})\n if x==float("-infinity"):\n return 0\n return x\n``` | 1 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree. | null |
sort best solution in python code Plz🔥🧐👍 Upvoted👍👍👍 | tallest-billboard | 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 tallestBillboard(self, rods: List[int]) -> int:\n dict1 = {0: 0}\n for r in rods:\n newDP = {}\n for k, v in dict1.items():\n newDP[k + r] = max(newDP.get(k + r, 0), v + r)\n newDP[k] = max(newDP.get(k, 0), v)\n newDP[k - r] = max(newDP.get(k - r, 0), v)\n dict1 = newDP\n return dict1[0]\n``` | 1 | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000` | null |
sort best solution in python code Plz🔥🧐👍 Upvoted👍👍👍 | tallest-billboard | 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 tallestBillboard(self, rods: List[int]) -> int:\n dict1 = {0: 0}\n for r in rods:\n newDP = {}\n for k, v in dict1.items():\n newDP[k + r] = max(newDP.get(k + r, 0), v + r)\n newDP[k] = max(newDP.get(k, 0), v)\n newDP[k - r] = max(newDP.get(k - r, 0), v)\n dict1 = newDP\n return dict1[0]\n``` | 1 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree. | null |
Clear Explanation with Dynamic Programming Solution | tallest-billboard | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we want the height of the left and right towers to be equal, we need to find a \n\n\n\n\n\n\n\nconfiguration of the rods such that the difference between the left tower and right tower is 0 and maximize that height. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI\'m not going to lie, my first intution was to use binary search for a range of heights and use a helper method to calculate if a given height was possible to construct out of the rods. But this solution has an exponential time complexity and frankly it is very difficult to implement. \n\nFor each rod, we can either add it to the left tower, the right tower, or not consider it at all. For each rod, we have three decisions. Therefore a bruteforce solution would have a complexity of O(3^n) which is very high. \n\nYou should note that for a valid billboard, the left and right tower will have the same height and therefore the difference in their height is 0.\n\nLet\'s say that we know the tallest left tower we can build with a height difference of ```diff```. For a particular rod ```rod```, we can either add it to the left tower which would increase the difference to ```diff + rod``` and the tallest left tower is ```max(hashmap[diff + rod], leftMax + rod)```. \n\nIf we add this rod to the right tower, the difference would decrease to ```diff - rod```. This is because we consider the left tower to be the tallest. Now, if adding this rod to the right tower makes it taller than the left tower, then we can swap the towers to make the left tower taller. We can again store the tallest leftTower with ```max(hashmap[abs(diff - rod)], leftMax + rod)```. \n\nIf we walk through the solution, then it will become clearer. \n\nLet\'s initialize a dictionary ```cache``` where the keys are the height differences between the left and the right tower and the values are the heights of the left tower (which we consider to be taller). In the start, we store ```cache[0] = 0``` since we have not explored any rods yet and we can have a height of 0 by not considering any rods in the towers. \n\nNow we iterate over the rods. For each rod, we iterate over all the configurations of towers we have seen so far. Since we might be adding key: value pairs to our cache, we create a deep copy of it so that our for loop can run without any errors. Now we loop over the ```diff, maxLeft``` pairs in the copy. For each configuration, we can either \n\n- **Add rod to the left tower**: Since the left tower is taller, the height difference be ```diff + rod```. The left tower becomes ```maxLeft + rod```. If ```diff + rod``` is a configuration in our cache, we update its value to be the maximum of what is already is and our current left tower. Otherwise, we store our current left tower. \n- **Add rod to the right tower**: The height of the right tower becomes ```right = diff - maxLeft + rod```. We compute the difference between the right tower and left tower. If we left tower is taller, then this difference will be negative. In this case, ```cache[heightDiff]``` is the maximum of what is already is and the left tower. However, if the right tower becomes taller, then we swap the towers to keep the left tower the tallest and update ```cache[heightDiff]``` in a similar way to how we update it for the case above.\n- **Not consder this rod**: This is the simplest case, we don\'t do anything. \n\nIn the end, we can return ```cache[0]```. If we ever saw a height greater than 0, then we will return that. Otherwise it means that we can\'t build a valid billboard.\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\n# Code\n```\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n """\n Returns the tallest pillars we can build for a billboard out of the rods\n\n Args:\n rods: List[int] = the heights of the rods available\n \n Returns:\n height: int = The tallest left and right pillars we can build for the board\n """\n cache = {0: 0} # key: height difference, val: tallest left tower\n\n for rod in rods:\n curr = cache.copy()\n\n for diff, leftTower in curr.items():\n # Adding this rod to the left tower \n cache[diff + rod] = max(cache.get(diff + rod, 0), leftTower + rod)\n\n # Adding this rod to the right tower\n # This is the height of the right tower after adding the rod\n rightTower = leftTower - diff + rod \n # This is the difference between the left and right towers\n heightDiff = abs(rightTower - leftTower) \n # Since we keep the left tower the tallest, we swap if needed\n leftTower = max(rightTower, leftTower)\n cache[heightDiff] = max(cache.get(heightDiff, 0), leftTower)\n\n # If we don\'t consider this rod then we can continue\n \n height = cache[0]\n return height\n\n\n``` | 2 | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000` | null |
Clear Explanation with Dynamic Programming Solution | tallest-billboard | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we want the height of the left and right towers to be equal, we need to find a \n\n\n\n\n\n\n\nconfiguration of the rods such that the difference between the left tower and right tower is 0 and maximize that height. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI\'m not going to lie, my first intution was to use binary search for a range of heights and use a helper method to calculate if a given height was possible to construct out of the rods. But this solution has an exponential time complexity and frankly it is very difficult to implement. \n\nFor each rod, we can either add it to the left tower, the right tower, or not consider it at all. For each rod, we have three decisions. Therefore a bruteforce solution would have a complexity of O(3^n) which is very high. \n\nYou should note that for a valid billboard, the left and right tower will have the same height and therefore the difference in their height is 0.\n\nLet\'s say that we know the tallest left tower we can build with a height difference of ```diff```. For a particular rod ```rod```, we can either add it to the left tower which would increase the difference to ```diff + rod``` and the tallest left tower is ```max(hashmap[diff + rod], leftMax + rod)```. \n\nIf we add this rod to the right tower, the difference would decrease to ```diff - rod```. This is because we consider the left tower to be the tallest. Now, if adding this rod to the right tower makes it taller than the left tower, then we can swap the towers to make the left tower taller. We can again store the tallest leftTower with ```max(hashmap[abs(diff - rod)], leftMax + rod)```. \n\nIf we walk through the solution, then it will become clearer. \n\nLet\'s initialize a dictionary ```cache``` where the keys are the height differences between the left and the right tower and the values are the heights of the left tower (which we consider to be taller). In the start, we store ```cache[0] = 0``` since we have not explored any rods yet and we can have a height of 0 by not considering any rods in the towers. \n\nNow we iterate over the rods. For each rod, we iterate over all the configurations of towers we have seen so far. Since we might be adding key: value pairs to our cache, we create a deep copy of it so that our for loop can run without any errors. Now we loop over the ```diff, maxLeft``` pairs in the copy. For each configuration, we can either \n\n- **Add rod to the left tower**: Since the left tower is taller, the height difference be ```diff + rod```. The left tower becomes ```maxLeft + rod```. If ```diff + rod``` is a configuration in our cache, we update its value to be the maximum of what is already is and our current left tower. Otherwise, we store our current left tower. \n- **Add rod to the right tower**: The height of the right tower becomes ```right = diff - maxLeft + rod```. We compute the difference between the right tower and left tower. If we left tower is taller, then this difference will be negative. In this case, ```cache[heightDiff]``` is the maximum of what is already is and the left tower. However, if the right tower becomes taller, then we swap the towers to keep the left tower the tallest and update ```cache[heightDiff]``` in a similar way to how we update it for the case above.\n- **Not consder this rod**: This is the simplest case, we don\'t do anything. \n\nIn the end, we can return ```cache[0]```. If we ever saw a height greater than 0, then we will return that. Otherwise it means that we can\'t build a valid billboard.\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\n# Code\n```\nclass Solution:\n def tallestBillboard(self, rods: List[int]) -> int:\n """\n Returns the tallest pillars we can build for a billboard out of the rods\n\n Args:\n rods: List[int] = the heights of the rods available\n \n Returns:\n height: int = The tallest left and right pillars we can build for the board\n """\n cache = {0: 0} # key: height difference, val: tallest left tower\n\n for rod in rods:\n curr = cache.copy()\n\n for diff, leftTower in curr.items():\n # Adding this rod to the left tower \n cache[diff + rod] = max(cache.get(diff + rod, 0), leftTower + rod)\n\n # Adding this rod to the right tower\n # This is the height of the right tower after adding the rod\n rightTower = leftTower - diff + rod \n # This is the difference between the left and right towers\n heightDiff = abs(rightTower - leftTower) \n # Since we keep the left tower the tallest, we swap if needed\n leftTower = max(rightTower, leftTower)\n cache[heightDiff] = max(cache.get(heightDiff, 0), leftTower)\n\n # If we don\'t consider this rod then we can continue\n \n height = cache[0]\n return height\n\n\n``` | 2 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree. | null |
Python DP Easiest Solution | tallest-billboard | 0 | 1 | \n# Code\n```\nclass Solution(object):\n def tallestBillboard(self, rods):\n """\n :type rods: List[int]\n :rtype: int\n """\n ans={}\n return self.dfs(rods,0,0,ans)\n def dfs(self,nums,i,diff,ans):\n if (i,diff) in ans:\n return ans[(i,diff)]\n if i>=len(nums):\n if diff:\n return float(\'-inf\')\n return 0\n long=self.dfs(nums,i+1,diff+nums[i],ans)\n skip=self.dfs(nums,i+1,diff,ans)\n short=self.dfs(nums,i+1,abs(nums[i]-diff),ans)+min(diff,nums[i])\n ans[(i,diff)]=max(long,short,skip)\n return ans[(i,diff)] \n``` | 1 | You are installing a billboard and want it to have the largest height. The billboard will have two steel supports, one on each side. Each steel support must be an equal height.
You are given a collection of `rods` that can be welded together. For example, if you have rods of lengths `1`, `2`, and `3`, you can weld them together to make a support of length `6`.
Return _the largest possible height of your billboard installation_. If you cannot support the billboard, return `0`.
**Example 1:**
**Input:** rods = \[1,2,3,6\]
**Output:** 6
**Explanation:** We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
**Example 2:**
**Input:** rods = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
**Example 3:**
**Input:** rods = \[1,2\]
**Output:** 0
**Explanation:** The billboard cannot be supported, so we return 0.
**Constraints:**
* `1 <= rods.length <= 20`
* `1 <= rods[i] <= 1000`
* `sum(rods[i]) <= 5000` | null |
Python DP Easiest Solution | tallest-billboard | 0 | 1 | \n# Code\n```\nclass Solution(object):\n def tallestBillboard(self, rods):\n """\n :type rods: List[int]\n :rtype: int\n """\n ans={}\n return self.dfs(rods,0,0,ans)\n def dfs(self,nums,i,diff,ans):\n if (i,diff) in ans:\n return ans[(i,diff)]\n if i>=len(nums):\n if diff:\n return float(\'-inf\')\n return 0\n long=self.dfs(nums,i+1,diff+nums[i],ans)\n skip=self.dfs(nums,i+1,diff,ans)\n short=self.dfs(nums,i+1,abs(nums[i]-diff),ans)+min(diff,nums[i])\n ans[(i,diff)]=max(long,short,skip)\n return ans[(i,diff)] \n``` | 1 | Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree. | null |
Solution | prison-cells-after-n-days | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> prisonAfterNDays(vector<int>& cells, int n) {\n if(n==0) return cells;\n int c = (n-1)%14 + 1;\n cout<<c;\n vector<int> newCell = cells;\n while(c--) {\n for(int i=1; i<7; i++) newCell[i] = !(cells[i-1]^cells[i+1]);\n newCell[0] = 0;\n newCell[7] = 0;\n cells = newCell;\n }\n return cells;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n count = 0\n done = {tuple(cells) : 0}\n def trans():\n nonlocal cells\n tmp = [0]*8\n for i in range(1,7):\n if cells[i-1] == cells[i+1]:\n tmp[i] = 1\n cells = tmp.copy()\n lcount = None\n for i in range(n):\n trans()\n count += 1\n if tuple(cells) in done:\n lcount = done[tuple(cells)]\n break\n \n else:\n done[tuple(cells)] = count\n if lcount == None: return cells\n time = (n-count)%(count-lcount)\n for i in range(time):\n trans()\n return cells\n```\n\n```Java []\nclass Solution {\n public int[] prisonAfterNDays(int[] cells, int n) {\n n=(n-1)%14+1;\n int[] newCells = new int[cells.length];\n if (n==0)\n return cells;\n for (int i=1;i<cells.length-1;i++)\n if (cells[i-1]==cells[i+1])\n newCells[i]=1;\n else\n newCells[i]=0;\n return prisonAfterNDays(newCells,n-1);\n }\n}\n```\n | 2 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
Solution | prison-cells-after-n-days | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> prisonAfterNDays(vector<int>& cells, int n) {\n if(n==0) return cells;\n int c = (n-1)%14 + 1;\n cout<<c;\n vector<int> newCell = cells;\n while(c--) {\n for(int i=1; i<7; i++) newCell[i] = !(cells[i-1]^cells[i+1]);\n newCell[0] = 0;\n newCell[7] = 0;\n cells = newCell;\n }\n return cells;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n count = 0\n done = {tuple(cells) : 0}\n def trans():\n nonlocal cells\n tmp = [0]*8\n for i in range(1,7):\n if cells[i-1] == cells[i+1]:\n tmp[i] = 1\n cells = tmp.copy()\n lcount = None\n for i in range(n):\n trans()\n count += 1\n if tuple(cells) in done:\n lcount = done[tuple(cells)]\n break\n \n else:\n done[tuple(cells)] = count\n if lcount == None: return cells\n time = (n-count)%(count-lcount)\n for i in range(time):\n trans()\n return cells\n```\n\n```Java []\nclass Solution {\n public int[] prisonAfterNDays(int[] cells, int n) {\n n=(n-1)%14+1;\n int[] newCells = new int[cells.length];\n if (n==0)\n return cells;\n for (int i=1;i<cells.length-1;i++)\n if (cells[i-1]==cells[i+1])\n newCells[i]=1;\n else\n newCells[i]=0;\n return prisonAfterNDays(newCells,n-1);\n }\n}\n```\n | 2 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
[Python3] Prison Cells After N days: dictionary to store pattern | prison-cells-after-n-days | 0 | 1 | * There must be a pattern in this problem. The length of the list is 8, and the first and last element of list will always be 0. So only 8-2= 6 items in the list will change. For each item, there are 2 possible values : 0 or 1. So the entile possible cell states will be less or equal to 2**6 = 64.\n\n* \uD83E\uDD89 the repeatition or pattern or cyclicality may start at N = 0 or 1.\nFact: the first and last element of the list will always be 0.\nIf your input starts with 1 [1......] or ends with 1[......1], it couldn\'t be in the cyclicality.\nSo We can\'t assume the input is inside the cyclicality.\n\n\n```\n// Case 1:\n0 [0, 1, 0, 1, 1, 0, 0, 1]\n----------------------------------------\n1 [0, 1, 1, 0, 0, 0, 0, 0]\n2 [0, 0, 0, 0, 1, 1, 1, 0]\n3 [0, 1, 1, 0, 0, 1, 0, 0]\n4 [0, 0, 0, 0, 0, 1, 0, 0]\n5 [0, 1, 1, 1, 0, 1, 0, 0]\n6 [0, 0, 1, 0, 1, 1, 0, 0]\n7 [0, 0, 1, 1, 0, 0, 0, 0]\n8 [0, 0, 0, 0, 0, 1, 1, 0]\n9 [0, 1, 1, 1, 0, 0, 0, 0]\n10 [0, 0, 1, 0, 0, 1, 1, 0]\n11 [0, 0, 1, 0, 0, 0, 0, 0]\n12 [0, 0, 1, 0, 1, 1, 1, 0]\n13 [0, 0, 1, 1, 0, 1, 0, 0]\n14 [0, 0, 0, 0, 1, 1, 0, 0]\n----------------------------------------\n15 [0, 1, 1, 0, 0, 0, 0, 0]\n16 [0, 0, 0, 0, 1, 1, 1, 0]\n17 [0, 1, 1, 0, 0, 1, 0, 0]\n18 [0, 0, 0, 0, 0, 1, 0, 0]\n19 [0, 1, 1, 1, 0, 1, 0, 0]\n20 [0, 0, 1, 0, 1, 1, 0, 0]\n21 [0, 0, 1, 1, 0, 0, 0, 0]\n22 [0, 0, 0, 0, 0, 1, 1, 0]\n23 [0, 1, 1, 1, 0, 0, 0, 0]\n24 [0, 0, 1, 0, 0, 1, 1, 0]\n25 [0, 0, 1, 0, 0, 0, 0, 0]\n26 [0, 0, 1, 0, 1, 1, 1, 0]\n27 [0, 0, 1, 1, 0, 1, 0, 0]\n28 [0, 0, 0, 0, 1, 1, 0, 0]\n----------------------------------------\n```\n* To calculate the next day prison states:\n```\n# the first and last cells will alwasy be zero according to the condition\ndef nextday(cells):\n next_day_cells = [0] *len(cells)\n for i in range(1,len(cells)-1):\n if cells[i-1] == cells[i+1]: \n next_day_cells[i] = 1\n else:\n next_day_cells[i] = 0\n return tuple(next_day_cells)\n \n```\n* From the results, we know that the length of the pattern will be 14. i.e. the length of pattern == 14.\n```\nSeen =\n{(0, 1, 1, 0, 0, 0, 0, 0): 1,\n(0, 0, 0, 0, 1, 1, 1, 0): 2,\n(0, 1, 1, 0, 0, 1, 0, 0): 3,\n(0, 0, 0, 0, 0, 1, 0, 0): 4,\n(0, 1, 1, 1, 0, 1, 0, 0): 5, \n(0, 0, 1, 0, 1, 1, 0, 0): 6, \n(0, 0, 1, 1, 0, 0, 0, 0): 7,\n(0, 0, 0, 0, 0, 1, 1, 0): 8, \n(0, 1, 1, 1, 0, 0, 0, 0): 9, \n(0, 0, 1, 0, 0, 1, 1, 0): 10, \n(0, 0, 1, 0, 0, 0, 0, 0): 11, \n(0, 0, 1, 0, 1, 1, 1, 0): 12,\n(0, 0, 1, 1, 0, 1, 0, 0): 13, \n(0, 0, 0, 0, 1, 1, 0, 0): 14}\n```\n\n* \n* Code \n\t\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n def nextday(cells):\n next_day_cells = [0] *len(cells)\n for i in range(1,len(cells)-1):\n if cells[i-1] == cells[i+1]: \n next_day_cells[i] = 1\n else:\n next_day_cells[i] = 0\n return next_day_cells\n \n seen = {}\n while N > 0:\n c = tuple(cells)\n if c in seen:\n N %= seen[c] - N\n seen[c] = N\n\n if N >= 1:\n N -= 1\n cells = nextday(cells)\n\n return cells\n``` | 33 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
[Python3] Prison Cells After N days: dictionary to store pattern | prison-cells-after-n-days | 0 | 1 | * There must be a pattern in this problem. The length of the list is 8, and the first and last element of list will always be 0. So only 8-2= 6 items in the list will change. For each item, there are 2 possible values : 0 or 1. So the entile possible cell states will be less or equal to 2**6 = 64.\n\n* \uD83E\uDD89 the repeatition or pattern or cyclicality may start at N = 0 or 1.\nFact: the first and last element of the list will always be 0.\nIf your input starts with 1 [1......] or ends with 1[......1], it couldn\'t be in the cyclicality.\nSo We can\'t assume the input is inside the cyclicality.\n\n\n```\n// Case 1:\n0 [0, 1, 0, 1, 1, 0, 0, 1]\n----------------------------------------\n1 [0, 1, 1, 0, 0, 0, 0, 0]\n2 [0, 0, 0, 0, 1, 1, 1, 0]\n3 [0, 1, 1, 0, 0, 1, 0, 0]\n4 [0, 0, 0, 0, 0, 1, 0, 0]\n5 [0, 1, 1, 1, 0, 1, 0, 0]\n6 [0, 0, 1, 0, 1, 1, 0, 0]\n7 [0, 0, 1, 1, 0, 0, 0, 0]\n8 [0, 0, 0, 0, 0, 1, 1, 0]\n9 [0, 1, 1, 1, 0, 0, 0, 0]\n10 [0, 0, 1, 0, 0, 1, 1, 0]\n11 [0, 0, 1, 0, 0, 0, 0, 0]\n12 [0, 0, 1, 0, 1, 1, 1, 0]\n13 [0, 0, 1, 1, 0, 1, 0, 0]\n14 [0, 0, 0, 0, 1, 1, 0, 0]\n----------------------------------------\n15 [0, 1, 1, 0, 0, 0, 0, 0]\n16 [0, 0, 0, 0, 1, 1, 1, 0]\n17 [0, 1, 1, 0, 0, 1, 0, 0]\n18 [0, 0, 0, 0, 0, 1, 0, 0]\n19 [0, 1, 1, 1, 0, 1, 0, 0]\n20 [0, 0, 1, 0, 1, 1, 0, 0]\n21 [0, 0, 1, 1, 0, 0, 0, 0]\n22 [0, 0, 0, 0, 0, 1, 1, 0]\n23 [0, 1, 1, 1, 0, 0, 0, 0]\n24 [0, 0, 1, 0, 0, 1, 1, 0]\n25 [0, 0, 1, 0, 0, 0, 0, 0]\n26 [0, 0, 1, 0, 1, 1, 1, 0]\n27 [0, 0, 1, 1, 0, 1, 0, 0]\n28 [0, 0, 0, 0, 1, 1, 0, 0]\n----------------------------------------\n```\n* To calculate the next day prison states:\n```\n# the first and last cells will alwasy be zero according to the condition\ndef nextday(cells):\n next_day_cells = [0] *len(cells)\n for i in range(1,len(cells)-1):\n if cells[i-1] == cells[i+1]: \n next_day_cells[i] = 1\n else:\n next_day_cells[i] = 0\n return tuple(next_day_cells)\n \n```\n* From the results, we know that the length of the pattern will be 14. i.e. the length of pattern == 14.\n```\nSeen =\n{(0, 1, 1, 0, 0, 0, 0, 0): 1,\n(0, 0, 0, 0, 1, 1, 1, 0): 2,\n(0, 1, 1, 0, 0, 1, 0, 0): 3,\n(0, 0, 0, 0, 0, 1, 0, 0): 4,\n(0, 1, 1, 1, 0, 1, 0, 0): 5, \n(0, 0, 1, 0, 1, 1, 0, 0): 6, \n(0, 0, 1, 1, 0, 0, 0, 0): 7,\n(0, 0, 0, 0, 0, 1, 1, 0): 8, \n(0, 1, 1, 1, 0, 0, 0, 0): 9, \n(0, 0, 1, 0, 0, 1, 1, 0): 10, \n(0, 0, 1, 0, 0, 0, 0, 0): 11, \n(0, 0, 1, 0, 1, 1, 1, 0): 12,\n(0, 0, 1, 1, 0, 1, 0, 0): 13, \n(0, 0, 0, 0, 1, 1, 0, 0): 14}\n```\n\n* \n* Code \n\t\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n def nextday(cells):\n next_day_cells = [0] *len(cells)\n for i in range(1,len(cells)-1):\n if cells[i-1] == cells[i+1]: \n next_day_cells[i] = 1\n else:\n next_day_cells[i] = 0\n return next_day_cells\n \n seen = {}\n while N > 0:\n c = tuple(cells)\n if c in seen:\n N %= seen[c] - N\n seen[c] = N\n\n if N >= 1:\n N -= 1\n cells = nextday(cells)\n\n return cells\n``` | 33 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
Simple Python Solution | prison-cells-after-n-days | 0 | 1 | The naive way is to compute the changes for N days (using the nextDay Function). But we can improve this because there will be a cycle and similar states will repeat. Since the first and last cell will become 0 after the the first day, the first day will eventually repeat if there is a cycle. So we keep a count of the number of days after which the cycle repeats ( count ) . \nWe keep doing nextDay till we see day1 repeat. When this happens, we just reduce the remaining N as N = N % count beacuse after "count" days, N will come back to the same state\n\nThus, Space Complexity : O(1), Time Complexity : O(n) where N is the number of days\n\n\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n \n def nextDay(cells):\n mask = cells.copy()\n for i in range(1, len(cells) - 1):\n if mask[i-1] ^ mask[i+1] == 0:\n cells[i] = 1\n else:\n cells[i] = 0\n cells[0] = 0\n cells[-1] = 0 \n return cells\n \n day1 = tuple(nextDay(cells))\n N -= 1\n count = 0\n \n while N > 0:\n day = tuple(nextDay(cells))\n N -= 1\n count += 1\n \n if day == day1:\n N = N % count\n return cells\n \n \n \n``` | 26 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
Simple Python Solution | prison-cells-after-n-days | 0 | 1 | The naive way is to compute the changes for N days (using the nextDay Function). But we can improve this because there will be a cycle and similar states will repeat. Since the first and last cell will become 0 after the the first day, the first day will eventually repeat if there is a cycle. So we keep a count of the number of days after which the cycle repeats ( count ) . \nWe keep doing nextDay till we see day1 repeat. When this happens, we just reduce the remaining N as N = N % count beacuse after "count" days, N will come back to the same state\n\nThus, Space Complexity : O(1), Time Complexity : O(n) where N is the number of days\n\n\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n \n def nextDay(cells):\n mask = cells.copy()\n for i in range(1, len(cells) - 1):\n if mask[i-1] ^ mask[i+1] == 0:\n cells[i] = 1\n else:\n cells[i] = 0\n cells[0] = 0\n cells[-1] = 0 \n return cells\n \n day1 = tuple(nextDay(cells))\n N -= 1\n count = 0\n \n while N > 0:\n day = tuple(nextDay(cells))\n N -= 1\n count += 1\n \n if day == day1:\n N = N % count\n return cells\n \n \n \n``` | 26 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
Very Intuitive Python Detailed Solution with Example | prison-cells-after-n-days | 0 | 1 | Lets just take an easier version of the question, **given the current state, find next state.**\n\nWe would write the following function, it just checks whether neighboring elements are same, if so, put a `1` else `0`\n\n```python\n def next(state):\n return tuple([1 if i>0 and i<len(state)-1 and state[i-1] == state[i+1] else 0 for i in range(len(state))])\n```\n\n\n**If we were asked how it would look after 10 days;**\n```python\n\t def after10Days(state):\n\t N = 10\n\t\t while i < N:\n\t\t state = next(state)\n\t\t\t i+=1\n\t\t return state\n```\n\n**After `N` days gets a little tricky**\n\nTechnically - you could just go by having a simple loop like above. But we want to be smarter than that, right?\n\nWell, with 8 cells, how many configurations can really be there. And we know for sure a state can only have a definite, single next state. In other words, state `i` will always have state `j` as next state. It can\'t be having different next states - Given current state, next state is always deterministic.\n\nThus we can keep a track of seen states, and when we see a state we\'ve already seen, we can advance multiple times further. A lot of us might be confused with simple math here - **how much to advance?**\n\nWe need to find a `k` such that we skip all the `cycle`s\n\n<center><p align=center><img src="https://assets.leetcode.com/users/images/3acefb2c-3712-4bae-b5fc-88bfa6fee218_1595174366.295264.png" width=500/></center></p>\n\nFrom above it\'s clear that :\n1. `cycle = i - seen[state]`\n2. `remaining = (N-i)%cycle` (Remainder after repeating cycles `(N-i)/cycles` number of times)\n\nAfter finding a cycle, we can break out of the loop, and execute the remainder peacefully to get to final state.\n\n\n```python\nclass Solution(object):\n def prisonAfterNDays(self, cells, N):\n """\n :type cells: List[int]\n :type N: int\n :rtype: List[int]\n """\n def next(state):\n return tuple([1 if i>0 and i<len(state)-1 and state[i-1] == state[i+1] else 0 for i in range(len(state))])\n \n seen = {}\n state = tuple(cells)\n i = 0\n remaining = 0\n while i < N:\n if state in seen:\n cycle = i - seen[state]\n remaining = (N-i)%cycle\n break\n seen[state] = i\n state = next(state)\n i+=1\n \n while remaining > 0:\n state = next(state)\n remaining-=1\n return state\n``` | 11 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
Very Intuitive Python Detailed Solution with Example | prison-cells-after-n-days | 0 | 1 | Lets just take an easier version of the question, **given the current state, find next state.**\n\nWe would write the following function, it just checks whether neighboring elements are same, if so, put a `1` else `0`\n\n```python\n def next(state):\n return tuple([1 if i>0 and i<len(state)-1 and state[i-1] == state[i+1] else 0 for i in range(len(state))])\n```\n\n\n**If we were asked how it would look after 10 days;**\n```python\n\t def after10Days(state):\n\t N = 10\n\t\t while i < N:\n\t\t state = next(state)\n\t\t\t i+=1\n\t\t return state\n```\n\n**After `N` days gets a little tricky**\n\nTechnically - you could just go by having a simple loop like above. But we want to be smarter than that, right?\n\nWell, with 8 cells, how many configurations can really be there. And we know for sure a state can only have a definite, single next state. In other words, state `i` will always have state `j` as next state. It can\'t be having different next states - Given current state, next state is always deterministic.\n\nThus we can keep a track of seen states, and when we see a state we\'ve already seen, we can advance multiple times further. A lot of us might be confused with simple math here - **how much to advance?**\n\nWe need to find a `k` such that we skip all the `cycle`s\n\n<center><p align=center><img src="https://assets.leetcode.com/users/images/3acefb2c-3712-4bae-b5fc-88bfa6fee218_1595174366.295264.png" width=500/></center></p>\n\nFrom above it\'s clear that :\n1. `cycle = i - seen[state]`\n2. `remaining = (N-i)%cycle` (Remainder after repeating cycles `(N-i)/cycles` number of times)\n\nAfter finding a cycle, we can break out of the loop, and execute the remainder peacefully to get to final state.\n\n\n```python\nclass Solution(object):\n def prisonAfterNDays(self, cells, N):\n """\n :type cells: List[int]\n :type N: int\n :rtype: List[int]\n """\n def next(state):\n return tuple([1 if i>0 and i<len(state)-1 and state[i-1] == state[i+1] else 0 for i in range(len(state))])\n \n seen = {}\n state = tuple(cells)\n i = 0\n remaining = 0\n while i < N:\n if state in seen:\n cycle = i - seen[state]\n remaining = (N-i)%cycle\n break\n seen[state] = i\n state = next(state)\n i+=1\n \n while remaining > 0:\n state = next(state)\n remaining-=1\n return state\n``` | 11 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
PYTHON SOL || FAST || MATHS || WELL EXPLAINED || PATTERN || LOGIC EXPLAINED || | prison-cells-after-n-days | 0 | 1 | # EXPLANATION\n```\nThe size of our cells = 8 \nNow the first and last cell can never have two adjacent cells hence they will always be 1\n\nWe can make new cells array n number of times to solve this ques -> BRUTE FORCE\n\nBut when n is large like n = 10^9 we get TLE\n\nNow since we can\'t do brute force and the way of creating cells for n = 1 , n = 2 is plain simple . We get the idea of pattern\n\nNow if you take any example and make new cells for n = 1,2,3..... \nAt n = 15 you\'ll find that cells for n = 15 is same as n = 1 i.e. repeatition\nSo we now know that after every 14 rounds we get repeatition\n\nSo firstly we do n mod 14\nif n is a multiple of 14 we will get n = 0 but here we should take n = 14 as 14 will be the last\n\n\n\n```\n\n# CODE\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n n = n%14 if n%14!=0 else 14\n for _ in range(n):\n new = [0]*8\n for i in range(1,7):\n if cells[i-1]==cells[i+1]: new[i] = 1\n cells = new\n return cells\n``` | 2 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
PYTHON SOL || FAST || MATHS || WELL EXPLAINED || PATTERN || LOGIC EXPLAINED || | prison-cells-after-n-days | 0 | 1 | # EXPLANATION\n```\nThe size of our cells = 8 \nNow the first and last cell can never have two adjacent cells hence they will always be 1\n\nWe can make new cells array n number of times to solve this ques -> BRUTE FORCE\n\nBut when n is large like n = 10^9 we get TLE\n\nNow since we can\'t do brute force and the way of creating cells for n = 1 , n = 2 is plain simple . We get the idea of pattern\n\nNow if you take any example and make new cells for n = 1,2,3..... \nAt n = 15 you\'ll find that cells for n = 15 is same as n = 1 i.e. repeatition\nSo we now know that after every 14 rounds we get repeatition\n\nSo firstly we do n mod 14\nif n is a multiple of 14 we will get n = 0 but here we should take n = 14 as 14 will be the last\n\n\n\n```\n\n# CODE\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n n = n%14 if n%14!=0 else 14\n for _ in range(n):\n new = [0]*8\n for i in range(1,7):\n if cells[i-1]==cells[i+1]: new[i] = 1\n cells = new\n return cells\n``` | 2 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
[Python] Easy O(1) Solution Explained | prison-cells-after-n-days | 0 | 1 | There is a pattern which repeats at every 14 steps. So we can simply take the modulo of N by 14 and calculate the pattern. Only there is a problem if the first and last cells are 1 at the beginning. In this case, the pattern will start after the first iteration. So take the modulo of N-1 by 14 and add 1 for the first iteration. \n\nI used a one line statement for calculating the value of cells. We need to check if the neighbor cells have the same value and write 1 if they do. This is basically XNOR operation so I took XOR of the values and substract it from 1.\n\n\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n prison_size = len(cells)\n if cells[0] == 1 or cells[-1] == 1:\n N = (N-1) % 14 + 1\n else:\n N = N % 14\n for d in range(N):\n cells = [0]+[1-cells[i-1]^cells[i+1] for i in range(1, prison_size-1)]+[0]\n return cells\n```\n\nEDIT:\nLet\'s say you don\'t know how often the pattern repeats itself or even if there is a pattern, then you can use the following code. It is good to assume that there is a pattern here but this solution has increased space complexity.\n\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n prison_size = len(cells)\n pattern=[]\n start = 0\n \n if cells[0] == 1 or cells[-1] == 1:\n start = 1\n ans = [0] * prison_size\n for i in range(1, prison_size-1):\n ans[i] = 1 if cells[i-1] == cells[i+1] else 0\n cells = ans\n \n for d in range(start, N):\n ans = [0] * prison_size\n for i in range(1, prison_size-1):\n ans[i] = 1 if cells[i-1] == cells[i+1] else 0\n cells = ans \n if d > start and cells == pattern[0]:\n return pattern[(N-start) % len(pattern) - 1]\n pattern.append(ans)\n \n return cells\n``` | 7 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
[Python] Easy O(1) Solution Explained | prison-cells-after-n-days | 0 | 1 | There is a pattern which repeats at every 14 steps. So we can simply take the modulo of N by 14 and calculate the pattern. Only there is a problem if the first and last cells are 1 at the beginning. In this case, the pattern will start after the first iteration. So take the modulo of N-1 by 14 and add 1 for the first iteration. \n\nI used a one line statement for calculating the value of cells. We need to check if the neighbor cells have the same value and write 1 if they do. This is basically XNOR operation so I took XOR of the values and substract it from 1.\n\n\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n prison_size = len(cells)\n if cells[0] == 1 or cells[-1] == 1:\n N = (N-1) % 14 + 1\n else:\n N = N % 14\n for d in range(N):\n cells = [0]+[1-cells[i-1]^cells[i+1] for i in range(1, prison_size-1)]+[0]\n return cells\n```\n\nEDIT:\nLet\'s say you don\'t know how often the pattern repeats itself or even if there is a pattern, then you can use the following code. It is good to assume that there is a pattern here but this solution has increased space complexity.\n\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], N: int) -> List[int]:\n prison_size = len(cells)\n pattern=[]\n start = 0\n \n if cells[0] == 1 or cells[-1] == 1:\n start = 1\n ans = [0] * prison_size\n for i in range(1, prison_size-1):\n ans[i] = 1 if cells[i-1] == cells[i+1] else 0\n cells = ans\n \n for d in range(start, N):\n ans = [0] * prison_size\n for i in range(1, prison_size-1):\n ans[i] = 1 if cells[i-1] == cells[i+1] else 0\n cells = ans \n if d > start and cells == pattern[0]:\n return pattern[(N-start) % len(pattern) - 1]\n pattern.append(ans)\n \n return cells\n``` | 7 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
🚩 EXPLAINED by picture ^^ | prison-cells-after-n-days | 0 | 1 | \n\n**Explanation:**\n\nThe state space consists of `256` 8-bit numbers.\nOn the picture we have all of `64` 8-bit `0...0` (starts and ends with `0`) numbers. The arrows show how they evolve under the rules of this problem. There are also three other numbers (that are depicted as grey arrows with a circle at the rear end) leading to every `0...0` number:\n* `1...0` number;\n* `0...1` number;\n* `1...1` number.\n* \n`0...0` numbers form `6` cycles. Four have period `14`, one has period `7` and one has period `1`. Note, that it all adds up correctly `(14*4+7+1)*4=256` so the total number of points is `256` as it should be. \nThe diagram suggests that you have to perform `14` iterations max in order to get your answer. That\'s because you **have to be** in one of the cycles shown on the picture and the cycles repeat themselves! Thus you need to use `%` in order to avoid useless computations that will keep cycling around.\nHere\'s an example:\n`10101000 -> 01111010 -> 00110110 -> 00001000 -> 01101010 -> 00011110 -> 01001100 -> 01000000 -> 01011110 -> 01101100`\n\n\n\n\n**c++:**\n**recursion:**\n```\nvector<int> prisonAfterNDays(vector<int> c, int n)\n{\n\treturn n ? prisonAfterNDays({0, c[0]==c[2], c[1]==c[3], c[2]==c[4], c[3]==c[5], c[4]==c[6], c[5]==c[7], 0}, (n-1)%14) : c; \xA0\n}\n```\n\n**iteration:**\n```\nvector<int> prisonAfterNDays(vector<int>& c, int n)\n{\n\tfor(n=(n-1)%14; n>=0; --n)\n\t\tfor(int i{}, p{-1}; i<8; ++i)\n\t\t p = exchange(c[i], i<7 and p==c[i+1]); \n\treturn c;\n}\n```\n||\n```\nvector<int> prisonAfterNDays(vector<int>& c, int n)\n{\n\tunsigned char x{};\n\tfor(const auto & i : c) x=2*x+i;\n\n\tfor(n=1+(n-1)%14; n--; x=~(x<<1^x>>1)&126);\n \n\tvector<int> out;\n\tfor(int i(256); i>>=1; out.push_back(!!(x&i)));\n\treturn out;\n}\n```\n||\n```\nvector<int> prisonAfterNDays(vector<int>& c, int n)\n{\n\tauto x{c[7]+2*c[6]+4*c[5]+8*c[4]+16*c[3]+32*c[2]+64*c[1]+128*c[0]};\n\tfor(n=1+(n-1)%14; n--; x=~(x<<1^x>>1)&126);\n\treturn {!!(x&128), !!(x&64), !!(x&32), !!(x&16), !!(x&8), !!(x&4), !!(x&2), x&1};\n}\n```\n**python:**\n**recursion:**\n```\nclass Solution:\n def prisonAfterNDays(self, c, n) :\n return self.prisonAfterNDays([0, c[0]==c[2], c[1]==c[3], c[2]==c[4], c[3]==c[5], c[4]==c[6], c[5]==c[7], 0], (n-1)%14) if n else [int(i) for i in c] \n```\n\n**iteration:**\n```\nclass Solution:\n def prisonAfterNDays(self, c, n) :\n for _ in range(1+(n-1)%14) :\n p=-1\n for i in range(8) : \n p, c[i] = c[i], int(i<7 and p==c[i+1])\n return c\n``` | 4 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
🚩 EXPLAINED by picture ^^ | prison-cells-after-n-days | 0 | 1 | \n\n**Explanation:**\n\nThe state space consists of `256` 8-bit numbers.\nOn the picture we have all of `64` 8-bit `0...0` (starts and ends with `0`) numbers. The arrows show how they evolve under the rules of this problem. There are also three other numbers (that are depicted as grey arrows with a circle at the rear end) leading to every `0...0` number:\n* `1...0` number;\n* `0...1` number;\n* `1...1` number.\n* \n`0...0` numbers form `6` cycles. Four have period `14`, one has period `7` and one has period `1`. Note, that it all adds up correctly `(14*4+7+1)*4=256` so the total number of points is `256` as it should be. \nThe diagram suggests that you have to perform `14` iterations max in order to get your answer. That\'s because you **have to be** in one of the cycles shown on the picture and the cycles repeat themselves! Thus you need to use `%` in order to avoid useless computations that will keep cycling around.\nHere\'s an example:\n`10101000 -> 01111010 -> 00110110 -> 00001000 -> 01101010 -> 00011110 -> 01001100 -> 01000000 -> 01011110 -> 01101100`\n\n\n\n\n**c++:**\n**recursion:**\n```\nvector<int> prisonAfterNDays(vector<int> c, int n)\n{\n\treturn n ? prisonAfterNDays({0, c[0]==c[2], c[1]==c[3], c[2]==c[4], c[3]==c[5], c[4]==c[6], c[5]==c[7], 0}, (n-1)%14) : c; \xA0\n}\n```\n\n**iteration:**\n```\nvector<int> prisonAfterNDays(vector<int>& c, int n)\n{\n\tfor(n=(n-1)%14; n>=0; --n)\n\t\tfor(int i{}, p{-1}; i<8; ++i)\n\t\t p = exchange(c[i], i<7 and p==c[i+1]); \n\treturn c;\n}\n```\n||\n```\nvector<int> prisonAfterNDays(vector<int>& c, int n)\n{\n\tunsigned char x{};\n\tfor(const auto & i : c) x=2*x+i;\n\n\tfor(n=1+(n-1)%14; n--; x=~(x<<1^x>>1)&126);\n \n\tvector<int> out;\n\tfor(int i(256); i>>=1; out.push_back(!!(x&i)));\n\treturn out;\n}\n```\n||\n```\nvector<int> prisonAfterNDays(vector<int>& c, int n)\n{\n\tauto x{c[7]+2*c[6]+4*c[5]+8*c[4]+16*c[3]+32*c[2]+64*c[1]+128*c[0]};\n\tfor(n=1+(n-1)%14; n--; x=~(x<<1^x>>1)&126);\n\treturn {!!(x&128), !!(x&64), !!(x&32), !!(x&16), !!(x&8), !!(x&4), !!(x&2), x&1};\n}\n```\n**python:**\n**recursion:**\n```\nclass Solution:\n def prisonAfterNDays(self, c, n) :\n return self.prisonAfterNDays([0, c[0]==c[2], c[1]==c[3], c[2]==c[4], c[3]==c[5], c[4]==c[6], c[5]==c[7], 0], (n-1)%14) if n else [int(i) for i in c] \n```\n\n**iteration:**\n```\nclass Solution:\n def prisonAfterNDays(self, c, n) :\n for _ in range(1+(n-1)%14) :\n p=-1\n for i in range(8) : \n p, c[i] = c[i], int(i<7 and p==c[i+1])\n return c\n``` | 4 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
Easy Python Solution - Faster than 95% (36ms) | prison-cells-after-n-days | 0 | 1 | The cell patterns repeat after every 14 operations. This is the key logic in this question. Now that we have the upper cap of 14, take `n % 14` and solve the problem.\n\nHere, we also need to use the list.copy() method. This function ensures that the original list doesn\'t get altered once there are any changes in the new list.\n\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n \n new_cells = [0] * len(cells)\n if n % 14 != 0:\n n = n % 14\n else:\n n = 14\n \n while n > 0:\n for i in range(1, len(cells)-1):\n if cells[i-1] == cells[i+1]:\n new_cells[i] = 1\n else:\n new_cells[i] = 0\n cells = new_cells.copy()\n n -= 1\n \n return new_cells\n\n``` | 1 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
Easy Python Solution - Faster than 95% (36ms) | prison-cells-after-n-days | 0 | 1 | The cell patterns repeat after every 14 operations. This is the key logic in this question. Now that we have the upper cap of 14, take `n % 14` and solve the problem.\n\nHere, we also need to use the list.copy() method. This function ensures that the original list doesn\'t get altered once there are any changes in the new list.\n\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n \n new_cells = [0] * len(cells)\n if n % 14 != 0:\n n = n % 14\n else:\n n = 14\n \n while n > 0:\n for i in range(1, len(cells)-1):\n if cells[i-1] == cells[i+1]:\n new_cells[i] = 1\n else:\n new_cells[i] = 0\n cells = new_cells.copy()\n n -= 1\n \n return new_cells\n\n``` | 1 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
beats 95% | prison-cells-after-n-days | 0 | 1 | \n\n# Code\n```\nclass Solution(object):\n def nextDay(self, cells):\n res = [0] * len(cells)\n l = 0\n r = 2\n i = 1\n while i <= len(cells) - 2:\n if cells[l] == cells[r]:\n res[i] = 1\n else:\n res[i] = 0\n r += 1\n l += 1\n i += 1\n return res\n\n def prisonAfterNDays(self, cells, n):\n seen = {}\n while n > 0:\n cell_str = \'\'.join(map(str, cells))\n if cell_str in seen:\n cycle_length = seen[cell_str] - n\n n %= cycle_length\n seen[cell_str] = n\n\n if n > 0:\n cells = self.nextDay(cells)\n n -= 1\n\n return cells\n``` | 0 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
beats 95% | prison-cells-after-n-days | 0 | 1 | \n\n# Code\n```\nclass Solution(object):\n def nextDay(self, cells):\n res = [0] * len(cells)\n l = 0\n r = 2\n i = 1\n while i <= len(cells) - 2:\n if cells[l] == cells[r]:\n res[i] = 1\n else:\n res[i] = 0\n r += 1\n l += 1\n i += 1\n return res\n\n def prisonAfterNDays(self, cells, n):\n seen = {}\n while n > 0:\n cell_str = \'\'.join(map(str, cells))\n if cell_str in seen:\n cycle_length = seen[cell_str] - n\n n %= cycle_length\n seen[cell_str] = n\n\n if n > 0:\n cells = self.nextDay(cells)\n n -= 1\n\n return cells\n``` | 0 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
Simple Python Solution || No dict || Two For loops Beats 87% | prison-cells-after-n-days | 0 | 1 | # Code\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n vals = []\n prev = cells\n for _ in range(7) :\n new = [0]*8\n for i in range(1,len(cells)-1):\n if prev[i-1] == prev[i+1] : new[i] = 1\n prev = new\n vals.append(new)\n for i in range(7) :\n vals.append(reversed(vals[i]))\n return vals[(n%14)-1]\n \n \n``` | 0 | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null |
Simple Python Solution || No dict || Two For loops Beats 87% | prison-cells-after-n-days | 0 | 1 | # Code\n```\nclass Solution:\n def prisonAfterNDays(self, cells: List[int], n: int) -> List[int]:\n vals = []\n prev = cells\n for _ in range(7) :\n new = [0]*8\n for i in range(1,len(cells)-1):\n if prev[i-1] == prev[i+1] : new[i] = 1\n prev = new\n vals.append(new)\n for i in range(7) :\n vals.append(reversed(vals[i]))\n return vals[(n%14)-1]\n \n \n``` | 0 | You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`. | null |
SImple Pyhton3 Solution || Upto 90 % Faster || O(n) || Simple Explaination of DFS | check-completeness-of-a-binary-tree | 0 | 1 | # Intuition\n1. Start with a queue containing only the root node.\n\n2. While the first element in the queue is not None, remove the first element from the queue, and add its left and right children (if they exist) to the end of the queue.\n\n3. After the while loop, check if all remaining elements in the queue are None. If they are, the binary tree is complete; otherwise, it\'s not complete.\n\nThis algorithm ensures that all nodes at each level are processed before moving on to the next level. If we encounter a **None element** in the queue before processing all nodes at a level, it means the binary tree is not complete.\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(m)\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 isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n queue = [root]\n while queue[0] is not None:\n node = queue.pop(0)\n queue.append(node.left)\n queue.append(node.right)\n return all([n is None for n in queue]) \n``` | 2 | Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
**Example 2:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 1000` | null |
SImple Pyhton3 Solution || Upto 90 % Faster || O(n) || Simple Explaination of DFS | check-completeness-of-a-binary-tree | 0 | 1 | # Intuition\n1. Start with a queue containing only the root node.\n\n2. While the first element in the queue is not None, remove the first element from the queue, and add its left and right children (if they exist) to the end of the queue.\n\n3. After the while loop, check if all remaining elements in the queue are None. If they are, the binary tree is complete; otherwise, it\'s not complete.\n\nThis algorithm ensures that all nodes at each level are processed before moving on to the next level. If we encounter a **None element** in the queue before processing all nodes at a level, it means the binary tree is not complete.\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(m)\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 isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n queue = [root]\n while queue[0] is not None:\n node = queue.pop(0)\n queue.append(node.left)\n queue.append(node.right)\n return all([n is None for n in queue]) \n``` | 2 | A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = Construct(a)`) recursively with the following `Construct(a)` routine:
* If `a` is empty, return `null`.
* Otherwise, let `a[i]` be the largest element of `a`. Create a `root` node with the value `a[i]`.
* The left child of `root` will be `Construct([a[0], a[1], ..., a[i - 1]])`.
* The right child of `root` will be `Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]])`.
* Return `root`.
Note that we were not given `a` directly, only a root node `root = Construct(a)`.
Suppose `b` is a copy of `a` with the value `val` appended to it. It is guaranteed that `b` has unique values.
Return `Construct(b)`.
**Example 1:**
**Input:** root = \[4,1,3,null,null,2\], val = 5
**Output:** \[5,4,null,1,3,null,null,2\]
**Explanation:** a = \[1,4,2,3\], b = \[1,4,2,3,5\]
**Example 2:**
**Input:** root = \[5,2,4,null,1\], val = 3
**Output:** \[5,2,4,null,1,null,3\]
**Explanation:** a = \[2,1,5,4\], b = \[2,1,5,4,3\]
**Example 3:**
**Input:** root = \[5,2,3,null,1\], val = 4
**Output:** \[5,2,4,null,1,3\]
**Explanation:** a = \[2,1,5,3\], b = \[2,1,5,3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 100`
* All the values of the tree are **unique**.
* `1 <= val <= 100` | null |
Awesome Logic with BFS Python3 | check-completeness-of-a-binary-tree | 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:95%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:99%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n q,gap=deque([root]),False\n while q:\n poping=q.popleft()\n if not poping: gap=True\n else:\n if gap: return False\n q.append(poping.left)\n q.append(poping.right)\n return True\n\n``` | 2 | Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
**Example 2:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 1000` | null |
Awesome Logic with BFS Python3 | check-completeness-of-a-binary-tree | 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:95%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:99%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n q,gap=deque([root]),False\n while q:\n poping=q.popleft()\n if not poping: gap=True\n else:\n if gap: return False\n q.append(poping.left)\n q.append(poping.right)\n return True\n\n``` | 2 | A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = Construct(a)`) recursively with the following `Construct(a)` routine:
* If `a` is empty, return `null`.
* Otherwise, let `a[i]` be the largest element of `a`. Create a `root` node with the value `a[i]`.
* The left child of `root` will be `Construct([a[0], a[1], ..., a[i - 1]])`.
* The right child of `root` will be `Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]])`.
* Return `root`.
Note that we were not given `a` directly, only a root node `root = Construct(a)`.
Suppose `b` is a copy of `a` with the value `val` appended to it. It is guaranteed that `b` has unique values.
Return `Construct(b)`.
**Example 1:**
**Input:** root = \[4,1,3,null,null,2\], val = 5
**Output:** \[5,4,null,1,3,null,null,2\]
**Explanation:** a = \[1,4,2,3\], b = \[1,4,2,3,5\]
**Example 2:**
**Input:** root = \[5,2,4,null,1\], val = 3
**Output:** \[5,2,4,null,1,null,3\]
**Explanation:** a = \[2,1,5,4\], b = \[2,1,5,4,3\]
**Example 3:**
**Input:** root = \[5,2,3,null,1\], val = 4
**Output:** \[5,2,4,null,1,3\]
**Explanation:** a = \[2,1,5,3\], b = \[2,1,5,3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 100`
* All the values of the tree are **unique**.
* `1 <= val <= 100` | null |
BFS, df, easy 3-line solution in Python | Ruby | Go | check-completeness-of-a-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBFS, Queue\n# Approach\n<!-- Describe your approach to solving the problem. -->\nafter first `node == None` all elements of `q` should be `None`\n# Complexity\n- Time complexity:\n$$O(n)$$\n- Space complexity:\n$$O(n)$$\n\n# Code\n```Python3 []\nclass Solution:\n def isCompleteTree(self, root: TreeNode | None) -> bool:\n q = [root]\n while node := q.pop(0): q += [node.left, node.right]\n return not any(q)\n```\n```Ruby []\ndef is_complete_tree(root)\n q = [root]\n q.push root.left, root.right while root = q.shift\n q.none?\nend\n```\n```Go []\nfunc isCompleteTree(root *TreeNode) bool {\n q := []*TreeNode{}\n for ; root != nil; root, q = q[0], q[1:] {\n q = append(q, root.Left, root.Right)\n }\n for _, root = range q {\n if root != nil { return false }\n }\n return true\n}\n``` | 1 | Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
**Example 2:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 1000` | null |
BFS, df, easy 3-line solution in Python | Ruby | Go | check-completeness-of-a-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBFS, Queue\n# Approach\n<!-- Describe your approach to solving the problem. -->\nafter first `node == None` all elements of `q` should be `None`\n# Complexity\n- Time complexity:\n$$O(n)$$\n- Space complexity:\n$$O(n)$$\n\n# Code\n```Python3 []\nclass Solution:\n def isCompleteTree(self, root: TreeNode | None) -> bool:\n q = [root]\n while node := q.pop(0): q += [node.left, node.right]\n return not any(q)\n```\n```Ruby []\ndef is_complete_tree(root)\n q = [root]\n q.push root.left, root.right while root = q.shift\n q.none?\nend\n```\n```Go []\nfunc isCompleteTree(root *TreeNode) bool {\n q := []*TreeNode{}\n for ; root != nil; root, q = q[0], q[1:] {\n q = append(q, root.Left, root.Right)\n }\n for _, root = range q {\n if root != nil { return false }\n }\n return true\n}\n``` | 1 | A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = Construct(a)`) recursively with the following `Construct(a)` routine:
* If `a` is empty, return `null`.
* Otherwise, let `a[i]` be the largest element of `a`. Create a `root` node with the value `a[i]`.
* The left child of `root` will be `Construct([a[0], a[1], ..., a[i - 1]])`.
* The right child of `root` will be `Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]])`.
* Return `root`.
Note that we were not given `a` directly, only a root node `root = Construct(a)`.
Suppose `b` is a copy of `a` with the value `val` appended to it. It is guaranteed that `b` has unique values.
Return `Construct(b)`.
**Example 1:**
**Input:** root = \[4,1,3,null,null,2\], val = 5
**Output:** \[5,4,null,1,3,null,null,2\]
**Explanation:** a = \[1,4,2,3\], b = \[1,4,2,3,5\]
**Example 2:**
**Input:** root = \[5,2,4,null,1\], val = 3
**Output:** \[5,2,4,null,1,null,3\]
**Explanation:** a = \[2,1,5,4\], b = \[2,1,5,4,3\]
**Example 3:**
**Input:** root = \[5,2,3,null,1\], val = 4
**Output:** \[5,2,4,null,1,3\]
**Explanation:** a = \[2,1,5,3\], b = \[2,1,5,3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 100`
* All the values of the tree are **unique**.
* `1 <= val <= 100` | null |
Clean Code Python | check-completeness-of-a-binary-tree | 0 | 1 | **Please upvote the solution if u liked**\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 isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n q=deque([root])\n while q[0]:\n node=q.popleft()\n q.extend([node.left,node.right])\n while q and not q[0]:\n q.popleft()\n return not q\n``` | 1 | Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
**Example 2:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 1000` | null |
Clean Code Python | check-completeness-of-a-binary-tree | 0 | 1 | **Please upvote the solution if u liked**\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 isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n q=deque([root])\n while q[0]:\n node=q.popleft()\n q.extend([node.left,node.right])\n while q and not q[0]:\n q.popleft()\n return not q\n``` | 1 | A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = Construct(a)`) recursively with the following `Construct(a)` routine:
* If `a` is empty, return `null`.
* Otherwise, let `a[i]` be the largest element of `a`. Create a `root` node with the value `a[i]`.
* The left child of `root` will be `Construct([a[0], a[1], ..., a[i - 1]])`.
* The right child of `root` will be `Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]])`.
* Return `root`.
Note that we were not given `a` directly, only a root node `root = Construct(a)`.
Suppose `b` is a copy of `a` with the value `val` appended to it. It is guaranteed that `b` has unique values.
Return `Construct(b)`.
**Example 1:**
**Input:** root = \[4,1,3,null,null,2\], val = 5
**Output:** \[5,4,null,1,3,null,null,2\]
**Explanation:** a = \[1,4,2,3\], b = \[1,4,2,3,5\]
**Example 2:**
**Input:** root = \[5,2,4,null,1\], val = 3
**Output:** \[5,2,4,null,1,null,3\]
**Explanation:** a = \[2,1,5,4\], b = \[2,1,5,4,3\]
**Example 3:**
**Input:** root = \[5,2,3,null,1\], val = 4
**Output:** \[5,2,4,null,1,3\]
**Explanation:** a = \[2,1,5,3\], b = \[2,1,5,3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 100`
* All the values of the tree are **unique**.
* `1 <= val <= 100` | null |
Python🐍 - Keeping track of the position of the last node seen (BFS) | check-completeness-of-a-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI keep track of the position of the last node I\'ve seen. The position in the binary tree is formed by the level of the tree and (at least what I called it) a column. In order for the tree to be complete, the current node always needs to be one higher than the last node; otherwise it\'s false.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\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 isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n queue = [(root, 0, 0)]\n position = 1\n while queue:\n node, level, column = queue.pop(0)\n if position != 2 ** level + column:\n return False\n\n if node.left:\n queue.append((node.left, level + 1, column * 2))\n if node.right:\n queue.append((node.right, level + 1, column * 2 + 1))\n\n position += 1\n\n return True\n \n``` | 1 | Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
**Example 2:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 1000` | null |
Python🐍 - Keeping track of the position of the last node seen (BFS) | check-completeness-of-a-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI keep track of the position of the last node I\'ve seen. The position in the binary tree is formed by the level of the tree and (at least what I called it) a column. In order for the tree to be complete, the current node always needs to be one higher than the last node; otherwise it\'s false.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\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 isCompleteTree(self, root: Optional[TreeNode]) -> bool:\n queue = [(root, 0, 0)]\n position = 1\n while queue:\n node, level, column = queue.pop(0)\n if position != 2 ** level + column:\n return False\n\n if node.left:\n queue.append((node.left, level + 1, column * 2))\n if node.right:\n queue.append((node.right, level + 1, column * 2 + 1))\n\n position += 1\n\n return True\n \n``` | 1 | A **maximum tree** is a tree where every node has a value greater than any other value in its subtree.
You are given the `root` of a maximum binary tree and an integer `val`.
Just as in the [previous problem](https://leetcode.com/problems/maximum-binary-tree/), the given tree was constructed from a list `a` (`root = Construct(a)`) recursively with the following `Construct(a)` routine:
* If `a` is empty, return `null`.
* Otherwise, let `a[i]` be the largest element of `a`. Create a `root` node with the value `a[i]`.
* The left child of `root` will be `Construct([a[0], a[1], ..., a[i - 1]])`.
* The right child of `root` will be `Construct([a[i + 1], a[i + 2], ..., a[a.length - 1]])`.
* Return `root`.
Note that we were not given `a` directly, only a root node `root = Construct(a)`.
Suppose `b` is a copy of `a` with the value `val` appended to it. It is guaranteed that `b` has unique values.
Return `Construct(b)`.
**Example 1:**
**Input:** root = \[4,1,3,null,null,2\], val = 5
**Output:** \[5,4,null,1,3,null,null,2\]
**Explanation:** a = \[1,4,2,3\], b = \[1,4,2,3,5\]
**Example 2:**
**Input:** root = \[5,2,4,null,1\], val = 3
**Output:** \[5,2,4,null,1,null,3\]
**Explanation:** a = \[2,1,5,4\], b = \[2,1,5,4,3\]
**Example 3:**
**Input:** root = \[5,2,3,null,1\], val = 4
**Output:** \[5,2,4,null,1,3\]
**Explanation:** a = \[2,1,5,3\], b = \[2,1,5,3,4\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 100`
* All the values of the tree are **unique**.
* `1 <= val <= 100` | null |
Solution | regions-cut-by-slashes | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n class DisjointSet {\n public: \n vector<int> rank, parent, size;\n DisjointSet(int n) {\n rank.resize(n+1, 0); \n parent.resize(n+1);\n size.resize(n+1); \n for(int i = 0;i<=n;i++) {\n parent[i] = i; \n size[i] = 1; \n }\n }\n int findparent(int node) {\n if(node == parent[node])\n return node; \n return parent[node] = findparent(parent[node]); \n }\n void unionByRank(int x, int y) {\n int u = findparent(x); \n int v = findparent(y); \n if(u == v) return; \n if(rank[u] < rank[v]) {\n parent[u] = v; \n }\n else if(rank[v] < rank[u]) {\n parent[v] = u; \n }\n else {\n parent[v] = u; \n rank[u]++; \n }\n }\n void unionBySize(int x, int y) {\n int u = findparent(x); \n int v = findparent(y); \n if(u == v) return; \n if(size[u] < size[v]) {\n parent[u] = v; \n size[v] += size[u]; \n size[u]=1;\n }\n else {\n parent[v] = u;\n size[u] += size[v];\n }\n }\n }; \n int regionsBySlashes(vector<string>& grid) {\n int m=grid.size();\n int n=grid[0].size();;\n \n int maxrow=m+1;\n int maxcol=n+1;\n\n DisjointSet ds(maxrow*maxcol);\n\n int ans=1;\n\n for(int i=0;i<maxrow;i++){\n for(int j=0;j<maxcol;j++){\n if( i==0 || j==0 || i==maxrow-1 || j==maxcol-1 ){\n int rownode=i*maxrow+j;\n if(rownode!=0)ds.unionBySize(0,rownode);\n }\n }\n } \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j]==\'/\'){\n int x1=i;\n int y1=j+1;\n int x2=i+1;\n int y2=j;\n int node1=x1*maxrow+y1;\n int node2=x2*maxrow+y2;\n if(ds.findparent(node1)!=ds.findparent(node2)){\n ds.unionBySize(node1,node2);\n }else{\n ans++;\n }\n }else if(grid[i][j]==\'\\\\\'){\n int x1=i;\n int y1=j;\n int x2=i+1;\n int y2=j+1;\n int node1=x1*maxrow+y1;\n int node2=x2*maxrow+y2;\n if(ds.findparent(node1)!=ds.findparent(node2)){\n ds.unionBySize(node1,node2);\n }else{\n ans++;\n }\n }\n }\n } \n return ans;\n }\n};\n```\n\n```Python3 []\nclass DSU:\n def __init__(self, n):\n self.parent = [i for i in range(n*n)]\n \n for i in range(n):\n self.parent[i] = 0\n self.parent[(n-1)*n + i] = 0\n \n for i in range(n):\n self.parent[i*n] = 0\n self.parent[(n-1) + i*n] = 0\n\n def find(self, x):\n if self.parent[x] != x:\n return self.find(self.parent[x])\n \n else:\n return x\n \n def union(self, x, y):\n px, py = self.find(x), self.find(y)\n self.parent[py] = px\n \n return px == py\n\nclass Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n \n ans = 0\n n = len(grid) + 1\n dsu = DSU(n)\n \n for i, row in enumerate(grid):\n for j, x in enumerate(row):\n if x == "/":\n ans += dsu.union(i*n + j + 1, (i+1)*n + j)\n \n elif x == "\\\\":\n ans += dsu.union(i*n + j, (i+1)*n + j + 1)\n \n return ans + 1\n```\n\n```Java []\nclass Solution {\n static int [] rank;\n static int [] p ;\n public int regionsBySlashes(String[] grid) {\n int n = grid.length;\n int m = n+1;\n rank = new int[m*m]; \n p = new int[m*m];\n int ans = 1;\n \n for(int i=0;i<m*m;i++)\n {\n p[i]=i;\n rank[i]=1;\n }\n for(int i=0;i<m;i++)\n {\n union(0,i);\n union(0,m*m-1-i);\n union(0,m*i);\n union(0,m-1 + m*i);\n }\n for(int i=0;i<n;i++){\n \n char[] arr = grid[i].toCharArray();\n \n for(int j=0;j<n;j++){\n if(arr[j]==\'/\'){\n int p1 = m*(i+1) + j;\n int p2 = m*(i) + j+1;\n if(union(p1,p2)) ans++;\n }else if(arr[j]==\'\\\\\'){\n int p1 = m*(i) + j;\n int p2 = m*(i+1) + j+1;\n if(union(p1,p2)) ans++;\n }\n }\n }\n return ans;\n }\n static int find(int x)\n {\n if(p[x]==x) return x;\n int temp = find(p[x]);\n p[x] = temp;\n return temp;\n }\n static boolean union(int x,int y)\n {\n int px = find(x);\n int py = find(y);\n \n if(px!=py)\n {\n if(rank[px]>rank[py]) p[py] = px; \n else if(rank[px]<rank[py]) p[px] = py; \n else{\n p[px] = py;\n rank[py]++;\n }\n return false;\n }\n return true;\n }\n}\n```\n | 1 | An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions.
Given the grid `grid` represented as a string array, return _the number of regions_.
Note that backslash characters are escaped, so a `'\'` is represented as `'\\'`.
**Example 1:**
**Input:** grid = \[ " / ", "/ "\]
**Output:** 2
**Example 2:**
**Input:** grid = \[ " / ", " "\]
**Output:** 1
**Example 3:**
**Input:** grid = \[ "/\\\\ ", "\\/ "\]
**Output:** 5
**Explanation:** Recall that because \\ characters are escaped, "\\/ " refers to /, and "/\\\\ " refers to /\\.
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 30`
* `grid[i][j]` is either `'/'`, `'\'`, or `' '`. | null |
Solution | regions-cut-by-slashes | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n class DisjointSet {\n public: \n vector<int> rank, parent, size;\n DisjointSet(int n) {\n rank.resize(n+1, 0); \n parent.resize(n+1);\n size.resize(n+1); \n for(int i = 0;i<=n;i++) {\n parent[i] = i; \n size[i] = 1; \n }\n }\n int findparent(int node) {\n if(node == parent[node])\n return node; \n return parent[node] = findparent(parent[node]); \n }\n void unionByRank(int x, int y) {\n int u = findparent(x); \n int v = findparent(y); \n if(u == v) return; \n if(rank[u] < rank[v]) {\n parent[u] = v; \n }\n else if(rank[v] < rank[u]) {\n parent[v] = u; \n }\n else {\n parent[v] = u; \n rank[u]++; \n }\n }\n void unionBySize(int x, int y) {\n int u = findparent(x); \n int v = findparent(y); \n if(u == v) return; \n if(size[u] < size[v]) {\n parent[u] = v; \n size[v] += size[u]; \n size[u]=1;\n }\n else {\n parent[v] = u;\n size[u] += size[v];\n }\n }\n }; \n int regionsBySlashes(vector<string>& grid) {\n int m=grid.size();\n int n=grid[0].size();;\n \n int maxrow=m+1;\n int maxcol=n+1;\n\n DisjointSet ds(maxrow*maxcol);\n\n int ans=1;\n\n for(int i=0;i<maxrow;i++){\n for(int j=0;j<maxcol;j++){\n if( i==0 || j==0 || i==maxrow-1 || j==maxcol-1 ){\n int rownode=i*maxrow+j;\n if(rownode!=0)ds.unionBySize(0,rownode);\n }\n }\n } \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j]==\'/\'){\n int x1=i;\n int y1=j+1;\n int x2=i+1;\n int y2=j;\n int node1=x1*maxrow+y1;\n int node2=x2*maxrow+y2;\n if(ds.findparent(node1)!=ds.findparent(node2)){\n ds.unionBySize(node1,node2);\n }else{\n ans++;\n }\n }else if(grid[i][j]==\'\\\\\'){\n int x1=i;\n int y1=j;\n int x2=i+1;\n int y2=j+1;\n int node1=x1*maxrow+y1;\n int node2=x2*maxrow+y2;\n if(ds.findparent(node1)!=ds.findparent(node2)){\n ds.unionBySize(node1,node2);\n }else{\n ans++;\n }\n }\n }\n } \n return ans;\n }\n};\n```\n\n```Python3 []\nclass DSU:\n def __init__(self, n):\n self.parent = [i for i in range(n*n)]\n \n for i in range(n):\n self.parent[i] = 0\n self.parent[(n-1)*n + i] = 0\n \n for i in range(n):\n self.parent[i*n] = 0\n self.parent[(n-1) + i*n] = 0\n\n def find(self, x):\n if self.parent[x] != x:\n return self.find(self.parent[x])\n \n else:\n return x\n \n def union(self, x, y):\n px, py = self.find(x), self.find(y)\n self.parent[py] = px\n \n return px == py\n\nclass Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n \n ans = 0\n n = len(grid) + 1\n dsu = DSU(n)\n \n for i, row in enumerate(grid):\n for j, x in enumerate(row):\n if x == "/":\n ans += dsu.union(i*n + j + 1, (i+1)*n + j)\n \n elif x == "\\\\":\n ans += dsu.union(i*n + j, (i+1)*n + j + 1)\n \n return ans + 1\n```\n\n```Java []\nclass Solution {\n static int [] rank;\n static int [] p ;\n public int regionsBySlashes(String[] grid) {\n int n = grid.length;\n int m = n+1;\n rank = new int[m*m]; \n p = new int[m*m];\n int ans = 1;\n \n for(int i=0;i<m*m;i++)\n {\n p[i]=i;\n rank[i]=1;\n }\n for(int i=0;i<m;i++)\n {\n union(0,i);\n union(0,m*m-1-i);\n union(0,m*i);\n union(0,m-1 + m*i);\n }\n for(int i=0;i<n;i++){\n \n char[] arr = grid[i].toCharArray();\n \n for(int j=0;j<n;j++){\n if(arr[j]==\'/\'){\n int p1 = m*(i+1) + j;\n int p2 = m*(i) + j+1;\n if(union(p1,p2)) ans++;\n }else if(arr[j]==\'\\\\\'){\n int p1 = m*(i) + j;\n int p2 = m*(i+1) + j+1;\n if(union(p1,p2)) ans++;\n }\n }\n }\n return ans;\n }\n static int find(int x)\n {\n if(p[x]==x) return x;\n int temp = find(p[x]);\n p[x] = temp;\n return temp;\n }\n static boolean union(int x,int y)\n {\n int px = find(x);\n int py = find(y);\n \n if(px!=py)\n {\n if(rank[px]>rank[py]) p[py] = px; \n else if(rank[px]<rank[py]) p[px] = py; \n else{\n p[px] = py;\n rank[py]++;\n }\n return false;\n }\n return true;\n }\n}\n```\n | 1 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered **attacking** a pawn if the rook can capture the pawn on the rook's turn. The **number of available captures** for the white rook is the number of pawns that the rook is **attacking**.
Return _the **number of available captures** for the white rook_.
**Example 1:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "R ", ". ", ". ", ". ", "p "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** In this example, the rook is attacking all the pawns.
**Example 2:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "B ", "R ", "B ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 0
**Explanation:** The bishops are blocking the rook from attacking any of the pawns.
**Example 3:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ "p ", "p ", ". ", "R ", ". ", "p ", "B ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** The rook is attacking the pawns at positions b5, d6, and f5.
**Constraints:**
* `board.length == 8`
* `board[i].length == 8`
* `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'`
* There is exactly one cell with `board[i][j] == 'R'` | null |
DFS on upscaled grid | regions-cut-by-slashes | 1 | 1 | We can upscale the input grid to `[n * 3][n * 3]` grid and draw "lines" there. Then, we can paint empty regions using DFS and count them. Picture below says it all. Note that `[n * 2][n * 2]` grid does not work as "lines" are too thick to identify empty areas correctly.\n\n> This transform this problem into [200. Number of Islands](https://leetcode.com/problems/number-of-islands/), where lines (\'1\') are the water, and rest (\'0\') is the land.\n\nI came up with this solution after I drew a few examples, and because I was lazy and saw it as an easy way. \n\n\n\n**C++**\n```\nint dfs(vector<vector<int>> &g, int i, int j) {\n if (min(i, j) < 0 || max(i, j) >= g.size() || g[i][j] != 0)\n return 0;\n g[i][j] = 1;\n return 1 + dfs(g, i - 1, j) + dfs(g, i + 1, j) + dfs(g, i, j - 1) + dfs(g, i, j + 1);\n}\nint regionsBySlashes(vector<string>& grid) {\n int n = grid.size(), regions = 0;\n vector<vector<int>> g(n * 3, vector<int>(n * 3, 0));\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == \'/\') \n g[i * 3][j * 3 + 2] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3] = 1;\n else if (grid[i][j] == \'\\\\\') \n g[i * 3][j * 3] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3 + 2] = 1;\n for (int i = 0; i < n * 3; ++i)\n for (int j = 0; j < n * 3; ++j)\n regions += dfs(g, i, j) ? 1 : 0; \n return regions;\n}\n```\n**Java**\n```java\nint dfs(int[][] g, int i, int j) {\n if (Math.min(i, j) < 0 || Math.max(i, j) >= g.length || g[i][j] != 0)\n return 0;\n g[i][j] = 1;\n return 1 + dfs(g, i - 1, j) + dfs(g, i + 1, j) + dfs(g, i, j - 1) + dfs(g, i, j + 1);\n} \npublic int regionsBySlashes(String[] grid) {\n int n = grid.length, regions = 0;\n int[][] g = new int[n * 3][n * 3];\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i].charAt(j) == \'/\') \n g[i * 3][j * 3 + 2] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3] = 1;\n else if (grid[i].charAt(j) == \'\\\\\') \n g[i * 3][j * 3] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3 + 2] = 1;\n for (int i = 0; i < n * 3; ++i)\n for (int j = 0; j < n * 3; ++j)\n regions += dfs(g, i, j) > 0 ? 1 : 0; \n return regions;\n}\n```\n**Python 3**\n```python\nclass Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n def dfs(i: int, j: int) -> int:\n if min(i, j) < 0 or max(i, j) >= len(g) or g[i][j] != 0:\n return 0\n g[i][j] = 1\n return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i, j + 1)\n n, regions = len(grid), 0\n g = [[0] * n * 3 for i in range(n * 3)]\n for i in range(n):\n for j in range(n):\n if grid[i][j] == \'/\':\n g[i * 3][j * 3 + 2] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3] = 1\n elif grid[i][j] == \'\\\\\':\n g[i * 3][j * 3] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3 + 2] = 1\n for i in range(n * 3):\n for j in range(n * 3):\n regions += 1 if dfs(i, j) > 0 else 0\n return regions\n``` | 812 | An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions.
Given the grid `grid` represented as a string array, return _the number of regions_.
Note that backslash characters are escaped, so a `'\'` is represented as `'\\'`.
**Example 1:**
**Input:** grid = \[ " / ", "/ "\]
**Output:** 2
**Example 2:**
**Input:** grid = \[ " / ", " "\]
**Output:** 1
**Example 3:**
**Input:** grid = \[ "/\\\\ ", "\\/ "\]
**Output:** 5
**Explanation:** Recall that because \\ characters are escaped, "\\/ " refers to /, and "/\\\\ " refers to /\\.
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 30`
* `grid[i][j]` is either `'/'`, `'\'`, or `' '`. | null |
DFS on upscaled grid | regions-cut-by-slashes | 1 | 1 | We can upscale the input grid to `[n * 3][n * 3]` grid and draw "lines" there. Then, we can paint empty regions using DFS and count them. Picture below says it all. Note that `[n * 2][n * 2]` grid does not work as "lines" are too thick to identify empty areas correctly.\n\n> This transform this problem into [200. Number of Islands](https://leetcode.com/problems/number-of-islands/), where lines (\'1\') are the water, and rest (\'0\') is the land.\n\nI came up with this solution after I drew a few examples, and because I was lazy and saw it as an easy way. \n\n\n\n**C++**\n```\nint dfs(vector<vector<int>> &g, int i, int j) {\n if (min(i, j) < 0 || max(i, j) >= g.size() || g[i][j] != 0)\n return 0;\n g[i][j] = 1;\n return 1 + dfs(g, i - 1, j) + dfs(g, i + 1, j) + dfs(g, i, j - 1) + dfs(g, i, j + 1);\n}\nint regionsBySlashes(vector<string>& grid) {\n int n = grid.size(), regions = 0;\n vector<vector<int>> g(n * 3, vector<int>(n * 3, 0));\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i][j] == \'/\') \n g[i * 3][j * 3 + 2] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3] = 1;\n else if (grid[i][j] == \'\\\\\') \n g[i * 3][j * 3] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3 + 2] = 1;\n for (int i = 0; i < n * 3; ++i)\n for (int j = 0; j < n * 3; ++j)\n regions += dfs(g, i, j) ? 1 : 0; \n return regions;\n}\n```\n**Java**\n```java\nint dfs(int[][] g, int i, int j) {\n if (Math.min(i, j) < 0 || Math.max(i, j) >= g.length || g[i][j] != 0)\n return 0;\n g[i][j] = 1;\n return 1 + dfs(g, i - 1, j) + dfs(g, i + 1, j) + dfs(g, i, j - 1) + dfs(g, i, j + 1);\n} \npublic int regionsBySlashes(String[] grid) {\n int n = grid.length, regions = 0;\n int[][] g = new int[n * 3][n * 3];\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n if (grid[i].charAt(j) == \'/\') \n g[i * 3][j * 3 + 2] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3] = 1;\n else if (grid[i].charAt(j) == \'\\\\\') \n g[i * 3][j * 3] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3 + 2] = 1;\n for (int i = 0; i < n * 3; ++i)\n for (int j = 0; j < n * 3; ++j)\n regions += dfs(g, i, j) > 0 ? 1 : 0; \n return regions;\n}\n```\n**Python 3**\n```python\nclass Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n def dfs(i: int, j: int) -> int:\n if min(i, j) < 0 or max(i, j) >= len(g) or g[i][j] != 0:\n return 0\n g[i][j] = 1\n return 1 + dfs(i - 1, j) + dfs(i + 1, j) + dfs(i, j - 1) + dfs(i, j + 1)\n n, regions = len(grid), 0\n g = [[0] * n * 3 for i in range(n * 3)]\n for i in range(n):\n for j in range(n):\n if grid[i][j] == \'/\':\n g[i * 3][j * 3 + 2] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3] = 1\n elif grid[i][j] == \'\\\\\':\n g[i * 3][j * 3] = g[i * 3 + 1][j * 3 + 1] = g[i * 3 + 2][j * 3 + 2] = 1\n for i in range(n * 3):\n for j in range(n * 3):\n regions += 1 if dfs(i, j) > 0 else 0\n return regions\n``` | 812 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered **attacking** a pawn if the rook can capture the pawn on the rook's turn. The **number of available captures** for the white rook is the number of pawns that the rook is **attacking**.
Return _the **number of available captures** for the white rook_.
**Example 1:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "R ", ". ", ". ", ". ", "p "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** In this example, the rook is attacking all the pawns.
**Example 2:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "B ", "R ", "B ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 0
**Explanation:** The bishops are blocking the rook from attacking any of the pawns.
**Example 3:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ "p ", "p ", ". ", "R ", ". ", "p ", "B ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** The rook is attacking the pawns at positions b5, d6, and f5.
**Constraints:**
* `board.length == 8`
* `board[i].length == 8`
* `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'`
* There is exactly one cell with `board[i][j] == 'R'` | null |
Python Union Find solution with comments (easy to understand) | regions-cut-by-slashes | 0 | 1 | ```\nclass UnionFind:\n def __init__(self, n):\n self.parent = [i for i in range(n)]\n \n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n \n def union(self, a, b):\n self.parent[self.find(b)] = self.find(a)\n\nclass Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n n = len(grid)\n # Divide each square into 4 triangles\n uf = UnionFind(4 * n * n) \n \n for row in range(n):\n for col in range(n):\n cell = grid[row][col]\n index = 4 * (row * n + col) \n \n # When there are no lines in the square\n if cell == \' \':\n uf.union(index+0, index+1)\n uf.union(index+1, index+2)\n uf.union(index+2, index+3)\n # When there\'s a bottom left - top right diagonal line dividing the square\n if cell == \'/\':\n uf.union(index+0, index+3)\n uf.union(index+1, index+2)\n # When there\'s a top left - bottom right diagonal line dividing the square\n if cell == \'\\\\\':\n uf.union(index+2, index+3)\n uf.union(index+0, index+1)\n # Connecting a square with square below it\n if row < n - 1:\n uf.union(index+2, (index + 4*n) + 0)\n # Connecting a square with right side square\n if col < n - 1:\n uf.union(index+1, (index + 4) + 3)\n \n output = 0\n for i in range(4*n*n):\n if uf.find(i) == i:\n output += 1\n return output\n``` | 13 | An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions.
Given the grid `grid` represented as a string array, return _the number of regions_.
Note that backslash characters are escaped, so a `'\'` is represented as `'\\'`.
**Example 1:**
**Input:** grid = \[ " / ", "/ "\]
**Output:** 2
**Example 2:**
**Input:** grid = \[ " / ", " "\]
**Output:** 1
**Example 3:**
**Input:** grid = \[ "/\\\\ ", "\\/ "\]
**Output:** 5
**Explanation:** Recall that because \\ characters are escaped, "\\/ " refers to /, and "/\\\\ " refers to /\\.
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 30`
* `grid[i][j]` is either `'/'`, `'\'`, or `' '`. | null |
Python Union Find solution with comments (easy to understand) | regions-cut-by-slashes | 0 | 1 | ```\nclass UnionFind:\n def __init__(self, n):\n self.parent = [i for i in range(n)]\n \n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n \n def union(self, a, b):\n self.parent[self.find(b)] = self.find(a)\n\nclass Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n n = len(grid)\n # Divide each square into 4 triangles\n uf = UnionFind(4 * n * n) \n \n for row in range(n):\n for col in range(n):\n cell = grid[row][col]\n index = 4 * (row * n + col) \n \n # When there are no lines in the square\n if cell == \' \':\n uf.union(index+0, index+1)\n uf.union(index+1, index+2)\n uf.union(index+2, index+3)\n # When there\'s a bottom left - top right diagonal line dividing the square\n if cell == \'/\':\n uf.union(index+0, index+3)\n uf.union(index+1, index+2)\n # When there\'s a top left - bottom right diagonal line dividing the square\n if cell == \'\\\\\':\n uf.union(index+2, index+3)\n uf.union(index+0, index+1)\n # Connecting a square with square below it\n if row < n - 1:\n uf.union(index+2, (index + 4*n) + 0)\n # Connecting a square with right side square\n if col < n - 1:\n uf.union(index+1, (index + 4) + 3)\n \n output = 0\n for i in range(4*n*n):\n if uf.find(i) == i:\n output += 1\n return output\n``` | 13 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered **attacking** a pawn if the rook can capture the pawn on the rook's turn. The **number of available captures** for the white rook is the number of pawns that the rook is **attacking**.
Return _the **number of available captures** for the white rook_.
**Example 1:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "R ", ". ", ". ", ". ", "p "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** In this example, the rook is attacking all the pawns.
**Example 2:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "B ", "R ", "B ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 0
**Explanation:** The bishops are blocking the rook from attacking any of the pawns.
**Example 3:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ "p ", "p ", ". ", "R ", ". ", "p ", "B ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** The rook is attacking the pawns at positions b5, d6, and f5.
**Constraints:**
* `board.length == 8`
* `board[i].length == 8`
* `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'`
* There is exactly one cell with `board[i][j] == 'R'` | null |
Python Solution based on Transformation | regions-cut-by-slashes | 0 | 1 | # Intuition\nThe key takeaway here is to design graphs, not graph algorithms, which we get from Skiena. To this end, we "blow up" the original graph into a bigger graph, where the connections between cells are more obvious.\n\n# Approach\nWe transform each cell of the original graph into 4 cells on a new graph. The transformations are as follows:\n\n" " ---> [" ", " "]\n"/" ---> [" /", "/ "]\n"\\" ---> ["\\ ", " \\"]\n\n# Complexity\n- Time complexity:\nTime compexity is O(V+E), since we use BFS. Copying the graph is also done in linear time in terms of the vertices and edges.\n\nThere\'s a constant factor of at least 4 when we are copying the graph, but this still keeps us in linear time. If desired, we could fine-tune this algorithm to have a lower constant factor, and probably also save on space complexity in the process. \n\nNote that in terms of the vertices, this makes it O(V^2) in worst-case, since there are at most V^2 edges.\n\n- Space complexity:\nSpace complexity is O(V+E) or O(V^2), since we copy the graph and keep a discovered matrix. There are a few significant constant factors here, again we could probably save on this if we fine-tuned the algorithm a bit.\n\nSince we are given an input that\'s size O(V^2), both time and space complexity are linear in terms of the input, which is reasonable since we assume that we have to at least read the entire input into memory (or over the course of the algorithm).\n\n# Code\n```\nclass Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n graph = self.generate_graph(grid)\n\n num_regions = self.connected_components(graph)\n\n return num_regions\n \n def generate_graph(self, orig_grid):\n graph = []\n n = len(orig_grid)\n for _ in range(2*n):\n row = [" " for _ in range(2*n)]\n graph.append(row)\n \n for i, orig_row in enumerate(orig_grid):\n for j, letter in enumerate(orig_row):\n # (i, j) -> (2*i, 2*j), (2*i + 1, 2*j), (2*i + 1, 2*j + 1), (2*i, 2*j + 1)\n if letter == "/":\n graph[2*i + 1][2*j] = "/"\n graph[2*i][2*j + 1] = "/"\n elif letter == "\\\\":\n graph[2*i][2*j] = "\\\\"\n graph[2*i+1][2*j+1] = "\\\\"\n \n return graph\n\n \n def connected_components(self, graph):\n num_components = 0\n\n discovered = [[0 for _ in graph[i]] for i, _ in enumerate(graph)]\n\n for i, row in enumerate(graph):\n for j, val in enumerate(row):\n if val != "/" and val != "\\\\" and discovered[i][j] == 0:\n num_components += 1\n queue = [(i,j)]\n discovered[i][j] = 1\n while queue:\n curr_i, curr_j = queue.pop(0)\n for neigh_i, neigh_j in self.get_neighbors(curr_i, curr_j, graph):\n if graph[neigh_i][neigh_j] != "/" \\\n and graph[neigh_i][neigh_j] != "\\\\" \\\n and discovered[neigh_i][neigh_j] == 0:\n queue.append((neigh_i, neigh_j))\n discovered[neigh_i][neigh_j] = 1\n discovered[curr_i][curr_j] = 2\n\n return num_components\n\n def get_neighbors(self, curr_i, curr_j, graph):\n above = (-1,0)\n below = (1,0)\n right = (0,1)\n left = (0,-1)\n\n lower_right = (1,1)\n upper_left = (-1,-1)\n lower_left = (1,-1)\n upper_right = (-1,1)\n\n directions = [above, below, right, left]\n diagonals = [lower_right, # lower right -- can traverse if \'\\\\\' are to right and to below\n upper_left, # upper left -- can traverse if \'\\\\\' are to above and to left\n lower_left, # lower left -- can traverse if \'/\' are to left and to below\n upper_right] # upper right -- can traverse if \'/\' are to right and to above\n\n neighbors = []\n\n for dx, dy in directions:\n if self.is_valid_index(curr_i, curr_j, dx, dy, graph):\n neighbors.append((curr_i+dx, curr_j+dy))\n \n for diag in diagonals:\n dx, dy = diag\n if self.is_valid_index(curr_i, curr_j, dx, dy, graph):\n if diag == lower_right: # desire "\\\\"\n dx1, dy1 = right\n dx2, dy2 = below\n if graph[curr_i+dx1][curr_j+dy1] == "\\\\" \\\n and graph[curr_i+dx2][curr_j+dy2] == "\\\\":\n neighbors.append((curr_i+dx, curr_j+dy))\n elif diag == upper_left: # desire "\\\\"\n dx1, dy1 = above\n dx2, dy2 = left\n if graph[curr_i+dx1][curr_j+dy1] == "\\\\" \\\n and graph[curr_i+dx2][curr_j+dy2] == "\\\\":\n neighbors.append((curr_i+dx, curr_j+dy))\n elif diag == lower_left: # desire "/"\n dx1, dy1 = left\n dx2, dy2 = below\n if graph[curr_i+dx1][curr_j+dy1] == "/" \\\n and graph[curr_i+dx2][curr_j+dy2] == "/":\n neighbors.append((curr_i+dx, curr_j+dy))\n elif diag == upper_right: # desire "/"\n dx1, dy1 = above\n dx2, dy2 = right\n if graph[curr_i+dx1][curr_j+dy1] == "/" \\\n and graph[curr_i+dx2][curr_j+dy2] == "/":\n neighbors.append((curr_i+dx, curr_j+dy))\n \n return neighbors\n\n def is_valid_index(self, curr_i, curr_j, dx, dy, graph):\n if curr_i + dx >= 0 \\\n and curr_j + dy >= 0 \\\n and curr_i + dx < len(graph) \\\n and curr_j + dy < len(graph[0]) \\\n and graph[curr_i+dx][curr_j+dy] != "/" \\\n and graph[curr_i+dx][curr_j+dy] != "\\\\":\n return True\n return False\n \n``` | 0 | An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions.
Given the grid `grid` represented as a string array, return _the number of regions_.
Note that backslash characters are escaped, so a `'\'` is represented as `'\\'`.
**Example 1:**
**Input:** grid = \[ " / ", "/ "\]
**Output:** 2
**Example 2:**
**Input:** grid = \[ " / ", " "\]
**Output:** 1
**Example 3:**
**Input:** grid = \[ "/\\\\ ", "\\/ "\]
**Output:** 5
**Explanation:** Recall that because \\ characters are escaped, "\\/ " refers to /, and "/\\\\ " refers to /\\.
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 30`
* `grid[i][j]` is either `'/'`, `'\'`, or `' '`. | null |
Python Solution based on Transformation | regions-cut-by-slashes | 0 | 1 | # Intuition\nThe key takeaway here is to design graphs, not graph algorithms, which we get from Skiena. To this end, we "blow up" the original graph into a bigger graph, where the connections between cells are more obvious.\n\n# Approach\nWe transform each cell of the original graph into 4 cells on a new graph. The transformations are as follows:\n\n" " ---> [" ", " "]\n"/" ---> [" /", "/ "]\n"\\" ---> ["\\ ", " \\"]\n\n# Complexity\n- Time complexity:\nTime compexity is O(V+E), since we use BFS. Copying the graph is also done in linear time in terms of the vertices and edges.\n\nThere\'s a constant factor of at least 4 when we are copying the graph, but this still keeps us in linear time. If desired, we could fine-tune this algorithm to have a lower constant factor, and probably also save on space complexity in the process. \n\nNote that in terms of the vertices, this makes it O(V^2) in worst-case, since there are at most V^2 edges.\n\n- Space complexity:\nSpace complexity is O(V+E) or O(V^2), since we copy the graph and keep a discovered matrix. There are a few significant constant factors here, again we could probably save on this if we fine-tuned the algorithm a bit.\n\nSince we are given an input that\'s size O(V^2), both time and space complexity are linear in terms of the input, which is reasonable since we assume that we have to at least read the entire input into memory (or over the course of the algorithm).\n\n# Code\n```\nclass Solution:\n def regionsBySlashes(self, grid: List[str]) -> int:\n graph = self.generate_graph(grid)\n\n num_regions = self.connected_components(graph)\n\n return num_regions\n \n def generate_graph(self, orig_grid):\n graph = []\n n = len(orig_grid)\n for _ in range(2*n):\n row = [" " for _ in range(2*n)]\n graph.append(row)\n \n for i, orig_row in enumerate(orig_grid):\n for j, letter in enumerate(orig_row):\n # (i, j) -> (2*i, 2*j), (2*i + 1, 2*j), (2*i + 1, 2*j + 1), (2*i, 2*j + 1)\n if letter == "/":\n graph[2*i + 1][2*j] = "/"\n graph[2*i][2*j + 1] = "/"\n elif letter == "\\\\":\n graph[2*i][2*j] = "\\\\"\n graph[2*i+1][2*j+1] = "\\\\"\n \n return graph\n\n \n def connected_components(self, graph):\n num_components = 0\n\n discovered = [[0 for _ in graph[i]] for i, _ in enumerate(graph)]\n\n for i, row in enumerate(graph):\n for j, val in enumerate(row):\n if val != "/" and val != "\\\\" and discovered[i][j] == 0:\n num_components += 1\n queue = [(i,j)]\n discovered[i][j] = 1\n while queue:\n curr_i, curr_j = queue.pop(0)\n for neigh_i, neigh_j in self.get_neighbors(curr_i, curr_j, graph):\n if graph[neigh_i][neigh_j] != "/" \\\n and graph[neigh_i][neigh_j] != "\\\\" \\\n and discovered[neigh_i][neigh_j] == 0:\n queue.append((neigh_i, neigh_j))\n discovered[neigh_i][neigh_j] = 1\n discovered[curr_i][curr_j] = 2\n\n return num_components\n\n def get_neighbors(self, curr_i, curr_j, graph):\n above = (-1,0)\n below = (1,0)\n right = (0,1)\n left = (0,-1)\n\n lower_right = (1,1)\n upper_left = (-1,-1)\n lower_left = (1,-1)\n upper_right = (-1,1)\n\n directions = [above, below, right, left]\n diagonals = [lower_right, # lower right -- can traverse if \'\\\\\' are to right and to below\n upper_left, # upper left -- can traverse if \'\\\\\' are to above and to left\n lower_left, # lower left -- can traverse if \'/\' are to left and to below\n upper_right] # upper right -- can traverse if \'/\' are to right and to above\n\n neighbors = []\n\n for dx, dy in directions:\n if self.is_valid_index(curr_i, curr_j, dx, dy, graph):\n neighbors.append((curr_i+dx, curr_j+dy))\n \n for diag in diagonals:\n dx, dy = diag\n if self.is_valid_index(curr_i, curr_j, dx, dy, graph):\n if diag == lower_right: # desire "\\\\"\n dx1, dy1 = right\n dx2, dy2 = below\n if graph[curr_i+dx1][curr_j+dy1] == "\\\\" \\\n and graph[curr_i+dx2][curr_j+dy2] == "\\\\":\n neighbors.append((curr_i+dx, curr_j+dy))\n elif diag == upper_left: # desire "\\\\"\n dx1, dy1 = above\n dx2, dy2 = left\n if graph[curr_i+dx1][curr_j+dy1] == "\\\\" \\\n and graph[curr_i+dx2][curr_j+dy2] == "\\\\":\n neighbors.append((curr_i+dx, curr_j+dy))\n elif diag == lower_left: # desire "/"\n dx1, dy1 = left\n dx2, dy2 = below\n if graph[curr_i+dx1][curr_j+dy1] == "/" \\\n and graph[curr_i+dx2][curr_j+dy2] == "/":\n neighbors.append((curr_i+dx, curr_j+dy))\n elif diag == upper_right: # desire "/"\n dx1, dy1 = above\n dx2, dy2 = right\n if graph[curr_i+dx1][curr_j+dy1] == "/" \\\n and graph[curr_i+dx2][curr_j+dy2] == "/":\n neighbors.append((curr_i+dx, curr_j+dy))\n \n return neighbors\n\n def is_valid_index(self, curr_i, curr_j, dx, dy, graph):\n if curr_i + dx >= 0 \\\n and curr_j + dy >= 0 \\\n and curr_i + dx < len(graph) \\\n and curr_j + dy < len(graph[0]) \\\n and graph[curr_i+dx][curr_j+dy] != "/" \\\n and graph[curr_i+dx][curr_j+dy] != "\\\\":\n return True\n return False\n \n``` | 0 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered **attacking** a pawn if the rook can capture the pawn on the rook's turn. The **number of available captures** for the white rook is the number of pawns that the rook is **attacking**.
Return _the **number of available captures** for the white rook_.
**Example 1:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "R ", ". ", ". ", ". ", "p "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** In this example, the rook is attacking all the pawns.
**Example 2:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "B ", "R ", "B ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 0
**Explanation:** The bishops are blocking the rook from attacking any of the pawns.
**Example 3:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ "p ", "p ", ". ", "R ", ". ", "p ", "B ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** The rook is attacking the pawns at positions b5, d6, and f5.
**Constraints:**
* `board.length == 8`
* `board[i].length == 8`
* `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'`
* There is exactly one cell with `board[i][j] == 'R'` | null |
Union find solution | regions-cut-by-slashes | 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(object):\n def regionsBySlashes(self, grid):\n """\n :type grid: List[str]\n :rtype: int\n """\n\n matrix = []\n\n for i in range(len(grid)):\n tmp = []\n for j in range(len(grid[i])):\n tmp.append(grid[i][j])\n matrix.append(tmp)\n\n n = len(matrix)+1\n\n par = [i for i in range((n*n+1))]\n rank = [1 for _ in range((n*n+1))]\n\n def findPar(node):\n p = par[node]\n\n while(p != par[p]):\n par[p] = par[par[p]]\n\n p = par[p]\n\n return p\n\n def union(n1, n2):\n p1, p2 = findPar(n1), findPar(n2)\n\n if p1 == p2:\n return False\n elif rank[p1] > rank[p2]:\n par[p2] = p1\n rank[p1] += rank[p2]\n else:\n par[p1] = p2\n rank[p2] += rank[p1]\n\n return True\n\n for i in range(n-1):\n n1, n2 = 0*n+i, 0*n+(i+1)\n union(n1, n2)\n\n for i in range(n-1):\n n1, n2 = (n-1)*n+i, (n-1)*n+(i+1)\n union(n1, n2)\n\n for i in range(n-1):\n n1, n2 = i*n+0, (i+1)*n+0\n union(n1, n2)\n\n for i in range(n-1):\n n1, n2 = i*n+(n-1), (i+1)*n+(n-1)\n union(n1, n2)\n\n region = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == \'/\':\n n1, n2 = (i+1)*n+j, (i)*n+(j+1)\n\n if union(n1, n2) == False:\n region += 1\n elif matrix[i][j] == \'\\\\\':\n n1, n2 = (i+1)*n+(j+1), (i)*n+j\n\n if union(n1, n2) == False:\n region += 1\n\n return region+1\n\n \n``` | 0 | An `n x n` grid is composed of `1 x 1` squares where each `1 x 1` square consists of a `'/'`, `'\'`, or blank space `' '`. These characters divide the square into contiguous regions.
Given the grid `grid` represented as a string array, return _the number of regions_.
Note that backslash characters are escaped, so a `'\'` is represented as `'\\'`.
**Example 1:**
**Input:** grid = \[ " / ", "/ "\]
**Output:** 2
**Example 2:**
**Input:** grid = \[ " / ", " "\]
**Output:** 1
**Example 3:**
**Input:** grid = \[ "/\\\\ ", "\\/ "\]
**Output:** 5
**Explanation:** Recall that because \\ characters are escaped, "\\/ " refers to /, and "/\\\\ " refers to /\\.
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 30`
* `grid[i][j]` is either `'/'`, `'\'`, or `' '`. | null |
Union find solution | regions-cut-by-slashes | 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(object):\n def regionsBySlashes(self, grid):\n """\n :type grid: List[str]\n :rtype: int\n """\n\n matrix = []\n\n for i in range(len(grid)):\n tmp = []\n for j in range(len(grid[i])):\n tmp.append(grid[i][j])\n matrix.append(tmp)\n\n n = len(matrix)+1\n\n par = [i for i in range((n*n+1))]\n rank = [1 for _ in range((n*n+1))]\n\n def findPar(node):\n p = par[node]\n\n while(p != par[p]):\n par[p] = par[par[p]]\n\n p = par[p]\n\n return p\n\n def union(n1, n2):\n p1, p2 = findPar(n1), findPar(n2)\n\n if p1 == p2:\n return False\n elif rank[p1] > rank[p2]:\n par[p2] = p1\n rank[p1] += rank[p2]\n else:\n par[p1] = p2\n rank[p2] += rank[p1]\n\n return True\n\n for i in range(n-1):\n n1, n2 = 0*n+i, 0*n+(i+1)\n union(n1, n2)\n\n for i in range(n-1):\n n1, n2 = (n-1)*n+i, (n-1)*n+(i+1)\n union(n1, n2)\n\n for i in range(n-1):\n n1, n2 = i*n+0, (i+1)*n+0\n union(n1, n2)\n\n for i in range(n-1):\n n1, n2 = i*n+(n-1), (i+1)*n+(n-1)\n union(n1, n2)\n\n region = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == \'/\':\n n1, n2 = (i+1)*n+j, (i)*n+(j+1)\n\n if union(n1, n2) == False:\n region += 1\n elif matrix[i][j] == \'\\\\\':\n n1, n2 = (i+1)*n+(j+1), (i)*n+j\n\n if union(n1, n2) == False:\n region += 1\n\n return region+1\n\n \n``` | 0 | On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered **attacking** a pawn if the rook can capture the pawn on the rook's turn. The **number of available captures** for the white rook is the number of pawns that the rook is **attacking**.
Return _the **number of available captures** for the white rook_.
**Example 1:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "R ", ". ", ". ", ". ", "p "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** In this example, the rook is attacking all the pawns.
**Example 2:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "B ", "R ", "B ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 0
**Explanation:** The bishops are blocking the rook from attacking any of the pawns.
**Example 3:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ "p ", "p ", ". ", "R ", ". ", "p ", "B ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** The rook is attacking the pawns at positions b5, d6, and f5.
**Constraints:**
* `board.length == 8`
* `board[i].length == 8`
* `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'`
* There is exactly one cell with `board[i][j] == 'R'` | null |
Python 3 || 6 lines, dp || T/M: 64% / 64% | delete-columns-to-make-sorted-iii | 0 | 1 | ```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n\n n = len(strs[0])\n\n isValid = lambda x: all(s[x] <= s[j] for s in strs)\n\n dp = [1] * n\n\n for j in range(1, n):\n\n dp[j] = max((dp[x] for x in \n filter(isValid,range(j))), default = 0) + 1\n \n return n - max(dp)\n```\n[https://leetcode.com/problems/delete-columns-to-make-sorted-iii/submissions/1024310229/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*MN*) and space complexity is *O*(*N*), in which *N* ~ `len(strs)` *M* ~ `len(strs[0])`. | 3 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Python 3 || 6 lines, dp || T/M: 64% / 64% | delete-columns-to-make-sorted-iii | 0 | 1 | ```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n\n n = len(strs[0])\n\n isValid = lambda x: all(s[x] <= s[j] for s in strs)\n\n dp = [1] * n\n\n for j in range(1, n):\n\n dp[j] = max((dp[x] for x in \n filter(isValid,range(j))), default = 0) + 1\n \n return n - max(dp)\n```\n[https://leetcode.com/problems/delete-columns-to-make-sorted-iii/submissions/1024310229/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*MN*) and space complexity is *O*(*N*), in which *N* ~ `len(strs)` *M* ~ `len(strs[0])`. | 3 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
Solution | delete-columns-to-make-sorted-iii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minDeletionSize(vector<string>& strs) {\n \n int n = strs.size();\n int m = strs[0].length();\n\n vector<int> dp(m, 1);\n int res = 1;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < i; j++) {\n for(int k = 0; k <= n; k++) {\n if(k == n) {\n dp[i] = max(dp[i], dp[j] + 1);\n res = max(res, dp[i]);\n } else if (strs[k][j] > strs[k][i]) {\n break;\n }\n }\n }\n }\n return m - res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n n = len(strs[0])\n dp = [1] * n\n for i in range(1, n):\n for j in range(i):\n valid = True\n for a in strs:\n if a[j] > a[i]: \n valid = False\n break\n if valid:\n dp[i] = max(dp[i], dp[j] + 1)\n return n - max(dp)\n```\n\n```Java []\nclass Solution {\n public int minDeletionSize(String[] strs) {\n \n int length = strs[0].length();\n int[] dp = new int[length];\n \n int max = 0;\n for (int i = 0; i < length; i++){\n dp[i] = 1;\n for (int j = 0; j < i; j++){\n if (checkLager(j,i, strs)){\n dp[i] = Math.max(dp[i], dp[j] + 1);\n }\n }\n max = Math.max(max, dp[i]);\n }\n return length - max;\n }\n public boolean checkLager(int j, int i, String[] strs){\n for (String s : strs){\n if (s.charAt(j) > s.charAt(i)){\n return false;\n }\n }\n return true;\n }\n}\n```\n | 1 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Solution | delete-columns-to-make-sorted-iii | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int minDeletionSize(vector<string>& strs) {\n \n int n = strs.size();\n int m = strs[0].length();\n\n vector<int> dp(m, 1);\n int res = 1;\n for(int i = 0; i < m; i++) {\n for(int j = 0; j < i; j++) {\n for(int k = 0; k <= n; k++) {\n if(k == n) {\n dp[i] = max(dp[i], dp[j] + 1);\n res = max(res, dp[i]);\n } else if (strs[k][j] > strs[k][i]) {\n break;\n }\n }\n }\n }\n return m - res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n n = len(strs[0])\n dp = [1] * n\n for i in range(1, n):\n for j in range(i):\n valid = True\n for a in strs:\n if a[j] > a[i]: \n valid = False\n break\n if valid:\n dp[i] = max(dp[i], dp[j] + 1)\n return n - max(dp)\n```\n\n```Java []\nclass Solution {\n public int minDeletionSize(String[] strs) {\n \n int length = strs[0].length();\n int[] dp = new int[length];\n \n int max = 0;\n for (int i = 0; i < length; i++){\n dp[i] = 1;\n for (int j = 0; j < i; j++){\n if (checkLager(j,i, strs)){\n dp[i] = Math.max(dp[i], dp[j] + 1);\n }\n }\n max = Math.max(max, dp[i]);\n }\n return length - max;\n }\n public boolean checkLager(int j, int i, String[] strs){\n for (String s : strs){\n if (s.charAt(j) > s.charAt(i)){\n return false;\n }\n }\n return true;\n }\n}\n```\n | 1 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
[Python3] O(mn^2) DP | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is similar to longest non-decrease subseqence, except we need to consider all strings at the same time.\n\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0])\n dp = [1] * n\n for i in range(1, n):\n for j in range(i):\n if all(strs[k][i] >= strs[k][j] for k in range(m)):\n dp[i] = max(dp[i], dp[j] + 1)\n return n - max(dp)\n``` | 1 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
[Python3] O(mn^2) DP | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is similar to longest non-decrease subseqence, except we need to consider all strings at the same time.\n\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0])\n dp = [1] * n\n for i in range(1, n):\n for j in range(i):\n if all(strs[k][i] >= strs[k][j] for k in range(m)):\n dp[i] = max(dp[i], dp[j] + 1)\n return n - max(dp)\n``` | 1 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
Solution to 960. Delete Columns to Make Sorted III | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this problem is to find the longest increasing subsequence of columns. This is because the columns in the longest increasing subsequence do not need to be deleted to make the rows sorted. The remaining columns, which are not part of this subsequence, need to be deleted.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to use dynamic programming. We iterate over the columns of the input from right to left. For each column, we check if it is lexicographically less than or equal to all other columns to its right. If it is, we update the dynamic programming array to keep track of the maximum increasing subsequence of columns. The final answer is the total number of columns minus the length of the maximum increasing subsequence.\n# Pseudocode\n```\nProcedure minDeletionSize(strs: List of strings) -> int:\n Initialize W as the width of the input (length of any string in strs)\n Initialize dp as an array of size W with all elements as 1\n\n For i from W-2 to 0 (inclusive) in reverse order:\n For j from i+1 to W (exclusive):\n If all characters at index j in strs are greater than or equal to characters at index i:\n Update dp[i] as the maximum of dp[i] and 1 + dp[j]\n\n Return W - maximum value in dp\nEnd Procedure\n\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is $$O(W2\u22C5N)$$, where $$W$$ is the width of the input and $$N$$ is the number of strings. This is because for each column, we compare it with all other columns to its right, and for each comparison, we check all the strings.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is $$O(W)$$, where $$W$$ is the width of the input. This is because we use a dynamic programming array of size $$W$$ to keep track of the maximum increasing subsequence of columns.\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n W = len(strs[0])\n dp = [1] * W\n for i in range(W-2, -1, -1):\n for j in range(i+1, W):\n if all(row[i] <= row[j] for row in strs):\n dp[i] = max(dp[i], 1 + dp[j])\n\n return W - max(dp)\n\n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Solution to 960. Delete Columns to Make Sorted III | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this problem is to find the longest increasing subsequence of columns. This is because the columns in the longest increasing subsequence do not need to be deleted to make the rows sorted. The remaining columns, which are not part of this subsequence, need to be deleted.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to use dynamic programming. We iterate over the columns of the input from right to left. For each column, we check if it is lexicographically less than or equal to all other columns to its right. If it is, we update the dynamic programming array to keep track of the maximum increasing subsequence of columns. The final answer is the total number of columns minus the length of the maximum increasing subsequence.\n# Pseudocode\n```\nProcedure minDeletionSize(strs: List of strings) -> int:\n Initialize W as the width of the input (length of any string in strs)\n Initialize dp as an array of size W with all elements as 1\n\n For i from W-2 to 0 (inclusive) in reverse order:\n For j from i+1 to W (exclusive):\n If all characters at index j in strs are greater than or equal to characters at index i:\n Update dp[i] as the maximum of dp[i] and 1 + dp[j]\n\n Return W - maximum value in dp\nEnd Procedure\n\n```\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is $$O(W2\u22C5N)$$, where $$W$$ is the width of the input and $$N$$ is the number of strings. This is because for each column, we compare it with all other columns to its right, and for each comparison, we check all the strings.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is $$O(W)$$, where $$W$$ is the width of the input. This is because we use a dynamic programming array of size $$W$$ to keep track of the maximum increasing subsequence of columns.\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n W = len(strs[0])\n dp = [1] * W\n for i in range(W-2, -1, -1):\n for j in range(i+1, W):\n if all(row[i] <= row[j] for row in strs):\n dp[i] = max(dp[i], 1 + dp[j])\n\n return W - max(dp)\n\n``` | 0 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
python super easy to understand (dp top down) | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n \n @functools.lru_cache(None)\n def dp(i, j): # i -> current index , j -> prev index after deletion\n\n if i == len(strs[0]):\n return 0\n ans = float("inf")\n\n if j == -1: # -> delete or not delete beginning of characters\n ans = min(ans, dp(i+1, i), 1 + dp(i+1, j))\n return ans\n\n for x in range(len(strs)):\n if strs[x][i] < strs[x][j]: # if current index is less than prev index, must delete current index\n ans = min(ans, 1 + dp(i+1, j))\n return ans\n # delete current index or not delete current index\n ans = min(ans, dp(i+1, i), 1 + dp(i+1, j))\n return ans\n\n return dp(0, -1)\n \n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
python super easy to understand (dp top down) | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n \n @functools.lru_cache(None)\n def dp(i, j): # i -> current index , j -> prev index after deletion\n\n if i == len(strs[0]):\n return 0\n ans = float("inf")\n\n if j == -1: # -> delete or not delete beginning of characters\n ans = min(ans, dp(i+1, i), 1 + dp(i+1, j))\n return ans\n\n for x in range(len(strs)):\n if strs[x][i] < strs[x][j]: # if current index is less than prev index, must delete current index\n ans = min(ans, 1 + dp(i+1, j))\n return ans\n # delete current index or not delete current index\n ans = min(ans, dp(i+1, i), 1 + dp(i+1, j))\n return ans\n\n return dp(0, -1)\n \n``` | 0 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
Python 3: LIS DP Solution with comments; TC - 99.37% | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n\n # dp[i], including i for every strs, the length of the LIS\n N = len(strs[0])\n dp = [1] * N\n\n for i in range(N - 1, -1, -1):\n for j in range(i + 1, N):\n canIncrease = True\n\n # check against every strings whether including current\n # can still mean it is LIS\n for s in strs:\n if s[i] > s[j]:\n canIncrease = False\n break\n \n # if including current char, for all string, does not go against LIS\n if canIncrease:\n dp[i] = max(dp[i], dp[j] + 1)\n\n return N - max(dp)\n\n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Python 3: LIS DP Solution with comments; TC - 99.37% | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n\n # dp[i], including i for every strs, the length of the LIS\n N = len(strs[0])\n dp = [1] * N\n\n for i in range(N - 1, -1, -1):\n for j in range(i + 1, N):\n canIncrease = True\n\n # check against every strings whether including current\n # can still mean it is LIS\n for s in strs:\n if s[i] > s[j]:\n canIncrease = False\n break\n \n # if including current char, for all string, does not go against LIS\n if canIncrease:\n dp[i] = max(dp[i], dp[j] + 1)\n\n return N - max(dp)\n\n``` | 0 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
(Python) Delete Columns to Make Sorted III | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\nThe intuition behind the approach is to use dynamic programming to find the length of the longest increasing subsequence (LIS) for each position in the strings. By keeping track of this information, we can determine the minimum number of deletions required to make all the strings lexicographically sorted.\n\n# Approach\n1. Initialize a 1D array dp of length `n` (number of columns) with all elements set to 1. This array will keep track of the length of the LIS at each position.\n2. Iterate through each column (j) from 1 to n.\n3. For each column (j), iterate through all the previous columns (i) from 0 to j-1.\n4. Check if all elements in the current column (j) are greater than or equal to the corresponding elements in the previous column (i) for all rows. If this condition is true, it means we can extend the LIS by including the current column (j).\n5. If the condition in step 4 is met, update `dp[j]` to be the maximum of `dp[j]` and `dp[i] + 1`, indicating the extended length of the LIS at column j.\n6. After iterating through all previous columns for the current column (j), we will have the length of the LIS at position j in the dp array.\n7. The minimum number of deletions required to make all the strings lexicographically sorted will be the total number of columns (n) minus the length of the longest increasing subsequence, which is `n - max(dp)`.\n# Complexity\n- Time complexity:\nThe time complexity of the solution is `O(n^2)`, where n is the number of columns in the strings. The dynamic programming approach involves two nested loops to fill the dp array.\n- Space complexity:\nThe space complexity is `O(n)`, where n is the number of columns. We use a 1D array dp of length n to store the LIS at each position.\n# Code\n```\nfrom typing import List\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0])\n dp = [1] * n\n\n for j in range(1, n):\n for i in range(j):\n if all(strs[k][i] <= strs[k][j] for k in range(m)):\n dp[j] = max(dp[j], dp[i] + 1)\n\n return n - max(dp)\n\n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
(Python) Delete Columns to Make Sorted III | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\nThe intuition behind the approach is to use dynamic programming to find the length of the longest increasing subsequence (LIS) for each position in the strings. By keeping track of this information, we can determine the minimum number of deletions required to make all the strings lexicographically sorted.\n\n# Approach\n1. Initialize a 1D array dp of length `n` (number of columns) with all elements set to 1. This array will keep track of the length of the LIS at each position.\n2. Iterate through each column (j) from 1 to n.\n3. For each column (j), iterate through all the previous columns (i) from 0 to j-1.\n4. Check if all elements in the current column (j) are greater than or equal to the corresponding elements in the previous column (i) for all rows. If this condition is true, it means we can extend the LIS by including the current column (j).\n5. If the condition in step 4 is met, update `dp[j]` to be the maximum of `dp[j]` and `dp[i] + 1`, indicating the extended length of the LIS at column j.\n6. After iterating through all previous columns for the current column (j), we will have the length of the LIS at position j in the dp array.\n7. The minimum number of deletions required to make all the strings lexicographically sorted will be the total number of columns (n) minus the length of the longest increasing subsequence, which is `n - max(dp)`.\n# Complexity\n- Time complexity:\nThe time complexity of the solution is `O(n^2)`, where n is the number of columns in the strings. The dynamic programming approach involves two nested loops to fill the dp array.\n- Space complexity:\nThe space complexity is `O(n)`, where n is the number of columns. We use a 1D array dp of length n to store the LIS at each position.\n# Code\n```\nfrom typing import List\n\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0])\n dp = [1] * n\n\n for j in range(1, n):\n for i in range(j):\n if all(strs[k][i] <= strs[k][j] for k in range(m)):\n dp[j] = max(dp[j], dp[i] + 1)\n\n return n - max(dp)\n\n``` | 0 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
NOT LIS intution | delete-columns-to-make-sorted-iii | 0 | 1 | \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n strs=list(map(list,strs))\n n=len(strs[0])\n def check(i,last):\n if last==-1 or i>=n:\n return True\n for s in strs:\n if s[last]>s[i]:\n return False\n return True\n \n dp=[-1]*(n+1)\n def rec(last):\n if last>=n:\n return 0\n if dp[last]!=-1:\n return dp[last]\n ans=float("inf")\n for i in range(last+1,n+1):\n if check(i,last):\n cs=(i-last-1)\n if last==-1:\n cs=i+1\n ans=min(ans,(cs)+rec(i))\n dp[last]=ans\n return ans\n return rec(-1)-1\n\n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
NOT LIS intution | delete-columns-to-make-sorted-iii | 0 | 1 | \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n strs=list(map(list,strs))\n n=len(strs[0])\n def check(i,last):\n if last==-1 or i>=n:\n return True\n for s in strs:\n if s[last]>s[i]:\n return False\n return True\n \n dp=[-1]*(n+1)\n def rec(last):\n if last>=n:\n return 0\n if dp[last]!=-1:\n return dp[last]\n ans=float("inf")\n for i in range(last+1,n+1):\n if check(i,last):\n cs=(i-last-1)\n if last==-1:\n cs=i+1\n ans=min(ans,(cs)+rec(i))\n dp[last]=ans\n return ans\n return rec(-1)-1\n\n``` | 0 | There are `n` piles of `stones` arranged in a row. The `ith` pile has `stones[i]` stones.
A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.
Return _the minimum cost to merge all piles of stones into one pile_. If it is impossible, return `-1`.
**Example 1:**
**Input:** stones = \[3,2,4,1\], k = 2
**Output:** 20
**Explanation:** We start with \[3, 2, 4, 1\].
We merge \[3, 2\] for a cost of 5, and we are left with \[5, 4, 1\].
We merge \[4, 1\] for a cost of 5, and we are left with \[5, 5\].
We merge \[5, 5\] for a cost of 10, and we are left with \[10\].
The total cost was 20, and this is the minimum possible.
**Example 2:**
**Input:** stones = \[3,2,4,1\], k = 3
**Output:** -1
**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.
**Example 3:**
**Input:** stones = \[3,5,1,2,6\], k = 3
**Output:** 25
**Explanation:** We start with \[3, 5, 1, 2, 6\].
We merge \[5, 1, 2\] for a cost of 8, and we are left with \[3, 8, 6\].
We merge \[3, 8, 6\] for a cost of 17, and we are left with \[17\].
The total cost was 25, and this is the minimum possible.
**Constraints:**
* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30` | null |
Python solution in 5 lines | delete-columns-to-make-sorted-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is identical to the classic longest non-decreasing subsequence. \nThe problem can be efficiently solved in binary search. \nDue to the small input size, the solution based on the slower DP algorithm can also be accepted. \nThe implementation can be very short with the `all()` function for comparing two indices. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n^2 * m) where n is the length of indices, and m is the number of strings. \n\n# Code\n```\nclass Solution:\n def minDeletionSize(self, strs: List[str]) -> int:\n m, n = len(strs), len(strs[0])\n dp = [0] * (n+1)\n for i in range(n):\n dp[i] = 1 + max([dp[j] for j in range(i) if all(strs[k][j] <= strs[k][i] for k in range(m))], default=0)\n return n - max(dp)\n\n\n \n``` | 0 | You are given an array of `n` strings `strs`, all of the same length.
We may choose any deletion indices, and we delete all the characters in those indices for each string.
For example, if we have `strs = [ "abcdef ", "uvwxyz "]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `[ "bef ", "vyz "]`.
Suppose we chose a set of deletion indices `answer` such that after deletions, the final array has **every string (row) in lexicographic** order. (i.e., `(strs[0][0] <= strs[0][1] <= ... <= strs[0][strs[0].length - 1])`, and `(strs[1][0] <= strs[1][1] <= ... <= strs[1][strs[1].length - 1])`, and so on). Return _the minimum possible value of_ `answer.length`.
**Example 1:**
**Input:** strs = \[ "babca ", "bbazb "\]
**Output:** 3
**Explanation:** After deleting columns 0, 1, and 4, the final array is strs = \[ "bc ", "az "\].
Both these rows are individually in lexicographic order (ie. strs\[0\]\[0\] <= strs\[0\]\[1\] and strs\[1\]\[0\] <= strs\[1\]\[1\]).
Note that strs\[0\] > strs\[1\] - the array strs is not necessarily in lexicographic order.
**Example 2:**
**Input:** strs = \[ "edcba "\]
**Output:** 4
**Explanation:** If we delete less than 4 columns, the only row will not be lexicographically sorted.
**Example 3:**
**Input:** strs = \[ "ghi ", "def ", "abc "\]
**Output:** 0
**Explanation:** All rows are already lexicographically sorted.
**Constraints:**
* `n == strs.length`
* `1 <= n <= 100`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters. | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.