title
stringlengths 1
100
| titleSlug
stringlengths 3
77
| Java
int64 0
1
| Python3
int64 1
1
| content
stringlengths 28
44.4k
| voteCount
int64 0
3.67k
| question_content
stringlengths 65
5k
| question_hints
stringclasses 970
values |
---|---|---|---|---|---|---|---|
Python Elegant & Short | O(n) | Powers of two | minimum-impossible-or | 0 | 1 | ```\nfrom typing import List\n\n\nclass Solution:\n """\n Time: O(n)\n Memory: O(n)\n """\n\n def minImpossibleOR(self, nums: List[int]) -> int:\n nums = set(nums)\n impossible = 1\n\n while impossible in nums:\n impossible <<= 1\n\n return impossible\n\n``` | 1 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of `nums`.
Return _the minimum **positive non-zero integer** that is not_ _expressible from_ `nums`.
**Example 1:**
**Input:** nums = \[2,1\]
**Output:** 4
**Explanation:** 1 and 2 are already present in the array. We know that 3 is expressible, since nums\[0\] | nums\[1\] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
**Example 2:**
**Input:** nums = \[5,3,2\]
**Output:** 1
**Explanation:** We can show that 1 is the smallest number that is not expressible.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109` | null |
Python || Explained | minimum-impossible-or | 0 | 1 | # Intuition\nWe are only concerned about numbers in the form of 2^x.\nIf the array has [1, 2, 4, 8], then we can form every number between [2^0, (2^4)-1] by forming every possible representation of xxxx in binary.\n# Approach\nLet p be the minimum power such that 2^p doesn\'t exist in the array. Our answer is (2^p) = (2^0 + 2^1 + ... + 2^p-1) + 1\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minImpossibleOR(self, nums: List[int]) -> int:\n vals, ans = set(nums), 0\n for i in range(31):\n val = 2**i\n if val in vals:\n ans += val\n continue\n return ans + 1\n``` | 8 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of `nums`.
Return _the minimum **positive non-zero integer** that is not_ _expressible from_ `nums`.
**Example 1:**
**Input:** nums = \[2,1\]
**Output:** 4
**Explanation:** 1 and 2 are already present in the array. We know that 3 is expressible, since nums\[0\] | nums\[1\] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
**Example 2:**
**Input:** nums = \[5,3,2\]
**Output:** 1
**Explanation:** We can show that 1 is the smallest number that is not expressible.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109` | null |
✅Java || C++ || Python3✅ sort and Pow of 2 | minimum-impossible-or | 0 | 1 | # Please UPVOTE\uD83D\uDE0A\n\n# Python3\n```\nclass Solution:\n def minImpossibleOR(self, nums: List[int]) -> int:\n nums.sort()\n x=1\n for i in nums:\n if x==i:\n x*=2\n return x\n \n```\n# C++\n```\nclass Solution {\npublic:\n int minImpossibleOR(vector<int>& nums) {\n long long int ans=1;\n sort(nums.begin(),nums.end());\n for(int i=0;i<nums.size();i++)\n {\n if(nums[i]==ans)\n {\n ans*=2;\n }\n }\n return ans;\n }\n};\n```\n# Java\n```\nclass Solution {\n public int minImpossibleOR(int[] nums) {\n Arrays.sort(nums);\n int a = 1;\n for(int i:nums)\n {\n if(i==a)\n {\n a=a*2;\n }\n }\n return a;\n }\n}\n``` | 21 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of `nums`.
Return _the minimum **positive non-zero integer** that is not_ _expressible from_ `nums`.
**Example 1:**
**Input:** nums = \[2,1\]
**Output:** 4
**Explanation:** 1 and 2 are already present in the array. We know that 3 is expressible, since nums\[0\] | nums\[1\] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
**Example 2:**
**Input:** nums = \[5,3,2\]
**Output:** 1
**Explanation:** We can show that 1 is the smallest number that is not expressible.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109` | null |
Python 3 || 4 lines, w/ explanation || T/M: 100% / 69% | minimum-impossible-or | 0 | 1 | It\'s easy to show that`n` is not the answer if and only if every power of two less that is than`n`is in`nums`. A direct result of that fact is the answer is the first power of 2 not in`nums`is the answer.\n\nIt follows directly from this fact that the answer is the first power of two not in`nums`.\n```\nclass Solution:\n def minImpossibleOR(self, nums: List[int]) -> int:\n\n pow2 = 1\n\n for _ in range(30):\n\n if pow2 not in nums: return pow2\n\n pow2*= 2\n\n```\n[https://leetcode.com/problems/minimum-impossible-or/submissions/901095002/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(1). | 4 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of `nums`.
Return _the minimum **positive non-zero integer** that is not_ _expressible from_ `nums`.
**Example 1:**
**Input:** nums = \[2,1\]
**Output:** 4
**Explanation:** 1 and 2 are already present in the array. We know that 3 is expressible, since nums\[0\] | nums\[1\] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
**Example 2:**
**Input:** nums = \[5,3,2\]
**Output:** 1
**Explanation:** We can show that 1 is the smallest number that is not expressible.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109` | null |
Python || Easy to understand || python3 | minimum-impossible-or | 0 | 1 | ```\nclass Solution:\n def minImpossibleOR(self, nums: List[int]) -> int:\n i = 1\n cnt = 1\n nums = set(nums)\n while True:\n if i not in nums:\n return i\n i = 2**(cnt)\n cnt += 1\n``` | 1 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of `nums`.
Return _the minimum **positive non-zero integer** that is not_ _expressible from_ `nums`.
**Example 1:**
**Input:** nums = \[2,1\]
**Output:** 4
**Explanation:** 1 and 2 are already present in the array. We know that 3 is expressible, since nums\[0\] | nums\[1\] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
**Example 2:**
**Input:** nums = \[5,3,2\]
**Output:** 1
**Explanation:** We can show that 1 is the smallest number that is not expressible.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109` | null |
💡🐍 Python3 | Check only the powers of 2 | 💡 Aha-moment 💡| O(n) | minimum-impossible-or | 0 | 1 | # Intuition\nThe thing to notice with this problem is, that if there is any number that is not expressible with OR-ing, it is either a power of two, or there exists a number smaller than it, which is power of 2, and that number is also not expressible.\nThis is because of the way the "OR" works in binary, by "switching on" bits.\n\n# Approach\nCheck from smallest to larger the powers of 2 and stop when we find one that cannot be expressed.\n\n# Complexity\n- Time complexity: O(n), and we cannot possibly do better *asymptotically*, as we need to at least look at each of the numbers in `nums`.\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def minImpossibleOR(self, nums: List[int]) -> int:\n pows2 = [2**i for i in range(32)]\n for pow2 in pows2:\n if pow2 not in nums:\n return pow2\n # NOTE: This shouldn\'t execute, as per the problem statement\'s conditions, because nums[i] <= 10^9 < 2**30\n return 2**32\n```\n\n# Tag\nBitwise Arithmetic, Aha-moment \uD83D\uDCA1 | 2 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of `nums`.
Return _the minimum **positive non-zero integer** that is not_ _expressible from_ `nums`.
**Example 1:**
**Input:** nums = \[2,1\]
**Output:** 4
**Explanation:** 1 and 2 are already present in the array. We know that 3 is expressible, since nums\[0\] | nums\[1\] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
**Example 2:**
**Input:** nums = \[5,3,2\]
**Output:** 1
**Explanation:** We can show that 1 is the smallest number that is not expressible.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109` | null |
O(32) Constant Solution | Explained Step by Step | Easy to understand | minimum-impossible-or | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBit Manuplation Question\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can observe if the smaller numbers are present we can produce the larger one. \nEg: if 1 is persent and 2 is present we can produce 3.\nIf 1,2 and 4 are present we can produce all nos till 7.\nIf 1,2,4,and 8 are present we can produce all nos till 15.\nSo on.......\nSo blindly find the first missing power of 2.\nThats the answer.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(32)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\n\nclass Solution:\n def minImpossibleOR(self, nums: List[int]) -> int:\n \n nums=set(nums)\n for i in range(0,32):\n if 2**i not in nums:\n return 2**i\n \n\n``` | 0 | You are given a **0-indexed** integer array `nums`.
We say that an integer x is **expressible** from `nums` if there exist some integers `0 <= index1 < index2 < ... < indexk < nums.length` for which `nums[index1] | nums[index2] | ... | nums[indexk] = x`. In other words, an integer is expressible if it can be written as the bitwise OR of some subsequence of `nums`.
Return _the minimum **positive non-zero integer** that is not_ _expressible from_ `nums`.
**Example 1:**
**Input:** nums = \[2,1\]
**Output:** 4
**Explanation:** 1 and 2 are already present in the array. We know that 3 is expressible, since nums\[0\] | nums\[1\] = 2 | 1 = 3. Since 4 is not expressible, we return 4.
**Example 2:**
**Input:** nums = \[5,3,2\]
**Output:** 1
**Explanation:** We can show that 1 is the smallest number that is not expressible.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109` | null |
Solution Using XOR and bit_count() | handling-sum-queries-after-update | 0 | 1 | # Intuition and Description of Algorithm\nBecause of the size of the input, we need a solution with runtime complexity like $$\\mathcal{O}(n)$$. Therefore, we are considering `nums1` as the binary representation of some number. Each time having a query of 1st type we make XOR of `nums1` and $$x=\\underbrace{11...11}_{r - l + 1}\\underbrace{0...0}_{k}$$, where $$k=$$`len(nums1)-r-1`(i.e. $x$ has ones in the range where we want to flip bits of `nums1`).\n\nBesides, a crucial ingredient is the efficient counting of non-zero bits via `bit_count()`.\n\nSee details in the code snippet below.\n\n---\n\n**Please upvote \u2B06\uFE0F**\n\n---\n\n# Complexity\n- Time complexity: $$\\mathcal{O}(n)$$\n\n- Space complexity: $$\\mathcal{O}(n)$$\n\n---\n\n# Code\n```\nclass Solution:\n def handleQuery(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]:\n # get nums1 as the binary representation of some number\n n1 = int(\'\'.join([str(d) for d in nums1]), 2)\n res = []\n key = False\n # calculate sum of nums1 and nums2\n sum1, sum2 = n1.bit_count(), sum(nums2)\n for t, left, right in queries:\n if t == 1:\n # make xor of nums1 to flip corresponding bits\n temp = \'1\'*(right - left + 1) + \'0\'*(len(nums1) - right - 1)\n n1 ^= int(temp, 2)\n key = True\n if t == 2:\n # we don\'t recalculate sum1 when it isn\'t necessary\n if key:\n sum1 = n1.bit_count()\n key = False\n\n sum2 += left*sum1 \n if t == 3:\n res.append(sum2)\n \n return res \n``` | 2 | You are given two **0-indexed** arrays `nums1` and `nums2` and a 2D array `queries` of queries. There are three types of queries:
1. For a query of type 1, `queries[i] = [1, l, r]`. Flip the values from `0` to `1` and from `1` to `0` in `nums1` from index `l` to index `r`. Both `l` and `r` are **0-indexed**.
2. For a query of type 2, `queries[i] = [2, p, 0]`. For every index `0 <= i < n`, set `nums2[i] = nums2[i] + nums1[i] * p`.
3. For a query of type 3, `queries[i] = [3, 0, 0]`. Find the sum of the elements in `nums2`.
Return _an array containing all the answers to the third type queries._
**Example 1:**
**Input:** nums1 = \[1,0,1\], nums2 = \[0,0,0\], queries = \[\[1,1,1\],\[2,1,0\],\[3,0,0\]\]
**Output:** \[3\]
**Explanation:** After the first query nums1 becomes \[1,1,1\]. After the second query, nums2 becomes \[1,1,1\], so the answer to the third query is 3. Thus, \[3\] is returned.
**Example 2:**
**Input:** nums1 = \[1\], nums2 = \[5\], queries = \[\[2,0,0\],\[3,0,0\]\]
**Output:** \[5\]
**Explanation:** After the first query, nums2 remains \[5\], so the answer to the second query is 5. Thus, \[5\] is returned.
**Constraints:**
* `1 <= nums1.length,nums2.length <= 105`
* `nums1.length = nums2.length`
* `1 <= queries.length <= 105`
* `queries[i].length = 3`
* `0 <= l <= r <= nums1.length - 1`
* `0 <= p <= 106`
* `0 <= nums1[i] <= 1`
* `0 <= nums2[i] <= 109` | null |
O(n * sqrt(n)) solution by buffering type-1 queries. | handling-sum-queries-after-update | 0 | 1 | # Intuition\nSince I can\'t quickly find a clever O(n * Log(n)) solution, I will settle for an O(n * sqrt(n)) solution.\n\n# Approach\nCollect a buffer of type-1 queries. Every time a type-2 query is requested, determine the sum of nums1 using the type-1 queries. When\nthe number of type-1 queries exceeds the square root of the length\nof num1, apply the type-1 queries to nums1.\n* Each type-1 query adds two `flipIdxs` representing the indices of the subarray for which the bits are flipped on and off.\n\n# Complexity\n- Time complexity: $$O(n * sqrt(n))$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n \n def handleQuery(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]: \n sum3 = []\n sum2 = sum(nums2)\n n = len(nums1)\n psums1 = self.getPsums(nums1)\n flipIdxs = []\n for i1, i2, i3 in queries:\n if i1 == 1:\n for flipIdx in i2, i3 + 1:\n flipIdxs.insert(\n bisect.bisect_left(flipIdxs, flipIdx),\n flipIdx)\n if len(flipIdxs) * len(flipIdxs) > n * 4:\n self.flushFlipIdxs(nums1, flipIdxs)\n psums1 = self.getPsums(nums1)\n flipIdxs = []\n elif i1 == 2:\n sum2 += self.getSum(psums1, flipIdxs) * i2\n else:\n sum3.append(sum2)\n return sum3\n \n @classmethod \n def getPsums(cls, nums):\n psums = [0] + nums\n for i in range(len(nums)):\n psums[i + 1] += psums[i]\n return psums\n \n @classmethod\n def getSum(cls, psums, flipIdxs):\n sum1 = psums[-1]\n for i, flipIdx in enumerate(flipIdxs):\n isLo = i % 2 == 0\n if isLo:\n sum1 += psums[flipIdx] * 2 - flipIdx\n else:\n sum1 -= psums[flipIdx] * 2 - flipIdx\n return sum1 \n \n @classmethod\n def flushFlipIdxs(cls, nums, flipIdxs):\n for i in range(0, len(flipIdxs), 2):\n flipOnIdx = flipIdxs[i]\n flipOffIdx = flipIdxs[i + 1]\n for j in range(flipOnIdx, flipOffIdx):\n nums[j] = 1 - nums[j]\n \n``` | 1 | You are given two **0-indexed** arrays `nums1` and `nums2` and a 2D array `queries` of queries. There are three types of queries:
1. For a query of type 1, `queries[i] = [1, l, r]`. Flip the values from `0` to `1` and from `1` to `0` in `nums1` from index `l` to index `r`. Both `l` and `r` are **0-indexed**.
2. For a query of type 2, `queries[i] = [2, p, 0]`. For every index `0 <= i < n`, set `nums2[i] = nums2[i] + nums1[i] * p`.
3. For a query of type 3, `queries[i] = [3, 0, 0]`. Find the sum of the elements in `nums2`.
Return _an array containing all the answers to the third type queries._
**Example 1:**
**Input:** nums1 = \[1,0,1\], nums2 = \[0,0,0\], queries = \[\[1,1,1\],\[2,1,0\],\[3,0,0\]\]
**Output:** \[3\]
**Explanation:** After the first query nums1 becomes \[1,1,1\]. After the second query, nums2 becomes \[1,1,1\], so the answer to the third query is 3. Thus, \[3\] is returned.
**Example 2:**
**Input:** nums1 = \[1\], nums2 = \[5\], queries = \[\[2,0,0\],\[3,0,0\]\]
**Output:** \[5\]
**Explanation:** After the first query, nums2 remains \[5\], so the answer to the second query is 5. Thus, \[5\] is returned.
**Constraints:**
* `1 <= nums1.length,nums2.length <= 105`
* `nums1.length = nums2.length`
* `1 <= queries.length <= 105`
* `queries[i].length = 3`
* `0 <= l <= r <= nums1.length - 1`
* `0 <= p <= 106`
* `0 <= nums1[i] <= 1`
* `0 <= nums2[i] <= 109` | null |
Python | Segment Tree with Lazy Propagation | O(nlogn + qlogn) | Simple Code | handling-sum-queries-after-update | 0 | 1 | # Code\n```\n\n\nclass Solution:\n def handleQuery(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]:\n n = len(nums1)\n #root of the tree is at the index 0\n tree = [0]*(4*n)\n lazy = [0]*(4*n)\n\n def update(v, lo, hi, i, j):\n if lazy[v]:\n tree[v] = (hi - lo + 1) - tree[v]\n if lo < hi:\n lazy[2*v + 1] ^= lazy[v]\n lazy[2*v + 2] ^= lazy[v]\n lazy[v] = 0\n if lo > j or hi < i: \n return \n if i <= lo and hi <= j:\n tree[v] = (hi - lo + 1) - tree[v]\n if lo < hi:\n lazy[2*v + 1] ^= 1 \n lazy[2*v + 2] ^= 1\n return\n m = (lo + hi)//2\n update(2*v + 1, lo, m, i, j) \n update(2*v + 2, m+1, hi, i, j)\n tree[v] = tree[2*v + 1] + tree[2*v + 2]\n\n for i, b in enumerate(nums1):\n if b: update(0,0,n-1,i,i)\n sum2 = sum(nums2)\n res = []\n for t, l, r in queries:\n if t == 1:\n update(0, 0, n-1, l, r)\n elif t == 2:\n sum2 += l*tree[0]\n else:\n res.append(sum2)\n return res\n\n | 1 | You are given two **0-indexed** arrays `nums1` and `nums2` and a 2D array `queries` of queries. There are three types of queries:
1. For a query of type 1, `queries[i] = [1, l, r]`. Flip the values from `0` to `1` and from `1` to `0` in `nums1` from index `l` to index `r`. Both `l` and `r` are **0-indexed**.
2. For a query of type 2, `queries[i] = [2, p, 0]`. For every index `0 <= i < n`, set `nums2[i] = nums2[i] + nums1[i] * p`.
3. For a query of type 3, `queries[i] = [3, 0, 0]`. Find the sum of the elements in `nums2`.
Return _an array containing all the answers to the third type queries._
**Example 1:**
**Input:** nums1 = \[1,0,1\], nums2 = \[0,0,0\], queries = \[\[1,1,1\],\[2,1,0\],\[3,0,0\]\]
**Output:** \[3\]
**Explanation:** After the first query nums1 becomes \[1,1,1\]. After the second query, nums2 becomes \[1,1,1\], so the answer to the third query is 3. Thus, \[3\] is returned.
**Example 2:**
**Input:** nums1 = \[1\], nums2 = \[5\], queries = \[\[2,0,0\],\[3,0,0\]\]
**Output:** \[5\]
**Explanation:** After the first query, nums2 remains \[5\], so the answer to the second query is 5. Thus, \[5\] is returned.
**Constraints:**
* `1 <= nums1.length,nums2.length <= 105`
* `nums1.length = nums2.length`
* `1 <= queries.length <= 105`
* `queries[i].length = 3`
* `0 <= l <= r <= nums1.length - 1`
* `0 <= p <= 106`
* `0 <= nums1[i] <= 1`
* `0 <= nums2[i] <= 109` | null |
[Python3] lazy segment tree | handling-sum-queries-after-update | 0 | 1 | \n```\nclass SegTreeLazy: \n \n def __init__(self, arr: List[int]): \n """Build the segmentation tree."""\n self.n = n = len(arr)\n self.tree = [0]*(4*n)\n self.lazy = [0]*(4*n)\n \n def build(k: int, lo: int, hi: int) -> None: \n """Build segment tree from array."""\n if lo+1 == hi: self.tree[k] = arr[lo]\n else: \n mid = lo + hi >> 1\n build(2*k+1, lo, mid)\n build(2*k+2, mid, hi)\n self.tree[k] = self.tree[2*k+1] + self.tree[2*k+2]\n \n build(0, 0, n)\n\n\n def update(self, qlo: int, qhi: int, k: int = 0, lo: int = 0, hi: int = 0) -> None:\n """Update segment tree when value in [qlo, qhi) is flipped."""\n if not hi: hi = self.n\n if self.lazy[k]: \n self.tree[k] = (hi - lo) - self.tree[k]\n if lo+1 < hi: \n self.lazy[2*k+1] ^= 1\n self.lazy[2*k+2] ^= 1 \n self.lazy[k] = 0\n if lo < hi and qlo < hi and lo < qhi: \n if qlo <= lo and hi <= qhi: # total overlap\n self.tree[k] = (hi - lo) - self.tree[k]\n if lo+1 < hi: \n self.lazy[2*k+1] ^= 1\n self.lazy[2*k+2] ^= 1\n return \n mid = lo + hi >> 1\n self.update(qlo, qhi, 2*k+1, lo, mid) \n self.update(qlo, qhi, 2*k+2, mid, hi)\n self.tree[k] = self.tree[2*k+1] + self.tree[2*k+2]\n \n\nclass Solution:\n def handleQuery(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]:\n tree = SegTreeLazy(nums1)\n ans = []\n val = sum(nums2)\n for x, y, z in queries: \n if x == 1: tree.update(y, z+1)\n elif x == 2: val += y * tree.tree[0]\n else: ans.append(val)\n return ans \n``` | 8 | You are given two **0-indexed** arrays `nums1` and `nums2` and a 2D array `queries` of queries. There are three types of queries:
1. For a query of type 1, `queries[i] = [1, l, r]`. Flip the values from `0` to `1` and from `1` to `0` in `nums1` from index `l` to index `r`. Both `l` and `r` are **0-indexed**.
2. For a query of type 2, `queries[i] = [2, p, 0]`. For every index `0 <= i < n`, set `nums2[i] = nums2[i] + nums1[i] * p`.
3. For a query of type 3, `queries[i] = [3, 0, 0]`. Find the sum of the elements in `nums2`.
Return _an array containing all the answers to the third type queries._
**Example 1:**
**Input:** nums1 = \[1,0,1\], nums2 = \[0,0,0\], queries = \[\[1,1,1\],\[2,1,0\],\[3,0,0\]\]
**Output:** \[3\]
**Explanation:** After the first query nums1 becomes \[1,1,1\]. After the second query, nums2 becomes \[1,1,1\], so the answer to the third query is 3. Thus, \[3\] is returned.
**Example 2:**
**Input:** nums1 = \[1\], nums2 = \[5\], queries = \[\[2,0,0\],\[3,0,0\]\]
**Output:** \[5\]
**Explanation:** After the first query, nums2 remains \[5\], so the answer to the second query is 5. Thus, \[5\] is returned.
**Constraints:**
* `1 <= nums1.length,nums2.length <= 105`
* `nums1.length = nums2.length`
* `1 <= queries.length <= 105`
* `queries[i].length = 3`
* `0 <= l <= r <= nums1.length - 1`
* `0 <= p <= 106`
* `0 <= nums1[i] <= 1`
* `0 <= nums2[i] <= 109` | null |
Python | Segmentation Tree with Lazy Propogation | Explanation | handling-sum-queries-after-update | 0 | 1 | We can find from the question:\n* We only need to answer `sum(nums2)` every time encounters a query of type 3.\n* Every time we can update `sum(nums2)` by a query of type 2 with `sum(nums2) += sum(nums1) * p`.\n\nSo, we should keep update the `sum(nums1)` for every query of type 1.\nWe use Segmentation tree with Lazy Propogation to solve the problem.\nFor Segmentation tree with Lazy Propogation, we should write three functions, Propogation(`proplazy`), Update and Query.\nIn addition to the three functions, we know if we are going to flip all the value in the interval, the sum of the interval will the `sum(interval) = len(interval) - sum(interval)`.\nSo, we need to record the length `self.len` and the initial summation `self.tree` of each node in the first time(i.e. the `__init__` function).\nFor Propogation function, if the parent node has the mark to flip, then we update all summation of children nodes.\nThis function will work every time we need to access to the children nodes when invoking the following functions.\nFor Update function, we mark the flipping operation and update the summation, or just iterate with children nodes with lazy propogation.\nFor Query function, we collect the summation from children nodes with lazy propogation.\n\n```python []\nclass segtree():\n def __init__(self, n, nums):\n self.lazy = defaultdict(int)\n self.len = defaultdict(int)\n self.tree = defaultdict(int)\n # initial length and summation\n self.init_len(1, 0, n, 0, n, nums)\n self.init_num(1, 0, n, 0, n, nums)\n \n def init_len(self, ind, ul, ur, cl, cr, num):\n if cr < cl or cl >= len(num):\n return 0\n if cr == cl:\n self.len[ind] = 1\n return 1\n mid = (cl + cr) // 2\n if cl != cr:\n self.init_len(ind*2, ul, ur, cl, mid, num)\n self.init_len(ind*2+1, ul, ur, mid+1, cr, num)\n self.len[ind] = self.len[ind*2] + self.len[ind*2+1]\n \n def init_num(self, ind, ul, ur, cl, cr, num):\n if cr < cl or cl >= len(num):\n return\n if cl == cr:\n self.tree[ind] = num[cl]\n return\n mid = (cl + cr) // 2\n if cl != cr:\n self.init_num(ind*2, ul, ur, cl, mid, num)\n self.init_num(ind*2+1, ul, ur, mid+1, cr, num)\n \n self.tree[ind] = self.tree[ind*2] + self.tree[ind*2+1]\n \n \n def proplazy(self, ind):\n # if the parent node has the notation to flip, then we update all summation of children nodes.\n if self.lazy[ind]:\n self.lazy[ind*2] ^= self.lazy[ind]\n self.tree[ind*2] = self.len[ind*2] - self.tree[ind*2]\n self.lazy[ind*2 + 1] ^= self.lazy[ind]\n self.tree[ind*2 + 1] = self.len[ind*2+1] - self.tree[ind*2 + 1]\n self.tree[ind] = self.tree[ind*2] + self.tree[ind*2+1]\n self.lazy[ind] = 0\n \n def update(self, ind, ul, ur, cl, cr):\n if cl > ur or cr < ul:\n return \n if ul <= cl and cr <= ur:\n # mark to flip\n self.lazy[ind] ^= 1\n self.tree[ind] = self.len[ind] - self.tree[ind]\n else:\n mid = (cl + cr) // 2\n self.proplazy(ind)\n self.update(ind*2, ul, ur, cl, mid)\n self.update(ind*2+1, ul, ur, mid+1, cr)\n self.tree[ind] = self.tree[ind*2] + self.tree[ind*2+1]\n \n def query(self, ind, ul, ur, cl, cr):\n if cl > ur or cr < ul:\n return 0\n if ul <= cl and cr <= ur:\n return self.tree[ind]\n else:\n mid = (cl + cr) // 2\n self.proplazy(ind)\n return self.query(ind*2, ul, ur, cl, mid) + self.query(ind*2+1, ul, ur, mid+1, cr)\n \nclass Solution:\n def handleQuery(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]:\n seg = segtree(len(nums1) + 10, nums1)\n anss = []\n ans = sum(nums2)\n n = len(nums1) + 10\n for i, j, k in queries:\n if i == 1:\n seg.update(1, j, k, 0, n)\n if i == 2:\n ans += seg.tree[1] * j\n if i == 3:\n anss.append(ans)\n return anss\n``` | 9 | You are given two **0-indexed** arrays `nums1` and `nums2` and a 2D array `queries` of queries. There are three types of queries:
1. For a query of type 1, `queries[i] = [1, l, r]`. Flip the values from `0` to `1` and from `1` to `0` in `nums1` from index `l` to index `r`. Both `l` and `r` are **0-indexed**.
2. For a query of type 2, `queries[i] = [2, p, 0]`. For every index `0 <= i < n`, set `nums2[i] = nums2[i] + nums1[i] * p`.
3. For a query of type 3, `queries[i] = [3, 0, 0]`. Find the sum of the elements in `nums2`.
Return _an array containing all the answers to the third type queries._
**Example 1:**
**Input:** nums1 = \[1,0,1\], nums2 = \[0,0,0\], queries = \[\[1,1,1\],\[2,1,0\],\[3,0,0\]\]
**Output:** \[3\]
**Explanation:** After the first query nums1 becomes \[1,1,1\]. After the second query, nums2 becomes \[1,1,1\], so the answer to the third query is 3. Thus, \[3\] is returned.
**Example 2:**
**Input:** nums1 = \[1\], nums2 = \[5\], queries = \[\[2,0,0\],\[3,0,0\]\]
**Output:** \[5\]
**Explanation:** After the first query, nums2 remains \[5\], so the answer to the second query is 5. Thus, \[5\] is returned.
**Constraints:**
* `1 <= nums1.length,nums2.length <= 105`
* `nums1.length = nums2.length`
* `1 <= queries.length <= 105`
* `queries[i].length = 3`
* `0 <= l <= r <= nums1.length - 1`
* `0 <= p <= 106`
* `0 <= nums1[i] <= 1`
* `0 <= nums2[i] <= 109` | null |
Python3 - Four Methods | merge-two-2d-arrays-by-summing-values | 0 | 1 | # Code Save All Sums\n```\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n all_values = [0] * 1001\n for a,b in nums1:\n all_values[a] += b\n for a,b in nums2:\n all_values[a] += b\n return [[a,b] for a,b in enumerate(all_values) if b != 0]\n```\n\n# Code Build New Array\n```\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n ret = []\n while nums1 and nums2:\n if nums1[0][0] == nums2[0][0]:\n arr1 = nums1.pop(0)\n arr2 = nums2.pop(0)\n arr1[-1] += arr2[-1]\n ret.append(arr1)\n elif nums1[0][0] > nums2[0][0]:\n ret.append(nums2.pop(0))\n else:\n ret.append(nums1.pop(0))\n ret.extend(nums1)\n ret.extend(nums2)\n return ret\n```\n\n# Code Modify Longest Array In Place\n```\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n if len(nums2) > len(nums1):\n nums1, nums2 = nums2, nums1\n i = 0\n j = 0\n while i < len(nums1) and j < len(nums2):\n if nums1[i][0] == nums2[j][0]:\n nums1[i][1] += nums2[j][1]\n i, j = i + 1, j + 1\n elif nums1[i][0] < nums2[j][0]:\n i += 1\n else:\n nums1.insert(i, nums2[j])\n i, j = i + 1, j + 1\n if j != len(nums2):\n nums1.extend(nums2[j:])\n return nums1\n```\n\n\n# Code Use Default Dictionary\n```\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n d1, d2 = defaultdict(int, {a:b for a,b in nums1}), defaultdict(int, {a:b for a,b in nums2})\n return [[k, d1[k] + d2[k]] for k in sorted(set(d1.keys()).union(set(d2.keys())))]\n \n```\n\n | 1 | You are given two **2D** integer arrays `nums1` and `nums2.`
* `nums1[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
* `nums2[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
Each array contains **unique** ids and is sorted in **ascending** order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
* Only ids that appear in at least one of the two arrays should be included in the resulting array.
* Each id should be included **only once** and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be `0`.
Return _the resulting array_. The returned array must be sorted in ascending order by id.
**Example 1:**
**Input:** nums1 = \[\[1,2\],\[2,3\],\[4,5\]\], nums2 = \[\[1,4\],\[3,2\],\[4,1\]\]
**Output:** \[\[1,6\],\[2,3\],\[3,2\],\[4,6\]\]
**Explanation:** The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.
**Example 2:**
**Input:** nums1 = \[\[2,4\],\[3,6\],\[5,5\]\], nums2 = \[\[1,3\],\[4,3\]\]
**Output:** \[\[1,3\],\[2,4\],\[3,6\],\[4,3\],\[5,5\]\]
**Explanation:** There are no common ids, so we just include each id with its value in the resulting list.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 200`
* `nums1[i].length == nums2[j].length == 2`
* `1 <= idi, vali <= 1000`
* Both arrays contain unique ids.
* Both arrays are in strictly ascending order by id. | null |
Python || THIS IS THE SAME AS 2363!! | merge-two-2d-arrays-by-summing-values | 0 | 1 | # Code\n```\nfrom collections import defaultdict\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n table = defaultdict(lambda: 0)\n items = sorted(nums1 + nums2, key=lambda itm:itm[0])\n ret = []\n for itm in items:\n table[itm[0]] += itm[1]\n table = dict(table)\n return table.items()\n``` | 1 | You are given two **2D** integer arrays `nums1` and `nums2.`
* `nums1[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
* `nums2[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
Each array contains **unique** ids and is sorted in **ascending** order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
* Only ids that appear in at least one of the two arrays should be included in the resulting array.
* Each id should be included **only once** and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be `0`.
Return _the resulting array_. The returned array must be sorted in ascending order by id.
**Example 1:**
**Input:** nums1 = \[\[1,2\],\[2,3\],\[4,5\]\], nums2 = \[\[1,4\],\[3,2\],\[4,1\]\]
**Output:** \[\[1,6\],\[2,3\],\[3,2\],\[4,6\]\]
**Explanation:** The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.
**Example 2:**
**Input:** nums1 = \[\[2,4\],\[3,6\],\[5,5\]\], nums2 = \[\[1,3\],\[4,3\]\]
**Output:** \[\[1,3\],\[2,4\],\[3,6\],\[4,3\],\[5,5\]\]
**Explanation:** There are no common ids, so we just include each id with its value in the resulting list.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 200`
* `nums1[i].length == nums2[j].length == 2`
* `1 <= idi, vali <= 1000`
* Both arrays contain unique ids.
* Both arrays are in strictly ascending order by id. | null |
Readable Python solution | merge-two-2d-arrays-by-summing-values | 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 mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n a = [x[0] for x in nums2]\n b = [y[1] for y in nums2]\n c = [z[0] for z in nums1]\n nums3 = []\n for i in nums1:\n if i[0] in a:\n nums3.append([i[0], i[1]+b[a.index(i[0])]])\n else:\n nums3.append(i)\n for k in nums2:\n if k[0] not in c:\n nums3.append(k)\n return sorted(nums3) \n \n``` | 1 | You are given two **2D** integer arrays `nums1` and `nums2.`
* `nums1[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
* `nums2[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
Each array contains **unique** ids and is sorted in **ascending** order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
* Only ids that appear in at least one of the two arrays should be included in the resulting array.
* Each id should be included **only once** and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be `0`.
Return _the resulting array_. The returned array must be sorted in ascending order by id.
**Example 1:**
**Input:** nums1 = \[\[1,2\],\[2,3\],\[4,5\]\], nums2 = \[\[1,4\],\[3,2\],\[4,1\]\]
**Output:** \[\[1,6\],\[2,3\],\[3,2\],\[4,6\]\]
**Explanation:** The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.
**Example 2:**
**Input:** nums1 = \[\[2,4\],\[3,6\],\[5,5\]\], nums2 = \[\[1,3\],\[4,3\]\]
**Output:** \[\[1,3\],\[2,4\],\[3,6\],\[4,3\],\[5,5\]\]
**Explanation:** There are no common ids, so we just include each id with its value in the resulting list.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 200`
* `nums1[i].length == nums2[j].length == 2`
* `1 <= idi, vali <= 1000`
* Both arrays contain unique ids.
* Both arrays are in strictly ascending order by id. | null |
Python solution | merge-two-2d-arrays-by-summing-values | 0 | 1 | \n```\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n\n D = defaultdict(lambda:0) \n for n in nums1: \n D[n[0]] += n[1]\n\n for n in nums2:\n D[n[0]] += n[1]\n\n res = [] \n\n for k in sorted(D.keys()):\n tmp = [k,D[k]]\n res.append(tmp)\n\n return res\n\n\n``` | 1 | You are given two **2D** integer arrays `nums1` and `nums2.`
* `nums1[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
* `nums2[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
Each array contains **unique** ids and is sorted in **ascending** order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
* Only ids that appear in at least one of the two arrays should be included in the resulting array.
* Each id should be included **only once** and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be `0`.
Return _the resulting array_. The returned array must be sorted in ascending order by id.
**Example 1:**
**Input:** nums1 = \[\[1,2\],\[2,3\],\[4,5\]\], nums2 = \[\[1,4\],\[3,2\],\[4,1\]\]
**Output:** \[\[1,6\],\[2,3\],\[3,2\],\[4,6\]\]
**Explanation:** The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.
**Example 2:**
**Input:** nums1 = \[\[2,4\],\[3,6\],\[5,5\]\], nums2 = \[\[1,3\],\[4,3\]\]
**Output:** \[\[1,3\],\[2,4\],\[3,6\],\[4,3\],\[5,5\]\]
**Explanation:** There are no common ids, so we just include each id with its value in the resulting list.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 200`
* `nums1[i].length == nums2[j].length == 2`
* `1 <= idi, vali <= 1000`
* Both arrays contain unique ids.
* Both arrays are in strictly ascending order by id. | null |
Easy to Understand Solution |🔥 2 Approaches 🔥| Beats 100% | merge-two-2d-arrays-by-summing-values | 1 | 1 | # Approach 1: Array\n```java []\nclass Solution {\n public int[][] mergeArrays(int[][] nums1, int[][] nums2) {\n int[] arr = new int[1001];\n int len = 0;\n\n // Calculating length for res array.\n for(int i = 0; i < nums1.length; i++){\n if(arr[nums1[i][0]] == 0){\n len++;\n }\n arr[nums1[i][0]] = nums1[i][1];\n }\n \n for(int i = 0; i < nums2.length; i++){\n if(arr[nums2[i][0]] == 0){\n len++;\n }\n arr[nums2[i][0]] = arr[nums2[i][0]] + nums2[i][1];\n }\n\n int[][] res = new int[len][2];\n\n int ind = 0;\n for(int i = 0; i < arr.length; i++){\n if(arr[i] != 0){\n res[ind][0] = i;\n res[ind][1] = arr[i];\n ind++;\n }\n }\n\n return res;\n }\n}\n```\n```python []\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n arr = [0] * 1001\n length = 0\n\n # Calculating length for res array.\n for num in nums1:\n if arr[num[0]] == 0:\n length += 1\n arr[num[0]] = num[1]\n\n for num in nums2:\n if arr[num[0]] == 0:\n length += 1\n arr[num[0]] += num[1]\n\n res = [[0, 0] for _ in range(length)]\n\n ind = 0\n for i in range(len(arr)):\n if arr[i] != 0:\n res[ind][0] = i\n res[ind][1] = arr[i]\n ind += 1\n\n return res\n\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> mergeArrays(vector<vector<int>>& nums1, vector<vector<int>>& nums2) {\n std::vector<int> arr(1001, 0);\n int len = 0;\n\n // Calculating length for res array.\n for (const auto& num : nums1) {\n if (arr[num[0]] == 0) {\n len++;\n }\n arr[num[0]] = num[1];\n }\n\n for (const auto& num : nums2) {\n if (arr[num[0]] == 0) {\n len++;\n }\n arr[num[0]] += num[1];\n }\n\n std::vector<std::vector<int>> res(len, std::vector<int>(2, 0));\n\n int ind = 0;\n for (int i = 0; i < arr.size(); i++) {\n if (arr[i] != 0) {\n res[ind][0] = i;\n res[ind][1] = arr[i];\n ind++;\n }\n }\n\n return res; \n }\n};\n```\n\n\n\n# Approach 2: Two pointer\n```java []\nclass Solution {\n public int[][] mergeArrays(int[][] nums1, int[][] nums2) {\n int p1 = 0;\n int p2 = 0;\n\n ArrayList<int[]> res = new ArrayList<>();\n\n int n1 = nums1.length;\n int n2 = nums2.length;\n \n while(p1 < n1 && p2 < n2){\n // if id of nums1 is smaller\n if(nums1[p1][0] < nums2[p2][0]){\n res.add(nums1[p1]);\n p1++;\n }\n // if id of nums2 is smaller\n else if (nums2[p2][0] < nums1[p1][0]){\n res.add(nums2[p2]);\n p2++;\n }\n // id of both nums1 and nums2 is equal\n else{\n res.add(new int[] {nums1[p1][0], nums1[p1][1] + nums2[p2][1]});\n p1++;\n p2++;\n }\n }\n\n // covering cases where one array is longer than the other array. \n while(p1 < n1){\n res.add(nums1[p1]);\n p1++;\n }\n\n while(p2 < n2){\n res.add(nums2[p2]);\n p2++;\n }\n\n return res.toArray(new int[res.size()][]);\n }\n}\n```\n```python []\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n p1 = 0\n p2 = 0\n\n res = []\n\n n1 = len(nums1)\n n2 = len(nums2)\n\n while p1 < n1 and p2 < n2:\n # if id of nums1 is smaller\n if nums1[p1][0] < nums2[p2][0]:\n res.append(nums1[p1])\n p1 += 1\n # if id of nums2 is smaller\n elif nums2[p2][0] < nums1[p1][0]:\n res.append(nums2[p2])\n p2 += 1\n # id of both nums1 and nums2 is equal\n else:\n res.append([nums1[p1][0], nums1[p1][1] + nums2[p2][1]])\n p1 += 1\n p2 += 1\n\n # covering cases where one array is longer than the other array. \n while p1 < n1:\n res.append(nums1[p1])\n p1 += 1\n\n while p2 < n2:\n res.append(nums2[p2])\n p2 += 1\n\n return res\n```\n```C++ []\nclass Solution {\npublic:\n vector<vector<int>> mergeArrays(vector<vector<int>>& nums1, vector<vector<int>>& nums2) {\n int p1 = 0;\n int p2 = 0;\n\n std::vector<std::vector<int>> res;\n\n int n1 = nums1.size();\n int n2 = nums2.size();\n\n while (p1 < n1 && p2 < n2) {\n // if id of nums1 is smaller\n if (nums1[p1][0] < nums2[p2][0]) {\n res.push_back(nums1[p1]);\n p1++;\n }\n // if id of nums2 is smaller\n else if (nums2[p2][0] < nums1[p1][0]) {\n res.push_back(nums2[p2]);\n p2++;\n }\n // id of both nums1 and nums2 is equal\n else {\n res.push_back({nums1[p1][0], nums1[p1][1] + nums2[p2][1]});\n p1++;\n p2++;\n }\n }\n\n // covering cases where one array is longer than the other array. \n while (p1 < n1) {\n res.push_back(nums1[p1]);\n p1++;\n }\n\n while (p2 < n2) {\n res.push_back(nums2[p2]);\n p2++;\n }\n\n return res;\n }\n};\n```\n | 2 | You are given two **2D** integer arrays `nums1` and `nums2.`
* `nums1[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
* `nums2[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
Each array contains **unique** ids and is sorted in **ascending** order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
* Only ids that appear in at least one of the two arrays should be included in the resulting array.
* Each id should be included **only once** and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be `0`.
Return _the resulting array_. The returned array must be sorted in ascending order by id.
**Example 1:**
**Input:** nums1 = \[\[1,2\],\[2,3\],\[4,5\]\], nums2 = \[\[1,4\],\[3,2\],\[4,1\]\]
**Output:** \[\[1,6\],\[2,3\],\[3,2\],\[4,6\]\]
**Explanation:** The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.
**Example 2:**
**Input:** nums1 = \[\[2,4\],\[3,6\],\[5,5\]\], nums2 = \[\[1,3\],\[4,3\]\]
**Output:** \[\[1,3\],\[2,4\],\[3,6\],\[4,3\],\[5,5\]\]
**Explanation:** There are no common ids, so we just include each id with its value in the resulting list.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 200`
* `nums1[i].length == nums2[j].length == 2`
* `1 <= idi, vali <= 1000`
* Both arrays contain unique ids.
* Both arrays are in strictly ascending order by id. | null |
python solution || easy to understand | merge-two-2d-arrays-by-summing-values | 0 | 1 | ```\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n d1,d2 = {},{}\n\t\t# add all entries of nums1 to map d1\n for num in nums1:\n d1[num[0]] = num[1]\n\t\t\t\n\t\t# add all entries of nums2 to map d2\n for num in nums2:\n d2[num[0]] = num[1]\n\t\t\t\n\t\t# to store final ans\n ans = []\n\t\t\n\t\t# traverse map1\n for num in d1.keys():\n val = d1[num]\n\t\t\t\n\t\t\t# if the entry is in map2 add it in the value of map1 and remove it from map2\n if num in d2:\n val += d2[num]\n del d2[num]\n\t\t\t\t\n\t\t\t# add the id,val pair to ans\n ans.append([num,val])\n\t\t\t\n\t\t# traverse map2 to get items that are not in map1\n for key,val in d2.items():\n ans.append([key,val])\n\t\t\t\n\t\t# sort the final ans by ids\n ans.sort(key=lambda x:x[0])\n return ans\n``` | 1 | You are given two **2D** integer arrays `nums1` and `nums2.`
* `nums1[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
* `nums2[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
Each array contains **unique** ids and is sorted in **ascending** order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
* Only ids that appear in at least one of the two arrays should be included in the resulting array.
* Each id should be included **only once** and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be `0`.
Return _the resulting array_. The returned array must be sorted in ascending order by id.
**Example 1:**
**Input:** nums1 = \[\[1,2\],\[2,3\],\[4,5\]\], nums2 = \[\[1,4\],\[3,2\],\[4,1\]\]
**Output:** \[\[1,6\],\[2,3\],\[3,2\],\[4,6\]\]
**Explanation:** The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.
**Example 2:**
**Input:** nums1 = \[\[2,4\],\[3,6\],\[5,5\]\], nums2 = \[\[1,3\],\[4,3\]\]
**Output:** \[\[1,3\],\[2,4\],\[3,6\],\[4,3\],\[5,5\]\]
**Explanation:** There are no common ids, so we just include each id with its value in the resulting list.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 200`
* `nums1[i].length == nums2[j].length == 2`
* `1 <= idi, vali <= 1000`
* Both arrays contain unique ids.
* Both arrays are in strictly ascending order by id. | null |
[Python] Two pointers | merge two sorted arrays | merge-two-2d-arrays-by-summing-values | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMerge two sorted array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTwo pointers.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n + m)$$, where $$n$$ and $$m$$ stand for the length of two input arrays.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n + m)$$\n\n# Code\n```\nclass Solution:\n def mergeArrays(self, nums1: List[List[int]], nums2: List[List[int]]) -> List[List[int]]:\n res = []\n i = 0\n j = 0\n while i < len(nums1) or j < len(nums2):\n if i == len(nums1):\n res.append(nums2[j])\n j += 1\n elif j == len(nums2):\n res.append(nums1[i])\n i += 1\n else:\n if nums1[i][0] == nums2[j][0]:\n res.append([nums1[i][0], nums1[i][1] + nums2[j][1]])\n i += 1\n j += 1\n elif nums1[i][0] < nums2[j][0]:\n res.append(nums1[i])\n i += 1\n else:\n res.append(nums2[j])\n j += 1\n return res\n\n``` | 12 | You are given two **2D** integer arrays `nums1` and `nums2.`
* `nums1[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
* `nums2[i] = [idi, vali]` indicate that the number with the id `idi` has a value equal to `vali`.
Each array contains **unique** ids and is sorted in **ascending** order by id.
Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:
* Only ids that appear in at least one of the two arrays should be included in the resulting array.
* Each id should be included **only once** and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be `0`.
Return _the resulting array_. The returned array must be sorted in ascending order by id.
**Example 1:**
**Input:** nums1 = \[\[1,2\],\[2,3\],\[4,5\]\], nums2 = \[\[1,4\],\[3,2\],\[4,1\]\]
**Output:** \[\[1,6\],\[2,3\],\[3,2\],\[4,6\]\]
**Explanation:** The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.
**Example 2:**
**Input:** nums1 = \[\[2,4\],\[3,6\],\[5,5\]\], nums2 = \[\[1,3\],\[4,3\]\]
**Output:** \[\[1,3\],\[2,4\],\[3,6\],\[4,3\],\[5,5\]\]
**Explanation:** There are no common ids, so we just include each id with its value in the resulting list.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 200`
* `nums1[i].length == nums2[j].length == 2`
* `1 <= idi, vali <= 1000`
* Both arrays contain unique ids.
* Both arrays are in strictly ascending order by id. | null |
python3 , easy bitwise calculation | minimum-operations-to-reduce-an-integer-to-0 | 0 | 1 | # Intuition\nAn integer becomes zero when it has no bit set (i.e. 1). the max operations if we only substract , can be as many as there are number of 1s.\nHowever, there is a way to minimize the operations , if we have\nconsectives 1s more than once in number say 00001111 , if we add 1 to this number then this become 00010000 which needs one more extra operation (add 1 + make new 1 to zero i.e substrat = 2 op only), note originally it would be 4 ops , if we convert all 1 to 0.\nBased on above idea , we can reduce number of ops.\n\n\n# Code\n```\nclass Solution:\n def minOperations(self, n: int) -> int:\n \n count = 0\n op_count = 0\n \n for i in range(32):\n # if bit is set , count it\n if n & (1 << i):\n count += 1\n \n else:\n # if more than one consective 1s\n # we can all make 0 ,by add 1 to it\n if count > 1:\n op_count += 1\n count = 1 # 11101110-> 11110000\n # if chain of consective 1s break, we need to make it 0\n elif count == 1:\n op_count += 1\n count = 0\n else:\n count = 0 \n \n return op_count\n \n \n \n \n \n \n``` | 1 | You are given a positive integer `n`, you can do the following operation **any** number of times:
* Add or subtract a **power** of `2` from `n`.
Return _the **minimum** number of operations to make_ `n` _equal to_ `0`.
A number `x` is power of `2` if `x == 2i` where `i >= 0`_._
**Example 1:**
**Input:** n = 39
**Output:** 3
**Explanation:** We can do the following operations:
- Add 20 = 1 to n, so now n = 40.
- Subtract 23 = 8 from n, so now n = 32.
- Subtract 25 = 32 from n, so now n = 0.
It can be shown that 3 is the minimum number of operations we need to make n equal to 0.
**Example 2:**
**Input:** n = 54
**Output:** 3
**Explanation:** We can do the following operations:
- Add 21 = 2 to n, so now n = 56.
- Add 23 = 8 to n, so now n = 64.
- Subtract 26 = 64 from n, so now n = 0.
So the minimum number of operations is 3.
**Constraints:**
* `1 <= n <= 105` | null |
[Python 3] My brute force kinda way | BFS | minimum-operations-to-reduce-an-integer-to-0 | 0 | 1 | ```\nclass Solution:\n def minOperations(self, n: int) -> int:\n q = deque( [n] )\n seen = set( [n] )\n res = -1\n \n while q:\n res += 1\n for _ in range(len(q)):\n cur = q.popleft()\n \n if cur == 0:\n return res\n \n for i in range(17):\n t = 1 << i\n \n if cur + t <= 2 ** 17 and cur + t not in seen:\n q.append(cur + t)\n seen.add(cur + t)\n if cur - t >= -(2 ** 17) and cur - t not in seen:\n q.append(cur - t)\n seen.add(cur - t)\n``` | 1 | You are given a positive integer `n`, you can do the following operation **any** number of times:
* Add or subtract a **power** of `2` from `n`.
Return _the **minimum** number of operations to make_ `n` _equal to_ `0`.
A number `x` is power of `2` if `x == 2i` where `i >= 0`_._
**Example 1:**
**Input:** n = 39
**Output:** 3
**Explanation:** We can do the following operations:
- Add 20 = 1 to n, so now n = 40.
- Subtract 23 = 8 from n, so now n = 32.
- Subtract 25 = 32 from n, so now n = 0.
It can be shown that 3 is the minimum number of operations we need to make n equal to 0.
**Example 2:**
**Input:** n = 54
**Output:** 3
**Explanation:** We can do the following operations:
- Add 21 = 2 to n, so now n = 56.
- Add 23 = 8 to n, so now n = 64.
- Subtract 26 = 64 from n, so now n = 0.
So the minimum number of operations is 3.
**Constraints:**
* `1 <= n <= 105` | null |
Python BFS | minimum-operations-to-reduce-an-integer-to-0 | 0 | 1 | # Code\n```\nclass Solution:\n def minOperations(self, n: int) -> int:\n largest = 10**5\n lst = []\n i = 0\n res = 1\n # Populate list of all possible 2*i while 2*i < 10**5\n while res < largest:\n lst.append(res)\n i += 1\n res = 2**i\n \n \n q = deque([n])\n operations = 0\n visited = set()\n while q:\n for _ in range(len(q)):\n num = q.popleft()\n if num in visited:\n continue\n visited.add(num)\n if num == 0:\n return operations\n \n # add\n for val in lst:\n # Make sure q doesn\'t get too large with unnessecarry large numbers \n if num + val < 100000:\n q.append(num + val)\n \n # Subtract\n for val in lst:\n # No negatives\n if val > num:\n break\n q.append(num - val)\n operations += 1\n \n \n``` | 1 | You are given a positive integer `n`, you can do the following operation **any** number of times:
* Add or subtract a **power** of `2` from `n`.
Return _the **minimum** number of operations to make_ `n` _equal to_ `0`.
A number `x` is power of `2` if `x == 2i` where `i >= 0`_._
**Example 1:**
**Input:** n = 39
**Output:** 3
**Explanation:** We can do the following operations:
- Add 20 = 1 to n, so now n = 40.
- Subtract 23 = 8 from n, so now n = 32.
- Subtract 25 = 32 from n, so now n = 0.
It can be shown that 3 is the minimum number of operations we need to make n equal to 0.
**Example 2:**
**Input:** n = 54
**Output:** 3
**Explanation:** We can do the following operations:
- Add 21 = 2 to n, so now n = 56.
- Add 23 = 8 to n, so now n = 64.
- Subtract 26 = 64 from n, so now n = 0.
So the minimum number of operations is 3.
**Constraints:**
* `1 <= n <= 105` | null |
Python3, Check Groups of zeros and ones, Quick and Simple | minimum-operations-to-reduce-an-integer-to-0 | 0 | 1 | # Intuition\nWhen we have group of only one `\'1\'`, we eliminate it in one step (subtraction).\nWhen we have group of more ones, we eliminate it in two steps (add and subtract).\n\nWhen we have group of one `\'0\'`, we are not doing subtraction, instead we join new created `\'1\'` to the nexh group of ones.\n\nWe are processing it from right to left.\n\n# Example:\n`n = 3995` \nBinary it is `0111110011011` \n`re.findall(\'1+|0+\',\'0111110011011\')` is `[\'0\', \'11111\', \'00\', \'11\', \'0\', \'11\']`\n\nIteration 1:\nThe last two groups are `\'11\'` and `\'0\'`.\nWe eliminate ones in one step and we have one new `\'1\'` which we add to the next group of ones.\n\nIteration 2:\nNow we have two groups: `\'111\'` and `\'00\'`.\nWe eliminate ones in two steps.\n\nIteration 3:\nNow we have two groups: `\'11111\'` and `\'0\'`.\nWe eliminate ones in two steps.\n\nWe made 1 + 2 + 2 = 5 steps.\nAnswer is 5.\n\n# Code\n```\n def minOperations(self, n: int) -> int:\n b=\'0\'+bin(n)[2:].strip(\'0\')\n groups=re.findall(\'1+|0+\',b)\n i=1\n answ=0\n while i<len(groups):\n if len(groups[-i])==1:\n answ+=1\n elif 1<len(groups[-i-1]):\n answ+=2\n else:\n answ+=1\n if i+2<=len(groups):\n groups[-i-2]+=\'1\'\n else:\n answ+=1\n i+=2\n return answ \n``` | 1 | You are given a positive integer `n`, you can do the following operation **any** number of times:
* Add or subtract a **power** of `2` from `n`.
Return _the **minimum** number of operations to make_ `n` _equal to_ `0`.
A number `x` is power of `2` if `x == 2i` where `i >= 0`_._
**Example 1:**
**Input:** n = 39
**Output:** 3
**Explanation:** We can do the following operations:
- Add 20 = 1 to n, so now n = 40.
- Subtract 23 = 8 from n, so now n = 32.
- Subtract 25 = 32 from n, so now n = 0.
It can be shown that 3 is the minimum number of operations we need to make n equal to 0.
**Example 2:**
**Input:** n = 54
**Output:** 3
**Explanation:** We can do the following operations:
- Add 21 = 2 to n, so now n = 56.
- Add 23 = 8 to n, so now n = 64.
- Subtract 26 = 64 from n, so now n = 0.
So the minimum number of operations is 3.
**Constraints:**
* `1 <= n <= 105` | null |
Python | Factorization and Bit mask | DP | count-the-number-of-square-free-subsets | 0 | 1 | \n# Code\n```python []\nclass Solution:\n def squareFreeSubsets(self, nums: List[int]) -> int:\n \n def getfac(n):\n fac = [2,3,5,7,11,13,17,19,23,29]\n c = 0\n ind = 0\n while n != 1:\n while n % fac[ind] == 0:\n if c & (1<<ind):\n # n can be divided by fac[ind] * fac[ind], so -1\n return -1\n c |= (1<<ind)\n n //= fac[ind]\n ind += 1\n return c\n d = defaultdict(int)\n d[0] = 1\n mod = 1000000007\n for num in nums:\n fac = getfac(num)\n # if -1, then continue\n if fac < 0:\n continue\n k = list(d)\n for dd in k:\n if dd & fac == 0:\n d[dd|fac] += d[dd]\n d[dd|fac] %= mod\n ans = 0\n for n in d.values():\n ans += n\n ans %= mod\n # ans -= 1 for excluding empty set\n ans -= 1\n ans %= mod\n return ans \n \n \n``` | 5 | You are given a positive integer **0-indexed** array `nums`.
A subset of the array `nums` is **square-free** if the product of its elements is a **square-free integer**.
A **square-free integer** is an integer that is divisible by no square number other than `1`.
Return _the number of square-free non-empty subsets of the array_ **nums**. Since the answer may be too large, return it **modulo** `109 + 7`.
A **non-empty** **subset** of `nums` is an array that can be obtained by deleting some (possibly none but not all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[3,4,4,5\]
**Output:** 3
**Explanation:** There are 3 square-free subsets in this example:
- The subset consisting of the 0th element \[3\]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3rd element \[5\]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0th and 3rd elements \[3,5\]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** There is 1 square-free subset in this example:
- The subset consisting of the 0th element \[1\]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 30` | null |
Python approach with counting, no DP or bitmask | count-the-number-of-square-free-subsets | 0 | 1 | # Intuition\nAny list of numbers that doesn\'t have duplicate prime factors works\n\n# Approach\nWe first count and dedupe the input list to get at most 30 unique numbers. We then find the prime factorization of every number and removes ones and products of squares higher than 1.\nThis further reduces our input to at most 17 inputs.\nThis means there\'s only 131,072 possible combinations of these numbers, allowing us to brute force all combinations. (we can also choose to do dp + recursion at this point if we wanted it to be really fast, but it hardly seems worth it with such small inputs)\nNotice that if the length of set of all primes combined is the same as the original list, there was no intersection\n\n# Complexity\n- Time complexity:\n$$O(2^{17}*17*10)$$\n2^17 possible combinations, up to 17 numbers in subset, up to 10 primes per number.\nexpressed in terms of possible numbers $c$ and number of primes $p$:\n$$O(2^c*c*p)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\n\nclass Solution:\n def squareFreeSubsets(self, nums: List[int]) -> int:\n MOD = (10 ** 9 + 7)\n numsc = Counter(nums)\n ones = 1 << numsc[1] # get possible combinations of ones\n \n primefactors = [self.prime_factors(i) for i in numsc.keys()] # get prime factors\n primefactors = list(map(tuple, filter(lambda x: x != -1, primefactors))) # filter ones and square products\n\n if not primefactors:\n return (ones - 1) % MOD\n primefactorscount = {}\n for primefac in primefactors: # map prime factors to count\n primefactorscount[primefac] = numsc[prod(primefac)]\n ans = 0\n if not ones:\n ones = 1\n else:\n ans = ones - 1\n del numsc\n \n for i in range(1, len(primefactors) + 1): # iterate possible lengths\n for subset in combinations(primefactors, i): # iterate all possible combinations\n total = list(chain(*subset))\n if len(total) == len(set(total)): # if square-free subset\n plus = ones # can use any possible combination of ones\n for primelist in subset:\n plus *= primefactorscount[primelist] # multiply by how many instances of this number exists (can choose any one)\n ans += plus\n return ans % (MOD)\n\n\n def prime_factors(self, n):\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n factors = []\n for i in primes:\n if i * i > n:\n break\n if n % i == 0:\n n //= i\n if n % i == 0: # has square factor\n return -1\n factors.append(i)\n if n > 1:\n factors.append(n)\n if not factors:\n return -1 # passed in 1\n return factors\n\n``` | 1 | You are given a positive integer **0-indexed** array `nums`.
A subset of the array `nums` is **square-free** if the product of its elements is a **square-free integer**.
A **square-free integer** is an integer that is divisible by no square number other than `1`.
Return _the number of square-free non-empty subsets of the array_ **nums**. Since the answer may be too large, return it **modulo** `109 + 7`.
A **non-empty** **subset** of `nums` is an array that can be obtained by deleting some (possibly none but not all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[3,4,4,5\]
**Output:** 3
**Explanation:** There are 3 square-free subsets in this example:
- The subset consisting of the 0th element \[3\]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3rd element \[5\]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0th and 3rd elements \[3,5\]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** There is 1 square-free subset in this example:
- The subset consisting of the 0th element \[1\]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 30` | null |
[Python3] DFS + GCD Solution | 70ms (Beats 100%) | count-the-number-of-square-free-subsets | 0 | 1 | # Approach\n**Step 1:** Select all possible `num` between 2 to 30 that does not have a square as its factor. Record all such `num` in a set `candidates`;\n**Step 2:** Use a Counter `cnt` to record the number of appearances in `nums` for all `num` in `candidates`;\n**Step 3:** Define a helper function `count()` that return all possible Square-Free Subsets of a given array `arr` with unique elements;\n**Step 4:** Apply `count()` function on the unique elements of `nums` in `candidates` and multiply by the cardinality of the power set of `1`\'s in `nums`, then subtract 1 (the null subset) to get the final answer.\n\n# Code\n```\nclass Solution:\n def squareFreeSubsets(self, nums: List[int]) -> int:\n MOD = 10 ** 9 + 7\n candidates = set([2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30])\n cnt = defaultdict(int)\n for num in nums:\n if num in candidates:\n cnt[num] += 1\n \n def count(arr):\n if not arr:\n return 1\n arr1 = []\n for num in arr[1:]:\n if math.gcd(num, arr[0]) == 1:\n arr1.append(num)\n return (count(arr[1:]) + cnt[arr[0]] * count(arr1)) % MOD\n \n ones = nums.count(1)\n tmp = 1\n for _ in range(ones):\n tmp = (tmp * 2) % MOD\n return (count(list(cnt)) * tmp - 1) % MOD\n```\n\n# Polished code to make it less lengthy\nCredit to [@bortengineer](https://leetcode.com/bortengineer/).\n```\nclass Solution:\n def squareFreeSubsets(self, nums: List[int]) -> int:\n MOD = 10 ** 9 + 7\n cnt = Counter(nums)\n \n def count(arr):\n if not arr:\n return 1\n arr1 = [x for x in arr if math.gcd(x, arr[0]) == 1]\n return (count(arr[1:]) + cnt[arr[0]] * count(arr1)) % MOD\n\n candidates = [2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30]\n return (count(candidates) * pow(2, cnt[1], MOD) - 1) % MOD\n``` | 23 | You are given a positive integer **0-indexed** array `nums`.
A subset of the array `nums` is **square-free** if the product of its elements is a **square-free integer**.
A **square-free integer** is an integer that is divisible by no square number other than `1`.
Return _the number of square-free non-empty subsets of the array_ **nums**. Since the answer may be too large, return it **modulo** `109 + 7`.
A **non-empty** **subset** of `nums` is an array that can be obtained by deleting some (possibly none but not all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[3,4,4,5\]
**Output:** 3
**Explanation:** There are 3 square-free subsets in this example:
- The subset consisting of the 0th element \[3\]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3rd element \[5\]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0th and 3rd elements \[3,5\]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** There is 1 square-free subset in this example:
- The subset consisting of the 0th element \[1\]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 30` | null |
Concise 9 lines Python with prime factor bitmap and a map to record # of subsets of valid products | count-the-number-of-square-free-subsets | 0 | 1 | # Intuition\n1. A square-free integer requires the prime factorization of an integer doesn\'t have duplicate primes. (That is, each prime have a count of either **1 or 0**)\n2. Follow 1., as the range of possible numbers is very small, we can use bitmask to represent valid integers or subsets.\n3. Since we only care about subsets count, different subsets with the same composition of primes can be represented as a key-value pair with bitmask as key and subsets count as value. \ni.e.\n arr = [3, 5, 5]\n valid subsets are: {**3**(index=0), **5**(index=1)}, {**3**(index=0), **5**(index=2)}, {**3**(index=0)}, {**5**(index=0)}, {**5**(index=1)} \nand can be represent by \n map[**bitmask representation of 3*5**] = 2\n map[**bitmask representation of 3**] = 1\n map[**bitmask representation of 5**] = 2\n\n# Approach\n1. Map all valid numbers to its bit mask representation, each bit represent the existence of a prime factor\n * $2 \\to b\'1 = 1,\\; 3 \\to b\'10 = 2,\\; 5 \\to b\'100 = 4,\\; 7 \\to b\'1000 = 8 ...$\n * 1 is special because its existance does not affect anything, we use 0 so that every number that AND with it would result 0\n * For other valid numbers, do OR operation with the bit mask of its prime factor, $30 = 2 * 3 * 5 \\to 1 | 2 | 4 = 7$\n\n2. Now, we can check if a subset is still valid after adding a number by checking if the AND of their bitmasks is 0.\n i.e. \n * {6,7} and 11 ? $6 \\to b\'1\' | b\'10\',\\; 7 \\to b\'1000\',\\; 11 \\to b\'10000\'$, since $b\'1\' | b\'10\' | b\'1000\' & b\'10000\' = 0$, {6, 7, 11} is still a valid set\n3. Then, we loop over every valid number and do AND operation with bit representations of all valid subset bitmask representations we currently have, a result of 0 means that there\'s no duplicate prime factor between product of the subset and this number \n4. Since a subset that only contains the valid number itself: $count[valid[n]] += 1$\n\n# Complexity\nTime complexity: $O(n \\times 2^{10})$\nSpace complexity: $O(2^{10})$\n\nSince there are only 10 prime factors in [1, 30], the max size of count map is $2^{10}$ (Either pick or not pick a prime factor)\n# Code\n```python\nclass Solution:\n def squareFreeSubsets(self, nums):\n # Pre-prepared bitmask\n valid = {1:0, 2:1, 3:2, 5:4, 6:3, 7:8, 10:5, 11:16, 13:32, 14:9, 15:6, 17:64, 19:128, 21:10, 22:17, 23:256, 26:33, 29:512, 30:7}\n count = defaultdict(int)\n for n in nums:\n if n in valid:\n for k in count.copy():\n # If n & subset with bitmask k have common prime factor\n if valid[n] & k == 0:\n # Since the subset is still valid taking n in, we now have count[k] more subsets\n # count[k] subsets without n and count[k] subsets with n\n count[valid[n]|k] += count[k]\n # subset {n}\n count[valid[n]] += 1\n return sum(count.values()) % (10 ** 9 + 7)\n \n``` | 11 | You are given a positive integer **0-indexed** array `nums`.
A subset of the array `nums` is **square-free** if the product of its elements is a **square-free integer**.
A **square-free integer** is an integer that is divisible by no square number other than `1`.
Return _the number of square-free non-empty subsets of the array_ **nums**. Since the answer may be too large, return it **modulo** `109 + 7`.
A **non-empty** **subset** of `nums` is an array that can be obtained by deleting some (possibly none but not all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[3,4,4,5\]
**Output:** 3
**Explanation:** There are 3 square-free subsets in this example:
- The subset consisting of the 0th element \[3\]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3rd element \[5\]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0th and 3rd elements \[3,5\]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** There is 1 square-free subset in this example:
- The subset consisting of the 0th element \[1\]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 30` | null |
Python fast dfs | count-the-number-of-square-free-subsets | 0 | 1 | \n# Code\n```\nclass Solution:\n def squareFreeSubsets(self, nums: List[int]) -> int:\n squares = {4, 8, 9, 12, 16, 18, 20, 24, 25, 27, 28}\n nums = [x for x in nums if x not in squares]\n c, nums = collections.Counter(nums), sorted(set(nums))\n \n @cache\n def getBit(x):\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n return sum([1 << i for i, p in enumerate(primes) if x % p == 0])\n \n def dfs(u, cnt, mask):\n subRes = cnt\n for v in range(u + 1, len(nums)):\n if mask & getBit(nums[v]) == 0:\n choice = (2 ** c[nums[v]] - 1) if nums[v] == 1 else c[nums[v]]\n subRes += dfs(v, cnt * choice, mask | getBit(nums[v]))\n return subRes \n return (dfs(-1, 1, 0) - 1) % (10 ** 9 + 7)\n``` | 2 | You are given a positive integer **0-indexed** array `nums`.
A subset of the array `nums` is **square-free** if the product of its elements is a **square-free integer**.
A **square-free integer** is an integer that is divisible by no square number other than `1`.
Return _the number of square-free non-empty subsets of the array_ **nums**. Since the answer may be too large, return it **modulo** `109 + 7`.
A **non-empty** **subset** of `nums` is an array that can be obtained by deleting some (possibly none but not all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[3,4,4,5\]
**Output:** 3
**Explanation:** There are 3 square-free subsets in this example:
- The subset consisting of the 0th element \[3\]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3rd element \[5\]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0th and 3rd elements \[3,5\]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** There is 1 square-free subset in this example:
- The subset consisting of the 0th element \[1\]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 30` | null |
Python 3 || 10 lines, w/ explanation and example || T/M: 100% / 98% | count-the-number-of-square-free-subsets | 0 | 1 | This approach is pretty much the same as many already posted, but we try to optimize in two ways:\n1. Using `Counter` to reduce the amount of repetative work, and\n2. Divide the integers `1,2,3, ..., 29,30` into those elements that could contribute to a square factor(`prefix`), and those that cannot(`suffix`). Those that already have a square factor are ignored in the`Counter`.\n```\nclass Solution:\n def squareFreeSubsets(self, nums):\n\n prefix = (( 2, 1), ( 3, 2), ( 6, 3), ( 5, 4), (10, 5), # <-- These are \'prefix elements,\' the fourteen \n (15, 6), (30, 7), ( 7, 8), (14, 9), (21,10), # elements of nums, tupled along with their masks, \n (11,16), (13,32), (22,17), (26,33)) # that could potentially contribute to a square\n # factor. We use a tuple of tuples instead of a dict \n # for the iteration below.\n\n suffix = {1,17,19,23,29} # <-- The \'suffix\' elements\n\n nums, cnt = Counter(nums), defaultdict(int)\n\n for n, p in prefix:\n # <-- This is the standard stuff, except we use\n for k in list(cnt): # Counter to do each like value together instead\n if not p & k: cnt[p|k] += cnt[k]*nums[n] # of iterating thru nums element by element.\n #\n cnt[p]+= nums[n] #\n\n ans = (sum(cnt.values())+1)*pow(2,nums[1])-1 # <-- We mutiply the prefix count by the number of \n # potential 1s that may be appended to any prefix.\n \n for n in (17,19,23,29): ans = (ans+1)*(nums[n]+1) - 1 # <-- The other suffix elements. These factors differ\n # from the 1s because including more than one \n # will produce a square factor\n return ans % (10 ** 9 + 7)\n```\n[https://leetcode.com/problems/count-the-number-of-square-free-subsets/submissions/901832329/](http://)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*).\n | 5 | You are given a positive integer **0-indexed** array `nums`.
A subset of the array `nums` is **square-free** if the product of its elements is a **square-free integer**.
A **square-free integer** is an integer that is divisible by no square number other than `1`.
Return _the number of square-free non-empty subsets of the array_ **nums**. Since the answer may be too large, return it **modulo** `109 + 7`.
A **non-empty** **subset** of `nums` is an array that can be obtained by deleting some (possibly none but not all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[3,4,4,5\]
**Output:** 3
**Explanation:** There are 3 square-free subsets in this example:
- The subset consisting of the 0th element \[3\]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3rd element \[5\]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0th and 3rd elements \[3,5\]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** There is 1 square-free subset in this example:
- The subset consisting of the 0th element \[1\]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 30` | null |
careful implementation bitmask recursion (with almost oneliner variant; okey 3rd is oneliner): | count-the-number-of-square-free-subsets | 0 | 1 | \n```\nclass Solution:\n def squareFreeSubsets(self, n: List[int]) -> int:\n m,c=10**9+7,Counter(n)\n o=pow(2,c[1],m)\n for i in 17,19,23,29:o=o*(c[i]+1)%m\n b={2:1,3:2,5:4,6:3,7:8,10:5,11:16,13:32,14:9,15:6,21:10,22:17,26:33,30:7}\n for i in set(range(1,30))-set(b):del c[i]\n l=len(k:=list(c))\n #@cache\n def f(p,s):return (1+sum(c[v]*f(i+1,s|x)%m for i in range(p,l) if not s&(x:=b[v:=k[i]])))%m\n o=f(0,0)%m*o%m\n return (o-1+m)%m\n```\n\nalmost onliner:\n```\nclass Solution:\n def squareFreeSubsets(self, n: List[int]) -> int:\n for i in [d:=Counter(c:=Counter(n)),m:=10**9+7,set(range(1,30))-set(b:={2:1,3:2,5:4,6:3,7:8,10:5,11:16,13:32,14:9,15:6,21:10,22:17,26:33,30:7})].pop():del c[i]\n return (l:=len(k:=list(c)),(pow(2,d[1],m)*reduce(mul,(d[i]+1 for i in (17,19,23,29)))%m*(f:=lambda p,s:(1+sum(c[v]*f(i+1,s|x)%m for i in range(p,l) if not s&(x:=b[v:=k[i]])))%m)(0,0)+m-1)%m)[-1]\n```\n\nvuala onliner it is:\n```\nclass Solution:\n squareFreeSubsets=lambda s,n:(b:={2:1,3:2,5:4,6:3,7:8,10:5,11:16,13:32,14:9,15:6,21:10,22:17,26:33,30:7},d:=Counter(c:=Counter(n)),m:=10**9+7,{c.pop(i,0) for i in set(range(1,30))-set(b)},l:=len(k:=list(c)),(pow(2,d[1],m)*reduce(mul,(d[i]+1 for i in (17,19,23,29)))%m*(f:=lambda p,s:(1+sum(c[v]*f(i+1,s|x)%m for i in range(p,l) if not s&(x:=b[v:=k[i]])))%m)(0,0)+m-1)%m)[-1] | 0 | You are given a positive integer **0-indexed** array `nums`.
A subset of the array `nums` is **square-free** if the product of its elements is a **square-free integer**.
A **square-free integer** is an integer that is divisible by no square number other than `1`.
Return _the number of square-free non-empty subsets of the array_ **nums**. Since the answer may be too large, return it **modulo** `109 + 7`.
A **non-empty** **subset** of `nums` is an array that can be obtained by deleting some (possibly none but not all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[3,4,4,5\]
**Output:** 3
**Explanation:** There are 3 square-free subsets in this example:
- The subset consisting of the 0th element \[3\]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3rd element \[5\]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0th and 3rd elements \[3,5\]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** There is 1 square-free subset in this example:
- The subset consisting of the 0th element \[1\]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 30` | null |
recursion + map + fully explanation | count-the-number-of-square-free-subsets | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. It is noteworthy that the complexity of the question may be reduced by considering the given numbers as a set rather than an array.\n2. The range of numbers within the set allows for the pre-definition of all numbers between 1 and 30 that are free from squares.\n3. It is of paramount importance to recognize that the product of two square-free numbers is also square-free only if they are relatively prime, meaning that their greatest common divisor is equal to 1.\n4. By excluding the ones, we can compute the number of square-free subsets and subsequently double the quantity obtained based on the number of ones.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Count the number of each square-free number in the array named it counter_map.\n2. Using helper function to compute the number of non-empty square-free subset given set converted from counter_map.\n3. Doublue the result number of ones times and minus 1.\n# Complexity\n- Time complexity: O(n) Where n is the size of nums\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe running time should be linear, since the counter_map is constant size.\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSince the size of candidates is constant.\n# Code\n```\nclass Solution:\n def squareFreeSubsets(self, nums: List[int]) -> int:\n MOD = 10 ** 9 + 7 # applied when the number is too large\n # helper function to count the number of non-empty square-free subset given a set of number\n def sfs_for_set(_set):\n if not _set:\n return 1\n current_set = []\n for num in _set[1:]:\n if math.gcd(num, _set[0]) == 1:\n current_set.append(num)\n # recursively get the number of sf subset given the rest of set\n # each duplicated number contribute the same size so we do multiplication here \n return (sfs_for_set(_set[1:]) + counter_map[_set[0]] * sfs_for_set(current_set)) % MOD\n # the candidates which are square-free in the range [1, 30]\n candidates = set([2, 3, 5, 6, 7, 10, 11, 13, 14, 15, 17, 19, 21, 22, 23, 26, 29, 30])\n # count the number of appearance for each canditate\n counter_map = defaultdict(int)\n for num in nums:\n if num in candidates:\n counter_map[num] += 1\n # for each additional one, it could double the number of square-free subse \n return (sfs_for_set(list(counter_map)) * 2 ** nums.count(1) - 1) % MOD\n``` | 0 | You are given a positive integer **0-indexed** array `nums`.
A subset of the array `nums` is **square-free** if the product of its elements is a **square-free integer**.
A **square-free integer** is an integer that is divisible by no square number other than `1`.
Return _the number of square-free non-empty subsets of the array_ **nums**. Since the answer may be too large, return it **modulo** `109 + 7`.
A **non-empty** **subset** of `nums` is an array that can be obtained by deleting some (possibly none but not all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
**Example 1:**
**Input:** nums = \[3,4,4,5\]
**Output:** 3
**Explanation:** There are 3 square-free subsets in this example:
- The subset consisting of the 0th element \[3\]. The product of its elements is 3, which is a square-free integer.
- The subset consisting of the 3rd element \[5\]. The product of its elements is 5, which is a square-free integer.
- The subset consisting of 0th and 3rd elements \[3,5\]. The product of its elements is 15, which is a square-free integer.
It can be proven that there are no more than 3 square-free subsets in the given array.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 1
**Explanation:** There is 1 square-free subset in this example:
- The subset consisting of the 0th element \[1\]. The product of its elements is 1, which is a square-free integer.
It can be proven that there is no more than 1 square-free subset in the given array.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 30` | null |
[Python3] O(n^2) Build string from left to right and z-function check LCP | find-the-string-with-lcp | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst we build s from left to right. For position i, we will fill it with current smallest char if it is empty. Next we will check lcp with all other substrings starting with i+1, i+2, ..., n-1. If lcp[i][j] > 0, it means s[j] == s[i]. \nRepeat this process we will always get a string. Then we use z-function to check the lcp matrix. The detail of z-function please refer to [https://cp-algorithms.com/string/z-function.html](https://cp-algorithms.com/string/z-function.html).\n\n**Notice:**\n1. The lcp matrix is symmetric. The diagonal element is same as the substring length.\n2. Make sure the chars we used are not exceed 26.\n\n\n# Code\n```\nclass Solution:\n def z_function(self, s):\n n = len(s)\n z = [0] * n\n l, r = 0, 0\n for i in range(1, n):\n if i <= r and z[i - l] < r - i + 1:z[i] = z[i - l]\n else:\n z[i] = max(0, r - i + 1)\n while i + z[i] < n and s[z[i]] == s[i + z[i]]:z[i] += 1\n if i + z[i] - 1 > r:\n l = i\n r = i + z[i] - 1\n z[0] = len(s)\n return z\n\n def findTheString(self, lcp: List[List[int]]) -> str:\n n = len(lcp)\n s, idx = [\'\'] * n, 0\n for i in range(n):\n if i + lcp[i][i] != n: return \'\'\n if s[i] == \'\':\n if idx > 25: return \'\'\n s[i] = chr(ord(\'a\') + idx)\n idx += 1\n for j in range(i + 1, n):\n if lcp[i][j] != lcp[j][i]: return \'\'\n if lcp[i][j]:\n if s[j] != \'\' and s[j] != s[i]: return \'\'\n s[j] = s[i]\n s = \'\'.join(s)\n return \'\' if any(self.z_function(s[i:]) != lcp[i][i:] for i in range(n)) else s\n``` | 1 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
Support an Omissive Test Case | find-the-string-with-lcp | 0 | 1 | Some code([example1](https://leetcode.com/submissions/detail/900802586/), [example2](https://leetcode.com/submissions/detail/901252948/)) only checks this two constraints:\n\n1. if lcp[i][j] == 0 then str[i] != str[j]\n2. if lcp[i][j] < n - j then str[i + lcp[i][j]] != str[j + lcp[i][j]]\n\nbut also got Accepted! \n\nHere is a new case which can make it get Wrong Answer.\n\n```\n[[5,0,2,0,0],[0,4,0,0,0],[2,0,3,0,0],[0,0,0,2,0],[0,0,0,0,1]]\n```\n | 4 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
[Python3] tabu search | find-the-string-with-lcp | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/485c537c6fa9056ce656959ea352d2a68cef473f) for solutions of weekly 333. \n\n```\nclass Solution:\n def findTheString(self, lcp: List[List[int]]) -> str:\n n = len(lcp)\n ans = []\n for i in range(n): \n tabu = set()\n for j in range(i): \n if lcp[i][j]: \n ans.append(ans[j])\n break\n else: tabu.add(ans[j])\n else: \n for ch in ascii_lowercase: \n if ch not in tabu: \n ans.append(ch)\n break\n else: return ""\n dp = [[0]*n for _ in range(n)]\n for i in range(n-1, -1, -1): \n for j in range(n-1, -1, -1): \n if ans[i] == ans[j]: \n if i == n-1 or j == n-1: dp[i][j] = 1\n else: dp[i][j] = 1 + dp[i+1][j+1]\n if dp[i][j] != lcp[i][j]: return ""\n return "".join(ans)\n``` | 4 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
[Python3] Union find solution | find-the-string-with-lcp | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUnion find structure helps a lot with combining the same chars and then checking for contradictions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nStep 1: Use rules from lcp array to unify same symbols. Simultaneously checking for inconsistencies.\nStep 2: Check all conditions fulfilled and self-consistent.\nStep 3: Use union find structure to fill answer with chars.\n\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 findTheString(self, lcp: List[List[int]]) -> str:\n n = len(lcp)\n uf = [i for i in range(n)]\n \n def find(x):\n if uf[x] == x:\n return x\n uf[x] = find(uf[x])\n return uf[x]\n \n # Step 1: Use rules from lcp array to unify same symbols. Simultaneously checking for inconsistencies.\n for i in range(n):\n # bc symbols are equal to themselves\n if lcp[i][i] + i != n:\n return ""\n for j in range(i + 1, n):\n # border and symmetry check\n if j + lcp[i][j] > n or lcp[i][j] != lcp[j][i]:\n return ""\n \n if lcp[i][j]:\n if j + 1 < n and lcp[i + 1][j + 1] + 1 != lcp[i][j]:\n return ""\n \n uf[i] = uf[j] = min(find(i), find(j))\n \n # Step 2: Check all conditions fulfilled and self-consistent.\n for i in range(n):\n for j in range(i + 1, n):\n # cases: need to be unequal, but in reality opposite\n if lcp[i][j] == 0 and find(i) == find(j):\n return ""\n if lcp[i][j] > 0 and lcp[i][j] + j < n and find(i + lcp[i][j]) == find(j + lcp[i][j]):\n return ""\n \n # Step 3: Use union find structure to fill answer with chars.\n ret = [None] * n\n letter = 97 # ASCII code of \'a\' letter\n for i in range(len(ret)):\n val = find(i)\n if ret[val] is not None:\n ret[i] = ret[val]\n else:\n # if needed more letters, we can\'t afford it, as \'z\' has 122 ASCII code\n if letter == 123:\n return ""\n ret[i] = chr(letter)\n letter += 1\n return \'\'.join(ret)\n \n``` | 6 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
[Python 3] Build pattern & Validate lcp - O(N^2) | find-the-string-with-lcp | 0 | 1 | # Complexity\n- Time complexity: $O(N^2)$\n\n- Space complexity: $O(N^2)$ (can be reduced to $O(N)$ if build and check new lcp at the same time)\n\n# Code\n```\nclass Solution:\n def findTheString(self, lcp: List[List[int]]) -> str:\n # simple validation\n n = len(lcp)\n for i in range(n):\n for j in range(i + 1, n):\n if lcp[i][j] != lcp[j][i]:\n return \'\'\n if lcp[i][j] > n - j:\n return \'\'\n for i in range(n):\n if lcp[i][i] != n - i:\n return \'\'\n \n # build pattern \u2014 the only possible candidate for answer\n pattern = [None for _ in range(n)]\n next_el_ind = 0\n for i in range(n):\n if pattern[i] is not None:\n continue\n pattern[i] = next_el_ind\n next_el_ind += 1\n for j in range(i+1, n):\n if lcp[i][j] > 0:\n if pattern[j] is not None and pattern[j] != pattern[i]:\n return \'\'\n pattern[j] = pattern[i]\n \n # check if lcp is valid - check that pattern\'s lcp == original lcp\n pattern_lcp = [[0 for _ in range(n)] for _ in range(n)]\n for i in range(n-1, -1, -1):\n for j in range(n-1, -1, -1):\n if pattern[i] == pattern[j]:\n if max(i, j) + 1 < n:\n pattern_lcp[i][j] = pattern_lcp[i+1][j+1] + 1\n else:\n pattern_lcp[i][j] = 1\n for i in range(n):\n for j in range(n):\n if lcp[i][j] != pattern_lcp[i][j]:\n return \'\'\n \n # check that answer has no more than 26 distinct elements\n if max(pattern) > ord(\'z\') - ord(\'a\'):\n return \'\'\n\n return \'\'.join(chr(ord(\'a\') + ind) for ind in pattern)\n``` | 0 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
[Python3] Simple and commented O(N^2) | find-the-string-with-lcp | 0 | 1 | # Code\n```\nclass Solution:\n\n def checkNewLCP(self, lcp: List[List[int]], output: List[str]) -> bool:\n n = len(output)\n for row_index in range(n):\n for col_index in range(n):\n prev_val = lcp[row_index+1][col_index+1] if (row_index+1 < n and col_index+1 < n) else 0\n expected_val = -1\n if output[col_index] == output[row_index]:\n # If the two chars match, it means they must extend the prefix of lcp[row_index+1][col_index+1] by one because we have an additional matching char in both substrings\n expected_val = prev_val + 1\n else:\n # Since the additional char in the two substrings does not match, I expect the prefix to become zero\n expected_val = 0\n if lcp[row_index][col_index] != expected_val:\n return False\n return True\n\n def checkOldLCP(self, lcp: List[List[int]]) -> bool:\n n = len(lcp)\n for row_index in range(n):\n for col_index in range(n):\n if row_index == col_index:\n # Check if the value is the expected one\n expected_value = n - row_index\n if lcp[row_index][col_index] != expected_value:\n return False\n if lcp[row_index][col_index] != lcp[col_index][row_index]:\n return False\n # Check the length of the two string\n if lcp[row_index][col_index] > n - max(row_index, col_index):\n return False\n return True\n\n def findTheString(self, lcp: List[List[int]]) -> str:\n # Check if the matrix is symmetric and if in its principal diagonal we have the series [N, ..., 1]\n n = len(lcp)\n if not self.checkOldLCP(lcp):\n return ""\n \n output = [\'$\'] * n\n current_letter_index = 0\n\n for row_index in range(n):\n for col_index in range(row_index, n):\n # If a letter has not been assigned to this position, assign it\n if output[row_index] == \'$\':\n # If we ran out of letters, then we cannot build this string\n if ord(\'a\') + current_letter_index > ord(\'z\'):\n return ""\n output[row_index] = chr(ord(\'a\') + current_letter_index)\n current_letter_index += 1\n\n assert output[row_index] != \'$\'\n if lcp[row_index][col_index] == 0:\n # Rule: The two positions must not match\n if output[row_index] == output[col_index]:\n return ""\n else:\n # Rule: The two positions must match\n\n # if there is already a character assigned to the "col_index" position, it must have been assigned by another rule, so there\'s a mismatch between rules => return empty string\n if output[col_index] != \'$\':\n if output[col_index] != output[row_index]:\n return ""\n else:\n # The two positions already match, so nothing to do\n pass\n else:\n # Assign the character in row_index position to the col_index position as dictated by the rule\n output[col_index] = output[row_index]\n \n if not self.checkNewLCP(lcp, output):\n return ""\n else:\n return "".join(output)\n``` | 0 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
Clean python solution | find-the-string-with-lcp | 0 | 1 | # Code\n```\nclass Solution:\n def findTheString(self, lcp: List[List[int]]) -> str:\n res = \'\'\n if not check_valid_lcp(lcp):\n return \'\'\n\n for i in range(len(lcp)): \n exact = set()\n diff = set()\n for j in range(i):\n if lcp[i][j] > 0:\n exact.add(res[j])\n else:\n diff.add(res[j])\n if len(exact) > 1:\n return \'\'\n if len(exact) == 1:\n res += (list(exact)[0])\n if res[i] in diff:\n return \'\'\n if len(exact) == 0:\n c = choose_diff_char(diff)\n if c == \'\':\n return \'\'\n res += c\n\n return res\n\nalphabet = [chr(i+ ord(\'a\')) for i in range(26)]\ndef choose_diff_char(diff):\n for c in alphabet:\n if c not in diff:\n return c\n return \'\'\n\ndef check_valid_lcp(lcp):\n for i in range(len(lcp)):\n if lcp[i][i] != len(lcp) - i:\n return False\n for j in range(i):\n if lcp[i][j] != lcp[j][i] or lcp[i][j] > len(lcp) - i:\n return False\n if i == len(lcp)-1:\n next_value = 0\n else:\n next_value = lcp[i+1][j+1]\n\n if lcp[i][j] !=0 and lcp[i][j] != next_value+1:\n return False\n return True\n\n``` | 0 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
O(n^2) solution explained | Python | find-the-string-with-lcp | 0 | 1 | # Intuition\nOne way to solve this problem is to reverse-engineer the string from the given LCP matrix.\n\n# Approach\n1. Check top-left to bottom-right diagonal. They should be in strictly decreasing order from n -> 1.\n2. Reverse engineer the string. Att each position:\n - If the position has been filled, that means if there is any position after the current position that needs to be the same as the current position, it should be already filled too with the same character.\n - If the position has not been filled, We fill the position with the next available character `curr_l` and all the positions after that, that have to be the same as curr position.\n3. This step would be kind of DP, but instead of filling in values, we check the values.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def findTheString(self, lcp: List[List[int]]) -> str:\n n = len(lcp)\n letters = [None] * n\n curr_l = \'a\'\n \n for i in range(n):\n if lcp[i][i] != n-i: return ""\n lcp[i].append(0)\n \n for i in range(n):\n l = letters[i]\n if l is not None:\n for j in range(i+1, n):\n if lcp[i][j] != lcp[j][i]: return ""\n if lcp[i][j] and letters[j] != l: return ""\n else:\n if curr_l > \'z\': return ""\n for j in range(i, n):\n if lcp[i][j] != lcp[j][i]: return ""\n if lcp[i][j]:\n if letters[j]:\n if letters[j] != curr_l: return ""\n else:\n letters[j] = curr_l\n curr_l = chr(ord(curr_l) + 1)\n \n \n for i in range(n-1):\n for j in range(i+1, n):\n if letters[i] == letters[j] and lcp[i][j]!=lcp[i+1][j+1]+1:\n return ""\n \n \n return \'\'.join(letters)\n \n``` | 0 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
Python (Union Find) | find-the-string-with-lcp | 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 findTheString(self, lcp):\n n = len(lcp)\n\n dict1 = defaultdict(int)\n\n def find(x):\n if x not in dict1:\n return x\n else:\n if x != dict1[x]:\n dict1[x] = find(dict1[x])\n return dict1[x]\n\n def union(x,y):\n a,b = find(x),find(y)\n\n if a > b:\n dict1[a] = b\n else:\n dict1[b] = a\n\n for i in range(n):\n for j in range(i):\n if lcp[i][j]: union(i,j)\n\n ans = [find(i) for i in range(n)]\n\n for i in range(n):\n for j in range(n):\n val = lcp[i+1][j+1] if i+1 < n and j+1 < n else 0\n val = val + 1 if ans[i] == ans[j] else 0\n if val != lcp[i][j]:\n return ""\n\n group = set(ans)\n if len(group) > 26: return ""\n dict2 = {x:i for i,x in enumerate(sorted(group))}\n\n res = []\n\n for i,k in enumerate(ans):\n res.append(chr(97+dict2[k]))\n\n return "".join(res)\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n \n\n \n\n \n\n \n\n\n \n``` | 0 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
[Python3] Greedy O(n^2) solution with O(n) space cost with some exposition. | find-the-string-with-lcp | 0 | 1 | # Intuition and Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\n## Greedy\nWe can construct a valid string, not necessarily the lexicographically smallest one, by starting to look at the `lcp[i][j]` values for large `i` and `j` and moving toward smaller values. For example, suppose the string we want to construct is `s` and `len(lcp) == n` then we can put an arbitrary letter at `s[n-1]`, say `s[n-1] = \'z\'`. `lcp[n-2][n-1]` is either `0` or `1`. If it is `1` that means `s[n-2] == s[n-1]` and we assign `s[n-2] = \'z\'`. If it is `0` then `s[n-2] != s[n-1]` and we assign a different letter to `s[n-2]`, say `s[n-2] = \'y\'`. Once the last two letters have been decided we can focus on `s[n-3]` and fix it by first comparing it with `s[n-1]` (i.e. by looking at `lcp[n-3][n-1]`), and then comparing it with `s[n-2]` (i.e. by looking at `lcp[n-3][n-2]`). This process can be continued until we have fixed the first letter `s[0]`.\n\nSicne we have to iterate over the 2d array `lcp`, the time complexity is going to be $$O(n^2)$$.\n\n## Lexicographically minimum\nThe `lcp` matrix does not change if we change distinct letters in the string by distinct letters. So, once a valid string has been found it can be turned into the lexicographically smallest one by iterating once over the string. Before we start iterating, we consider all the letters in the alphabet to be avaialble. Then, wehenever we encounter a new letter in the string, we replace it with the smallest available letter, and mark that letter as unavailable. This takes $$O(n)$$ time, which is subleading to the $$O(n^2)$$ cost of iterating over `lcp`.\n\n## Some observations about a valid lcp matrix\n1. It is symmetric, obviously, the lcp of `s[i:]` and `s[j:]` is the same as that of `s[j:]` and `s[i:]`.\n2. `lcp[i][i] == n-i` because the lcp of `s[i]` and `s[i]` is `s[i]` itself. We use these to check if we have a valid `lcp` matrix as we iterate over it.\n3. If `lcp[i][j] != 0`, then `lcp[i][j] == lcp[i+1][j+1]+1` because the lcp of `s[i]` and `s[j]` is simply the lcp of `s[i+1]` and `s[j+1]` preceded by s[i]\n\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 findTheString(self, lcp: list[list[int]]) -> str:\n n = len(lcp)\n \n # start with the possibility that any letter can be placed anywhere\n s = [\'abcdefghijklmnopqrstuvwxyz\' for _ in range(n)] \n # storing this array takes O(26*n) = O(n) space.\n \n # arbitrarily assing the final letter in the string\n s[-1] = \'z\'\n \n for row in range(n-1,-1,-1):\n for col in range(n-1, row-1, -1):\n # lcp has to be symmetric\n if lcp[row][col] != lcp[col][row]: return(\'\')\n\n if row == col:\n # lcp[i][i] has to equal n-i\n if lcp[row][col] != n-row: return(\'\')\n\n # once we have compared s[row] with s[row+1:] and eliminated all letters from the possible choices for s[row], we can freely assign one out of the remaining pool. If nothing remains in the pool, a valid string does not exist.\n if len(s[row]): s[row] = s[row][-1]\n else: return(\'\')\n continue\n \n c = s[col]\n \n # if lcp[row][col] is zero, we remove s[col] from the list of possible letters for s[row]\n if lcp[row][col] == 0:\n if s[row][-1] == c: s[row] = s[row][:-1]\n if not s[row]: return(\'\')\n continue\n \n # if lcp[i][j] is nonzero then it must equal lcp[i+1][j+1] + 1 \n if lcp[row][col] > min(n-row, n-col): return(\'\')\n if col < n-1 and lcp[row+1][col+1] != lcp[row][col]-1: return(\'\')\n \n # once all these checks have been passed and lcp[row][col] is nonzero, we can safely assign s[row] to be equal to s[col]\n if c not in s[row]: return(\'\')\n else: s[row] = c\n \n # from the existing string s (a list of characters at the momen), generate the lexicographically smallest one\n sub = 26*[None]\n newLetter = \'a\'\n for i, c in enumerate(s):\n if sub[ord(c)-ord(\'a\')] is None:\n sub[ord(c)-ord(\'a\')] = newLetter\n s[i] = newLetter\n newLetter = chr(ord(newLetter)+1)\n else:\n s[i] = sub[ord(s[i])-ord(\'a\')]\n \n return(\'\'.join(s))\n``` | 0 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
DSU +Z function solution | find-the-string-with-lcp | 0 | 1 | <!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\njust did what the question said with help of suitable ds and Z function\n<!-- Describe your approach to solving the problem. -->\n\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass dsu():\n\tdef __init__(self,n):\n\t\tself.parent=[0]*(n)\n\t\tself.sz=[0]*(n)\n\n\tdef make_set(self,v):\n\t\tself.parent[v]=v\n\t\tself.sz[v]=1\n\n\tdef find_set(self,v):\n\t\tif v==self.parent[v]:\n\t\t\treturn v\n\t\tself.parent[v]=self.find_set(self.parent[v])\n\t\treturn self.parent[v]\n\n\tdef union(self,a,b):\n\t\ta=self.find_set(a)\n\t\tb=self.find_set(b)\n\t\tif a==b:\n\t\t\treturn\n\t\tif self.sz[a]<self.sz[b]:\n\t\t\ta,b=b,a\n\t\tself.parent[b]=a\n\t\tself.sz[a]+=self.sz[b]\n\n\tdef getsize(self,v):\n\t\treturn self.sz[self.find_set(v)]\ndef Z(s):\n\tn=len(s)\n\tx=0;y=0\n\tz=[0]*(n)\n\tfor i in range(1,n):\n\t\tz[i]=max(0,min(z[i-x],y-i+1))\n\t\twhile i+z[i]<n and s[z[i]]==s[i+z[i]]:\n\t\t\tx=i\n\t\t\ty=i+z[i]\n\t\t\tz[i]+=1\n\treturn z\nclass Solution:\n def findTheString(self, l: List[List[int]]) -> str:\n pairs=[]\n n=len(l)\n ds=dsu(n)\n for i in range(n):\n ds.make_set(i)\n for i in range(n):\n for j in range(n):\n if l[i][j]:\n if ds.find_set(i)!=ds.find_set(j):\n ds.union(i,j)\n st=defaultdict(list)\n for i in range(n):\n st[ds.find_set(i)].append(i)\n vis=[0]*n\n let="abcdefghijklmnopqrstuvwxyz"\n print(len(let))\n base=0\n sr=["-1"]*n\n for i in range(n):\n \n if vis[i]:\n continue\n for vl in st[ds.find_set(i)]:\n vis[vl]=1\n sr[vl]=let[base]\n base+=1\n if base>=26:\n base=0\n # return ""\n fl=False\n lc=[]\n sr="".join(sr)\n for i in range(n):\n li=sr[i:]\n x=li+"#"+sr\n zr=Z(x)\n print(zr)\n lc.append(zr[len(li)+1:])\n if lc!=l:\n return ""\n return sr\n``` | 0 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
[1Sentence]Build the sequence by looking at non-zero elems (easy) and verify diagonally from the end | find-the-string-with-lcp | 0 | 1 | \n# Code\n```\ndef findTheString(self, lcp: List[List[int]]) -> str:\n n = len(lcp)\n seq = [0] * n\n letter = ord(\'a\')\n lcp.append([0] * (n+1))\n for i in range(0, n):\n if not seq[i]:\n for j in range(i, n):\n if lcp[i][j]:\n seq[j] = letter\n letter += 1\n if letter > ord(\'z\') + 1:\n return ""\n for i in reversed(range(n)):\n for j in range(i+1):\n if not (lcp[i][j] == lcp[j][i] == (lcp[i+1][j+1] + 1 if seq[i] == seq[j] else 0)):\n return ""\n return \'\'.join([chr(i) for i in seq])\n``` | 0 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
[Python 3]Union Find | find-the-string-with-lcp | 0 | 1 | ```\nclass Solution:\n def findTheString(self, lcp: List[List[int]]) -> str:\n n = len(lcp) \n \n loc = list(range(n))\n \n def find(x):\n if loc[x] != x:\n loc[x] = find(loc[x])\n return loc[x]\n \n def union(x, y):\n a, b = find(x), find(y)\n if a < b:\n loc[b] = a\n else:\n loc[a] = b \n \n \n for i in range(n):\n for j in range(i+1):\n # the tricky part is that the value of lcp doesn\'t matter here, as long as > 0, just union the index, will check the value later on\n if lcp[i][j]: union(i, j) \n \n g = [find(i) for i in range(n)]\n \n\n # check if the built union-find group is valid\n # based on @lee215\'s solution\n # lcp[i][j] must equal lcp[i+1][j+1] + 1 if (i, j) shares common prefix\n for i in range(n):\n for j in range(n):\n v = lcp[i+1][j+1] if i < n - 1 and j < n - 1 else 0\n v = v + 1 if g[i] == g[j] else 0\n if v != lcp[i][j]:\n return ""\n \n # collapse grop sequence number to most smallest character index \n # for example if group number is [0, 2] then collapse to [0, 1]\n grp = set(g)\n if len(grp) > 26: return ""\n grp = {x: i for i, x in enumerate(sorted(grp))}\n \n ans = []\n for i, k in enumerate(g):\n ans.append(chr(97+grp[k])) \n \n \n return "".join(ans) | 0 | We define the `lcp` matrix of any **0-indexed** string `word` of `n` lowercase English letters as an `n x n` grid such that:
* `lcp[i][j]` is equal to the length of the **longest common prefix** between the substrings `word[i,n-1]` and `word[j,n-1]`.
Given an `n x n` matrix `lcp`, return the alphabetically smallest string `word` that corresponds to `lcp`. If there is no such string, return an empty string.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"aabd "` is lexicographically smaller than `"aaca "` because the first position they differ is at the third letter, and `'b'` comes before `'c'`.
**Example 1:**
**Input:** lcp = \[\[4,0,2,0\],\[0,3,0,1\],\[2,0,2,0\],\[0,1,0,1\]\]
**Output:** "abab "
**Explanation:** lcp corresponds to any 4 letter string with two alternating letters. The lexicographically smallest of them is "abab ".
**Example 2:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,1\]\]
**Output:** "aaaa "
**Explanation:** lcp corresponds to any 4 letter string with a single distinct letter. The lexicographically smallest of them is "aaaa ".
**Example 3:**
**Input:** lcp = \[\[4,3,2,1\],\[3,3,2,1\],\[2,2,2,1\],\[1,1,1,3\]\]
**Output:** " "
**Explanation:** lcp\[3\]\[3\] cannot be equal to 3 since word\[3,...,3\] consists of only a single letter; Thus, no answer exists.
**Constraints:**
* `1 <= n ==` `lcp.length ==` `lcp[i].length` `<= 1000`
* `0 <= lcp[i][j] <= n` | null |
Easy solution in python | left-and-right-sum-differences | 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 leftRightDifference(self, nums: List[int]) -> List[int]:\n leftsum=[]\n rightsum=[]\n res=[0]*len(nums)\n sum1=0\n for i in range(len(nums)):\n if i==0:\n leftsum.append(0)\n else:\n sum1=nums[i-1]+sum1\n leftsum.append(sum1)\n for j in range(len(nums)):\n if j==len(nums)-1:\n rightsum.append(0)\n else:\n sum2=0\n x=sum(nums[j+1:])\n rightsum.append(x)\n for k in range(len(nums)):\n res[k]=abs(leftsum[k]-rightsum[k])\n return res\n``` | 0 | Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where:
* `answer.length == nums.length`.
* `answer[i] = |leftSum[i] - rightSum[i]|`.
Where:
* `leftSum[i]` is the sum of elements to the left of the index `i` in the array `nums`. If there is no such element, `leftSum[i] = 0`.
* `rightSum[i]` is the sum of elements to the right of the index `i` in the array `nums`. If there is no such element, `rightSum[i] = 0`.
Return _the array_ `answer`.
**Example 1:**
**Input:** nums = \[10,4,8,3\]
**Output:** \[15,1,11,22\]
**Explanation:** The array leftSum is \[0,10,14,22\] and the array rightSum is \[15,11,3,0\].
The array answer is \[|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|\] = \[15,1,11,22\].
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[0\]
**Explanation:** The array leftSum is \[0\] and the array rightSum is \[0\].
The array answer is \[|0 - 0|\] = \[0\].
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 105` | null |
Easy Python Solution | left-and-right-sum-differences | 0 | 1 | \n# Code\n```\nclass Solution:\n def leftRigthDifference(self, nums: List[int]) -> List[int]:\n left, right, final =[], [], []\n nums2=nums[::-1]\n\n for i in range(len(nums)):\n if i==0:\n left.append(0)\n right.append(0)\n else:\n left.append(left[i-1]+nums[i-1])\n right.append(right[i-1]+nums2[i-1])\n right=right[::-1]\n \n for i in range(len(nums)):\n final.append(abs(left[i]-right[i]))\n return final\n``` | 2 | Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where:
* `answer.length == nums.length`.
* `answer[i] = |leftSum[i] - rightSum[i]|`.
Where:
* `leftSum[i]` is the sum of elements to the left of the index `i` in the array `nums`. If there is no such element, `leftSum[i] = 0`.
* `rightSum[i]` is the sum of elements to the right of the index `i` in the array `nums`. If there is no such element, `rightSum[i] = 0`.
Return _the array_ `answer`.
**Example 1:**
**Input:** nums = \[10,4,8,3\]
**Output:** \[15,1,11,22\]
**Explanation:** The array leftSum is \[0,10,14,22\] and the array rightSum is \[15,11,3,0\].
The array answer is \[|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|\] = \[15,1,11,22\].
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[0\]
**Explanation:** The array leftSum is \[0\] and the array rightSum is \[0\].
The array answer is \[|0 - 0|\] = \[0\].
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 105` | null |
Easy Solution | left-and-right-sum-differences | 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 leftRightDifference(self, nums: List[int]) -> List[int]:\n ans=[]\n R=sum(nums) #right sum\n L=0 #left sum\n for i in range(len(nums)):\n x=abs(L-R+nums[i]) #calculating ith index\n ans.append(x) \n R-=nums[i]\n L+=nums[i]\n\n return ans\n\n``` | 1 | Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where:
* `answer.length == nums.length`.
* `answer[i] = |leftSum[i] - rightSum[i]|`.
Where:
* `leftSum[i]` is the sum of elements to the left of the index `i` in the array `nums`. If there is no such element, `leftSum[i] = 0`.
* `rightSum[i]` is the sum of elements to the right of the index `i` in the array `nums`. If there is no such element, `rightSum[i] = 0`.
Return _the array_ `answer`.
**Example 1:**
**Input:** nums = \[10,4,8,3\]
**Output:** \[15,1,11,22\]
**Explanation:** The array leftSum is \[0,10,14,22\] and the array rightSum is \[15,11,3,0\].
The array answer is \[|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|\] = \[15,1,11,22\].
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[0\]
**Explanation:** The array leftSum is \[0\] and the array rightSum is \[0\].
The array answer is \[|0 - 0|\] = \[0\].
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 105` | null |
[Python3] prefix & suffix sum | left-and-right-sum-differences | 0 | 1 | \n```\nclass Solution:\n def leftRigthDifference(self, nums: List[int]) -> List[int]:\n prefix = 0 \n suffix = sum(nums)\n ans = []\n for x in nums: \n prefix += x\n ans.append(abs(prefix - suffix))\n suffix -= x\n return ans \n``` | 42 | Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where:
* `answer.length == nums.length`.
* `answer[i] = |leftSum[i] - rightSum[i]|`.
Where:
* `leftSum[i]` is the sum of elements to the left of the index `i` in the array `nums`. If there is no such element, `leftSum[i] = 0`.
* `rightSum[i]` is the sum of elements to the right of the index `i` in the array `nums`. If there is no such element, `rightSum[i] = 0`.
Return _the array_ `answer`.
**Example 1:**
**Input:** nums = \[10,4,8,3\]
**Output:** \[15,1,11,22\]
**Explanation:** The array leftSum is \[0,10,14,22\] and the array rightSum is \[15,11,3,0\].
The array answer is \[|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|\] = \[15,1,11,22\].
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[0\]
**Explanation:** The array leftSum is \[0\] and the array rightSum is \[0\].
The array answer is \[|0 - 0|\] = \[0\].
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 105` | null |
[ Python ] ✅✅ Simple Python Solution🥳✌👍 | left-and-right-sum-differences | 0 | 1 | \n# If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 79 ms, faster than 86.67% of Python3 online submissions for Left and Right Sum Differences.\n# Memory Usage: 14.2 MB, less than 13.33% of Python3 online submissions for Left and Right Sum Differences.\n\n\tclass Solution:\n\t\tdef leftRigthDifference(self, nums: List[int]) -> List[int]:\n\n\t\t\tresult = []\n\n\t\t\tleft_sum = [0]\n\t\t\tright_sum = [0]\n\n\t\t\tfor num in nums[:-1]:\n\t\t\t\tleft_sum.append(left_sum[-1] + num)\n\n\t\t\tfor num in nums[::-1][:-1]:\n\t\t\t\tright_sum.insert(0, right_sum[0] + num)\n\n\t\t\tfor index in range(len(nums)):\n\t\t\t\tresult.append(abs(left_sum[index] - right_sum[index]))\n\n\t\t\treturn result\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D | 3 | Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where:
* `answer.length == nums.length`.
* `answer[i] = |leftSum[i] - rightSum[i]|`.
Where:
* `leftSum[i]` is the sum of elements to the left of the index `i` in the array `nums`. If there is no such element, `leftSum[i] = 0`.
* `rightSum[i]` is the sum of elements to the right of the index `i` in the array `nums`. If there is no such element, `rightSum[i] = 0`.
Return _the array_ `answer`.
**Example 1:**
**Input:** nums = \[10,4,8,3\]
**Output:** \[15,1,11,22\]
**Explanation:** The array leftSum is \[0,10,14,22\] and the array rightSum is \[15,11,3,0\].
The array answer is \[|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|\] = \[15,1,11,22\].
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[0\]
**Explanation:** The array leftSum is \[0\] and the array rightSum is \[0\].
The array answer is \[|0 - 0|\] = \[0\].
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 105` | null |
✅Python3 || C++ || Java✅ prevSum O(1) | left-and-right-sum-differences | 1 | 1 | # Please UPVOTE\uD83D\uDE0A\n\n# Python3\n```\nclass Solution:\n def leftRigthDifference(self, nums: List[int]) -> List[int]:\n ans=[0]\n for i in nums: ans+=[ans[-1]+i]\n a=[]\n for i in range(1,len(ans)):\n a+=[abs(ans[-1]-ans[i]-ans[i-1])] \n return a\n \n```\n# C++\n```\nclass Solution {\npublic:\n vector<int> leftRigthDifference(vector<int>& nums) {\n vector<int>ans,a;\n a.push_back(0);\n for(int i=0;i<nums.size();i++) a.push_back(a.back()+nums[i]);\n for(int i=1;i<a.size();i++) ans.push_back(abs(a[nums.size()]-a[i]-a[i-1]));\n return ans;\n }\n};\n```\n# Java\n```\nclass Solution {\n public int[] leftRigthDifference(int[] nums) {\n long x=0;\n int n=nums.length;\n int[] ans = new int[n];\n int[] a = new int[n+1];\n a[0]=0;\n for(int i=0;i<nums.length;i++)\n {\n a[i+1]=a[i]+nums[i];\n }\n for(int i=1;i<n+1;i++) ans[i-1]=Math.abs(a[n]-a[i]-a[i-1]);\n return ans;\n }\n}\n```\n | 30 | Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where:
* `answer.length == nums.length`.
* `answer[i] = |leftSum[i] - rightSum[i]|`.
Where:
* `leftSum[i]` is the sum of elements to the left of the index `i` in the array `nums`. If there is no such element, `leftSum[i] = 0`.
* `rightSum[i]` is the sum of elements to the right of the index `i` in the array `nums`. If there is no such element, `rightSum[i] = 0`.
Return _the array_ `answer`.
**Example 1:**
**Input:** nums = \[10,4,8,3\]
**Output:** \[15,1,11,22\]
**Explanation:** The array leftSum is \[0,10,14,22\] and the array rightSum is \[15,11,3,0\].
The array answer is \[|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|\] = \[15,1,11,22\].
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[0\]
**Explanation:** The array leftSum is \[0\] and the array rightSum is \[0\].
The array answer is \[|0 - 0|\] = \[0\].
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 105` | null |
Very easy solution python | left-and-right-sum-differences | 0 | 1 | # Using Accumulate Cooncept\n\n# Code\n```\nclass Solution:\n def leftRightDifference(self, nums: List[int]) -> List[int]:\n left=list(accumulate(nums,initial=0))\n right=list(accumulate(nums[::-1],initial=0))[:-1][::-1]\n for i in range(len(nums)):\n nums[i]=abs(left[i]-right[i])\n return nums\n``` | 1 | Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where:
* `answer.length == nums.length`.
* `answer[i] = |leftSum[i] - rightSum[i]|`.
Where:
* `leftSum[i]` is the sum of elements to the left of the index `i` in the array `nums`. If there is no such element, `leftSum[i] = 0`.
* `rightSum[i]` is the sum of elements to the right of the index `i` in the array `nums`. If there is no such element, `rightSum[i] = 0`.
Return _the array_ `answer`.
**Example 1:**
**Input:** nums = \[10,4,8,3\]
**Output:** \[15,1,11,22\]
**Explanation:** The array leftSum is \[0,10,14,22\] and the array rightSum is \[15,11,3,0\].
The array answer is \[|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|\] = \[15,1,11,22\].
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[0\]
**Explanation:** The array leftSum is \[0\] and the array rightSum is \[0\].
The array answer is \[|0 - 0|\] = \[0\].
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 105` | null |
Very EASY SOLUTION | left-and-right-sum-differences | 0 | 1 | >\n\n# Code\n```\nclass Solution:\n def leftRigthDifference(self, nums: List[int]) -> List[int]:\n res = []\n\n for i in range(len(nums)):\n res.append(abs(sum(nums[0:i])-sum(nums[i+1:])))\n\n return res\n``` | 1 | Given a **0-indexed** integer array `nums`, find a **0-indexed** integer array `answer` where:
* `answer.length == nums.length`.
* `answer[i] = |leftSum[i] - rightSum[i]|`.
Where:
* `leftSum[i]` is the sum of elements to the left of the index `i` in the array `nums`. If there is no such element, `leftSum[i] = 0`.
* `rightSum[i]` is the sum of elements to the right of the index `i` in the array `nums`. If there is no such element, `rightSum[i] = 0`.
Return _the array_ `answer`.
**Example 1:**
**Input:** nums = \[10,4,8,3\]
**Output:** \[15,1,11,22\]
**Explanation:** The array leftSum is \[0,10,14,22\] and the array rightSum is \[15,11,3,0\].
The array answer is \[|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|\] = \[15,1,11,22\].
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[0\]
**Explanation:** The array leftSum is \[0\] and the array rightSum is \[0\].
The array answer is \[|0 - 0|\] = \[0\].
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 105` | null |
2575. Find the Divisibility Array of a String - Python Easy approach | find-the-divisibility-array-of-a-string | 0 | 1 | # Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def divisibilityArray(self, word: str, m: int) -> List[int]:\n l = []\n rem = 0\n for i in word:\n rem = (rem * 10 +int(i))%m \n if rem%m==0:\n l.append(1)\n else:\n l.append(0)\n return l\n \n```\n | 1 | You are given a **0-indexed** string `word` of length `n` consisting of digits, and a positive integer `m`.
The **divisibility array** `div` of `word` is an integer array of length `n` such that:
* `div[i] = 1` if the **numeric value** of `word[0,...,i]` is divisible by `m`, or
* `div[i] = 0` otherwise.
Return _the divisibility array of_ `word`.
**Example 1:**
**Input:** word = "998244353 ", m = 3
**Output:** \[1,1,0,0,0,1,1,0,0\]
**Explanation:** There are only 4 prefixes that are divisible by 3: "9 ", "99 ", "998244 ", and "9982443 ".
**Example 2:**
**Input:** word = "1010 ", m = 10
**Output:** \[0,1,0,1\]
**Explanation:** There are only 2 prefixes that are divisible by 10: "10 ", and "1010 ".
**Constraints:**
* `1 <= n <= 105`
* `word.length == n`
* `word` consists of digits from `0` to `9`
* `1 <= m <= 109` | null |
[ Python ] ✅✅ Simple Python Solution🥳✌👍 | find-the-divisibility-array-of-a-string | 0 | 1 | # If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDD3C\uD83D\uDE4F\n# Runtime: 570 ms, faster than 37.50% of Python3 online submissions for Find the Divisibility Array of a String.\n# Memory Usage: 23.7 MB, less than 12.50% of Python3 online submissions for Find the Divisibility Array of a String.\n\n\tclass Solution:\n\t\tdef divisibilityArray(self, word: str, m: int) -> List[int]:\n\n\t\t\tresult = [0 for _ in range(len(word))]\n\n\t\t\tcurrent_num = 0\n\n\t\t\tfor index in range(len(word)):\n\n\t\t\t\tcurrent_num = (current_num * 10 + (int(word[index]))) % m\n\n\t\t\t\tif current_num == 0:\n\t\t\t\t\tresult[index] = 1\n\n\t\t\treturn result\n\n# Thank You \uD83E\uDD73\u270C\uD83D\uDC4D | 1 | You are given a **0-indexed** string `word` of length `n` consisting of digits, and a positive integer `m`.
The **divisibility array** `div` of `word` is an integer array of length `n` such that:
* `div[i] = 1` if the **numeric value** of `word[0,...,i]` is divisible by `m`, or
* `div[i] = 0` otherwise.
Return _the divisibility array of_ `word`.
**Example 1:**
**Input:** word = "998244353 ", m = 3
**Output:** \[1,1,0,0,0,1,1,0,0\]
**Explanation:** There are only 4 prefixes that are divisible by 3: "9 ", "99 ", "998244 ", and "9982443 ".
**Example 2:**
**Input:** word = "1010 ", m = 10
**Output:** \[0,1,0,1\]
**Explanation:** There are only 2 prefixes that are divisible by 10: "10 ", and "1010 ".
**Constraints:**
* `1 <= n <= 105`
* `word.length == n`
* `word` consists of digits from `0` to `9`
* `1 <= m <= 109` | null |
[Python3] Very Simple MOD Solution | find-the-divisibility-array-of-a-string | 0 | 1 | # Code\n```\nclass Solution:\n def divisibilityArray(self, word: str, m: int) -> List[int]:\n N = len(word)\n ans = [0]*N\n cur = 0\n for i in range(N):\n cur *= 10\n cur += int(word[i])\n \n if cur%m==0:\n ans[i] = 1\n \n cur%=m\n \n return ans\n``` | 1 | You are given a **0-indexed** string `word` of length `n` consisting of digits, and a positive integer `m`.
The **divisibility array** `div` of `word` is an integer array of length `n` such that:
* `div[i] = 1` if the **numeric value** of `word[0,...,i]` is divisible by `m`, or
* `div[i] = 0` otherwise.
Return _the divisibility array of_ `word`.
**Example 1:**
**Input:** word = "998244353 ", m = 3
**Output:** \[1,1,0,0,0,1,1,0,0\]
**Explanation:** There are only 4 prefixes that are divisible by 3: "9 ", "99 ", "998244 ", and "9982443 ".
**Example 2:**
**Input:** word = "1010 ", m = 10
**Output:** \[0,1,0,1\]
**Explanation:** There are only 2 prefixes that are divisible by 10: "10 ", and "1010 ".
**Constraints:**
* `1 <= n <= 105`
* `word.length == n`
* `word` consists of digits from `0` to `9`
* `1 <= m <= 109` | null |
[Python3] prefix modulo sum | find-the-divisibility-array-of-a-string | 0 | 1 | \n```\nclass Solution:\n def divisibilityArray(self, word: str, m: int) -> List[int]:\n ans = []\n prefix = 0 \n for i, x in enumerate(word): \n prefix = 10*prefix + ord(x) - 48\n prefix %= m \n if prefix == 0: ans.append(1)\n else: ans.append(0)\n return ans \n``` | 7 | You are given a **0-indexed** string `word` of length `n` consisting of digits, and a positive integer `m`.
The **divisibility array** `div` of `word` is an integer array of length `n` such that:
* `div[i] = 1` if the **numeric value** of `word[0,...,i]` is divisible by `m`, or
* `div[i] = 0` otherwise.
Return _the divisibility array of_ `word`.
**Example 1:**
**Input:** word = "998244353 ", m = 3
**Output:** \[1,1,0,0,0,1,1,0,0\]
**Explanation:** There are only 4 prefixes that are divisible by 3: "9 ", "99 ", "998244 ", and "9982443 ".
**Example 2:**
**Input:** word = "1010 ", m = 10
**Output:** \[0,1,0,1\]
**Explanation:** There are only 2 prefixes that are divisible by 10: "10 ", and "1010 ".
**Constraints:**
* `1 <= n <= 105`
* `word.length == n`
* `word` consists of digits from `0` to `9`
* `1 <= m <= 109` | null |
✅Python3 || C++ || Java✅ Easy solution | find-the-divisibility-array-of-a-string | 1 | 1 | # Please UPVOTE\uD83D\uDE0A\n\n# Python3\n```\nclass Solution:\n def divisibilityArray(self, word: str, m: int) -> List[int]:\n x=0\n a=[]\n for i in word:\n x=x*10+int(i)\n if(x%m==0):\n a+=[1]\n else:\n a+=[0]\n x%=m\n return a\n \n```\n# C++\n```\nclass Solution {\npublic:\n vector<int> divisibilityArray(string word, int m) {\n long long int x=0;\n vector<int>ans;\n for(int i=0;i<word.size();i++)\n {\n x=x*10+(word[i]-\'0\');\n if(x%m==0) ans.push_back(1);else ans.push_back(0);\n x%=m;\n }\n return ans;\n }\n};\n```\n# Java\n```\nclass Solution {\n public int[] divisibilityArray(String word, int m) {\n long x=0;\n int n=word.length();\n int[] ans = new int[n];\n for(int i=0;i<word.length();i++)\n {\n x=x*10+(word.charAt(i)-\'0\');\n if(x%m==0) ans[i]=1;else ans[i]=0;\n x%=m;\n }\n return ans;\n }\n}\n```\n | 40 | You are given a **0-indexed** string `word` of length `n` consisting of digits, and a positive integer `m`.
The **divisibility array** `div` of `word` is an integer array of length `n` such that:
* `div[i] = 1` if the **numeric value** of `word[0,...,i]` is divisible by `m`, or
* `div[i] = 0` otherwise.
Return _the divisibility array of_ `word`.
**Example 1:**
**Input:** word = "998244353 ", m = 3
**Output:** \[1,1,0,0,0,1,1,0,0\]
**Explanation:** There are only 4 prefixes that are divisible by 3: "9 ", "99 ", "998244 ", and "9982443 ".
**Example 2:**
**Input:** word = "1010 ", m = 10
**Output:** \[0,1,0,1\]
**Explanation:** There are only 2 prefixes that are divisible by 10: "10 ", and "1010 ".
**Constraints:**
* `1 <= n <= 105`
* `word.length == n`
* `word` consists of digits from `0` to `9`
* `1 <= m <= 109` | null |
Python || Naive and Fast Approach || Mod of a Big Number. | find-the-divisibility-array-of-a-string | 0 | 1 | ## Naive solution. TLE\nDerive the number from string and check if divisble, just as described in the question. TLE due to large modulo operations.\n```\nclass Solution:\n def divisibilityArray(self, word: str, m: int) -> List[int]:\n num = int(word[0])\n div = [1 if num % m == 0 else 0]\n\n for i in range(1, len(word)):\n num = int(word[0: i + 1])\n div.append(1 if num % m == 0 else 0)\n return div\n```\n\n## Faster solution. No TLE\nUsing the mathematical property that\n`ab (mod m) \u2261 ((a (mod m) * 10) + (b (mod m))) mod m`\nWe can compute and store the mod of current digit and use it for the next digit. No TLE due to small modulo operations.\n\n```\nclass Solution:\n def divisibilityArray(self, word: str, m: int) -> List[int]:\n mod = 0\n div = []\n\n for i in range(0, len(word)):\n mod = (mod * 10 + int(word[i])) % m\n div.append(1 if mod % m == 0 else 0)\n return div\n``` | 6 | You are given a **0-indexed** string `word` of length `n` consisting of digits, and a positive integer `m`.
The **divisibility array** `div` of `word` is an integer array of length `n` such that:
* `div[i] = 1` if the **numeric value** of `word[0,...,i]` is divisible by `m`, or
* `div[i] = 0` otherwise.
Return _the divisibility array of_ `word`.
**Example 1:**
**Input:** word = "998244353 ", m = 3
**Output:** \[1,1,0,0,0,1,1,0,0\]
**Explanation:** There are only 4 prefixes that are divisible by 3: "9 ", "99 ", "998244 ", and "9982443 ".
**Example 2:**
**Input:** word = "1010 ", m = 10
**Output:** \[0,1,0,1\]
**Explanation:** There are only 2 prefixes that are divisible by 10: "10 ", and "1010 ".
**Constraints:**
* `1 <= n <= 105`
* `word.length == n`
* `word` consists of digits from `0` to `9`
* `1 <= m <= 109` | null |
Python | O(n) | find-the-divisibility-array-of-a-string | 0 | 1 | # Approach\n- We will keep track of remainder till `ith` index.\n- If `rem % m == 0` the add 1, otherwise 0.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def divisibilityArray(self, word: str, m: int) -> List[int]:\n ans = []\n n = 0\n for i in word:\n n = (n*10+int(i))%m\n if n==0:\n ans.append(1)\n else:\n ans.append(0)\n return ans\n \n```\n---------------\n**Upvote the post if you find it helpful.\nHappy coding.** | 2 | You are given a **0-indexed** string `word` of length `n` consisting of digits, and a positive integer `m`.
The **divisibility array** `div` of `word` is an integer array of length `n` such that:
* `div[i] = 1` if the **numeric value** of `word[0,...,i]` is divisible by `m`, or
* `div[i] = 0` otherwise.
Return _the divisibility array of_ `word`.
**Example 1:**
**Input:** word = "998244353 ", m = 3
**Output:** \[1,1,0,0,0,1,1,0,0\]
**Explanation:** There are only 4 prefixes that are divisible by 3: "9 ", "99 ", "998244 ", and "9982443 ".
**Example 2:**
**Input:** word = "1010 ", m = 10
**Output:** \[0,1,0,1\]
**Explanation:** There are only 2 prefixes that are divisible by 10: "10 ", and "1010 ".
**Constraints:**
* `1 <= n <= 105`
* `word.length == n`
* `word` consists of digits from `0` to `9`
* `1 <= m <= 109` | null |
pure bfs, no heap, max(grid[i][j])+mn | minimum-time-to-visit-a-cell-in-a-grid | 0 | 1 | # Approach\n1) as regular BFS, move 1 level at a time and record adjacent cells as new level\n2) the difference is, if `adjacent cell\'s required time > current time + 1`, meaning we need to move back-and-forth to reach this cell, so put them in future level to be processed\n3) for 2), one caveat is that when steps between adjacent cell\'s time and current time is odd, it can move back-and-forth till exact adjacent cell time to reach it,\nbut when it is even, it need 1 extra move to reach the adjacent cell\n\ne.g. \n```\nt=0 t[5] = (1,0)\n 0 1 2 3\n0[0*,1a,3 ,2 ]\n1[5f,1 ,2 ,5 ]\n2[4 ,3 ,8 ,6 ]\n\nt=1 t[4] = (2,2)\n 0 1 2 3 t[5] = (1,0)\n0[0-,1*,3f,2 ]\n1[5f,1a,2 ,5 ]\n2[4 ,3 ,8 ,6 ]\n\nt=2 t[4] = (2,2)\n 0 1 2 3 t[5] = (1,0)\n0[0-,1-,3f,2 ]\n1[5f,1*,2a,5 ]\n2[4 ,3a,8 ,6 ]\n\nt=3 t[4] = (2,2)\n 0 1 2 3 t[5] = (1,0)\n0[0-,1-,3f,2 ] t[6] = (1,3)\n1[5f,1-,2*,5f] t[8] = (2,2)\n2[4a,3*,8f,6 ]\n\nt=4 t[5] = (1,0)\n 0 1 2 3 t[6] = (1,3)\n0[0-,1-,3*,2a] t[8] = (2,2)\n1[5f,1-,2-,5f]\n2[4*,3-,8f,6 ]\n\nt=5 \n 0 1 2 3 t[6] = (1,3)\n0[0-,1-,3-,2*] t[8] = (2,2)\n1[5*,1-,2-,5f]\n2[4-,3-,8f,6 ]\n\nt=6 \n 0 1 2 3 \n0[0-,1-,3-,2-] t[8] = (2,2)\n1[5-,1-,2-,5*]\n2[4-,3-,8f,6a]\n\nt=7 \n 0 1 2 3 \n0[0-,1-,3-,2-] t[8] = (2,2)\n1[5-,1-,2-,5-]\n2[4-,3-,8f,6*]\n```\n\n# Complexity\n- Time complexity: O(max(grid[i][j])+mn)\n- Space complexity: O(m*n)\n\n\n# Code\n```python\nclass Solution:\n def minimumTime(self, grid: List[List[int]]) -> int:\n R, C = 0, 1\n nr, nc = len(grid), len(grid[0])\n\n def get_nx(r, c):\n for r_nx, c_nx in ((r+1,c),(r-1,c),(r,c+1),(r,c-1)):\n if 0 <= r_nx <= nr-1 and 0 <= c_nx <= nc-1:\n yield r_nx, c_nx\n\n # main\n if grid[0][1] > 1 and grid[1][0] > 1:\n return -1\n start, end = (0, 0), (nr-1, nc-1)\n t_to_cells = defaultdict(set)\n t = 0\n t_to_cells[t].add(start)\n visited = {start}\n while True:\n for r, c in t_to_cells[t]:\n for r_nx, c_nx in get_nx(r, c):\n if (r_nx, c_nx) in visited:\n continue\n if grid[r_nx][c_nx] > t+1:\n t_diff = grid[r_nx][c_nx] - t\n t_nx = t + t_diff if t_diff % 2 == 1 else t + t_diff + 1\n else:\n t_nx = t+1\n if (r_nx, c_nx) == end:\n return t_nx\n t_to_cells[t_nx].add((r_nx, c_nx))\n visited.add((r_nx, c_nx))\n t += 1\n\n``` | 5 | You are given a `m x n` matrix `grid` consisting of **non-negative** integers where `grid[row][col]` represents the **minimum** time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the time you visit it is greater than or equal to `grid[row][col]`.
You are standing in the **top-left** cell of the matrix in the `0th` second, and you must move to **any** adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return _the **minimum** time required in which you can visit the bottom-right cell of the matrix_. If you cannot visit the bottom-right cell, then return `-1`.
**Example 1:**
**Input:** grid = \[\[0,1,3,2\],\[5,1,2,5\],\[4,3,8,6\]\]
**Output:** 7
**Explanation:** One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid\[0\]\[1\] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid\[1\]\[3\] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid\[2\]\[3\] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
**Example 2:**
**Input:** grid = \[\[0,2,4\],\[3,2,1\],\[1,0,4\]\]
**Output:** -1
**Explanation:** There is no path from the top left to the bottom-right cell.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `0 <= grid[i][j] <= 105`
* `grid[0][0] == 0`
.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;} | null |
[C++, Java, Python] 🏓 Ping Pong Dijkstra | minimum-time-to-visit-a-cell-in-a-grid | 1 | 1 | \n# Intuition\nWe want to find minimum time to reach bottom right cell. We\'ll have to traverse the matrix as the time in each cell allows. We can use a priority queue to keep track of time.\nSome things to keep in mind:\n1. If we can not move to the neighboring cells from starting position we can not move anywhere in the matrix hence answer is -1. \n2. But if we can move to the neighboring cells from starting position, we can move anywhere in the matrix. We can wait by playing "ping pong" between previous cell and current cell till a neighboring cell opens up.\n\n\n# Approach\n* If `grid[0][1] > 1 and grid[1][0] > 1` we can not move anywhere from cell `grid[0][0]` hence answer is `-1`\n* Use priority queue to find next cell with minimum time to move to it\n* If time for a neighbor (target) cell is > 1 + time for current cell. We can not directly move to target cell. We will have to "ping pong" between previous cell and current cell. When playing ping pong between previous and current cell there can be two cases. \n * Let\'s say time for target cell is 4 and current time is 2, difference = 2 (even).\n * Move to prev cell, time = 3\n * Move to curr cell, time = 4\n * Move to target cell, time = 5. \n * Hence we reach target cell with time: **target cell time + 1** when difference between target cell time and curr cell time is even.\n * Let\'s say time for target cell is 5 and current time is 2, difference = 3 (odd).\n * Move to prev cell, time = 3\n * Move to curr cell, time = 4\n * Move to target cell, time = 5. \n * Hence we reach target cell with time: target cell time when difference between target cell time and curr cell time is odd.\n * This "ping pong" is captured in the `wait` variable in the code\n\n\n# Complexity\n- Time complexity: `O(mnlog(mn))`\n\n- Space complexity: `O(mn)`\n\n# Code\n**Python3**:\n```\ndef minimumTime(self, grid: List[List[int]]) -> int:\n if grid[0][1] > 1 and grid[1][0] > 1: return -1\n m, n = len(grid), len(grid[0])\n visited = set()\n pq = [(grid[0][0], 0, 0)]\n \n while pq:\n time, row, col = heappop(pq)\n if row == m-1 and col == n-1: return time\n if (row, col) in visited: continue\n visited.add((row, col))\n for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:\n r, c = row + dr, col + dc\n if 0 <= r < m and 0 <= c < n and (r, c) not in visited:\n wait = 1 if ((grid[r][c] - time) % 2 == 0) else 0\n heappush(pq, (max(time + 1, grid[r][c] + wait), r, c))\n```\n\n**C++**\n```\nint minimumTime(vector<vector<int>>& grid) {\n // Check if the starting points are blocked\n if (grid[0][1] > 1 && grid[1][0] > 1) return -1;\n \n int m = grid.size(), n = grid[0].size();\n vector<vector<int>> dirs{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n vector<vector<bool>> visited(m, vector<bool>(n, false));\n priority_queue<vector<int>, vector<vector<int>>, greater<>> pq;\n \n pq.push({grid[0][0], 0, 0}); // Start at top-left corner\n while (!pq.empty()) {\n // Get the current time, row, and column\n int time = pq.top()[0], row = pq.top()[1], col = pq.top()[2];\n pq.pop();\n \n // Check if we\'ve reached the bottom-right corner\n if (row == m - 1 && col == n - 1) return time;\n \n // Mark the current cell as visited\n if (visited[row][col]) continue;\n visited[row][col] = true;\n \n // Explore the neighboring cells\n for (auto dr: dirs) {\n int r = row + dr[0], c = col + dr[1];\n if (r < 0 || r >= m || c < 0 || c >= n || visited[r][c]) continue;\n \n // Calculate the time required to reach the neighboring cell\n int wait = (grid[r][c] - time) % 2 == 0;\n pq.push({max(grid[r][c] + wait, time + 1), r, c});\n }\n }\n return -1; // We couldn\'t reach the bottom-right corner. \n // We will never actually encounter this in practice.\n}\n```\n\n**Java**:\n```\npublic int minimumTime(int[][] grid) {\n if (grid[0][1] > 1 && grid[1][0] > 1) return -1;\n \n int m = grid.length, n = grid[0].length;\n int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n boolean[][] visited = new boolean[m][n];\n PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));\n pq.offer(new int[]{grid[0][0], 0, 0});\n \n while (!pq.isEmpty()) {\n int[] curr = pq.poll();\n int time = curr[0], row = curr[1], col = curr[2];\n \n if (row == m - 1 && col == n - 1) return time;\n if (visited[row][col]) continue;\n visited[row][col] = true;\n \n for (int[] dir : dirs) {\n int r = row + dir[0], c = col + dir[1];\n if (r < 0 || r >= m || c < 0 || c >= n || visited[r][c]) continue;\n int wait = ((grid[r][c] - time) % 2 == 0) ? 1 : 0;\n pq.offer(new int[]{Math.max(grid[r][c] + wait, time + 1), r, c});\n }\n }\n return -1;\n}\n``` | 148 | You are given a `m x n` matrix `grid` consisting of **non-negative** integers where `grid[row][col]` represents the **minimum** time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the time you visit it is greater than or equal to `grid[row][col]`.
You are standing in the **top-left** cell of the matrix in the `0th` second, and you must move to **any** adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return _the **minimum** time required in which you can visit the bottom-right cell of the matrix_. If you cannot visit the bottom-right cell, then return `-1`.
**Example 1:**
**Input:** grid = \[\[0,1,3,2\],\[5,1,2,5\],\[4,3,8,6\]\]
**Output:** 7
**Explanation:** One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid\[0\]\[1\] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid\[1\]\[3\] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid\[2\]\[3\] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
**Example 2:**
**Input:** grid = \[\[0,2,4\],\[3,2,1\],\[1,0,4\]\]
**Output:** -1
**Explanation:** There is no path from the top left to the bottom-right cell.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `0 <= grid[i][j] <= 105`
* `grid[0][0] == 0`
.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;} | null |
[Python/C++] clean Dijkstra's algorithm solution with explanation | minimum-time-to-visit-a-cell-in-a-grid | 0 | 1 | **Explaination**\n\nThis problem can be solved using the Dijkstra\'s algorithm with a small variation.\n\nFirstly, note that we can always reach the bottom-right cell of the matrix if we can move to at least one adjacent cell (i.e. `grid[0][1]` or `grid[1][0]`). After that, we can simply move back and forth to spend time as needed.\n\nIt\'s also worth noting that we may not always be able to move to an adjacent cell immediately. For example, in Example 1, we have to step back to cell (1,1) before moving to cell (1,3) because we must move every second.\n\nSince it takes an even number of seconds to "stand still" when moving back and forth, we need to wait for an extra second if we want to move after an odd number of seconds\n\nAfter accounting for these factors, we can use the standard Dijkstra\'s algorithm to find the answer.\n\n<br/>\n\n**Complexity**\n\nTime complexity: `O(MNlog(MN))`\nSpace complexity: `O(MN)`\n\n<br/>\n\n**Python**\n```Python\nclass Solution:\n def minimumTime(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n if grid[0][1] > 1 and grid[1][0] > 1:\n return -1\n visited = [[False] * n for _ in range(m)]\n heap = [(0, 0, 0)] # (t, r, c)\n while heap:\n t, r, c = heapq.heappop(heap)\n if r == m - 1 and c == n - 1:\n return t\n if visited[r][c]:\n continue\n visited[r][c] = True\n for dr, dc in ((0, 1), (0, -1), (1, 0), (-1, 0)):\n nr, nc = r + dr, c + dc\n if nr < 0 or nr >= m or nc < 0 or nc >= n or visited[nr][nc]:\n continue\n wait = (grid[nr][nc] - t) % 2 == 0\n nt = max(grid[nr][nc] + wait, t + 1)\n heapq.heappush(heap, (nt, nr, nc))\n return -1\n```\n\n<br/>\n\n**C++**\n```cpp\nclass Solution {\npublic:\n int minimumTime(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n if (grid[0][1] > 1 && grid[1][0] > 1) {\n return -1;\n }\n vector<vector<int>> directions{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n vector<vector<bool>> visited(m, vector<bool>(n, false));\n priority_queue<vector<int>, vector<vector<int>>, greater<>> pq;\n pq.push({0, 0, 0}); // (t, r, c)\n while (!pq.empty()) {\n auto cur = pq.top();\n int t = cur[0], r = cur[1], c = cur[2];\n pq.pop();\n if (r == m - 1 && c == n - 1) {\n return t;\n }\n if (visited[r][c]) {\n continue;\n }\n visited[r][c] = true;\n for (const auto& dir : directions) {\n int nr = r + dir[0], nc = c + dir[1];\n if (nr < 0 || nr >= m || nc < 0 || nc >= n || visited[nr][nc]) {\n continue;\n }\n bool wait = (grid[nr][nc] - t) % 2 == 0;\n int nt = max(grid[nr][nc] + wait, t + 1);\n pq.push({nt, nr, nc});\n }\n }\n return -1;\n }\n};\n``` | 34 | You are given a `m x n` matrix `grid` consisting of **non-negative** integers where `grid[row][col]` represents the **minimum** time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the time you visit it is greater than or equal to `grid[row][col]`.
You are standing in the **top-left** cell of the matrix in the `0th` second, and you must move to **any** adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return _the **minimum** time required in which you can visit the bottom-right cell of the matrix_. If you cannot visit the bottom-right cell, then return `-1`.
**Example 1:**
**Input:** grid = \[\[0,1,3,2\],\[5,1,2,5\],\[4,3,8,6\]\]
**Output:** 7
**Explanation:** One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid\[0\]\[1\] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid\[1\]\[3\] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid\[2\]\[3\] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
**Example 2:**
**Input:** grid = \[\[0,2,4\],\[3,2,1\],\[1,0,4\]\]
**Output:** -1
**Explanation:** There is no path from the top left to the bottom-right cell.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `0 <= grid[i][j] <= 105`
* `grid[0][0] == 0`
.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;} | null |
Python | Dijkstra | Simple Solution | minimum-time-to-visit-a-cell-in-a-grid | 0 | 1 | # Code\n```\nfrom heapq import heappush, heappop\nclass Solution:\n def minimumTime(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n if grid[0][1] > 1 and grid[1][0] > 1: \n return -1\n heap = [(0,0,0)]\n visited = set()\n while heap:\n d, i, j = heappop(heap)\n if (i, j) in visited: continue\n visited.add((i,j))\n if (i, j) == (m-1, n-1): return d\n for di, dj in [[-1,0], [1,0], [0,-1], [0,1]]:\n if 0 <= i + di < m and 0 <= j + dj < n and (i + di, j + dj) not in visited:\n t = grid[i+di][j+dj]\n gap = max(t-(d+1), 0)\n heappush(heap, (d + 1 + gap + (gap%2), i + di, j + dj))\n``` | 5 | You are given a `m x n` matrix `grid` consisting of **non-negative** integers where `grid[row][col]` represents the **minimum** time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the time you visit it is greater than or equal to `grid[row][col]`.
You are standing in the **top-left** cell of the matrix in the `0th` second, and you must move to **any** adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return _the **minimum** time required in which you can visit the bottom-right cell of the matrix_. If you cannot visit the bottom-right cell, then return `-1`.
**Example 1:**
**Input:** grid = \[\[0,1,3,2\],\[5,1,2,5\],\[4,3,8,6\]\]
**Output:** 7
**Explanation:** One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid\[0\]\[1\] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid\[1\]\[3\] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid\[2\]\[3\] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
**Example 2:**
**Input:** grid = \[\[0,2,4\],\[3,2,1\],\[1,0,4\]\]
**Output:** -1
**Explanation:** There is no path from the top left to the bottom-right cell.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `0 <= grid[i][j] <= 105`
* `grid[0][0] == 0`
.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;} | null |
[Python3] Modified Dijkstra. Detailed Solution. | minimum-time-to-visit-a-cell-in-a-grid | 0 | 1 | # Intuition\nDijkstra algorithm should always be considered first in shortest time/path questions.\n\n# Approach\nFirst observation:\nIf ```grid[0][1] <= 1``` or ```grid[1][0] <= 1```, then you can always reach the bottom right position because you can jump back and forth between the starting point ```(0, 0)``` and its neighbour.\n\nSecond observation:\nFor each position ```(r, c)```, you can visit it either at odd time or at even time, you won\'t be able to visit ```(r, c)``` at both an odd time and an even time. This is because if you jump out and jump in, it will take `2` seconds, so the time you can visit a cell should be `t`, `t + 2`, `t + 4`, ..., where all of them are all even or all odd, depends on whether `t` is even or not.\n\nFinally:\nIt\'s just the standard Dijkstra\'s algorithm, when you are about to visit a new cell `(r + dr, c + dc)`, assume the current time is `t`\n- if `t + 1` and `grid[r + dr][c + dc]` are of the same parity (e.g. both odd or both even), then earliest time you can visit `(r + dr, c + dc)` is either `t + 1` or `grid[r][c]`. \n- if `t + 1` and `grid[r + dr][c + dc]` are of different parity, then earliest time you can visit `(r + dr, c + dc)` is either `t + 1` or `grid[r][c] + 1`. Notice that we have `+1` here so that after that, `t + 1` and `grid[r][c] + 1` will have the same parity. \n\n# Complexity\n- Time complexity:\n$$O(mn log(mn))$$. Recall that for a standard Dijkstra algorithm, the time complexity is $$O((|V| + |E|) log V)$$, in our case, both $|V|$ and $|E|$ are $$O(mn)$$.\n\n- Space complexity:\n$$O(mn)$$. Recall that for a standard Dijkstra algorithm, the space complexity is $$O(|V| + |E|)$$, in our case, both $|V|$ and $|E|$ are $$O(mn)$$.\n\n# Code\n```\nclass Solution:\n def minimumTime(self, grid: List[List[int]]) -> int:\n if grid[0][1] > 1 and grid[1][0] > 1:\n return -1\n\n m, n = len(grid), len(grid[0])\n heap = [(0, 0, 0)]\n min_time = [[inf] * n for _ in range(m)]\n min_time[0][0] = 0\n \n while heap:\n curr_time, r, c = heappop(heap)\n for dr, dc in [[-1, 0], [1, 0], [0, -1], [0, 1]]:\n if 0 <= r + dr < m and 0 <= c + dc < n:\n if curr_time + 1 >= min_time[r + dr][c + dc]:\n continue\n else:\n if (curr_time + 1 - grid[r + dr][c + dc]) % 2 == 0:\n min_time[r + dr][c + dc] = max(curr_time + 1, grid[r + dr][c + dc])\n else:\n min_time[r + dr][c + dc] = max(curr_time + 1, grid[r + dr][c + dc] + 1)\n heappush(heap, (min_time[r + dr][c + dc], r + dr, c + dc))\n return min_time[-1][-1]\n``` | 9 | You are given a `m x n` matrix `grid` consisting of **non-negative** integers where `grid[row][col]` represents the **minimum** time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the time you visit it is greater than or equal to `grid[row][col]`.
You are standing in the **top-left** cell of the matrix in the `0th` second, and you must move to **any** adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return _the **minimum** time required in which you can visit the bottom-right cell of the matrix_. If you cannot visit the bottom-right cell, then return `-1`.
**Example 1:**
**Input:** grid = \[\[0,1,3,2\],\[5,1,2,5\],\[4,3,8,6\]\]
**Output:** 7
**Explanation:** One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid\[0\]\[1\] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid\[1\]\[3\] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid\[2\]\[3\] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
**Example 2:**
**Input:** grid = \[\[0,2,4\],\[3,2,1\],\[1,0,4\]\]
**Output:** -1
**Explanation:** There is no path from the top left to the bottom-right cell.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `0 <= grid[i][j] <= 105`
* `grid[0][0] == 0`
.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;} | null |
Python || Dijkstra Variant || Explained | minimum-time-to-visit-a-cell-in-a-grid | 0 | 1 | There is only one case where we can\'t reach last cell , i.e. when all cells adjacent to (0,0) are greater than 1.\nOtherwise we can always keep switching between current cell and the last visited cell to pass the time.\nNow when we are moving from one cell to its adjacent cell -\n1) if the difference between grid value of new cell and current cost is odd and grid value is greater than cost then we can move to new cell with it\'s required grid value.\n2) otherwise if difference is even and new cell grid value is greater than cost then we can only reach it by grid value+1 (since we will need 1 extra move while swtiching between current and previously visited cell).\n3) If grid value of new cell is less than or equal to current cost then we can always move to new cell with new_cost=cost+1 (This is normal bfs move) .\n\nTime Complexity - O(m* n * log (m* n))\n\nCode : \n```\nclass Solution:\n def minimumTime(self, grid: List[List[int]]) -> int:\n m,n=len(grid),len(grid[0])\n directions=((0,1),(1,0),(-1,0),(0,-1))\n i,j,flag=0,0,0\n for di,dj in directions:\n ni,nj=i+di,j+dj\n if 0<=ni<m and 0<=nj<n and grid[ni][nj]<=1: flag=1;break;\n if not flag: return -1\n heap=[]\n heappush(heap,(0,0,0))\n dist=[[sys.maxsize]*n for _ in range(m)]\n while heap:\n cost,i,j=heappop(heap)\n if i==m-1 and j==n-1: return cost\n for di,dj in directions:\n ni,nj=i+di,j+dj\n if 0<=ni<m and 0<=nj<n:\n new_cost=cost+1\n if grid[ni][nj]>cost:\n if abs(cost-grid[ni][nj])%2==0:\n new_cost=grid[ni][nj]+1\n else:\n new_cost=grid[ni][nj]\n if new_cost<dist[ni][nj]:\n dist[ni][nj]=new_cost\n heappush(heap,(new_cost,ni,nj))\n \n \n``` | 3 | You are given a `m x n` matrix `grid` consisting of **non-negative** integers where `grid[row][col]` represents the **minimum** time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the time you visit it is greater than or equal to `grid[row][col]`.
You are standing in the **top-left** cell of the matrix in the `0th` second, and you must move to **any** adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return _the **minimum** time required in which you can visit the bottom-right cell of the matrix_. If you cannot visit the bottom-right cell, then return `-1`.
**Example 1:**
**Input:** grid = \[\[0,1,3,2\],\[5,1,2,5\],\[4,3,8,6\]\]
**Output:** 7
**Explanation:** One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid\[0\]\[1\] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid\[1\]\[3\] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid\[2\]\[3\] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
**Example 2:**
**Input:** grid = \[\[0,2,4\],\[3,2,1\],\[1,0,4\]\]
**Output:** -1
**Explanation:** There is no path from the top left to the bottom-right cell.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `0 <= grid[i][j] <= 105`
* `grid[0][0] == 0`
.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;} | null |
[Python] BFS with priority queue; Explained | minimum-time-to-visit-a-cell-in-a-grid | 0 | 1 | The BFS can be used to solve the minimum time or minimum length problem.\n\n(1) In this problem, we must move to a different cell every second. Thus, the only case that we cannot reach the bottom right cell is that all the cells next to (0, 0) has required visit time larger than 1. If we have more than 2 visited cells, we can move back and forth so that the required visit time can meet.\n\n(2) Since we are moving back and forth, the minimum increment of time is 2. If the difference between the required visit time of next cell and the current time is multiple of 2, we need add one more second before we can reach the next cell.\n\n(3) Sort all the cells in a priority queue based on the next visit time, so that we can always visit the cell using the minimum time.\n\nWhenever, we reach the bottom right cell, we can return the visiting time.\n\n```\nclass Solution:\n def minimumTime(self, grid: List[List[int]]) -> int:\n nrow = len(grid)\n ncol = len(grid[0])\n \n visited = set()\n visit_queue = [(0, 0, 0)]\n visited.add((0, 0))\n \n ans = -1\n while visit_queue:\n visit_time, r, c = heapq.heappop(visit_queue)\n if r == nrow - 1 and c == ncol - 1:\n ans = visit_time\n break\n \n for ncell in {(0, 1), (1, 0), (0, -1), (-1, 0)}:\n nr = r + ncell[0]\n nc = c + ncell[1]\n if nr >= 0 and nr < nrow and nc >= 0 and nc < ncol and (nr, nc) not in visited:\n if grid[nr][nc] <= visit_time + 1:\n heapq.heappush(visit_queue, (visit_time + 1, nr, nc))\n visited.add((nr, nc))\n elif len(visited) >= 2:\n if (grid[nr][nc] - visit_time - 1) % 2:\n heapq.heappush(visit_queue, (grid[nr][nc] + 1, nr, nc))\n else:\n heapq.heappush(visit_queue, (grid[nr][nc], nr, nc))\n visited.add((nr, nc))\n \n return ans\n``` | 3 | You are given a `m x n` matrix `grid` consisting of **non-negative** integers where `grid[row][col]` represents the **minimum** time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the time you visit it is greater than or equal to `grid[row][col]`.
You are standing in the **top-left** cell of the matrix in the `0th` second, and you must move to **any** adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return _the **minimum** time required in which you can visit the bottom-right cell of the matrix_. If you cannot visit the bottom-right cell, then return `-1`.
**Example 1:**
**Input:** grid = \[\[0,1,3,2\],\[5,1,2,5\],\[4,3,8,6\]\]
**Output:** 7
**Explanation:** One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid\[0\]\[1\] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid\[1\]\[3\] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid\[2\]\[3\] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
**Example 2:**
**Input:** grid = \[\[0,2,4\],\[3,2,1\],\[1,0,4\]\]
**Output:** -1
**Explanation:** There is no path from the top left to the bottom-right cell.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `0 <= grid[i][j] <= 105`
* `grid[0][0] == 0`
.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;} | null |
[Python3] Dijkstra's algo | minimum-time-to-visit-a-cell-in-a-grid | 0 | 1 | \n```\nclass Solution:\n def minimumTime(self, grid: List[List[int]]) -> int:\n if grid[0][1] <= 1 or grid[1][0] <= 1: \n m, n = len(grid), len(grid[0])\n pq = [(0, 0, 0)]\n dist = defaultdict(lambda : inf, {(0, 0) : 0})\n while pq: \n x, i, j = heappop(pq)\n if (i, j) == (m-1, n-1): return x \n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n: \n xx = x + 1 + max(0, (grid[ii][jj] - x)//2*2) \n if dist[ii, jj] > xx: \n heappush(pq, (xx, ii, jj))\n dist[ii, jj] = xx \n return -1 \n``` | 3 | You are given a `m x n` matrix `grid` consisting of **non-negative** integers where `grid[row][col]` represents the **minimum** time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the time you visit it is greater than or equal to `grid[row][col]`.
You are standing in the **top-left** cell of the matrix in the `0th` second, and you must move to **any** adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second.
Return _the **minimum** time required in which you can visit the bottom-right cell of the matrix_. If you cannot visit the bottom-right cell, then return `-1`.
**Example 1:**
**Input:** grid = \[\[0,1,3,2\],\[5,1,2,5\],\[4,3,8,6\]\]
**Output:** 7
**Explanation:** One of the paths that we can take is the following:
- at t = 0, we are on the cell (0,0).
- at t = 1, we move to the cell (0,1). It is possible because grid\[0\]\[1\] <= 1.
- at t = 2, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 2.
- at t = 3, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 3.
- at t = 4, we move to the cell (1,1). It is possible because grid\[1\]\[1\] <= 4.
- at t = 5, we move to the cell (1,2). It is possible because grid\[1\]\[2\] <= 5.
- at t = 6, we move to the cell (1,3). It is possible because grid\[1\]\[3\] <= 6.
- at t = 7, we move to the cell (2,3). It is possible because grid\[2\]\[3\] <= 7.
The final time is 7. It can be shown that it is the minimum time possible.
**Example 2:**
**Input:** grid = \[\[0,2,4\],\[3,2,1\],\[1,0,4\]\]
**Output:** -1
**Explanation:** There is no path from the top left to the bottom-right cell.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `2 <= m, n <= 1000`
* `4 <= m * n <= 105`
* `0 <= grid[i][j] <= 105`
* `grid[0][0] == 0`
.spoilerbutton {display:block; border:dashed; padding: 0px 0px; margin:10px 0px; font-size:150%; font-weight: bold; color:#000000; background-color:cyan; outline:0; } .spoiler {overflow:hidden;} .spoiler > div {-webkit-transition: all 0s ease;-moz-transition: margin 0s ease;-o-transition: all 0s ease;transition: margin 0s ease;} .spoilerbutton\[value="Show Message"\] + .spoiler > div {margin-top:-500%;} .spoilerbutton\[value="Hide Message"\] + .spoiler {padding:5px;} | null |
2578: Solution with step by step explanation | split-with-minimum-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. a = [int(x) for x in str(num)]: This converts the input integer num into a list of integers a where each element of the list represents a digit of the number num.\n\n2. pq = PriorityQueue(): This creates an instance of the PriorityQueue class from the queue module. This class represents a priority queue data structure that stores elements in a sorted order based on their priority. In this case, the priority is given by the value of the digits.\n\n3. num1 = "" and num2 = "": These create two empty strings to store the digits of the number after they have been sorted.\n\n4. for i in a: pq.put(i): This adds each digit in the list a to the priority queue pq.\n\n5. while not pq.empty():: This starts a loop that continues until the priority queue pq is empty.\n\n6. num1 += str(pq.get()): This appends the smallest digit in the priority queue pq to the string num1.\n\n7. if not pq.empty(): num2 += str(pq.get()): This checks if the priority queue pq is still not empty. If it is not empty, it appends the next smallest digit to the string num2.\n\n8. if num2: return int(num1) + int(num2): This checks if the string num2 is not empty. If it is not empty, it converts both num1 and num2 to integers and returns their sum. Otherwise, it returns the integer value of num1.\n\nIn summary, the splitNum function sorts the digits of the input integer in ascending order and then splits them into two numbers by alternating digits. Finally, it returns the sum of the two numbers if they are both non-empty, otherwise, it returns the integer value of the first number.\n\n\n# Complexity\n- Time complexity:\n100%\n\n- Space complexity:\n100%\n\n# Code\n```\nfrom queue import PriorityQueue\n\nclass Solution:\n def splitNum(self, num: int) -> int:\n a = [int(x) for x in str(num)]\n pq = PriorityQueue()\n num1 = ""\n num2 = ""\n for i in a:\n pq.put(i)\n\n while not pq.empty():\n num1 += str(pq.get())\n if not pq.empty():\n num2 += str(pq.get())\n\n if num2:\n return int(num1) + int(num2)\n else:\n return int(num1)\n\n``` | 5 | Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is equal to the number of occurrences of that digit in `num`.
* `num1` and `num2` can contain leading zeros.
Return _the **minimum** possible sum of_ `num1` _and_ `num2`.
**Notes:**
* It is guaranteed that `num` does not contain any leading zeros.
* The order of occurrence of the digits in `num1` and `num2` may differ from the order of occurrence of `num`.
**Example 1:**
**Input:** num = 4325
**Output:** 59
**Explanation:** We can split 4325 so that `num1` is 24 and num2 `is` 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
**Example 2:**
**Input:** num = 687
**Output:** 75
**Explanation:** We can split 687 so that `num1` is 68 and `num2` is 7, which would give an optimal sum of 75.
**Constraints:**
* `10 <= num <= 109` | null |
Simple solution with Sorting in Python3 | split-with-minimum-sum | 0 | 1 | # Intuition\nHere we have:\n- integer `num`\n- our goal is to **divide it** and extract **minimum possible sum**\n\nLet\'s act **greedily**: \n- sort digits of `num`\n- and at each step **distribute** it into **two parts**\n- after you achieved `left` and `right` optimal distributions\n\n# Approach\n1. split `num` as **string**\n2. **sort** digits\n3. and distribute them optimally for `left` and `right` parts\n4. sum up `left + right`\n\n# Complexity\n- Time complexity: **O(N log N)**\n\n- Space complexity: **O(1)**\n\n# Code\n```\nclass Solution:\n def splitNum(self, num: int) -> int:\n s = list(str(num))\n s.sort()\n left = 0\n right = 0\n\n for i in range(len(s)):\n if i & 1:\n right = right * 10 + int(s[i])\n else:\n left = left * 10 + int(s[i])\n \n return left + right\n``` | 1 | Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is equal to the number of occurrences of that digit in `num`.
* `num1` and `num2` can contain leading zeros.
Return _the **minimum** possible sum of_ `num1` _and_ `num2`.
**Notes:**
* It is guaranteed that `num` does not contain any leading zeros.
* The order of occurrence of the digits in `num1` and `num2` may differ from the order of occurrence of `num`.
**Example 1:**
**Input:** num = 4325
**Output:** 59
**Explanation:** We can split 4325 so that `num1` is 24 and num2 `is` 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
**Example 2:**
**Input:** num = 687
**Output:** 75
**Explanation:** We can split 687 so that `num1` is 68 and `num2` is 7, which would give an optimal sum of 75.
**Constraints:**
* `10 <= num <= 109` | null |
Easy Python solution | split-with-minimum-sum | 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 splitNum(self, num: int) -> int:\n a = sorted([int(i) for i in str(num)])\n b = \'\'\n c = \'\'\n for ind, x in enumerate(a):\n if ind%2 == 0:\n b += str(x)\n else:\n c += str(x)\n return int(b)+int(c)\n``` | 1 | Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is equal to the number of occurrences of that digit in `num`.
* `num1` and `num2` can contain leading zeros.
Return _the **minimum** possible sum of_ `num1` _and_ `num2`.
**Notes:**
* It is guaranteed that `num` does not contain any leading zeros.
* The order of occurrence of the digits in `num1` and `num2` may differ from the order of occurrence of `num`.
**Example 1:**
**Input:** num = 4325
**Output:** 59
**Explanation:** We can split 4325 so that `num1` is 24 and num2 `is` 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
**Example 2:**
**Input:** num = 687
**Output:** 75
**Explanation:** We can split 687 so that `num1` is 68 and `num2` is 7, which would give an optimal sum of 75.
**Constraints:**
* `10 <= num <= 109` | null |
[Java/Python 3] Greedy: Sort then concatenate digits @ even and odd indices. | split-with-minimum-sum | 1 | 1 | **Intuition:**\n\nWe want to make the most significant digits (MSD) as small as possible in order to split `num` into `2` smallest numbers, say, `a` and `b`.\n\nTherefore, \n1. We have to choose the smallest digit as the MSD of `a`; then\n2. Choose the second smallest digit as the MSD of `b`;\n3. Choose the third smallest digit as the 2nd MSD of `a`;\n4. Choose the fourth smallest digit as the 2nd MSD of `b`;\n5. ....\n\nThe pattern is: choose the sorted digits alternatively for the `2` numbers, `a` & `b`.\n\n----\n\nConvert `num` to char[] (or list), sort it, then concatenate the digits at even and odd indices repectively. By this way, we can get the smallest `2` numbers to sum.\n\n```java\n public int splitNum(int num) {\n char[] ca = Integer.toString(num).toCharArray();\n Arrays.sort(ca);\n int a = 0, b = 0;\n for (int i = 0; i < ca.length; ++i) {\n int digit = ca[i] - \'0\';\n if (i % 2 == 0) {\n a *= 10;\n a += digit;\n }else {\n b *= 10;\n b += digit;\n }\n }\n return a + b;\n }\n```\nor\n```java\n public int splitNum(int num) {\n char[] ca = Integer.toString(num).toCharArray();\n Arrays.sort(ca);\n int[] arr = {0, 0};\n for (int i = 0; i < ca.length; ++i) {\n arr[i % 2] *= 10;\n arr[i % 2] += ca[i] - \'0\';\n }\n return arr[0] + arr[1];\n }\n```\n\n```python\n def splitNum(self, num: int) -> int:\n a, b = [], []\n for i, c in enumerate(sorted(str(num))):\n (a if i % 2 == 0 else b).append(c)\n return int(\'\'.join(a)) + int(\'\'.join(b))\n```\nor \n```python\n def splitNum(self, num: int) -> int:\n num = \'\'.join(sorted(str(num)))\n return sum(map(int, (num[::2], num[1::2])))\n```\n\n**Analysis:**\n\nSince there are `log(num)` digits in `num`, \n\nTime: `O(dlogd)` space: `O(d)`, where `d = log(num)`.\n\n----\n\n**Q & A:** - credit to **@prakhar432**\n\n*Q1:* Why is there -> log(num) digits in num?\n\n*A1:* Note: The base for the logarithm is 10 everywhere in the answer.\n\nI will try to give an intuitive idea without a mathematical proof for this. Suppose we have the number 10000, which can be written as 10^5.\nIf we write N = 10^5, and then take log with base 10 on both sides, then we will get-\nlog N = 5*log 10 = 5*1 = 5. So we can see that it takes 5 digits to represent 10^5. Or, we can say that it takes log(N) = log(10^5) number of digits to represent a number N.\n\nTo get a better idea, consider we have k number of digits in a number. Then, we can see that the range of the number will be between 10^(k-1) and 10^k - 1.\nSo, for k number of digits, range is - [10^(k-1), 10^k - 1]\nNow, if we take log on both sides, then-\nwe need log(k) number of digits for the range of - [k-1, log(10^k -1], which is approximately [k-1,k].\nHence, we can see that it takes nearly log(N) digits to represent a number N.\nWith precision, a number N requires [log(N)] + 1.\n\n**End of Q & A** | 25 | Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is equal to the number of occurrences of that digit in `num`.
* `num1` and `num2` can contain leading zeros.
Return _the **minimum** possible sum of_ `num1` _and_ `num2`.
**Notes:**
* It is guaranteed that `num` does not contain any leading zeros.
* The order of occurrence of the digits in `num1` and `num2` may differ from the order of occurrence of `num`.
**Example 1:**
**Input:** num = 4325
**Output:** 59
**Explanation:** We can split 4325 so that `num1` is 24 and num2 `is` 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
**Example 2:**
**Input:** num = 687
**Output:** 75
**Explanation:** We can split 687 so that `num1` is 68 and `num2` is 7, which would give an optimal sum of 75.
**Constraints:**
* `10 <= num <= 109` | null |
Python Easy | split-with-minimum-sum | 0 | 1 | # Intuition\nCreate two numbers through odd even position of index and you will get your ans. :)\n\n# Code\n```\nclass Solution:\n def splitNum(self, num: int) -> int:\n nums = []\n for n in str(num):\n nums.append(int(n))\n if len(nums) % 2 != 0:\n nums.append(0)\n nums.sort()\n num1 = ""\n num2 = ""\n for i in range(len(nums)):\n if i % 2 == 0:\n num1 += str(nums[i])\n else:\n num2 += str(nums[i])\n ans = int(num1) + int(num2)\n return ans\n \n \n \n``` | 1 | Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is equal to the number of occurrences of that digit in `num`.
* `num1` and `num2` can contain leading zeros.
Return _the **minimum** possible sum of_ `num1` _and_ `num2`.
**Notes:**
* It is guaranteed that `num` does not contain any leading zeros.
* The order of occurrence of the digits in `num1` and `num2` may differ from the order of occurrence of `num`.
**Example 1:**
**Input:** num = 4325
**Output:** 59
**Explanation:** We can split 4325 so that `num1` is 24 and num2 `is` 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
**Example 2:**
**Input:** num = 687
**Output:** 75
**Explanation:** We can split 687 so that `num1` is 68 and `num2` is 7, which would give an optimal sum of 75.
**Constraints:**
* `10 <= num <= 109` | null |
🤯 CRAZY ONE-LINE SOLUTION IN PYTHON | split-with-minimum-sum | 0 | 1 | # Approach\nDefine $$s$$ as string with sorted digits of source number.\n\nThe minimum string would be: $$\\overline{s_0s_2s_4...s_{2i}} + \\overline{s_1s_3s_5...s_{2i+1}}$$\n\n# Complexity\n- Time complexity: $$O(\\log N * \\log (\\log N))$$, since we sort digits\n\n- Space complexity: $$O(\\log N)$$\n\n# Code\n```\nclass Solution:\n def splitNum(self, num: int) -> int:\n return int((s:=\'\'.join(sorted(str(num))))[::2])+int(s[1::2])\n```\n\n\n | 5 | Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is equal to the number of occurrences of that digit in `num`.
* `num1` and `num2` can contain leading zeros.
Return _the **minimum** possible sum of_ `num1` _and_ `num2`.
**Notes:**
* It is guaranteed that `num` does not contain any leading zeros.
* The order of occurrence of the digits in `num1` and `num2` may differ from the order of occurrence of `num`.
**Example 1:**
**Input:** num = 4325
**Output:** 59
**Explanation:** We can split 4325 so that `num1` is 24 and num2 `is` 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
**Example 2:**
**Input:** num = 687
**Output:** 75
**Explanation:** We can split 687 so that `num1` is 68 and `num2` is 7, which would give an optimal sum of 75.
**Constraints:**
* `10 <= num <= 109` | null |
[Python3] Simple solution (heap) | split-with-minimum-sum | 0 | 1 | ```\nclass Solution:\n def splitNum(self, num: int) -> int:\n nums = [i for i in str(num)]\n num1, num2 = \'\', \'\'\n i = 0\n \n heapify(nums)\n \n while nums:\n if i % 2 == 0:\n num1 += heappop(nums)\n else:\n num2 += heappop(nums)\n \n i += 1\n \n return int(num1) + int(num2)\n``` | 2 | Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is equal to the number of occurrences of that digit in `num`.
* `num1` and `num2` can contain leading zeros.
Return _the **minimum** possible sum of_ `num1` _and_ `num2`.
**Notes:**
* It is guaranteed that `num` does not contain any leading zeros.
* The order of occurrence of the digits in `num1` and `num2` may differ from the order of occurrence of `num`.
**Example 1:**
**Input:** num = 4325
**Output:** 59
**Explanation:** We can split 4325 so that `num1` is 24 and num2 `is` 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
**Example 2:**
**Input:** num = 687
**Output:** 75
**Explanation:** We can split 687 so that `num1` is 68 and `num2` is 7, which would give an optimal sum of 75.
**Constraints:**
* `10 <= num <= 109` | null |
Python 3 || 2 versions: w/ and w/o str || T/M: 100% / 100% | split-with-minimum-sum | 0 | 1 | \'\'\'\nWith`str`:\n```\nclass Solution:\n def splitNum(self, num: int) -> int:\n\n num = sorted(list(str(num)))\n\n num1,num2 = int(\'\'.join(num[0::2])), int(\'\'.join(num[1::2]))\n return num1+num2 \n```\nWithout`str`:\n```\nclass Solution:\n def splitNum(self, num: int) -> int:\n\n digits, ans = [], 0\n while num:\n digits.append(num%10)\n num//= 10\n\n if len(digits)%2: digits.append(0)\n\n digits.sort()\n\n for i in range(0,len(digits),2):\n ans = ans*10+digits[i]+digits[i+1]\n \n return ans\n\n```\n[https://leetcode.com/problems/split-with-minimum-sum/submissions/909206195/](http://)\n\n\nI could be wrong, but I think that time complexity is *O*(*NlogN*) and space complexity is *O*(*N*), in which *N* ~`len(str(num))`. | 4 | Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is equal to the number of occurrences of that digit in `num`.
* `num1` and `num2` can contain leading zeros.
Return _the **minimum** possible sum of_ `num1` _and_ `num2`.
**Notes:**
* It is guaranteed that `num` does not contain any leading zeros.
* The order of occurrence of the digits in `num1` and `num2` may differ from the order of occurrence of `num`.
**Example 1:**
**Input:** num = 4325
**Output:** 59
**Explanation:** We can split 4325 so that `num1` is 24 and num2 `is` 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
**Example 2:**
**Input:** num = 687
**Output:** 75
**Explanation:** We can split 687 so that `num1` is 68 and `num2` is 7, which would give an optimal sum of 75.
**Constraints:**
* `10 <= num <= 109` | null |
Easy Python Solution | split-with-minimum-sum | 0 | 1 | # Code\n```\nclass Solution:\n def splitNum(self, num: int) -> int:\n l=list(str(num))\n l.sort()\n even, odd= "", ""\n for i in range(0,len(l)):\n if i%2==0:\n even+= l[i]\n else:\n odd+= l[i]\n return int(even)+int(odd)\n``` | 3 | Given a positive integer `num`, split it into two non-negative integers `num1` and `num2` such that:
* The concatenation of `num1` and `num2` is a permutation of `num`.
* In other words, the sum of the number of occurrences of each digit in `num1` and `num2` is equal to the number of occurrences of that digit in `num`.
* `num1` and `num2` can contain leading zeros.
Return _the **minimum** possible sum of_ `num1` _and_ `num2`.
**Notes:**
* It is guaranteed that `num` does not contain any leading zeros.
* The order of occurrence of the digits in `num1` and `num2` may differ from the order of occurrence of `num`.
**Example 1:**
**Input:** num = 4325
**Output:** 59
**Explanation:** We can split 4325 so that `num1` is 24 and num2 `is` 35, giving a sum of 59. We can prove that 59 is indeed the minimal possible sum.
**Example 2:**
**Input:** num = 687
**Output:** 75
**Explanation:** We can split 687 so that `num1` is 68 and `num2` is 7, which would give an optimal sum of 75.
**Constraints:**
* `10 <= num <= 109` | null |
[Java/Python 3] Sum of square of n and n - 1. | count-total-number-of-colored-cells | 1 | 1 | By obersance, there are `2` arithmetic sequences if we divide the cells right below the horizontal middle cells, and they are:\n\n1, 3, 5,..., 2 * i - 1, ..., 2 * n - 1 = n * n.\n1, 3, 5,..., 2 * i - 1, ..., 2 * n - 3 = (n - 1) * (n - 1).\n\n```java\n public long coloredCells(int n) {\n return (long)n * n + (long)(n - 1) * (n - 1);\n }\n```\n\n```python\n def coloredCells(self, n: int) -> int:\n return n ** 2 + (n - 1) ** 2\n```\n\n**Analysis:**\n\nTime & space: `O(1)`.\n\n----\n\nAnother Easy way of doing this problem -- credit to **@Himanshu3889**\n\nObserve we are increasing stairs on all four sides Left-up , Left-down , Right-up Right-down this means previous stairs contributes 4* prevStairs to the next n and in each directions a new stair is coming\n`O(n)` dp\n\n```python\ndef coloredCells(self, n: int) -> int:\n res = 1 # for n == 1\n for stairs in range(1,n): # prev stairs\n res += stairs*4\n return res\n```\n`O(1)` using maths\n\nNow use the maths see sequence\n`1 + 1* 4 + 2* 4 + 3* 4....(n-1) * 4`\n`1 + 4 * (1+2+3+4 ..n-1) = 1 + 4* (sum of n-1 natural numbers)`\n\n```python\ndef coloredCells(self, n: int) -> int:\n return 1 + 4*n*(n-1)//2\n``` | 11 | There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes:
* At the first minute, color **any** arbitrary unit cell blue.
* Every minute thereafter, color blue **every** uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Return _the number of **colored cells** at the end of_ `n` _minutes_.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** After 1 minute, there is only 1 blue cell, so we return 1.
**Example 2:**
**Input:** n = 2
**Output:** 5
**Explanation:** After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
**Constraints:**
* `1 <= n <= 105` | null |
Easy Python Solution (using recursion) | count-total-number-of-colored-cells | 0 | 1 | # Code\n```\nclass Solution:\n def coloredCells(self, n: int) -> int:\n if n==1:\n return 1\n else:\n return (4*(n-1))+self.coloredCells(n-1)\n``` | 2 | There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes:
* At the first minute, color **any** arbitrary unit cell blue.
* Every minute thereafter, color blue **every** uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Return _the number of **colored cells** at the end of_ `n` _minutes_.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** After 1 minute, there is only 1 blue cell, so we return 1.
**Example 2:**
**Input:** n = 2
**Output:** 5
**Explanation:** After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
**Constraints:**
* `1 <= n <= 105` | null |
Simple one-liner. Just do n**2 + (n-1)**2 | count-total-number-of-colored-cells | 0 | 1 | \n# Code\n```\nclass Solution:\n def coloredCells(self, n: int) -> int:\n return n**2 + (n-1)**2\n``` | 1 | There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes:
* At the first minute, color **any** arbitrary unit cell blue.
* Every minute thereafter, color blue **every** uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Return _the number of **colored cells** at the end of_ `n` _minutes_.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** After 1 minute, there is only 1 blue cell, so we return 1.
**Example 2:**
**Input:** n = 2
**Output:** 5
**Explanation:** After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
**Constraints:**
* `1 <= n <= 105` | null |
[Python] It is a math problem; Explained | count-total-number-of-colored-cells | 0 | 1 | Here is the pattern:\nT = 1: 1\nT = 2: 1 + 4\nT = 3: (1 + 4) + 4 + 4\nT = 4: ((1 + 4) + 4 + 4) + 4 + 8\nT = 5: (((1 + 4) + 4 + 4) + 4 + 8) + 4 + 12\n\nT = n: 1 + 4 * (n - 1) + 4 * ((n - 2) + (n - 3) + ... + 1)\n\n\n```\nclass Solution:\n def coloredCells(self, n: int) -> int:\n ans = 1\n \n if n > 1:\n ans += 4 * (n - 1)\n if n > 2:\n ans += 4 * ((n - 1) * (n - 2) // 2)\n \n return ans\n``` | 1 | There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes:
* At the first minute, color **any** arbitrary unit cell blue.
* Every minute thereafter, color blue **every** uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Return _the number of **colored cells** at the end of_ `n` _minutes_.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** After 1 minute, there is only 1 blue cell, so we return 1.
**Example 2:**
**Input:** n = 2
**Output:** 5
**Explanation:** After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
**Constraints:**
* `1 <= n <= 105` | null |
[Python 3] Math | count-total-number-of-colored-cells | 0 | 1 | ```\nclass Solution:\n def coloredCells(self, n: int) -> int:\n return 2 * n * (n - 1) + 1\n``` | 1 | There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes:
* At the first minute, color **any** arbitrary unit cell blue.
* Every minute thereafter, color blue **every** uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Return _the number of **colored cells** at the end of_ `n` _minutes_.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** After 1 minute, there is only 1 blue cell, so we return 1.
**Example 2:**
**Input:** n = 2
**Output:** 5
**Explanation:** After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
**Constraints:**
* `1 <= n <= 105` | null |
2579. Solution with step by step explanation | count-total-number-of-colored-cells | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. n*n: This calculates the number of cells in a square grid of size n by n. This is the number of cells that will be colored.\n\n2. (n-1)*(n-1): This calculates the number of cells that will be colored by the diagonals of the grid. Each diagonal consists of n-1 cells, so there are n-1 diagonals in each direction (horizontal and vertical). The total number of cells colored by the diagonals is therefore (n-1)*(n-1).\n\n3. n*n + (n-1)*(n-1): This adds the number of cells colored by the diagonals to the number of cells in the grid to get the total number of colored cells.\n\n4. The final result is returned as an integer value.\n\nSo, in summary, the function coloredCells calculates the total number of cells that will be colored in a square grid of size n, where the cells are colored in a diagonal pattern as well.\n\nThe time complexity of the given algorithm is O(1) as the calculations involved are basic arithmetic operations that take constant time. Similarly, the space complexity of the algorithm is also O(1) as we are not using any additional data structure.\n\n# Complexity\n- Time complexity:\nO(1)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def coloredCells(self, n: int) -> int:\n return n*n + (n-1)*(n-1)\n\n``` | 7 | There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes:
* At the first minute, color **any** arbitrary unit cell blue.
* Every minute thereafter, color blue **every** uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Return _the number of **colored cells** at the end of_ `n` _minutes_.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** After 1 minute, there is only 1 blue cell, so we return 1.
**Example 2:**
**Input:** n = 2
**Output:** 5
**Explanation:** After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
**Constraints:**
* `1 <= n <= 105` | null |
Easiest Python solution | count-total-number-of-colored-cells | 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 coloredCells(self, n: int) -> int:\n summ = 1\n for i in range(1, n):\n summ += 4*i\n return summ\n \n``` | 1 | There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes:
* At the first minute, color **any** arbitrary unit cell blue.
* Every minute thereafter, color blue **every** uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Return _the number of **colored cells** at the end of_ `n` _minutes_.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** After 1 minute, there is only 1 blue cell, so we return 1.
**Example 2:**
**Input:** n = 2
**Output:** 5
**Explanation:** After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
**Constraints:**
* `1 <= n <= 105` | null |
python easy to understand || math || sequence and series | count-total-number-of-colored-cells | 0 | 1 | ```\nclass Solution:\n def coloredCells(self, n: int) -> int:\n if n<=1:\n return n\n ans = 0\n\t\t# hint: The Given sequence is arithmetic sequence\n\t\t# finding the nth term of arithmetic progression \n an = (1+(n-1)*2)\n\t\t# formulae to find sum of 2*n terms\n sn = n*(1+an)\n\t\t# the middle layer is appeared twice so remove it to get the ans\n return sn - 2*n + 1\n``` | 1 | There exists an infinitely large two-dimensional grid of uncolored unit cells. You are given a positive integer `n`, indicating that you must do the following routine for `n` minutes:
* At the first minute, color **any** arbitrary unit cell blue.
* Every minute thereafter, color blue **every** uncolored cell that touches a blue cell.
Below is a pictorial representation of the state of the grid after minutes 1, 2, and 3.
Return _the number of **colored cells** at the end of_ `n` _minutes_.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** After 1 minute, there is only 1 blue cell, so we return 1.
**Example 2:**
**Input:** n = 2
**Output:** 5
**Explanation:** After 2 minutes, there are 4 colored cells on the boundary and 1 in the center, so we return 5.
**Constraints:**
* `1 <= n <= 105` | null |
Python 3 || 6 lines, w/example || T/M: 1197 ms / 64 MB | count-ways-to-group-overlapping-ranges | 0 | 1 | ```\nclass Solution:\n def countWays(self, ranges:List[List[int]])-> int: # Example: [[11,11],[3,9],[12,13],[1,8]]\n #\n cnt, ans = 0, 1 # _, idx = zip(*sorted(zip(11,11,8,9,12,13,1,3), [-1,1]*4)\n # = zip(*sorted((11,-1),(11,1),(3,-1),(9,1),(12,-1),(13,1)),(1,-1),(8,1))))\n _, idx = zip(*sorted(zip(chain(*ranges), # = zip(*(1,-1),(3,-1),(8,1),(9,1),(11,-1),(11,1),(12,-1),(13,1))\n [-1,1]*len(ranges)))) # idx = (-1,-1,1,1,-1,1,-1,1)\n \n # i cnt ans\n # \u2013\u2013\u2013 \u2013\u2013\u2013 \u2013\u2013\u2013 \n for i in idx: # 0 1 \n cnt+= i # -1 -1 \n if cnt == 0: ans*= 2 # -1 -2 \n # 1 -1 \n return ans # 1 0 -\u2013> 2\n # -1 -1 \n # 1 0 -\u2013> 4\n # -1 -1 \n # 1 0 -\u2013> 8 <\u2013\u2013\u2013 return\n\n\n\n```\n[https://leetcode.com/problems/count-ways-to-group-overlapping-ranges/submissions/909737649/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*NlogN*) and space complexity is *O*(*N*).\n\n | 3 | You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each range belongs to exactly one group.
* Any two **overlapping** ranges must belong to the **same** group.
Two ranges are said to be **overlapping** if there exists at least **one** integer that is present in both ranges.
* For example, `[1, 3]` and `[2, 5]` are overlapping because `2` and `3` occur in both ranges.
Return _the **total number** of ways to split_ `ranges` _into two groups_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** ranges = \[\[6,10\],\[5,15\]\]
**Output:** 2
**Explanation:**
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
**Example 2:**
**Input:** ranges = \[\[1,3\],\[10,20\],\[2,5\],\[4,8\]\]
**Output:** 4
**Explanation:**
Ranges \[1,3\], and \[2,5\] are overlapping. So, they must be in the same group.
Again, ranges \[2,5\] and \[4,8\] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 1 and \[10,20\] in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 2 and \[10,20\] in group 1.
**Constraints:**
* `1 <= ranges.length <= 105`
* `ranges[i].length == 2`
* `0 <= starti <= endi <= 109` | null |
Merge and Power | count-ways-to-group-overlapping-ranges | 0 | 1 | First, we need to "merge" overlapping intervals, so that we have `m` non-overlapping intervals.\n\nWe can put each interval in any of two groups, so the total number of splits is `2 ^ m`.\n\nSo, we sort `ranges`, and multiply the result by 2 when we detect a new non-overlapping interval.\n\n**Python 3**\n```python\nclass Solution:\n def countWays(self, ranges: List[List[int]]) -> int:\n end_max, res = -1, 1\n for start_i, end_i in sorted(ranges):\n res = res * (2 if end_max < start_i else 1) % 1000000007\n end_max = max(end_max, end_i)\n return res\n``` | 4 | You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each range belongs to exactly one group.
* Any two **overlapping** ranges must belong to the **same** group.
Two ranges are said to be **overlapping** if there exists at least **one** integer that is present in both ranges.
* For example, `[1, 3]` and `[2, 5]` are overlapping because `2` and `3` occur in both ranges.
Return _the **total number** of ways to split_ `ranges` _into two groups_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** ranges = \[\[6,10\],\[5,15\]\]
**Output:** 2
**Explanation:**
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
**Example 2:**
**Input:** ranges = \[\[1,3\],\[10,20\],\[2,5\],\[4,8\]\]
**Output:** 4
**Explanation:**
Ranges \[1,3\], and \[2,5\] are overlapping. So, they must be in the same group.
Again, ranges \[2,5\] and \[4,8\] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 1 and \[10,20\] in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 2 and \[10,20\] in group 1.
**Constraints:**
* `1 <= ranges.length <= 105`
* `ranges[i].length == 2`
* `0 <= starti <= endi <= 109` | null |
9 line answer easy to understand c++ solution | count-ways-to-group-overlapping-ranges | 1 | 1 | \n# Code\n```\n\nconst int MOD = 1e9 + 7;\n\nclass Solution {\npublic:\n int countWays(vector<vector<int>>& a) {\n int n = a.size();\n sort(a.begin(), a.end());\n \n int ret = 1;\n for (int i = 0, j; i < n; i = j) {\n int R = a[i][1];\n for (j = i + 1; j < n && a[j][0] <= R; ++j) R = max(R, a[j][1]);\n ret = ret * 2LL % MOD;\n }\n return ret;\n \n }\n};\n``` | 1 | You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each range belongs to exactly one group.
* Any two **overlapping** ranges must belong to the **same** group.
Two ranges are said to be **overlapping** if there exists at least **one** integer that is present in both ranges.
* For example, `[1, 3]` and `[2, 5]` are overlapping because `2` and `3` occur in both ranges.
Return _the **total number** of ways to split_ `ranges` _into two groups_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** ranges = \[\[6,10\],\[5,15\]\]
**Output:** 2
**Explanation:**
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
**Example 2:**
**Input:** ranges = \[\[1,3\],\[10,20\],\[2,5\],\[4,8\]\]
**Output:** 4
**Explanation:**
Ranges \[1,3\], and \[2,5\] are overlapping. So, they must be in the same group.
Again, ranges \[2,5\] and \[4,8\] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 1 and \[10,20\] in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 2 and \[10,20\] in group 1.
**Constraints:**
* `1 <= ranges.length <= 105`
* `ranges[i].length == 2`
* `0 <= starti <= endi <= 109` | null |
Python3, Sort, Merge, Pow | count-ways-to-group-overlapping-ranges | 0 | 1 | # Intuition\nFirst we sort ranges\nThen we are counting numberOfGroups by merging ranges.\n\nFinally we count answer\nIf group is going into FIRST -> assign 0\nIf group is going into SECOND -> assign 1\n\nThis means that the answer is power of 2.\n\n# Code\n```\nclass Solution:\n def countWays(self, ranges: List[List[int]]) -> int:\n ranges.sort()\n A,B=-1,-1 # Artificial first Range, smallest non-Overlapping\n numberOfGroups=0\n for a,b in ranges:\n if B<a:\n # starting New Group\n numberOfGroups+=1\n A,B=a,b\n else:\n # same Group\n B=max(B,b)\n return pow(2,numberOfGroups,10**9+7) \n``` | 1 | You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each range belongs to exactly one group.
* Any two **overlapping** ranges must belong to the **same** group.
Two ranges are said to be **overlapping** if there exists at least **one** integer that is present in both ranges.
* For example, `[1, 3]` and `[2, 5]` are overlapping because `2` and `3` occur in both ranges.
Return _the **total number** of ways to split_ `ranges` _into two groups_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** ranges = \[\[6,10\],\[5,15\]\]
**Output:** 2
**Explanation:**
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
**Example 2:**
**Input:** ranges = \[\[1,3\],\[10,20\],\[2,5\],\[4,8\]\]
**Output:** 4
**Explanation:**
Ranges \[1,3\], and \[2,5\] are overlapping. So, they must be in the same group.
Again, ranges \[2,5\] and \[4,8\] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 1 and \[10,20\] in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 2 and \[10,20\] in group 1.
**Constraints:**
* `1 <= ranges.length <= 105`
* `ranges[i].length == 2`
* `0 <= starti <= endi <= 109` | null |
[Python 3] Merge Intervals | Math | count-ways-to-group-overlapping-ranges | 0 | 1 | ```\nclass Solution:\n def countWays(self, ranges: List[List[int]]) -> int:\n ranges.sort()\n res = [ranges[0]]\n \n for s1, e1 in ranges[1 : ]:\n s2, e2 = res[-1]\n \n if max(s1, s2) <= min(e1, e2):\n res[-1] = [min(s1, s2), max(e1, e2)]\n else:\n res.append([s1, e1])\n \n return pow(2, len(res), pow(10, 9) + 7)\n``` | 1 | You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each range belongs to exactly one group.
* Any two **overlapping** ranges must belong to the **same** group.
Two ranges are said to be **overlapping** if there exists at least **one** integer that is present in both ranges.
* For example, `[1, 3]` and `[2, 5]` are overlapping because `2` and `3` occur in both ranges.
Return _the **total number** of ways to split_ `ranges` _into two groups_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** ranges = \[\[6,10\],\[5,15\]\]
**Output:** 2
**Explanation:**
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
**Example 2:**
**Input:** ranges = \[\[1,3\],\[10,20\],\[2,5\],\[4,8\]\]
**Output:** 4
**Explanation:**
Ranges \[1,3\], and \[2,5\] are overlapping. So, they must be in the same group.
Again, ranges \[2,5\] and \[4,8\] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 1 and \[10,20\] in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 2 and \[10,20\] in group 1.
**Constraints:**
* `1 <= ranges.length <= 105`
* `ranges[i].length == 2`
* `0 <= starti <= endi <= 109` | null |
[Java/Python 3] Count non-overlapping components and double accordingly. | count-ways-to-group-overlapping-ranges | 1 | 1 | Sort the `ranges` to find the number of non-overlapping components, and for each component, we have 2 options: put it into group `1` or `2`.\n\nTherefore, the answer is `2 ^ (# of componenets)`.\n\n```java\n public int countWays(int[][] ranges) {\n Arrays.sort(ranges, Comparator.comparingInt(r -> r[0]));\n int cnt = 1, hi = -1;\n for (int[] r : ranges) {\n if (hi < r[0]) {\n cnt <<= 1;\n cnt %= 1_000_000_007;\n }\n hi = Math.max(hi, r[1]);\n }\n return cnt;\n }\n```\n\n```python\n def countWays(self, ranges: List[List[int]]) -> int:\n cnt, hi = 1, -1\n for a, b in sorted(ranges):\n if hi < a:\n cnt <<= 1\n cnt %= 10 ** 9 + 7\n hi = max(hi, b)\n return cnt\n```\n**Analysis:**\n\nTime: `O(nlogn)`, space: `O(n)` - including sorting space. | 10 | You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each range belongs to exactly one group.
* Any two **overlapping** ranges must belong to the **same** group.
Two ranges are said to be **overlapping** if there exists at least **one** integer that is present in both ranges.
* For example, `[1, 3]` and `[2, 5]` are overlapping because `2` and `3` occur in both ranges.
Return _the **total number** of ways to split_ `ranges` _into two groups_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** ranges = \[\[6,10\],\[5,15\]\]
**Output:** 2
**Explanation:**
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
**Example 2:**
**Input:** ranges = \[\[1,3\],\[10,20\],\[2,5\],\[4,8\]\]
**Output:** 4
**Explanation:**
Ranges \[1,3\], and \[2,5\] are overlapping. So, they must be in the same group.
Again, ranges \[2,5\] and \[4,8\] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 1 and \[10,20\] in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 2 and \[10,20\] in group 1.
**Constraints:**
* `1 <= ranges.length <= 105`
* `ranges[i].length == 2`
* `0 <= starti <= endi <= 109` | null |
Python solution || Easy to understand || Very Easy || With Explianation | count-ways-to-group-overlapping-ranges | 0 | 1 | ```\nclass Solution:\n def countWays(self, intervals: List[List[int]]) -> int:\n\t\t\n\t\t# we can move a interval to either grp 1 or grp 2 so ans will be multiple of two\n ans=2\n\t\t\n\t\t# sort the intervals based on first element\n intervals.sort(key=lambda x: x[0])\n\t\t\n\t\t# stores the merged intervals\n mer = []\n\t\t\n\t\t# traverse intervals one by one and merging them\n for interval in intervals:\n if not mer or mer[-1][1] < interval[0]:\n mer.append(interval)\n else:\n mer[-1][1] = max(mer[-1][1], interval[1])\n\t\t\t\t\n\t\t# finally our ans will be 2**total_merge_intervals because ans may be large it\'ll take time to\n\t\t# compute modulo so for avoid it pass it to pow and return the ans\n return pow(ans,len(mer),1000_000_007)\n``` | 1 | You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each range belongs to exactly one group.
* Any two **overlapping** ranges must belong to the **same** group.
Two ranges are said to be **overlapping** if there exists at least **one** integer that is present in both ranges.
* For example, `[1, 3]` and `[2, 5]` are overlapping because `2` and `3` occur in both ranges.
Return _the **total number** of ways to split_ `ranges` _into two groups_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** ranges = \[\[6,10\],\[5,15\]\]
**Output:** 2
**Explanation:**
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
**Example 2:**
**Input:** ranges = \[\[1,3\],\[10,20\],\[2,5\],\[4,8\]\]
**Output:** 4
**Explanation:**
Ranges \[1,3\], and \[2,5\] are overlapping. So, they must be in the same group.
Again, ranges \[2,5\] and \[4,8\] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 1 and \[10,20\] in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 2 and \[10,20\] in group 1.
**Constraints:**
* `1 <= ranges.length <= 105`
* `ranges[i].length == 2`
* `0 <= starti <= endi <= 109` | null |
Simple Solution of grouping together || Python | count-ways-to-group-overlapping-ranges | 0 | 1 | \n\n# Approach\nA question for great revision of using combinations. Treat this question as putting n distinct balls into k different boxes (2 here).\nIts k ** n\nWe know there are 2 possible groups only so k = 2.\nNow if the ranges overlap u dont need to classify them into unique balls but if they donot overlap consider them as unique ball.\nNow with above method find the number of ways they can be groupped.\n\n# Code\n```\nclass Solution:\n def countWays(self, ranges: List[List[int]]) -> int:\n balls = 1\n sortedRange = sorted(ranges, key=lambda x: (x[0], x[1]))\n lastSeenRange = sortedRange[0][1]\n MOD = 10 ** 9 + 7\n for i in range(1, len(sortedRange)):\n if sortedRange[i][0] <= lastSeenRange:\n lastSeenRange = max(lastSeenRange, sortedRange[i][1])\n else:\n balls += 1\n lastSeenRange = sortedRange[i][1]\n return (2 ** balls) % MOD\n``` | 1 | You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each range belongs to exactly one group.
* Any two **overlapping** ranges must belong to the **same** group.
Two ranges are said to be **overlapping** if there exists at least **one** integer that is present in both ranges.
* For example, `[1, 3]` and `[2, 5]` are overlapping because `2` and `3` occur in both ranges.
Return _the **total number** of ways to split_ `ranges` _into two groups_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** ranges = \[\[6,10\],\[5,15\]\]
**Output:** 2
**Explanation:**
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
**Example 2:**
**Input:** ranges = \[\[1,3\],\[10,20\],\[2,5\],\[4,8\]\]
**Output:** 4
**Explanation:**
Ranges \[1,3\], and \[2,5\] are overlapping. So, they must be in the same group.
Again, ranges \[2,5\] and \[4,8\] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 1 and \[10,20\] in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 2 and \[10,20\] in group 1.
**Constraints:**
* `1 <= ranges.length <= 105`
* `ranges[i].length == 2`
* `0 <= starti <= endi <= 109` | null |
Scanline O(NlogN) | count-ways-to-group-overlapping-ranges | 0 | 1 | \n# Code\n```\nclass Solution:\n def countWays(self, ranges: List[List[int]]) -> int:\n new = []\n for start, end in ranges:\n new.append((start, -1))\n new.append((end, 1))\n new = sorted(new)\n\n s = 0\n groups = 0\n for d, t in new:\n if t == -1:\n s += 1\n else:\n s -= 1\n \n if s == 0:\n groups += 1\n \n return (2 ** groups) % (int(1e9+7))\n``` | 0 | You are given a 2D integer array `ranges` where `ranges[i] = [starti, endi]` denotes that all integers between `starti` and `endi` (both **inclusive**) are contained in the `ith` range.
You are to split `ranges` into **two** (possibly empty) groups such that:
* Each range belongs to exactly one group.
* Any two **overlapping** ranges must belong to the **same** group.
Two ranges are said to be **overlapping** if there exists at least **one** integer that is present in both ranges.
* For example, `[1, 3]` and `[2, 5]` are overlapping because `2` and `3` occur in both ranges.
Return _the **total number** of ways to split_ `ranges` _into two groups_. Since the answer may be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** ranges = \[\[6,10\],\[5,15\]\]
**Output:** 2
**Explanation:**
The two ranges are overlapping, so they must be in the same group.
Thus, there are two possible ways:
- Put both the ranges together in group 1.
- Put both the ranges together in group 2.
**Example 2:**
**Input:** ranges = \[\[1,3\],\[10,20\],\[2,5\],\[4,8\]\]
**Output:** 4
**Explanation:**
Ranges \[1,3\], and \[2,5\] are overlapping. So, they must be in the same group.
Again, ranges \[2,5\] and \[4,8\] are also overlapping. So, they must also be in the same group.
Thus, there are four possible ways to group them:
- All the ranges in group 1.
- All the ranges in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 1 and \[10,20\] in group 2.
- Ranges \[1,3\], \[2,5\], and \[4,8\] in group 2 and \[10,20\] in group 1.
**Constraints:**
* `1 <= ranges.length <= 105`
* `ranges[i].length == 2`
* `0 <= starti <= endi <= 109` | null |
Top-down DP | count-number-of-possible-root-nodes | 0 | 1 | **Intuition**\n\n1. Given a sub-tree, we can count how many edges are in `guesses`, which means how many guesses are correct for this sub-tree.\n\t* `guesses` should be put into a hash so that we can achieve `O(1)` for each edge to find out if it is in `guesses`.\n2. The answer for each sub-tree can be memorized.\n\t* That implies each edge will be visited only twice (forward and backward). Given that each edge costs `O(1)`, so it would cost `O(n)` as a total.\n\t* Remember, a sub-tree is defined by not only the sub-root node but the also its parent node, because the given graph is undirected.\n\n**Step by step**\n\nFirst, we put `guesses` into a hash, and we build the graph:\n```\n\t\tn = len(edges) + 1\n\t\th = set(tuple(x) for x in guesses)\n g = [[] for _ in range(n)]\n for a, b in edges:\n g[a].append(b)\n g[b].append(a)\n```\nAnd then we make a recursive function to count the correct guesses in each sub-tree:\n```\n @cache\n def rec(p, pp):\n\t\t\t# p: sub-root, pp: parent of p\n r = 0\n for q in g[p]:\n if q == pp: continue\n if (p, q) in h:\n r += 1\n r += rec(q, p)\n return r\n```\nAnd finally, we try to make each node as the root and check the correct guess count:\n```\n r = 0\n for i in range(n):\n if rec(i, i) >= k:\n r += 1\n return r\n```\nWe got the answer.\n\n**Complete code**\n\t\t\n```\n def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int:\n n = len(edges) + 1\n \n h = set(tuple(x) for x in guesses)\n \n g = [[] for _ in range(n)]\n for a, b in edges:\n g[a].append(b)\n g[b].append(a)\n \n @cache\n def rec(p, pp):\n r = 0\n for q in g[p]:\n if q == pp: continue\n if (p, q) in h:\n r += 1\n r += rec(q, p)\n return r\n \n r = 0\n for i in range(n):\n if rec(i, i) >= k:\n r += 1\n return r\n``` | 1 | Alice has an undirected tree with `n` nodes labeled from `0` to `n - 1`. The tree is represented as a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several **guesses** about her tree. In one guess, he does the following:
* Chooses two **distinct** integers `u` and `v` such that there exists an edge `[u, v]` in the tree.
* He tells Alice that `u` is the **parent** of `v` in the tree.
Bob's guesses are represented by a 2D integer array `guesses` where `guesses[j] = [uj, vj]` indicates Bob guessed `uj` to be the parent of `vj`.
Alice being lazy, does not reply to each of Bob's guesses, but just says that **at least** `k` of his guesses are `true`.
Given the 2D integer arrays `edges`, `guesses` and the integer `k`, return _the **number of possible nodes** that can be the root of Alice's tree_. If there is no such tree, return `0`.
**Example 1:**
**Input:** edges = \[\[0,1\],\[1,2\],\[1,3\],\[4,2\]\], guesses = \[\[1,3\],\[0,1\],\[1,0\],\[2,4\]\], k = 3
**Output:** 3
**Explanation:**
Root = 0, correct guesses = \[1,3\], \[0,1\], \[2,4\]
Root = 1, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 2, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 3, correct guesses = \[1,0\], \[2,4\]
Root = 4, correct guesses = \[1,3\], \[1,0\]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
**Example 2:**
**Input:** edges = \[\[0,1\],\[1,2\],\[2,3\],\[3,4\]\], guesses = \[\[1,0\],\[3,4\],\[2,1\],\[3,2\]\], k = 1
**Output:** 5
**Explanation:**
Root = 0, correct guesses = \[3,4\]
Root = 1, correct guesses = \[1,0\], \[3,4\]
Root = 2, correct guesses = \[1,0\], \[2,1\], \[3,4\]
Root = 3, correct guesses = \[1,0\], \[2,1\], \[3,2\], \[3,4\]
Root = 4, correct guesses = \[1,0\], \[2,1\], \[3,2\]
Considering any node as root will give at least 1 correct guess.
**Constraints:**
* `edges.length == n - 1`
* `2 <= n <= 105`
* `1 <= guesses.length <= 105`
* `0 <= ai, bi, uj, vj <= n - 1`
* `ai != bi`
* `uj != vj`
* `edges` represents a valid tree.
* `guesses[j]` is an edge of the tree.
* `guesses` is unique.
* `0 <= k <= guesses.length` | null |
[Python3] 2 BFS | count-number-of-possible-root-nodes | 0 | 1 | First, if both `[i, j]` and `[j, i]` are in `guesses`, in any case, they contribute to 1 correct guess. So, apart from these pairs, we use `s` to represent all the other guesses. We define `cnt` to be the number of correct guesses when the root is `0`.\nLet `dp[i]` be the number of correct guesses when the root is `i`. We do BFS from node `0`. Consider a parent-child pair `(i, j)`, if we change the root from `i` to `j`, only the relation between `i` and `j` changes. Then we can get the `dp[j]` from `dp[i]`.\n```\nclass Solution:\n def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int:\n n = len(edges)\n if k == 0:\n return n + 1\n s = set()\n cnt = 0\n for i, j in guesses:\n if (j, i) not in s:\n s.add((i, j))\n else:\n s.remove((j, i))\n cnt += 1\n \n g = [[] for _ in range(n + 1)]\n for i, j in edges:\n g[i].append(j)\n g[j].append(i)\n ans = 0\n q = deque([0])\n visited = [True] * (n + 1)\n visited[0] = False\n while q:\n i = q.popleft()\n for j in g[i]:\n if visited[j]:\n q.append(j)\n visited[j] = False\n if (i, j) in s:\n cnt += 1\n if cnt >= k:\n ans += 1\n \n q = deque([0])\n dp = [-1] * (n + 1)\n dp[0] = cnt\n while q:\n i = q.popleft()\n for j in g[i]:\n if dp[j] == -1:\n q.append(j)\n if (i, j) in s:\n dp[j] = dp[i] - 1\n elif (j, i) in s:\n dp[j] = dp[i] + 1\n else:\n dp[j] = dp[i]\n if dp[j] >= k:\n ans += 1\n return ans\n``` | 1 | Alice has an undirected tree with `n` nodes labeled from `0` to `n - 1`. The tree is represented as a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several **guesses** about her tree. In one guess, he does the following:
* Chooses two **distinct** integers `u` and `v` such that there exists an edge `[u, v]` in the tree.
* He tells Alice that `u` is the **parent** of `v` in the tree.
Bob's guesses are represented by a 2D integer array `guesses` where `guesses[j] = [uj, vj]` indicates Bob guessed `uj` to be the parent of `vj`.
Alice being lazy, does not reply to each of Bob's guesses, but just says that **at least** `k` of his guesses are `true`.
Given the 2D integer arrays `edges`, `guesses` and the integer `k`, return _the **number of possible nodes** that can be the root of Alice's tree_. If there is no such tree, return `0`.
**Example 1:**
**Input:** edges = \[\[0,1\],\[1,2\],\[1,3\],\[4,2\]\], guesses = \[\[1,3\],\[0,1\],\[1,0\],\[2,4\]\], k = 3
**Output:** 3
**Explanation:**
Root = 0, correct guesses = \[1,3\], \[0,1\], \[2,4\]
Root = 1, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 2, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 3, correct guesses = \[1,0\], \[2,4\]
Root = 4, correct guesses = \[1,3\], \[1,0\]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
**Example 2:**
**Input:** edges = \[\[0,1\],\[1,2\],\[2,3\],\[3,4\]\], guesses = \[\[1,0\],\[3,4\],\[2,1\],\[3,2\]\], k = 1
**Output:** 5
**Explanation:**
Root = 0, correct guesses = \[3,4\]
Root = 1, correct guesses = \[1,0\], \[3,4\]
Root = 2, correct guesses = \[1,0\], \[2,1\], \[3,4\]
Root = 3, correct guesses = \[1,0\], \[2,1\], \[3,2\], \[3,4\]
Root = 4, correct guesses = \[1,0\], \[2,1\], \[3,2\]
Considering any node as root will give at least 1 correct guess.
**Constraints:**
* `edges.length == n - 1`
* `2 <= n <= 105`
* `1 <= guesses.length <= 105`
* `0 <= ai, bi, uj, vj <= n - 1`
* `ai != bi`
* `uj != vj`
* `edges` represents a valid tree.
* `guesses[j]` is an edge of the tree.
* `guesses` is unique.
* `0 <= k <= guesses.length` | null |
[Python🤫🐍] Simple DFS with cache - 5 steps | count-number-of-possible-root-nodes | 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## - Step 1 build the Graph\nDICT of Node to List of Nodes\nSET of Nodes\n\n## - Step 2 build a set of Guesses for fast access\nSET of Tuple Edges\n\n## - Step 3 DFS \n\ninput: Node and Previous node\noutput: The number of right guesses\n\ncache all the results in order to avoid computing again\n\n## - Step 4 Try all the roots \nTry all the roots and if the returned number of guesses is greater than k. Add 1 to the total.\n\n## - Step 5 Return the Result\nReturn the total\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N + E) where N is the number of nodes, E is the number of edges\n\nWe only visit each node and edge a constant number of times\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int:\n\n \n \n\n # Step 1 build the graph\n\n #contains all the edges\n # 0 -> 1,2,3 Node to list of Nodes\n GRAPH = defaultdict(list)\n\n #contains all the nodes\n NODES = set()\n\n for e in edges:\n\n NODES.add(e[0])\n NODES.add(e[1])\n\n GRAPH[e[0]].append(e[1])\n GRAPH[e[1]].append(e[0])\n\n ## Step 2 build a set of Guesses for fast access\n\n #contains all the guesses\n GUESSES = set()\n\n #contains all the edges of the nodes\n for e in guesses:\n GUESSES.add((e[0],e[1]))\n\n\n #visited set\n visited = set()\n\n # Step 3 DFS\n #cache the result with the node and previous\n @cache\n def dfs(node:int, previous:int) -> int:\n\n # count the number of right guesses\n guess_count = 0\n\n if (previous,node) in GUESSES:\n guess_count+=1\n\n # add node to visited set\n visited.add(node)\n\n for next_node in GRAPH[node]:\n\n if next_node not in visited:\n guess_count += dfs(next_node,node)\n\n return guess_count\n \n # Step 4 Try all the roots\n\n result = 0\n\n for node in NODES:\n #if the root has k guesses, add 1 to the result\n if dfs(node,-1) >= k:\n result+=1\n visited = set()\n\n # Step 5 Return the result\n return result\n\n \n``` | 5 | Alice has an undirected tree with `n` nodes labeled from `0` to `n - 1`. The tree is represented as a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several **guesses** about her tree. In one guess, he does the following:
* Chooses two **distinct** integers `u` and `v` such that there exists an edge `[u, v]` in the tree.
* He tells Alice that `u` is the **parent** of `v` in the tree.
Bob's guesses are represented by a 2D integer array `guesses` where `guesses[j] = [uj, vj]` indicates Bob guessed `uj` to be the parent of `vj`.
Alice being lazy, does not reply to each of Bob's guesses, but just says that **at least** `k` of his guesses are `true`.
Given the 2D integer arrays `edges`, `guesses` and the integer `k`, return _the **number of possible nodes** that can be the root of Alice's tree_. If there is no such tree, return `0`.
**Example 1:**
**Input:** edges = \[\[0,1\],\[1,2\],\[1,3\],\[4,2\]\], guesses = \[\[1,3\],\[0,1\],\[1,0\],\[2,4\]\], k = 3
**Output:** 3
**Explanation:**
Root = 0, correct guesses = \[1,3\], \[0,1\], \[2,4\]
Root = 1, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 2, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 3, correct guesses = \[1,0\], \[2,4\]
Root = 4, correct guesses = \[1,3\], \[1,0\]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
**Example 2:**
**Input:** edges = \[\[0,1\],\[1,2\],\[2,3\],\[3,4\]\], guesses = \[\[1,0\],\[3,4\],\[2,1\],\[3,2\]\], k = 1
**Output:** 5
**Explanation:**
Root = 0, correct guesses = \[3,4\]
Root = 1, correct guesses = \[1,0\], \[3,4\]
Root = 2, correct guesses = \[1,0\], \[2,1\], \[3,4\]
Root = 3, correct guesses = \[1,0\], \[2,1\], \[3,2\], \[3,4\]
Root = 4, correct guesses = \[1,0\], \[2,1\], \[3,2\]
Considering any node as root will give at least 1 correct guess.
**Constraints:**
* `edges.length == n - 1`
* `2 <= n <= 105`
* `1 <= guesses.length <= 105`
* `0 <= ai, bi, uj, vj <= n - 1`
* `ai != bi`
* `uj != vj`
* `edges` represents a valid tree.
* `guesses[j]` is an edge of the tree.
* `guesses` is unique.
* `0 <= k <= guesses.length` | null |
✔️ Python3 Solution | DFS | Clean & Concise | count-number-of-possible-root-nodes | 0 | 1 | # Approach\nLet assume an arrow which is from child to parent (v -> u), now if you traverse from a node (let say root) to every node and encounter k incoming arrows (->) then the root is possible else not.\nFor optimizing, we count the incoming arrows for 0 (call it value), and then apply dfs, if encounter incoming arrows (which now will be out going) subtract 1 and similarly for outgoing arrows(which now will be ingoing) add 1, if the value >= k, then the current node can be root else not.\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def rootCount(self, E, G, k):\n n = len(E)\n G = set(map(tuple, G))\n graph = [[] for _ in range(n + 1)]\n for a, b in E:\n graph[a].append(b)\n graph[b].append(a)\n def count(node, parent):\n val = 0\n for i in graph[node]:\n if i == parent: continue\n if (node, i) in G: val += 1\n val += count(i, node)\n return val\n def dfs(node, parent, val):\n ans = 0\n if val >= k: ans += 1\n for i in graph[node]:\n if i == parent: continue\n cur = val - (1 if (node, i) in G else 0) + (1 if (i, node) in G else 0)\n ans += dfs(i, node, cur)\n return ans\n return dfs(0, -1, count(0, -1))\n``` | 2 | Alice has an undirected tree with `n` nodes labeled from `0` to `n - 1`. The tree is represented as a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several **guesses** about her tree. In one guess, he does the following:
* Chooses two **distinct** integers `u` and `v` such that there exists an edge `[u, v]` in the tree.
* He tells Alice that `u` is the **parent** of `v` in the tree.
Bob's guesses are represented by a 2D integer array `guesses` where `guesses[j] = [uj, vj]` indicates Bob guessed `uj` to be the parent of `vj`.
Alice being lazy, does not reply to each of Bob's guesses, but just says that **at least** `k` of his guesses are `true`.
Given the 2D integer arrays `edges`, `guesses` and the integer `k`, return _the **number of possible nodes** that can be the root of Alice's tree_. If there is no such tree, return `0`.
**Example 1:**
**Input:** edges = \[\[0,1\],\[1,2\],\[1,3\],\[4,2\]\], guesses = \[\[1,3\],\[0,1\],\[1,0\],\[2,4\]\], k = 3
**Output:** 3
**Explanation:**
Root = 0, correct guesses = \[1,3\], \[0,1\], \[2,4\]
Root = 1, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 2, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 3, correct guesses = \[1,0\], \[2,4\]
Root = 4, correct guesses = \[1,3\], \[1,0\]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
**Example 2:**
**Input:** edges = \[\[0,1\],\[1,2\],\[2,3\],\[3,4\]\], guesses = \[\[1,0\],\[3,4\],\[2,1\],\[3,2\]\], k = 1
**Output:** 5
**Explanation:**
Root = 0, correct guesses = \[3,4\]
Root = 1, correct guesses = \[1,0\], \[3,4\]
Root = 2, correct guesses = \[1,0\], \[2,1\], \[3,4\]
Root = 3, correct guesses = \[1,0\], \[2,1\], \[3,2\], \[3,4\]
Root = 4, correct guesses = \[1,0\], \[2,1\], \[3,2\]
Considering any node as root will give at least 1 correct guess.
**Constraints:**
* `edges.length == n - 1`
* `2 <= n <= 105`
* `1 <= guesses.length <= 105`
* `0 <= ai, bi, uj, vj <= n - 1`
* `ai != bi`
* `uj != vj`
* `edges` represents a valid tree.
* `guesses[j]` is an edge of the tree.
* `guesses` is unique.
* `0 <= k <= guesses.length` | null |
【C++|Python】once dfs | count-number-of-possible-root-nodes | 0 | 1 | > **I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.**\n\n> **In addition, I\'m too weak, please be critical of my ideas.**\n---\n\n# Intuition\n1. Think about these 2 questions:\n - What happens if we point a special vertex as the root?\n - How does the situation change when we select another vertex from the root\'s children as the new root?\n2. For the first question, we can use a dfs to count correct pairs in `guesses` and determine the father-child relationship of the tree.\n3. For the second question, once we reroot from $x$ to its child $c$, we can easily find the only change is edge from $x$ to $c$. It will change the correct count.\n - **If there is a right guess from $x$ to $c$, the change will break this correctness. So the correct count should be decremented by 1.**\n - **If there is a wrong guess from $x$ to $c$, the change will fix this wrong. So the correct count should be incremented by 1.**\n \n4. Travel from father to its children, record and update $d$ as the difference between the $0$-rooted tree and $x$-rooted tree. \n Suppose the $0$-rooted tree has $cnt$ right pairs, so the $x$-rooted tree has $cnt+d$ right pairs. \n All the $cnt+d \\geq k$ will be the answer.\n\n# Approach\n- Notice that in the first dfs, we don\'t know the $cnt$. So we consider to record the count of $d$ for every $x$-rooted tree in a $mp$, and calculate the $cnt$ in one dfs.\n\n- After dfs, we enumerate $mp$ and count the answer. So that we can use one dfs to solve the problem.\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(n)$\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n int rootCount(vector<vector<int>>& edges, vector<vector<int>>& guesses, int k) {\n vector<vector<int>> g(edges.size() + 1);\n for (auto &e: edges) {\n g[e[0]].push_back(e[1]);\n g[e[1]].push_back(e[0]);\n }\n vector<unordered_map<int, int>> gu(edges.size() + 1);\n for (auto &e: guesses)\n gu[e[0]][e[1]]++;\n unordered_map<int, int> mp;\n // cnt is the correct pairs of guesses on 0-rooted tree\n int cnt = 0;\n // fa is father of x, d is the difference from the 0-rooted \n function<void(int, int, int)> dfs = [&](int x, int fa, int d) -> void {\n mp[d]++;\n for (int c: g[x]) {\n if (c == fa) continue;\n cnt += gu[x][c];\n dfs(c, x, d + gu[c][x] - gu[x][c]);\n }\n };\n dfs(0, -1, 0);\n return accumulate(mp.begin(), mp.end(), 0, [&](int s, auto p) -> int {\n return s + p.second * (p.first + cnt >= k);\n });\n }\n};\n```\n``` Python []\nclass Solution:\n def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int:\n g = [set() for i in range(len(edges) + 1)]\n for e in edges:\n g[e[0]].add(e[1])\n g[e[1]].add(e[0])\n gu = [defaultdict(int) for i in range(len(edges) + 1)]\n for e in guesses:\n gu[e[0]][e[1]] += 1\n mp = defaultdict(int)\n # cnt is the correct pairs of guesses on 0-rooted tree\n cnt = 0\n # fa is father of x, d is the difference from the 0-rooted \n def dfs(x, fa, d):\n nonlocal cnt\n mp[d] += 1\n for c in g[x] - {fa}:\n cnt += gu[x][c]\n dfs(c, x, d + gu[c][x] - gu[x][c])\n dfs(0, -1, 0)\n return sum(v * (d + cnt >= k) for d,v in mp.items())\n``` | 8 | Alice has an undirected tree with `n` nodes labeled from `0` to `n - 1`. The tree is represented as a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several **guesses** about her tree. In one guess, he does the following:
* Chooses two **distinct** integers `u` and `v` such that there exists an edge `[u, v]` in the tree.
* He tells Alice that `u` is the **parent** of `v` in the tree.
Bob's guesses are represented by a 2D integer array `guesses` where `guesses[j] = [uj, vj]` indicates Bob guessed `uj` to be the parent of `vj`.
Alice being lazy, does not reply to each of Bob's guesses, but just says that **at least** `k` of his guesses are `true`.
Given the 2D integer arrays `edges`, `guesses` and the integer `k`, return _the **number of possible nodes** that can be the root of Alice's tree_. If there is no such tree, return `0`.
**Example 1:**
**Input:** edges = \[\[0,1\],\[1,2\],\[1,3\],\[4,2\]\], guesses = \[\[1,3\],\[0,1\],\[1,0\],\[2,4\]\], k = 3
**Output:** 3
**Explanation:**
Root = 0, correct guesses = \[1,3\], \[0,1\], \[2,4\]
Root = 1, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 2, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 3, correct guesses = \[1,0\], \[2,4\]
Root = 4, correct guesses = \[1,3\], \[1,0\]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
**Example 2:**
**Input:** edges = \[\[0,1\],\[1,2\],\[2,3\],\[3,4\]\], guesses = \[\[1,0\],\[3,4\],\[2,1\],\[3,2\]\], k = 1
**Output:** 5
**Explanation:**
Root = 0, correct guesses = \[3,4\]
Root = 1, correct guesses = \[1,0\], \[3,4\]
Root = 2, correct guesses = \[1,0\], \[2,1\], \[3,4\]
Root = 3, correct guesses = \[1,0\], \[2,1\], \[3,2\], \[3,4\]
Root = 4, correct guesses = \[1,0\], \[2,1\], \[3,2\]
Considering any node as root will give at least 1 correct guess.
**Constraints:**
* `edges.length == n - 1`
* `2 <= n <= 105`
* `1 <= guesses.length <= 105`
* `0 <= ai, bi, uj, vj <= n - 1`
* `ai != bi`
* `uj != vj`
* `edges` represents a valid tree.
* `guesses[j]` is an edge of the tree.
* `guesses` is unique.
* `0 <= k <= guesses.length` | null |
Python DFS + DP O(N) trivial solution | count-number-of-possible-root-nodes | 0 | 1 | # Intuition\nlet n = len(edges)\nand # of correct witrh guesses is fixed if we explore from i->j (since it\'s a tree, which means there always only one path between nodes)\n\nthus we will only have 2n possible values (i->j, j<-i)\n\nand finally let we set each i as root, check how many root align with guesses >= k\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code - Version 1 (Mar 05, 2023 Ver)\nthis version only when tree is linked-list will be time O(n)\nif there are a node as center and every other node link to center it will be O(n^2)\n\n\n```\nclass Solution:\n def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int:\n # n memory\n # build graph\n graph = defaultdict(list)\n for i, j in edges:\n graph[i].append(j)\n graph[j].append(i)\n \n gt = set((i, j) for i, j in guesses)\n\n # dfs traverse from parent -> i\n @cache\n def get_correct_pairs(i, parent):\n next_nodes = graph[i]\n n_correct = 0\n for next_node in next_nodes:\n if next_node == parent:\n continue\n if (i, next_node) in gt:\n n_correct += 1\n n_correct += get_correct_pairs(next_node, i)\n return n_correct\n \n ans = 0\n for i in graph:\n if get_correct_pairs(i, None) >= k:\n ans += 1\n return ans\n \n```\n\n\n# Code - Version 2 (Sep 25, 2023 Ver)\nthanks for @cy171\'s patiently explain I finally realize the blindspot I meet.\n\nthe optimization idea is that\n```\nf(i, next) = f_sum_out(next) - f(next, i)\nf_sum_out(j) = sum(f(j, i) for all i in graph[j]) \n```\n\nthe only change is add a map `graph_out_sum` used to calculate the out direction sum.\n\n```\nclass Solution:\n def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int:\n # build graph\n graph = defaultdict(list)\n for i, j in edges:\n graph[i].append(j)\n graph[j].append(i)\n \n gt = set((i, j) for i, j in guesses)\n\n graph_added = defaultdict(set)\n graph_out_sum = defaultdict(int)\n\n # random traverse \n @cache\n def get_correct_pairs(i, parent):\n next_nodes = graph[i]\n if len(graph_added[i]) == next_nodes:\n return graph_out_sum[i] - get_correct_pairs(i, parent)\n else:\n n_correct = 0\n for next_node in next_nodes:\n if next_node == parent:\n continue\n if (i, next_node) in gt:\n graph_out_sum[i] += 1\n n_correct += 1\n\n n_correct += get_correct_pairs(next_node, i)\n graph_out_sum[i] += get_correct_pairs(next_node, i)\n graph_added[i].add((next_node, i))\n \n return n_correct\n \n ans = 0\n for i in graph:\n if get_correct_pairs(i, None) >= k:\n ans += 1\n return ans\n \n \n``` | 17 | Alice has an undirected tree with `n` nodes labeled from `0` to `n - 1`. The tree is represented as a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several **guesses** about her tree. In one guess, he does the following:
* Chooses two **distinct** integers `u` and `v` such that there exists an edge `[u, v]` in the tree.
* He tells Alice that `u` is the **parent** of `v` in the tree.
Bob's guesses are represented by a 2D integer array `guesses` where `guesses[j] = [uj, vj]` indicates Bob guessed `uj` to be the parent of `vj`.
Alice being lazy, does not reply to each of Bob's guesses, but just says that **at least** `k` of his guesses are `true`.
Given the 2D integer arrays `edges`, `guesses` and the integer `k`, return _the **number of possible nodes** that can be the root of Alice's tree_. If there is no such tree, return `0`.
**Example 1:**
**Input:** edges = \[\[0,1\],\[1,2\],\[1,3\],\[4,2\]\], guesses = \[\[1,3\],\[0,1\],\[1,0\],\[2,4\]\], k = 3
**Output:** 3
**Explanation:**
Root = 0, correct guesses = \[1,3\], \[0,1\], \[2,4\]
Root = 1, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 2, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 3, correct guesses = \[1,0\], \[2,4\]
Root = 4, correct guesses = \[1,3\], \[1,0\]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
**Example 2:**
**Input:** edges = \[\[0,1\],\[1,2\],\[2,3\],\[3,4\]\], guesses = \[\[1,0\],\[3,4\],\[2,1\],\[3,2\]\], k = 1
**Output:** 5
**Explanation:**
Root = 0, correct guesses = \[3,4\]
Root = 1, correct guesses = \[1,0\], \[3,4\]
Root = 2, correct guesses = \[1,0\], \[2,1\], \[3,4\]
Root = 3, correct guesses = \[1,0\], \[2,1\], \[3,2\], \[3,4\]
Root = 4, correct guesses = \[1,0\], \[2,1\], \[3,2\]
Considering any node as root will give at least 1 correct guess.
**Constraints:**
* `edges.length == n - 1`
* `2 <= n <= 105`
* `1 <= guesses.length <= 105`
* `0 <= ai, bi, uj, vj <= n - 1`
* `ai != bi`
* `uj != vj`
* `edges` represents a valid tree.
* `guesses[j]` is an edge of the tree.
* `guesses` is unique.
* `0 <= k <= guesses.length` | null |
Traverse with Memoisation | count-number-of-possible-root-nodes | 0 | 1 | We use an adjacency list (undirected), tracking weight of each edge (initially zero).\n\nFor directed edges from `guesses`, we set weight to be `1`.\n\nThen, we pick a node as a root node, and traverse from that node and sum the weights. The result is the number of correct guesses for that node.\n\nWe repeat this for each node. For O(n) solution, we memoise the result for each directed edge `u` -> `v`.\n\nFinally, we count nodes that have `k` or more correct guesses.\n\n**Python 3**\n```python\nclass Solution:\n def rootCount(self, edges: List[List[int]], guesses: List[List[int]], k: int) -> int:\n @cache\n def dfs(u: int, v: int) -> int:\n res = 0\n for w, score in al[v].items():\n res += score + dfs(v, w) if w != u else 0\n return res\n al = [{} for _ in range(len(edges) + 1)]\n for a, b in edges:\n al[a][b] = al[b][a] = 0\n for u, v in guesses:\n al[u][v] = 1\n return sum(1 if dfs(-1, u) >= k else 0 for u in range(len(edges) + 1))\n``` | 9 | Alice has an undirected tree with `n` nodes labeled from `0` to `n - 1`. The tree is represented as a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree.
Alice wants Bob to find the root of the tree. She allows Bob to make several **guesses** about her tree. In one guess, he does the following:
* Chooses two **distinct** integers `u` and `v` such that there exists an edge `[u, v]` in the tree.
* He tells Alice that `u` is the **parent** of `v` in the tree.
Bob's guesses are represented by a 2D integer array `guesses` where `guesses[j] = [uj, vj]` indicates Bob guessed `uj` to be the parent of `vj`.
Alice being lazy, does not reply to each of Bob's guesses, but just says that **at least** `k` of his guesses are `true`.
Given the 2D integer arrays `edges`, `guesses` and the integer `k`, return _the **number of possible nodes** that can be the root of Alice's tree_. If there is no such tree, return `0`.
**Example 1:**
**Input:** edges = \[\[0,1\],\[1,2\],\[1,3\],\[4,2\]\], guesses = \[\[1,3\],\[0,1\],\[1,0\],\[2,4\]\], k = 3
**Output:** 3
**Explanation:**
Root = 0, correct guesses = \[1,3\], \[0,1\], \[2,4\]
Root = 1, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 2, correct guesses = \[1,3\], \[1,0\], \[2,4\]
Root = 3, correct guesses = \[1,0\], \[2,4\]
Root = 4, correct guesses = \[1,3\], \[1,0\]
Considering 0, 1, or 2 as root node leads to 3 correct guesses.
**Example 2:**
**Input:** edges = \[\[0,1\],\[1,2\],\[2,3\],\[3,4\]\], guesses = \[\[1,0\],\[3,4\],\[2,1\],\[3,2\]\], k = 1
**Output:** 5
**Explanation:**
Root = 0, correct guesses = \[3,4\]
Root = 1, correct guesses = \[1,0\], \[3,4\]
Root = 2, correct guesses = \[1,0\], \[2,1\], \[3,4\]
Root = 3, correct guesses = \[1,0\], \[2,1\], \[3,2\], \[3,4\]
Root = 4, correct guesses = \[1,0\], \[2,1\], \[3,2\]
Considering any node as root will give at least 1 correct guess.
**Constraints:**
* `edges.length == n - 1`
* `2 <= n <= 105`
* `1 <= guesses.length <= 105`
* `0 <= ai, bi, uj, vj <= n - 1`
* `ai != bi`
* `uj != vj`
* `edges` represents a valid tree.
* `guesses[j]` is an edge of the tree.
* `guesses` is unique.
* `0 <= k <= guesses.length` | null |
Subsets and Splits