title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
643 values
level
stringclasses
3 values
question_hints
stringclasses
869 values
view_count
int64
19
630k
vote_count
int64
5
3.67k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Redistribute Characters to Make All Strings Equal
redistribute-characters-to-make-all-strings-equal
You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make every string in words equal using any number of operations, and false otherwise.
Hash Table,String,Counting
Easy
Characters are independent—only the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.
1,977
17
```\nclass Solution:\n def makeEqual(self, words: List[str]) -> bool:\n map_ = {}\n for word in words:\n for i in word:\n if i not in map_:\n map_[i] = 1\n else:\n map_[i] += 1\n n = len(words)\n for k,v in map_.items():\n if (v%n) != 0:\n return False\n return True\n```
97,133
Redistribute Characters to Make All Strings Equal
redistribute-characters-to-make-all-strings-equal
You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make every string in words equal using any number of operations, and false otherwise.
Hash Table,String,Counting
Easy
Characters are independent—only the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.
1,155
21
eg --> words = ["abc","aabc","bcc"]\n\n* stp1) join --> "abcaabcbc"\n* stp2) set --> {\'b\', \'a\', \'c\'}\n* stp3) joint.count(\'b\') = 3 , joint.count(\'a\') = 3 , joint.count(\'c\') = 4\n* stp4) as joint.count(\'c\') = 4 therefore it is not multiple of len(words)--->[here 3]\n\tif joint.count(i) % len(words) != 0 : return False\n* \tif joint.count(\'c\') >len(words) and also multiple of len(words) , then also it will work coz we can distribute all \'c\' equally in all the substrings, therfore we are using (%), for eg if count(c) = 6 then we we can distribute \'c\' like [\'....cc\',\'....cc\',\'...cc\']\n\n\n\n**44 ms, faster than 98.48%**\n```\nclass Solution:\n def makeEqual(self, words: List[str]) -> bool:\n \n joint = \'\'.join(words)\n set1 = set(joint)\n \n for i in set1 :\n if joint.count(i) % len(words) != 0 : return False \n return True\n```\n\n**56 ms, faster than 85.81%**\n```\nclass Solution:\n def makeEqual(self, words: List[str]) -> bool:\n \n joint = \'\'.join(words)\n dic = {}\n \n for i in joint :\n if i not in dic :\n dic[i] = joint.count(i)\n \n for v in dic.values() :\n if v % len(words) != 0 : return False \n return True\n```\n\n\n**plz upvote if u like : )**
97,134
Redistribute Characters to Make All Strings Equal
redistribute-characters-to-make-all-strings-equal
You are given an array of strings words (0-indexed). In one operation, pick two distinct indices i and j, where words[i] is a non-empty string, and move any character from words[i] to any position in words[j]. Return true if you can make every string in words equal using any number of operations, and false otherwise.
Hash Table,String,Counting
Easy
Characters are independent—only the frequency of characters matters. It is possible to distribute characters if all characters can be divided equally among all strings.
368
5
Idea: For each word count the number of letters together in a hashmap/array.\nE.g.: words = [\'abc\',\'aabc\',\'bc\']\nHashmap = [\'a\' : 3, \'b\': 3, \'c\': 3]\n\nNow, if every string in words are made to be equal, tehn count of every letter in hashmap must be divisible by the length of words, otherwise atleast one letter will be extra in one word.\nE.g: words = [\'abcc\',\'aabc\',\'bc\']\nHashmap = [\'a\' : 3, \'b\': 3, \'c\': 4]\nHere, \'abc\' will be present in all the strings but one extra \'c\' will be with atleast one of them, like [\'abcc\',\'abc\',\'abc] or [\'abc\',abcc\',\'abc\'] or [\'abc\',\'abc\',\'abcc\']...\n\nSo, calculate the hashmap and check if any element in hashmap is not exactly divisible by the number of words.\n```\nclass Solution:\n def makeEqual(self, words: List[str]) -> bool:\n def indx(x):\n return ord(x) - ord(\'a\')\n \n hashmap = [0]*26\n for word in words:\n for c in word:\n hashmap[indx(c)]+=1\n \n n = len(words)\n \n for i in range(26):\n if hashmap[i]%n != 0:\n return False\n return True\n```\nTime: O(n) for iterating through each word in words and O(n) for iterating through each character in a word = O(n^2)\nSpace: Constant as we are using a hashmap of fixed size (26).\n\n
97,143
Maximum Number of Removable Characters
maximum-number-of-removable-characters
You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Array,String,Binary Search
Medium
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
163
6
```python3 []\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n l, r = 0, len(removable)\n\n def isEnough(k):\n s_arr = list(s)\n for i in removable[:k]:\n s_arr[i] = \'\'\n return isSubsequence(p, s_arr)\n \n def isSubsequence(s, t):\n t = iter(t)\n return all(c in t for c in s)\n\n while l < r:\n m = (l+r+1)//2\n if isEnough(m):\n l = m\n else:\n r = m - 1\n \n return l\n```\n![Screenshot 2023-07-15 at 23.39.25.png]()\n
97,231
Maximum Number of Removable Characters
maximum-number-of-removable-characters
You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Array,String,Binary Search
Medium
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
2,866
29
**Idea**\nBinary Search `k` in interval `[0, r)`, where `r` = `len(removable)`\nFor each `mid`, check if `removable[:mid+1]` could make `p` a subsequence of `s`.\nIf True, `k` could be larger, so we search in the right half; else, search in the left half.\n\n**Complexity**\nTime: `O((p+s+r) * logr)`\nSpace: `O(r)`\nwhere `r` = `len(removable)`; `p` = `len(p)`; `s` = `len(s)`.\n\n**Python**\n```\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n \n def check(m):\n i = j = 0\n remove = set(removable[:m+1])\n while i < len(s) and j < len(p):\n if i in remove:\n i += 1\n continue\n if s[i] == p[j]:\n i += 1\n j += 1\n else:\n i += 1\n \n return j == len(p)\n \n \n # search interval is [lo, hi)\n lo, hi = 0, len(removable)+1\n \n while lo < hi:\n mid = (lo + hi) // 2\n if check(mid):\n lo = mid + 1\n else:\n hi = mid\n \n return lo if lo < len(removable) else lo-1\n```\n\n**Optimization**\nIt is expensive to do `remove = set(removable[:m+1])` repeatedly, see [@AlkhanZi \'s post]() below on how to speed it up.\n
97,238
Maximum Number of Removable Characters
maximum-number-of-removable-characters
You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Array,String,Binary Search
Medium
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
1,099
13
\n```\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n mp = {x: i for i, x in enumerate(removable)}\n \n def fn(x):\n """Return True if p is a subseq of s after x removals."""\n k = 0 \n for i, ch in enumerate(s): \n if mp.get(i, inf) < x: continue \n if k < len(p) and ch == p[k]: k += 1\n return k == len(p)\n \n lo, hi = -1, len(removable)\n while lo < hi: \n mid = lo + hi + 1 >> 1\n if fn(mid): lo = mid\n else: hi = mid - 1\n return lo \n```
97,244
Maximum Number of Removable Characters
maximum-number-of-removable-characters
You are given two strings s and p where p is a subsequence of s. You are also given a distinct 0-indexed integer array removable containing a subset of indices of s (s is also 0-indexed). You want to choose an integer k (0 <= k <= removable.length) such that, after removing k characters from s using the first k indices in removable, p is still a subsequence of s. More formally, you will mark the character at s[removable[i]] for each 0 <= i < k, then remove all marked characters and check if p is still a subsequence. Return the maximum k you can choose such that p is still a subsequence of s after the removals. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Array,String,Binary Search
Medium
First, we need to think about solving an easier problem, If we remove a set of indices from the string does P exist in S as a subsequence We can binary search the K and check by solving the above problem.
710
7
```\nclass Solution:\n def maximumRemovals(self, s: str, p: str, removable: List[int]) -> int:\n l, r = 0, len(removable)\n while l <= r:\n m = (l + r) >> 1\n d = set(removable[:m])\n i, j = 0, 0\n while i < len(s) and j < len(p):\n if i not in d:\n if s[i] == p[j]:\n j += 1\n i += 1\n \n if j == len(p):\n l = m + 1\n else:\n r = m - 1\n return r\n```
97,252
The Earliest and Latest Rounds Where Players Compete
the-earliest-and-latest-rounds-where-players-compete
There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.
Dynamic Programming,Memoization
Hard
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
1,493
20
This greedy code can handle n up to 1e18. No iteration over choices, no min() or max() used. \nHowever, the solution is hard to explain. Sorry, have to leave it for you guys to understand.\n```py\nclass Solution(object):\n def earliestAndLatest(self, n, a, b):\n """\n :type n: int\n :type firstPlayer: int\n :type secondPlayer: int\n :rtype: List[int]\n """\n def simplify(n, a, b):\n # swap\n if a>b: a, b = b, a\n # flip\n if a+b >= n+1:\n a, b = n+1-b, n+1-a\n return n, a, b\n \n def get_info(n,a,b):\n ll, rr = a-1, n-b\n aa = n-ll\n bb = 1+rr\n return ll,rr,aa,bb\n\n def while_loop(n, a, b):\n ans = 1\n while a+b < n+1:\n n = (n+1)/2\n ans += 1\n if b-a-1==0:\n while n%2:\n n = (n+1)/2\n ans += 1\n return ans\n\n def solve_fast(n, a, b):\n n, a, b = simplify(n, a, b)\n if a+b == n+1: \n return 1\n\n # b is on the left, including center\n if b <= (n+1)/2:\n return while_loop(n, a, b)\n \n # b is on the right\n ll, rr, aa, bb = get_info(n, a, b)\n if (ll%2==1 and bb-a-1==0):\n if (n%2==0) and (b == n/2+1): \n return 1 + while_loop((n+1)/2, a, a+1)\n else:\n return 3\n else:\n return 2\n\n def solve_slow(n, a, b):\n n, a, b = simplify(n, a, b)\n if a+b==n+1: \n return 1\n # b is in the left, all can be deleted\n if b <= n+1-b: \n return 1+solve_slow((n+1)/2, 1, 2)\n else:\n # b is in the right\n ll, rr, aa, bb = get_info(n, a, b)\n keep = (b-bb-1)/2 + n%2\n return 1+solve_slow((n+1)/2, 1, 1+keep+1) \n\n return [solve_fast(n,a,b), solve_slow(n,a,b)]\n```\t\t
97,279
The Earliest and Latest Rounds Where Players Compete
the-earliest-and-latest-rounds-where-players-compete
There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.
Dynamic Programming,Memoization
Hard
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
949
12
**Idea**\nI was heavily inspired by @wisdompeak\'s [`O(log n)` greedy recursive solution]((N)-solution), and looked for more patterns and how to eliminate all the recursive calls and loops. \n\nThis problem turns out to have a pretty simple solution. A key insight also came from @alanlzl\'s post: we can assume that `first` is closer to the left than `second` is to the right.\n\n1. **Finding Latest**: The optimal strategy for getting the latest round is to push `first` and `second` into positions 1 and 2, so all players left of \'second\' should try to lose. This is always possible to do if `second` is left of or at the middle, after which we return the most significant bit of n (rounds left). If `second` is close to the right edge, we can\'t push it to position 2, and `first` will eliminate at least one player to the right of `second` each round.\n\n2. **Finding Earliest**: It\'s usually possible to win in around 2-3 rounds. This is intuitive by the huge amount of control we have for where `first` and `second` will go in the next round, especially if there are many spaces between `first` and `second`. However, the position of each player only moves left, so we may need to wait some rounds for the midpoint of our player list to fall between `first` and `second`, in which case all players left of `second` should try to win.\n\n**Complexity**\nAssuming that we can read the number of trailing zeroes and leading zeroes from `n` in `O(1)` time, e.g. with the builtin assembly functions, there are a fixed number of operations. There\'s no recursion or loops (and both versions can be done without any function calls), and our only memory usage is 2 or 3 ints. \n* Time complexity: `O(1)` if `n` fits in a machine word / 64 bits\n* Space complexity: `O(1)`\n\t\n\n**C++:**\n\n```c++\nclass Solution {\npublic:\n vector<int> earliestAndLatest(int n, int first, int second) {\n if (first + second == n + 1) return {1, 1};\n if (first + second > n + 1) tie(first, second) = make_tuple(n+1-second, n+1-first);\n \n int ans_earliest = 1, ans_latest = min(32 - __builtin_clz(n-1), n+1-second);\n if (first + second==n){\n if (first % 2 == 0) ans_earliest = first+2 < second? 2: 1 + __builtin_ctz(first);\n }\n else if (first+1 == second){\n ans_earliest = 32 - __builtin_clz((n-1) / (first+second-1));\n ans_earliest += __builtin_ctz((n-1)>>ans_earliest);\n }\n else if (first+second <= (n+1)/2) ans_earliest = 32 - __builtin_clz((n-1) / (first+second-1));\n return {ans_earliest+1, ans_latest};\n }\n};\n```\n\nSome more insight:\n\n* One trick used repeatedly is that the number of players transforms as: `n -> (n+1) / 2` every round. This means that the number of rounds by the time `n` becomes 2 is `ceiling(log_2(n))`, at which point the game ends. `ceiling(log_2(n))` can be computed efficiently as `# of bits in an int (32) - leading zeros(n-1)`. \n* This line requires special attention:\n```python\n# We want to know the number of rounds left until first + second >= n+1. \n# By the game rules, this is the minimum value of \n# k >= 0 such that ceiling(n / 2^k) < first + second.\n# With some rearranging, this becomes \nrounds_left = ceiling_of_log2((n + first + second - 2) // (first + second - 1))\n```\n\n\nMost of the Python code is just the bitwise implementations of C++ builtins/ assembly operations, working for up to 32 bit ints, as well as many comments. If `2**31 < n < 2**64`, a single extra line is required for these functions. These are fairly common; I found these 3 functions in a textbook. If `n` is tiny and needs much fewer than `32` bits, it\'s faster to just loop over the bits.\n\nI wrote out a full proof for each of the cases, but the \'earliest\' case is quite long. The key idea is to treat the problem as having 3 boxes, left, middle, and right, and trying to allocate an equal number of players into the left and right boxes. We get a choice of distributing `first-1` players to either the left or right boxes. If `second` is at or right of the midpoint, we also get `n-first-second` players to place in the middle or right boxes, and so we can make the left and right boxes equal in 2 or 3 rounds, at which point we\'ve won if `first+1 != second`. If `second` is left of the midpoint, we only get `second-first-1` players to place in the middle or right boxes, which means the right box will end up larger than the left box. So we use induction to show that the optimal placement is having all `first-1` players left of `first` win their games, and all players between `first` and `second` try to win their games, minimizing the difference between right and left.\n\n**Python:**\n```python\nclass Solution:\n\tdef earliestAndLatest(self, n: int, first: int, second: int) -> List[int]:\n\t\tdef ceiling_of_log2(x: int) -> int:\n\t\t\t""" Return the ceiling of the integer log 2, i.e. index(MSB) - 1 + (1 if x not pow2) """\n\t\t\tassert 0 < x < 0x100000000\n\t\t\t# Use power of 2 test. offset is 1 iff x is NOT a power of 2\n\t\t\toffset = 1 if (x & (x - 1)) != 0 else 0\n\t\t\tx |= (x >> 1)\n\t\t\tx |= (x >> 2)\n\t\t\tx |= (x >> 4)\n\t\t\tx |= (x >> 8)\n\t\t\tx |= (x >> 16)\n\t\t\t# Remove offset to get floor_of_log2. floor(log2(x)) + 1 == ceil(log2(x)) iff x not a power of 2.\n\t\t\treturn popcount(x) - 1 + offset\n\n\t\tdef popcount(x: int) -> int:\n\t\t\t""" Return the number of set bits in 32 bit unsigned x (Hamming weight) """\n\t\t\tassert 0 <= x < 0x100000000\n\t\t\tx = x - ((x >> 1) & 0x55555555)\n\t\t\tx = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n\t\t\treturn (((x + (x >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24\n\n\t\tdef count_trailing_zeroes(x: int) -> int:\n\t\t\t""" Return the number of trailing zeroes in 32 bit unsigned x > 0 (LSB + 1). This method is similar to\n\t\t\t\tbranchless binary search, but there are many other methods using the integer log2"""\n\t\t\tassert 0 < x < 0x100000000\n\t\t\tif x & 0x1: return 0 # odd x, quick break\n\t\t\tc = 1\n\t\t\tif (x & 0xffff) == 0:\n\t\t\t\tx >>= 16\n\t\t\t\tc += 16\n\t\t\tif (x & 0xff) == 0:\n\t\t\t\tx >>= 8\n\t\t\t\tc += 8\n\t\t\tif (x & 0xf) == 0:\n\t\t\t\tx >>= 4\n\t\t\t\tc += 4\n\t\t\tif (x & 0x3) == 0:\n\t\t\t\tx >>= 2\n\t\t\t\tc += 2\n\t\t\treturn c - (x & 0x1)\n\n\t\t# Base case, we can return instantly\n\t\tif first + second == n + 1: return [1, 1]\n\n\t\t# This ensures that \'first\' is closer to the left than \'second\' is to the right.\n\t\t# Also, crucially ensures that the sum of first and second is minimal among equivalent configs.\n\t\tif first + second >= n + 1: first, second = n + 1 - second, n + 1 - first\n\n\t\tfirst_plus_second = first + second\n\n\t\t# Special case if first + 1 == second, since we then need to find which round will have an even # of players\n\t\tif first + 1 != second and first_plus_second >= (n + 1) // 2 + 1:\n\t\t\tif first_plus_second == n:\n\t\t\t\t# If n is 4k + 2, first is 2k, and second is 2k+2, then parity of n also matters.\n\t\t\t\tif n % 4 == 2 and first + 2 == second:\n\t\t\t\t\t# Using n // 4 instead of n//4 + 1 because trailing_zeroes(x-1) = rounds until x is even\n\t\t\t\t\tans_earliest = 3 + count_trailing_zeroes(n // 4)\n\t\t\t\telse:\n\t\t\t\t\tans_earliest = 3 - (first % 2)\n\t\t\telse:\n\t\t\t\tans_earliest = 2\n\n\t\t# If we are in a special case: Players are too far left and close together to meet next round\n\t\telse:\n\t\t\tans_earliest = 1 + ceiling_of_log2((n + first_plus_second - 2) // (first_plus_second - 1))\n\t\t\tif first + 1 == second:\n\t\t\t\tans_earliest += count_trailing_zeroes(((n + (1 << (ans_earliest-1)) - 1) >> (ans_earliest-1)) - 1)\n\n\t\t# ceiling_of_log2 of n is the number of rounds left until there are exactly 2 players remaining, starting at n.\n\t\t# This implicitly assumes that optimal strategy for ans_latest is moving \'first\' and \'second\' to pos. 1 and 2\n\t\tans_latest = min(ceiling_of_log2(n), n + 1 - second)\n\n\t\treturn [ans_earliest, ans_latest]\n```
97,282
The Earliest and Latest Rounds Where Players Compete
the-earliest-and-latest-rounds-where-players-compete
There is a tournament where n players are participating. The players are standing in a single row and are numbered from 1 to n based on their initial standing position (player 1 is the first player in the row, player 2 is the second player in the row, etc.). The tournament consists of multiple rounds (starting from round number 1). In each round, the ith player from the front of the row competes against the ith player from the end of the row, and the winner advances to the next round. When the number of players is odd for the current round, the player in the middle automatically advances to the next round. After each round is over, the winners are lined back up in the row based on the original ordering assigned to them initially (ascending order). The players numbered firstPlayer and secondPlayer are the best in the tournament. They can win against any other player before they compete against each other. If any two other players compete against each other, either of them might win, and thus you may choose the outcome of this round. Given the integers n, firstPlayer, and secondPlayer, return an integer array containing two values, the earliest possible round number and the latest possible round number in which these two players will compete against each other, respectively.
Dynamic Programming,Memoization
Hard
Brute force using bitmasks and simulate the rounds. Calculate each state one time and save its solution.
447
8
\n```\nclass Solution:\n def earliestAndLatest(self, n: int, firstPlayer: int, secondPlayer: int) -> List[int]:\n firstPlayer, secondPlayer = firstPlayer-1, secondPlayer-1 # 0-indexed\n \n @cache\n def fn(k, mask): \n """Return earliest and latest rounds."""\n can = deque()\n for i in range(n): \n if mask & (1 << i): can.append(i)\n \n cand = [] # eliminated player\n while len(can) > 1: \n p1, p2 = can.popleft(), can.pop()\n if p1 == firstPlayer and p2 == secondPlayer or p1 == secondPlayer and p2 == firstPlayer: return [k, k] # game of interest \n if p1 in (firstPlayer, secondPlayer): cand.append([p2]) # p2 eliminated \n elif p2 in (firstPlayer, secondPlayer): cand.append([p1]) # p1 eliminated \n else: cand.append([p1, p2]) # both could be elimited \n \n minn, maxx = inf, -inf\n for x in product(*cand): \n mask0 = mask\n for i in x: mask0 ^= 1 << i\n mn, mx = fn(k+1, mask0)\n minn = min(minn, mn)\n maxx = max(maxx, mx)\n return minn, maxx\n \n return fn(1, (1<<n)-1)\n```
97,284
Egg Drop With 2 Eggs and N Floors
egg-drop-with-2-eggs-and-n-floors
You are given two identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is.
Math,Dynamic Programming
Medium
Is it really optimal to always drop the egg on the middle floor for each move? Can we create states based on the number of unbroken eggs and floors to build our solution?
18,793
226
It may take you a while to come up with an efficient math-based solution. So, for an interview, I would start with a simple recursion - at least you will have something. It can help you see a pattern, and it will be easiser to develop an intuition for an improved solution. \n\nIf you follow-up with an improved solution, and also generalize it for `k` eggs ([887. Super Egg Drop]()) - it would be a home run. This is how this progression might look like.\n\n> Fun fact: this problem is decribed in the Wikipedia\'s article for [Dynamic Programming]().\n\n#### Simple Recursion\nIn the solution below, we drop an egg from each floor and find the number of throws for these two cases:\n- We lost an egg but we reduced the number of floors to `i`.\n\t- Since we only have one egg left, we can just return `i - 1` to check all floors.\n- The egg did not break, and we reduced the number of floors to `n - i`.\n\t- Solve this recursively to get the number of throws for `n - i` floors.\n\nThis way, we find a floor for which the number of throws - maximum from these two cases - is minimal.\n\n**C++**\n```cpp\nint dp[1001] = {};\nclass Solution {\npublic:\nint twoEggDrop(int n) {\n\tif (dp[n] == 0)\n\t\tfor (int i = 1; i <= n; ++i)\n\t\t\tdp[n] = min(dp[n] == 0 ? n : dp[n], 1 + max(i - 1, twoEggDrop(n - i)));\n\treturn dp[n];\n}\n};\n```\n**Java**\n```java\nstatic int[] dp = new int[1001];\npublic int twoEggDrop(int n) {\n if (dp[n] == 0)\n for (int i = 1; i <= n; ++i)\n dp[n] = Math.min(dp[n] == 0 ? n : dp[n], 1 + Math.max(i - 1, twoEggDrop(n - i)));\n return dp[n];\n}\n```\n\n**Python 3**\n```python\nclass Solution:\n @cache\n def twoEggDrop(self, n: int) -> int:\n return min((1 + max(i - 1, self.twoEggDrop(n - i)) for i in range (1, n)), default = 1)\n```\n#### Iterative Computation\nLet\'s take a look at the results from the first solution for different `n`:\n```\n1: 1\n2: 2\n4: 3\n7: 4\n11: 5\n16: 6\n22: 7\n29: 8\n37: 9\n46: 10\n```\nAs you see, with `m` drops, we can test up to 1 + 2 + ... + m floors. \n\n**C++**\n```cpp\nint twoEggDrop(int n) {\n int res = 1;\n while (n - res > 0)\n n -= res++;\n return res; \n}\n```\n... or, using a formula:\n\n**C++**\n```cpp\nint twoEggDrop(int n) {\n int m = 1;\n while (m * (m + 1) / 2 < n)\n ++m;\n return m; \n} \n```\n\n#### Inversion and Generic Solution\nWith the help of the iterative solution above, we see that it\'s easier to solve an inverse problem: given `m` total drops, and `k` eggs, how high can we go?\n\nSo with one egg and `m` drops, we can only test `m` floors.\n\nWith two eggs and `m` drops:\n1. We drop one egg to test one floor.\n2. We add the number of floors we can test with `m - 1` drops and 2 eggs (the egg did not break).\n3. And we add `m - 1 ` floors we can test with the last egg (the egg broke).\n\nThus, the formula is:\n```\ndp[m] = 1 + dp[m - 1] + m - 1;\n```\n... which is in-line with the observation we made for the iterative solution above!\n\nThis can be easily generalized for `k` eggs:\n\n```\ndp[m][k] = 1 + dp[m - 1][k] + dp[m - 1][k - 1];\n```\n\n**C++**\n```cpp\nint dp[1001][3] = {};\nclass Solution {\npublic:\nint twoEggDrop(int n, int k = 2) {\n int m = 0;\n while (dp[m][k] < n) {\n ++m;\n for (int j = 1; j <= k; ++j)\n dp[m][j] = dp[m - 1][j - 1] + dp[m - 1][j] + 1;\n }\n return m; \n}\n};\n```\nAs we only look one step back, we can reduce the memory ussage to O(k): \n\n**C++**\n```cpp\nint twoEggDrop(int n, int k = 2) {\n int dp[3] = {};\n int m = 0;\n while (dp[k] < n) {\n ++m;\n for (int j = k; j > 0; --j)\n dp[j] += dp[j - 1] + 1;\n }\n return m;\n}\n```
97,327
Egg Drop With 2 Eggs and N Floors
egg-drop-with-2-eggs-and-n-floors
You are given two identical eggs and you have access to a building with n floors labeled from 1 to n. You know that there exists a floor f where 0 <= f <= n such that any egg dropped at a floor higher than f will break, and any egg dropped at or below floor f will not break. In each move, you may take an unbroken egg and drop it from any floor x (where 1 <= x <= n). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves. Return the minimum number of moves that you need to determine with certainty what the value of f is.
Math,Dynamic Programming
Medium
Is it really optimal to always drop the egg on the middle floor for each move? Can we create states based on the number of unbroken eggs and floors to build our solution?
803
5
I found the example case `n=100` to be very helpful. Used the idea of drawing out examples and finding the pattern (as taught in Cracking the Coding Interview book).\n\nSee, when n = 100, in their example case:\n```\ndropAtFloors = [9,22,34,45,55,64,72,79,85,90,94,97,99,100]\n\t\t\t ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^\n(gap)\t\t 8 13 12 11 10 9 8 7 6 5 4 3 2 1 \n```\n\nNotice the pattern? Now implement.\n \n```\nclass Solution(object):\n def twoEggDrop(self, n):\n """\n :type n: int\n :rtype: int\n """\n count = 0\n iterable = n\n while iterable > 0:\n count += 1\n iterable -= count\n \n return count\n```
97,367
Largest Odd Number in String
largest-odd-number-in-string
You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string.
Math,String,Greedy
Easy
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
15,884
93
![Screenshot 2023-12-07 065808.png]()\n\n# YouTube Video Explanation:\n\n[]()\n<!-- **If you want a video for this question please write in the comments** -->\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: \n\n*Subscribe Goal: 700 Subscribers*\n*Current Subscribers: 630*\n\n---\n\n# Example Explanation\nLet\'s create a step-by-step explanation using a table:\n\n| Iteration | Current Substring | Last Digit | Odd? | Action |\n|-----------|---------------------|-------------|------|------------------------------------|\n| 1 | "52" | 2 | No | Move left (decrement index) |\n| 2 | "5" | 5 | Yes | Return the substring "5" |\n\nExplanation:\n1. Start with the given string "52".\n2. The last digit is 2, which is not odd, so move left.\n3. Move left to "5", which is an odd digit. Return the substring "5".\n\nThis way, we find the largest odd number ("5") within the given string "52".\n\n---\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to find the largest odd number within a given integer represented as a string. We need to identify the largest odd substring or return an empty string if no odd number exists.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate through the string from right to left.\n2. If the last digit is odd, return the entire string as it is already the largest odd number.\n3. If the last digit is even, keep moving left until an odd digit is found.\n4. Return the substring from the beginning of the string to the index where the first odd digit is encountered.\n\n# Complexity\n- The time complexity is O(n), where n is the length of the input string num.\n- The space complexity is O(1) since we are not using any extra space that scales with the input size.\n\n# Code\n```java []\nclass Solution {\n public String largestOddNumber(String num) {\n if((int)num.charAt(num.length()-1)%2==1) return num;\n int i=num.length()-1;\n while(i>=0){\n int n=num.charAt(i);\n if(n%2==1) return num.substring(0,i+1);\n i--;\n }\n return "";\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n string largestOddNumber(string num) {\n if (num.back() % 2 == 1) return num;\n int i = num.length() - 1;\n while (i >= 0) {\n int n = num[i];\n if (n % 2 == 1) return num.substr(0, i + 1);\n i--;\n }\n return "";\n }\n};\n```\n```Python []\nclass Solution(object):\n def largestOddNumber(self, num):\n for i in range(len(num) - 1, -1, -1):\n if num[i] in {\'1\', \'3\', \'5\', \'7\', \'9\'}:\n return num[:i + 1]\n return \'\'\n \n```\n```Javascript []\n/**\n * @param {string} num\n * @return {string}\n */\nvar largestOddNumber = function(num) {\n if (parseInt(num.slice(-1)) % 2 === 1) return num;\n let i = num.length - 1;\n while (i >= 0) {\n const n = parseInt(num[i]);\n if (n % 2 === 1) return num.slice(0, i + 1);\n i--;\n }\n return "";\n};\n```\n![upvote.png]()\n
97,374
Largest Odd Number in String
largest-odd-number-in-string
You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string.
Math,String,Greedy
Easy
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
1,230
9
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLet $x$ be a natural number expressed in decimal digit representation.\nThen $x$ is odd $\\iff$ its least significant digit is an odd.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nNote `int(\'0\')`=48, it suffices to check if `num[i]%2==1` which can by done by `num[i]&1`. \n\nIterate the string `num` backward!\n\nPython code is 1-line.\n\nC code is rare which is fastest among all implemenations & runs in 0 ms & beats 100%.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$ where `n=len(num)`\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code 11 ms Beats 99.88%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n string largestOddNumber(string& num) {\n for(int i=num.size()-1; i>=0; i--){\n if (num[i]&1)\n return move(num.substr(0, i+1));\n } \n return ""; \n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# C++ 1 line\n```\n string largestOddNumber(string& num) {\n return num.substr(0, num.find_last_of("13579")+1); \n }\n```\n# Python 1 line\n```\nclass Solution:\n def largestOddNumber(self, num: str) -> str:\n return num[:next((i for i in range(len(num)-1, -1, -1) if ord(num[i]) &1==1), -1) + 1]\n\n \n```\n# C code 0 ms Beats 100%\n```\nchar* largestOddNumber(char* num) {\n for(register int i=strlen(num)-1; i>=0; i--)\n if (num[i]&1){\n num[i+1]=\'\\0\';\n return num;\n }\n return "";\n}\n```\n![\u672A\u547D\u540D.png]()\n
97,376
Largest Odd Number in String
largest-odd-number-in-string
You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string.
Math,String,Greedy
Easy
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
1,093
13
# Intuition\nThe problem seems to involve finding the largest odd number from a given numeric string. The approach likely involves iterating through the string from right to left and stopping when an odd digit is encountered. The result should then be the substring from the beginning of the input string to the position where the odd digit was found.\n\n# Approach\nThe provided code seems to follow the intuition correctly. It initializes an empty string `result` and iterates through the input numeric string `num` from right to left. For each digit, it checks if it\'s odd, and if so, it updates the `result` to be the substring from the beginning of the input string to the current position. The loop breaks as soon as an odd digit is found.\n\n# Complexity\n- Time complexity: \\(O(n)\\), where \\(n\\) is the length of the input string `num`. In the worst case, the algorithm may iterate through the entire string once.\n- Space complexity: \\(O(1)\\), as the algorithm only uses a constant amount of extra space regardless of the input size. The primary variable is `result`, which is a string holding the final result.\n\n# Code\n```csharp []\npublic class Solution {\n public string LargestOddNumber(string num)\n {\n int ln = num.Length - 1;\n for (int i = ln; i >= 0; i--)\n {\n var ch = num[i].ToString();\n if (int.Parse(ch) % 2 != 0)\n {\n return num.Substring(0, i + 1);\n }\n }\n return "";\n }\n}\n```\n```python []\nclass Solution:\n def largestOddNumber(self, num: str) -> str:\n ln = len(num) - 1\n for i in range(ln, -1, -1):\n ch = num[i]\n if int(ch) % 2 != 0:\n return num[:i + 1]\n return ""\n```\n``` Java []\npublic class Solution {\n public String largestOddNumber(String num) {\n String result = "";\n int ln = num.length() - 1;\n for (int i = ln; i >= 0; i--) {\n char ch = num.charAt(i);\n if (Character.getNumericValue(ch) % 2 != 0) {\n return num.substring(0, i + 1);\n }\n }\n return result;\n }\n}\n```\n``` Rust []\npub fn largest_odd_number(num: &str) -> String {\n let ln = num.len();\n for (i, ch) in num.chars().rev().enumerate() {\n if ch.to_digit(10).unwrap() % 2 != 0 {\n return num[..ln - i].to_string();\n }\n }\n String::new()\n}\n\n```\n![image name]()\n\n- Please upvote me !!!
97,380
Largest Odd Number in String
largest-odd-number-in-string
You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string.
Math,String,Greedy
Easy
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
3,826
19
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n1. **Check Last Digit:** Check if the last digit of the input number is odd. If it is, the input number is already the largest odd number. Return the input number in this case.\n1. **Iterative Check**: Starting from the end of the number, iterate backward. If an odd digit is encountered, return the substring from the beginning up to (and including) that odd digit, as this is the largest odd number possible.\n1. **Return:** If no odd digits are found after the loop, return an empty string to indicate that there\'s no odd number in the given input.\n\n\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\n\nclass Solution {\npublic:\n string largestOddNumber(string num) {\n int n = num.size(); // Get the size of the input string\n\n\n if (num[n - 1] % 2 != 0) // Check if the last digit of the input number is odd\n return num; // If it is, the input number is already the largest odd number\n\n for (int i = n - 1; i >= 0; i--) {\n if (num[i] % 2 != 0) {\n return num.substr(0, i + 1); // If an odd digit is found, return the substring up to that point\n }\n }\n\n return ""; // If no odd digits are found, return an empty string\n }\n};\n\n\n```\n```C []\n\nchar* largestOddNumber(char* num) {\n int n = strlen(num);\n static char ans[100001]; // Assuming maximum length\n ans[0] = \'\\0\';\n\n if ((num[n - 1] - \'0\') % 2 != 0)\n return num;\n\n for (int i = n - 1; i >= 0; i--) {\n if ((num[i] - \'0\') % 2 != 0) {\n num[i + 1] = \'\\0\';\n strcpy(ans, num);\n return ans;\n }\n }\n\n return "";\n}\n\n\n\n```\n```Java []\nclass Solution {\n public String largestOddNumber(String num) {\n for (int i = num.length() - 1; i >= 0; i--) {\n if (Character.getNumericValue(num.charAt(i)) % 2 != 0) {\n return num.substring(0, i + 1);\n }\n }\n \n return "";\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def largestOddNumber(self, num: str) -> str:\n for i in range(len(num) - 1, -1, -1):\n if int(num[i]) % 2 != 0:\n return num[:i + 1]\n \n return ""\n\n\n```\n```javascript []\nfunction largestOddNumber(num) {\n let n = num.length;\n\n if (parseInt(num[n - 1]) % 2 !== 0)\n return num;\n\n for (let i = n - 1; i >= 0; i--) {\n if (parseInt(num[i]) % 2 !== 0) {\n return num.substring(0, i + 1);\n }\n }\n\n return \'\';\n}\n\n```\n\n---\n\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
97,381
Largest Odd Number in String
largest-odd-number-in-string
You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists. A substring is a contiguous sequence of characters within a string.
Math,String,Greedy
Easy
In what order should you iterate through the digits? If an odd number exists, where must the number start from?
3,917
40
# Intuition\nIterate through from the last\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:04` Coding\n`1:18` Time Complexity and Space Complexity\n`1:31` Step by step algorithm with my solution code\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 3,374\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n---\n\n# Approach\n\n## How we think about a solution\n\nSimply, in determining whether a digit is even or odd, it is determined by the least significant digit\'s value, so we iterate from the least significant digit.\n\n```\nInput: num = "52"\n```\nWe start iteration from the last.\n```\n"52"\n \u2191\n```\nConvert string `2` to integer `2` then\n\n```[]\nif 2 % 2 == 1\n\u2192 false\n```\nMove next\n```\n"52"\n \u2191\n```\nConvert string `5` to integer `5` then\n```[]\nif 5 % 2 == 1\n\u2192 true\n```\nNow we found the odd number in the least significant digit.\n```\nreturn "5"\n```\n\nLet\'s see a real algorithm!\n\n---\n \n1. **Iteration through Digits:**\n ```python\n for i in range(len(num) - 1, -1, -1):\n ```\n - The loop iterates through each character in the input string `num` in reverse order, starting from the least significant digit (`len(num) - 1`) and going up to the most significant digit (`-1`) with a step of `-1`.\n\n2. **Check for Odd Digit:**\n ```python\n if int(num[i]) % 2 == 1:\n ```\n - For each digit at the current index `i`, it converts the character to an integer and checks if it\'s an odd number (`% 2 == 1`).\n\n3. **Return the Largest Odd Number:**\n ```python\n return num[:i+1]\n ```\n - If an odd digit is found, it returns the substring of the input string from the beginning up to the current index (inclusive). This substring represents the largest odd number.\n\n4. **Return Empty String if No Odd Digit:**\n ```python\n return ""\n ```\n - If no odd digit is found in the entire string, the function returns an empty string.\n\nThis algorithm efficiently identifies and returns the largest odd number by iterating through the digits in reverse order. The process stops as soon as an odd digit is encountered, ensuring that the result is the largest possible odd number.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```python []\nclass Solution:\n def largestOddNumber(self, num: str) -> str:\n \n for i in range(len(num) - 1, -1, -1):\n if int(num[i]) % 2 == 1:\n return num[:i+1]\n \n return ""\n```\n```javascript []\n/**\n * @param {string} num\n * @return {string}\n */\nvar largestOddNumber = function(num) {\n for (let i = num.length - 1; i >= 0; i--) {\n if (parseInt(num[i]) % 2 === 1) {\n return num.slice(0, i + 1);\n }\n }\n \n return ""; \n};\n```\n```java []\nclass Solution {\n public String largestOddNumber(String num) {\n for (int i = num.length() - 1; i >= 0; i--) {\n if (Character.getNumericValue(num.charAt(i)) % 2 == 1) {\n return num.substring(0, i + 1);\n }\n }\n return ""; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n string largestOddNumber(string num) {\n for (int i = num.length() - 1; i >= 0; i--) {\n if ((num[i] - \'0\') % 2 == 1) {\n return num.substr(0, i + 1);\n }\n }\n return ""; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\n\n\n\u25A0 Twitter\n\n\n### My next daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:05` How we create an output string\n`2:07` Coding\n`4:30` Time Complexity and Space Complexity\n`4:49` Step by step of recursion process\n`7:27` Step by step algorithm with my solution code\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n`0:06` Understand the description and think about key points\n`1:56` How to calculate weekly base and days within the week\n`4:35` Coding\n`5:15` Time Complexity and Space Complexity\n`5:35` Think about another idea with O(1) time\n`10:22` Coding\n`12:04` Time Complexity and Space Complexity\n
97,383
The Number of Full Rounds You Have Played
the-number-of-full-rounds-you-have-played
You are participating in an online chess tournament. There is a chess round that starts every 15 minutes. The first round of the day starts at 00:00, and after every 15 minutes, a new round starts. You are given two strings loginTime and logoutTime where: If logoutTime is earlier than loginTime, this means you have played from loginTime to midnight and from midnight to logoutTime. Return the number of full chess rounds you have played in the tournament. Note: All the given times follow the 24-hour clock. That means the first round of the day starts at 00:00 and the last round of the day starts at 23:45.
Math,String
Medium
Consider the day as 48 hours instead of 24. For each round check if you were playing.
1,846
20
\n```\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n hs, ms = (int(x) for x in startTime.split(":"))\n ts = 60 * hs + ms\n hf, mf = (int(x) for x in finishTime.split(":"))\n tf = 60 * hf + mf\n if 0 <= tf - ts < 15: return 0 # edge case \n return tf//15 - (ts+14)//15 + (ts>tf)*96\n```\n\n```\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n ts = 60 * int(startTime[:2]) + int(startTime[-2:])\n tf = 60 * int(finishTime[:2]) + int(finishTime[-2:])\n if 0 <= tf - ts < 15: return 0 # edge case \n return tf//15 - (ts+14)//15 + (ts>tf)*96\n```
97,428
Minimum Absolute Difference Queries
minimum-absolute-difference-queries
The minimum absolute difference of an array a is defined as the minimum value of |a[i] - a[j]|, where 0 <= i < j < a.length and a[i] != a[j]. If all elements of a are the same, the minimum absolute difference is -1. You are given an integer array nums and the array queries where queries[i] = [li, ri]. For each query i, compute the minimum absolute difference of the subarray nums[li...ri] containing the elements of nums between the 0-based indices li and ri (inclusive). Return an array ans where ans[i] is the answer to the ith query. A subarray is a contiguous sequence of elements in an array. The value of |x| is defined as:
Array,Hash Table
Medium
How does the maximum value being 100 help us? How can we tell if a number exists in a given range?
1,127
8
\n```\nclass Solution:\n def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n loc = {}\n for i, x in enumerate(nums): loc.setdefault(x, []).append(i)\n keys = sorted(loc)\n \n ans = []\n for l, r in queries: \n prev, val = 0, inf\n for x in keys: \n i = bisect_left(loc[x], l)\n if i < len(loc[x]) and loc[x][i] <= r: \n if prev: val = min(val, x - prev)\n prev = x \n ans.append(val if val < inf else -1)\n return ans\n```
97,484
Count Sub Islands
count-sub-islands
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
Let's use floodfill to iterate over the islands of the second grid Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island
9,404
199
## IDEA:\n\uD83D\uDC49 firstly remove all the non-common island\n\uD83D\uDC49 Now count the sub-islands\n\'\'\'\n\n\tclass Solution:\n def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:\n \n m=len(grid1)\n n=len(grid1[0])\n \n def dfs(i,j):\n if i<0 or i>=m or j<0 or j>=n or grid2[i][j]==0:\n return\n \n grid2[i][j]=0\n dfs(i+1,j)\n dfs(i,j+1)\n dfs(i,j-1)\n dfs(i-1,j)\n \n # removing all the non-common sub-islands\n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1 and grid1[i][j]==0:\n dfs(i,j)\n \n c=0\n\t\t# counting sub-islands\n for i in range(m):\n for j in range(n):\n if grid2[i][j]==1:\n dfs(i,j)\n c+=1\n return c\n\t\t\nIf you have any doubt ......... please feel free to ask !!!\nThank You \uD83E\uDD1E
97,531
Count Sub Islands
count-sub-islands
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
Let's use floodfill to iterate over the islands of the second grid Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island
180
5
# Algorithm : \n- Perform DFS on grid2 and store the coordinates of the island.\n- Check if every coordinate stored is \'1\' in grid1.\n- If all the coordinates are 1\'s in grid1 then increment the count.\n- Finally return the count.\n>### *Check the implementation for clear understanding !!*\n---\n# Java Code\n```\nclass Pair\n{\n int x = 0;\n int y = 0;\n Pair(int x,int y)\n {\n this.x = x;\n this.y = y;\n }\n}\nclass Solution {\n int[] xDir = {0,0,-1,1};\n int[] yDir = {-1,1,0,0};\n public void DFS(int[][] grid2,boolean[][] visited,int i,int j,ArrayList<Pair> arr)\n {\n if(i<0 || i>=grid2.length || j<0 || j>=grid2[0].length || visited[i][j] == true ||grid2[i][j]!=1)\n return;\n visited[i][j] = true;\n Pair p = new Pair(i,j);\n arr.add(p);\n for(int k = 0;k<4;k++)\n {\n int newRow = i+xDir[k];\n int newCol = j+yDir[k];\n DFS(grid2,visited,newRow,newCol,arr);\n }\n }\n public int countSubIslands(int[][] grid1, int[][] grid2) {\n int rows = grid1.length;\n int cols = grid1[0].length;\n boolean[][] visited = new boolean[rows][cols];\n int count = 0;\n for(int i = 0;i<rows;i++)\n {\n for(int j = 0;j<cols;j++)\n {\n if(grid2[i][j] == 1 && visited[i][j] == false)\n {\n ArrayList<Pair> arr = new ArrayList<>();\n DFS(grid2,visited,i,j,arr);\n boolean flag = false;\n for(Pair p : arr)\n {\n int x = p.x;\n int y = p.y;\n if(grid1[x][y] != 1)\n {\n flag = true;\n break;\n }\n }\n if(!flag)\n count++;\n }\n }\n }\n return count;\n }\n}\n```\n---\n#### *Please don\'t forget to upvote if you\'ve liked my explanation.*\n---
97,541
Count Sub Islands
count-sub-islands
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
Let's use floodfill to iterate over the islands of the second grid Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island
611
6
\n\n# Code\n```\nclass Solution:\n def countSubIslands(self, back: List[List[int]], grid: List[List[int]]) -> int:\n m=len(grid)\n n=len(grid[0])\n res=0\n test=True\n def dfs(i,j):\n nonlocal test\n if grid[i][j]==1:\n if back[i][j] != 1:\n test=False\n grid[i][j]=0\n if j<n-1:\n dfs(i,j+1)\n if j>0:\n dfs(i,j-1)\n if i>0:\n dfs(i-1,j)\n if i<m-1:\n dfs(i+1,j)\n for i in range(m):\n for j in range(n):\n if grid[i][j]==1:\n \n test=True\n dfs(i,j)\n if test :\n res+=1\n \n\n return res\n```
97,543
Count Sub Islands
count-sub-islands
You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells. An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2. Return the number of islands in grid2 that are considered sub-islands.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
Let's use floodfill to iterate over the islands of the second grid Let's note that if all the cells in an island in the second grid if they are represented by land in the first grid then they are connected hence making that island a sub-island
774
6
\tclass Solution:\n\t\t"""\n\t\tTime: O(n^2)\n\t\tMemory: O(n^2)\n\t\t"""\n\n\t\tLAND = 1\n\t\tWATER = 0\n\n\t\tdef countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:\n\t\t\tm, n = len(grid1), len(grid1[0])\n\n\t\t\tfor i in range(m):\n\t\t\t\tfor j in range(n):\n\t\t\t\t\tif grid2[i][j] == self.LAND and grid1[i][j] == self.WATER:\n\t\t\t\t\t\tself.sink_island(i, j, grid2)\n\n\t\t\tislands = 0\n\t\t\tfor i in range(m):\n\t\t\t\tfor j in range(n):\n\t\t\t\t\tif grid2[i][j] == self.LAND:\n\t\t\t\t\t\tself.sink_island(i, j, grid2)\n\t\t\t\t\t\tislands += 1\n\n\t\t\treturn islands\n\n\t\t@classmethod\n\t\tdef sink_island(cls, row: int, col: int, grid: List[List[int]]):\n\t\t\tif grid[row][col] == cls.LAND:\n\t\t\t\tgrid[row][col] = cls.WATER\n\t\t\t\tif row > 0:\n\t\t\t\t\tcls.sink_island(row - 1, col, grid)\n\t\t\t\tif row < len(grid) - 1:\n\t\t\t\t\tcls.sink_island(row + 1, col, grid)\n\t\t\t\tif col < len(grid[0]) - 1:\n\t\t\t\t\tcls.sink_island(row, col + 1, grid)\n\t\t\t\tif col > 0:\n\t\t\t\t\tcls.sink_island(row, col - 1, grid)\n
97,559
Count Square Sum Triples
count-square-sum-triples
A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Math,Enumeration
Easy
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt
2,674
31
**Python :**\n\n```\ndef countTriples(self, n: int) -> int:\n\tres = 0\n\n\tfor i in range(1, n):\n\t\tfor j in range(i + 1, n):\n\t\t\ts = math.sqrt(i * i + j * j)\n\t\t\tif int(s) == s and s <= n:\n\t\t\t\tres += 2\n\n\treturn res\n```\n\n**Like it ? please upvote !**
97,585
Count Square Sum Triples
count-square-sum-triples
A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Math,Enumeration
Easy
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt
3,975
26
**C++ :**\n```\nclass Solution {\npublic:\n int countTriples(int n) { \n int c = 0;\n for(int i=1 ; i<=n ; i++){\n for(int j=i+1 ; j<=n ; j++){\n int sq = ( i * i) + ( j * j);\n int r = sqrt(sq);\n if( r*r == sq && r <= n )\n c += 2;\n }\n }\n return c;\n }\n};\n```\n\n**Java:**\n```\nclass Solution {\n public int countTriples(int n) {\n int c = 0;\n for(int i=1 ; i<=n ; i++){\n for(int j=i+1 ; j<=n ; j++){\n int sq = ( i * i) + ( j * j);\n int r = (int) Math.sqrt(sq);\n if( r*r == sq && r <= n )\n c += 2;\n }\n }\n return c;\n }\n}\n```\n\n**Python:**\n```\nclass Solution:\n def countTriples(self, n: int) -> int:\n c = 0\n for i in range(1, n+1):\n for j in range(i+1, n+1):\n sq = i*i + j*j\n r = int(sq ** 0.5)\n if ( r*r == sq and r <= n ):\n c +=2\n return c\n```
97,587
Count Square Sum Triples
count-square-sum-triples
A square triple (a,b,c) is a triple where a, b, and c are integers and a2 + b2 = c2. Given an integer n, return the number of square triples such that 1 <= a, b, c <= n.
Math,Enumeration
Easy
Iterate over all possible pairs (a,b) and check that the square root of a * a + b * b is an integers less than or equal n You can check that the square root of an integer is an integer using binary seach or a builtin function like sqrt
823
8
### Overview\nThis solution uses [Euclid\'s formula]() to generate all primitive Pythagorean triple. A primitive triple is one which can not be reduced by dividing all numbers by a common factor e.g. `(2, 3, 4)` is primitive while `(4, 6, 8)` and `(6, 9, 12)` are not.\n\nFor a given primitive triple `(a, b, c)` , a total of `n // c` triples are less than or equal to `n`, after including both primitive and non-primitive triples.\n\nFinally, we have to account for the different permutations of each primitive triple. Each triple must consist of three unique numbers (it should be fairly easy to see that `x^2 + x^2` can never equal another square number for any `x`). Therefore, for a triple `(a, b, c)` where `a < b < c`, there will always be exactly one other permutation, `(b, a, c)`. As a result, to account for this permutation we can simply multiply the total count by 2.\n\n### Time complexity\nThe number of executions of the main body of `gen_primitive_triples` scales as `O(n)`, as the two loops over `x` and `y` are both bounded by `x^2 + y^2` being less than `n`. Theoretetically, `math.gcd` should have amortized time complexity of `O(log n)`, which would give an overall time complexity of `O(n log n)`. However, empirically the overall time complexity appears to be linear (tested up to `n = 10^9`). This is likely because the logarithmic cost of `math.gcd` is masked by other constant-time costs in the `gen_primitive_triples` main body. For completeness, the sum in `countTriples` also runs in linear time.\n\n### Space complexity\nThis solution only uses constant space as `gen_primitive_triples` is a generator and therefore the sum in `countTriples` only consumes values lazily.\n\n### Python code\n\n```python\nimport math\n\nclass Solution:\n def countTriples(self, n: int) -> int:\n return 2 * sum(n // triple[2] for triple in gen_primitive_triples(n))\n\n\ndef gen_primitive_triples(n):\n """Generates primitive Pythagorean triples less than or equal to `n`.\n\n Uses Euclid\'s formula (see\n ).\n """\n\n x = 2\n while True:\n for y in range(1, x):\n\t\t\t# Euclid\'s formula only yields primitive triples when x and y are\n # co-prime and not both odd.\n if math.gcd(x, y) != 1 or (x % 2 == 1 and y % 2 == 1):\n continue\n # Technically the first and second terms of the triple are not\n # needed to solve the problem. They are only included here to show\n # Euclid\'s formula.\n triple = (\n x ** 2 - y ** 2,\n 2 * x * y,\n x ** 2 + y ** 2,\n )\n\t\t\t# The last number in the triple is always the largest, so no need\n\t\t\t# to check that the first two are less than or equal to `n`.\n if triple[2] <= n:\n yield triple\n elif y == 1:\n return\n x += 1\n
97,600
Sum Game
sum-game
Alice and Bob take turns playing a game, with Alice starting first. You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num: The game ends when there are no more '?' characters in num. For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal. Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.
Math,Greedy,Game Theory
Medium
Bob can always make the total sum of both sides equal in mod 9. Why does the difference between the number of question marks on the left and right side matter?
1,095
25
### Explanation\n- Intuition: Starting with the three examples, you will soon realize that this is essentially a Math problem.\n- Our goal is to see if left sum can equal to right sum, that is, `left_sum - right_sum == 0`. \n- To make it easier to understand, we can move digits to one side and `?` mark to the other side, for example, `?3295???`\n\t- Can be represented as `?329=5???` -> `3+2+9-5=???-?` -> `9=??`\n\t- Now, the original question becomes: Given `9=??` and Alice plays first, can we get this left & right not equal to each other?\n\t- The answer is NO. It doesn\'t matter what number `x` Alice gives, Bob only need to provide `9-x` to make sure the left equals to right.\n- Let\'s try out some other examples, based on the previous observation.\n\t- `8=??`, can Alice win? \n\t\t- Yes, if Alice plays 9 first\n\t- `9=???`, can Alice win?\n\t\t- Yes, since Alice can play 1 time more than Bob\n\t- `9=????`, can Alice win?\n\t\t- Yes, if the sum of Alice\'s 2 plays is greater than 9\n\t- `18=????`, can Alice win?\n\t\t- No, ame as `9=??`, doesn\'t matter what `x` Alice plays, Bob just need to play `9-x`\n\t- `18=??`, can Alice win?\n\t\t- Yes, unless Alice & Bob both play 9 (not optimal play, against the game rule)\n- I think now you should get the idea of the game. Let\'s say, for left side & right side, we move the smaller sum to the other side of the equal sign (we call the result `digit_sum`); for question mark, we move it to the opposite direction (we call the result `?_count`. After doing something Math, the only situation that Bob can win is that:\n\t- `?_count % 2 == 0 and digit_sum == ?_count // 2 * 9`. This basically saying that:\n\t\t- `?_count` has to be an even number\n\t\t- `digit_sum` is a multiple of 9\n\t\t- Half number of plays (or `?`) * 9 equals to `digit_sum`\n- In the following implementation:\n\t- `q_cnt_1`: **Q**uestion mark **c**ou**nt** for the **1**st half of `num`\n\t- `q_cnt_2`: **Q**uestion mark **c**ou**nt** for the **2**nd half of `num`\n\t- `s1`: **S**um of digits for the **1**st half of `num`\n\t- `s2`: **S**um of digits for the **2**nd half of `num`\n\t- `s_diff`: **S**um difference (we take the greater sum - the smaller sum)\n\t- `q_diff`: **Q**uestion mark difference (opposite direction to the digit sum move)\n\n\n### Implementation\n```\nclass Solution:\n def sumGame(self, num: str) -> bool:\n n = len(num)\n q_cnt_1 = s1 = 0\n for i in range(n//2): # get digit sum and question mark count for the first half of `num`\n if num[i] == \'?\':\n q_cnt_1 += 1\n else: \n s1 += int(num[i])\n q_cnt_2 = s2 = 0\t\t\t\t\n for i in range(n//2, n): # get digit sum and question mark count for the second half of `num`\n if num[i] == \'?\':\n q_cnt_2 += 1\n else: \n s2 += int(num[i])\n s_diff = s1 - s2 # calculate sum difference and question mark difference\n q_diff = q_cnt_2 - q_cnt_1\n return not (q_diff % 2 == 0 and q_diff // 2 * 9 == s_diff) # When Bob can\'t win, Alice wins\n```
97,680
Maximum Product Difference Between Two Pairs
maximum-product-difference-between-two-pairs
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the maximum such product difference.
Array,Sorting
Easy
If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array.
3,893
36
# Intuition\r\nUse the two biggest numbers and the two smallest numbers\r\n\r\n---\r\n\r\n# Solution Video\r\n\r\n\r\n\r\n\u25A0 Timeline of the video\r\n\r\n`0:05` Explain solution formula\r\n`0:47` Talk about the first smallest and the second smallest\r\n`3:32` Talk about the first biggest and the second biggest\r\n`5:11` coding\r\n`8:10` Time Complexity and Space Complexity\r\n`8:26` Step by step algorithm of my solution code\r\n\r\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\r\n\r\n**\u25A0 Subscribe URL**\r\n\r\n\r\nSubscribers: 3,518\r\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\r\nThank you for your support!\r\n\r\n---\r\n\r\n# Approach\r\n\r\n## How we think about a solution\r\n\r\nConstraints says `1 <= nums[i] <= 104`, so simply maximum product difference should be\r\n\r\n```\r\nfirst biggest * second biggest - first smallest * second smallest\r\n```\r\n\r\nIf we use `sort` and then take the first two numbers and the last two numbers, we can solve this question. But that is $$O(nlogn)$$. It\'s a boring answer. Let\'s think about $$O(n)$$ solution.\r\n\r\nLet\'s think about 4 cases.\r\n\r\n---\r\n\r\n- First smallest\r\n- Second smallest\r\n- First biggest\r\n- Second biggest\r\n\r\n---\r\nBasically we iterate through all numbers one by one. The numbers are compared in the order specified above.\r\n\r\n#### First smallest\r\n\r\nIf current number is smaller than the current smallest number,\r\n\r\n---\r\n\r\n\u2B50\uFE0F Points\r\n\r\nthe current number will be the first smallest number.\r\nthe current first smallest number will be the second smallest number.\r\n\r\n---\r\n\r\n#### Second smallest\r\n\r\nNext, we check the second smallest. If current number is smaller than the current second smallest number,\r\n\r\n---\r\n\r\n\u2B50\uFE0F Points\r\n\r\nWe can just update the second smallest number with current number, because we already compared current number with the first smallest number, so we are sure that the current number is \r\n\r\n```\r\nthe first smallest < current < the second smallest\r\n```\r\n\r\n---\r\n\r\nSo, current number will be the second smallest number.\r\n\r\nRegarding biggest numbers, we apply the same idea. Let me explain them quickly.\r\n\r\n#### First biggest\r\n\r\nIf current number is bigger than the current biggest number,\r\n\r\n---\r\n\r\n\u2B50\uFE0F Points\r\n\r\nthe current number will be the first biggest number.\r\nthe current first biggest number will be the second biggest number.\r\n\r\n---\r\n\r\n#### Second biggest\r\n\r\nIf current number is bigger than the current second bigger number,\r\n\r\n---\r\n\r\n\u2B50\uFE0F Points\r\n\r\nWe are sure\r\n\r\n```\r\nthe first biggest > current > the second biggest\r\n```\r\n\r\nBecause we already compared current number with the first biggest number.\r\n\r\n---\r\n\r\nSo, current number will be the second biggest number.\r\n\r\nEasy!\uD83D\uDE04\r\nLet\'s see a real algorithm!\r\n\r\n---\r\n\r\n# Complexity\r\n- Time complexity: $$O(n)$$\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n\r\n- Space complexity: $$O(1)$$\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\n\r\n```python []\r\nclass Solution:\r\n def maxProductDifference(self, nums: List[int]) -> int:\r\n first_big = second_big = 0\r\n first_small = second_small = float("inf")\r\n\r\n for n in nums:\r\n if n < first_small:\r\n second_small, first_small = first_small, n \r\n elif n < second_small: \r\n second_small = n \r\n\r\n if n > first_big:\r\n second_big, first_big = first_big, n\r\n elif n > second_big:\r\n second_big = n \r\n\r\n return first_big * second_big - first_small * second_small\r\n```\r\n```javascript []\r\n/**\r\n * @param {number[]} nums\r\n * @return {number}\r\n */\r\nvar maxProductDifference = function(nums) {\r\n let firstBig = secondBig = 0;\r\n let firstSmall = secondSmall = Infinity;\r\n\r\n for (const n of nums) {\r\n if (n < firstSmall) {\r\n [secondSmall, firstSmall] = [firstSmall, n];\r\n } else if (n < secondSmall) {\r\n secondSmall = n;\r\n }\r\n\r\n if (n > firstBig) {\r\n [secondBig, firstBig] = [firstBig, n];\r\n } else if (n > secondBig) {\r\n secondBig = n;\r\n }\r\n }\r\n\r\n return firstBig * secondBig - firstSmall * secondSmall; \r\n};\r\n```\r\n```java []\r\nclass Solution {\r\n public int maxProductDifference(int[] nums) {\r\n int firstBig = 0, secondBig = 0;\r\n int firstSmall = Integer.MAX_VALUE, secondSmall = Integer.MAX_VALUE;\r\n\r\n for (int n : nums) {\r\n if (n < firstSmall) {\r\n secondSmall = firstSmall;\r\n firstSmall = n;\r\n } else if (n < secondSmall) {\r\n secondSmall = n;\r\n }\r\n\r\n if (n > firstBig) {\r\n secondBig = firstBig;\r\n firstBig = n;\r\n } else if (n > secondBig) {\r\n secondBig = n;\r\n }\r\n }\r\n\r\n return firstBig * secondBig - firstSmall * secondSmall; \r\n }\r\n}\r\n```\r\n```C++ []\r\nclass Solution {\r\npublic:\r\n int maxProductDifference(vector<int>& nums) {\r\n int firstBig = 0, secondBig = 0;\r\n int firstSmall = INT_MAX, secondSmall = INT_MAX;\r\n\r\n for (int n : nums) {\r\n if (n < firstSmall) {\r\n secondSmall = firstSmall;\r\n firstSmall = n;\r\n } else if (n < secondSmall) {\r\n secondSmall = n;\r\n }\r\n\r\n if (n > firstBig) {\r\n secondBig = firstBig;\r\n firstBig = n;\r\n } else if (n > secondBig) {\r\n secondBig = n;\r\n }\r\n }\r\n\r\n return firstBig * secondBig - firstSmall * secondSmall; \r\n }\r\n};\r\n```\r\n\r\n## Step by step algorithm\r\n\r\n1. **Initialize Variables:**\r\n ```python\r\n first_big = second_big = 0\r\n first_small = second_small = float("inf")\r\n ```\r\n - `first_big`, `second_big`: Initialize variables to keep track of the two largest numbers.\r\n - `first_small`, `second_small`: Initialize variables to keep track of the two smallest numbers. `float("inf")` is used to represent positive infinity.\r\n\r\n2. **Iterate Through the Numbers:**\r\n ```python\r\n for n in nums:\r\n ```\r\n - Loop through each number in the input list `nums`.\r\n\r\n3. **Update Variables for Smallest Numbers:**\r\n ```python\r\n if n < first_small:\r\n second_small, first_small = first_small, n\r\n elif n < second_small:\r\n second_small = n\r\n ```\r\n - If the current number `n` is smaller than the current smallest number (`first_small`), update both smallest numbers accordingly.\r\n - If `n` is smaller than the second smallest number (`second_small`) but not the smallest, update only the second smallest.\r\n\r\n4. **Update Variables for Largest Numbers:**\r\n ```python\r\n if n > first_big:\r\n second_big, first_big = first_big, n\r\n elif n > second_big:\r\n second_big = n\r\n ```\r\n - If the current number `n` is larger than the current largest number (`first_big`), update both largest numbers accordingly.\r\n - If `n` is larger than the second largest number (`second_big`) but not the largest, update only the second largest.\r\n\r\n5. **Calculate and Return Result:**\r\n ```python\r\n return first_big * second_big - first_small * second_small\r\n ```\r\n - Calculate the product difference between the two largest and two smallest numbers.\r\n - Return the result.\r\n\r\nThe algorithm efficiently finds the two largest and two smallest numbers in the list and computes their product difference.\r\n\r\n---\r\n\r\nThank you for reading my post.\r\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\r\n\r\n\u25A0 Subscribe URL\r\n\r\n\r\n\u25A0 Twitter\r\n\r\n\r\n### My next daily coding challenge post and video.\r\n\r\npost\r\n\r\n\r\nvideo\r\n\r\n\r\n\u25A0 Timeline of the video\r\n\r\n`0:03` Explain how we solve Image Smoother\r\n`1:13` Check Top side\r\n`2:18` Check Bottom side\r\n`4:11` Check left and right side\r\n`3:32` Talk about the first biggest and the second biggest\r\n`6:26` coding\r\n`9:24` Time Complexity and Space Complexity\r\n`9:45` Step by step algorithm of my solution code\r\n\r\n### My previous daily coding challenge post and video.\r\n\r\npost\r\n\r\n\r\nvideo\r\n\r\n\r\n\u25A0 Timeline of the video\r\n\r\n`0:04` Explain constructor\r\n`1:21` Why -rating instead of rating?\r\n`4:09` Talk about changeRating\r\n`5:19` Time Complexity and Space Complexity\r\n`6:36` Step by step algorithm of my solution code\r\n`6:39` Python Tips - SortedList\r\n
97,824
Maximum Product Difference Between Two Pairs
maximum-product-difference-between-two-pairs
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the maximum such product difference.
Array,Sorting
Easy
If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array.
12,213
57
![Screenshot 2023-12-18 081529.png]()\r\n\r\n# YouTube Video Explanation:\r\n\r\n[]()\r\n<!-- **If you want a video for this question please write in the comments** -->\r\n\r\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\r\n\r\nSubscribe Link: \r\n\r\n*Subscribe Goal: 900 Subscribers*\r\n*Current Subscribers: 856*\r\n\r\n---\r\n\r\n# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nTo maximize the product difference between pairs, we need to select the largest and second-largest values for one pair and the smallest and second-smallest values for the other pair. By finding these extreme values, we ensure that the product difference is maximized.\r\n\r\n# Approach\r\n<!-- Describe your approach to solving the problem. -->\r\n1. Initialize variables to keep track of the largest (`largest`) and second-largest (`secondLargest`) values, as well as the smallest (`smallest`) and second-smallest (`secondSmallest`) values.\r\n2. Iterate through the array, updating the extreme values based on the current element.\r\n3. Calculate the product difference using the formula: `(largest * secondLargest) - (smallest * secondSmallest)`.\r\n4. Return the calculated product difference.\r\n\r\n# Complexity\r\n- Time complexity: `O(N)` - We iterate through the array once.\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n\r\n- Space complexity: `O(1)` - We use a constant amount of space for variables.\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\n\r\n# Code\r\n```java []\r\nclass Solution {\r\n public int maxProductDifference(int[] nums) {\r\n int firstBig = 0, secondBig = 0;\r\n int firstSmall = Integer.MAX_VALUE, secondSmall = Integer.MAX_VALUE;\r\n\r\n for (int n : nums) {\r\n if (n < firstSmall) {\r\n secondSmall = firstSmall;\r\n firstSmall = n;\r\n } else if (n < secondSmall) {\r\n secondSmall = n;\r\n }\r\n\r\n if (n > firstBig) {\r\n secondBig = firstBig;\r\n firstBig = n;\r\n } else if (n > secondBig) {\r\n secondBig = n;\r\n }\r\n }\r\n\r\n return firstBig * secondBig - firstSmall * secondSmall; \r\n }\r\n}\r\n```\r\n```C++ []\r\nclass Solution {\r\npublic:\r\n int maxProductDifference(vector<int>& nums) {\r\n int largest = 0, secondLargest = 0;\r\n int smallest = INT_MAX, secondSmallest = INT_MAX;\r\n\r\n for (int n : nums) {\r\n if (n < smallest) {\r\n secondSmallest = smallest;\r\n smallest = n;\r\n } else if (n < secondSmallest) {\r\n secondSmallest = n;\r\n }\r\n\r\n if (n > largest) {\r\n secondLargest = largest;\r\n largest = n;\r\n } else if (n > secondLargest) {\r\n secondLargest = n;\r\n }\r\n }\r\n\r\n return (largest * secondLargest) - (smallest * secondSmallest);\r\n }\r\n};\r\n```\r\n```Python []\r\nclass Solution(object):\r\n def maxProductDifference(self, nums):\r\n largest, secondLargest = 0, 0\r\n smallest, secondSmallest = float(\'inf\'), float(\'inf\')\r\n\r\n for n in nums:\r\n if n < smallest:\r\n secondSmallest = smallest\r\n smallest = n\r\n elif n < secondSmallest:\r\n secondSmallest = n\r\n\r\n if n > largest:\r\n secondLargest = largest\r\n largest = n\r\n elif n > secondLargest:\r\n secondLargest = n\r\n\r\n return (largest * secondLargest) - (smallest * secondSmallest)\r\n```\r\n```JavaScript []\r\n/**\r\n * @param {number[]} nums\r\n * @return {number}\r\n */\r\nvar maxProductDifference = function(nums) {\r\n let largest = 0, secondLargest = 0;\r\n let smallest = Number.MAX_SAFE_INTEGER, secondSmallest = Number.MAX_SAFE_INTEGER;\r\n\r\n for (const n of nums) {\r\n if (n < smallest) {\r\n secondSmallest = smallest;\r\n smallest = n;\r\n } else if (n < secondSmallest) {\r\n secondSmallest = n;\r\n }\r\n\r\n if (n > largest) {\r\n secondLargest = largest;\r\n largest = n;\r\n } else if (n > secondLargest) {\r\n secondLargest = n;\r\n }\r\n }\r\n\r\n return (largest * secondLargest) - (smallest * secondSmallest);\r\n};\r\n```\r\n![upvote.png]()\r\n
97,825
Maximum Product Difference Between Two Pairs
maximum-product-difference-between-two-pairs
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the maximum such product difference.
Array,Sorting
Easy
If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array.
1,762
8
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse sort 1-line by Python\nC++ sort.\nOther approaches are\n- Heap solution\n- Loop with conditional clause\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[]()\n\nSince the question is easy, try other approach by using priority_queue. Keep the size below 3 for 2 priority_queues with different orderings. \n\nAt final 1 priority_queue contains 2 biggest numbers, & other priority_queue contains 2 smallest numbers.\n\nThis method is not slow runs in 19ms & beats 83.95%.\n\nA loop with if-else clause is also implemented which runs in 11 ms &beats 99.06%. This is a a standard solution which is explained as follows\n\nVariable Initialization:\n`int max0=1, max1=1, min1=INT_MAX, min0=INT_MAX;`: Initializes four variables (max0, max1, min1, min0) to specific values. max0 and max1 are initialized to 1, and min1 and min0 are initialized to the maximum representable integer value (INT_MAX).\nLoop Over Input Vector:\n\n`for(int x: nums) { ... }`: Iterates over each element x in the nums vector.\nInside the loop, there are conditional statements to update the maximum and minimum values:\nIf x is greater than max0, update max1 and max0 accordingly.\nIf x is less than min0, update min1 and min0 accordingly.\n\n\n`return max0*max1-min0*min1;`: Computes the result, which is the product of the two largest elements (max0 and max1) minus the product of the two smallest elements (min0 and min1), and returns it.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)$$\n2 priority_queues: $O(n)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n2 priority_queues: $O(n)$\n# Python 1-line Code\n```\nclass Solution:\n def maxProductDifference(self, nums: List[int]) -> int:\n return (X:=sorted(nums))[-1]*X[-2]-X[1]*X[0]\n```\n# C++ using sort\n```\nclass Solution {\npublic:\n int maxProductDifference(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n=nums.size();\n return nums[n-1]*nums[n-2]-nums[1]*nums[0];\n \n }\n};\n```\n# C++ using 2 priority_queues||19ms Beats 83.95%\n```\nclass Solution {\npublic:\n int maxProductDifference(vector<int>& nums) {\n priority_queue<int> pq0;\n priority_queue<int, vector<int>, greater<int>> pq1;\n for(int x: nums){\n pq0.push(x);\n if (pq0.size()>2){\n int y=pq0.top();\n pq0.pop();\n pq1.push(y);\n }\n if (pq1.size()>2)\n pq1.pop();\n }\n int w=pq0.top();\n pq0.pop();\n w*=pq0.top();\n int z=pq1.top();\n pq1.pop();\n z*=pq1.top();\n return z-w;\n }\n};\n```\n# C++ loop with if-else runs in 11 ms Beats 99.06%\n\n```\nclass Solution {\npublic:\n int maxProductDifference(vector<int>& nums) {\n int max0=1, max1=1, min1=INT_MAX, min0=INT_MAX;\n for(int x: nums){\n if (x>max0){\n max1=max0;\n max0=x; \n }\n else max1=max(max1, x);\n if (x<min0) {\n min1=min0;\n min0=x;\n }\n else min1=min(min1, x);\n }\n return max0*max1-min0*min1;\n }\n};\n```\n
97,828
Maximum Product Difference Between Two Pairs
maximum-product-difference-between-two-pairs
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the maximum such product difference.
Array,Sorting
Easy
If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array.
1,578
10
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n*(Also explained in the code)*\n\n#### ***Approach 1(with Sort)***\n1. sorts the input array `nums` in ascending order.\n1. Computes the difference between the product of the last two elements and the product of the first two elements in the sorted array.\n 1. Returns the calculated difference between the maximum product (of the last two elements) and the minimum product (of the first two elements) in the array.\n\n# Complexity\n- Time complexity:\n $$O(nlogn)$$\n \n\n- Space complexity:\n $$O(logn)$$ or $$O(n)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxProductDifference(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n =nums.size();\n\n return nums[n-2]*nums[n-1]-nums[0]*nums[1];\n }\n};\n\n\n```\n\n```Java []\nclass Solution {\n public int maxProductDifference(int[] nums) {\n Arrays.sort(nums);\n return nums[nums.length - 1] * nums[nums.length - 2] - nums[0] * nums[1];\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maxProductDifference(self, nums: List[int]) -> int:\n nums.sort()\n return nums[-1] * nums[-2] - nums[0] * nums[1]\n\n\n```\n```javascript []\nfunction maxProductDifference(nums) {\n nums.sort((a, b) => a - b);\n const n = nums.length;\n\n return nums[n - 2] * nums[n - 1] - nums[0] * nums[1];\n}\n\n\n\n```\n---\n#### ***Approach 2(Keeping track of 2 largest and 2 smallest)***\n1. `maxProductDifference` finds the maximum difference between the product of the largest and second-largest numbers and the product of the smallest and second-smallest numbers in the given array `nums`.\n1. It iterates through the array, keeping track of the largest, second-largest, smallest, and second-smallest numbers encountered.\n1. Finally, it computes the product difference of these values and returns the result.\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n \n\n- Space complexity:\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int maxProductDifference(vector<int>& nums) {\n // Initialize variables to hold the largest, second-largest, smallest, and second-smallest numbers\n int biggest = 0;\n int secondBiggest = 0;\n int smallest = INT_MAX;\n int secondSmallest = INT_MAX;\n \n // Iterate through the input array \'nums\'\n for (int num : nums) {\n // Check if \'num\' is greater than the current \'biggest\'\n if (num > biggest) {\n // Update \'secondBiggest\' and \'biggest\' accordingly\n secondBiggest = biggest;\n biggest = num;\n } else {\n // If \'num\' is not the largest, update \'secondBiggest\' if necessary\n secondBiggest = max(secondBiggest, num);\n }\n \n // Check if \'num\' is smaller than the current \'smallest\'\n if (num < smallest) {\n // Update \'secondSmallest\' and \'smallest\' accordingly\n secondSmallest = smallest;\n smallest = num;\n } else {\n // If \'num\' is not the smallest, update \'secondSmallest\' if necessary\n secondSmallest = min(secondSmallest, num);\n }\n }\n \n // Calculate the product difference of the largest and smallest values and return the result\n return biggest * secondBiggest - smallest * secondSmallest;\n }\n};\n\n\n\n```\n```Java []\nclass Solution {\n public int maxProductDifference(int[] nums) {\n int biggest = 0;\n int secondBiggest = 0;\n int smallest = Integer.MAX_VALUE;\n int secondSmallest = Integer.MAX_VALUE;\n \n for (int num : nums) {\n if (num > biggest) {\n secondBiggest = biggest;\n biggest = num;\n } else {\n secondBiggest = Math.max(secondBiggest, num);\n }\n \n if (num < smallest) {\n secondSmallest = smallest;\n smallest = num;\n } else {\n secondSmallest = Math.min(secondSmallest, num);\n }\n }\n \n return biggest * secondBiggest - smallest * secondSmallest;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def maxProductDifference(self, nums: List[int]) -> int:\n biggest = 0\n second_biggest = 0\n smallest = inf\n second_smallest = inf\n \n for num in nums:\n if num > biggest:\n second_biggest = biggest\n biggest = num\n else:\n second_biggest = max(second_biggest, num)\n \n if num < smallest:\n second_smallest = smallest\n smallest = num\n else:\n second_smallest = min(second_smallest, num)\n \n return biggest * second_biggest - smallest * second_smallest\n\n\n```\n```javascript []\n\n\n\n```\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n---
97,838
Maximum Product Difference Between Two Pairs
maximum-product-difference-between-two-pairs
The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d). Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized. Return the maximum such product difference.
Array,Sorting
Easy
If you only had to find the maximum product of 2 numbers in an array, which 2 numbers should you choose? We only need to worry about 4 numbers in the array.
538
8
# 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:\nO(n log n), where n is the number of elements in the input array. This is because sorting the array takes O(n log n) time.\n\n- Space complexity:\no(1)\n```c++ []\nclass Solution {\npublic:\n int maxProductDifference(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n1=(nums[nums.size()-1]) * (nums[nums.size()-2]);\n int n2=nums[0]*nums[1];\n return n1-n2;\n }\n};\n```\n```python []\nclass Solution:\n def maxProductDifference(self, nums):\n nums.sort()\n n1 = nums[-1] * nums[-2]\n n2 = nums[0] * nums[1]\n return n1 - n2\n\n```\n```java []\nclass Solution {\n public int maxProductDifference(int[] nums) {\n Arrays.sort(nums);\n int n1 = nums[nums.length - 1] * nums[nums.length - 2];\n int n2 = nums[0] * nums[1];\n return n1 - n2;\n }\n}\n```\n![WhatsApp Image 2023-10-20 at 08.23.29.jpeg]()\n
97,848
Cyclically Rotating a Grid
cyclically-rotating-a-grid
You are given an m x n integer matrix grid​​​, where m and n are both even integers, and an integer k. The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: Return the matrix after applying k cyclic rotations to it.
Array,Matrix,Simulation
Medium
First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it.
1,384
26
\n```\nclass Solution:\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n m, n = len(grid), len(grid[0]) # dimensions \n \n for r in range(min(m, n)//2): \n i = j = r\n vals = []\n for jj in range(j, n-j-1): vals.append(grid[i][jj])\n for ii in range(i, m-i-1): vals.append(grid[ii][n-j-1])\n for jj in range(n-j-1, j, -1): vals.append(grid[m-i-1][jj])\n for ii in range(m-i-1, i, -1): vals.append(grid[ii][j])\n \n kk = k % len(vals)\n vals = vals[kk:] + vals[:kk]\n \n x = 0 \n for jj in range(j, n-j-1): grid[i][jj] = vals[x]; x += 1\n for ii in range(i, m-i-1): grid[ii][n-j-1] = vals[x]; x += 1\n for jj in range(n-j-1, j, -1): grid[m-i-1][jj] = vals[x]; x += 1\n for ii in range(m-i-1, i, -1): grid[ii][j] = vals[x]; x += 1\n return grid\n```
97,881
Cyclically Rotating a Grid
cyclically-rotating-a-grid
You are given an m x n integer matrix grid​​​, where m and n are both even integers, and an integer k. The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: Return the matrix after applying k cyclic rotations to it.
Array,Matrix,Simulation
Medium
First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it.
1,234
19
**Method 1: The naive method**\nRotate the Matrix layer by layer K times -> Time = O(m * n * k) and since k = 10^9, it will give TLE.\n\n**METHOD 2: Rotate K times in one Go**\n![image]()\n\n```\nclass Solution:\n def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:\n n = len(grid)\n m = len(grid[0])\n \n i, j = 0, 0\n bottom, right = n-1, m-1 \n while i < n//2 and j < m//2:\n temp = []\n for x in range(j, right):\n temp.append(grid[i][x])\n for x in range(i, bottom):\n temp.append(grid[x][right])\n for x in range(right, j, -1):\n temp.append(grid[bottom][x])\n for x in range(bottom, i, -1):\n temp.append(grid[x][j])\n \n \n indx = 0\n for x in range(j, right):\n grid[i][x] = temp[(k + indx)%len(temp)]\n indx += 1\n for x in range(i, bottom):\n grid[x][right] = temp[(k + indx)%len(temp)]\n indx += 1\n for x in range(right, j, -1):\n grid[bottom][x] = temp[(k + indx)%len(temp)]\n indx += 1\n for x in range(bottom, i, -1):\n grid[x][j] = temp[(k + indx)%len(temp)]\n indx += 1\n \n i += 1\n j += 1\n bottom -= 1\n right -= 1\n return grid\n```\nTime = O(n * m) for matrix traversal.\nSpace = O(n) for the temp array, but still since the same matrix is modified, Hence it is an **in-place solution**.
97,882
Cyclically Rotating a Grid
cyclically-rotating-a-grid
You are given an m x n integer matrix grid​​​, where m and n are both even integers, and an integer k. The matrix is composed of several layers, which is shown in the below image, where each color is its own layer: A cyclic rotation of the matrix is done by cyclically rotating each layer in the matrix. To cyclically rotate a layer once, each element in the layer will take the place of the adjacent element in the counter-clockwise direction. An example rotation is shown below: Return the matrix after applying k cyclic rotations to it.
Array,Matrix,Simulation
Medium
First, you need to consider each layer separately as an array. Just cycle this array and then re-assign it.
449
7
## IDEA: \n\uD83D\uDC49 keep the boundary matrix in a list\n\uD83D\uDC49 Then rotate by len % k\n\uD83D\uDC49 again store in the matrix\n\'\'\'\n\n\tclass Solution:\n def rotateGrid(self, mat: List[List[int]], k: int) -> List[List[int]]:\n \n top = 0\n bottom = len(mat)-1\n left = 0\n right = len(mat[0])-1\n res = []\n\t\t\n # storing in res all the boundry matrix elements.\n while left<right and top<bottom:\n local=[]\n for i in range(left,right+1):\n local.append(mat[top][i])\n top+=1\n\t\t\t\n for i in range(top,bottom+1):\n local.append(mat[i][right])\n right-=1\n\t\t\t\n for i in range(right,left-1,-1):\n local.append(mat[bottom][i])\n bottom-=1\n\t\t\t\n for i in range(bottom,top-1,-1):\n local.append(mat[i][left])\n left+=1\n \n res.append(local)\n\t\t\t\n\t\t# rotating the elements by k.\n for ele in res:\n l=len(ele)\n r=k%l\n ele[::]=ele[r:]+ele[:r]\n \n\t\t# Again storing in the matrix. \n top = 0\n bottom = len(mat)-1\n left = 0\n right = len(mat[0])-1\n while left<right and top<bottom:\n local=res.pop(0)\n for i in range(left,right+1):\n mat[top][i] = local.pop(0)\n top+=1\n\t\t\t\n for i in range(top,bottom+1):\n mat[i][right] = local.pop(0)\n right-=1\n\t\t\t\n for i in range(right,left-1,-1):\n mat[bottom][i] = local.pop(0)\n bottom-=1\n\t\t\t\n for i in range(bottom,top-1,-1):\n mat[i][left] = local.pop(0)\n left+=1\n \n return mat\n\t\t\nIf you got helped ...... Please **upvote !!** \uD83E\uDD1E\nif any doubt feel free to ask \uD83E\uDD17
97,893
Number of Wonderful Substrings
number-of-wonderful-substrings
A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string.
Hash Table,String,Bit Manipulation,Prefix Sum
Medium
For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit.
11,650
154
The idea is similar to:\n- [1371. Find the Longest Substring Containing Vowels in Even Counts](). \n- [1542. Find Longest Awesome Substring]((similar-to-1371))\n\nWe can track whether we have an odd (1) or even (0) number of characters using a bit mask. Every time we see a character - we just flip the corresponding bit. Unlike related problems listed above, where we track the minimum position for each bitmask, here we count how many times we arrived at that bitmask (`cnt[mask]`).\n\n![image]()\n\nIn the example above, we have four wonderful substrings: `abab`, `cc`, `ababcc` and `bccb`.\n\n>For simplicity, we only show substrings with all even characters. We will look into counting substrings with one odd character below.\n\nSay we arrive at bitmask `0000000001` at index `i`. That means that the count of all characters in `word[0..i]` is even except for `a`. What if we have seen this bitmask before at index `j`? Same, count for character `a` is odd in `word[0..j]`. Now, it tells us that the count for all characters in `word[j + 1, i]` is even... We have found a wonderful substring!\n\nFinal stretch - our substring can have up to one "odd" character. So we mutate our bitmask - one character at a time, and add the count for the mutated bitmask. The substring between the original and mutated mask will have a single "odd" character. In other words, XOR of these two masks will have one bit set.\n\n> This is the same technique as we used in [1542. Find Longest Awesome Substring]((similar-to-1371)).\n\nFor example, for bitmask `0000000100` (or 4, which correspond to the first `c` in the example above), we will try:\n1. `0000000101`\n2. `0000000110`\n3. `0000000000` -> this matches `ababc` substring in the example above.\n4. `0000001100` \n\t- and so on...\n\n**C++**\nNote that we run the count one more time for the original mask - the shift `1 << 11` is offset by `1023 &` operation.\n\n```cpp\nlong long wonderfulSubstrings(string word) {\n long cnt[1024] = { 1 }, mask = 0, res = 0;\n for (auto ch : word) {\n mask ^= 1 << (ch - \'a\');\n res += cnt[mask];\n for (auto n = 0; n < 10; ++n)\n res += cnt[mask ^ (1 << n)];\n ++cnt[mask];\n }\n return res;\n}\n```\n**Java**\n```java\npublic long wonderfulSubstrings(String word) {\n long cnt[] = new long[1024], res = 0;\n int mask = 0;\n cnt[0] = 1;\n for (var ch : word.toCharArray()) {\n mask ^= 1 << (ch - \'a\');\n res += cnt[mask];\n for (var n = 0; n < 10; ++n)\n res += cnt[mask ^ (1 << n)];\n ++cnt[mask];\n }\n return res;\n}\n```\n**Python 3**\n```python\nclass Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n cnt, res, mask = [1] + [0] * 1023, 0, 0\n for ch in word:\n mask ^= 1 << (ord(ch) - ord(\'a\'))\n res += cnt[mask]\n for n in range(10):\n res += cnt[mask ^ 1 << n];\n cnt[mask] += 1\n return res\n```
97,927
Number of Wonderful Substrings
number-of-wonderful-substrings
A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string.
Hash Table,String,Bit Manipulation,Prefix Sum
Medium
For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit.
1,254
11
\n```\nclass Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n ans = mask = 0\n freq = defaultdict(int, {0: 1})\n for ch in word: \n mask ^= 1 << ord(ch)-97\n ans += freq[mask]\n for i in range(10): ans += freq[mask ^ 1 << i]\n freq[mask] += 1\n return ans \n```
97,936
Number of Wonderful Substrings
number-of-wonderful-substrings
A wonderful string is a string where at most one letter appears an odd number of times. Given a string word that consists of the first ten lowercase English letters ('a' through 'j'), return the number of wonderful non-empty substrings in word. If the same substring appears multiple times in word, then count each occurrence separately. A substring is a contiguous sequence of characters in a string.
Hash Table,String,Bit Manipulation,Prefix Sum
Medium
For each prefix of the string, check which characters are of even frequency and which are not and represent it by a bitmask. Find the other prefixes whose masks differs from the current prefix mask by at most one bit.
1,246
6
explaination for this `res+=dp[curr ^(1<<i)]`.\nIntuition :\nThis was similar to solving the problem of finding the subarray of sum k. This can be solved using prefix sum concept . For example given an array a= [ 2, 3 ,4 ,5 ,10] and k=9, we can calculate running sum and store Its prefix sum array as dp=[2,5,9,14,24]. Here for a running sum "rs =14 " which occured at index j=3, we can check if "rs - k=14-9=5" is available in dp array. let\'s say "rs - k=5" was available at index i=1 (i<j) then subarray a[i+1 : j ]=a[2:3] will sum upto k=9.\n\nNow coming to this problem, let\'s say we want a subarray which gives 1000000000 and we have a "curr" value( similar to running sum mentioned above ) so we should check if dp[ curr - 1000000000] . But since these are binary numbers dp[ curr - 1000000000] is equivalent to dp[ curr ^ 1000000000] --> dp[ curr^(1<<pos)] here pos=10. \nThe reason for checking ``curr^1000000000`` was `curr ^ (curr^1000000000) = 1000000000 `.\nSimilarily we want to check all other possibilities like 0100000000, 0010000000,... etc. All these cases corresponds to having one character with odd count and others with even count\n\n\n```\nclass Solution:\n def wonderfulSubstrings(self, word: str) -> int:\n \n # we are representing each char with a bit, 0 for count being even and 1 for odd\n # 10 char from a to j\n # array to store 2^10 numbers\n dp=[0]*1024\n \n # jihgfedcba -> 0000000000\n curr=0 # 000..(0-> 10 times) \n \n # since we are starting with curr as 0 make dp[0]=1\n dp[0]=1\n \n # result\n res=0\n \n for c in word:\n # 1<<i sets i th bit to 1 and else to 0\n # xor will toggle the bit\n curr^= (1<<(ord(c)-ord(\'a\')))\n \n # if curr occurred earlier at j and now at i then [j+1: i] has all zeroes\n # this was to count all zeroes case\n res+=dp[curr]\n \n # now to check if these 100000..,010000..,001.. cases can be acheived using brute force\n # we want to see if curr ^ delta = 10000.. or 010000.. etc\n # curr^delta =1000... then\n # curr ^ 1000.. = delta\n \n for i in range(10):\n res+=dp[curr ^(1<<i)] \n \n dp[curr]+=1 \n \n \n \n return res\n```
97,944
Find a Peak Element II
find-a-peak-element-ii
A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j]. You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.
Array,Binary Search,Divide and Conquer,Matrix
Medium
Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If it's on the left side, run this algorithm on subarray left_side + central_column. If it's on the right side, run this algorithm on subarray right_side + central_column
30,251
912
# **Prerequisites:**\nSolve the 1D version of this problem first to better understand the 2D version. Here is the link for 1D version : [**Find-Peak-Element-1D**]()\n\n---\n\n# **Logic:**\nFor given `matrix[M][N]`, create a new 1D array `maxPlaneOfCol[N]` which stores the largest number in each column.\n\n![image]()\n\n\n\n\nFor the above matrix, **`maxPlaneOfCol = {4, 9, 6, 3, 7, 5}`**\nLet `maxPlaneOfCol[i]` represent a height of the plane at index `i`\n![image]()\n\nNow we have reduced the 2D problem to a 1D problem. Using the same logic as in [Solution-Find-Peak-Element](), we can find the column that has the peak plane. Remember, the elements in **`maxPlaneOfCol`** represent the largest number of each column. If we find a peak plane at index `\'p\'`, then it means that there is an element in `column# p` which is bigger than all the elments in `column# p-1` and `column# p+1`. Once we have the peak column `p`, we can easily find the `row#` of the peak element in the `column# p`. Now you have both `row#` and `col#` of a peak element in 2D array. Thats it !!\n\n**BUT!! BUT!! BUT!!**\n\nTo populate **`maxPlaneOfCol[N]`**, we need to traverse all the columns in the 2D array, which basically means that we have to read all the elements in 2D array. So, when you are reading the entire 2D array, why not just return the coordinates of the largest number in the 2D array ?!! The largest element is gauranteed to be a peak element, isn\'t it !!??\n\n**HOLD ON** \uD83E\uDD14\uD83E\uDD14\uD83E\uDD14\n\nDo we really need to find the `max` in each and every column? Will it not be sufficent to just find the `max` of the `midColumn` ? If we find the `max` of only the `midColumn`, we will calculate `max` of only `log(N)` columns in our entire algorithm. \nHence the **Time Complexity is M*log(N)**. Below is the prettiest code I could come up with.\n\n---\n\n**REQUEST :** If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.\n\n---\n\n# **Code:**\n\n<iframe src="" frameBorder="0" width="1050" height="500"></iframe>\n
97,975
Find a Peak Element II
find-a-peak-element-ii
A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j]. You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.
Array,Binary Search,Divide and Conquer,Matrix
Medium
Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If it's on the left side, run this algorithm on subarray left_side + central_column. If it's on the right side, run this algorithm on subarray right_side + central_column
415
6
-->\n\n# Approach\nThe problem is to find a peak element in a 2D grid, which is an element greater than its adjacent neighbors (up, down, left, right). The grid is surrounded by a boundary of -1.\n\nThe provided algorithm uses a binary search approach to find the peak element. It iterates over columns and uses binary search within each column to find the peak.\n\n1. For each column, it performs a binary search to find the maximum element in that column and its corresponding row (maxEl function).\n2. Then, it compares the peak element in the column with its adjacent elements (left and right).\n3. Based on the comparison, it updates the search range for the next iteration until a peak element is found.\n\n# Complexity\n- Time complexity:\nO(log(m)*n)\n\n- Space complexity:\nO(1)\n\n```C++ []\nclass Solution {\npublic:\n int maxEl(vector<vector<int>>& mat, int n, int m, int col) {\n int maxi = -1;\n int ind = -1; \n for(int i = 0; i<n; i++) {\n if(mat[i][col]>maxi) {\n maxi = mat[i][col];\n ind = i;\n }\n }\n return ind;\n }\n vector<int> findPeakGrid(vector<vector<int>>& mat) {\n int n = mat.size();\n int m = mat[0].size();\n int low = 0;\n int high = m - 1; \n while(low<=high) {\n int mid = (low+high)/2;\n int row = maxEl(mat, n, m, mid);\n int left = mid-1>=0 ? mat[row][mid-1] : -1; \n int right = mid+1<m ? mat[row][mid+1] : -1; \n if(mat[row][mid]>left && mat[row][mid]>right) return {row, mid};\n else if(mat[row][mid]<left) high = mid-1;\n else low = mid+1;\n }\n return {-1,-1};\n }\n};\n\n```\n```Java []\nclass Solution {\n public int maxEl(int[][] mat, int n, int m, int col) {\n int maxi = -1;\n int ind = -1;\n for (int i = 0; i < n; i++) {\n if (mat[i][col] > maxi) {\n maxi = mat[i][col];\n ind = i;\n }\n }\n return ind;\n }\n\n public int[] findPeakGrid(int[][] mat) {\n int n = mat.length;\n int m = mat[0].length;\n int low = 0;\n int high = m - 1;\n\n while (low <= high) {\n int mid = (low + high) / 2;\n int row = maxEl(mat, n, m, mid);\n int left = mid - 1 >= 0 ? mat[row][mid - 1] : -1;\n int right = mid + 1 < m ? mat[row][mid + 1] : -1;\n\n if (mat[row][mid] > left && mat[row][mid] > right)\n return new int[]{row, mid};\n else if (mat[row][mid] < left)\n high = mid - 1;\n else\n low = mid + 1;\n }\n return new int[]{-1, -1};\n }\n}\n\n```\n```Python []\nclass Solution:\n def maxEl(self, mat, n, m, col):\n maxi = -1\n ind = -1\n for i in range(n):\n if mat[i][col] > maxi:\n maxi = mat[i][col]\n ind = i\n return ind\n\n def findPeakGrid(self, mat):\n n = len(mat)\n m = len(mat[0])\n low = 0\n high = m - 1\n\n while low <= high:\n mid = (low + high) // 2\n row = self.maxEl(mat, n, m, mid)\n left = mat[row][mid - 1] if mid - 1 >= 0 else -1\n right = mat[row][mid + 1] if mid + 1 < m else -1\n\n if mat[row][mid] > left and mat[row][mid] > right:\n return [row, mid]\n elif mat[row][mid] < left:\n high = mid - 1\n else:\n low = mid + 1\n return [-1, -1]\n\n```\n
97,980
Find a Peak Element II
find-a-peak-element-ii
A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j]. You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.
Array,Binary Search,Divide and Conquer,Matrix
Medium
Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If it's on the left side, run this algorithm on subarray left_side + central_column. If it's on the right side, run this algorithm on subarray right_side + central_column
3,464
22
### Explanation\n- Below code is an implementation to `hint` section\n- Start from `mid` column, if a peak is found in this column, return its location\n\t- If peak is on the left, then do a binary search on the left side `columns between [left, mid-1]`\n\t- If peak is on the right, then do a binary search on the right side `columns between [mid+1, right]`\n- Time: `O(m*log(n))`\n- Space: `O(1)`\n- Thanks @andy_ng for helping improve this solution\n### Implementation\n```\nclass Solution:\n def findPeakGrid(self, mat: List[List[int]]) -> List[int]:\n m, n = len(mat), len(mat[0])\n l, r = 0, n\n while l <= r:\n mid = (l + r) // 2\n cur_max, left = 0, False\n for i in range(m):\n if i > 0 and mat[i-1][mid] >= mat[i][mid]:\n continue\n if i+1 < m and mat[i+1][mid] >= mat[i][mid]: \n continue\n if mid+1 < n and mat[i][mid+1] >= mat[i][mid]: \n cur_max, left = mat[i][mid], not mat[i][mid] > cur_max\n continue\n if mid > 0 and mat[i][mid-1] >= mat[i][mid]: \n cur_max, left = mat[i][mid], mat[i][mid] > cur_max\n continue\n return [i, mid]\n if left:\n r = mid-1\n else:\n l = mid+1\n return []\n```
98,010
Find a Peak Element II
find-a-peak-element-ii
A peak element in a 2D grid is an element that is strictly greater than all of its adjacent neighbors to the left, right, top, and bottom. Given a 0-indexed m x n matrix mat where no two adjacent cells are equal, find any peak element mat[i][j] and return the length 2 array [i,j]. You may assume that the entire matrix is surrounded by an outer perimeter with the value -1 in each cell. You must write an algorithm that runs in O(m log(n)) or O(n log(m)) time.
Array,Binary Search,Divide and Conquer,Matrix
Medium
Let's assume that the width of the array is bigger than the height, otherwise, we will split in another direction. Split the array into three parts: central column left side and right side. Go through the central column and two neighbor columns and look for maximum. If it's in the central column - this is our peak. If it's on the left side, run this algorithm on subarray left_side + central_column. If it's on the right side, run this algorithm on subarray right_side + central_column
1,326
14
```\nclass Solution:\n def findPeakGrid(self, mat: List[List[int]]) -> List[int]:\n """\n How is Binary Search possible here?\n First we should understand that this is a Greedy Problem.\n \n Say we took the largest element in a column, if any of adjacent\n element is greater than the current Largest, we can just greedily go through\n the largest elements till we find a Peak Element\n \n In my Solution I am splitting column wise because in the hint it is given that width\n is more that the height.\n """\n start, end = 0, len(mat[0]) - 1\n while start <= end:\n cmid = start + (end - start) // 2\n \n # Finding the largest element in the middle Column\n ridx, curLargest = 0, float(\'-inf\')\n for i in range(len(mat)):\n if mat[i][cmid] > curLargest:\n curLargest = mat[i][cmid]\n ridx= i \n \n # Checking the adjacent element\n leftisBig = cmid > start and mat[ridx][cmid - 1] > mat[ridx][cmid]\n rightisBig = cmid < end and mat[ridx][cmid + 1] > mat[ridx][cmid]\n \n if not leftisBig and not rightisBig:\n return [ridx, cmid]\n \n if leftisBig:\n end = cmid - 1\n else:\n start = cmid + 1\n```\n\nFeel Free to ask any doubts in the comment
98,013
Build Array from Permutation
build-array-from-permutation
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
Array,Simulation
Easy
Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application
36,279
310
The intuition behind doing the problem in constant space is that we must process the original array:\n1. in-place,\n2. in a way that allows us to move the correct value (`nums[nums[i]`) to it\'s correct place (`i`) \n3. while also keeping the original value, (`nums[i]`), in-place, in some way so that we can use it when needed later. \n\nWe must keep `nums[i]` intact because if, for example, a later position in the array, say `j`, has a value `nums[j] = i`, but we\'ve overwrote the value at `i` (`nums[i]`) with `nums[nums[i]]` already, then we\'re out of luck.\n\nTo accomplish this task, we\'re going to use the fact that if we have a number of the form `a = qb + r`, where `b` and `r` are *not* multiples of `q` and `r` < `q`, then we can extract `b` and `r` with the following:\n- `b = a // q` (where `//` is integer division) - we know that `qb` when divided by `q` will give us `b`, however we still would need to get rid of the `r // q`. From our requirements though, `r < q`, so `r // q` will always be `0`, thus `b = (qb//q) + (r//q) = b + 0 = b`\n- `r = a % q` - we know that `qb` is a multiple of `q`, thus is divided by it cleanly and we know that `r < q`, so `r` is not a multiple of `q`, therefore the remainder when dividing `a = qb + r` by `q` is just `r`\n\nWe need to find a way to transform every element of `nums` into the form `a = qb + r`. \n\nAt every `i`, `nums[nums[i]]` is going to be our `b` and the original value, `nums[i]` is our `r`. Now we just need a `q` that satisfies the `r < q`, for all the possible `r` values (all `nums[i]`). Luckily, we have such a `q` already, as our array values are ***indices*** into the same array. `q = len(nums)` is always guaranteed to be greater than all `nums[i]` because each index is always within the bounds of the array, from `0` to `len(nums) - 1`.\n\nThe rest is translation to code (purposely verbose):\n```\ndef buildArray(nums: List[int]) -> List[int]:\n q = len(nums)\n \n # turn the array into a=qb+r\n for i in range(len(nums)):\n\tr = nums[i]\n\t\n\t# retrieve correct value from potentially already processed element\n\t# i.e. get r from something maybe already in the form a = qb + r\n\t# if it isnt already processed (doesnt have qb yet), that\'s ok b/c\n\t# r < q, so r % q will return the same value\n\tb = nums[nums[i]] % q\n\t\n # put it all together\n\tnums[i] = q*b + r\n\t\n# extract just the final b values\n for i in range(len(nums)):\n nums[i] = nums[i] // q\n \n return nums\n```\nCondensed version:\n```\ndef buildArray(nums: List[int]) -> List[int]:\n q = len(nums)\n for i,c in enumerate(nums):\n nums[i] += q * (nums[c] % q)\n for i,_ in enumerate(nums):\n nums[i] //= q\n return nums\n```
98,033
Build Array from Permutation
build-array-from-permutation
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
Array,Simulation
Easy
Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application
2,275
6
\'\'\'\n ans=[]\n for i in range(len(nums)):\n ans.append(nums[nums[i]])\n return ans\n\'\'\'
98,044
Build Array from Permutation
build-array-from-permutation
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
Array,Simulation
Easy
Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application
8,689
79
**Explanation for O(1) space complexity**\n\n*Lets first see generally what should be done.*\n\n**1.** We need to store 2 values in one place, so we will use math (quotient and remainder)\n\t \n\n**2.** Let, size of array = **n**\n original number = **a**\n final number = **b**\n\t \n**3.** So we will store **a = a + n*b**\n\n**4.** On taking **a%n**, we will get **a**\n On doing **a/n**, we will get **b**\n\t \n**5.** Here the **b** that we are using is actually an **a** and there is a chance that it might be an **a** that is updated (final number)\n To get **a** from **a**, we use **a%n**\n So, here it will be **b%n**\n \n **6.** Finally, our equation becomes **a=a +n(b%n)**\n \n **7.** In the question **a=nums[i] and b=nums[nums[i]]**\n \n **8.** So finally, the equation becomes\n **nums[i] = nums[i] + n * (nums[nums[i]]%n)**\n\n***\n**Update 1 (Intuition):**\nIn the question, it\'s given that `nums[i]` is always less than the length of nums. So, we take a number bigger than our numbers in the array. Here, we took it to be **nums.length()**.\nWe are updating our number in such a way that on taking `nums[i] % n` will return the original number and `nums[i]/n` will give the new number. \nSince we are adding` n*(new number)` to our original number, then `nums[i] % n` will be the previous number because the remainder will be the same.\nEx: let `n=7`, `nums[i] = 3`, `new number = 5`.\nSo, initially, `nums[i] = original number % n` => `3%7 =3`\nNow, lets update to get the new value. `nums[i] = nums[i] + n * new number` => `nums[i] = 3 + 7*5 = 38`\nTo get original number: `nums[i]%n` => `38%7 = 3`\nTo get the new number: `nums[i]/n` => `38/7 = 5`\n***\n**Update 2 (Summary):**\t \nAs we proceed through the loop, we are updating the value of `nums[i]`\nIn `b`, we are storing the value of `nums[nums[i]]` (the original value, not the updated one)\nFor example, **we updated nums[i] for i=0,1,2** and at 3, `let nums[3] =0` .\nHere, we need to store two values, `a=nums[3]` and `b=nums[nums[3]] = nums[0]`\nSo, *we need to store the value of nums[0] in b* .\nCurrently, **the value of nums[0] is updated one** and we need to store the original value.\nTo get the `original value from nums[i]`, we do `nums[i] % n`, which we will store in b. (see point 4)\nSo, `nums[nums[3]] % n` = `nums[0] % n` = `original value of nums[0]`\n(if we did not use %n here, then it would have given ( `nums[0] = nums[0] + n*(something)`) , coz it was updated by the loop for i=0 . \n \n***\t \n\n*Here is the C++ solution for the same:*\n\t \n```\nclass Solution {\npublic:\n vector<int> buildArray(vector<int>& nums) {\n \n \n int n=nums.size();\n \n for(int i=0;i<n;++i){\n \n nums[i] = nums[i] + n * (nums[nums[i]]%n);\n \n }\n \n for(int i=0;i<n;++i){\n nums[i]/=n;\n }\n \n return nums;\n }\n};\n```\n\n
98,045
Build Array from Permutation
build-array-from-permutation
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
Array,Simulation
Easy
Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application
8,227
80
**O(1) approach**\n\t\t \n\t\t I am just explaining O(1) space complexity approach and it can be implemented using any language. i am also sharing the c++ code.\n\nlet a = nums[i] and b= nums[nums[i]]\nlet nums=[0,2,1,5,3,4]\nif a = nums[3] = 5 then b = nums[nums[3]] = nums[5] = 4\na+n*b = 5 + 6*4 = 29\n29%n = 29 % 6 = 5 = a; so formula for a = (a+nb)%n \n29/n = 29/6 = 4 = b ; so formula for b = (a+nb)/n\n\nso in the first step we will be calculating a+nb for each index and replacing element at this value by the obtained result.\ni.e,\n```\nfor(int i=0;i<n;i++)\n {\n nums[i] = nums[i]+(n*(nums[nums[i]]%n)); \n // here %n is taken to compensate the changes happened in previous iteration and get exat value of b;\n }\n```\n In the next step we just have to replace value at each index by num[i]/n to get b which is equal to nums[nums[i]] ;\n i.e,\n ```\n for(int i=0;i<n;i++)\n {\n nums[i]/=n;\n }\n```\nnums is the vector to be returned;\n\t\t\n**FULL CODE**\n```\n vector<int> buildArray(vector<int>& nums) \n {\n \n int n = nums.size();\n for(int i=0;i<n;i++)\n {\n nums[i] = nums[i]+(n*(nums[nums[i]]%n));\n }\n for(int i=0;i<n;i++)\n {\n nums[i]/=n;\n }\n return nums;\n }\n\t\n\t//please upvote if you guys find it useful.\n```\n![up.png]()\n
98,058
Build Array from Permutation
build-array-from-permutation
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where ans[i] = nums[nums[i]] for each 0 <= i < nums.length and return it. A zero-based permutation nums is an array of distinct integers from 0 to nums.length - 1 (inclusive).
Array,Simulation
Easy
Just apply what's said in the statement. Notice that you can't apply it on the same array directly since some elements will change after application
7,321
48
**Python :**\n\n```\ndef buildArray(self, nums: List[int]) -> List[int]:\n\treturn [nums[i] for i in nums]\n```\n\n**Like it ? please upvote !**
98,066
Eliminate Maximum Number of Monsters
eliminate-maximum-number-of-monsters
You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.
Array,Greedy,Sorting
Medium
Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive.
2,069
49
# Intuition\nWe can calculate number of turns to arrive at the city\n\n# Approach\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:04` Heap solution I came up with at first\n`2:38` Two key points with O(n) solution for Eliminate Maximum Number of Monsters\n`2:59` Explain the first key point\n`5:08` Explain the second key point\n`6:19` How we can eliminate monsters that are out of bounds\n`8:48` Let\'s see another case\n`9:52` How we can calculate eliminated numbers\n`10:56` Coding\n`13:03` Time Complexity and Space Complexity\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 2,966\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n---\n\n## How we think about a solution\n\n\nFirst of all, I came up with heap solution like this.\n```\nclass Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n heap = []\n for i in range(len(dist)):\n heapq.heappush(heap, dist[i] / speed[i])\n \n res = 0\n\n while heap:\n if heapq.heappop(heap) <= res:\n break\n res += 1\n \n return res \n```\n\nThe heap has `number of turns` to arrive at city and we can eliminate monsters one by one that arrive at the city earlier, so `res` should be `number of monsters we can eliminate`, but it is considered as `chances` to try to eliminate them so far.\n\nSo if minimum turn in heap is less than or equal to `res`, monsters will arrive at the city before they are eliminated. The number of turns to arrive must be greater than or equal to `res`(chance) if you want to eliminate them.\n\nFor example\n```\nInput: dist = [1,2,2,3], speed = [1,1,1,1]\n```\n\nHeap has\n```\n[1.0, 2.0, 2.0, 3.0]\n```\nIn that case, we can eliminate `1.0` and one of `2.0` monsters. So now `res` should be `2`. \n\nLook at index `3`. there is another monster arriving at the city with `2` turns. But we elimiante `2.0` at index `2` when `res = 2`, so `2.0` at index `3` will reach the city before we elimiante it.\n\n```\noutput: 2\n```\n\nTime complexity is $$O(n log n)$$. I thought it was not bad. However result is slow. Actually I\'m not sure why. Is there special case?\n\nThat\'s how I try to think about $$O(n)$$ solution.\n\n\n---\n\n## O(n) solution\n\nWe have two points from the solution above.\n\n---\n\n\u2B50\uFE0F Points\n\n- We can calculate number of turns to arrive at the city.\n\n- We can eliminate monsters if number of turns to arrive is greater than or equal to chance to eliminate them.\n\n---\n\nLet me explain one by one.\n\n- **We can calculate number of turns to arrive at the city**\n\n```\nInput: dist = [1,3,4], speed = [1,1,1]\n```\n\nIn this case, There are 3 monsters, so create `monsters` list which is length of `3` with all `0` values.\n\n```\nmonsters = [0,0,0]\n\nIndex number is arrival(number of turns to arrive at the city)\nValue is number of monsters.\n```\n\n\nThen calculate each arrival\n```\nmath.ceil(dist[i] / speed[i])\n```\n\n- Why do we need `math.ceil`?\n\nBecause there are cases where we get float from `dist[i] / speed[i]`. Let\'s say we get `1.5`(dist = `3`, speed = `2`). In that case, the monster need `2` turns to arrive at the city. That\'s why we need to round it up. \n\nIf dist = `2` and speed = `2`, the monster need only `1` turn to arrive at the city.\n\nIn the end, we will have `monsters` list like this\n\n```\nmonsters = [0,1,0]\n\nmath.ceil(1 / 1) = 1\nmath.ceil(3 / 1) = 3 (out of bounds)\nmath.ceil(4 / 1) = 4 (out of bounds)\n```\n\nThat means there is one monster will arrive at the city with `1` turn. Wait! Somebody is wondering where the other monsters are. They are out of bounds(`3/1` and `4/1`).\n\nNo problem, we can count them. Let me explain it later.\n\n---\n\n\n- **We can eliminate monsters if number of turns to arrive is greater than or equal to chance to eliminate them**\n\nIt\'s time to calculate the number of monsters we can eliminate. Let\'s iteration through `monsters` list\n\n```\nmonsters = [0,1,0]\neliminated = 0 (0 monsters at index 0)\ni = 0 (coming from len(dist) or len(speed))\n```\n\n```\nmonsters = [0,1,0]\neliminated = 1 (`1 monster at index 1, we can eliminate the monster)\ni = 1\n```\n```\nmonsters = [0,1,0]\neliminated = 1 (0 monsters at index 2)\ni = 2\n```\nSo return value is `1`? That is wrong. We still have two monsters at index `3` and `4`. They are out of bounds.\n\n```\nmonsters = [0,1,0] (solution code)\nmonsters = [0,1,0,1,1] (including monsters which are out of bounds) \n```\nBut we don\'t have to care about monsters which are out of bounds, because since `monsters` list is created by `len(dist)` or `len(speed)`, we know that length of mosters list is `number of monsters` approaching to the city.\n\n---\n\n\u2B50\uFE0F Points\n\nWe reach the end of `mosters` list, that means we can eliminate all monsters including monsters which are out of bounds. Because we have a change to elimiate a monster every turns.\n\nIn other words, `index number of monsters list` is `chances` to eliminate them.\n\nDo you remember the second key point? It says "We can eliminate monsters if number of turns to arrive is greater than or equal to chance to eliminate them."\n\nWe can definitely eliminate monsters that are out of bounds when we reach end of `monsters` list.\n\nTo prove that,\n\nWhen we reach the end of monsters list, we have `3` chances(length of `monsters` list) and we use `1` change for a monster at index `1`.\n\nWe still have `2` chances at index `2`, the number of monsters that are out of bounds is `2` and they are coming from idnex `3` and `4`. So, we can elimaite all monsters.\n\nIn reality, \n```\nwhen index is 0(the first turn), elimiate a monster at index 1\nwhen index is 1(the second turn), elimiate a monster at index 3\nwhen index is 2(the thrid turn), elimiate a monster at index 4\n```\n---\n\nIn that case, we can simply return `len(dist)` or `len(speed)`.\n```\nreturn 3\n```\n\nLet\'s see one more case quickly.\n\n```\nInput: dist = [1,2,2,3], speed = [1,1,1,1]\n```\n`monsters` list should be\n```\nmonsters = [0,1,2,1]\n\nmath.ceil(dist[i] / speed[i])\nmath.ceil(1 / 1)\nmath.ceil(2 / 1)\nmath.ceil(2 / 1)\nmath.ceil(3 / 1)\n```\n\n```\nmonsters = [0,1,2,1]\neliminated = 0 (0 monsters at index 0)\ni = 0 (coming from len(dist) or len(speed))\n```\n```\nmonsters = [0,1,2,1]\neliminated = 1 (1 monster at index 1)\ni = 1\n```\n```\nmonsters = [0,1,2,1]\neliminated = 2 (2 monster at index 2, we can eliminete one monster)\ni = 2\n```\nWe can\'t eliminate two monsters at the same time, so\n```\nreturn 2(= eliminated)\n```\n\n- How we can calculate `eliminated` in solution code?\n\n`i` is number of chance to eliminate monsters. So, at each index, if total number of monsters is greater than index number, some monsters reach the city, that\'s why we return current index `i` because we can eliminte number of `i` monsters.\n\nTotal number of monsters so far should be `eliminated monsters` + `monsters from current index`\n```\nif eliminated + monsters[i] > i:\n return i\n```\n\nAs you can see in the first example, if we reach end of monsters list, that means we can elimiate all monsters including out of bounds. So we can eliminate `n` monster. `n` is length of `dist` or `speed`.\n\nI hope you understand main idea now. I spent 2 hours to write this. lol\nLet\'s see a real algorithm!\n\n---\n\n\n\n### Algorithm Overview:\n\nThe code is designed to determine how many monsters can be eliminated before they reach the target position based on their distances and speeds.\n\n### Detailed Explanation:\n\n1. Initialize necessary variables:\n - `n` is assigned the length of the `dist` list, representing the number of monsters.\n\n - `monsters` is initialized as a list of zeros with a length of `n`. This list will keep track of the number of monsters arriving at each time step.\n\n2. Iterate through the monsters:\n - A loop runs from 0 to `n-1`, representing each monster.\n\n - For each monster, calculate the `arrival` time, which is determined by dividing the monster\'s distance by its speed and rounding up using `math.ceil()`. This gives the time it will take for the monster to arrive at the target position.\n\n - If the `arrival` time is less than `n`, increment the corresponding element in the `monsters` list to count the number of monsters arriving at that time.\n\n3. Eliminate monsters:\n - Initialize the variable `eliminated` to 0. It will keep track of the number of eliminated monsters.\n\n - Iterate through the elements of the `monsters` list.\n\n - For each element, check if the current count of eliminated monsters (`eliminated`) plus the number of monsters arriving at this time step is greater than or equal to the time step `i`.\n\n - If this condition is met, return `i` as the result, indicating that the maximum number of monsters that can be eliminated before reaching their target position is at time `i`.\n\n - Update `eliminated` by adding the number of monsters arriving at this time step.\n \n4. If no return statement is executed within the loop, it means that all monsters have arrived before being eliminated. In this case, return `n`, indicating that all monsters have reached their target positions without being eliminated.\n\nThe algorithm calculates the maximum number of monsters that can be eliminated based on their arrival times and provides the earliest time when the elimination limit is reached.\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n1. The code first iterates through the \'dist\' and \'speed\' lists to calculate the arrival time for each monster and increments the corresponding bucket in the \'monsters\' list. This step has a time complexity of $$O(n)$$, where \'n\' is the length of the input lists.\n\n2. The code then iterates through the \'monsters\' list to check if the monsters can be eliminated at each time step. This step also has a time complexity of $$O(n)$$.\n\nTherefore, the overall time complexity of the code is $$O(n)$$.\n\n- Space complexity: $$O(n)$$\n\n1. The code uses an additional list \'monsters\' of the same size as the input lists, which has a space complexity of $$O(n)$$ to store the counts of monsters arriving at each time step.\n\n3. 2. There are a few integer variables used, but their space complexity is constant $$O(1)$$.\n\nTherefore, the overall space complexity of the code is $$O(n)$$ due to the \'monsters\' list.\n\n```python []\nclass Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n n = len(dist)\n monsters = [0] * n\n\n for i in range(n):\n arrival = math.ceil(dist[i] / speed[i])\n\n if arrival < n:\n monsters[arrival] += 1\n\n eliminated = 0\n for i in range(n):\n if eliminated + monsters[i] > i:\n return i\n\n eliminated += monsters[i]\n\n return n \n```\n```javascript []\nvar eliminateMaximum = function(dist, speed) {\n const n = dist.length;\n const monsters = new Array(n).fill(0);\n\n for (let i = 0; i < n; i++) {\n const arrival = Math.ceil(dist[i] / speed[i]);\n\n if (arrival < n) {\n monsters[arrival]++;\n }\n }\n\n let eliminated = 0;\n for (let i = 0; i < n; i++) {\n if (eliminated + monsters[i] > i) {\n return i;\n }\n\n eliminated += monsters[i];\n }\n\n return n; \n};\n```\n```java []\nclass Solution {\n public int eliminateMaximum(int[] dist, int[] speed) {\n int n = dist.length;\n int[] monsters = new int[n];\n\n for (int i = 0; i < n; i++) {\n int arrival = (int) Math.ceil((double) dist[i] / speed[i]);\n\n if (arrival < n) {\n monsters[arrival]++;\n }\n }\n\n int eliminated = 0;\n for (int i = 0; i < n; i++) {\n if (eliminated + monsters[i] > i) {\n return i;\n }\n\n eliminated += monsters[i];\n }\n\n return n; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int eliminateMaximum(vector<int>& dist, vector<int>& speed) {\n int n = dist.size();\n vector<int> monsters(n, 0);\n\n for (int i = 0; i < n; i++) {\n int arrival = ceil(static_cast<double>(dist[i]) / speed[i]);\n\n if (arrival < n) {\n monsters[arrival]++;\n }\n }\n\n int eliminated = 0;\n for (int i = 0; i < n; i++) {\n if (eliminated + monsters[i] > i) {\n return i;\n }\n\n eliminated += monsters[i];\n }\n\n return n; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\n\n\n\u25A0 Twitter\n\n\n\n### My next daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:04` How we can calculate x and y distances\n`0:55` We need to consider 2 cases and explain what if start and finish cell are the same position\n`2:20` Explain case 2, what if start and finish cell are different positions\n`4:53` Coding\n`6:18` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:04` Difficulty of Seat Reservation Manager\n`0:52` Two key points to solve Seat Reservation Manager\n`3:25` Coding\n`5:18` Time Complexity and Space Complexity\n
98,074
Eliminate Maximum Number of Monsters
eliminate-maximum-number-of-monsters
You are playing a video game where you are defending your city from a group of n monsters. You are given a 0-indexed integer array dist of size n, where dist[i] is the initial distance in kilometers of the ith monster from the city. The monsters walk toward the city at a constant speed. The speed of each monster is given to you in an integer array speed of size n, where speed[i] is the speed of the ith monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a single monster. However, the weapon takes one minute to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a loss, and the game ends before you can use your weapon. Return the maximum number of monsters that you can eliminate before you lose, or n if you can eliminate all the monsters before they reach the city.
Array,Greedy,Sorting
Medium
Find the amount of time it takes each monster to arrive. Find the order in which the monsters will arrive.
1,778
24
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust consider the arrival times of monsters.\nIn fact just consider how many monsters in the time iterval (t-1, t] will arrive.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Chinese spoken! Please turn English subtitles if necessary]\n[]()\nUse the array monsters_time[t] to store the monsters within the time interval (t-1, t]. When `t>n`, set `t=n`; the slow monsters can be easily handled.\n\nUse prefix sum\n`monsters+=monsters_time[shot-1];\n`\nwhen `shot<=monsters` return `shot-1`\n\nUse matplotlib.pyplot to show the testcase\n```\ndist = [3,5,7,4,5]\nspeed = [2,3,6,3,2]\n```\n![monsters_shot.jpg]()\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass Solution {\npublic:\n int eliminateMaximum(vector<int>& dist, vector<int>& speed) {\n int n=dist.size();\n vector<int> monsters_time(n+1, 0);\n #pragma unroll\n for(int i=0; i<n; i++){\n int t=ceil((double)dist[i]/speed[i]);\n if (t>n) t=n;\n monsters_time[t]++;\n }\n int shot=1, monsters=0;\n #pragma unroll\n for (; shot<=n; shot++){\n monsters+=monsters_time[shot-1];\n // cout<<"shot="<<shot<<" monsters="<<monsters<<"\\n";\n if (shot<=monsters) break;\n }\n return --shot;\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# Python Solution\n```\nclass Solution:\n def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:\n n=len(dist)\n monsters_t=[0]*(n+1)\n\n for i in range(n):\n # the following is ceil function\n t=(dist[i]+speed[i]-1)//speed[i] \n if t>n: \n t=n\n monsters_t[t]+=1\n \n shot=1\n monsters=0\n while shot<=n:\n monsters+=monsters_t[shot-1]\n if shot<=monsters: \n break\n shot+=1\n shot-=1\n return shot\n \n \n```\n![DALL\xB7E 2023-11-07 13.30.30 - Near the the dogs there are some pigeons and pigeonholes in the realistic style.png]()\n
98,090
Count Good Numbers
count-good-numbers
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Math,Recursion
Medium
Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n.
821
5
# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(log n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n\n# Code\n```python []\nimport math\n\nclass Solution:\n MOD = int(1e9+7)\n\n @staticmethod\n def binexp(a, b, MOD):\n a %= MOD\n res = 1\n\n while b > 0:\n if b & 1:\n res = res * a % MOD\n a = a * a % MOD\n b >>= 1\n\n return res\n\n def countGoodNumbers(self, n: int) -> int:\n odds = math.floor(n/2)\n evens = math.ceil(n/2)\n return int(self.binexp(5, evens, self.MOD) * self.binexp(4, odds, self.MOD) % self.MOD)\n```\n\n``` C++ []\nclass Solution {\npublic:\n static constexpr int MOD = 1e9 + 7;\n\n static long long binexp(long long a, long long b, int MOD) {\n a %= MOD;\n int res = 1;\n\n while (b > 0) {\n if (b & 1) {\n res = (res * 1LL * a) % MOD;\n }\n a = (a * 1LL * a) % MOD;\n b >>= 1;\n }\n\n return res;\n }\n\n int countGoodNumbers(long long n) {\n long long odds = floor(n / 2.0);\n long long evens = ceil(n / 2.0);\n return (binexp(5, evens, MOD) * 1LL * binexp(4, odds, MOD)) % MOD;\n }\n};\n```\n\n``` Golang []\nconst MOD = int(1e9 + 7)\n\nfunc binexp(a, b, MOD int) int {\n\ta %= MOD\n\tres := 1\n\n\tfor b > 0 {\n\t\tif b&1 == 1 {\n\t\t\tres = (res * a) % MOD\n\t\t}\n\t\ta = (a * a) % MOD\n\t\tb >>= 1\n\t}\n\n\treturn res\n}\n\nfunc countGoodNumbers(n int64) int {\n\todds := int(n / 2)\n\tevens := int((n + 1) / 2)\n\treturn (binexp(5, evens, MOD) * binexp(4, odds, MOD)) % MOD\n}\n```
98,137
Count Good Numbers
count-good-numbers
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Math,Recursion
Medium
Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n.
1,810
18
Approach: Each even index numbers have 5 possibilites (0,2,4,6,8) and each odd index numbers have 4 possibilities(2,3,5,7).\n\nSo, \nif n = 4, ans = 5 * 4 * 5 * 4 = 20 ^ (4/2) = 20 ^ 2\nif n = 7, ans = 5 * 4 * 5 * 4 * 5 * 4 * 5 = (20 ^ (6/2)) * 5 = (20 ^ 3) * 5 \n\nClearly it is visible that, if the number n is even ans is 20 ^ (n/2) and if the number n is odd, then along with doing 20 ^ (n/2) we need to multiply 5 at the end.\n\nNow if we do it linearly, it will throw a TLE. But using **inbuilt pow funtion** in python, we can calucate the pow(a,b) in log2(b) time. \n*Now, calculating power can exceed the size of variable, so pass a mod constant as 3rd parameter in pow funtion.*\n\n```\nclass Solution:\n def countGoodNumbers(self, n: int) -> int:\n ans = 1\n rem = n % 2\n n -= rem\n ans = pow(20, n//2, 10**9 + 7)\n if rem == 1:\n ans *= 5\n return ans % (10**9 + 7)\n```\n**Note:** It can be solved in constant time, by using math.pow funtion.\n\nTime : O(log (n/2)) = O(logn)\nSpace : O(1)
98,145
Count Good Numbers
count-good-numbers
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Math,Recursion
Medium
Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n.
3,402
21
1. For each even index, there are 5 options: `0`, `2`, `4`, `6`, `8`;\n2. For each odd index, there are 4 options: `2`, `3`, `5`, `7`;\n3. If `n` is even, the solution is `(4 * 5) ^ (n / 2)`; if odd, `(4 * 5) ^ (n / 2) * 5`.\n\n**Method 1: Bruteforce**\n\nThe input range is as large as `10 ^ 15`, hence the following bruteforec codes will get `TLE` (Time Limit Exceeded) without any surprise.\n\n```java\n private static final int MOD = 1_000_000_007;\n public int countGoodNumbers(long n) {\n long good = n % 2 == 0 ? 1 : 5;\n for (long i = 0, x = 4 * 5; i < n / 2; ++i) {\n good = good * x % MOD; \n }\n return (int)good;\n }\n```\n```python\n def countGoodNumbers(self, n: int) -> int:\n good, x = 5 ** (n % 2), 4 * 5\n for _ in range(n // 2):\n good = good * x % (10 ** 9 + 7)\n return good\n```\n\n**Analysis:**\n\nTime: `O(n)`, space: `O(1)`.\n\n----\n\n**Method 2: fast power**\n\nOur main object is to compute `x ^ (n // 2)`. To deal with the large input of `10 ^ 15`, we can use fast power: \n\nDenote `n // 2` as `i`. \n1. If `i` is even, increase `x` to `x ^ 2` and divide `i` by `2`;\n2. If `i` is odd, multiply `good` by `x` and deduct `i` by `1`; now `i` is even, go to procedure `1`.\n\nRepeat the above till `i` decrease to `0`, and `good` is our solution. Please refer to the following recursive codes:\n\n```java\n private static final int MOD = 1_000_000_007;\n public int countGoodNumbers(long n) {\n return (int)(countGood(n / 2, 4 * 5) * (n % 2 == 0 ? 1 : 5) % MOD);\n }\n private long countGood(long power, long x) {\n if (power == 0) {\n return 1;\n }else if (power % 2 == 0) {\n return countGood(power / 2, x * x % MOD);\n } \n return x * countGood(power - 1, x) % MOD;\n }\n```\n```python\n def countGoodNumbers(self, n: int) -> int:\n \n def countGood(power: int, x: int) -> int:\n if power == 0:\n return 1 \n elif power % 2 == 0:\n return countGood(power // 2, x * x % MOD)\n return x * countGood(power - 1, x) % MOD\n\n MOD = 10 ** 9 + 7\n return 5 ** (n % 2) * countGood(n // 2, 4 * 5) % MOD\n```\n**Analysis:**\n\nTime & space: `O(logn)`.\n\nWe can further change the above recursive versions into iterative ones:\n```java\n private static final int MOD = 1_000_000_007;\n public int countGoodNumbers(long n) {\n long good = n % 2 == 0 ? 1 : 5;\n for (long i = n / 2, x = 4 * 5; i > 0; i /= 2, x = x * x % MOD) {\n if (i % 2 != 0) {\n good = good * x % MOD;\n }\n }\n return (int)good;\n }\n```\n```python\n def countGoodNumbers(self, n: int) -> int:\n MOD = 10 ** 9 + 7\n good, x, i = 5 ** (n % 2), 4 * 5, n // 2\n while i > 0:\n if i % 2 == 1:\n good = good * x % MOD\n x = x * x % MOD\n i //= 2\n return good\n```\n\n**Analysis:**\n\nTime: `O(logn)`, space: `O(1)`.
98,150
Count Good Numbers
count-good-numbers
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Math,Recursion
Medium
Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n.
937
9
## Idea :\n\uD83D\uDC49 *find number of odd and even places of from given n.*\n\uD83D\uDC49 *each even places can take (0,2,4,6,8) 5 different numbers.*\n\uD83D\uDC49 *each odd places can take (2,3,5,7) 4 different prime numbers.*\n\uD83D\uDC49 *return the total combination of both even and odd places.*\n\n### **pow(a,b,c) = (a^b)%c**\n\ne.g. : n = 4\n\n_ _ _ _ _ _\n\tne = 2 # n//2\n\tno = 2 # n//2\n\tte = (5**2)%MOD #te=25\n\tto = (4**2)%MOD # to=16\n\t\n\treturn (25*16)%MOD # 400\n\t\n\'\'\'\n\n\tclass Solution:\n def countGoodNumbers(self, n: int) -> int:\n MOD = 10**9+7\n\t\t\n\t\t# No. of even places\n if n%2==0:\n ne=n//2\n else:\n ne=(n+1)//2\n # No. of odd places\n no=n//2\n \n te = pow(5,ne,MOD) #Total number of even places combinations.\n tp = pow(4,no,MOD) #Total number of odd/prime combinations.\n return (tp*te)%MOD\n\t\t\nIf you have any doubt feel free to ask. \uD83E\uDD17\nIf you got any help then DO **upvote!!** \uD83E\uDD1E\nThanks
98,163
Count Good Numbers
count-good-numbers
A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (2, 3, 5, or 7). Given an integer n, return the total number of good digit strings of length n. Since the answer may be large, return it modulo 109 + 7. A digit string is a string consisting of digits 0 through 9 that may contain leading zeros.
Math,Recursion
Medium
Is there a formula we can use to find the count of all the good numbers? Exponentiation can be done very fast if we looked at the binary bits of n.
963
5
---\n- ### the combinatorics part goes like this:\n- there are ceil(n/2) even positions and floor(n/2) odd positions\n- for each even positions the variations are (02,4,6,8). there are five variations for each even position.\n- for each odd position the variations are (2,3,5,7). there are four variations for each odd position.\n- thus, the total number of variations, aka the answer is 5^ceil(n/2) * 4^floor(n/2), up to the mod operation.\n- this leads to the commented out naive solution, which is not fast enough.\n---\n- ### speedup\n- there is a powermod operation that speeds the whole thing up.\n- powermod calculates the second power mod the number, fourth power mod the number, eighth power mod the number, etc.\n- then it converts the power into binary and simply multiply the powermod results where the power has a one bit.\n- for example, to compute the fifth power of x mod y, first calculate x mod y, x^2 mod y, x^4 mod y.\n- then realzing five in binary is \'101\' and multiply x^4 mod y with x mod y\n- this has logarithmic time and space complexity with regards to the power\n---\n- ### the hack\n- powermod is somewhat tricky to implement from scratch, especially during a contet\n- so .. realizing the modern language of python has a implicit powermod implemented in ```pow```, why don\'t we use that?\n\n```\nclass Solution:\n def countGoodNumbers(self, n: int) -> int:\n \'\'\'\n ans=1\n MOD=int(10**9+7)\n for i in range(n):\n if i%2==0:\n ans*=5\n else:\n ans*=4\n ans%=MOD\n return ans\n \'\'\'\n MOD=int(10**9+7)\n\n fives,fours=n//2+n%2,n//2\n # 5^fives*4^fours % MOD\n # = 5^fives % MOD * 4^fours % MOD\n return (pow(5,fives,MOD) * pow(4,fours,MOD)) % MOD\n```
98,164
Longest Common Subpath
longest-common-subpath
There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities. There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively. Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all. A subpath of a path is a contiguous sequence of cities within that path.
Array,Binary Search,Rolling Hash,Suffix Array,Hash Function
Hard
If there is a common path with length x, there is for sure a common path of length y where y < x. We can use binary search over the answer with the range [0, min(path[i].length)]. Using binary search, we want to verify if we have a common path of length m. We can achieve this using hashing.
1,039
11
Credits @knighthoodcode for suggesting this idea in another thread\n\n### Approach\n* Binary search for the longest length of sub path.\n* Get sub path signature as a concatenation of two hash values obtained using rabin-karp algorithm, but using two sets of `base` and `mod` values. This reduces the probability of collisions drastically.\n\n```\n def longestCommonSubpath(self, n: int, paths: List[List[int]]) -> int:\n\n def getSubPathsHashes(array, l):\n base1, mod1 = 101, 999979\n base2, mod2 = 103, 999959\n \n h1, P1 = 0, pow(base1, l-1, mod1)\n h2, P2 = 0, pow(base2, l-1, mod2)\n\n for i in range(l):\n h1 = (h1 * base1 + array[i]) % mod1\n h2 = (h2 * base2 + array[i]) % mod2\n\n sub_path_hashset = set([str(h1)+str(h2)])\n\n for i in range(len(array)-l):\n h1 = ((h1 - array[i]*P1)*base1 + array[i+l]) % mod1\n h2 = ((h2 - array[i]*P2)*base2 + array[i+l]) % mod2 \n sub_path_hashset.add(str(h1)+str(h2))\n \n return sub_path_hashset\n \n lo, hi = 0, min(len(path) for path in paths) + 1\n \n while lo < hi:\n mid = (hi+lo) // 2\n lcs = set.intersection(*[getSubPathsHashes(path, mid) for path in paths])\n if lcs: lo = mid+1\n else: hi = mid\n \n return lo-1\n```
98,180
Longest Common Subpath
longest-common-subpath
There is a country of n cities numbered from 0 to n - 1. In this country, there is a road connecting every pair of cities. There are m friends numbered from 0 to m - 1 who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively. Given an integer n and a 2D integer array paths where paths[i] is an integer array representing the path of the ith friend, return the length of the longest common subpath that is shared by every friend's path, or 0 if there is no common subpath at all. A subpath of a path is a contiguous sequence of cities within that path.
Array,Binary Search,Rolling Hash,Suffix Array,Hash Function
Hard
If there is a common path with length x, there is for sure a common path of length y where y < x. We can use binary search over the answer with the range [0, min(path[i].length)]. Using binary search, we want to verify if we have a common path of length m. We can achieve this using hashing.
1,378
7
Credited: @DBabichev, @tonghuikang, @kcsquared\n\nThis algorithm is a fully randomized version based on . Refer to the above link for the basic ideas of applying rolling hash & binary search.\n\nOne major concern is that LeetCode might generate adversarial test cases to invalidate any deterministic algorithm. To defend against any future updates of test cases, randomly chosen large primes can help to minimize the possibility of failing on them.\n\n---\n## How to generate large primes\nGenerally, large primes are necessary in many cryptographic algorithms such as RSA. To generate such *sufficiently large* primes (usually at least as large as 2^1024), we can select a random number that is large enough, and test its primality by [Miller-Rabin primality test](\u2013Rabin_primality_test). If this try fails, then we should make another try until finding a prime.\n\nMiller-Rabin is a probabilistic primality test which takes logarithmic time in the magnitude of desired prime. Also, [the "density" of primes]() ensures that we could expect to try within logarithmic times to find a prime. Therefore it won\'t take much time to select such large primes.\n\n---\n## Running time analysis\n\nWe only consider the time complexity of main function, because \n1. prime generation is not a significant bottleneck compared to main function\n2. we can substitute a pre-computed large prime for large prime generator\n\nWe perform binary search between `[1, min path length]` and test if there is a common subpath with length of the chosen value. For each test, we iterate over everyone\'s path in linear time to compute rolling hashes, which takes `O(sum of path lengths)` time. Set construction and intersection take linear time in set size as well, which is bounded by the path length. Hence the running time is\n> `O(sum * log(min))`, where `sum <= 10^5` is the sum of path lengths, and `min <= 10^5` is the minimum of path lengths.\n\n---\n## Implementation in Python\n> Update1: replace erroneous Miller-Rabin implementation with code from CLRS\n> Update2: increase modulus magnitude, and remove multiple trials\n\nThe Miller-Rabin test code is rewritten from pseudocode in CLRS 31.8.\n\nOur choice of modulus with magnitude of `10^18` will guarantee a virtually undetectable error rate for any practical test suite provided by LeetCode.\nYou can simply delete the function `_generate_large_prime()` and assign `mod` a pre-computed large prime. Here is a list of available large primes (fitting in 64-bit signed integer) generated by the function, whose primality have been validated by [this tool]()):\n```\n6268599155699029141\n4061760809781307937\n8010655192548934421\n4753132327198877137\n4820028217243953113\n```\n\n```python\nclass Solution:\n def longestCommonSubpath(self, n, paths) -> int:\n def get_common_subpath_hashes(k):\n """Return hash values of common subpaths of length k, or empty set if none exists"""\n def get_subpath_hashes(path):\n hash, coeff = 0, pow(n, k-1, mod)\n for i in range(len(path)+1):\n if i < k:\n hash = (hash*n + path[i]) % mod\n else:\n yield hash\n if i < len(path):\n hash = ((hash-coeff*path[i-k])*n + path[i]) % mod \n return reduce(set.intersection, (set(get_subpath_hashes(p)) for p in paths))\n \n\t # can be replaced with a pre-computed large prime\n mod = self._generate_large_prime(int(1e18), int(9e18))\n low, high = 1, min(len(p) for p in paths)+1\n while low < high:\n mid = (low+high) // 2\n if get_common_subpath_hashes(mid):\n low = mid + 1\n else:\n high = mid\n return high - 1\n \n def _generate_large_prime(self, lower, upper):\n """Generate a prime between [lower, upper)"""\n def is_prime(n, trials=50):\n def witness(a, n):\n x0 = pow(a, u, n)\n for _ in range(t):\n x = x0**2 % n\n if x == 1 and x0 != 1 and x0 != n-1:\n return True\n x0 = x\n return True if x0 != 1 else False\n\n t, u = 0, n-1\n while u%2 == 0:\n t, u = t+1, u>>1\n return not any(witness(randrange(1, n), n) for _ in range(trials))\n return next(r for r in iter(lambda: randrange(lower, upper), None) if is_prime(r))\n```\n\n---\n## Optional Part: Math Proof of Error Rate\n\nThis part is inspired by @kcsquared. Refer to the thread\n- \n\nfor details.\n\n### Intuition\n\nIn the first place, the algorithm may well give an incorrect answer. Hashing is accompanied by collisions. Imagine that there are subpaths (recall that a subpath is a sequence of city numbers) `p1, p2, ..., p_m` from `m` persons. While `p1 = p2 = ... = p_m` is not true, by accident their hash values are equal, i.e., `h(p1) = h(p2) = ... = h(p_m)`. If there is actually no satisfying common subpath with the current testing length, we will overestimate the final answer.\n\nNote that hash collision is a necessary but not sufficient condition for an incorrect answer. If collision occurs between subpaths of the same person, or when there is indeed another satisfying common subpath, collision doesn\'t matter.\n\n### Collision probability\n\nWe have shown that the probability of hash collision should be an **upper bound** of the error rate (i.e. returning an incorrect answer). Now let\'s consider the probability of any hash collision.\n\nIn a problem instance, let `s` denote the sum of length of everyone\'s path, where `s` is no more than 10^5 by constraint. The upper bound of subpath count occurs when there is only a single person. In this case, there are `s + (s-1) + ... + 2 + 1` subpaths, counting subpaths with length `1, 2, ..., s-1, s` respectively.\n\nNow the problem is how to get the probability of hash collision with at most `10^5*(10^5+1)/2 = 5,000,050,000` subpaths to be hashed. If we choose the modulus as `mod`, we have a hash space of size `mod` (i.e., integers between `[0, mod)`).\n\n#### Simple Uniform Hashing Assumption (SUHA)\n\nA subtlety is that rolling hash does **NOT** necessarily use hash functions that satisfy [simple uniform hashing assumption]((computer_science)). However, if we choose an appropriate prime number as modulus, we can consider it approximately as a hash function that hashes any integer to `[0, mod)` with equal possibility, independent of whichever slot any other integer is hashed to.\n\n#### Birthday paradox\n\nAs long as we have ensured SUHA for our rolling hash function, the problem can be reduced to a classical probability problem: [birthday paradox]().\n\n> In probability theory, the birthday problem or birthday paradox concerns the probability that, in a set of n randomly chosen people, some pair of them will have the same birthday.\n\nThe probability of collision is simply the probability that any two randomly chosen people would share the same birthday. Here, the number of people corresponds to the total number of subpaths to be hashed, and the number of days in a year corresponds to the number of hashing slots (i.e., `length of [0, mod)`).\n\nBy first-order approximation of Taylor series expansion, we can derive an approximation of collision probability `p(total, mod) = 1 - e^(-total^2/(2*mod))`, where `total` is the sum of the number of everyone\'s subpaths. Using this approximation, we need a prime modulus as large as 10^24 to bound collision probability to roughly 0.001%.\n\n#### A tighter estimation\n\nIn fact, the collision probability estimated above is a very coarse one that exhibits far more collisions than actual. For this specific problem, we can make a much tighter estimation on the probability, through both [Monte Carlo simulations]((*add-math-proof)/999506) and [an analytical model]((*add-math-proof)/1000160).\n\nBy the tighter estimations, we can conclude that a prime modulus with magnitude of `10^15 ~ 10^18` will ensure a sufficiently low collision probability (and error rate).\n\nNote that it still provides an **upper bound** on the error rate of the whole algorithm, therefore a smaller modulus may work as well.\n\n### Choice of modulus and number of trials\n\nThe probability of collision is decided by two factors:\n- magnitude of modulus\n- number of trials when testing existence of a common subpath with length k\n\nOf course, the larger modulus and more trials, the lower collision possibility (thus error rate). But we\'d like to avoid unnecessary time and program complexity burdens as well. Using multiple moduli impose extra code complexity and running time overheads, and thus is undesirable. \n\nTo achieve a reasonably low probability of collision, we\'ve shown the range from which we could safely pick a prime modulus. Taking account of the fact that the largest 64-bit signed integer is `2^63-1` (slightly larger than `9 * 10^18`), we finally decided to choose the single prime modulus from `[1e18, 9e18)`.\n\n---\n## Further readings\n- Rabin-Karp algorithm, aka rolling hash: CLRS Chapter 32\n- Miller-Rabin primality test and RSA: CLRS Chapter 31\n- Hash tables: CLRS Chapter 11
98,185
Check if All Characters Have Equal Number of Occurrences
check-if-all-characters-have-equal-number-of-occurrences
Given a string s, return true if s is a good string, or false otherwise. A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).
Hash Table,String,Counting
Easy
Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same.
3,401
44
\n```\nclass Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(Counter(s).values())) == 1\n```
98,255
Check if All Characters Have Equal Number of Occurrences
check-if-all-characters-have-equal-number-of-occurrences
Given a string s, return true if s is a good string, or false otherwise. A string s is good if all the characters that appear in s have the same number of occurrences (i.e., the same frequency).
Hash Table,String,Counting
Easy
Build a dictionary containing the frequency of each character appearing in s Check if all values in the dictionary are the same.
3,311
31
**Python, One Liner:**\n```\nclass Solution:\n def areOccurrencesEqual(self, s: str) -> bool:\n return len(set(Counter(s).values())) == 1\n```\n**C++, 0ms Faster than 100%:**\n```\nclass Solution {\npublic:\n bool areOccurrencesEqual(string s) {\n unordered_map<char, int> freq;\n for (auto c : s) freq[c]++;\n int val = freq[s[0]];\n for (auto [a, b] : freq) if (b != val) return false;\n return true;\n }\n};\n```\n**C / C++, 0 ms Faster than 100%:**\n```\nbool areOccurrencesEqual(char * s){\n int freq[26] = {0};\n char* ptr = s;\n while (*ptr) freq[*ptr++ - \'a\']++;\n \n int val = freq[s[0] - \'a\'];\n for (int i = 0; i < 26; i++)\n if (freq[i] && freq[i] != val) return false; \n \n return true;\n}\n```\n**Java, 1ms Faster than 100%:**\n```\nclass Solution {\n public boolean areOccurrencesEqual(String s) {\n int[] freq = new int[26];\n \n for (int i = 0; i < s.length(); i++) freq[s.charAt(i)-\'a\']++;\n\n int val = freq[s.charAt(0) - \'a\'];\n for (int i = 0; i < 26; i++)\n if (freq[i] != 0 && freq[i] != val) return false; \n\n return true;\n }\n}\n```\n**Javascript:**\n```\nvar areOccurrencesEqual = function(s) {\n var freq = {}\n for (let c of s) freq[c] = (freq[c] || 0) + 1\n var val = freq[s[0]]\n for (let c in freq) if (freq[c] && freq[c] != val) return false;\n return true;\n};\n```\n**Like it? please upvote!**
98,259
The Number of the Smallest Unoccupied Chair
the-number-of-the-smallest-unoccupied-chair
There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number. When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct. Return the chair number that the friend numbered targetFriend will sit on.
Array,Heap (Priority Queue),Ordered Set
Medium
Sort times by arrival time. for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i.
1,626
21
**Explanation:**\n* Put all arrivals in one heap and all departures in another heap - this helps us to go by the chronogical order of time\n* If smallest time in arrivals heap is less than smallest time in departures heap, then pop from arrivals heap and occupy the 1st available table with the popped element. \n* If popped index/friend is the target friend, then return the occupied index\n* Else if smallest time in departures heap is less than or equal to smallest time in arrivals heap, then pop from departures heap and vacate the table occupied by the popped element\n\n```\nclass Solution:\n def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n arrivals = []\n departures = []\n for ind, (x, y) in enumerate(times):\n heappush(arrivals, (x, ind))\n heappush(departures, (y, ind))\n d = {}\n occupied = [0] * len(times)\n while True:\n if arrivals and departures and arrivals[0][0] < departures[0][0]:\n _, ind = heappop(arrivals)\n d[ind] = occupied.index(0)\n occupied[d[ind]] = 1\n if ind == targetFriend:\n return d[ind]\n elif arrivals and departures and arrivals[0][0] >= departures[0][0]:\n _, ind = heappop(departures)\n occupied[d[ind]] = 0\n```
98,280
The Number of the Smallest Unoccupied Chair
the-number-of-the-smallest-unoccupied-chair
There is a party where n friends numbered from 0 to n - 1 are attending. There is an infinite number of chairs in this party that are numbered from 0 to infinity. When a friend arrives at the party, they sit on the unoccupied chair with the smallest number. When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a 0-indexed 2D integer array times where times[i] = [arrivali, leavingi], indicating the arrival and leaving times of the ith friend respectively, and an integer targetFriend. All arrival times are distinct. Return the chair number that the friend numbered targetFriend will sit on.
Array,Heap (Priority Queue),Ordered Set
Medium
Sort times by arrival time. for each arrival_i find the smallest unoccupied chair and mark it as occupied until leaving_i.
995
21
\n```\nclass Solution:\n def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:\n vals = []\n for i, (arrival, leaving) in enumerate(times): \n vals.append((arrival, 1, i))\n vals.append((leaving, 0, i))\n \n k = 0 \n pq = [] # available seats \n mp = {} # player-to-seat mapping \n for _, arrival, i in sorted(vals): \n if arrival: \n if pq: s = heappop(pq)\n else: \n s = k\n k += 1\n if i == targetFriend: return s\n mp[i] = s\n else: heappush(pq, mp[i]) # new seat available\n```
98,282
Describe the Painting
describe-the-painting
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.
Array,Prefix Sum
Medium
Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)?
3,065
136
### Idea\nwe can iterate on coordinates of each `[start_i, end_i)` from small to large and maintain the current mixed color.\n\n### How can we maintain the mixed color?\nWe can do addition if the current coordinate is the beginning of a segment.\nIn contrast, We do subtraction if the current coordinate is the end of a segment.\n\n### Examples\nLet\'s give the example for understanding it easily.\n\n#### Example 1:\n![image]()\n\nThere are 3 coordinates get involved. 1, 4, 7 respetively.\nAt coordinate 1, there are two segment starting here. Thus, the current mixed color will be 5 + 9 = 14\nAt coordinate 4, the segment [1, 4, 5] is end here and the segment [4, 7, 7] also start here. Thus, the current mixed color will be 14 - 5 + 7 = 16\nAt coordinate 7, two segments are end here. Thus, the current mixed color will be 0\nSo we know the final answer should be [1, 4, 14] and [4, 7, 16].\n\n\n#### Example 2:\n![image]()\n\nThere are 5 coordinates get involved. 1, 6, 7, 8, 10 respetively.\nAt coordinate 1, only the segment [1, 7, 9] start here. Thus, the current mixed color will be 0 + 9 = 9\nAt coordinate 6, another segment [6, 8, 15] start here. Thus, the current mixed color will be 9 + 15 = 24\nAt coordinate 7, the segment [1, 7, 9] is end here. Thus, the current mixed color will be 24 - 9 = 15\nAt coordinate 8, the segment [6, 8, 15] is end here and the segment [8, 10, 7] also start here. Thus, the current mixed color will be 15 - 15 + 7 = 7\nAt coordinate 10, the segment [8, 10, 7] is end here. Thus, the current mixed color will be 0\nSo we know the final answer should be [1,6,9], [6,7,24], [7,8,15], [8,10,7].\n\n### Complexity\n- Time complexity: O(n * log(n)) # We can use a fixed size array with length 10^5 to replace the default dict and bound the time complexity to O(n).\n- Space complexity: O(n)\n\n### Code\n\n```python\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n\t\t# via this mapping, we can easily know which coordinates should be took into consideration.\n mapping = defaultdict(int)\n for s, e, c in segments:\n mapping[s] += c\n mapping[e] -= c\n \n res = []\n prev, color = None, 0\n for now in sorted(mapping):\n if color: # if color == 0, it means this part isn\'t painted.\n res.append((prev, now, color))\n \n color += mapping[now]\n prev = now\n \n return res\n```\n\nPlease upvote if it\'s helpful or leave comments if I can do better. Thank you in advance.\n
98,324
Describe the Painting
describe-the-painting
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.
Array,Prefix Sum
Medium
Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)?
4,912
72
We can use the line sweep approach to compute the sum (color mix) for each point. We use this line to check when a sum changes (a segment starts or finishes) and describe each mix. But there is a catch: different colors could produce the same sum. \n\nI was puzzled for a moment, and then I noticed that the color for each segment is distinct. So, every time a segment starts or ends, the color mix is different (even if the sum is the same). So we also mark `ends` of color segments on our line.\n\n**Java**\n```java\npublic List<List<Long>> splitPainting(int[][] segments) {\n long mix[] = new long[100002], sum = 0, last_i = 0;\n boolean ends[] = new boolean[100002];\n List<List<Long>> res = new ArrayList<>();\n for (var s : segments) {\n mix[s[0]] += s[2];\n mix[s[1]] -= s[2];\n ends[s[0]] = ends[s[1]] = true;\n }\n for (int i = 1; i < 100002; ++i) {\n if (ends[i] && sum > 0)\n res.add(Arrays.asList(last_i, (long)i, sum));\n last_i = ends[i] ? i : last_i;\n sum += mix[i];\n } \n return res;\n}\n```\n**C++**\n```cpp\nvector<vector<long long>> splitPainting(vector<vector<int>>& segments) {\n long long mix[100002] = {}, sum = 0, last_i = 0;\n bool ends[100002] = {};\n vector<vector<long long>> res;\n for (auto &s : segments) {\n mix[s[0]] += s[2];\n mix[s[1]] -= s[2];\n ends[s[0]] = ends[s[1]] = true;\n }\n for (int i = 1; i < 100002; ++i) {\n if (ends[i] && sum)\n res.push_back({last_i, i, sum});\n last_i = ends[i] ? i : last_i;\n sum += mix[i];\n }\n return res;\n}\n```\n**Python 3**\n```python\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n mix, res, last_i = DefaultDict(int), [], 0\n for start, end, color in segments:\n mix[start] += color\n mix[end] -= color\n for i in sorted(mix.keys()):\n if last_i in mix and mix[last_i]:\n res.append([last_i, i, mix[last_i]])\n mix[i] += mix[last_i]\n last_i = i\n return res\n```
98,326
Describe the Painting
describe-the-painting
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.
Array,Prefix Sum
Medium
Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)?
848
14
\n```\nclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n vals = []\n for start, end, color in segments: \n vals.append((start, +color))\n vals.append((end, -color))\n \n ans = []\n prefix = prev = 0 \n for x, c in sorted(vals): \n if prev < x and prefix: ans.append([prev, x, prefix])\n prev = x\n prefix += c \n return ans \n```
98,330
Describe the Painting
describe-the-painting
There is a long and thin painting that can be represented by a number line. The painting was painted with multiple overlapping segments where each segment was painted with a unique color. You are given a 2D integer array segments, where segments[i] = [starti, endi, colori] represents the half-closed segment [starti, endi) with colori as the color. The colors in the overlapping segments of the painting were mixed when it was painted. When two or more colors mix, they form a new color that can be represented as a set of mixed colors. For the sake of simplicity, you should only output the sum of the elements in the set rather than the full set. You want to describe the painting with the minimum number of non-overlapping half-closed segments of these mixed colors. These segments can be represented by the 2D array painting where painting[j] = [leftj, rightj, mixj] describes a half-closed segment [leftj, rightj) with the mixed color sum of mixj. Return the 2D array painting describing the finished painting (excluding any parts that are not painted). You may return the segments in any order. A half-closed segment [a, b) is the section of the number line between points a and b including point a and not including point b.
Array,Prefix Sum
Medium
Can we sort the segments in a way to help solve the problem? How can we dynamically keep track of the sum of the current segment(s)?
503
11
## IDEA :\nWe are finding all the starting and ending points. These points score we are storing in our dictinoary and after sorting all the poiints we are making our result array.\n\nEg: segments = [[1,7,9],[6,8,15],[8,10,7]]\nThere are 5 coordinates get involved. 1, 6, 7, 8, 10 respetively.\n* At coordinate 1, only the segment [1, 7, 9] start here. Thus, the current mixed color will be 0 + 9 = 9\n* At coordinate 6, another segment [6, 8, 15] start here. Thus, the current mixed color will be 9 + 15 = 24\n* At coordinate 7, the segment [1, 7, 9] is end here. Thus, the current mixed color will be 24 - 9 = 15\n* At coordinate 8, the segment [6, 8, 15] is end here and the segment [8, 10, 7] also start here. Thus, the current mixed color will be 15 - 15 + 7 = 7\n* At coordinate 10, the segment [8, 10, 7] is end here. Thus, the current mixed color will be 0\n* So we know the final answer should be [1,6,9], [6,7,24], [7,8,15], [8,10,7].\n\n\'\'\'\n\n\tclass Solution:\n def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:\n \n dic = defaultdict(int)\n for s,e,c in segments:\n dic[s]+=c\n dic[e]-=c\n \n st=None\n color=0\n res = []\n for p in sorted(dic):\n if st is not None and color!=0:\n res.append([st,p,color])\n color+=dic[p]\n st = p\n \n return res\n\nThanks and Happy Coding !!\uD83E\uDD1E\nFeel free to ask and **Upvote** if you got any help. \uD83E\uDD17
98,334
Count Salary Categories
count-salary-categories
null
Database
Medium
null
6,453
78
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef count_salary_categories(accounts: pd.DataFrame) -> pd.DataFrame:\n return pd.DataFrame({\n \'category\': [\'Low Salary\', \'Average Salary\', \'High Salary\'],\n \'accounts_count\': [\n accounts[accounts.income < 20000].shape[0],\n accounts[(accounts.income >= 20000) & (accounts.income <= 50000)].shape[0],\n accounts[accounts.income > 50000].shape[0],\n ],\n })\n```\n```SQL []\nSELECT "Low Salary" AS category,\n sum(income < 20000) AS accounts_count\n FROM Accounts\n\nUNION\n\nSELECT "Average Salary" AS category,\n sum(income BETWEEN 20000 AND 50000) AS accounts_count\n FROM Accounts\n\nUNION\n\nSELECT "High Salary" AS category,\n sum(income > 50000) AS accounts_count\n FROM Accounts;\n```\n\n# Important!\n###### If you like the solution or find it useful, feel free to **upvote** for it, it will support me in creating high quality solutions)\n\n# 30 Days of Pandas solutions\n\n### Data Filtering \u2705\n- [Big Countries]()\n- [Recyclable and Low Fat Products]()\n- [Customers Who Never Order]()\n- [Article Views I]()\n\n\n### String Methods \u2705\n- [Invalid Tweets]()\n- [Calculate Special Bonus]()\n- [Fix Names in a Table]()\n- [Find Users With Valid E-Mails]()\n- [Patients With a Condition]()\n\n\n### Data Manipulation \u2705\n- [Nth Highest Salary]()\n- [Second Highest Salary]()\n- [Department Highest Salary]()\n- [Rank Scores]()\n- [Delete Duplicate Emails]()\n- [Rearrange Products Table]()\n\n\n### Statistics \u2705\n- [The Number of Rich Customers]()\n- [Immediate Food Delivery I]()\n- [Count Salary Categories]()\n\n\n### Data Aggregation \u2705\n- [Find Total Time Spent by Each Employee]()\n- [Game Play Analysis I]()\n- [Number of Unique Subjects Taught by Each Teacher]()\n- [Classes More Than 5 Students]()\n- [Customer Placing the Largest Number of Orders]()\n- [Group Sold Products By The Date]()\n- [Daily Leads and Partners]()\n\n\n### Data Aggregation \u2705\n- [Actors and Directors Who Cooperated At Least Three Times]()\n- [Replace Employee ID With The Unique Identifier]()\n- [Students and Examinations]()\n- [Managers with at Least 5 Direct Reports]()\n- [Sales Person]()\n\n\n
98,374
Concatenation of Array
concatenation-of-array
Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans.
Array
Easy
Build an array of size 2 * n and assign num[i] to ans[i] and ans[i + n]
955
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to return a new array that repeats the original array twice.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n### Approach 1\nWe can concatenate the original `nums` array with itself using the `+` operator.\n\n> `+` \u2192 it concatenates two lists in Python:\nExample: `[1, 2, 3] + [1, 2, 3] = [1, 2, 3, 1, 2, 3]`\n\n### Approach 2\nWe can repeat the the original `nums` array `2` times using the `*` operator.\n\n> `*` \u2192 it repeats a list a specified number of times in Python:\nExample: `[1, 2, 3] * 2 = [1, 2, 3, 1, 2, 3]`\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`n` is the length of the `nums` array. Both solutions require going through each element of the input list once, and the time they take scales linearly with the size of the input list.\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`n` is the length of the `nums` array. Both solutions create a new list to store the concatenated list, and the space used for this is directly proportional to the size of the input list.\n\n# Code\n## Approach 1 Solution:\n```\nclass Solution:\n def getConcatenation(self, nums: List[int]) -> List[int]:\n return nums + nums\n \n```\n\n## Approach 2 Solution:\n```\nclass Solution:\n def getConcatenation(self, nums: List[int]) -> List[int]:\n return nums * 2 \n```
98,456
Concatenation of Array
concatenation-of-array
Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed). Specifically, ans is the concatenation of two nums arrays. Return the array ans.
Array
Easy
Build an array of size 2 * n and assign num[i] to ans[i] and ans[i + n]
1,105
7
# Intuition\nThe intuition behind this solution is straightforward. We want to concatenate the given array with itself to create a new array that has the same elements repeated twice.\n\n# Approach\n- We start by initializing an empty list called ans, which we\'ll use to store the concatenated array.\n\n- We iterate through the elements of the input nums array using a for loop. For each element num in nums, we append it to the ans list.\n\n- After the loop, we concatenate the nums array again to the ans list using the += operator. This effectively adds all the elements of nums to the end of ans.\n\n- Finally, we return the ans list, which now contains the concatenated array.\n\n# Complexity\n- Time complexity:\nO(n) - We iterate through the input nums array once, where n is the length of nums.\n\n\n- Space complexity:\nWe use additional space to store the ans list, which has the same length as nums.\n\n# Code\n```\nclass Solution:\n def getConcatenation(self, nums):\n # Initialize an empty list to store the concatenated array\n ans = []\n \n # Iterate through the elements of the input \'nums\' array\n for num in nums:\n # Append the current number to the \'ans\' list\n ans.append(num)\n \n # Concatenate \'nums\' again to \'ans\' to form the final result\n ans += nums\n \n return ans\n};\n```\n\n![478xve.jpg]()\n
98,462
Unique Length-3 Palindromic Subsequences
unique-length-3-palindromic-subsequences
Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Hash Table,String,Prefix Sum
Medium
What is the maximum number of length-3 palindromic strings? How can we keep track of the characters that appeared to the left of a given position?
3,439
20
![Screenshot 2023-11-14 085449.png]()\n# YouTube Video Explanation:\n\n[]()\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: \n\n*Current Subscribers: 241*\n*Subscribe Goal: 250 Subscribers*\n\n# Example Explanation\n\nLet\'s break down the solution step by step using tables to visualize the process:\n\n### Example:\n\nGiven String: "aabca"\n\n#### Iteration through Characters \'a\' to \'z\':\n\n| Character | First Occurrence | Last Occurrence | Unique Characters Count (t) | Palindromes Count (a) |\n|-----------|-------------------|------------------|-----------------------------|-----------------------|\n| \'a\' | 0 | 3 | 3 |3 |\n| \'b\' | 1 | 1 | 0 | 3 |\n| \'c\' | 2 | 2 | 0 | 3 |\n| \'d\' | Not Found | Not Found | - | - |\n| ... | ... | ... | ... | ... |\n| \'z\' | Not Found | Not Found | - | - |\n\n#### Explanation:\n\n1. **Character \'a\':**\n - First occurrence at index 0, last occurrence at index 3.\n - Iterate from index 1 to 2, marking characters \'a\' and \'b\' as visited.\n - Unique characters count (t): 3.\n - Add t to the total count (a): 3.\n\n\n4. **Character \'d\' to \'z\':**\n - Not found in the given string, so no further actions are taken.\n\n#### Result:\n\nTotal Palindromes Count (a): 3\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks for the count of unique palindromes of length three that are subsequences of the given string `s`. A palindrome of length three has the form "aba". To count these palindromes, the solution seems to iterate through the string, finding the first and last occurrences of each character and checking the characters in between.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Iterate through each character from \'a\' to \'z\'.\n2. For each character, find the first and last occurrence in the string `s`.\n3. If the first occurrence is not found, move to the next character.\n4. If the first occurrence is found, iterate from the next index to the last occurrence.\n - For each character in between, mark it as visited to avoid duplicate counting.\n - Increment a counter for unique characters.\n - If the counter reaches 26 (the total number of lowercase English letters), break the loop to avoid unnecessary iterations.\n5. Add the counter value to the total count.\n\n# Complexity\n- Time Complexity: O(N)\n - The solution iterates through the string once for each character, and the inner loop iterates through the characters between the first and last occurrences.\n\n- Space Complexity: O(1)\n - The solution uses a constant amount of space for the boolean array `v` and some variables, independent of the input size.\n\n# Code\n## Java\n```\nclass Solution {\n public int countPalindromicSubsequence(String s) {\n char[] c = s.toCharArray();\n boolean[] v = new boolean[128];\n int a=0, t=0;\n\n int l, r;\n for(char x=\'a\'; x<=\'z\'; x++){\n for(l=0; l<c.length && c[l]!=x; l++);\n if(l==c.length)continue;\n for(r=c.length-1; r>=0 && c[r]!=x; r--);\n if(l>=r)continue;\n\n Arrays.fill(v, false); t=0;\n for(int i=l+1; i<r; i++){\n if(!v[c[i]]){\n v[c[i]]=true; t++;\n if(t==26)break;\n }\n }\n a+=t;\n }\n return a;\n }\n}\n```\n## C++\n```\nclass Solution {\npublic:\n int countPalindromicSubsequence(string s) {\n char c[26] = {\'a\', \'b\', \'c\', \'d\', \'e\', \'f\', \'g\', \'h\', \'i\', \'j\', \'k\', \'l\', \'m\', \'n\', \'o\', \'p\', \'q\', \'r\', \'s\', \'t\', \'u\', \'v\', \'w\', \'x\', \'y\', \'z\'};\n int a = 0, t = 0;\n\n int l, r;\n for (char x : c) {\n for (l = 0; l < s.length() && s[l] != x; l++);\n if (l == s.length()) continue;\n for (r = s.length() - 1; r >= 0 && s[r] != x; r--);\n if (l >= r) continue;\n\n vector<bool> v(128, false);\n t = 0;\n for (int i = l + 1; i < r; i++) {\n if (!v[s[i]]) {\n v[s[i]] = true;\n t++;\n if (t == 26) break;\n }\n }\n a += t;\n }\n return a;\n }\n};\n```\n## Python\n```\nclass Solution(object):\n def countPalindromicSubsequence(self, s):\n c = \'abcdefghijklmnopqrstuvwxyz\'\n a, t = 0, 0\n\n for x in c:\n l = s.find(x)\n if l == -1:\n continue\n r = s.rfind(x)\n if l >= r:\n continue\n\n v = [False] * 128\n t = 0\n for i in range(l + 1, r):\n if not v[ord(s[i])]:\n v[ord(s[i])] = True\n t += 1\n if t == 26:\n break\n a += t\n return a\n \n```\n## JavaScript\n```\n/**\n * @param {string} s\n * @return {number}\n */\nvar countPalindromicSubsequence = function(s) {\n const c = \'abcdefghijklmnopqrstuvwxyz\';\n let a = 0, t = 0;\n\n for (const x of c) {\n const l = s.indexOf(x);\n if (l === -1) {\n continue;\n }\n const r = s.lastIndexOf(x);\n if (l >= r) {\n continue;\n }\n\n const v = new Array(128).fill(false);\n t = 0;\n for (let i = l + 1; i < r; i++) {\n if (!v[s.charCodeAt(i)]) {\n v[s.charCodeAt(i)] = true;\n t++;\n if (t === 26) {\n break;\n }\n }\n }\n a += t;\n }\n return a;\n};\n```\n---\n![upvote1.jpeg]()\n
98,474
Unique Length-3 Palindromic Subsequences
unique-length-3-palindromic-subsequences
Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Hash Table,String,Prefix Sum
Medium
What is the maximum number of length-3 palindromic strings? How can we keep track of the characters that appeared to the left of a given position?
5,672
30
**UPVOTE IF HELPFuuL**\n\n# Intuition\nWe need to find the number of unique of ```PalindromicSubsequence```, hence repitition is not a case to be done here.\n\n# Approach\nFor every char ```$``` in ```[a,b,c...y,z]``` , a palindrome of type ```"$ @ $"``` will exist if there are atleast 2 occurances of ```"$"```.\n\nHence we need to find first and last occurance of every char and for every char we need to count unique ```"@"``` which represents what characters come in middle of palindrome. This is number of unique characters between FIRST and LAST occurance of ```"$"``` char.\n![Screenshot 2023-11-14 at 6.07.34 AM.png]()\n\n\n# Complexity\n- Time complexity: O(n)\n- O(N) for traversing string to find char occurances.\n- O(26 * N) for slicing string for every lowercase char.\n\n\n# C++ Solution\n```\nclass Solution {\npublic:\n int countPalindromicSubsequence(string inputString) {\n \n int result = 0;\n int firstIndex[26] = {[0 ... 25] = INT_MAX};\n int lastIndex[26] = {};\n\n for (int i = 0; i < inputString.size(); ++i) {\n firstIndex[inputString[i] - \'a\'] = min(firstIndex[inputString[i] - \'a\'], i);\n lastIndex[inputString[i] - \'a\'] = i;\n }\n for (int i = 0; i < 26; ++i)\n if (firstIndex[i] < lastIndex[i])\n result += unordered_set<char>(begin(inputString) + firstIndex[i] + 1, begin(inputString) + lastIndex[i]).size();\n return result;\n}\n};\n\n```\n\n# Python Solution\n```\nclass Solution:\n def countPalindromicSubsequence(self, s):\n res = 0\n\n #string.ascii_lowercase = {a,b,c,d ... x,y,z}\n for k in string.ascii_lowercase:\n first, last = s.find(k), s.rfind(k)\n if first > -1:\n res += len(set(s[first + 1: last]))\n return res\n```\n\n# Java Solution\n```\nclass Solution {\n public int countPalindromicSubsequence(String inputString) {\n int firstIndex[] = new int[26], lastIndex[] = new int[26], result = 0;\n Arrays.fill(firstIndex, Integer.MAX_VALUE);\n for (int i = 0; i < inputString.length(); ++i) {\n firstIndex[inputString.charAt(i) - \'a\'] = Math.min(firstIndex[inputString.charAt(i) - \'a\'], i);\n lastIndex[inputString.charAt(i) - \'a\'] = i;\n }\n for (int i = 0; i < 26; ++i)\n if (firstIndex[i] < lastIndex[i])\n result += inputString.substring(firstIndex[i] + 1, lastIndex[i]).chars().distinct().count();\n return result;\n }\n}\n```\n\n![IMG_3726.JPG]()\n
98,475
Unique Length-3 Palindromic Subsequences
unique-length-3-palindromic-subsequences
Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Hash Table,String,Prefix Sum
Medium
What is the maximum number of length-3 palindromic strings? How can we keep track of the characters that appeared to the left of a given position?
468
7
<iframe width="560" height="315" src="" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n\n```\nclass Solution {\n public int countPalindromicSubsequence(String s) {\n int[] left = new int[26];\n int[] right = new int[26];\n Arrays.fill(left, -1);\n int curr;\n for (int i = 0; i < s.length(); i++) {\n curr = s.charAt(i) - \'a\';\n if (left[curr] == - 1) {\n left[curr] = i;\n }\n right[curr] = i;\n }\n int ans = 0;\n boolean [] count;\n for (int i = 0; i < 26; i++) {\n if (left[i] == -1) {\n continue;\n }\n count = new boolean[26];\n for (int j = left[i] + 1; j < right[i]; j++) {\n if(!count[s.charAt(j)-\'a\']){\n count[s.charAt(j)-\'a\'] = true;\n ans++;\n } \n }\n }\n return ans;\n }\n}\n```\n\n```\nclass Solution {\npublic:\n int countPalindromicSubsequence(std::string s) {\n std::vector<int> left(26, -1);\n std::vector<int> right(26, -1);\n\n int curr;\n for (int i = 0; i < s.length(); i++) {\n curr = s[i] - \'a\';\n if (left[curr] == -1) {\n left[curr] = i;\n }\n right[curr] = i;\n }\n\n int ans = 0;\n std::vector<bool> count(26, false);\n for (int i = 0; i < 26; i++) {\n if (left[i] == -1) {\n continue;\n }\n std::fill(count.begin(), count.end(), false);\n for (int j = left[i] + 1; j < right[i]; j++) {\n if (!count[s[j] - \'a\']) {\n count[s[j] - \'a\'] = true;\n ans++;\n }\n }\n }\n\n return ans;\n }\n};\n```\n\n```\nclass Solution:\n def countPalindromicSubsequence(self, s: str) -> int:\n left = [-1] * 26\n right = [-1] * 26\n\n for i in range(len(s)):\n curr = ord(s[i]) - ord(\'a\')\n if left[curr] == -1:\n left[curr] = i\n right[curr] = i\n\n ans = 0\n count = [False] * 26\n for i in range(26):\n if left[i] == -1:\n continue\n count = [False] * 26\n for j in range(left[i] + 1, right[i]):\n if not count[ord(s[j]) - ord(\'a\')]:\n count[ord(s[j]) - ord(\'a\')] = True\n ans += 1\n\n return ans\n```
98,478
Unique Length-3 Palindromic Subsequences
unique-length-3-palindromic-subsequences
Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Hash Table,String,Prefix Sum
Medium
What is the maximum number of length-3 palindromic strings? How can we keep track of the characters that appeared to the left of a given position?
12,509
144
# Problem Description\n\nGiven a string `s`, calculates the count of **unique** palindromes of length **three** that can be formed as **subsequences** within `s`. \n\nA **palindrome** is a string that reads the **same** forward and backward. In this context, a **subsequence** of a string is a new string formed by **deleting** some characters (possibly none) from the original string without altering the relative **order** of the remaining characters.\n\n**Note** that the count should consider only **unique** palindromes, even if there are multiple ways to derive the same subsequence.\n\n- **Constraints:**\n - $3 <= s.length <= 10^5$\n - `s` consists of only **lowercase** English letters.\n - Count **unique** palindromes\n\n\n---\n\n\n\n# Intuition\n\nHi there,\uD83D\uDE04\n\nHow are you? I hope you are fine \uD83D\uDE03\uD83D\uDCAA\nLet\'s zoom in\uD83D\uDD0E the details of our today\'s interesting problem.\n\nWe have a string\uD83E\uDDF5 and we want to calculate the number of **palindrome** subsequences in this string of length `3` specifically the **unique** number of those subsequences.\n\nOk, seems easy to solve right ?\uD83E\uDD14\nFirst thing that we can think of is our big guy **BRUTE FORCE**\uD83D\uDCAA\uD83D\uDCAA.\nBy **looping** over all the characters of our string and thing look **forward** and **backward** for **similar** characters that can form 3-length palindrome.\uD83D\uDE03\nUnfortunately, this solution will give us $O(N ^ 2)$ time complexity, **TLE** and some **headaches**.\uD83D\uDE02\uD83D\uDE02\n\nHow can we improve this solution atleast to get rid of headaces?\uD83D\uDCA2\nDid you notice something I said earlier ?\uD83E\uDD28\nWe will look for **similar** characters forward and backward for every character in our string.\uD83E\uDD2F\n\nSo why don\'t we change our perspective a little !\uD83E\uDD29\nWe know that we have `26` **unique** characters in English so why don\'t we compute last and first occurences only for each character and then for each **pair** of them let\'s see how many **unique** letters between them.\uD83E\uDD2F\n\nHuh, Does that improve our time complexity ?\uD83E\uDD14\nYes, alot and also remove headaces.\uD83D\uDE02\uD83D\uDCA2\nto compute **first** and **last** occurences of every character of the `26` English characters it will take us to iterate over the input string one time and to look for every **unique** character between them it will take at most to iterate over the whole string for the `26` English characters which is `26 * N` so it is at most `27 * N` iterations which is $O(N)$.\uD83E\uDD29\n\nLet\'s see an example:\n```\ninput = abascba\n\nFirst occurence: a -> 0\n b -> 1\n c -> 4\n s -> 3\nLast occurence: a -> 6\n b -> 5\n c -> 4\n s -> 3\n\nNow for each character of them we calculate number of unique characters between both occurences.\n\nFor a -> 0 : 6\n unique chars -> a, b, c, s -> 4 answers\nFor b -> 1 : 5\n unique chars -> a, c, s -> 3 answers\nFor c -> 4 : 4\n unique chars -> - -> 0 answers\nFor s -> 5 : 5\n unique chars -> - -> 0 answers\n\nFinal asnwer is 4 + 3 + 0 + 0 = 7\n```\n\n```\ninput = bbsasccbaba\n\nFirst occurence: a -> 3\n b -> 0\n c -> 5\n s -> 2\nLast occurence: a -> 10\n b -> 9\n c -> 6\n s -> 4\n\nNow for each character of them we calculate number of unique characters between both occurences.\n\nFor a -> 3 : 10\n unique chars -> a, b, c, s -> 4 answers\nFor b -> 0 : 9\n unique chars -> a, b, c, s -> 4 answers\nFor c -> 5 : 6\n unique chars -> - -> 0 answers\nFor s -> 2 : 4\n unique chars -> a -> 1 answers\n\nFinal asnwer is 4 + 4 + 0 + 1 = 9\n```\nAnd this how will our algorithm work. \u2728\n\n**Bonus part**\uD83E\uDD29\nWhat is the **maximum** answer that can we get for this problem ?\uD83E\uDD14\n<details>\n <summary>Click to show the answer</summary>\n <div>\n It is 676 but why?\uD83E\uDD28 </br>\n <details>\n <summary>Click to show the justification</summary>\n <div>How we got such a number? </br>\n We remember that we have 26 unique chars in English right? </br>\n our palidrome subsequences are formed of 3 places _ _ _ let\'s call them a b c. a and c must have the same value of the 26 chars and b can be any char of the 26 chars so the answer will be 26 * 26 different unique palindromes.\n </div>\n </details>\n </div>\n</details>\n\n</br>\nAnd this is the solution for our today\'S problem I hope that you understood it\uD83D\uDE80\uD83D\uDE80\n\n\n\n\n---\n\n\n# Approach\n1. **Initialize Arrays:** Create arrays `minExist` and `maxExist` with 26 elements each, initialized to `INT_MAX` and `INT_MIN`, respectively.\n2. **Populate Arrays:** Iterate through each character in the input string, updating the minimum and maximum occurrences for each character in the corresponding arrays.\n3. **Count Unique Palindromic Subsequences:**\n - Iterate over each character in the alphabet (26 characters).\n - Check if the character has occurred in the input string. If not, skip to the next character.\n - Create an empty set `uniqueCharsBetween` to store unique characters between the minimum and maximum occurrences of the current character.\n - Iterate over the characters between the minimum and maximum occurrences, adding each character to the set.\n - Add the count of unique characters between occurrences to `uniqueCount`.\n4. **Return Result:** Return the total count of unique palindromic subsequences `uniqueCount`.\n\n\n## Complexity\n- **Time complexity:** $O(N)$\nSince we iterating **two** passes, **first** pass to compute first and last occurence for each character with time `N` and **second** pass to compute number of unique palindromes. In the **second** pass we iterate over all the unique characters which are `26` and we iterate between their first and last occurence to compute the number of unique characters which can be at most `N` characters.\nSo time complexity is `26 * N + N` which is `27 * N` which is also `O(N)`.\nWhere `N` is number of characters in our input string.\n\n- **Space complexity:** $O(1)$\nSince we are storing two arrays to compute last and first occurence each one of them is of size `26` and we use hash set that can be at maximum with size `26` so the space complexity is still `O(1)`. Since we have constant space variables.\n\n\n---\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int countPalindromicSubsequence(string inputString) {\n // Arrays to store the minimum and maximum occurrences of each character in the input string\n vector<int> minExist(26, INT_MAX);\n vector<int> maxExist(26, INT_MIN);\n\n // Populate minExist and maxExist arrays\n for(int i = 0; i < inputString.size(); i++) {\n int charIndex = inputString[i] - \'a\';\n minExist[charIndex] = min(minExist[charIndex], i);\n maxExist[charIndex] = max(maxExist[charIndex], i);\n }\n\n // Variable to store the final count of unique palindromic subsequences\n int uniqueCount = 0;\n\n // Iterate over each character in the alphabet\n for (int charIndex = 0; charIndex < 26; charIndex++) {\n // Check if the character has occurred in the input string\n if (minExist[charIndex] == INT_MAX || maxExist[charIndex] == INT_MIN) {\n continue; // No occurrences, move to the next character\n }\n\n // Set to store unique characters between the minimum and maximum occurrences\n unordered_set<char> uniqueCharsBetween;\n\n // Iterate over the characters between the minimum and maximum occurrences\n for (int j = minExist[charIndex] + 1; j < maxExist[charIndex]; j++) {\n uniqueCharsBetween.insert(inputString[j]);\n }\n\n // Add the count of unique characters between the occurrences to the final count\n uniqueCount += uniqueCharsBetween.size();\n }\n\n // Return the total count of unique palindromic subsequences\n return uniqueCount;\n }\n};\n```\n```Java []\nclass Solution {\n public int countPalindromicSubsequence(String inputString) {\n // Arrays to store the minimum and maximum occurrences of each character in the input string\n int[] minExist = new int[26];\n int[] maxExist = new int[26];\n for (int i = 0; i < 26; i++) {\n minExist[i] = Integer.MAX_VALUE;\n maxExist[i] = Integer.MIN_VALUE;\n }\n\n // Populate minExist and maxExist arrays\n for (int i = 0; i < inputString.length(); i++) {\n int charIndex = inputString.charAt(i) - \'a\';\n minExist[charIndex] = Math.min(minExist[charIndex], i);\n maxExist[charIndex] = Math.max(maxExist[charIndex], i);\n }\n\n // Variable to store the final count of unique palindromic subsequences\n int uniqueCount = 0;\n\n // Iterate over each character in the alphabet\n for (int charIndex = 0; charIndex < 26; charIndex++) {\n // Check if the character has occurred in the input string\n if (minExist[charIndex] == Integer.MAX_VALUE || maxExist[charIndex] == Integer.MIN_VALUE) {\n continue; // No occurrences, move to the next character\n }\n\n // Set to store unique characters between the minimum and maximum occurrences\n HashSet<Character> uniqueCharsBetween = new HashSet<>();\n\n // Iterate over the characters between the minimum and maximum occurrences\n for (int j = minExist[charIndex] + 1; j < maxExist[charIndex]; j++) {\n uniqueCharsBetween.add(inputString.charAt(j));\n }\n\n // Add the count of unique characters between the occurrences to the final count\n uniqueCount += uniqueCharsBetween.size();\n }\n\n // Return the total count of unique palindromic subsequences\n return uniqueCount;\n }\n}\n```\n```Python []\nclass Solution:\n def countPalindromicSubsequence(self, inputString):\n # Arrays to store the minimum and maximum occurrences of each character in the input string\n min_exist = [float(\'inf\')] * 26\n max_exist = [float(\'-inf\')] * 26\n\n # Populate min_exist and max_exist arrays\n for i in range(len(inputString)):\n char_index = ord(inputString[i]) - ord(\'a\')\n min_exist[char_index] = min(min_exist[char_index], i)\n max_exist[char_index] = max(max_exist[char_index], i)\n\n # Variable to store the final count of unique palindromic subsequences\n unique_count = 0\n\n # Iterate over each character in the alphabet\n for char_index in range(26):\n # Check if the character has occurred in the input string\n if min_exist[char_index] == float(\'inf\') or max_exist[char_index] == float(\'-inf\'):\n continue # No occurrences, move to the next character\n\n # Set to store unique characters between the minimum and maximum occurrences\n unique_chars_between = set()\n\n # Iterate over the characters between the minimum and maximum occurrences\n for j in range(min_exist[char_index] + 1, max_exist[char_index]):\n unique_chars_between.add(inputString[j])\n\n # Add the count of unique characters between the occurrences to the final count\n unique_count += len(unique_chars_between)\n\n # Return the total count of unique palindromic subsequences\n return unique_count\n```\n```C []\nint countPalindromicSubsequence(char* inputString) {\n // Arrays to store the minimum and maximum occurrences of each character in the input string\n int minExist[26];\n int maxExist[26];\n\n // Initialize arrays with default values\n for (int i = 0; i < 26; i++) {\n minExist[i] = INT_MAX;\n maxExist[i] = INT_MIN;\n }\n\n // Populate minExist and maxExist arrays\n for (int i = 0; inputString[i] != \'\\0\'; i++) {\n int charIndex = inputString[i] - \'a\';\n minExist[charIndex] = (minExist[charIndex] < i) ? minExist[charIndex] : i;\n maxExist[charIndex] = (maxExist[charIndex] > i) ? maxExist[charIndex] : i;\n }\n\n // Variable to store the final count of unique palindromic subsequences\n int uniqueCount = 0;\n\n // Iterate over each character in the alphabet\n for (int charIndex = 0; charIndex < 26; charIndex++) {\n // Check if the character has occurred in the input string\n if (minExist[charIndex] == INT_MAX || maxExist[charIndex] == INT_MIN) {\n continue; // No occurrences, move to the next character\n }\n\n // Set to store unique characters between the minimum and maximum occurrences\n char uniqueCharsBetween[CHAR_MAX];\n int uniqueCharsCount = 0;\n\n // Iterate over the characters between the minimum and maximum occurrences\n for (int j = minExist[charIndex] + 1; j < maxExist[charIndex]; j++) {\n int charExists = 0;\n for (int k = 0; k < uniqueCharsCount; k++) {\n if (uniqueCharsBetween[k] == inputString[j]) {\n charExists = 1;\n break;\n }\n }\n if (!charExists) {\n uniqueCharsBetween[uniqueCharsCount++] = inputString[j];\n }\n }\n\n // Add the count of unique characters between the occurrences to the final count\n uniqueCount += uniqueCharsCount;\n }\n\n // Return the total count of unique palindromic subsequences\n return uniqueCount;\n}\n```\n\n\n![HelpfulJerry.jpg]()\n
98,482
Unique Length-3 Palindromic Subsequences
unique-length-3-palindromic-subsequences
Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Hash Table,String,Prefix Sum
Medium
What is the maximum number of length-3 palindromic strings? How can we keep track of the characters that appeared to the left of a given position?
232
5
# Intuition\nFor each letter check if there is another letter in between its min and max positions\n\n# Approach\nStore positions for each character\nLoop over combinations of two characters. Take min and max positions from one of them and check if there is a position in between them for the second char using binary search.\n\n# Complexity\n- Time complexity:\nO(N + 26^2 * log(N))\n\n- Space complexity:\nO(N*26) = O(N)\n\n# Code\n```\nclass Solution:\n def countPalindromicSubsequence(self, s: str) -> int:\n c2pos = defaultdict(list)\n for index, c in enumerate(s):\n c2pos[c].append(index)\n n = len(s)\n res = 0\n for center, center_positions in c2pos.items():\n for candidate, cand_positions in c2pos.items():\n # if its the same character then\n # we only need to have at least three of them\n # to get palindrome\n if candidate == center:\n if len(center_positions) >= 3:\n res += 1\n continue\n # get min and max positions of a char\n left_pos, right_pos = cand_positions[0], cand_positions[-1]\n # check if center char has position in between\n index = bisect.bisect_left(center_positions, left_pos)\n if index < 0 or index > len(center_positions) - 1: continue\n if left_pos < center_positions[index] < right_pos:\n res += 1\n return res\n\n```
98,487
Unique Length-3 Palindromic Subsequences
unique-length-3-palindromic-subsequences
Given a string s, return the number of unique palindromes of length three that are a subsequence of s. Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once. A palindrome is a string that reads the same forwards and backwards. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Hash Table,String,Prefix Sum
Medium
What is the maximum number of length-3 palindromic strings? How can we keep track of the characters that appeared to the left of a given position?
3,882
82
# Intuition\nFind the same characters at the both sides.\n\n---\n\n# Solution Video\n\n\n\n\u203B Since I recorded that video last year, there might be parts that could be unclear. If you have any questions, feel free to leave a comment.\n\n\u25A0 Timeline of the video\n\n`0:00` Read the question of Unique Length-3 Palindromic Subsequences\n`1:03` Explain a basic idea to solve Unique Length-3 Palindromic Subsequences\n`4:48` Coding\n`8:01` Summarize the algorithm of Unique Length-3 Palindromic Subsequences\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\n\n\nSubscribers: 3,083\nMy first goal is 10,000 (It\'s far from done \uD83D\uDE05)\nThank you for your support!\n\n**My channel reached 3,000 subscribers these days. Thank you so much for your support!**\n\n---\n\n# Approach\n\n## How we think about a solution\n\nWe know that we create strings which are length of `3`. So simply if we find the same characters at the both sides, we can create Unique Length-3 Palindromic Subsequences, because Length-3 palindrome has only one pattern.\n\nFor example\n```\naba: OK\nxyx: OK\nctc: OK\naaa: OK\n\naab: not good\nbaa: not good\n\n```\n\n---\n\n\u2B50\uFE0F Points\n\nWe will create and count this pattern.\n```\na _ a\nz _ z\n```\nBoth sides of characters are the same.\n\n---\n\n\n\n\n##### How can you create the strings?\n\nLet\'s say\n\n```\nInput: ababcad\n```\nLet\'s find the frist `a` from beginning and from the last.\n```\nababcad\n\u2191 \u2191\n```\n\nNext, look at the characters between `a`.\n\n```\nbabc\n```\nNow we find `a` at the both sides. So if we can make each character unique between `a`, that means we can create Unique Length-3 Palindromic Subsequences.\n\nIn this case,\n\n```\n(a)babc(a) \u2192 (a)bac(a)\naba\naaa\naca\n``` \n---\n\n\u2B50\uFE0F Points\n\nIterate through input string from the beginning and from the last. Try to find the same characters at the both sides. Then we make each character unique between the same characters.\n\n--- \n\n##### How many times do you have to find the same characters at the both sides.\n\nThe answer is number of unique characters in input string.\n```\nInput: ababcad\n```\nIn this case, we should find `a`,`b`,`c`,`d` 4 times, because there is posibility that we can create Unique Length-3 Palindromic Subsequences with each unique character.\n\nLet\'s see the rest of characters `b`,`c`,`d`\n```\ntarget = b\n\nababcad\n \u2191 \u2191\n\nFound bab\n```\n```\ntarget = c\n\nababcad\n \u2191\n \u2191\n\nThere is no Unique Length-3 Palindromic Subsequences.\n```\n```\ntarget = d\n\nababcad\n \u2191\n \u2191\n\nThere is no Unique Length-3 Palindromic Subsequences.\n```\nIn the end, we found\n```\naba\naaa\naca\nbab\n```\nOutput should be total number of unique characters between specific characters at the both sides.\n```\nbetween a, we have 3 unique characters (= b, a and c)\nbetween b, we have 1 unique character (= a)\nbetween c, we have 0 unique characters\nbetween d, we have 0 unique characters\n```\n```\nOutput: 4\n```\n\n\nEasy! \uD83D\uDE04\nLet\'s see a real algorithm.\n\n\n---\n\n### Algorithm Overview:\n\n1. Initialization\n\n2. Loop through unique characters\n\n3. Find the first and last occurrence of the character\n\n4. Check if there is a valid range\n\n5. Count unique characters within the valid range\n\n6. Return the result\n\n### Detailed Explanation:\n\n1. **Initialization**:\n ```python\n res = 0\n uniq = set(s)\n ```\n\n - Initialize `res` to 0, which will store the final result.\n - Create a set `uniq` containing unique characters from the string `s`.\n\n2. **Loop through unique characters**:\n ```python\n for c in uniq:\n ```\n\n - Iterate through each unique character in the set `uniq`.\n\n3. **Find the first and last occurrence of the character**:\n ```python\n start = s.find(c)\n end = s.rfind(c)\n ```\n\n - Use `find` to locate the first occurrence of the character `c`.\n - Use `rfind` to locate the last occurrence of the character `c`.\n\n4. **Check if there is a valid range**:\n ```python\n if start < end:\n ```\n\n - Verify that the first occurrence index is less than the last occurrence index.\n\n5. **Count unique characters within the valid range**:\n ```python\n res += len(set(s[start+1:end]))\n ```\n\n - If there is a valid range, calculate the length of the set of characters within the substring between `start+1` and `end` (excluding the character at `start`).\n - Add this length to the result.\n\n6. **Return the result**:\n ```python\n return res\n ```\n\n - After iterating through all unique characters, return the final result.\n \n\n# Complexity\n- Time complexity: $$O(26 * (n+n+n))$$ \u2192 $$O(n)$$\n3n is start, end, set in the for loop.\n\n- Space complexity: $$O(26)$$ \u2192 $$O(1)$$\n`uniq` variable has potentially 26 unique characters.\n\n\n```python []\nclass Solution:\n def countPalindromicSubsequence(self, s: str) -> int:\n \n res = 0\n uniq = set(s)\n \n for c in uniq:\n start = s.find(c) # search a character from the beginning\n end = s.rfind(c) # search a character from the last index\n \n if start < end:\n res += len(set(s[start+1:end]))\n \n return res\n```\n```javascript []\nvar countPalindromicSubsequence = function(s) {\n let res = 0;\n const uniq = new Set(s);\n\n for (const c of uniq) {\n const start = s.indexOf(c);\n const end = s.lastIndexOf(c);\n\n if (start < end) {\n res += new Set(s.slice(start + 1, end)).size;\n }\n }\n\n return res; \n};\n```\n```java []\nclass Solution {\n public int countPalindromicSubsequence(String s) {\n int res = 0;\n Set<Character> uniq = new HashSet<>();\n\n for (char c : s.toCharArray()) {\n uniq.add(c);\n }\n\n for (char c : uniq) {\n int start = s.indexOf(c);\n int end = s.lastIndexOf(c);\n\n if (start < end) {\n Set<Character> charSet = new HashSet<>();\n for (int i = start + 1; i < end; i++) {\n charSet.add(s.charAt(i));\n }\n res += charSet.size();\n }\n }\n\n return res; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int countPalindromicSubsequence(string s) {\n int res = 0;\n unordered_set<char> uniq;\n\n for (char c : s) {\n uniq.insert(c);\n }\n\n for (char c : uniq) {\n int start = s.find(c);\n int end = s.rfind(c);\n\n if (start < end) {\n unordered_set<char> charSet;\n for (int i = start + 1; i < end; i++) {\n charSet.insert(s[i]);\n }\n res += charSet.size();\n }\n }\n\n return res; \n }\n};\n```\n\n---\n\nThank you for reading my post.\n\u2B50\uFE0F Please upvote it and don\'t forget to subscribe to my channel!\n\n\u25A0 Subscribe URL\n\n\n\u25A0 Twitter\n\n\n### My next daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`0:19` Important condition\n`0:56` Demonstrate how it works\n`3:08` What if we have a lot of the same numbers in input array?\n`4:10` Coding\n`4:55` Time Complexity and Space Complexity\n\n### My previous daily coding challenge post and video.\n\npost\n\n\nvideo\n\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`1:19` Demonstrate how it works\n`3:09` Coding\n`5:02` Time Complexity and Space Complexity\n
98,491
Painting a Grid With Three Different Colors
painting-a-grid-with-three-different-colors
You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.
Dynamic Programming
Hard
Represent each colored column by a bitmask based on each cell color. Use bitmasks DP with state (currentCell, prevColumn).
805
11
*foreword: I\'m trying to share logical thought process for deriving various solutions from scratch with minimum tricks, if you think this style helps, please kindly **upvote** and/or **comment** for encouragement, or leave your thoughts to tune the content, thanks and happy thought processing :)*\n\n1) naive: find all [color choices] of [all cells] and check if meet constraint -> each cell has 3 color choices, there are m*n cells, so total ways are: `3*3*...*3` with `m*n` terms \n\t- -> Time: `O(3^(m*n) * (m*n))`\n\n2) is there any processed info can be reused? \n -> row=i ways only depends on row=i-1 ways if all ways before are embedded into row=i-1 \n```\nrow colors\ni-3 *** ***\ni-2 *** ***\ni-1 GRG GBR\ni RGB RGB\n```\n\n3) each row way as a state, each row=i state has possible transitions from all row=i-1\'s states, and filtered by constraint (color of adjacent cell differs), so state transition per row is:\n n_ways(row=i, state=way1) = valid(n_ways(row=i-1, state=way1)) + valid(n_ways(row=i-1, state=way2)) + ...\n n_ways(row=i, state=way2) = valid(n_ways(row=i-1, state=way1)) + valid(n_ways(row=i-1, state=way2)) + ...\n ...\n the number of state transitions are: `[number of row=i\'s states] * [number of row=i-1\'s states]`\n \n4) base on 3). each row has 3^m or 3^n states, since m is much smaller, so we choose m as column and states per row will be 3^m . so \n\t- [number of state transitions] = [number of row=i\'s states] * [number of row=i-1\'s states] = (3^m) * (3^m) = (3^m)^2\n\t- -> Total Time: [number of rows] * [state transitions] = `n * ( (3^m)^2 )`\n\t- -> `n * 243^2 (m=5)`\n\t since row and column are exchange-able logically in this case.\n\n5) we found that not all states are valid due to the constraint, e.g. RRB, GGB is invalid, so we can prune row\'s state as [3 choose 1, 2 choose 1, ... , 2 choose 1] , then number of states will become 3 * ( 2 ^ (m-1) ) \n\t- -> [state transitions]: ( 3 * ( 2 ^ (m-1) ) ) ^ 2\n\t- -> Total Time: `n*((3*(2^(m-1)))^2)`\n\t- -> `n * ( 48^2 )` (m=5)\n\n6) observe 5)\'s states to see if there are any repeated patterns for reducing calculations\n```\n123\n---\nRGB\nRBG\nGRB\nGBR\nBRG\nBGR\n```\n - when m=3, RGB, BGR, GRB seems the same pattern where 1st, 2nd, 3rd cell colors differs to each other, can be denoted as [123]. While RGR, GRG seems the same pattern where 1st, 3rd cell color are the same, denoted [121]. So that if we can prove each permutation of the same pattern has the same state transition, then we can safely calculate 1 permutation\'s state value(ways) and multiply by number of permutations to get total original ways.\n The permutations of a pattern [123] can be calculated by replacing as color permutations\n denoted as `P(|colors|, |pattern colors|)`, \nP(3,3)=6, when m >= 3\nP(3,2)=6, when m = 2\nP(3,1)=3, when m <= 1\n-> generalized as `P(3, min(3, m))`\n\n7) what about number of state transitions of each permutation of a specific pattern? we found numbers are the same as well, since they are also permutations of same pattern state transitions, \ne.g. m=3,\n```\nrow=i row=i-1\nBGR(123) GBG(121) GRB(123) GRG(121) RBG(123) \nBRG(123) GBR(123) RBR(121) RGB(123) RGR(121) \n```\n- n_ways(row=i, state=[123]) = n_ways(row=i-1, state=[121])*2 + n_ways(row=i-1, state=[123])*2\n\n\n8) based on 6), number of pattern as state can be: when m=3, first 2 cells as [12], then 3rd cell can choose from {1,3} and result in [123], [121] \n -> total number is 2 \n -> generalize as `1* 1 * 2^(m-2)` = `2^(m-2)`\n\n9) based on 7), since we know row=i-1\'s number of pattern as state are also 2^(m-2), how do we find all state transitions as \n `n_ways(row=i, state=way1) = n_ways(row=i-1, state=way1)*n1 + n_ways(row=i-1, state=way2)*n2 + ...`?\n ```\nrow=i row=i-1\n123 212(121) 231(123) 232(121) 312(123) \n121 212(121) 213(123) 232(121) 312(123) 313(121)\n```\n- if we think from single row=i\'s pattern [123]\'s transitions from row=i-1 possible patterns [212], [232] can also generalized to [121], which means it has [121] * 2 transitions\n\t- "normalize" row=i-1 pattern as 1st cell as 1, 2nd cell as 2, rest cell as 3 (e.g. [231] -> 2:1, 3:2, 1:3 -> pattern:[123])\n\t- finally, we can get\n\t `n_ways(row=i, state=[123]) = n_ways(row=i-1, state=[121])*2 + n_ways(row=i-1, state=[123])*2`\n\n10) base 8), 9), \n\t- -> [state transitions]: `( 2^(m-2) ) ^ 2`\n\t- -> Total Time: `n*((2^(m-2))^2)`\n\t- -> `n * ( 8^2 )` (m=5)\n\n11) we can store row\'s state transitions function in advance, so for each row\'s state-value calculation we just reference that without re-calculation of state transitions\n\n12) since each state\'s element is m <= 5, additional compression by 3-base or 2-bit doesn\'t help much\n\n< code >\n```python\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n from functools import reduce\n MOD = 10**9 + 7\n sum_mod = lambda x,y: (x+y)%MOD\n \n def normalize(pat_var):\n mapping = { e:i+1 for i, e in enumerate(pat_var[0:2]) }\n mapping[list({1,2,3}.difference(mapping.keys()))[0]] = 3\n return tuple([ mapping[e] for e in pat_var])\n \n def get_pats(m, i, pat, pats):\n if i == m-1:\n pats.append(tuple(pat))\n return\n i_nx = i+1\n for p_it_nx in (1,2,3):\n if (i_nx <= 1 and p_it_nx == i_nx+1 ) or (i_nx >= 2 and p_it_nx != pat[-1]):\n pat.append(p_it_nx)\n get_pats(m, i_nx, pat, pats)\n pat.pop()\n return pats\n \n def get_trans(pat, i, pat_pre, trans):\n if i == len(pat)-1:\n pat_nl = normalize(pat_pre)\n trans[pat_nl] = trans.get(pat_nl, 0) + 1\n return\n for p_it_pre in (1,2,3):\n i_nx = i+1\n if (p_it_pre != pat[i_nx]\n and (not pat_pre or p_it_pre != pat_pre[-1])):\n pat_pre.append(p_it_pre)\n get_trans(pat, i_nx, pat_pre, trans)\n pat_pre.pop()\n return trans\n\n pats = get_pats(m, -1, [], [])\n # {pattern_i: {pattern_pre:count}}\n pat_trans = { pat: get_trans(pat, -1, [], {}) for pat in pats } \n \n p_counts = { pat:1 for pat in pat_trans.keys() }\n for i in range(n-1):\n p_counts_new = {}\n for pat, trans in pat_trans.items():\n p_counts_new[pat] = reduce(sum_mod, (p_counts[pat_pre] * cnt for pat_pre, cnt in trans.items()))\n p_counts = p_counts_new\n \n res = reduce(sum_mod, (cnt for cnt in p_counts.values()))\n perms = reduce(lambda x,y: x*y, (3-i for i in range(min(3,m))))\n return (res * perms) % MOD\n```\n\n< reference >\n-
98,585
Painting a Grid With Three Different Colors
painting-a-grid-with-three-different-colors
You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.
Dynamic Programming
Hard
Represent each colored column by a bitmask based on each cell color. Use bitmasks DP with state (currentCell, prevColumn).
1,404
12
Using dp. Consider each row to be a state, we can find the valid adjacent states. Becomes number of paths problem.\nTime complexity : O(n*3^m) \n```\n\nfrom functools import cache, lru_cache\nfrom itertools import product\n\n\nclass Solution:\n def colorTheGrid(self, m: int, n: int) -> int:\n mod = 10 ** 9 + 7\n\n def check(pos):\n return all(a != b for a, b in zip(pos, pos[1:]))\n\n def neighs(pos1, pos2):\n return all(a != b for a, b in zip(pos1, pos2))\n\n states = {\'\'.join(pos) for pos in product(\'RGB\', repeat=m) if check(pos)}\n adj = {}\n for state in states:\n adj[state] = [next_state for next_state in states if neighs(state, next_state)]\n\n @cache\n def f(prv_state, N):\n if N == 0:\n return 1\n return sum(f(next_state, N - 1) for next_state in adj[prv_state]) % mod\n\n return sum(f(state, n - 1) for state in states) % mod\n\n\n
98,588
Add Minimum Number of Rungs
add-minimum-number-of-rungs
You are given a strictly increasing integer array rungs that represents the height of rungs on a ladder. You are currently on the floor at height 0, and you want to reach the last rung. You are also given an integer dist. You can only climb to the next highest rung if the distance between where you are currently at (the floor or on a rung) and the next rung is at most dist. You are able to insert rungs at any positive integer height if a rung is not already there. Return the minimum number of rungs that must be added to the ladder in order for you to climb to the last rung.
Array,Greedy
Medium
Go as far as you can on the available rungs before adding new rungs. If you have to add a new rung, add it as high up as possible. Try using division to decrease the number of computations.
2,463
39
The only trick here is to use division, as the gap between two rungs could be large. We will get TLE if we add rungs one-by-one.\n\n**Java**\n```java\npublic int addRungs(int[] rungs, int dist) {\n int res = (rungs[0] - 1) / dist;\n for (int i = 1; i < rungs.length; ++i)\n res += (rungs[i] - rungs[i - 1] - 1) / dist;\n return res;\n}\n```\n**C++**\n```cpp\nint addRungs(vector<int>& rungs, int dist) {\n int res = (rungs[0] - 1) / dist;\n for (int i = 1; i < rungs.size(); ++i)\n res += (rungs[i] - rungs[i - 1] - 1) / dist;\n return res;\n}\n```\n**Python 3**\n```python\nclass Solution:\n def addRungs(self, rungs: List[int], dist: int) -> int:\n return sum((a - b - 1) // dist for a, b in zip(rungs, [0] + rungs))\n```
98,629
Maximum Number of Points with Cost
maximum-number-of-points-with-cost
You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. Return the maximum number of points you can achieve. abs(x) is defined as:
Array,Dynamic Programming
Medium
Try using dynamic programming. dp[i][j] is the maximum number of points you can have if points[i][j] is the most recent cell you picked.
2,329
23
It\'s a pretty standard dynamic programming problem. It is easy to find the O(M * N^2) solution but it is possible to go lower with some post-processing of the memory array.\n\n```\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n current_points = [point for point in points[0]]\n \n for row in range(1, len(points)):\n # We traverse current_points left to right and store the maximum possible score that the next row can get,\n # taking into account only the elements with indexes [0, col]\n max_col_points = -float("inf")\n for col in range(0, len(current_points)):\n max_col_points = max(max_col_points - 1, current_points[col])\n current_points[col] = max_col_points\n \n # We traverse current_points right to left and store the maximum possible score that the next row can get,\n # taking into account only the elements with indexes [col, end]\n max_col_points = -float("inf")\n for col in range(len(current_points) - 1, -1, -1):\n max_col_points = max(max_col_points - 1, current_points[col])\n current_points[col] = max_col_points\n \n # We update current_points, adding the maximum value we can carry over from the previous row to the value\n # contained in the current column of the current row\n for col in range(len(current_points)):\n current_points[col] = points[row][col] + current_points[col]\n \n return max(current_points)\n```
98,683
Maximum Number of Points with Cost
maximum-number-of-points-with-cost
You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. Return the maximum number of points you can achieve. abs(x) is defined as:
Array,Dynamic Programming
Medium
Try using dynamic programming. dp[i][j] is the maximum number of points you can have if points[i][j] is the most recent cell you picked.
1,421
17
![image]()\n\n```\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n m, n = len(points), len(points[0])\n \n dp = points[0]\n \n left = [0] * n ## left side contribution\n right = [0] * n ## right side contribution\n \n for r in range(1, m):\n for c in range(n):\n if c == 0:\n left[c] = dp[c]\n else:\n left[c] = max(left[c - 1] - 1, dp[c])\n \n for c in range(n - 1, -1, -1):\n if c == n-1:\n right[c] = dp[c]\n else:\n right[c] = max(right[c + 1] - 1, dp[c])\n \n for c in range(n):\n dp[c] = points[r][c] + max(left[c], right[c])\n \n return max(dp)\n```\n
98,697
Maximum Number of Points with Cost
maximum-number-of-points-with-cost
You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. Return the maximum number of points you can achieve. abs(x) is defined as:
Array,Dynamic Programming
Medium
Try using dynamic programming. dp[i][j] is the maximum number of points you can have if points[i][j] is the most recent cell you picked.
992
10
To brute force this problem we find the max value at each row, column by comparing it to the previous row, column and factoring in the subtraction based on distance. One for each index.\n\nThis leads to an `O(M*N**2)` time complexity. \n\nExperience with this sort of problem tells us that there\'s a dynamic programming solution that reduces the inner processing step to linear time.\n\nAssuming that we have a single row of size N to cache our results, we just have to come up with a memoization criteria. That criteria is as follows:\n\nEach dp[j] can be one of three values:\n1) dp[j]\n2) dp[j-1]-1\n3) dp[j+1]+1\n\nMoreover, dp[j+1] can be:\n1) dp[j+1]\n2) dp[j]-1\n3) dp[j+2]-1\n\nThis is because we know there\'s a cost of 1 for every value we selected previously. And `max(dp[0]-j, dp[1]-(j-1),..,dp[j]..)` is the same as `max(max(dp[0]-j, dp[1]-(j-1),..,dp[j-1]-1), dp[j])`. So we only need to compare the current dp value to its neighbor as we\'re iterating over the dp array.\n\nSo we just have to create a left to right dp array and a right to left dp array for every row and then take the max at each postion j and add it to the current point at points[i][j] to get the subsequent dp[j].\n\nThis leads to a time complexity of `O(M*N)` and a space complexity of `O(N)`.\n\n```\nclass Solution:\n def maxPoints(self, points: List[List[int]]) -> int:\n M, N = len(points), len(points[0])\n left = [0] * N\n right = [0] * N\n dp = points[0]\n for i in range(1, M):\n # process from left to right\n for j in range(N):\n if j == 0:\n left[0] = dp[0]\n else:\n left[j] = max(dp[j], left[j-1]-1)\n # process from right to left\n for j in range(N-1,-1,-1):\n if j == N-1:\n right[N-1] = dp[N-1]\n else:\n right[j] = max(dp[j], right[j+1]-1)\n # set the new max points at each column based on the max of going\n # left to right vs right to left\n for j in range(N):\n dp[j] = points[i][j] + max(left[j], right[j])\n return max(dp)\n```
98,700
Maximum Number of Points with Cost
maximum-number-of-points-with-cost
You are given an m x n integer matrix points (0-indexed). Starting with 0 points, you want to maximize the number of points you can get from the matrix. To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c) will add points[r][c] to your score. However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r and r + 1 (where 0 <= r < m - 1), picking cells at coordinates (r, c1) and (r + 1, c2) will subtract abs(c1 - c2) from your score. Return the maximum number of points you can achieve. abs(x) is defined as:
Array,Dynamic Programming
Medium
Try using dynamic programming. dp[i][j] is the maximum number of points you can have if points[i][j] is the most recent cell you picked.
1,042
5
DP idea:\n***base line, r=0***: at each (r, c) the largets score at (0, c) = max(points[r][c], "largest score passed from the left", "largest score passed from the right")\n***first iteration, r=1***: ***largets score at (1, c)*** = max( ***largets score at (0, c)*** , "largest score passed from the left", "largest score passed from the right")\nHere we found the state transfer already: ***state(r,c)*** = max(***state(r-1,c)*** , extra cases for this state).\n\nTime: O(mn)\nSpace: O(n) (O(1) if using points in space)\n```\n def maxPoints(self, points):\n dp = [0 for i in range(len(points[0]))] # each dp[c] means the max val points[r][c] can get from previous row\n for r in range(len(points)):\n dp[0] += points[r][0] \n for c in range(1, len(points[0])): # forward pass\n dp[c] = max(dp[c]+points[r][c], dp[c-1]-1)\n \n for c in range(len(points[0])-2, -1, -1): # backward pass\n dp[c] = max(dp[c], dp[c+1]-1)\n \n return max(dp)\n```
98,708
Sum of Digits of String After Convert
sum-of-digits-of-string-after-convert
You are given a string s consisting of lowercase English letters, and an integer k. First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total. For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations: Return the resulting integer after performing the operations described above.
String,Simulation
Easy
First, let's note that after the first transform the value will be at most 100 * 9 which is not much After The first transform, we can just do the rest of the transforms by brute force
667
5
# 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 getLucky(self, s: str, k: int) -> int:\n alphabet = {"a" : 1 , "b" : 2 , "c" : 3 , "d" : 4 , "e" : 5 , "f" : 6 , "g" : 7 \\\n , "h" : 8 , "i" : 9 , "j" : 10 , "k" : 11 , "l" : 12 , "m" : 13 , "n" : 14 , "o" : 15 \\\n , "p" : 16 , "q" : 17 , "r" : 18 , "s" : 19 , "t" : 20 , "u" : 21 , "v" : 22 , "w" : 23 \\\n , "x" : 24 , "y" : 25 , "z" : 26}\n answ = ""\n for i in s:\n answ += str(alphabet[i])\n while k != 0:\n answ = sum(int(x) for x in str(answ))\n k -= 1\n return answ\n\n\n```
98,792
Sum of Digits of String After Convert
sum-of-digits-of-string-after-convert
You are given a string s consisting of lowercase English letters, and an integer k. First, convert s into an integer by replacing each letter with its position in the alphabet (i.e., replace 'a' with 1, 'b' with 2, ..., 'z' with 26). Then, transform the integer by replacing it with the sum of its digits. Repeat the transform operation k times in total. For example, if s = "zbax" and k = 2, then the resulting integer would be 8 by the following operations: Return the resulting integer after performing the operations described above.
String,Simulation
Easy
First, let's note that after the first transform the value will be at most 100 * 9 which is not much After The first transform, we can just do the rest of the transforms by brute force
1,046
5
\n```\nclass Solution:\n def getLucky(self, s: str, k: int) -> int:\n s = "".join(str(ord(ch) - 96) for ch in s)\n for _ in range(k): \n x = sum(int(ch) for ch in s)\n s = str(x)\n return x \n```\n\n```\nclass Solution:\n def getLucky(self, s: str, k: int) -> int:\n s = "".join(str(ord(ch)-96) for ch in s)\n for _ in range(k): s = str(sum(int(ch) for ch in s))\n return int(s)\n```
98,811
Largest Number After Mutating Substring
largest-number-after-mutating-substring
You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d]. You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num. A substring is a contiguous sequence of characters within the string.
Array,String,Greedy
Medium
Should you change a digit if the new digit is smaller than the original? If changing the first digit and the last digit both make the number bigger, but you can only change one of them; which one should you change? Changing numbers closer to the front is always better
937
7
\n```\nclass Solution:\n def maximumNumber(self, num: str, change: List[int]) -> str:\n num = list(num)\n on = False \n for i, ch in enumerate(num): \n x = int(ch)\n if x < change[x]: \n on = True\n num[i] = str(change[x])\n elif x > change[x] and on: break\n return "".join(num)\n```
98,838
Largest Number After Mutating Substring
largest-number-after-mutating-substring
You are given a string num, which represents a large integer. You are also given a 0-indexed integer array change of length 10 that maps each digit 0-9 to another digit. More formally, digit d maps to digit change[d]. You may choose to mutate a single substring of num. To mutate a substring, replace each digit num[i] with the digit it maps to in change (i.e. replace num[i] with change[num[i]]). Return a string representing the largest possible integer after mutating (or choosing not to) a single substring of num. A substring is a contiguous sequence of characters within the string.
Array,String,Greedy
Medium
Should you change a digit if the new digit is smaller than the original? If changing the first digit and the last digit both make the number bigger, but you can only change one of them; which one should you change? Changing numbers closer to the front is always better
434
6
\tclass Solution:\n def maximumNumber(self, num: str, change: List[int]) -> str:\n flag=0\n ls=list(num)\n for i in range(len(ls)):\n k=int(ls[i])\n if change[k]>k:\n ls[i]=str(change[k])\n flag=1\n elif flag==1 and change[k]<k:\n break\n \n return "".join(ls)\n\n![image]()\n
98,839
Maximum Compatibility Score Sum
maximum-compatibility-score-sum
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores. Given students and mentors, return the maximum compatibility score sum that can be achieved.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
1,786
20
**Approach 1 - brute force**\n```\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m = len(students)\n \n score = [[0]*m for _ in range(m)]\n for i in range(m): \n for j in range(m): \n score[i][j] = sum(x == y for x, y in zip(students[i], mentors[j]))\n \n ans = 0 \n for perm in permutations(range(m)): \n ans = max(ans, sum(score[i][j] for i, j in zip(perm, range(m))))\n return ans \n```\n\nEdited on 7/26/2021\n**Approach 2 - dp**\n```\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m = len(students)\n \n score = [[0]*m for _ in range(m)]\n for i in range(m): \n for j in range(m): \n score[i][j] = sum(x == y for x, y in zip(students[i], mentors[j]))\n \n @cache \n def fn(mask, j): \n """Return max score of assigning students in mask to first j mentors."""\n ans = 0 \n for i in range(m): \n if not mask & (1<<i): \n ans = max(ans, fn(mask^(1<<i), j-1) + score[i][j])\n return ans \n \n return fn(1<<m, m-1)\n```
98,890
Maximum Compatibility Score Sum
maximum-compatibility-score-sum
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores. Given students and mentors, return the maximum compatibility score sum that can be achieved.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
804
10
This questions is similar to [1066. Campus Bike II](). Please also refer to my post: [Classical Dijkstra in Python with clear explanation]()\n\n`Workers` -> `Students`, `Bikes` -> `Mentors`, Manhattan distance -> Hamming distance \n\nHere I reimplemented the same idea with a classical Dijkstra algorithm with explanations, for those who are interested in this classical algorithm. \n\nThe code basically performs a state-based search, with certain kinds of `state` space and `cost`, with an `initial state` and a `termination condition`: \n\n`state` : a scheme of mentor assignment for the first `i` students, which can be denoted as a tuple (number of assigned students, status of all mentors). The status of all students can be denoted in multiple ways, here we use a bit string. (e.g. total 4 mentors, the first taken while the rest 3 available, \'1000\')\n\n`cost` : total sum of Hanmming distances between the students and mentors assigned following a scheme.\n\n`initial state`: no students assigned any mentor, all mentors are in available status. (e.g. (0, \'0000\'))\n\n`termination condition`: each student assigned a mentor. Since Dijkstra algorithm guarantees optimal cost when a node is closed, as well as BFS, so we can terminate the search when a scheme appears with last student assigned a mentor. \n\nThe final results is `m*n - total sum of Hamming distances`.\n\nHere is the code: \n\n```\nimport heapq\nfrom collections import defaultdict\n\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n m, n = len(students), len(students[0])\n def hamming(student, mentor):\n return sum([int(student[i] != mentor[i]) for i in range(n)])\n \n pq = [(0, 0, \'0\'*m)] # state: (n-comp_score aka Hamming distance, number of assigned students, mentor status)\n optimal = defaultdict(lambda:float(\'inf\'))\n \n while pq: # O(V)\n cost, i, mentor_status = heapq.heappop(pq) # O(logV)\n \n # early stopping with termination condition \n if i == m:\n return m * n - cost\n \n # generate successors. The next student to be assigned is at index i\n for j, mentor in enumerate(mentors): # O(m)\n if mentor_status[j] != \'1\':\n new_cost = cost + hamming(students[i], mentor)\n new_mentor_status = mentor_status[:j] + \'1\' + mentor_status[j+1:]\n \n # update optimal cost if a new successor appears with lower cost to the same node\n if new_cost < optimal[(i+1, new_mentor_status)]:\n optimal[(i+1, new_mentor_status)] = new_cost\n heapq.heappush(pq, (new_cost, i+1, new_mentor_status)) # O(logV)\n \n return 0\n```\n\n**Complexity**\nGiven `V` is the number of vertices, `E` is the number of edges in the graph, the time complexity of Dijkstra with min Heap is `O(V*logV + V*E/V*logV) = O((V+E)logV)`. Here the `O(E/V)` denotes the average number of neighbors of a vertex, where the neighbors of each vertices is stored in an adjacency list. In this problem, the average number of neighbors of a vertex is bounded by `O(m)`, since at each step we are looking for a mentor for the next step. \n\nSo the time complexity becomes: `O(V*logV + V*m*logV) = O(V(m+1)logV) = O(mVlogV)`, where `V`, the number of vertices, is bounded by O(`m!`), the number of permutations of `m` students, becasue each vertex denotes one possible way to assign at most `m`students to at most `m` mentors. And further more, `O(m!) <= O(m^m)`, so the time complexity is bounded as `<= O(m^(m+2)*log(m))`.
98,892
Maximum Compatibility Score Sum
maximum-compatibility-score-sum
There is a survey that consists of n questions where each question's answer is either 0 (no) or 1 (yes). The survey was given to m students numbered from 0 to m - 1 and m mentors numbered from 0 to m - 1. The answers of the students are represented by a 2D integer array students where students[i] is an integer array that contains the answers of the ith student (0-indexed). The answers of the mentors are represented by a 2D integer array mentors where mentors[j] is an integer array that contains the answers of the jth mentor (0-indexed). Each student will be assigned to one mentor, and each mentor will have one student assigned to them. The compatibility score of a student-mentor pair is the number of answers that are the same for both the student and the mentor. You are tasked with finding the optimal student-mentor pairings to maximize the sum of the compatibility scores. Given students and mentors, return the maximum compatibility score sum that can be achieved.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
Calculate the compatibility score for each student-mentor pair. Try every permutation of students with the original mentors array.
480
6
Since this was originally a contest problem, we want to find a solution that\'s simple to code.\n\nFirst thing to do is look at the constraints and when we do we notice that both m and n are at most 8. When the constraints are this small (less than 10/11) this means we can likely use a factorial time solution (or a polynomial solution with a high power.)\n\nAnd 8! is only 40k, so we can just try all pairings of mentor and student, since there are 8! of them.\n\n```\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n ans = 0\n for perm in itertools.permutations(range(len(students))):\n cur = 0\n for i in range(len(students)):\n for j in range(len(students[0])):\n cur += 1 if students[i][j] == mentors[perm[i]][j] else 0\n ans = max(ans, cur)\n return ans\n```\n\nThis uses `O(m! * n * m)` time and the extra memory use is `O(m)`.\n\n### Bonus One-Line version\nGranted it\'s split over multiple lines for readabilty.\n\nThe one trick I use is that `sum(array_of_bools)` returns the number of `True`s in the array.\n\n```\nclass Solution:\n def maxCompatibilitySum(self, students: List[List[int]], mentors: List[List[int]]) -> int:\n return max(\n sum(\n students[i][j] == mentors[perm[i]][j]\n for i in range(len(students)) \n for j in range(len(students[0]))\n ) \n for perm in itertools.permutations(range(len(students)))\n )\n```
98,902
Check if Move is Legal
check-if-move-is-legal
You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'. Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal). A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below: Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal.
Array,Matrix,Enumeration
Medium
For each line starting at the given cell check if it's a good line To do that iterate over all directions horizontal, vertical, and diagonals then check good lines naively
1,330
14
**Q & A**\n\nQ1: Why `size` is initialized to `2`?\nA1: We actually check the cells starting from the `2nd` one, and the first one is the cell we are allowed to change color. \n\n**End of Q & A**\n\n----\n\nStarting from the given cell, check if any of the 8 directions has a good line.\n\nFor each direction:\nCheck if any of the neighbors is empty, if yes, break; otherwise, keep checking till encounter a cell of same color, return true if size no less than `3`, otherwise break.\n\n```java\n private static final int[][] d = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {1, -1}, {-1, 1}};\n public boolean checkMove(char[][] board, int r, int c, char color) {\n for (int k = 0; k < 8; ++k) {\n for (int i = r + d[k][0], j = c + d[k][1], size = 2; 0 <= i && i < 8 && 0 <= j && j < 8; i += d[k][0], j += d[k][1], ++size) {\n if (board[i][j] == \'.\' || size < 3 && board[i][j] == color) {\n break;\n } \n if (board[i][j] == color) {\n return true;\n }\n }\n }\n return false;\n }\n```\n```python\n def checkMove(self, board: List[List[str]], r: int, c: int, color: str) -> bool:\n for dr, dc in (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1):\n i, j = r + dr, c + dc\n size = 2\n while 8 > i >= 0 <= j < 8:\n if board[i][j] == \'.\'or size < 3 and board[i][j] == color:\n break \n if board[i][j] == color:\n return True \n i += dr\n j += dc\n size += 1\n return False\n```
98,983
Check if Move is Legal
check-if-move-is-legal
You are given a 0-indexed 8 x 8 grid board, where board[r][c] represents the cell (r, c) on a game board. On the board, free cells are represented by '.', white cells are represented by 'W', and black cells are represented by 'B'. Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only legal if, after changing it, the cell becomes the endpoint of a good line (horizontal, vertical, or diagonal). A good line is a line of three or more cells (including the endpoints) where the endpoints of the line are one color, and the remaining cells in the middle are the opposite color (no cells in the line are free). You can find examples for good lines in the figure below: Given two integers rMove and cMove and a character color representing the color you are playing as (white or black), return true if changing cell (rMove, cMove) to color color is a legal move, or false if it is not legal.
Array,Matrix,Enumeration
Medium
For each line starting at the given cell check if it's a good line To do that iterate over all directions horizontal, vertical, and diagonals then check good lines naively
602
8
\n```\nclass Solution:\n def checkMove(self, board: List[List[str]], rMove: int, cMove: int, color: str) -> bool:\n for di, dj in (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1): \n i, j = rMove+di, cMove+dj\n step = 0\n while 0 <= i < 8 and 0 <= j < 8: \n if board[i][j] == color and step: return True \n if board[i][j] == "." or board[i][j] == color and not step: break \n i, j = i+di, j+dj\n step += 1\n return False\n```
98,986
Minimum Total Space Wasted With K Resizing Operations
minimum-total-space-wasted-with-k-resizing-operations
You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size). The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length. Return the minimum total space wasted if you can resize the array at most k times. Note: The array can have any size at the start and does not count towards the number of resizing operations.
Array,Dynamic Programming
Medium
Given a range, how can you find the minimum waste if you can't perform any resize operations? Can we build our solution using dynamic programming using the current index and the number of resizing operations performed as the states?
1,398
14
\n```\nclass Solution:\n def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int:\n \n @cache\n def fn(i, k): \n """Return min waste from i with k ops."""\n if i == len(nums): return 0\n if k < 0: return inf \n ans = inf\n rmx = rsm = 0\n for j in range(i, len(nums)): \n rmx = max(rmx, nums[j])\n rsm += nums[j]\n ans = min(ans, rmx*(j-i+1) - rsm + fn(j+1, k-1))\n return ans \n \n return fn(0, k)\n```
99,029
Three Divisors
three-divisors
Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false. An integer m is a divisor of n if there exists an integer k such that n = k * m.
Math
Easy
You can count the number of divisors and just check that they are 3 Beware of the case of n equal 1 as some solutions might fail in it
1,640
17
\n```\nclass Solution:\n def isThree(self, n: int) -> bool:\n return sum(n%i == 0 for i in range(1, n+1)) == 3\n```\n\nAdding `O(N^1/4)` solution \n```\nclass Solution:\n def isThree(self, n: int) -> bool:\n if n == 1: return False # edge case \n \n x = int(sqrt(n))\n if x*x != n: return False \n \n for i in range(2, int(sqrt(x))+1): \n if x % i == 0: return False \n return True\n```
99,108
Three Divisors
three-divisors
Given an integer n, return true if n has exactly three positive divisors. Otherwise, return false. An integer m is a divisor of n if there exists an integer k such that n = k * m.
Math
Easy
You can count the number of divisors and just check that they are 3 Beware of the case of n equal 1 as some solutions might fail in it
885
7
# Explained Python Solution using primes, O(1) | Faster than 99%\n\n**Runtime: 24 ms, faster than 99% of Python3 online submissions for Three Divisors.\nMemory Usage: 14.2 MB, less than 74% of Python3 online submissions for Three Divisors.**\n\n**Original Program**\n```\nimport math\nclass Solution:\n def isThree(self, n: int) -> bool:\n primes = {3:1, 5:1, 7:1, 11:1, 13:1, 17:1, 19:1, 23:1, 29:1, 31:1, 37:1, 41:1, 43:1, 47:1, 53:1, 59:1, 61:1, 67:1, 71:1, 73:1, 79:1, 83:1, 89:1, 97:1}\n if n == 4:\n return True\n else:\n a = math.sqrt(n)\n\n if primes.get(a,0):\n return True\n else:\n return False\n```\n\n## Explanation:\nEvery number `n` has **atleast** two divisors/factors, that are `1` and `n` (the number itself).\n\nA Prime number `n` is a number which has **eactly** two factors, `1` and `n` (the number itself).\n\nTherefore, a number `a` (`n*n`) which is a **square of a prime number** `n` will have three factors, `1` and `n` and `a` (`n*n`).\n\nThe above program uses this logic and checks if the square root of `n` (which is `a`) is in the dictionary or not.\n\n_______________________________________________\n\n**Updated Program for the same Approach**\nAs suggested by @NiklasPrograms in the comments.\n\n**Runtime: 42 ms, faster than 70.97% of Python3 online submissions for Three Divisors.\nMemory Usage: 13.8 MB, less than 55.18% of Python3 online submissions for Three Divisors.**\n\n```\nclass Solution:\n def isThree(self, n: int) -> bool:\n primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};\n \n return sqrt(n) in primes\n```
99,114
Maximum Number of Weeks for Which You Can Work
maximum-number-of-weeks-for-which-you-can-work
There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
Array,Greedy
Medium
Work on the project with the largest number of milestones as long as it is possible. Does the project with the largest number of milestones affect the number of weeks?
9,247
243
\n## Solution 1\nThanks [@pgthebigshot]() for providing another solution for easier understanding. \nI make some images to explain the idea.\n\n### Idea\nWe can separate projects to two sets.\n1. The project with the most milestones\n2. The rest of the projects.\n\nIf `sum(milestones except the max)) = sum(milestones) - max(milestones)` < `max(milestones)`, we can only finish `2 * (sum(milestones) - max(milestones)) + 1` milestones.\n![image]()\n\nElse, we can finish all milestones.\n![image]()\n\nThere is a edge case that if more than one project contains the same and the most milestones like [5, 5, 3], but we still be able to finish all of them.\n![image]()\n\n\n## Solution 2\n### Idea\nIf there are at least two projects with same number of milestones and there isn\'t a project with more milestones than that two, we can finish all milestones.\nIf not, we can only finish `2 * (sum(milestones) - max(milestones)) + 1` at most.\n\n### Example\nLet\'s say we have milestones like [5, 5, 3, 2].\nWe can take turn working on those projects with the most milestones.\nSo, [5, 5] will become [4, 4], then become [3, 3].\nBecause we have another project with 3 milestones, so we can take turn working on [3, 3, 3].\n[3, 3, 3] after three rounds, will become [2, 2, 2].\n[2, 2, 2, 2] -> [1, 1, 1, 1] -> [0, 0, 0, 0] -> all the milestones are finished\n\n### What to do if no two projects with same number of milestones?\nWe can seperate projects to two parts: (1)project with most milestones (2)the rest of projects\nThe `greedy strategy` here is trying to use the milestones from (2) to form a new project with the same number of milestones as (1)\nIf possible, we can finish all milestones as we demonstrate.\nIf impossible, we can only start to work on the max (1)- > work on others (2) -> work on the max (1) -> etc\n\n### Why the greedy strategy works?\nLet\'s consider the case if n >= 3. (because if n == 1 -> only can finish 1, if n == 2, we can only take turn working on it and `_sum - _max` must < `_max` )\nLet\'s say we have:\n1. A max project with the most milestones: `p milestones`\n2. A project with the second most milestones: `q milestones`\n3. Rest of projects with `r milestones` in total\n\nif `q + r >= p` ( note: `q + r` is the sum of milestones except the max project)\nWe can do `p-q` rounds, each round, we work on the max project first and the any one of the rest projects.\nAfter one round, the milestones will be `p-1`, `q`, `r-1` respectively.\nSo after `p-q` rounds, the milestones will be `p-(p-q) = q`, `q`, `r-(p-q)` respectively.\nBecause the assumption of `q + r >= p`, `r-(p-q) ` will be larger or equal to 0, it\'s valid operations. \nThen we have two projects with `q` milestones each and it means we can finish all the tasks (can refer to `Example` section)\n\n## Code\n\n```python\nclass Solution:\n def numberOfWeeks(self, milestones: List[int]) -> int:\n _sum, _max = sum(milestones), max(milestones)\n\t\t# (_sum - _max) is the sum of milestones from (2) the rest of projects, if True, we can form another project with the same amount of milestones as (1)\n\t\t# can refer to the section `Why the greedy strategy works?` for the proof\n if _sum - _max >= _max: \n return _sum\n return 2 * (_sum - _max) + 1 # start from the project with most milestones (_sum - _max + 1) and work on the the rest of milestones (_sum - _max)\n```\n\n## Complexity\n- Time complexity: O(n)\n- Space complexity: O(1)\n\n## Bonus\nI noticed many people are trying to use priority queue to solve this problem, but there are two possible failed reasons.\n\n1. Incorrect strategy\nIf you try to work on the top milestones and until one is all finished. Can consider the test case [100, 100, 100]. (Answer should be 300, but many will get 201 if using the wrong strategy)\n\n2. TLE\nIf you always pick the top two milestones and reduce 1 milestones from each and put them back. Due to 1 <= n <= 10^5, 1 <= milestones[i] <= 10^9. In the worse case, you will need O(10^5 * 10^9 * log(10^5)))\n\nNote: Please upvote if it\'s helpful or leave comments if I can do better. Thank you in advance.\n\n
99,125
Maximum Number of Weeks for Which You Can Work
maximum-number-of-weeks-for-which-you-can-work
There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
Array,Greedy
Medium
Work on the project with the largest number of milestones as long as it is possible. Does the project with the largest number of milestones affect the number of weeks?
3,989
50
I got a working solution using a max heap, then tried to optimized it to push through TLE. No luck. \n\nThis prolem seems to requrie prior knowledge or a very good intuition:\n\n> We can complete all milestones for all projects, unless one project has more milestones then all other projects combined.\n> \n> For the latter case: \n\t>> We can complete all milestones for other projects, \n\t>> plus same number of milestones for the largest project, \n\t>> plus one more milestone for the largest project.\n>\n> After that point, we will not be able to alternate projects anymore.\n\n**C++**\n```cpp\nlong long numberOfWeeks(vector<int>& m) {\n long long sum = accumulate(begin(m), end(m), 0ll), max = *max_element(begin(m), end(m));\n return min(sum, 2 * (sum - max) + 1);\n}\n```\n**Java**\n```java\npublic long numberOfWeeks(int[] m) {\n long sum = IntStream.of(m).asLongStream().sum(), max = IntStream.of(m).max().getAsInt();\n return Math.min(sum, 2 * (sum - max) + 1);\n}\n```\n**Python 3**\n```python\nclass Solution:\n def numberOfWeeks(self, m: List[int]) -> int:\n return min(sum(m), 2 * (sum(m) - max(m)) + 1)\n```
99,131
Maximum Number of Weeks for Which You Can Work
maximum-number-of-weeks-for-which-you-can-work
There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
Array,Greedy
Medium
Work on the project with the largest number of milestones as long as it is possible. Does the project with the largest number of milestones affect the number of weeks?
992
18
I thought this question was difficult, but when I looked at different cases through test cases given, I could do it in a minute. \n***BOOM!***\nIf sum of remaining numbers is greater than or equal to the maximum milestone then maximum milestone can be completed along with other milestones. Otherwise, maximum milestone cannot be reached as it will go till the sum of remaining milestones.\n\nComplexity\nTime complexity: O(n)\nSpace complexity: O(1)\n```\nclass Solution: \n\tdef numberOfWeeks(self, milestones: List[int]) -> int:\n mx = max(milestones)\n sm = sum(milestones) - mx\n if sm >= mx:\n return sm+mx\n else: \n return 2*sm+1\n```
99,137
Maximum Number of Weeks for Which You Can Work
maximum-number-of-weeks-for-which-you-can-work
There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
Array,Greedy
Medium
Work on the project with the largest number of milestones as long as it is possible. Does the project with the largest number of milestones affect the number of weeks?
651
9
Just sort the array in any order and sum up the elements upto the maximum element (not including it). If the sum is less than the maximum element then the answer is simple **2 x minimum(sum,maximum) + 1** as we can take one project in one week from maximum one and one from the sum in another week and at last we take the maximum element again. So its twice the given value + 1 (for last remaining value) since **sum<maximum**.\n\nFor all other cases where **sum>=maximum** we can achieve all projects milestone so answer will be **total sum of the milestone OR sum+maximum**.\n\n```\nclass Solution:\n def numberOfWeeks(self, l: List[int]) -> int:\n l.sort(reverse=True)\n s=sum(l)-l[0]\n if s<l[0]:\n return min(s,l[0])*2 + 1\n return s+l[0]\n```\n\nThis was my approach, feel free to share your approach.
99,139
Maximum Number of Weeks for Which You Can Work
maximum-number-of-weeks-for-which-you-can-work
There are n projects numbered from 0 to n - 1. You are given an integer array milestones where each milestones[i] denotes the number of milestones the ith project has. You can work on the projects following these two rules: Once all the milestones of all the projects are finished, or if the only milestones that you can work on will cause you to violate the above rules, you will stop working. Note that you may not be able to finish every project's milestones due to these constraints. Return the maximum number of weeks you would be able to work on the projects without violating the rules mentioned above.
Array,Greedy
Medium
Work on the project with the largest number of milestones as long as it is possible. Does the project with the largest number of milestones affect the number of weeks?
718
9
**Intuition:**\nAccording to the rule "cannot work on two milestones from the same project for two consecutive weeks.", we at least need to avoid the consecutive working on the project with the maximum milestones, which are most likely to be involved to violate the rule.\n\n----\n\n1. If the `max` of the `milestones` is no more than the the remaining sum by `1`, `sum(milestones) - max + 1`, we can always use the remaining parts to divide the project with max milestones, hence the answer is `sum(milestones)`; e.g., \n\n`milestones = [1,2,4]`, that is, projects `p0, p1, p2` have `1,2,` and `4` milestones repectively. \n\nWe can separate the `4` milestones using the remaining `1 + 2 = 3` ones: `p2, p0, p2, p1, p2, p1, p2`;\n\n2. Otherwise, get the `remaining part + 1` out of the `max`, together with the remaing part, is the solution: `2 * (sum(milestones) - max) + 1`. e.g., \n\n`milestones = [1,5,2]`, that is, projects `p0, p1, p2` have `1,5,` and `2` milestones repectively. \n\nWe can use the `1 + 2 = 3` milestones from `p0` and `p2` to separate only `3 + 1 = 4` milestones out of the `5` ones from `p1`: `p1, p0, p1, p2, p1, p2, p1`.\n\n```java\n public long numberOfWeeks(int[] milestones) {\n int max = IntStream.of(milestones).max().getAsInt();\n long sum = IntStream.of(milestones).mapToLong(i -> i).sum(), rest = sum - max;\n return max <= rest + 1 ? sum : 2 * rest + 1;\n }\n```\n```python\n def numberOfWeeks(self, milestones: List[int]) -> int:\n mx, sm = max(milestones), sum(milestones)\n return sm if 2 * mx <= sm + 1 else 2 * (sm - mx) + 1\n```
99,140
Minimum Time to Type Word Using Special Typewriter
minimum-time-to-type-word-using-special-typewriter
There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'. Each second, you may perform one of the following operations: Given a string word, return the minimum number of seconds to type out the characters in word.
String,Greedy
Easy
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
3,888
61
\n```\nclass Solution:\n def minTimeToType(self, word: str) -> int:\n ans = len(word)\n prev = "a"\n for ch in word: \n val = (ord(ch) - ord(prev)) % 26 \n ans += min(val, 26 - val)\n prev = ch\n return ans \n```
99,332
Minimum Time to Type Word Using Special Typewriter
minimum-time-to-type-word-using-special-typewriter
There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'. Each second, you may perform one of the following operations: Given a string word, return the minimum number of seconds to type out the characters in word.
String,Greedy
Easy
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
3,456
47
1. Initialize the `prev` as `a`;\n2. Traverse the `word`, for each character, compute the distances from current character, `cur`, to previous one, `prev`, clockwise and counter-clockwise, respectively; Choose the minimum between them; \n3. Count in `1` second for each typing character; therefore we can initialize `cnt` to `word.length()`.\n\n```java\n public int minTimeToType(String word) {\n int cnt = word.length();\n char prev = \'a\';\n for (int i = 0; i < word.length(); ++i) {\n char cur = word.charAt(i);\n int diff = Math.abs(cur - prev);\n cnt += Math.min(diff, 26 - diff);\n prev = cur;\n }\n return cnt;\n }\n```\n```python\n def minTimeToType(self, word: str) -> int:\n cnt, prev = len(word), \'a\'\n for cur in word:\n diff = abs(ord(cur) - ord(prev)) \n cnt += min(diff, 26 - diff)\n prev = cur\n return cnt\n```\n\n**Analysis:**\n\nTime: `O(n)`, space: `O(1)`, where `n = word.length()`.
99,334
Minimum Time to Type Word Using Special Typewriter
minimum-time-to-type-word-using-special-typewriter
There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'. Each second, you may perform one of the following operations: Given a string word, return the minimum number of seconds to type out the characters in word.
String,Greedy
Easy
There are only two possible directions you can go when you move to the next letter. When moving to the next letter, you will always go in the direction that takes the least amount of time.
890
20
\n```\npre = "a"\nsum1 = 0\nfor i in word:\n\tL = abs((ord(i)-ord(pre)))\n\tsum1 += min(L,26-L)\n\tpre = i\nreturn (sum1+len(word))\n```\n\n\nhope it is usefull, UPVOTE will make my day :) \nthank you in advance
99,341