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 a...
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) = (...
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 a...
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(ve...
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 a...
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...
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 a...
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 a...
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...
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 a...
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...
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 a...
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...
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 ...
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 ro...
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 ...
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]...
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 ...
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 arr...
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 ...
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 P...
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 ...
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 ...
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 **a...
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 ...
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 **a...
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)$$ --...
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 **a...
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.key...
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 **a...
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 ...
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 **a...
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 ...
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 **a...
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$$ ...
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 **a...
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 0...
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 *...
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 ...
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 *...
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 ...
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 *...
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 ...
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 *...
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<<...
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 o...
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 m...
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 o...
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 ret...
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 o...
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 ab...
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 o...
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 ...
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 o...
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 th...
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 o...
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 ...
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 o...
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 t...
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 o...
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]. \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...
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\nH...
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...
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(...
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...
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. Simultane...
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...
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 ...
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...
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 ...
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...
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 ...
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...
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 mea...
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...
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)$$ --...
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...
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 st...
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...
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__(sel...
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...
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 ...
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...
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 ...
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...
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)$$ --...
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] = ...
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 ...
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] = ...
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)$$ --...
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] = ...
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] = ...
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\tclas...
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] = ...
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```...
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] = ...
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 ...
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] = ...
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] = ...
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...
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 _...
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 ...
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 _...
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 ...
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 _...
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 ...
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 _...
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 ...
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 _...
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...
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 _...
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 fo...
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 _...
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 bet...
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 ...
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 ...
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 ...
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 ti...
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 ...
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 ...
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 ...
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...
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 ...
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 valu...
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 ...
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,...
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 ...
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 = heapp...
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 ...
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 th...
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 ...
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 *...
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 ...
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)$$ --...
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 ...
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 s...
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 ...
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 ...
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 ...
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```\nc...
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 ...
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...
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 ...
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 ...
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 ...
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 ...
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 +...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 t...
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 ...
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)$$ --...
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 ...
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...
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 ...
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 ...
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 *...
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\ncla...
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 *...
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 &...
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 *...
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[Lis...
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 *...
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 ...
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 *...
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 ...
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 *...
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...
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 *...
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 consid...
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 *...
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...
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 *...
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* ...
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 seve...
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`....
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 seve...
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...
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 seve...
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 arr...
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 seve...
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 situ...
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 seve...
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...
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 seve...
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 e...
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 seve...
null