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
Maximum Matrix Sum
maximum-matrix-sum
You are given an n x n integer matrix. You can do the following operation any number of times: Two elements are considered adjacent if and only if they share a border. Your goal is to maximize the summation of the matrix's elements. Return the maximum sum of the matrix's elements using the operation mentioned above.
Array,Greedy,Matrix
Medium
Try to use the operation so that each row has only one negative number. If you have only one negative element you cannot convert it to positive.
1,026
15
\n```\nclass Solution:\n def maxMatrixSum(self, matrix: List[List[int]]) -> int:\n ans = mult = 0\n val = inf \n for i in range(len(matrix)): \n for j in range(len(matrix)):\n ans += abs(matrix[i][j])\n val = min(val, abs(matrix[i][j]))\n if matrix[i][j] < 0: mult ^= 1\n return ans - 2*mult*val\n```
99,386
Number of Ways to Arrive at Destination
number-of-ways-to-arrive-at-destination
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.
Dynamic Programming,Graph,Topological Sort,Shortest Path
Medium
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
869
11
## Logic\n- Dijkstra algorithm can only get the shortest time from src to dst.\n- What we want to get is **the number of ways with minimum time from src to dst.**\n- We need\n\t1) **times** array : to check the minimum time to take from src to times[i].\n\t2) **ways** array : to check the total ways from src to ways[i] within minimum time.\n\n- if find same time path... update **ways** only \n ... because we don\'t need to update time \n ... and we don\'t need to go to that node(already in our heap)\n\n\n## EX1\n**times** [INF, INF, INF, INF, INF, INF] => [0, 2, 5, 5, 6, 7]\n**ways** [0, 0, 0, 0, 0, 0] => [1, 1, 1, 1, 1, 2, 4]\n\n\n## Reference\nIdea and code from ... #happycoding\n\n\n\n\n```\nclass Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n\n #1. graph\n graph = collections.defaultdict(list)\n for u, v, t in roads:\n graph[u].append((v, t))\n graph[v].append((u, t))\n \n #2. times, ways array initializer\n times = [float(\'inf\')] * n\n ways = [0] * n\n \n times[0] = 0\n ways[0] = 1\n \n #3. dijkstra\n pq = [(0, 0)] # time, node\n \n while pq:\n old_t, u = heapq.heappop(pq) # current time, current node\n \n for v, t in graph[u]:\n new_t = old_t + t\n \n # casual logic: update shorter path\n if new_t < times[v]:\n times[v] = new_t\n ways[v] = ways[u]\n heapq.heappush(pq, (new_t, v))\n \n # if find same time path... update ways only\n elif new_t == times[v]:\n ways[v] += ways[u]\n \n modulo = 10 ** 9 + 7\n \n return ways[n-1] % modulo\n```\n\n**Please upvote if it helped! :)**
99,462
Number of Ways to Arrive at Destination
number-of-ways-to-arrive-at-destination
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.
Dynamic Programming,Graph,Topological Sort,Shortest Path
Medium
First use any shortest path algorithm to get edges where dist[u] + weight = dist[v], here dist[x] is the shortest distance between node 0 and x Using those edges only the graph turns into a dag now we just need to know the number of ways to get from node 0 to node n - 1 on a dag using dp
1,529
10
```\nfrom heapq import *\nclass Solution:\n def countPaths(self, n: int, roads: List[List[int]]) -> int:\n # create adjacency list\n adj_list = defaultdict(list)\n for i,j,k in roads:\n adj_list[i].append((j,k))\n adj_list[j].append((i,k))\n \n start = 0\n end = n-1\n \n # set minimum distance of all nodes but start to infinity.\n # min_dist[i] = [minimum time from start, number of ways to get to node i in min time]\n min_dist = {i:[float(\'inf\'),0] for i in adj_list.keys()}\n min_dist[start] = [0,1]\n \n # Heap nodes in the format (elapsed time to get to that node, node index)\n # This is done so as to allow the heap to pop node with lowest time first\n # Push first node to heap.\n heap = [(0, start)]\n while heap:\n elapsed_time, node = heappop(heap)\n # if nodes getting popped have a higher elapsed time than minimum time required\n # to reach end node, means we have exhausted all possibilities\n # Note: we can do this only because time elapsed cannot be negetive\n if elapsed_time > min_dist[end][0]:\n break\n for neighbor, time in adj_list[node]:\n # check most expected condition first. Reduce check time for if statement\n if (elapsed_time + time) > min_dist[neighbor][0]:\n continue\n # if time is equal to minimum time to node, add the ways to get to node to\n # the next node in minimum time\n elif (elapsed_time + time) == min_dist[neighbor][0]:\n min_dist[neighbor][1] += min_dist[node][1]\n else: # node has not been visited before. Set minimum time \n min_dist[neighbor][0] = elapsed_time + time\n min_dist[neighbor][1] = min_dist[node][1]\n heappush(heap, (elapsed_time+time,neighbor))\n\n return min_dist[end][1]%(pow(10,9)+7)\n \n
99,469
Number of Ways to Separate Numbers
number-of-ways-to-separate-numbers
You wrote down many positive integers in a string called num. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you could have written down to get the string num. Since the answer may be large, return it modulo 109 + 7.
String,Dynamic Programming,Suffix Array
Hard
If we know the current number has d digits, how many digits can the previous number have? Is there a quick way of calculating the number of possibilities for the previous number if we know that it must have less than or equal to d digits? Try to do some pre-processing.
851
5
\n```\nclass Solution:\n def numberOfCombinations(self, num: str) -> int:\n n = len(num)\n lcs = [[0]*(n+1) for _ in range(n)]\n for i in reversed(range(n)): \n for j in reversed(range(i+1, n)): \n if num[i] == num[j]: lcs[i][j] = 1 + lcs[i+1][j+1]\n \n def cmp(i, j, d): \n """Return True if """\n m = lcs[i][j]\n if m >= d: return True \n return num[i+m] <= num[j+m]\n \n dp = [[0]*(n+1) for _ in range(n)]\n for i in range(n): \n if num[i] != "0": \n for j in range(i+1, n+1): \n if i == 0: dp[i][j] = 1\n else: \n dp[i][j] = dp[i][j-1]\n if 2*i-j >= 0 and cmp(2*i-j, i, j-i): dp[i][j] += dp[2*i-j][i]\n if 2*i-j+1 >= 0 and not cmp(2*i-j+1, i, j-i-1): dp[i][j] += dp[2*i-j+1][i]\n return sum(dp[i][n] for i in range(n)) % 1_000_000_007\n```
99,495
Check If String Is a Prefix of Array
check-if-string-is-a-prefix-of-array
Given a string s and an array of strings words, determine whether s is a prefix string of words. A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length. Return true if s is a prefix string of words, or false otherwise.
Array,String
Easy
There are only words.length prefix strings. Create all of them and see if s is one of them.
2,298
24
\n```\nclass Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n i = 0\n for word in words: \n if s[i:i+len(word)] != word: return False \n i += len(word)\n if i == len(s): return True \n return False \n```\n\nThe solutions for weekly 255 can be found in this [commit]().
99,535
Check If String Is a Prefix of Array
check-if-string-is-a-prefix-of-array
Given a string s and an array of strings words, determine whether s is a prefix string of words. A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length. Return true if s is a prefix string of words, or false otherwise.
Array,String
Easy
There are only words.length prefix strings. Create all of them and see if s is one of them.
579
5
**Solution**:\n```\nclass Solution:\n def isPrefixString(self, s, words):\n return s in accumulate(words)\n```
99,549
Check If String Is a Prefix of Array
check-if-string-is-a-prefix-of-array
Given a string s and an array of strings words, determine whether s is a prefix string of words. A string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k no larger than words.length. Return true if s is a prefix string of words, or false otherwise.
Array,String
Easy
There are only words.length prefix strings. Create all of them and see if s is one of them.
1,086
11
```\nclass Solution:\n def isPrefixString(self, s: str, words: List[str]) -> bool:\n \n a = \'\'\n \n for i in words:\n \n a += i\n \n if a == s:\n return True\n if not s.startswith(a):\n break\n \n return False \n```
99,551
Minimum Number of Swaps to Make the String Balanced
minimum-number-of-swaps-to-make-the-string-balanced
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced.
Two Pointers,String,Stack,Greedy
Medium
Iterate over the string and keep track of the number of opening and closing brackets on each step. If the number of closing brackets is ever larger, you need to make a swap. Swap it with the opening bracket closest to the end of s.
249
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: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n cnt = 0\n stack = []\n for p in s:\n if p == "[": stack.append("[")\n else:\n if not stack: \n stack.append("]")\n cnt += 1\n else: \n stack.pop()\n return cnt\n```
99,632
Minimum Number of Swaps to Make the String Balanced
minimum-number-of-swaps-to-make-the-string-balanced
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced.
Two Pointers,String,Stack,Greedy
Medium
Iterate over the string and keep track of the number of opening and closing brackets on each step. If the number of closing brackets is ever larger, you need to make a swap. Swap it with the opening bracket closest to the end of s.
4,761
47
Traverse the input `s`, remove all matched `[]`\'s. Since the number of `[`\'s and `]`\'s are same, the remaining must be `]]]...[[[`. Otherwise, **if left half had any `[`, there would be at least a matched `[]` among them.**\n\n1. For every `2` pairs of square brackets, a swap will make them matched;\n2. If only `1` pair not matched, we need a swap.\nTherefore, we need at least `(pairs + 1) / 2` swaps.\n\n----\n**Method 1: Stack**\nOnly store open square brackets.\n```java\n public int minSwaps(String s) {\n Deque<Character> stk = new ArrayDeque<>();\n for (char c : s.toCharArray()) {\n if (!stk.isEmpty() && c == \']\') {\n stk.pop();\n }else if (c == \'[\') {\n stk.push(c);\n }\n }\n return (stk.size() + 1) / 2;\n }\n```\n```python\n def minSwaps(self, s: str) -> int:\n stk = []\n for c in s:\n if stk and c == \']\':\n stk.pop()\n elif c == \'[\':\n stk.append(c)\n return (len(stk) + 1) // 2\n```\n**Analysis:**\nTime & space: `O(n)`, where `n = s.length()`.\n\n----\n\nThere are only `2` types of characters in `s`, so we can get rid of stack in above codes and use two counters, `openBracket` and `closeBracket`, to memorize the unmatched open and close square brackets: - Credit to **@saksham66** for suggestion of variables naming.\n```java\n public int minSwaps(String s) {\n int openBracket = 0;\n for (int i = 0, closeBracket = 0; i < s.length(); ++i) {\n char c = s.charAt(i);\n if (openBracket > 0 && c == \']\') {\n --openBracket;\n }else if (c == \'[\') {\n ++openBracket;\n }else {\n ++closeBracket;\n }\n }\n return (openBracket + 1) / 2;\n }\n```\n```python\n def minSwaps(self, s: str) -> int:\n open_bracket = close_bracket = 0\n for c in s:\n if open_bracket > 0 and c == \']\':\n open_bracket -= 1\n elif c == \'[\':\n open_bracket += 1\n else:\n close_bracket += 1 \n return (open_bracket + 1) // 2\n```\nSince the occurrences of `[`\'s and `]`\'s are same, we actually only need to count `openBracket`, and `closeBracket` is redundant. Credit to **@fishballLin**\n\n```java\n public int minSwaps(String s) {\n int openBracket = 0;\n for (int i = 0; i < s.length(); ++i) {\n char c = s.charAt(i);\n if (openBracket > 0 && c == \']\') {\n --openBracket;\n }else if (c == \'[\') {\n ++openBracket;\n }\n }\n return (openBracket + 1) / 2;\n }\n```\n\n```python\n def minSwaps(self, s: str) -> int:\n open_bracket = 0\n for c in s:\n if open_bracket > 0 and c == \']\':\n open_bracket -= 1\n elif c == \'[\':\n open_bracket += 1\n return (open_bracket + 1) // 2\n```\n\n**Analysis:**\nTime: `O(n)`, space: `O(1)`, where `n = s.length()`.\n
99,636
Minimum Number of Swaps to Make the String Balanced
minimum-number-of-swaps-to-make-the-string-balanced
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced.
Two Pointers,String,Stack,Greedy
Medium
Iterate over the string and keep track of the number of opening and closing brackets on each step. If the number of closing brackets is ever larger, you need to make a swap. Swap it with the opening bracket closest to the end of s.
3,103
23
We go left to right (`i`), and track open and closed brackets in `bal`. When `bal` goes negative, we have an orphan `]`. \n\nTo balance it out, we need to find an orphaned `[` and swap those two. So, we go right-to-left (`j`), and we can search for the orphaned `[`. \n\nWhy is this strategy optimal? Because we have to fix all orphaned `]` and `[` brackets. The optimal strategy is to fix two brackets with one swap.\n\n#### Alternative Solution\nSee the original solution for additional details. To find the number of swaps, we can just count all orphaned `]` (or `[`) in `cnt`. The answer is `(cnt + 1) / 2` to fix the string, since one swap matches 4 brackest (or two in the last swap - if `cnt` is odd.\n\nThis solution was inspired by our conversation with [digvijay91]() (see comments for additional details).\n\n**C++**\n```cpp\nint minSwaps(string s) {\n int bal = 0, cnt = 0;\n for (auto ch : s)\n if (bal == 0 && ch == \']\')\n ++cnt;\n else\n bal += ch == \'[\' ? 1 : -1;\n return (cnt + 1) / 2;\n}\n```\n\n#### Original Solution\n**C++**\n```cpp\nint minSwaps(string s) {\n int res = 0, bal = 0;\n for (int i = 0, j = s.size() - 1; i < j; ++i) {\n bal += s[i] == \'[\' ? 1 : -1;\n if (bal < 0) {\n for (int bal1 = 0; bal1 >= 0; --j)\n bal1 += s[j] == \']\' ? 1 : -1;\n swap(s[i], s[j + 1]);\n ++res;\n bal = 1;\n }\n }\n return res;\n}\n```\n**Python 3**\n```python\nclass Solution:\n def minSwaps(self, s: str) -> int:\n res, bal = 0, 0\n for ch in s:\n bal += 1 if ch == \'[\' else -1\n if bal == -1:\n res += 1\n bal = 1\n return res\n```
99,640
Minimum Number of Swaps to Make the String Balanced
minimum-number-of-swaps-to-make-the-string-balanced
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'. A string is called balanced if and only if: You may swap the brackets at any two indices any number of times. Return the minimum number of swaps to make s balanced.
Two Pointers,String,Stack,Greedy
Medium
Iterate over the string and keep track of the number of opening and closing brackets on each step. If the number of closing brackets is ever larger, you need to make a swap. Swap it with the opening bracket closest to the end of s.
1,167
18
## Hi guys, I hope my post can help you in understanding this problem. ##\n\n### First, we need to understand what is the "**balanced**" scenario. There are 3 types of balanced scenario as shown below: ###\n<img src = "" width = "700" height = "250"> \n\n### This is the "**worst**" scenario where everything is not in order: ###\n<img src = "" width = "600" height = "200">\n\n### This is the half-good half bad scenario. Some brackets are balanced, some are not. The highlighted brackets are balanced. ###\n<img src = "" width = "700" height = "300">\n\n### Note that the following is a **NON**-efficient way in swapping. We are swapping more than needed. We are swapping 4 times in this case. ### \n<img src = "" width = "700" height = "300"> )\n\n### The most efficient way to swap the brackets to become balanced is by using the following trick. We only swap 2 times in this case. Swap brackets 3 and 6 followed with 1 and 8. Note that this is for even numbers of pairs of unbalanced brackets. In this case, we have 4 pairs of unbalanced brackets which is an even numbers of pairs of unbalanced brackets. ###\n<img src = "" width = "700" height = "250" >\n\n### Question: What if we have an odd number of pairs of unbalanced brackets? How many times do we need to switch? Is it the same as even number of unbalanced brackets? In the image below, we have 3 pairs of unbalanced brackets which is an odd pair. ###\n<img src = "" width = "700" height = "100">\n\n<img src = "" width = "700" height = "250">\n\n### We can have other methods to switch the brackets to make it balanced. To find the minimum number of swaps to make the string balanced, we have to use the most effective swapping technique which is shown in the image below. In this case we need to switch 2 times. You can try out other possible methods to check it yourself.\n<img src = "" width = "700" height = "250">\n\n### Notice!!! We can ignore balanced brackets in the middle of the given string if there is any! For example, take a look at the image below. ###\n\n<img src="" width = "700" height = "300">\n\n\n### After cancelling the highlighted part, we are left with the simple case of either odd pairs of unbalanced brackets or an even case of unbalanced brackets. ###\n\n### In conclusion, for both even number or odd number of unbalanced brackets, the minimum swaps needed is (n + 1) // 2 since that is the most efficient way to perform the minimum number of swaps. The (n + 1) is used to account for the odd case. For example, in the previous example, we have 3 odd pairs of brackets so minimum number of swaps needed = (3 + 1) // 2 = 2. \n\n\n### \n### Question: How do we know whether a string is balanced or not? We can use a counter to keep track of the number of opening " [ " and number \n### of " ] " bracket. Whenever we encounter " [ " we will add one to our counter and we will only decrement the counter if and only if the counter is positive and the current bracket is a closing one (" ] " ). \n\n### ...\n### ...\n### ...\n\n### Why? Let\'s take a look at the image below!\n<img src = "" width = "700" height = "150">\n\n### For this normal case, the result will be zero after we reached the end of the string. The steps would be +1 + 1 -1 + 1 - 1 - 1 = 0\n\n### Special case !!! ###\n<img src = "" width = "700" height = "150">\n\n### The image above will result in a count of 0 ( -1 + 1 -1 + 1). Does it mean it is balanced? No, it is not. To tackle this special case, we will increase the counter value by one if and only if it is an opening bracket (" [ " ) and decrease the counter value by one if and only if it is a closing bracket (" ] " ) and the counter is positive. Reason? This is because we are finding the number of unbalanced pairs of brackets. Whenever we encounter an opening bracket, there must be a closing bracket waiting after the opening bracket to make it balanced. So for the case like the one in the image here: \n\n<img src = "" width = "700" height = "150">\n\n### We will skip through the first bracket and do nothing to our counter even if it is a closing one and move to the next bracket. The reason we are allowed to skip this bracket is although we know that it is an unbalanced bracket is because we always know that there is an extra opening bracket waiting for this closing bracket somewhere in the future that makes this pair an unbalanced one. We can increment the counter when we find this leftover opening bracket later in the string afterwards. ###\n\n# Detailed walkthrough of the changes in counter value: \n### Step 1: \n### We will not decrement our counter since counter is initially zero. Move to the next bracket.\n### Step 2:\n### It is an opening bracket so add one to our counter. This is because this signifies a possibility of an (one) unbalanced bracket. Now, counter = 1. Move to the next bracket.\n### Step 3:\n### It is a closing bracket and since counter is greater than zero, we can decrease our counter value. We found a matching pair so it is logical and reasonable to decrement our value by one to indicate that the possibility of an (one) unbalanced bracket has decrease by one. Move to the next bracket.\n### Step 4:\n### It is an opening bracket so increase counter value by one. Now here, counter = 1 and the loops stop. ### That means We found one pair of unbalanced bracket and well where does this come from? This is a result of the mismatched( unbalanced bracket we encounter at start remember???) Hence, that is the reason why we do not need to decrease the counter at step one. The fact is we will always find a pair of opening bracket and opening bracket. If the counter is not positive and we encounter a closing bracket, we will skip it and not decrement the counter and move on and we know that we will find its counter (opening bracket in the future) and we can add one to the counter later on in the future.\n\n\n```\nclass Solution:\n def minSwaps(self, s: str) -> int:\n count = 0\n for i in s:\n if i == "[":\n count += 1 # increment only if we encounter an open bracket. \n else:\n if count > 0: #decrement only if count is positive. Else do nothing and move on. This is because for the case " ] [ [ ] " we do not need to in\n count -= 1\n return (count + 1) // 2\n \n```\n\n\n\n\n\n\n\n\n
99,645
Find the Longest Valid Obstacle Course at Each Position
find-the-longest-valid-obstacle-course-at-each-position
You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle. For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that: Return an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.
Array,Binary Search,Binary Indexed Tree
Hard
Can you keep track of the minimum height for each obstacle course length? You can use binary search to find the longest previous obstacle course length that satisfies the conditions.
2,905
9
Simple Upper Bound and Binary Search\n\n```\nclass Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n stack,ans=[],[]\n \n for i in obstacles:\n br=bisect_right(stack,i)\n if br==len(stack):\n stack.append(i)\n else:\n stack[br]=i\n ans.append(br+1)\n \n return ans
99,674
Find the Longest Valid Obstacle Course at Each Position
find-the-longest-valid-obstacle-course-at-each-position
You want to build some obstacle courses. You are given a 0-indexed integer array obstacles of length n, where obstacles[i] describes the height of the ith obstacle. For every index i between 0 and n - 1 (inclusive), find the length of the longest obstacle course in obstacles such that: Return an array ans of length n, where ans[i] is the length of the longest obstacle course for index i as described above.
Array,Binary Search,Binary Indexed Tree
Hard
Can you keep track of the minimum height for each obstacle course length? You can use binary search to find the longest previous obstacle course length that satisfies the conditions.
4,414
27
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEvery time a number is traversed, if:\n- If the current number is greater than or equal to the number on the top of the stack, it will be directly pushed onto the stack\n- If the current number is less than the number on the top of the stack, use binary search to find the first number in the stack that is greater than the current number and replace it\n\nThen how to consider must choose the i-th obstacle:\nOnly need to check at the end of each loop, what is the number to be replaced (or added), and then the final result will come out\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Example\nComsider the example `[1,2,3,1,2,3]`\n- Initially `stack` is `[0, 0, 0, 0, 0, 0]` and `res` is `[0, 0, 0, 0, 0, 0]`\n- When `i = 0`, `obstacles[i] = 1`\n - `top == -1` and we go to `if` branch\n - `stack[0] = 1`, `res[0] = 1`\n- When `i = 1`, `obstacles[i] = 2`\n - `top=0` and stack is `[1, 0, 0, 0, 0, 0]`\n - `obstacles[i] >= stack[top]` and we go to `if` branch\n - `stack[1] = 2`, `res[1] = 2`\n- When `i = 2`, `obstacles[i] = 3`\n - ...\n- When `i = 3`, `obstacles[i] = 1` notice!\n - Now stack is `[1, 2, 3, 0, 0, 0]`\n - We go to `else` branch\n - We need use binary search to find the first number that larger than `obstacles[i]` from 0 to top=2 in the stack\n - `r = 1`, `stack[r] = obstacles[i]`, `res[3] = r+1`\n- When `i = 4`, `obstacles[i] = 2`\n - `top=2`, and stack is `[1, 1, 3, 0, 0, 0]`\n - `obstacles[i] < stack[top]` and we go to `else` branch\n - Find first number larger than `obstacles[i]` from 0 to top=2\n - `r = 2`, `stack[r] = obstacles[i]`, `res[4] = r+1`\n- Now `stack` is `[1, 1, 2, 0, 0, 0]` and `res` is `[1, 2, 3, 2, 3, 0]`\n- When `i = 5`, `obstacles[i] = 3`\n - `obstacles[i] >= stack[top]` and we go to `if` branch\n - `top++=3`, `stack[top] = 3`, `res[5] = top+1`\n- Finally, \n - Stack is `[1, 1, 2, 3, 0, 0]`\n - res is `[1, 2, 3, 2, 3, 4]`\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(nlogn)$$\n\n# Code\n``` java []\nclass Solution {\n public int[] longestObstacleCourseAtEachPosition(int[] obstacles) {\n int[] stack = new int[obstacles.length];\n int top = -1;\n int[] res = new int[obstacles.length];\n for (int i = 0; i < obstacles.length; i++) {\n if (top == -1 || obstacles[i] >= stack[top]) {\n stack[++top] = obstacles[i];\n res[i] = top + 1;\n } else {\n int l = 0, r = top, m;\n while (l < r) {\n m = l + (r - l) / 2;\n if (stack[m] <= obstacles[i]) {\n l = m + 1;\n } else {\n r = m;\n }\n }\n stack[r] = obstacles[i];\n res[i] = r + 1;\n }\n }\n return res;\n }\n}\n```\n``` python []\nclass Solution:\n def longestObstacleCourseAtEachPosition(self, obstacles: List[int]) -> List[int]:\n lst,ans=[],[]\n for i in obstacles:\n b=bisect_right(lst,i)\n if b==len(lst):\n lst.append(i)\n else:\n lst[b]=i\n ans.append(b+1)\n return ans\n```\n``` C++ []\nclass Solution \n{\npublic:\n vector<int> longestObstacleCourseAtEachPosition(vector<int>& obstacles) \n {\n vector<int> a;\n vector<int> res;\n for (auto x : obstacles)\n {\n int idx = upper_bound(a.begin(), a.end(), x) - a.begin();\n if (idx == a.size())\n a.push_back(x);\n else\n a[idx] = x;\n res.push_back(idx + 1);\n }\n\n return res;\n }\n};\n```\n\n**Please upvate if helpful!!**\n\n![image.png]()
99,713
Number of Strings That Appear as Substrings in Word
number-of-strings-that-appear-as-substrings-in-word
Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word. A substring is a contiguous sequence of characters within a string.
String
Easy
Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word.
2,207
23
\n```\nclass Solution:\n def numOfStrings(self, patterns: List[str], word: str) -> int:\n return sum(x in word for x in patterns)\n```\n\nYou can find the solutions to weekly 254 in this [repo]().
99,739
Number of Strings That Appear as Substrings in Word
number-of-strings-that-appear-as-substrings-in-word
Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word. A substring is a contiguous sequence of characters within a string.
String
Easy
Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word.
1,674
16
**C++ :**\n\n```\nint numOfStrings(vector<string>& patterns, string word) {\n int counter = 0;\n \n for(auto p: patterns)\n if(word.find(p) != std::string::npos)\n ++counter;\n \n return counter;\n }\n```\n\n**Python :**\n\n```\ndef numOfStrings(self, patterns: List[str], word: str) -> int:\n\treturn len([p for p in patterns if p in word])\n```\n\n**Like it ? please upvote !**
99,750
Number of Strings That Appear as Substrings in Word
number-of-strings-that-appear-as-substrings-in-word
Given an array of strings patterns and a string word, return the number of strings in patterns that exist as a substring in word. A substring is a contiguous sequence of characters within a string.
String
Easy
Deal with each of the patterns individually. Use the built-in function in the language you are using to find if the pattern exists as a substring in word.
428
5
```\ndef numOfStrings(self, patterns: List[str], word: str) -> int:\n return sum(i in word for i in patterns)\n```
99,760
Minimum Non-Zero Product of the Array Elements
minimum-non-zero-product-of-the-array-elements
You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times: For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001. Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7. Note: The answer should be the minimum product before the modulo operation is done.
Math,Greedy,Recursion
Medium
Try to minimize each element by swapping bits with any of the elements after it. If you swap out all the 1s in some element, this will lead to a product of zero.
894
6
To calculate the minimum non-zero product we always have to change the value such as it will provide the minimum multiplication value -\n\ni.e \nn = 3\n1 - 001\n2 - 010\n3 - 011\n4 - 100\n5 - 101\n6 - 110\n7 - 111\n\nHere we convert all the value **i** to **1** and **pow(2, n)-i-1** to **pow(2, n)-2** *(where i<pow(2, n-1))*\n\nBasically we convert the first half of the occurances to 1 which in return provide us minimum multiplication value.\n\nThe above explanation will lead us to the following deduction as -\n1 - 001\n2 - 001 (swapped with 5)\n3 - 001 (swapped with 4)\n4 - 110\n5 - 110\n6 - 110\n7 - 111\n\n\n...................................................................................................................................................................................................................................\n**Mathematical proof :**\n\nSuppose n = 3, it will have 2^3-1 = 7 non-zero occurances.\nNow we have \n2+5 = 7\n\nlet x = 2, y = 5, z = 7\n\nso, x+y = z -----------------------**{1}**\nx * y>x+y (if x>1 and y>1)\nx * y>x+y\nx * y > z --------------**(using {1})**\n**x * y > (z-1) * (1)**\nHence we can use this to formulate the minimum multiplication value.\n\nWe can do transition between the elements so that **upper half** become **1** and **lower half** become **2^n-2**. Also **last element can\'t be transformed as we are neglecting the zero valued element so we multiply it as it is**.\n\n\n\n\n--------------------------------------------------------------------------------------------------------------------------------\n\n\nAnother way to understand it as we push one element to attain minimum possible value (which is 1 here) and their counter part will increase accordingly.\n\nNow for 3, pairing it as (1, 6) (2, 5) (3, 4) (7).\nwe decrease the minimum value (suppose k) to 1 and increase the other value (suppose m) to m+k-1\n\nSo now the pairs are (1, 6) (1, 6) (1, 6) (7) which will give us minimum multiplication value.\n\n\nNow take n = 4, \nwe have pairs as (1, 14) (2, 13) (3, 12) (4, 11) (5, 10) (6, 9) (7, 8) (15) \nwhich we can reform as (1, 14) (1, 14) (1, 14) (1, 14) (1, 14) (1, 14) (1, 14) (15)\n\n\nHope you understand the approach. Queries are welcomed.\n\n**The code goes as -**\n\n\n```\ndef minNonZeroProduct(self, p: int) -> int:\n return (pow(2**p-2, (2**p-2)//2, 1000000007)*(2**p-1))%1000000007
99,785
Minimum Non-Zero Product of the Array Elements
minimum-non-zero-product-of-the-array-elements
You are given a positive integer p. Consider an array nums (1-indexed) that consists of the integers in the inclusive range [1, 2p - 1] in their binary representations. You are allowed to do the following operation any number of times: For example, if x = 1101 and y = 0011, after swapping the 2nd bit from the right, we have x = 1111 and y = 0001. Find the minimum non-zero product of nums after performing the above operation any number of times. Return this product modulo 109 + 7. Note: The answer should be the minimum product before the modulo operation is done.
Math,Greedy,Recursion
Medium
Try to minimize each element by swapping bits with any of the elements after it. If you swap out all the 1s in some element, this will lead to a product of zero.
854
6
\n```\nclass Solution:\n def minNonZeroProduct(self, p: int) -> int:\n x = (1 << p) - 1\n return pow(x-1, (x-1)//2, 1_000_000_007) * x % 1_000_000_007\n```\n\nYou can find the solutions to weekly 256 in this [repo]().
99,787
Last Day Where You Can Still Cross
last-day-where-you-can-still-cross
There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Matrix
Hard
What graph algorithm allows us to find whether a path exists? Can we use binary search to help us solve the problem?
2,110
8
Why DFS?\nDFS tries to reach the last row first and then try with other options unlike BFS reaching its neighbors first. \n\nThe idea is given a water configurations i.e matrix with cells 0 and 1, can we travel from row 0 to last row. If Yes then on that day we are able to travel and our answer will be atleast this day or days further.\n\nBinary Search: Say there are 8 days and we find out we are not able to travel on day 5. Can we safely eliminate day 6, 7,8. Yes. Similarly if we can travel on day 4, why check day 1,2,or 3.\n\n<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```\nclass Solution {\n int row = 0;\n int col = 0;\n int [][]cells;\n public int[][] directions = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n public int latestDayToCross(int row, int col, int[][] cells) {\n this.cells = cells;\n this.row = row;\n this.col = col;\n \n int left = 1, right = cells.length;\n int mid;\n while(left<right){\n mid = right - (right - left) / 2;\n if(canCross(mid)){\n left = mid;\n }else{\n right = mid-1;\n }\n }\n return left;\n }\n \n public boolean canCross(int day){\n int [][] grid = new int[row][col];\n for(int i = 0;i<day;i++){\n grid[cells[i][0] - 1][cells[i][1] - 1] = 1;\n }\n \n for(int i = 0;i<col;i++){\n if(grid[0][i]==0 && dfs(grid,0,i)){\n return true;\n }\n }\n return false;\n }\n \n public boolean dfs(int [][] grid, int r, int c){\n if(r<0 || r>=row || c<0 || c>=col || grid[r][c]!=0) return false;\n \n if(r == row-1) return true;\n grid[r][c] = -1;\n for(int [] direction: directions){\n int i = r + direction[0];\n int j = c + direction[1];\n if(dfs(grid,i,j)) return true;\n }\n return false;\n }\n}\n```\n\n```\n#include <vector>\n\nclass Solution {\n int row;\n int col;\n std::vector<std::vector<int>> cells;\n std::vector<std::vector<int>> directions;\n \npublic:\n Solution() {\n directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n }\n \n int latestDayToCross(int row, int col, std::vector<std::vector<int>>& cells) {\n this->row = row;\n this->col = col;\n this->cells = cells;\n \n int left = 1, right = cells.size();\n int mid;\n while (left < right) {\n mid = right - (right - left) / 2;\n if (canCross(mid)) {\n left = mid;\n } else {\n right = mid - 1;\n }\n }\n return left;\n }\n \n bool canCross(int day) {\n std::vector<std::vector<int>> grid(row, std::vector<int>(col, 0));\n for (int i = 0; i < day; i++) {\n grid[cells[i][0] - 1][cells[i][1] - 1] = 1;\n }\n \n for (int i = 0; i < col; i++) {\n if (grid[0][i] == 0 && dfs(grid, 0, i)) {\n return true;\n }\n }\n return false;\n }\n \n bool dfs(std::vector<std::vector<int>>& grid, int r, int c) {\n if (r < 0 || r >= row || c < 0 || c >= col || grid[r][c] != 0) {\n return false;\n }\n \n if (r == row - 1) {\n return true;\n }\n grid[r][c] = -1;\n for (const auto& direction : directions) {\n int i = r + direction[0];\n int j = c + direction[1];\n if (dfs(grid, i, j)) {\n return true;\n }\n }\n return false;\n }\n};\n\n```\n\n```\nclass Solution:\n def __init__(self):\n self.row = 0\n self.col = 0\n self.cells = []\n self.directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]\n\n def latestDayToCross(self, row, col, cells):\n self.row = row\n self.col = col\n self.cells = cells\n \n left = 1\n right = len(cells)\n while left < right:\n mid = right - (right - left) // 2\n if self.canCross(mid):\n left = mid\n else:\n right = mid - 1\n return left\n \n def canCross(self, day):\n grid = [[0] * self.col for _ in range(self.row)]\n for i in range(day):\n grid[self.cells[i][0] - 1][self.cells[i][1] - 1] = 1\n \n for i in range(self.col):\n if grid[0][i] == 0 and self.dfs(grid, 0, i):\n return True\n return False\n \n def dfs(self, grid, r, c):\n if r < 0 or r >= self.row or c < 0 or c >= self.col or grid[r][c] != 0:\n return False\n \n if r == self.row - 1:\n return True\n grid[r][c] = -1\n for direction in self.directions:\n i = r + direction[0]\n j = c + direction[1]\n if self.dfs(grid, i, j):\n return True\n return False\n\n```
99,825
Last Day Where You Can Still Cross
last-day-where-you-can-still-cross
There is a 1-based binary matrix where 0 represents land and 1 represents water. You are given integers row and col representing the number of rows and columns in the matrix, respectively. Initially on day 0, the entire matrix is land. However, each day a new cell becomes flooded with water. You are given a 1-based 2D array cells, where cells[i] = [ri, ci] represents that on the ith day, the cell on the rith row and cith column (1-based coordinates) will be covered with water (i.e., changed to 1). You want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells. You can start from any cell in the top row and end at any cell in the bottom row. You can only travel in the four cardinal directions (left, right, up, and down). Return the last day where it is possible to walk from the top to the bottom by only walking on land cells.
Array,Binary Search,Depth-First Search,Breadth-First Search,Union Find,Matrix
Hard
What graph algorithm allows us to find whether a path exists? Can we use binary search to help us solve the problem?
17,126
116
# Intuition:\n\nThe intuition behind the problem is to find the latest day where it is still possible to cross the grid by incrementally adding cells and checking if a path exists from the top row to the bottom row, utilizing binary search to optimize the search process.\n\n# Explanation:\n**Binary Search:**\n1. Initialize `left` as 0 (representing the earliest day) and `right` as `row * col` (representing the latest possible day).\n2. While `left` is less than `right - 1`, do the following:\n - Calculate the mid-day as `mid = (left + right) / 2`.\n - Check if it is possible to cross the grid on day `mid` by calling the `isPossible` function.\n - The `isPossible` function checks if it is possible to cross the grid by considering the first `mid` cells from the given list. It uses BFS to explore the grid and checks if the bottom row can be reached.\n - If it is possible to cross, update `left` to `mid` and store the latest possible day in a variable (let\'s call it `latestPossibleDay`).\n - If it is not possible to cross, update `right` to `mid`.\n3. Return `latestPossibleDay` as the latest day where it is still possible to cross the grid.\n\n**Breadth-First Search (BFS):**\nThe `isPossible` function:\n1. Create a grid with dimensions `(m + 1)` x `(n + 1)` and initialize all cells to 0.\n2. Mark the cells from the given list as blocked by setting their corresponding positions in the grid to 1.\n3. Create a queue to perform BFS.\n4. For each cell in the first row of the grid, if it is not blocked, add it to the queue and mark it as visited.\n5. While the queue is not empty, do the following:\n - Dequeue a cell from the front of the queue.\n - Get the current cell\'s coordinates (row and column).\n - Explore the neighboring cells (up, down, left, and right) by checking their validity and whether they are blocked or not.\n - If a neighboring cell is valid, not blocked, and has not been visited, mark it as visited and enqueue it.\n - If a neighboring cell is in the last row, return `true` as it means a\n\n path to the bottom row has been found.\n6. If we finish the BFS without finding a path to the bottom row, return `false`.\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool isPossible(int m, int n, int t, vector<vector<int>>& cells) {\n vector<vector<int>> grid(m + 1, vector<int>(n + 1, 0)); // Grid representation\n vector<pair<int, int>> directions {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // Possible directions\n\n for (int i = 0; i < t; i++) {\n grid[cells[i][0]][cells[i][1]] = 1; // Mark cells from the given list as blocked\n }\n\n queue<pair<int, int>> q;\n \n for (int i = 1; i <= n; i++) {\n if (grid[1][i] == 0) {\n q.push({1, i}); // Start BFS from the top row\n grid[1][i] = 1; // Mark the cell as visited\n }\n }\n while (!q.empty()) {\n pair<int, int> p = q.front();\n q.pop();\n int r = p.first, c = p.second; // Current cell coordinates\n for (auto d : directions) {\n int nr = r + d.first, nc = c + d.second; // Neighbor cell coordinates\n if (nr > 0 && nc > 0 && nr <= m && nc <= n && grid[nr][nc] == 0) {\n grid[nr][nc] = 1; // Mark the neighbor cell as visited\n if (nr == m) {\n return true; // Found a path to the bottom row\n }\n q.push({nr, nc}); // Add the neighbor cell to the queue for further exploration\n }\n }\n }\n return false; // Unable to find a path to the bottom row\n }\n\n int latestDayToCross(int row, int col, vector<vector<int>>& cells) {\n int left = 0, right = row * col, latestPossibleDay = 0;\n while (left < right - 1) {\n int mid = left + (right - left) / 2; // Calculate the mid-day\n if (isPossible(row, col, mid, cells)) {\n left = mid; // Update the left pointer to search in the upper half\n latestPossibleDay = mid; // Update the latest possible day\n } else {\n right = mid; // Update the right pointer to search in the lower half\n }\n }\n return latestPossibleDay;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean isPossible(int m, int n, int t, int[][] cells) {\n int[][] grid = new int[m + 1][n + 1]; // Grid representation\n int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // Possible directions\n\n for (int i = 0; i < t; i++) {\n grid[cells[i][0]][cells[i][1]] = 1; // Mark cells from the given list as blocked\n }\n\n Queue<int[]> queue = new LinkedList<>();\n \n for (int i = 1; i <= n; i++) {\n if (grid[1][i] == 0) {\n queue.offer(new int[]{1, i}); // Start BFS from the top row\n grid[1][i] = 1; // Mark the cell as visited\n }\n }\n \n while (!queue.isEmpty()) {\n int[] cell = queue.poll();\n int r = cell[0], c = cell[1]; // Current cell coordinates\n \n for (int[] dir : directions) {\n int nr = r + dir[0], nc = c + dir[1]; // Neighbor cell coordinates\n \n if (nr > 0 && nc > 0 && nr <= m && nc <= n && grid[nr][nc] == 0) {\n grid[nr][nc] = 1; // Mark the neighbor cell as visited\n \n if (nr == m) {\n return true; // Found a path to the bottom row\n }\n \n queue.offer(new int[]{nr, nc}); // Add the neighbor cell to the queue for further exploration\n }\n }\n }\n \n return false; // Unable to find a path to the bottom row\n }\n\n public int latestDayToCross(int row, int col, int[][] cells) {\n int left = 0, right = row * col, latestPossibleDay = 0;\n \n while (left < right - 1) {\n int mid = left + (right - left) / 2; // Calculate the mid-day\n \n if (isPossible(row, col, mid, cells)) {\n left = mid; // Update the left pointer to search in the upper half\n latestPossibleDay = mid; // Update the latest possible day\n } else {\n right = mid; // Update the right pointer to search in the lower half\n }\n }\n \n return latestPossibleDay;\n }\n}\n```\n```Python3 []\nclass Solution:\n def isPossible(self, row, col, cells, day):\n grid = [[0] * col for _ in range(row)]\n queue = collections.deque()\n \n for r, c in cells[:day]:\n grid[r - 1][c - 1] = 1\n \n for i in range(col):\n if not grid[0][i]:\n queue.append((0, i))\n grid[0][i] = -1\n\n while queue:\n r, c = queue.popleft()\n if r == row - 1:\n return True\n for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n nr, nc = r + dr, c + dc\n if 0 <= nr < row and 0 <= nc < col and grid[nr][nc] == 0:\n grid[nr][nc] = -1\n queue.append((nr, nc))\n \n return False\n \n \n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n left, right = 1, row * col\n \n while left < right:\n mid = right - (right - left) // 2\n if self.isPossible(row, col, cells, mid):\n left = mid\n else:\n right = mid - 1\n \n return left\n```\n\n![CUTE_CAT.png]()\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.**
99,843
Find the Middle Index in Array
find-the-middle-index-in-array
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0. Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Array,Prefix Sum
Easy
Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i].
1,008
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSo we notice that for index `i` and index `i + 1`, most of the sum on the left and right side are shared. In particular, the left side of index `i` is `sum(nums[0..i-1])` and the left side of `i + 1` is `sum(nums[0..i-1]) + nums[i]`, so they both share `sum(nums[0..i-1]`. This is similar for the right side.\n\nSo we can split the problem in half, calculate the sum of the left half and calculate the sum of the right half and keep that in a cumulative sum so we don\'t have to repeat work.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst find the sum of the left and right half of some subsection of the array (originally the entire array). Then find the middle index of the left half of the array recursively, but make sure to add on the sum of the right half you have calculated so far. Similar for the left side.\n\n# Complexity\n- Time complexity: $O(n \\log n)$\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: $O(n)$ (proof as an exercise to the reader)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findMiddleIndex(self, nums: List[int]) -> int:\n def dnc(l, r, lo, hi):\n if l == r - 1:\n return l if lo == hi else -1\n \n mid = (l + r) // 2\n right = sum(nums[mid:r])\n left = sum(nums[l:mid])\n\n left_ind = dnc(l, mid, lo, hi + right)\n return left_ind if left_ind != -1 else dnc(mid, r, lo + left, hi)\n return dnc(0, len(nums), 0, 0)\n```
99,888
Find the Middle Index in Array
find-the-middle-index-in-array
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0. Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Array,Prefix Sum
Easy
Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i].
3,086
60
**Python :**\n\n```\ndef findMiddleIndex(self, nums: List[int]) -> int: \n\tleftSum = 0\n\trightSum = sum(nums)\n\n\tfor i in range(len(nums)):\n\t\tif leftSum == rightSum - nums[i]:\n\t\t\treturn i\n\n\t\tleftSum += nums[i]\n\t\trightSum -= nums[i]\n\n\treturn -1\n```\n\n**Like it ? please upvote !**
99,889
Find the Middle Index in Array
find-the-middle-index-in-array
Given a 0-indexed integer array nums, find the leftmost middleIndex (i.e., the smallest amongst all the possible ones). A middleIndex is an index where nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]. If middleIndex == 0, the left side sum is considered to be 0. Similarly, if middleIndex == nums.length - 1, the right side sum is considered to be 0. Return the leftmost middleIndex that satisfies the condition, or -1 if there is no such index.
Array,Prefix Sum
Easy
Could we go from left to right and check to see if an index is a middle index? Do we need to sum every number to the left and right of an index each time? Use a prefix sum array where prefix[i] = nums[0] + nums[1] + ... + nums[i].
332
6
You don\'t need to calc sum in every iteration.\nYou also don\'t need a prefix sum.\nHere is what I did:\n```python\n def findMiddleIndex(self, nums: List[int]) -> int:\n leftsum = 0\n rightsum = sum(nums) # O(n) in time\n for i, num in enumerate(nums): # O(n) in time\n leftsum += num\n if leftsum == rightsum:\n return i\n rightsum -= num\n return -1\n```
99,891
Find All Groups of Farmland
find-all-groups-of-farmland
You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through different groups of farmlands and keep track of the smallest and largest x-coordinate and y-coordinates you have seen in each group.
1,475
18
### Idea\n- first we need to iterative through all the positions in the square from the left to the right, top to the bottom.\n- If the land[i][j] == 1, the current coordinate (i, j) will be the top left position and then we will dfs from that coordinate to find to bottom right coordinate.\n- The dfs function will stop if the value is not `1` and the current coordinate are not on the given board.\n- then it turns the current coordinate of the board into `1` to ensure that we visited it.\n- then it try to recursively search for the right and below square of this.\n- the bottom right coordinate will be the maximum value of column and row of alls the block that contains `1` we visited from `dfs`\n\n\n### Analysis\n- Time Complexity O(m X n + k) ~ O(n^2). Where m, n are size of the board, k is number of farm area (k <= m X n).\n- \n\n### Code\n\n```\ndef findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n group = []\n m, n = len(land), len(land[0])\n \n def dfs(row: int, col: int) -> (int, int):\n if row < 0 or row >= m or col < 0 or col >= n or land[row][col] == 0:\n return (0, 0)\n \n land[row][col] = 0\n \n h_r1, h_c1 = dfs(row + 1, col)\n h_r2, h_c2 = dfs(row, col + 1)\n \n h_r = max(h_r1, h_r2, row)\n h_c = max(h_c1, h_c2, col)\n \n return (h_r, h_c)\n \n for i in range(m):\n for j in range(n):\n if land[i][j] == 1:\n x, y = dfs(i, j)\n group.append([i, j, x, y])\n \n return group\n```
99,936
Find All Groups of Farmland
find-all-groups-of-farmland
You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through different groups of farmlands and keep track of the smallest and largest x-coordinate and y-coordinates you have seen in each group.
979
13
```\ndef findFarmland(self, grid):\n self.ans=[]\n row=len(grid)\n col=len(grid[0])\n \n def helper(i,j,grid):\n if i<0 or j<0 or j>=len(grid[0]) or i>=len(grid) or grid[i][j]==0:return (0,0)\n (nx,ny)=(i,j)\n grid[i][j]=0\n for x,y in [(1,0),(0,1)]:\n (nx,ny)=max((nx,ny),helper(i+x,j+y,grid))\n return (nx,ny)\n \n for i in range(row):\n for j in range(col):\n if grid[i][j]==1:\n (x,y)=helper(i,j,grid)\n self.ans.append([i,j,x,y])\n return self.ans
99,945
Find All Groups of Farmland
find-all-groups-of-farmland
You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through different groups of farmlands and keep track of the smallest and largest x-coordinate and y-coordinates you have seen in each group.
265
5
```python\nclass Solution:\n \n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n n = len(land)\n m = len(land[0])\n\n groups = []\n visited = set()\n \n for y in range(n):\n for x in range(m):\n if land[y][x] == 0:\n continue\n \n if (y, x) in visited:\n continue\n \n q = collections.deque()\n q.append((y, x))\n visited.add((y, x))\n \n while q:\n cy, cx = q.popleft()\n \n for dy, dx in ((0, 1), (1, 0)):\n if (cy + dy, cx + dx) in visited:\n continue\n \n if 0 <= cy + dy < n and 0 <= cx + dx < m:\n if land[cy + dy][cx + dx] == 1:\n q.append((cy + dy, cx + dx))\n visited.add((cy + dy, cx + dx))\n\n groups.append([y, x, cy, cx])\n \n return groups\n```
99,956
Find All Groups of Farmland
find-all-groups-of-farmland
You are given a 0-indexed m x n binary matrix land where a 0 represents a hectare of forested land and a 1 represents a hectare of farmland. To keep the land organized, there are designated rectangular areas of hectares that consist entirely of farmland. These rectangular areas are called groups. No two groups are adjacent, meaning farmland in one group is not four-directionally adjacent to another farmland in a different group. land can be represented by a coordinate system where the top left corner of land is (0, 0) and the bottom right corner of land is (m-1, n-1). Find the coordinates of the top left and bottom right corner of each group of farmland. A group of farmland with a top left corner at (r1, c1) and a bottom right corner at (r2, c2) is represented by the 4-length array [r1, c1, r2, c2]. Return a 2D array containing the 4-length arrays described above for each group of farmland in land. If there are no groups of farmland, return an empty array. You may return the answer in any order.
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
Since every group of farmland is rectangular, the top left corner of each group will have the smallest x-coordinate and y-coordinate of any farmland in the group. Similarly, the bootm right corner of each group will have the largest x-coordinate and y-coordinate of any farmland in the group. Use DFS to traverse through different groups of farmlands and keep track of the smallest and largest x-coordinate and y-coordinates you have seen in each group.
386
5
Please check out this [commit]() for solutions of biweekly 60.\n```\nclass Solution:\n def findFarmland(self, land: List[List[int]]) -> List[List[int]]:\n m, n = len(land), len(land[0])\n ans = []\n for i in range(m):\n for j in range(n): \n if land[i][j]: # found farmland\n mini, minj = i, j \n maxi, maxj = i, j \n stack = [(i, j)]\n land[i][j] = 0 # mark as visited \n while stack: \n i, j = stack.pop()\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): \n if 0 <= ii < m and 0 <= jj < n and land[ii][jj]: \n stack.append((ii, jj))\n land[ii][jj] = 0 \n maxi = max(maxi, ii)\n maxj = max(maxj, jj)\n ans.append([mini, minj, maxi, maxj])\n return ans \n```
99,958
Operations on Tree
operations-on-tree
You are given a tree with n nodes numbered from 0 to n - 1 in the form of a parent array parent where parent[i] is the parent of the ith node. The root of the tree is node 0, so parent[0] = -1 since it has no parent. You want to design a data structure that allows users to lock, unlock, and upgrade nodes in the tree. The data structure should support the following functions: Implement the LockingTree class:
Hash Table,Tree,Breadth-First Search,Design
Medium
How can we use the small constraints to help us solve the problem? How can we traverse the ancestors and descendants of a node?
1,817
15
Please check out this [commit]() for solutions of biweekly 60.\n```\nclass LockingTree:\n\n def __init__(self, parent: List[int]):\n self.parent = parent\n self.tree = [[] for _ in parent]\n for i, x in enumerate(parent): \n if x != -1: self.tree[x].append(i)\n self.locked = {}\n\n def lock(self, num: int, user: int) -> bool:\n if num in self.locked: return False \n self.locked[num] = user\n return True \n\n def unlock(self, num: int, user: int) -> bool:\n if self.locked.get(num) != user: return False \n self.locked.pop(num)\n return True \n\n def upgrade(self, num: int, user: int) -> bool:\n if num in self.locked: return False # check for unlocked\n \n node = num\n while node != -1: \n if node in self.locked: break # locked ancestor\n node = self.parent[node]\n else: \n stack = [num]\n descendant = []\n while stack: \n node = stack.pop()\n if node in self.locked: descendant.append(node)\n for child in self.tree[node]: stack.append(child)\n if descendant: \n self.locked[num] = user # lock given node \n for node in descendant: self.locked.pop(node) # unlock all descendants\n return True \n return False # locked ancestor \n```
99,980
Find Unique Binary String
find-unique-binary-string
Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Array,String,Backtracking
Medium
We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?
651
10
![Screenshot (206).png]()\n\n# Intuition\nCantor\'s diagonal argument is a mathematical proof technique used to show that the set of real numbers is uncountably infinite. It\'s often applied in discussions related to the limitations of countable sets. The intuition behind Cantor\'s diagonal argument is crucial for understanding why certain sets are uncountable.\n\nIn the context of the provided solution:\n\n1. **Binary Strings as Countable Sets:**\n - If the set of binary strings represented by `nums` were countable, one might attempt to enumerate them.\n - Cantor\'s diagonal argument suggests that even in such an enumeration, we can always construct a binary string that was not in the original enumeration.\n\n2. **Construction of a Different Binary String:**\n - The provided code aims to find a binary string that differs from each binary string in `nums`.\n - The subtraction of each bit from 1 in the solution corresponds to the flipping of each bit (changing 0 to 1 and vice versa).\n\n3. **Assumption of Countability:**\n - The assumption that there is a countable list of binary strings leads to a contradiction, as the constructed binary string differs from each enumerated string.\n\n4. **Uncountability Implication:**\n - The inability to enumerate all binary strings suggests that the set of binary strings is uncountably infinite.\n\nIn summary, the solution leverages the intuition from Cantor\'s diagonal argument to construct a binary string that is not in the assumed countable list, demonstrating that the set of binary strings is not countable.\n# Approach\n\n1. **Assumption:**\n - Suppose we have a countable list of binary strings, represented by the input list `nums`.\n\n2. **Cantor\'s Diagonal Argument Intuition:**\n - Cantor\'s diagonal argument suggests that even in a countable list of binary strings, we can construct a binary string that is not in the list.\n\n3. **Construction of a Different Binary String:**\n - Initialize an empty string `ans` to store the result.\n - Iterate through each binary string in `nums`.\n - For each binary string, consider the bit at the current index.\n - Flip the bit by subtracting it from 1 and append the result to the `ans` string.\n - Move to the next index and repeat the process.\n\n4. **Result:**\n - The constructed `ans` string represents a binary string that differs from each binary string in the assumed countable list.\n\n5. **Contradiction:**\n - This contradicts the assumption that we had a complete countable list of binary strings.\n - The inability to enumerate all binary strings suggests that the set of binary strings is uncountably infinite.\n\n6. **Return:**\n - Return the constructed `ans` string, which is a binary string not present in the assumed countable list.\n\n# Time and Space Complexity:\n\n- **Time Complexity:**\n - The time complexity is O(n), and `n` is the number of binary strings in `nums`.\n\n- **Space Complexity:**\n - The space complexity is O(n), where `n` is the length of the longest binary string.\n\nThe approach constructs a binary string that is designed to be different from each binary string in the assumed countable list, drawing inspiration from Cantor\'s diagonal argument to highlight the uncountability of the set of binary strings.\n\n\n# Code\n\n```C++ []\nclass Solution {\npublic:\n string findDifferentBinaryString(vector<string>& nums) {\n string ans;\n\n int index = 0;\n for(auto binary : nums)\n {\n ans = ans + to_string(\'1\' - binary[index]);\n index+=1;\n }\n return ans;\n }\n};\n```\n\n```Python []\nclass Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n ans = ""\n\n index = 0\n for bin_num in nums:\n ans = ans + str(1 - int(bin_num[index]))\n index+=1\n return ans\n```
100,125
Find Unique Binary String
find-unique-binary-string
Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Array,String,Backtracking
Medium
We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?
975
9
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere are 2 methods, 3 C++ & 1 python solutions, provided.\nOne is very standard. Define a function `int toInt(string& nums)` converting a binary string to its int number `x`.\n\nThere are numbers for choice, say `[0, 1,..., 2**len-1]`. \nSet a boolean array `hasX` to store the status whether number `x` is already in `nums`.\n\nFinally find any number `N` which is not in `nums`, and convert it to the desired binary string. \n\nA variant using bitset & C++ string::substr is also provided.\n# Cantor\'s Diagonal Approach\n<!-- Describe your approach to solving the problem. -->\n[I give a Math proof in this film on Cantor\'s diagonal mehod. Please turn on English subtitles if necessary]\n[]()\nCantor diagonal argument is the learning stuff for the set theory, purely math. But it can be applied for solving this question. Quite amazing.\n\n2nd method is using the Cantor diagonal argument. This argument I learned from the set theory & advanced Calculus. It is used for proving that the set of real numbers is uncountable. Of course, a Math argument.\n\nA python version is also provided.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(len*n)$$\nCantor method $O(n)$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(len)$\nCantor method extra space $O(1)$ \n# Code\n```\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n int len;\n int toInt(string& nums){\n int x=0;\n #pragma unroll\n for(char c: nums){\n x=(x<<1)+(c-\'0\');\n }\n return x;\n }\n string findDifferentBinaryString(vector<string>& nums) {\n len=nums[0].size();\n vector<bool> hasX(1<<len, 0);\n\n #pragma unroll \n for(auto& x: nums)\n hasX[toInt(x)]=1;\n int N=0;//find N\n\n #pragma unroll\n for(; N<(1<<len) && hasX[N]; N++);\n // cout<<N<<endl;\n string ans=string(len, \'0\');\n\n #pragma unroll\n for(int i=len-1; i>=0 && N>0; i--){\n ans[i]=(N&1)+\'0\';\n N>>=1;\n }\n return ans;\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# Code using bitset & substr\n```\nclass Solution {\npublic:\n string findDifferentBinaryString(vector<string>& nums) {\n const int len=nums[0].size();\n vector<bool> hasX(1<<len, 0);\n\n #pragma unroll \n for(auto& x: nums)\n hasX[bitset<16>(x).to_ulong()]=1;\n int N=0;//find N\n\n #pragma unroll\n for(; N<(1<<len) && hasX[N]; N++);\n // cout<<N<<endl;\n return bitset<16>(N).to_string().substr(16-len,len);\n }\n};\n```\n# Cantor diagonal argument runs in 0ms\n```\n// Use Cantor argument\n// Cantor argument is used to prove that the set of real numbers\n// is uncountable\n// I think that it is the learning stuff for set theory or \n// advanced calculus, pure Math\n#pragma GCC optimize("O3")\nclass Solution {\npublic:\n string findDifferentBinaryString(vector<string>& nums) {\n int n=nums.size(), len=nums[0].size();\n string ans=string(len, \'1\');\n #pragma unroll\n for(int i=0; i<n; i++)\n ans[i]=(\'1\'-nums[i][i])+\'0\';\n return ans;\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 code\n```\nclass Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n n=len(nums[0])\n ans=[\'0\']*n\n for i, x in enumerate(nums):\n if x[i]==\'0\':\n ans[i]=\'1\'\n else:\n ans[i]=\'0\'\n return "".join(ans)\n \n```\n![cantor_diagonal_proof.png]()\n\nSuppose that the real number within $[0,1)$ was countable many. All numbers are expressed in therir binary expansion.\n\nSo, list them as $a_0, a_1,\\cdots, a_n,\\cdots$.\nConstruct a number $ans=0.x_0x_1\\cdots x_n\\cdots$ with $x_i=1-a_{ii}$\n\nThen $ans\\not=a_i \\forall i$. $ans$ can not be in the list. A contradiction.\n
100,126
Find Unique Binary String
find-unique-binary-string
Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Array,String,Backtracking
Medium
We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?
12,509
129
![Screenshot 2023-11-16 060204.png]()\n\n---\n\n# YouTube Video Explanation:\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*Subscribe Goal: 300 Subscribers*\n*Current Subscribers: 261*\n\n---\n\n# Example Explanation\nLet\'s break down the logic step by step using tables for the given input:\n\n### Example:\n\nGiven Array: ["111", "011", "001"]\n\n#### Step 1: Constructing the Result Binary String\n\n| Iteration | Binary String | Character at Diagonal Position | Result Binary String |\n|-----------|---------------|--------------------------------|-----------------------|\n| 1 | "111" | "1" (at position 0) | "0" |\n| 2 | "011" | "1" (at position 1) | "00" |\n| 3 | "001" | "1" (at position 2) | "000" |\n\n### Final Result:\n\nThe binary string "000" does not appear in the given array.\n\n### Explanation:\n\n- Iterate through each binary string in the array.\n- Append the character at the diagonal position to the result binary string.\n- Ensure the constructed binary string is different from any binary string in the array.\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks for a binary string that does not appear in the given array of binary strings. Since each binary string has a length of `n` and the strings are unique, we can construct a binary string by considering the characters at the diagonal positions in the given strings.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a `StringBuilder` to construct the result binary string.\n2. Iterate through the array of binary strings.\n3. At each iteration, append the character at the diagonal position (position `i`) in the current binary string to the result.\n4. Return the result binary string.\n\n# Complexity\n- Time Complexity: O(n)\n - The algorithm iterates through the given array of binary strings once, and each iteration takes constant time.\n- Space Complexity: O(n)\n - The `StringBuilder` is used to construct the result binary string.\n\n# Code\n## Java\n```\nclass Solution {\n public String findDifferentBinaryString(String[] nums) {\n StringBuilder sb = new StringBuilder();\n\n for(int i=0;i<nums.length;i++)\n {\n sb.append(nums[i].charAt(i) == \'0\'? "1": "0");\n }\n return new String(sb);\n }\n}\n```\n## C++\n```\nclass Solution {\npublic:\n string findDifferentBinaryString(vector<string>& nums) {\n string result;\n\n for (int i = 0; i < nums.size(); ++i) {\n result += (nums[i][i] == \'0\' ? \'1\' : \'0\');\n }\n\n return result;\n }\n};\n```\n## Python\n```\nclass Solution(object):\n def findDifferentBinaryString(self, nums):\n result = ""\n\n for i in range(len(nums)):\n result += \'1\' if nums[i][i] == \'0\' else \'0\'\n\n return result\n \n```\n## JavaScript\n```\nvar findDifferentBinaryString = function(nums) {\n let result = "";\n\n for (let i = 0; i < nums.length; ++i) {\n result += (nums[i][i] === \'0\' ? \'1\' : \'0\');\n }\n\n return result;\n};\n```\n---\n<!-- ![upvote1.jpeg]() -->\n
100,127
Find Unique Binary String
find-unique-binary-string
Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Array,String,Backtracking
Medium
We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?
1,895
22
# Approach\nGiven an array nums consisting of binary strings, we need to find a binary string that differs from all the binary strings in the array. We can achieve this by iterating through each position in the binary strings and flipping the bit at that position. This will ensure that the resulting binary string is different from each binary string in the array. \n\n### why?\nBecause `len(nums) == len(nums[i])`\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```py\nclass Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n res = []\n for i in range(len(nums)):\n if nums[i][i] == \'1\':\n res.append(\'0\')\n else:\n res.append(\'1\')\n return "".join(res)\n```\nplease upvote :D
100,128
Find Unique Binary String
find-unique-binary-string
Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Array,String,Backtracking
Medium
We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?
950
28
# Intuition\nConvert input strings to integer.\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n\n`0:04` Explain a key point of the question\n`1:39` Why you need to iterate through input array with len(nums) + 1?\n`2:25` Coding\n`3:56` Explain part of my solution code.\n`3:08` What if we have a lot of the same numbers in input array?\n`6:11` 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: 3,123\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\nBefore I explain my solution, I don\'t take this solution. This is a smart solution but probably nobody will come up with this solution in such a short real interview, if you don\'t know "Cantor\'s diagonal argument". We need a [mathematical proof]() if you use it in the interviews. At least I didn\'t come up with it.\n\n```\nclass Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n ans = []\n for i in range(len(nums)):\n curr = nums[i][i]\n ans.append("1" if curr == "0" else "0")\n \n return "".join(ans)\n```\n\nLet\'s talk about another solution.\n\nMy idea is simply to convert binary strings to decimal, because creating and comparing decimal numbers is easier than creating and comparing binary strings, especially creating. For example, we get `"00"` as a `0` of binary string. Typical biarny is just `0`, so we need to add `0` until we meet length of `n`. It\'s time comsuming and complicated.\n\n```\nInput: nums = ["00","01"]\n```\nConvert the binary strings to decimal\n```\n"00" \u2192 0\n"01" \u2192 1\n\nset = {0, 1}\n```\nThen iterate through decimal numbers from `0` to `len(nums) + 1`.\n\nLet\'s start.\n\n```\nWe have 0 in set.\nWe have 1 in set.\nWe don\'t have 2 in set.\n```\nThen we need to convert `2` to a binary string\n```\nOutput: "10"\n```\n\n### Why len(nums) + 1?\n\nThe description says "Given an array of strings nums containing n unique binary strings each of length n".\n\nSo all possible answers of binary string for the input array should be `00`,`01`, `10`, `11`. but we have the first two numbers of binary strings(= 0, 1).\n\nThere are cases where we already have the first a few numbers. In that case, we need to find larger number than length of input. In this case, `2` or `3`. \n\n`+1` enables us to find a output definitely.\n\n### What if the first answer we found is `0` or `1`?\n\n```\nInput: nums = ["00","11"]\n```\nSince we iterate through from `0` to `len(nums) + 1`, the output should be\n```\nOutput: "01"\n```\nThis is a binary list.\n```\ndecimal \u2192 binary\n\n0 \u2192 0\n1 \u2192 1\n2 \u2192 10\n3 \u2192 11\n```\nWe found `1` as a output. If we return binary string of `1`, we will return `"1"`. But for this question, we need to fill blanks with `0`, because length of output is also length of `n`.\n\nLook at this Python code.\n```\nreturn bin(i)[2:].zfill(n) \n```\n`zfill` is build-in function to fill the blanks with `0`. The reason why we start from `[2:]` is that when we convert decimal to binary with bin function, there is some prefix which we don\'t need this time. `[2:]` enables us to remove the first two chracters then `zfill` function will fill the blanks with `0` until we reach length of `n`.\n\nEasy! \uD83D\uDE04\nLet\'s see a real algorithm!\n\n---\n\n\n### Algorithm Overview:\n\nConvert input strings to integer, then compare one by one.\n\n### Detailed Explanation:\n\n1. **Initialize an empty set `seen`:**\n - `seen` is a set to store integers that have been encountered.\n\n ```python\n seen = set()\n ```\n\n2. **Convert each binary string in `nums` to an integer and add to `seen`:**\n - Iterate through each binary string in `nums`, convert it to an integer in base 2, and add it to the `seen` set.\n\n ```python\n for binary_string in nums:\n seen.add(int(binary_string, 2))\n ```\n\n3. **Get the length `n` of the binary strings:**\n - Utilize the fact that all binary strings in `nums` have the same length to get the value of `n`.\n\n ```python\n n = len(nums[0])\n ```\n\n4. **Inspect integers from 0 to `len(nums)`:**\n - Loop `len(nums) + 1` times to inspect integers from 0 to `len(nums)`.\n\n ```python\n for i in range(len(nums) + 1):\n ```\n\n5. **If the integer is not in the `seen` set:**\n - If `i` is not in the `seen` set (not encountered yet), generate a new binary string representation and return it.\n\n ```python\n if i not in seen:\n return bin(i)[2:].zfill(n)\n ```\n\nIn the end, find the first integer not present in the `seen` set, convert it to a binary string, and return it.\n\n\n\n# Complexity\n- Time complexity: $$O(n^2)$$\nIterate through input array n times and fill the blank with n times at most. But $$O(n^2)$$ will happen only when we found the answer number. For the most part, we have $$O(n)$$ time.\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```python []\nclass Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n\n seen = set()\n\n for binary_string in nums:\n seen.add(int(binary_string, 2))\n\n n = len(nums[0])\n\n for i in range(len(nums) + 1):\n if i not in seen:\n return bin(i)[2:].zfill(n) \n```\n```javascript []\nvar findDifferentBinaryString = function(nums) {\n const seen = new Set();\n\n for (const binaryString of nums) {\n seen.add(parseInt(binaryString, 2));\n }\n\n const n = nums[0].length;\n\n for (let i = 0; i <= nums.length; i++) {\n if (!seen.has(i)) {\n return i.toString(2).padStart(n, \'0\');\n }\n } \n};\n```\n```java []\nclass Solution {\n public String findDifferentBinaryString(String[] nums) {\n HashSet<Integer> seen = new HashSet<>();\n\n for (String binaryString : nums) {\n seen.add(Integer.parseInt(binaryString, 2));\n }\n\n int n = nums[0].length();\n\n for (int i = 0; i <= n; i++) {\n if (!seen.contains(i)) {\n StringBuilder binaryStringBuilder = new StringBuilder(Integer.toBinaryString(i));\n while (binaryStringBuilder.length() < n) {\n binaryStringBuilder.insert(0, \'0\');\n }\n return binaryStringBuilder.toString();\n }\n }\n\n return ""; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n string findDifferentBinaryString(vector<string>& nums) {\n unordered_set<int> seen;\n\n for (const auto& binaryString : nums) {\n seen.insert(stoi(binaryString, nullptr, 2));\n }\n\n int n = nums[0].length();\n\n for (int i = 0; i <= nums.size(); i++) {\n if (seen.find(i) == seen.end()) {\n return bitset<32>(i).to_string().substr(32 - n);\n }\n }\n\n return ""; \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 how we can solve Minimize Maximum Pair Sum in Array\n`2:21` Check with other pair combinations\n`4:12` Let\'s see another example!\n`5:37` Find Common process of the two examples\n`6:45` Coding\n`7: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`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\n
100,129
Find Unique Binary String
find-unique-binary-string
Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Array,String,Backtracking
Medium
We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?
2,420
37
# Problem Description\n\nWrite a function that takes an array of length `n` of **unique** **binary** strings, each of length `n`, as input. The task is to **find** and return a binary string of length `n` that does not **exist** in the given array. \nIn case there are multiple valid answers, the function is allowed to return any of them.\n\n- Constraints:\n - $n == nums.length$\n - $1 <= n <= 16$\n - $nums[i].length == n$\n - nums[i][j] is either \'0\' or \'1\'.\n - All the strings of nums are **unique**.\n\n---\n\n\n\n# Intuition\n\nHi there,\uD83D\uDE00\n\nLet\'s take a look\uD83D\uDC40 on our today\'s problem.\nIn our today\'s problem, We have array of **binary** strings of size `n` and each string in it has length `n` and our task is to return any binary string og length `n` that doesn\'t **appear** in our array.\uD83E\uDD14\n\nSeem pretty easy !\uD83D\uDCAA\n\nWe can notice that `n` isn\'t that large $1 <= n <= 16$ so there are at most `2^16` possible binary strings. Our **Brute Force** guy can be used here !\uD83D\uDCAA\uD83D\uDCAA\nWe can **generate** all **possible** strings and see when string of them doesn\'t exist then we can return it as an answer.\uD83E\uDD29\nbut we can try a neat solution using **Sorting**.\uD83E\uDD2F\n\n### Sorting\nWhy not we **sort** the array then **initialize** pointer variable that **expects** the next element in sequence of binary strings and return that pointer if it doesn\'t match with current element in the array.... How ?\uD83E\uDD28\n\nLet\'s see some examples\n```\nnums = ["111","011","001"]\nDecimal = [7, 3, 1]\nSorted = [1, 3, 7]\n\nPointer = 0 \nFirst element = 1 -> 1 != Pointer\n\nReturn 0 which is 000\n```\n```\nnums = ["1110","0000", "0001", "1100"]\nDecimal = [14, 0, 1, 12]\nSorted = [0, 1, 12, 14]\n\nPointer = 0 \nFirst element = 0 -> 0 == Pointer\n\nPointer = 1\nSecond element = 1 -> 1 == Pointer\n\nPointer = 2\nThird element = 12 -> 12 != Pointer\n\nReturn 2 which is 0010\n```\n\nSince the input array is **smaller** than the whole sequence of binary strings of length `n` then we are sure that at some point our pointer won\'t match the sorted array.\uD83E\uDD29\nAnd is a neat solution and has good complexity of $O(N * log(N))$.\uD83D\uDE0E\n\nThere is another pretty solution using a **mathematical** proof from the world of set theory called **Cantor\'s diagonal argument**.\n\n### Cantor\'s diagonal argument\nThis mathimatical proof was published in `1891` by **Georg Cantor**. \nPretty old proof.\uD83D\uDE05\n\nThis was a mathematical proof that set of **Real numbers** are **uncountable** sets which means that we **can\'t count** all the numbers in this set.\uD83E\uDD2F\n\nHow does that relate to our problem?\uD83E\uDD14\nThe proof started by **mapping** each binary string `X` to a real number and said that if the set of binary strings are **countable** then the set of real numbers are **countable**.\nWhat next\u2753\nIt was proven by **contradiction** that the set of binary strings in **uncountable**.\nBy simply, construct a new string `Xn` that doesn\'t exist in this set and that what we will use in our problem.\uD83E\uDD2F\n\nSince we want a new string that is **different** from all strings in our array then why don\'t we **alter** some character from each string so that the result is **different** from each string in the array in some **position**.\uD83D\uDE00\nAnd these positions are the **diagonal** of the matrix formed by our input.\uD83E\uDD28\n\nLet\'s see some examples\n\n```\nnums = ["111","011","001"]\n\nnums = ["1 1 1",\n "0 1 1",\n "0 0 1"]\n\nresult = "000"\n```\n```\nnums = ["1011","1001","0001", "1100"]\n\nnums = ["1 011",\n "1 0 01",\n "00 0 1", \n "110 0"]\n\nresult = "0111"\n```\nYou can see the **pattern** right?\nour result is **different** from all of the strings in the array. Actually it is **formed** from the **input** itself to ensure that it is different from it.\uD83E\uDD29\n\n\n### Bonus Part\nThere is pretty **observation**. You noticed that the array length is `n` right ? and the binary string length is also `n` ?\uD83E\uDD14\nThat means that can exist $2^n - n$ answers to return.\n|Input Size | Possible strings of lengths n | Number of Answers |\n| :---:| :---: | :---: | \n| 1 | 2 | 1 |\n| 2 | 4 | 2 |\n| 3 | 8 | 5 |\n| 4 | 16 | 12 |\n| 5 | 32 | 27 |\n| ... | ... | ... |\n| 16 | 65536 | 65520 | \n\n\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\n## 1. Sorting\n\n1. Declare an integer `pointer` to track the expected decimal value for the next binary string.\n2. Sort the input vector `nums` in lexicographical order.\n\n3. Iterate through the sorted binary strings using a for loop:\n - Convert the current binary string to decimal.\n - Check if the decimal value matches the expected value (`pointer`).\n - If they **match**, increment `pointer`.\n - If **not**, return the binary representation of the expected value with the appropriate length.\n4. If no binary string is found during the iteration, return the binary representation of the next expected value.\n\n\n\n## Complexity\n- **Time complexity:** $O(N ^ 2)$\nWe are sorting the input array which takes `O(N * log(N))` generally in all programming languages then we are iterating over all of its elements in `O(N)` and converting each string to its equivalent integer in `O(N)` Which cost us total `O(N^2)` for the for loop then total complexity is `O(N^2 + N * log(N))` which is `O(N^2)`.\n- **Space complexity:** $O(log(N))$ or $O(N)$\nThe space complexity depends on the used sorting algorithm. In Java which uses **Dual-Pivot Quick Sort** and C++ which uses **Intro Sort** the complexity of their algorithms are `O(log(N))` space which in Python which uses **Timsort** it uses `O(N)`.\n\n\n\n---\n\n## 2. Cantor\'s Diagonal Argument\n\n1. Create an empty string called `result` to store the binary string.\n2. Use a **loop** to iterate through each binary string in the vector:\n - For each binary string, access the character at the current index (`i`) and **append** the **opposite** binary value to the `result` string.\n - If the current character is `0`, append `1`; otherwise, append `0`.\n4. The final **result** is the binary string formed by appending the **opposite** binary values from each binary string.\n\n\n## Complexity\n- **Time complexity:** $O(N)$\nWe are iterating over the input using for loop which cost us `O(N)`.\n- **Space complexity:** $O(1)$\nWithout considering the result then we are using constant variables.\n\n\n---\n\n\n\n# Code\n## 1. Sorting\n```C++ []\nclass Solution {\npublic:\n\n string findDifferentBinaryString(vector<string>& nums) {\n const int size = nums.size(); // Number of binary strings in the input vector\n\n // Sort the input vector in lexicographical order\n sort(nums.begin(), nums.end());\n\n int pointer = 0; // Pointer to track the expected decimal value for the next binary string\n\n // Iterate through the sorted binary strings\n for(int i = 0; i < size; ++i) {\n // Convert the current binary string to decimal\n unsigned long decimalValue = bitset<16>(nums[i]).to_ulong();\n\n // Check if the decimal value matches the expected value\n if(decimalValue == pointer)\n pointer++;\n else\n // If not, return the binary representation of the expected value with appropriate length\n return bitset<16>(pointer).to_string().substr(16 - size);\n }\n\n // If no unique binary string is found, return the binary representation of the next expected value\n return bitset<16>(pointer).to_string().substr(16 - size);\n }\n};\n```\n```Java []\npublic class Solution {\n public String findDifferentBinaryString(String[] nums) {\n int size = nums.length; // Number of binary strings in the input array\n\n // Sort the input array in lexicographical order\n Arrays.sort(nums);\n\n int pointer = 0; // Pointer to track the expected decimal value for the next binary string\n\n // Iterate through the sorted binary strings\n for (int i = 0; i < size; ++i) {\n // Convert the current binary string to decimal\n long decimalValue = Long.parseLong(nums[i], 2);\n\n // Check if the decimal value matches the expected value\n if (decimalValue == pointer)\n pointer++;\n else\n // If not, return the binary representation of the expected value with appropriate length\n return String.format("%" + size + "s", Long.toBinaryString(pointer)).replace(\' \', \'0\');\n }\n\n // If no unique binary string is found, return the binary representation of the next expected value\n return String.format("%" + size + "s", Long.toBinaryString(pointer)).replace(\' \', \'0\');\n }\n}\n```\n```Python []\nclass Solution:\n def findDifferentBinaryString(self, nums: List[str]) -> str:\n size = len(nums) # Number of binary strings in the input list\n\n # Sort the input list in lexicographical order\n nums.sort()\n\n pointer = 0 # Pointer to track the expected decimal value for the next binary string\n\n # Iterate through the sorted binary strings\n for i in range(size):\n # Convert the current binary string to decimal\n decimal_value = int(nums[i], 2)\n\n # Check if the decimal value matches the expected value\n if decimal_value == pointer:\n pointer += 1\n else:\n # If not, return the binary representation of the expected value with appropriate length\n return format(pointer, f\'0{size}b\')\n\n # If no unique binary string is found, return the binary representation of the next expected value\n return format(pointer, f\'0{size}b\')\n```\n\n\n---\n\n## 2. Cantor\'s Diagonal Argument\n```C++ []\nclass Solution {\npublic:\n string findDifferentBinaryString(vector<string>& nums) {\n string result;\n\n // Iterate through each binary string in the vector\n for (int i = 0; i < nums.size(); ++i) {\n // Access the i-th character of the i-th binary string\n char currentCharacter = nums[i][i];\n\n // Append the opposite binary value to the result string\n result += (currentCharacter == \'0\' ? \'1\' : \'0\');\n }\n\n // Return the resulting binary string\n return result;\n }\n};\n```\n```Java []\npublic class Solution {\n public String findDifferentBinaryString(String[] nums) {\n StringBuilder result = new StringBuilder();\n\n // Iterate through each binary string in the array\n for (int i = 0; i < nums.length; ++i) {\n // Access the i-th character of the i-th binary string\n char currentCharacter = nums[i].charAt(i);\n\n // Append the opposite binary value to the result string\n result.append((currentCharacter == \'0\' ? \'1\' : \'0\'));\n }\n\n // Return the resulting binary string\n return result.toString();\n }\n}\n```\n```Python []\nclass Solution:\n def findDifferentBinaryString(self, binaryStrings: List[str]) -> str:\n result = []\n\n # Iterate through each binary string in the list\n for i in range(len(binaryStrings)):\n # Access the i-th character of the i-th binary string\n current_character = binaryStrings[i][i]\n\n # Append the opposite binary value to the result string\n result.append(\'1\' if current_character == \'0\' else \'0\')\n\n # Return the resulting binary string\n return \'\'.join(result)\n```\n\n\n\n\n\n![HelpfulJerry.jpg]()\n\n
100,130
Find Unique Binary String
find-unique-binary-string
Given an array of strings nums containing n unique binary strings each of length n, return a binary string of length n that does not appear in nums. If there are multiple answers, you may return any of them.
Array,String,Backtracking
Medium
We can convert the given strings into base 10 integers. Can we use recursion to generate all possible strings?
6,236
50
### Brute force: Base intuition \n\nWhen told to find some possible outcome out of an already large set, recursion comes to mind as it will check every path to find a valid binary string of size `n` that is not already present in the nums array. Also note that `n` is less than or equal to `16`, so `2^16` equals 65536 possible binary strings. Thus, it\'s feasible to generate all of them in an attempt to find one that does not appear in nums.\n\nA binary string comprises of two numbers, 0 and 1. Thus, during recursion, we choose either the addzero path `(curr + "0")` or addone path `(curr + "1")`. For example, for `n=2`, the addzero path gives `01` and `00`, or addone path gives `10` and `11`. When the length becomes equal to `n`, we need to stop adding those characters and check if it\'s in nums. If not, then we found the answer. If it\'s already present, then check for other possibilities. A quick optimization can be whenever we need to check if the curr string is in the `nums` or not. We can\'t do array traversal as it will cost `O(n)`, but what if we use a set which has a lookup time complexity of `O(1)`.\n\nOne more optimization can be that we can be smart about our choices. If adding "`0`" works, great! If not, don\'t waste time trying "`1`" on that branch because we know "1" must work. This early stopping is a nice-to-have in cases where finding a valid answer can be achieved without checking all possibilities.\n\nAs without the early return, we would explore both "`0`" and "`1`" paths in every branch, potentially leading to `2^n` recursive calls. The optimization makes sure that, in the best case, it only checks `n + 1` different strings of length `n` to find a valid answer. But still, in the worst case, it will be `2^n`.\n\n```cpp\nclass Solution {\npublic:\n string binGenerate(string curr, int n, unordered_set<string> binSet) {\n if (curr.size() == n) {\n if (binSet.find(curr) == binSet.end()) return curr;\n return "";\n }\n \n string addZero = binGenerate(curr + "0", n, binSet);\n if (addZero.size() > 0) return addZero;\n\n return binGenerate(curr + "1", n, binSet);\n }\n\n string findDifferentBinaryString(vector<string>& nums) {\n int n = nums.size();\n unordered_set<string> binSet;\n\n for(string s: nums){\n binSet.insert(s);\n }\n return binGenerate("", n, binSet);\n }\n};\n```\n\n```java\nclass Solution {\n public String binGenerate(String curr, int n, Set<String> binSet) {\n if (curr.length() == n) {\n if (!binSet.contains(curr)) return curr;\n return "";\n }\n\n String addZero = binGenerate(curr + "0", n, binSet);\n if (!addZero.isEmpty()) return addZero;\n\n return binGenerate(curr + "1", n, binSet);\n }\n\n public String findDifferentBinaryString(String[] nums) {\n int n = nums.length;\n Set<String> binSet = new HashSet<>();\n\n for (String s : nums) {\n binSet.add(s);\n }\n return binGenerate("", n, binSet);\n }\n}\n```\n\n\n```python\nclass Solution:\n def binGenerate(self, curr, n, binSet):\n if len(curr) == n:\n if curr not in binSet:\n return curr\n return ""\n\n addZero = self.binGenerate(curr + "0", n, binSet)\n if addZero:\n return addZero\n\n return self.binGenerate(curr + "1", n, binSet)\n\n def findDifferentBinaryString(self, nums):\n n = len(nums)\n binSet = set(nums)\n\n return self.binGenerate("", n, binSet)\n```\n\n\n### Optimized approach: base2 to base10\nIn the last intuition, one thing we didn\'t use was that the possible binary string will always have the size of n. So, whats the need to create the entire binary string from scratch. Since the constraint already specifies that we have the size of nums and valid ans has also the same size then dont you think directly checking their numbers is bit easy!? Let\'s go a bit into detail.\n\nTake `["010", "101", "110"]` as an example; their equivalent base-10 integers are `{2, 5, 6}`. Ding ding! Now, you know what I am thinking: the missing integer is our answer. Still, one thing is not so clear, and that is from where to where we need to use a loop. Let\'s say we have an integer string that comes out as `{1, 2, 3}` instead of `{2, 5, 6}`. To make things clear, we will loop from `0` to `2^n`, as we are dealing with binary strings of length `n`, and each digit in a binary string can take two values (`0` or `1`). Thus, for a binary string of length n, there are `2^n` possible combinations.\n\n```cpp\nclass Solution {\npublic:\n string findDifferentBinaryString(vector<string>& nums) {\n unordered_set<int> integers;\n \n // Binary string to base-10 integer\n for (const string& num : nums) {\n integers.insert(bitset<16>(num).to_ulong());\n }\n \n int n = nums.size();\n for (int i = 0; i < pow(2, n); ++i) {\n if (integers.find(i) == integers.end()) {\n // Convert the found number back to a binary string of length n\n return bitset<16>(i).to_string().substr(16 - n);\n }\n }\n \n return ""; \n }\n};\n```\n\n```java\nclass Solution {\n public String findDifferentBinaryString(String[] nums) {\n Set<Integer> integers = new HashSet<>();\n\n // Binary string to base-10 integer\n for (String num : nums) {\n integers.add(Integer.parseInt(num, 2));\n }\n\n int n = nums.length;\n for (int i = 0; i < Math.pow(2, n); ++i) {\n if (!integers.contains(i)) {\n // Convert the found number back to a binary string of length n\n return String.format("%" + n + "s", Integer.toBinaryString(i)).replace(\' \', \'0\');\n }\n }\n\n return "";\n }\n}\n```\n\n\n```python\nclass Solution:\n def findDifferentBinaryString(self, nums):\n integers = set()\n\n # Binary string to base-10 integer\n for num in nums:\n integers.add(int(num, 2))\n\n n = len(nums)\n for i in range(int(pow(2, n))):\n if i not in integers:\n # Convert the found number back to a binary string of length n\n return format(i, \'0\' + str(n) + \'b\')\n\n return ""\n```\n\n### Most optimized: Flipping the binarys\n\nDuring the last solution, I was thinking, what if I take each opposite binary digit from nums and make ans from it? Like, let\'s say for `n=2`, `[0,1]` `[0,0]`. So what I was thinking was if I make a binary number like this `[1,1]`. These will always be different from what was given. \n\nLet\'s get into some more details: the first set of binary digits is `[0,1]`, so if I take its first digit `0` and flip it, thus becoming `1`. So now one thing is sure that the future binary number will always be different from the first given binary number as we just flipped its digit `[1,_]`. Now, to make sure that the next digit does not make it the same, we do the same, i.e., in `[0,0]` flip the second binary `0` to `1`. This will make sure that the produced ans has one flipped binary from every nums binary, ultimately producing a string that\'s different than the given nums.\n\nIn a pure mathemetical form we can say that the result will differ from each string in nums at their respective indices. For example:\nfinal res will be different from `nums[0]` in `nums[0][0]`.\nfinal res will be different from `nums[1]` in `nums[1][1]`.\nfinal res will be different from `nums[2]` in `nums[2][2]`.\nfinal res will be different from `nums[3]` in `nums[3][3]`.\n... and so on for all indices up to `n - 1`.\n\nLate realization but this will only be possible if the ans length and the length of each string in nums are larger than or equal to `n`. Which in our case is equal to `n`. So it will work.\n\n```cpp\nclass Solution {\npublic:\n string findDifferentBinaryString(vector<string>& nums) {\n string ans = "";\n\n for (int i = 0; i < nums.size(); ++i) {\n char currentChar = nums[i][i];\n char oppositeChar = (currentChar == \'0\') ? \'1\' : \'0\';\n\n // add the opposite character to the result string\n ans += oppositeChar;\n }\n\n return ans;\n }\n};\n```\n\n```java\nclass Solution {\n public String findDifferentBinaryString(String[] nums) {\n StringBuilder ans = new StringBuilder();\n\n for (int i = 0; i < nums.length; ++i) {\n char currentChar = nums[i].charAt(i);\n char oppositeChar = (currentChar == \'0\') ? \'1\' : \'0\';\n\n // Append the opposite character to the result string\n ans.append(oppositeChar);\n }\n\n return ans.toString();\n }\n}\n```\n\n\n```python\nclass Solution:\n def findDifferentBinaryString(self, nums):\n ans = ""\n\n for i in range(len(nums)):\n currentChar = nums[i][i]\n oppositeChar = \'1\' if currentChar == \'0\' else \'0\'\n\n # Append the opposite character to the result string\n ans += oppositeChar\n\n return ans\n```
100,142
Minimize the Difference Between Target and Chosen Elements
minimize-the-difference-between-target-and-chosen-elements
You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. The absolute difference between two numbers a and b is the absolute value of a - b.
Array,Dynamic Programming,Matrix
Medium
The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much.
3,275
25
**Explanation:**\n\n\nPlease note following important observations from question,\n1. We must choose exactly one element from each row\n2. Minimize the diff between target and the sum of all chosen elements\n\nApproach (and how to solve TLE)\n\nNow, the general idea is to explore all possibilities, however, that\'ll be very hug (~70^70). Hence, the immediate thought is to apply dynamic programmic. The subproblems can be modelled as,\n\n`findMinAbsDiff(i,prevSum)` -> returns the minimum abs diff with target, given that we\'re currently at row i and the sum of chosen numbers for row 0 to i-1 is `prevSum`\n\nHence, we can use a `dp[i][prevSum]` array for memoization. However, the answer will still not get accepted due to the nature of input test cases provided.\n\nSo, to optimize further you can leverage the fact the minimum possible answer for any input is `0`. Hence, if we get `0` absolute difference then we don\'t need to explore further, we stop and prune further explorations to save cost.\n\n**Additional Note:** I\'ve also sorted the array prior to actual exploration code to make pruning more efficient, based on the observation of the test constraints, as the target sum is much smaller compared to the sum of max values of the rows. However, that\'s not neccesary. \n\n**Code:**\n```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n \n # store the mxn size of the matrix\n m = len(mat)\n n = len(mat[0])\n \n dp = defaultdict(defaultdict)\n \n # Sorting each row of the array for more efficient pruning\n # Note:this purely based on the observation on problem constraints (although interesting :))\n for i in range(m):\n mat[i] = sorted(mat[i])\n \n # returns minimum absolute starting from from row i to n-1 for the target\n globalMin = float("inf")\n def findMinAbsDiff(i,prevSum):\n nonlocal globalMin\n if i == m:\n globalMin = min(globalMin, abs(prevSum-target))\n return abs(prevSum-target)\n \n # pruning step 1\n # because the array is increasing & prevSum & target will always be positive\n if prevSum-target > globalMin:\n return float("inf")\n \n \n if (i in dp) and (prevSum in dp[i]):\n return dp[i][prevSum]\n \n minDiff = float("inf")\n # for each candidate select that and backtrack\n for j in range(n):\n diff = findMinAbsDiff(i+1, prevSum+mat[i][j])\n # pruning step 2 - break if we found minDiff 0 --> VERY CRTICIAL\n if diff == 0:\n minDiff = 0\n break\n minDiff = min(minDiff, diff)\n \n dp[i][prevSum] = minDiff\n return minDiff\n \n return findMinAbsDiff(0, 0)\n```
100,182
Minimize the Difference Between Target and Chosen Elements
minimize-the-difference-between-target-and-chosen-elements
You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. The absolute difference between two numbers a and b is the absolute value of a - b.
Array,Dynamic Programming,Matrix
Medium
The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much.
438
5
```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n\n mat = [set(row) for row in mat]\n \n rSet = set(mat.pop())\n\n for row in mat: rSet = {m+n for m in row for n in rSet}\n \n return min(abs(n - target) for n in rSet)\n\n```\n[](http://)\n\n
100,187
Minimize the Difference Between Target and Chosen Elements
minimize-the-difference-between-target-and-chosen-elements
You are given an m x n integer matrix mat and an integer target. Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized. Return the minimum absolute difference. The absolute difference between two numbers a and b is the absolute value of a - b.
Array,Dynamic Programming,Matrix
Medium
The sum of chosen elements will not be too large. Consider using a hash set to record all possible sums while iterating each row. Instead of keeping track of all possible sums, since in each row, we are adding positive numbers, only keep those that can be a candidate, not exceeding the target by too much.
524
6
```\nclass Solution:\n def minimizeTheDifference(self, mat: List[List[int]], target: int) -> int:\n possibleSum = set([0])\n for m in mat:\n temp = set()\n for y in possibleSum:\n for x in sorted(set(m)):\n temp.add(x+y)\n if x+y>target:\n break\n possibleSum = temp\n return min(abs(s-target) for s in possibleSum)\n```
100,202
Find Array Given Subset Sums
find-array-given-subset-sums
You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order). Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them. An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0. Note: Test cases are generated such that there will always be at least one correct answer.
Array,Divide and Conquer
Hard
What information do the two largest elements tell us? Can we use recursion to check all possible states?
2,795
81
**Some key principles of a set that we will use to construct our solution**\n1. If the size of a set is `n` then its superset has a size of `2^n`. Hence, any superset is always divisible in two equal parts.\n2. Any superset must have an empty set. The sum of elements of any empty set is `0`, hence any set containing all subset sums must contain `0` as an element.\n3. Any superset can be divided into two parts with equal size, such that one part has all the subsets `excluding` an element `x` and the other one has all the subsets `including` the element `x`. In such a case, the `excluding` set corresponds to the superset of the original set after removing the element `x` from it. For example, let the original set be `set={x, y, z}`, then\n\t* its superset is `superset={ {}, {x}, {y}, {z}, {x, y}, {x, z}, {y, z}, {x, y, z} }`. \n\t* the superset can be divided into two equal parts based on the element `x` like `excluding={ {}, {y}, {z}, {y, z}}` and `including={ {x}, {x, y}, {x, z}, {x, y, z} }`. \n\t* the `excluding` set corresponds to the superset of the set `{y, z}`. Now since `excluding` is a superset too, it must have a size of `2^(n-1)` (using principle 1). This should give us an idea on how to approach the solution. \n4. The `excluding` set must contain the empty set `{}` as an element.\n5. Multiple sets can result in the same superset i.e. given a superset there can be multiple solution sets that are valid. For example, `{2, 3, -5}` and `{-2, -3, 5}` both have same superset. \n\n**Intuition**\nFrom the pt 3 above, it looks like given a superset, if we can somehow get one element of the original set, and if somehow we can figure out the `excluding` set then we can re-apply the same steps repeatedly (on the `excluding` set this time) till we have figured out all the elements. \n\nThe questions that need to be answered are: \n1. How to find an element of the original set (since we are given subset **sum** instead of subsets) ?\n2. How to find the `excluding` set ?\n\n **How to find an element of the original set ?**\nPlease note that if we take the maximum and the second maximum elements of the subset sums (say `max` and `secondMax`), then `secondMax` can be obtained from `max` by doing one of the following:\n1. remove the least non-negative element from the `max`.\n2. add the largest (least if absolute value is considered) negative element to the `max`. \nFor example, for the set `{-1, -2, 3, 4}` the `max` element in the superset is `7` (corresponding to subset `{3, 4}`) and the `secondMax` element in the superset is `6` (corresponding to subset `{3, 4, -1}`). Here `-1` is the largest negative number (least if absolute value is considered). \nHence, if `diff = max - secondMax` then, either `diff` or `-1*diff` is a member of the original set. Now here we can choose either `diff` or `-1*diff` based on which one is a plausible value. In many cases any of the both `diff` or `-1*diff` can be chosen (using principle 5 of key principles). We can check for the plausiblity based on the empty set being a part of the `excuding` set (using principle 4 of key principles). If the `excluding` set does not contain the value `0` (corresponding to the empty set), then we would include `-1*diff` in our solution set (as the `including` set would become the true `excluding` set in this case). \n\n**How to find the `excluding` set ?**\nTo find the `excluding` set we start with the assumption that `diff` (from above) is a valid member of the solution set. Please note that `diff` is always non-negative. Hence, the least element of subset sum must belong to `excluding` set and the max element must belong to the `including` set. Hence, we can sort the subset sum in increasing order, pick the least element and add it to the `excluding` set and add the least + `diff` element to the `including` set. Please note that a least + `diff` element must exist (using principle 3 of key principles). We can keep adding elements to `excluding` and `including` sets like this by iterating over the sorted subset sums.\nOnce we have the `excluding` set with us, we can check its validity by checking if `0` is a part of it (using principle 4 of key principles). If not, then `including` set must have it (since any subset sum must have a `0` (using principle 2 of key principles)). This implies that `including` set is the actual `excluding` set and that `secondMax` was actually obtained by adding a negative number to `max` and not by removing a postive number. Hence, we add `-1*diff` to our result set instead. \n\n**Code**\n```\nclass Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n res = [] # Result set\n sums.sort()\n \n while len(sums) > 1:\n num = sums[-1] - sums[-2] # max - secondMax\n countMap = Counter(sums) # Get count of each elements\n excluding = [] # Subset sums that do NOT contain num\n including = [] # Subset sums that contain num\n \n for x in sums:\n if countMap.get(x) > 0:\n excluding.append(x)\n including.append(x+num)\n countMap[x] -= 1\n countMap[x+num] -= 1\n \n\t\t\t# Check validity of excluding set\t\n if 0 in excluding:\n sums = excluding\n res.append(num)\n else:\n sums = including\n res.append(-1*num)\n \n return res\n```\n
100,225
Find Array Given Subset Sums
find-array-given-subset-sums
You are given an integer n representing the length of an unknown array that you are trying to recover. You are also given an array sums containing the values of all 2n subset sums of the unknown array (in no particular order). Return the array ans of length n representing the unknown array. If multiple answers exist, return any of them. An array sub is a subset of an array arr if sub can be obtained from arr by deleting some (possibly zero or all) elements of arr. The sum of the elements in sub is one possible subset sum of arr. The sum of an empty array is considered to be 0. Note: Test cases are generated such that there will always be at least one correct answer.
Array,Divide and Conquer
Hard
What information do the two largest elements tell us? Can we use recursion to check all possible states?
1,171
6
Basically I did the following:\n1. Sort the summaries.\n2. Divide it by two groups so that every single value in the higher group has a conterpart in lower group. And the differences (set it to positive for now) are the same among all such pairs.\n3. If zero is in lower group, return the lower group and the difference, if not, return the higher one and the inversed difference. Because if we take the group doesn\'t have any zeros, at last we can\'t get the zero-valued summary, which is the value for an empty subset. If zero exists on both groups it means one of the diff (a number in the original array) must be zero and we can choose arbitrarily.\n4. Redo step 2 and 3 until the summaries are only [0] and meanwhile collect the differences.\n5. The differences are the original array.\n\nAn random example:\noriginal array -> [-9, 5, 11]\nsubset summaries -> [-9, -4, 0, 2, 5, 7, 11, 16]\n\niteration 1:\ndiff -> 9\nlows-> [-9, -4, 2, 7]\nhigh -> [*0*, 5, 11, 16] (zero is here)\nwe get diff as **-9** and work on the **high** group\n\niteration 2:\ndiff -> 5\nlow -> [*0*, 11] (zero is here)\nhigh -> [5, 16]\nwe get diff as **5** and work on the **low** group\n\niteration 3:\ndiff -> 11\nlow -> [*0*] (zero is here)\nhigh -> [11]\nwe get diff as **11** and work on the **low** group (well actually not)\n\nAnd the answer is [-9, 5, 11]\n\n```\nclass Solution:\n def recoverArray(self, n: int, sums: List[int]) -> List[int]:\n sums.sort()\n ans = []\n while len(sums) > 1:\n ele, sums = self._recoverArray(sums)\n ans.append(ele)\n return ans\n\n def _recoverArray(self, sums: List[int]) -> [int, List]:\n max_val = max(sums)\n L = len(sums)\n sums_map = {}\n for val in sums:\n if val not in sums_map:\n sums_map[val] = 0\n sums_map[val] += 1\n sorted_vals = sorted(sums_map.keys())\n init_low = sorted_vals[0]\n sums_map[init_low] -= 1\n if sums_map[init_low] == 0:\n del sums_map[init_low]\n sorted_vals.pop(0)\n for high in sorted_vals:\n _sums_map = sums_map.copy()\n _sums_map[high] -= 1\n if _sums_map[high] == 0:\n del _sums_map[high]\n count = 2\n diff = high - init_low\n ans = [init_low]\n for low in sorted_vals:\n skip_all_the_way = False\n while low in _sums_map:\n _sums_map[low] -= 1\n if _sums_map[low] == 0:\n del _sums_map[low]\n high = low + diff\n if high not in _sums_map:\n skip_all_the_way = True\n break\n _sums_map[high] -= 1\n if _sums_map[high] == 0:\n del _sums_map[high]\n count += 2\n ans.append(low)\n if count == L:\n skip_all_the_way = True\n break\n if skip_all_the_way:\n break\n if count == L:\n if 0 in set(ans):\n return [diff, ans]\n return [-diff, [num + diff for num in ans]]\n```
100,233
Minimum Difference Between Highest and Lowest of K Scores
minimum-difference-between-highest-and-lowest-of-k-scores
You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k. Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized. Return the minimum possible difference.
Array,Sliding Window,Sorting
Easy
For the difference between the highest and lowest element to be minimized, the k chosen scores need to be as close to each other as possible. What if the array was sorted? After sorting the scores, any contiguous k scores are as close to each other as possible. Apply a sliding window solution to iterate over each contiguous k scores, and find the minimum of the differences of all windows.
4,269
32
**Python :**\n\n```\ndef minimumDifference(self, nums: List[int], k: int) -> int:\n\tif len(nums) <= 1:\n\t\treturn 0\n\n\tnums = sorted(nums)\n\tres = nums[k-1] - nums[0]\n\n\tfor i in range(k, len(nums)):\n\t\tres = min(res, nums[i] - nums[i - k + 1])\n\n\treturn res\n```\n\n**Like it ? please upvote !**
100,323
Minimum Difference Between Highest and Lowest of K Scores
minimum-difference-between-highest-and-lowest-of-k-scores
You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k. Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized. Return the minimum possible difference.
Array,Sliding Window,Sorting
Easy
For the difference between the highest and lowest element to be minimized, the k chosen scores need to be as close to each other as possible. What if the array was sorted? After sorting the scores, any contiguous k scores are as close to each other as possible. Apply a sliding window solution to iterate over each contiguous k scores, and find the minimum of the differences of all windows.
1,308
6
```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n m,n=100001,len(nums)\n i,j=0,k-1\n while j<n:\n m=min(m,nums[j]-nums[i])\n i+=1\n j+=1\n return m\n```\n\n**An upvote will be encouraging**
100,332
Minimum Difference Between Highest and Lowest of K Scores
minimum-difference-between-highest-and-lowest-of-k-scores
You are given a 0-indexed integer array nums, where nums[i] represents the score of the ith student. You are also given an integer k. Pick the scores of any k students from the array so that the difference between the highest and the lowest of the k scores is minimized. Return the minimum possible difference.
Array,Sliding Window,Sorting
Easy
For the difference between the highest and lowest element to be minimized, the k chosen scores need to be as close to each other as possible. What if the array was sorted? After sorting the scores, any contiguous k scores are as close to each other as possible. Apply a sliding window solution to iterate over each contiguous k scores, and find the minimum of the differences of all windows.
1,829
10
Slide the window and update the min. each time we increase the window, if needed!\n\n```\ndef minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n l, r = 0, k-1\n \n minDiff = float(\'inf\')\n \n while r < len(nums):\n minDiff = min(minDiff, nums[r] - nums[l])\n l, r = l+1, r+1\n \n return minDiff \n```
100,356
Find the Kth Largest Integer in the Array
find-the-kth-largest-integer-in-the-array
You are given an array of strings nums and an integer k. Each string in nums represents an integer without leading zeros. Return the string that represents the kth largest integer in nums. Note: Duplicate numbers should be counted distinctly. For example, if nums is ["1","2","2"], "2" is the first largest integer, "2" is the second-largest integer, and "1" is the third-largest integer.
Array,String,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
If two numbers have different lengths, which one will be larger? The longer number is the larger number. If two numbers have the same length, which one will be larger? Compare the two numbers starting from the most significant digit. Once you have found the first digit that differs, the one with the larger digit is the larger number.
3,404
40
Although, this ways works, ie by directly converting all string to integer. Then sort and reverse.\n\n```\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n nums = sorted(map(int, nums), reverse=True)\n return str(nums[k-1])\n```\n\nThis works because there is no limit to size of int in Python, here 100 digits. So it works, but it only works in Python, not in any other. And it may not work if the length of string is much larger or even if work ,can take large memory. So you can\'t risk using this method in actual interview. This is the correct way.\n\nBy sorting based on customize sort function, which sorts x and y like\n1. when left is smaller, then -1, to keep left on left, \n2. when left is larger, then +1, to put on right\n\n\'4\', \'33\' - len of 4 is smaller, so left smaller, -1\n\'555\', \'66\' - len of 555 is larger, so right larger, +1\n\'342\', \'312\' - left if larger, so +1\n\'11\', \'11\', - both same, so 0\n\ncmp_to_key - is an comparator in python, used to create customized sort based on compare conditions (x, y for eg, in default sort, if x < y then x stays on left, else x goes on right of y).\n\n```\nfrom functools import cmp_to_key\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n def sorter(x, y):\n n, m = len(x), len(y)\n if n < m: # if you want to keep x in left of y, return -1, here if len(x) is shorter, so it is smaller, so left # [\'33\', \'4\'], 4 to left\n return -1\n elif n > m: # +1, if to keep in right of y\n return 1\n else:\n for i in range(n):\n if x[i] < y[i]: # if x[i] smaller, then left\n return -1\n elif x[i] > y[i]: # else in right \n return 1\n else:\n continue\n return 0 # if both same, x==y\n \n key = cmp_to_key(sorter)\n nums.sort(key=key, reverse=True)\n # print(nums)\n return nums[k-1]\n```\n\nUpper Code in more concise form -\n\n```\nfrom functools import cmp_to_key\nclass Solution:\n def kthLargestNumber(self, nums: List[str], k: int) -> str:\n def sorter(x, y):\n n, m = len(x), len(y)\n if n != m:\n return -1 if n < m else 1 # when n > m\n else:\n return -1 if x < y else 1 if x > y else 0\n \n key = cmp_to_key(sorter)\n nums.sort(key=key, reverse=True)\n return nums[k-1]\n```\n\n**Please give this a Upvote if you liked my effort.**
100,382
Minimum Number of Work Sessions to Finish the Tasks
minimum-number-of-work-sessions-to-finish-the-tasks
There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break. You should finish the given tasks in a way that satisfies the following conditions: Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above. The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way.
4,295
58
The full problem is NP-hard: \n\nTo get the exact result, we have to recurse with some smart memorization techniques.\n\nI still find it challenging to use bitmask, so here is the dfs version.\n\nComparing to the default dfs which gets TLE, the trick here is to loop through the sessions, rather than the tasks themselves.\n\n```python\nclass Solution:\n def minSessions(self, tasks: List[int], sessionTime: int) -> int:\n n = len(tasks)\n tasks.sort(reverse=True)\n sessions = []\n result = [n]\n \n def dfs(index):\n if len(sessions) > result[0]:\n return\n if index == n:\n result[0] = len(sessions)\n return\n for i in range(len(sessions)):\n if sessions[i] + tasks[index] <= sessionTime:\n sessions[i] += tasks[index]\n dfs(index + 1)\n sessions[i] -= tasks[index]\n sessions.append(tasks[index])\n dfs(index + 1)\n sessions.pop()\n \n dfs(0)\n return result[0]\n```
100,420
Minimum Number of Work Sessions to Finish the Tasks
minimum-number-of-work-sessions-to-finish-the-tasks
There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break. You should finish the given tasks in a way that satisfies the following conditions: Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above. The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way.
2,390
26
* I think the test cases are little weak, because I just did backtracking and a little pruning and seems to be 4x faster than bitmask solutions.\n* The question boils down to finding minimum number of subsets such that each subset sum <= sessionTime. I maintain a list called subsets, where I track each subset sum. For each tasks[i] try to fit it into one of the existing subsets or create a new subset with this tasks[i] and recurse further. Once I reach the end of the list, I compare the length of the subsets list with current best and record minimum.\n* For pruning, I do the following - Once the length of subsets is larger than current best length, I backtrack. This doesn\'t decrease complexity in mathematical terms but I think in implementation, it helps a lot.\n\n```\nclass Solution:\n def minSessions(self, tasks: List[int], sessionTime: int) -> int:\n subsets = []\n self.ans = len(tasks)\n \n def func(idx):\n if len(subsets) >= self.ans:\n return\n \n if idx == len(tasks):\n self.ans = min(self.ans, len(subsets))\n return\n \n for i in range(len(subsets)):\n if subsets[i] + tasks[idx] <= sessionTime:\n subsets[i] += tasks[idx]\n func(idx + 1)\n subsets[i] -= tasks[idx]\n \n subsets.append(tasks[idx])\n func(idx + 1)\n subsets.pop()\n \n func(0)\n return self.ans
100,429
Minimum Number of Work Sessions to Finish the Tasks
minimum-number-of-work-sessions-to-finish-the-tasks
There are n tasks assigned to you. The task times are represented as an integer array tasks of length n, where the ith task takes tasks[i] hours to finish. A work session is when you work for at most sessionTime consecutive hours and then take a break. You should finish the given tasks in a way that satisfies the following conditions: Given tasks and sessionTime, return the minimum number of work sessions needed to finish all the tasks following the conditions above. The tests are generated such that sessionTime is greater than or equal to the maximum element in tasks[i].
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
Try all possible ways of assignment. If we can store the assignments in form of a state then we can reuse that state and solve the problem in a faster way.
905
5
```\ndef minSessions(self, tasks: List[int], sessionTime: int) -> int:\n def dfs(i):\n if i == len(tasks):\n return True\n for j in range(mid):\n if cnt[j] >= tasks[i]:\n cnt[j] -= tasks[i]\n if dfs(i + 1):\n return True\n cnt[j] += tasks[i]\n if cnt[j] == sessionTime:\n break\n return False \n \n l, r = 1, len(tasks)\n tasks.sort(reverse=True)\n while l < r:\n mid = (l + r) // 2\n cnt = [sessionTime] * mid\n if not dfs(0):\n l = mid + 1\n else:\n r = mid\n return l
100,440
Count Number of Pairs With Absolute Difference K
count-number-of-pairs-with-absolute-difference-k
Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k. The value of |x| is defined as:
Array,Hash Table,Counting
Easy
Can we check every possible pair? Can we use a nested for loop to solve this problem?
6,929
47
```\nclass Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n seen = defaultdict(int)\n counter = 0\n for num in nums:\n tmp, tmp2 = num - k, num + k\n if tmp in seen:\n counter += seen[tmp]\n if tmp2 in seen:\n counter += seen[tmp2]\n \n seen[num] += 1\n \n return counter\n```\n\nShorter version\n\n```\nclass Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n seen = defaultdict(int)\n counter = 0\n for num in nums:\n counter += seen[num-k] + seen[num+k]\n seen[num] += 1\n return counter\n```
100,537
Count Number of Pairs With Absolute Difference K
count-number-of-pairs-with-absolute-difference-k
Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k. The value of |x| is defined as:
Array,Hash Table,Counting
Easy
Can we check every possible pair? Can we use a nested for loop to solve this problem?
1,240
8
O(n)\n```\nclass Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n count = 0\n \n hash = {}\n \n for i in nums:\n if i in hash:\n hash[i] +=1\n else:\n hash[i] = 1\n \n for i in hash:\n if i+k in hash:\n count+=hash[i]*hash[i+k]\n \n return count\n```\nO(n2)\n```\nclass Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n \n count = 0\n i = 0\n j = len(nums)-1\n nums.sort()\n while i<len(nums):\n if abs(nums[j]-nums[i])==k:\n count+=1\n j-=1\n \n \n elif abs(nums[j]-nums[i])<k:\n i+=1\n j=len(nums)-1\n else:\n j-=1\n \n return count\n\t\n\t\t
100,551
Count Number of Pairs With Absolute Difference K
count-number-of-pairs-with-absolute-difference-k
Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k. The value of |x| is defined as:
Array,Hash Table,Counting
Easy
Can we check every possible pair? Can we use a nested for loop to solve this problem?
499
5
```\nclass Solution:\n def countKDifference(self, nums: List[int], k: int) -> int:\n count=0\n from collections import Counter\n mydict=Counter(nums) \n for i in mydict:\n if i+k in mydict:\n count=count+ mydict[i]*mydict[i+k] \n return count\n```
100,565
Find Original Array From Doubled Array
find-original-array-from-doubled-array
An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.
Array,Hash Table,Greedy,Sorting
Medium
If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be a doubled value?
11,570
158
The tricky part of the problem is to handle groups of numbers such as `[1, 2, 2, 4, 4, 4, 8, 8]`, which won\'t necessarily appear in order. The O(n)-time way of handling this is to first find the smallest number in the group (linear time with a hash map) and then walk up through the chain by doubling the number each time (linear time).\n\nThe `collections.Counter` here is just a python shortcut for a counter hashmap.\n\n```\nclass Solution:\n def findOriginalArray(self, changed: List[int]) -> List[int]:\n counter = collections.Counter(changed)\n res = []\n for k in counter.keys():\n \n if k == 0:\n # handle zero as special case\n if counter[k] % 2 > 0:\n return []\n res += [0] * (counter[k] // 2)\n \n elif counter[k] > 0:\n x = k\n \n # walk down the chain\n while x % 2 == 0 and x // 2 in counter:\n x = x // 2\n \n # walk up and process all numbers within the chain. mark the counts as 0\n while x in counter:\n if counter[x] > 0:\n res += [x] * counter[x]\n if counter[x+x] < counter[x]:\n return []\n counter[x+x] -= counter[x]\n counter[x] = 0\n x += x\n return res\n```
100,574
Find Original Array From Doubled Array
find-original-array-from-doubled-array
An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.
Array,Hash Table,Greedy,Sorting
Medium
If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be a doubled value?
1,548
5
Pretty much explains itself. It uses a Counter, handles the zeros separately, then iterates\nthrough the keys of the Counter to check the doubles and to build the answer array.\n\nI\'m no expert, but I guess time/space to be *O*(*n*)/*O*(*n*). (Counter is *O*(*n*) on both I believe.)\n[edit: @jacobquicksilver--oops, you\'re correct, thank you; you get my upvote. *O*(*n*log(*n*)/*O*(*n*log(*n*)\nis mitigated a little because the sort is on the keys, not the whole list. ]\n\n```\nclass Solution:\n def findOriginalArray(self, changed: List[int]) -> List[int]:\n c = Counter(changed)\n\n zeros, m = divmod(c[0], 2)\n if m: return []\n ans = [0]*zeros \n\n for n in sorted(c.keys()):\n if c[n] > c[2*n]: return []\n c[2*n]-= c[n]\n ans.extend([n]*c[n])\n\n return ans\n\n```\n[](http://)\n\t\t
100,577
Find Original Array From Doubled Array
find-original-array-from-doubled-array
An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.
Array,Hash Table,Greedy,Sorting
Medium
If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be a doubled value?
4,900
46
Please check out [LeetCode The Hard Way]() for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord]().\nIf you like it, please give a star, watch my [Github Repository]() and upvote this post.\n\n---\n\n**C++ - HashMap Approach**\n\n```cpp\n// Time Complexity: O(N + NlogN)\n// Space Complexity: O(N)\n// where N is the number of elements in `changed` \nclass Solution {\npublic:\n // hashmap approach\n vector<int> findOriginalArray(vector<int>& changed) {\n // if the length of the input is odd, then return {}\n // because doubled array must have even length\n if (changed.size() & 1) return {};\n // count the frequency of each number\n unordered_map<int, int> m;\n for (auto x: changed) m[x]++;\n vector<int> ans;\n // sort in ascending order\n sort(changed.begin(), changed.end());\n // keep the unique elements only in changed\n // think of test cases like [0,0,0,0]\n // alternatively you can handle it like\n // - check if the frequency of 0 is odd, if so, return {}\n // - push `0` `m[0] / 2` times to ans\n changed.erase(unique(changed.begin(), changed.end()), changed.end());\n // so that we can iterate `changed` from smallest to largest\n for (auto x : changed) {\n // if the number of m[x] is greater than than m[x * 2]\n // then there would be some m[x] left\n // therefore, return {} here as changed is not a doubled array\n if (m[x] > m[x * 2]) return {};\n for (int i = 0; i < m[x]; i++) {\n // otherwise, we put the element `x` `m[x]` times to ans\n ans.push_back(x);\n // at the same time we decrease the count of m[x * 2] by 1\n // we don\'t need to decrease m[x] by 1 as we won\'t use it again\n m[x * 2] -= 1;\n }\n }\n return ans;\n }\n};\n```\n\n```cpp\n// Time Complexity: O(N + KlogK)\n// Space Complexity: O(N)\n// where N is the number of elements in `changed` \n// and K is the number of elements in `uniqueNumbers`\nclass Solution {\npublic:\n // hashmap approach\n vector<int> findOriginalArray(vector<int>& changed) {\n // if the length of the input is odd, then return {}\n // because doubled array must have even length\n if (changed.size() & 1) return {};\n // count the frequency of each number\n unordered_map<int, int> m;\n for (auto x: changed) m[x]++;\n vector<int> ans;\n vector<int> uniqueNumbers;\n\t\t// push all unuque numbers to `uniqueNumbers`\n for (auto x : m) uniqueNumbers.push_back(x.first);\n // sort in ascending order\n sort(uniqueNumbers.begin(), uniqueNumbers.end());\n // so that we can iterate `changed` from smallest to largest\n for (auto x : uniqueNumbers) {\n // if the number of m[x] is greater than than m[x * 2]\n // then there would be some m[x] left\n // therefore, return {} here as changed is not a doubled array\n if (m[x] > m[x * 2]) return {};\n for (int i = 0; i < m[x]; i++) {\n // otherwise, we put the element `x` `m[x]` times to ans\n ans.push_back(x);\n // at the same time we decrease the count of m[x * 2] by 1\n // we don\'t need to decrease m[x] by 1 as we won\'t use it again\n m[x * 2] -= 1;\n }\n }\n return ans;\n }\n};\n```\n\n**C++ - Multiset Approach**\n\n```cpp\n// Time Complexity: O(NlogN)\n// Space Complexity: O(N)\n// where N is the number of elements in `changed` \nclass Solution {\npublic:\n // multiset approach\n vector<int> findOriginalArray(vector<int>& changed) {\n // if the length of the input is odd, then return {}\n // because doubled array must have even length\n if (changed.size() & 1) return {};\n vector<int> ans;\n // put all the elements to a multiset\n multiset<int> s(changed.begin(), changed.end());\n // keep doing the following logic when there is an element in the multiset\n while (s.size()) {\n // get the smallest element\n int smallest = *s.begin();\n ans.push_back(smallest);\n // remove the smallest element in multiset\n s.erase(s.begin());\n // if the doubled value of smallest doesn\'t exist in the multiset\n // then return {}\n if (s.find(smallest * 2) == s.end()) return {};\n // otherwise we can remove its doubled element\n else s.erase(s.find(smallest * 2)); \n }\n return ans;\n }\n};\n```\n\n**Python**\n\n```py\n# Time Complexity: O(NlogN)\n# Space Complextiy O(N)\n# where N is the number of elements in `changed` \nclass Solution:\n def findOriginalArray(self, changed):\n # use Counter to count the frequency of each element in `changed`\n cnt, ans = Counter(changed), []\n # if the length of the input is odd, then return []\n # because doubled array must have even length\n if len(changed) % 2: return []\n # sort in ascending order\n for x in sorted(cnt.keys()):\n # if the number of cnt[x] is greater than than cnt[x * 2]\n # then there would be some cnt[x] left\n # therefore, return [] here as changed is not a doubled array\n if cnt[x] > cnt[x * 2]: return []\n # handle cases like [0,0,0,0]\n if x == 0:\n # similarly, odd length -> return []\n if cnt[x] % 2:\n return []\n else: \n # add `0` `cnt[x] // 2` times \n ans += [0] * (cnt[x] // 2)\n else:\n # otherwise, we put the element `x` `cnt[x]` times to ans\n ans += [x] * cnt[x]\n cnt[2 * x] -= cnt[x]\n return ans\n```\n\n**Java - Counting Sort**\n\n```java\nclass Solution {\n // counting sort approach\n public int[] findOriginalArray(int[] changed) {\n int n = changed.length, j = 0;\n // if the length of the input is odd, then return []\n // because doubled array must have even length\n if (n % 2 == 1) return new int[]{};\n int[] ans = new int[n / 2];\n // alternatively, you can find the max number in `changed`\n // then use new int[2 * mx + 1]\n int[] cnt = new int[200005];\n // count the frequency of each number\n for (int x : changed) cnt[x] += 1;\n // iterate from 0 to max number\n for (int i = 0; i < 200005; i++) {\n // check if the count of number i is greater than 0\n if (cnt[i] > 0) {\n // number i exists, decrease by 1\n cnt[i] -= 1;\n // look for the doubled value\n if (cnt[i * 2] > 0) {\n // doubled value exists, decrease by 1\n cnt[i * 2] -= 1;\n // add this number to ans\n ans[j++] = i--;\n } else {\n // cannot pair up, return []\n return new int[]{};\n }\n }\n }\n return ans;\n }\n}\n```
100,586
Find Original Array From Doubled Array
find-original-array-from-doubled-array
An integer array original is transformed into a doubled array changed by appending twice the value of every element in original, and then randomly shuffling the resulting array. Given an array changed, return original if changed is a doubled array. If changed is not a doubled array, return an empty array. The elements in original may be returned in any order.
Array,Hash Table,Greedy,Sorting
Medium
If changed is a doubled array, you should be able to delete elements and their doubled values until the array is empty. Which element is guaranteed to not be a doubled value? It is the smallest element. After removing the smallest element and its double from changed, is there another number that is guaranteed to not be a doubled value?
5,874
54
**Please UPVOTE if you LIKE!!**\n**Watch this video \uD83E\uDC83 for the better explanation of the code.\n\n\n\n\n**Also you can SUBSCRIBE \uD83E\uDC81 \uD83E\uDC81 \uD83E\uDC81 this channel for the daily leetcode challange solution.**\n \u2B05\u2B05 **Telegram link** to discuss leetcode daily questions and other dsa problems\n\n**C++**\n```\n\n class Solution {\npublic:\n vector<int> findOriginalArray(vector<int>& changed) {\n int n = changed.size();\n\t\t// size of the array\n vector<int> ans;\n\t\t// answer storing array\n vector<int> vacans;\n\t\t// when we need to return vacant array\n unordered_map<int, int> um;\n\t\t // for storing the frequencies of each input\n if (n % 2 !=0) return ans;\n\t\t// when we will have odd number of integer in our input(double array can\'t be in odd number)\n sort(changed.begin(), changed.end());\n\t\t// sorting in increasing order\n for(auto x: changed){\n um[x]++;\n\t\t\t// storing the frequencies\n }\n for (auto y: changed) {\n if (um[y] == 0) continue;\n\t\t // if we have already decreased it\'s value when we were checking y/2 value, like 2,4 we will remove 4 also when we will check 2 but our iteration will come again on 4.\n if (um[y * 2] == 0) return vacans;\n\t\t // if we have y but not y*2 return vacant array\n ans.push_back(y);\n\t\t // if we have both y and y*2, store in our ans array\n um[y]--;\n\t\t // decrease the frequency of y and y*2\n um[y * 2]--;\n }\n return ans;\n }\n};\n```\n**JAVA**\n```\nclass Solution {\n public int[] findOriginalArray(int[] nums) {\n int[] vacarr = new int[0];\n\t \t// when we need to return vacant array\n int n= nums.length;\n\t\t\t// size of the array\n if(n%2!=0)\n {\n return vacarr;\n\t\t\t// when we will have odd number of integer in our input(double array can\'t be in odd number)\n \n }\n HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();\n\t\t\t // for storing the frequencies of each input\n int[] ans = new int[(nums.length/2)];\n // answer storing array\n \n for(int i=0;i<n;i++)\n {\n hm.put(nums[i], hm.getOrDefault(nums[i],0)+1);\n\t\t\t// storing the frequencies\n }\n int temp = 0;\n \n Arrays.sort(nums);\n\t\t// sorting in increasing order\n for(int i: nums)\n {\n \n if(hm.get(i)<=0)\n {\n\t\t\t // if we have already decreased it\'s value when we were checking y/2 value, like 2,4 we will remove 4 also when we will check 2 but our iteration will come again on 4.\n \n continue;\n }\n \n if(hm.getOrDefault(2*i,0)<=0)\n { // if we have y but not y*2 return vacant array\n return vacarr;\n }\n ans[temp++] = i;\n\t\t\t // if we have both y and y*2, store in our ans array\n // decrease the frequency of y and y*2\n hm.put(i, hm.get(i)-1); \n hm.put(2*i, hm.get(2*i)-1);\n }\n \n return ans;\n }\n}\n```\n**PYTHON**\n```\nclass Solution:\n def findOriginalArray(self, nums: List[int]) -> List[int]:\n ans = [] \n\t\t\t#answer storing array\n vacans = [] \n\t\t\t#when we need to return vacant array\n if len(nums)%2:\n return ans\n\t\t\t\t\t#when we will have odd number of integer in our input(double array can\'t be in odd number)\n \n nums.sort()\n\t\t\t#sorting \n\n temp = Counter(nums)\n\t\t\t#storing the frequencies\n for i in nums: \n if temp[i] == 0: \n\t\t\t\t#if we have already decreased it\'s value when we were checking y/2 value, like 2,4 we will remove 4 also when we will check 2 but our iteration will come again on 4.\n \n continue\n else:\n if temp.get(2*i,0) >= 1:\n\t\t\t\t\t#if we have both y and y*2, store in our ans array\n ans.append(i)\n\t\t\t\t\t\t#decrease the frequency of y and y*2\n temp[2*i] -= 1\n temp[i] -= 1\n else: \n return vacans\n return ans\n```\n**Please do UPVOTE to motivate me to solve more daily challenges like this !!**
100,589
Maximum Earnings From Taxi
maximum-earnings-from-taxi
There are n points on a road you are driving your taxi on. The n points on the road are labeled from 1 to n in the direction you are going, and you want to drive from point 1 to point n to make money by picking up passengers. You cannot change the direction of the taxi. The passengers are represented by a 0-indexed 2D integer array rides, where rides[i] = [starti, endi, tipi] denotes the ith passenger requesting a ride from point starti to point endi who is willing to give a tipi dollar tip. For each passenger i you pick up, you earn endi - starti + tipi dollars. You may only drive at most one passenger at a time. Given n and rides, return the maximum number of dollars you can earn by picking up the passengers optimally. Note: You may drop off a passenger and pick up a different passenger at the same point.
Array,Binary Search,Dynamic Programming,Sorting
Medium
Can we sort the array to help us solve the problem? We can use dynamic programming to keep track of the maximum at each position.
1,383
11
# Please upvote if you find the solution helpful :) Thanks!\n\n```\n# Approach 1: DP\n# Time: O(n)\n# Space: O(n)\n\n# Intuition: \n# We want to loop from location = 1 to n and at each step check if this location is an end point or not .\n# If it is an end point then we check all of its corresponding start points and get the maximum fare we can earn .\n# In order to quickly check if this number is an end point or not maintain a hashmap where keys="end point" and the values="[start_point, tip]""\n\ndef maxTaxiEarnings(n, rides):\n """\n :type n: int\n :type rides: List[List[int]]\n :rtype: int\n """\n import collections\n hashmap = collections.defaultdict(list)\n for start, end, tip in rides:\n hashmap[end].append((start, tip))\n\n dp = [0]*(n+1)\n for location in range(1, n+1):\n # taxi driver has the fare from the previous location, let\'s see if he/she can make more money by dropping someone at the current location\n # we check that by checking if the current location is an end point, among the ones gathered as hashmap keys\n dp[location] = dp[location-1] \n if location in hashmap:\n profitDroppingPassengersHere = 0\n # for each ending trip at the current \'location\'\n for start, tip in hashmap[location]:\n profitDroppingPassengersHere = max(profitDroppingPassengersHere, location - start + tip + dp[start])\n # update the dp\n dp[location] = max(dp[location], profitDroppingPassengersHere)\n\n return dp[n]\n```
100,637
Minimum Number of Operations to Make Array Continuous
minimum-number-of-operations-to-make-array-continuous
You are given an integer array nums. In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. Return the minimum number of operations to make nums continuous.
Array,Binary Search
Hard
Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer.
2,061
12
# Intuition\n\nThe goal is to determine the minimum number of operations needed to make the numbers consecutive. To do this, we want to find the maximum unique element within a certain range, specifically from \'n\' to \'n + nums.size() - 1\', where \'n\' can be any element from the array. \n\nThe idea is that if we choose \'n\' as an element in the array, we have found the maximum value that doesn\'t need to be changed to make the numbers consecutive. Therefore, the result can be calculated as \'nums.size() - maximum unique element in the range (n to n + nums.size() - 1)\'. This will give us the minimum number of operations required to make the numbers consecutive, as we are subtracting the count of numbers that don\'t need to be changed from the total count of numbers.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. **Sort the Array**: The first step is to sort the input `nums` array in ascending order. This is done using `sort(nums.begin(), nums.end())`.\n\n2. **Remove Duplicates**: After sorting, the code iterates through the sorted array to remove duplicate elements while maintaining a modified length in the variable `l`. This ensures that the array contains only unique elements in ascending order.\n\n3. **Choose a Reference Number \'n\'**: The algorithm selects a reference number \'n\' from the modified array. This \'n\' represents the starting point for our consecutive sequence. The code starts with \'n\' as the first element of the array.\n\n4. **Find the Maximum Consecutive Sequence**: The code iterates through the modified array, keeping track of the maximum consecutive sequence that includes \'n\'. It calculates the count of consecutive elements by comparing the difference between the current element and \'n\' and incrementing the count until the difference exceeds the maximum possible difference \'n\'. The maximum count is stored in the variable `maxi`.\n\n5. **Calculate the Minimum Operations**: The minimum number of operations needed to make the numbers consecutive is determined by subtracting the maximum count `maxi` from the total number of unique elements in the modified array, which is represented by `l`.\n\n6. **Return the Result**: Finally, the code returns the minimum number of operations as the result.\n\nThis approach ensures that we find the reference number \'n\' that, when used as the starting point, maximizes the consecutive sequence within the array. Subtracting this maximum count from the total unique elements gives us the minimum number of operations required to make the numbers consecutive.\n\n# Complexity\nHere are the time and space complexities for the given code:\n\n**Time Complexity:**\n\n1. Sorting the `nums` array takes O(n log n) time, where \'n\' is the number of elements in the array.\n2. Removing duplicates while iterating through the sorted array takes O(n) time, where \'n\' is the number of elements in the array.\n3. The consecutive sequence calculation also takes O(n) time in the worst case because for each element, we perform a while loop that goes through a portion of the array.\n4. The overall time complexity is dominated by the sorting step, so the total time complexity is O(n log n).\n\n**Space Complexity:**\n\n1. The code modifies the input `nums` array in place, so there is no additional space used for storing a separate copy of the array.\n2. The space used for variables like `maxi`, `count`, `n`, `l`, and loop indices is constant and not dependent on the size of the input array.\n3. Therefore, the space complexity of the code is O(1), which means it uses a constant amount of extra space.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums)\n {\n int maxi = 0; // Initialize a variable to store the maximum count of consecutive numbers\n int count = 0; // Initialize a variable to keep track of the current count of consecutive numbers\n int n = nums.size() - 1; // Calculate the maximum possible difference between numbers\n int l = 0; // Initialize a variable to keep track of the modified length of the \'nums\' vector\n\n sort(nums.begin(), nums.end()); // Sort the input vector \'nums\' in ascending order\n\n // Remove duplicates in \'nums\' and update \'l\' with the modified length\n for(int i = 0; i < nums.size(); i++) {\n if(i+1 < nums.size() && nums[i] == nums[i+1]) continue;\n nums[l++] = nums[i];\n }\n\n // Calculate the maximum count of consecutive numbers\n for(int i = 0, j = 0; i < l; i++) {\n while(j < l && (nums[j] - nums[i]) <= n) {\n count++;\n j++;\n }\n maxi = max(maxi, count);\n count--;\n }\n\n // Calculate and return the minimum number of operations needed to make the numbers consecutive\n return nums.size() - maxi;\n }\n};\n\n```\n```java []\nclass Solution {\n public int minOperations(int[] nums) {\n int maxi = 0; // Initialize a variable to store the maximum count of consecutive numbers\n int count = 0; // Initialize a variable to keep track of the current count of consecutive numbers\n int n = nums.length - 1; // Calculate the maximum possible difference between numbers\n int l = 0; // Initialize a variable to keep track of the modified length of the \'nums\' array\n\n Arrays.sort(nums); // Sort the input array \'nums\' in ascending order\n\n // Remove duplicates in \'nums\' and update \'l\' with the modified length\n for (int i = 0; i < nums.length; i++) {\n if (i + 1 < nums.length && nums[i] == nums[i + 1]) {\n continue;\n }\n nums[l++] = nums[i];\n }\n\n // Calculate the maximum count of consecutive numbers\n for (int i = 0, j = 0; i < l; i++) {\n while (j < l && (nums[j] - nums[i]) <= n) {\n count++;\n j++;\n }\n maxi = Math.max(maxi, count);\n count--;\n }\n\n // Calculate and return the minimum number of operations needed to make the numbers consecutive\n return nums.length - maxi;\n }\n}\n```\n```python3 []\nclass Solution:\n def minOperations(self, nums):\n maxi = 0 # Initialize a variable to store the maximum count of consecutive numbers\n count = 0 # Initialize a variable to keep track of the current count of consecutive numbers\n n = len(nums) - 1 # Calculate the maximum possible difference between numbers\n l = 0 # Initialize a variable to keep track of the modified length of the \'nums\' list\n\n nums.sort() # Sort the input list \'nums\' in ascending order\n\n # Remove duplicates in \'nums\' and update \'l\' with the modified length\n i = 0\n while i < len(nums):\n if i + 1 < len(nums) and nums[i] == nums[i + 1]:\n i += 1\n continue\n nums[l] = nums[i]\n l += 1\n i += 1\n\n # Calculate the maximum count of consecutive numbers\n i = 0\n j = 0\n while i < l:\n while j < l and (nums[j] - nums[i]) <= n:\n count += 1\n j += 1\n maxi = max(maxi, count)\n count -= 1\n i += 1\n\n # Calculate and return the minimum number of operations needed to make the numbers consecutive\n return len(nums) - maxi\n```\n*Thank you for taking the time to read my post in its entirety. I appreciate your attention and hope you found it informative and helpful.*\n\n**PLEASE UPVOTE THIS POST IF YOU FOUND IT HELPFUL**
100,667
Minimum Number of Operations to Make Array Continuous
minimum-number-of-operations-to-make-array-continuous
You are given an integer array nums. In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. Return the minimum number of operations to make nums continuous.
Array,Binary Search
Hard
Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer.
1,095
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nSorting and Removing Duplicates:\nFirst, the code sorts the input array nums in ascending order. This is done to make it easier to find the maximum and minimum elements.\nIt also removes any duplicate elements, ensuring that all elements are unique. This addresses the first condition.\n\nSliding Window Approach:\nThe core of the code is a sliding window approach, where the code iterates through potential "start" elements and extends a "window" to find a valid continuous subarray.\nFor each potential "start" element, it uses a while loop to find the maximum possible "end" element such that the difference between nums[end] and nums[start] is less than n (the length of the array).\n\nCalculating Operations:\nOnce the valid subarray is found, the code calculates the number of operations needed to make it continuous.\nThe number of operations is calculated as n - (end - start + 1). This formula considers the length of the array and the size of the valid subarray.\n\nTracking Minimum Operations:\nThe code keeps track of the minimum operations found so far using the ans variable.\nFor each potential "start" element, it updates ans with the minimum of the current ans and the calculated operations.\n\nFinal Result:\nAfter iterating through all potential "start" elements, the code returns the final value of ans, which represents the minimum number of operations needed to make the entire array continuous.\n\n# Complexity\n- Time complexity:\no(n*log(n))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n```c++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int n = nums.size();\n int ans=INT_MAX;\n sort(nums.begin(), nums.end());\n nums.erase(unique(begin(nums),end(nums)),end(nums));\n int end = 0;\n for(int start=0,end=0; start<nums.size(); ++start)\n {\n while (end < nums.size() && nums[end] < nums[start] + n) \n {\n ans=min(ans,n-(++end -start));\n }\n }\n\n return ans;\n }\n};\n```\n```python []\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n nums = sorted(set(nums))\n ans = sys.maxsize\n for i, s in enumerate(nums):\n e = s + n - 1\n idx = bisect_right(nums, e)\n ans = min(ans, n - (idx - i))\n return ans\n\n```\n```java []\nclass Solution {\n public int minOperations(int[] nums) {\n Arrays.sort(nums);\n int uniqueLen = 1;\n for (int i = 1; i < nums.length; ++i) {\n if (nums[i] != nums[i - 1]) {\n nums[uniqueLen++] = nums[i];\n }\n }\n \n int ans = nums.length;\n for (int i = 0, j = 0; i < uniqueLen; ++i) {\n while (j < uniqueLen && nums[j] - nums[i] <= nums.length - 1) {\n ++j;\n }\n ans = Math.min(ans, nums.length - (j - i));\n }\n \n return ans;\n }\n}\n```\n
100,668
Minimum Number of Operations to Make Array Continuous
minimum-number-of-operations-to-make-array-continuous
You are given an integer array nums. In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. Return the minimum number of operations to make nums continuous.
Array,Binary Search
Hard
Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer.
13,966
82
# Approach\n<!-- Describe your approach to solving the problem. -->\n- Sort the input array `nums` in ascending order.\n- Traverse the sorted array to remove duplicates and count unique elements in `uniqueLen`.\n- Initialize `ans` to the length of the input array, representing the maximum operations initially.\n- Iterate over unique elements using an outer loop.\n- Use an inner while loop with two pointers to find subarrays where the difference between the maximum and minimum element is within the array\'s length.\n- Calculate the number of operations needed to make all elements distinct within each subarray.\n- Update `ans` with the minimum operations found among all subarrays.\n- Return the minimum operations as the final result.\n# Complexity\n- Time complexity: `O(N*lgN + N + N*lgN)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(1)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minOperations(int[] nums) {\n Arrays.sort(nums);\n int uniqueLen = 1;\n for (int i = 1; i < nums.length; ++i) {\n if (nums[i] != nums[i - 1]) {\n nums[uniqueLen++] = nums[i];\n }\n }\n \n int ans = nums.length;\n for (int i = 0, j = 0; i < uniqueLen; ++i) {\n while (j < uniqueLen && nums[j] - nums[i] <= nums.length - 1) {\n ++j;\n }\n ans = Math.min(ans, nums.length - (j - i));\n }\n \n return ans;\n }\n}\n```\n```python3 []\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n n = len(nums)\n nums = sorted(set(nums))\n\t\t\n answer = float("+inf")\n for i, start in enumerate(nums):\n \n search = start + n - 1 # number to search\n start, end = 0, len(nums)-1\n \n while start <= end:\n mid = start + (end - start) // 2\n if nums[mid] <= search:\n idx = mid\n start = mid + 1\n else:\n end = mid - 1\n \n changes = idx - i + 1\n answer = min(answer, n - changes)\n return answer\n \n```\n```python []\nclass Solution(object):\n def minOperations(self, nums):\n # Sort the input list in ascending order.\n nums.sort()\n \n # Initialize variables to keep track of unique elements and minimum operations.\n unique_len = 1\n ans = len(nums)\n \n # Traverse the sorted list to remove duplicates and count unique elements.\n for i in range(1, len(nums)):\n if nums[i] != nums[i - 1]:\n nums[unique_len] = nums[i]\n unique_len += 1\n \n # Initialize pointers for calculating operations within subarrays.\n i, j = 0, 0\n \n # Iterate over unique elements to find minimum operations.\n for i in range(unique_len):\n while j < unique_len and nums[j] - nums[i] <= len(nums) - 1:\n j += 1\n ans = min(ans, len(nums) - (j - i))\n \n return ans\n\n```\n```C++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n // Sort the vector in ascending order\n sort(nums.begin(), nums.end());\n\n // Initialize variables\n int n = nums.size(); // Number of elements in the vector\n int left = 0; // Left pointer for the sliding window\n int maxCount = 1; // Initialize the maximum count of distinct elements\n int currentCount = 1; // Initialize the count of distinct elements in the current window\n\n // Iterate through the vector to find the minimum operations\n for (int right = 1; right < n; ++right) {\n // Check if the current element is equal to the previous one\n if (nums[right] == nums[right - 1]) {\n continue; // Skip duplicates\n }\n\n // Check if the current window size is less than or equal to the difference between the maximum and minimum values\n while (nums[right] - nums[left] > n - 1) {\n // Move the left pointer to shrink the window\n if(left<n && nums[left+1]==nums[left]){\ncurrentCount++;\n}\n left++;\n currentCount--;\n }\n\n // Update the count of distinct elements in the current window\n currentCount++;\n\n // Update the maximum count\n maxCount = max(maxCount, currentCount);\n }\n\n // Calculate the minimum operations\n int minOps = n - maxCount;\n\n return minOps;\n }\n};\n```\n```C []\n// Function prototype for the comparison function\nint compare(const void* a, const void* b);\n\nint minOperations(int* nums, int numsSize) {\n // Define the maximum size of the sliding window\n int k = numsSize - 1;\n\n // Sort the array in ascending order\n qsort(nums, numsSize, sizeof(int), compare);\n\n // Remove adjacent duplicates\n int newLen = 1;\n for (int i = 1; i < numsSize; ++i) {\n if (nums[i] != nums[i - 1]) {\n nums[newLen++] = nums[i];\n }\n }\n\n int l = 0, r = 0, fin = 1;\n\n while (r < newLen) {\n if (l == r)\n r++;\n else if (nums[r] - nums[l] > k)\n l++;\n else {\n fin = (fin > r - l + 1) ? fin : r - l + 1;\n r++;\n }\n }\n\n return k - fin + 1;\n}\n\nint compare(const void* a, const void* b) {\n return (*(int*)a - *(int*)b);\n}\n```\n# If you like the solution please Upvote !!\n![da69d522-8deb-4aa6-a4db-446363bf029f_1687283488.9528875.gif]()\n\n
100,676
Minimum Number of Operations to Make Array Continuous
minimum-number-of-operations-to-make-array-continuous
You are given an integer array nums. In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. Return the minimum number of operations to make nums continuous.
Array,Binary Search
Hard
Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer.
493
8
# Intuition\n\nThe continuous array that the problem asks for is simply an array with the form `[x, x + 1, x + 2, x + 3, ..., x + n - 1]`, but scrambled. Let\'s call that original sorted form **sorted continuous**.\n\nTo simplify the problem, we simply need to find the longest incomplete **sorted continuous** array from the given array.\n\nWe can keep a queue of the current longest incomplete **sorted continuous** array. Whenever adding a new element would make the queue an invalid incomplete **sorted continuous** array (i.e. the added element is larger than `queue[0] + N - 1`), we pop the first element of the queue.\n\nWhatever numbers that aren\'t included in the longest incomplete **sorted continuous** must be replaced. That\'s the number of operations we\'re looking for.\n\n# Code\n```\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n N = len(nums)\n queue = deque()\n max_length = 1\n\n for num in sorted(set(nums)):\n while queue and num - queue[0] >= N:\n queue.popleft()\n\n queue.append(num)\n max_length = max(max_length, len(queue))\n\n return N - max_length\n\n```\n\n## Time complexity\nSorting: O(NlogN)\nLoop: O(N)\n-> O(NlogN)\n\n## Note\n\nFor each `num` in `sorted(set(nums))`, we can also just binary search for the expected `num + N - 1` ending number. This will take O(logN) per loop iteration instead of O(1), but won\'t affect the final time complexity, which is bounded by the O(NlogN) sort anyway.\n\n## 2-liner using binary search, just for fun\n```\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n sn = sorted(set(nums))\n return min(len(nums) - (bisect_right(sn, sn[i] + len(nums) - 1) - i) for i in range(len(sn)))\n\n```
100,685
Minimum Number of Operations to Make Array Continuous
minimum-number-of-operations-to-make-array-continuous
You are given an integer array nums. In one operation, you can replace any element in nums with any integer. nums is considered continuous if both of the following conditions are fulfilled: For example, nums = [4, 2, 5, 3] is continuous, but nums = [1, 2, 3, 5, 6] is not continuous. Return the minimum number of operations to make nums continuous.
Array,Binary Search
Hard
Sort the array. For every index do a binary search to get the possible right end of the window and calculate the possible answer.
3,013
85
Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\nSorting input array.\n\n---\n\n# Solution Video\n\n\n\n\u25A0 Timeline of the video\n`0:00` Read the question of Minimum Number of Operations to Make Array Continuous\n`0:42` How we think about a solution\n`4:33` Demonstrate solution with an example\n`8:10` Why the window has all valid numbers?\n`8:36` We don\'t have to reset the right pointer to 0 or something\n`10:36` Why we need to start window from each number?\n`12:24` What if we have duplicate numbers in input array?\n`14:50` Coding\n`17:11` 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,643\nMy initial goal is 10,000\nThank you for your support!\n\n---\n\n\n# Approach\n\n### How we think about a solution\nWe have two constraints.\n\n\n---\n- All elements in nums are unique.\n- The difference between the maximum element and the minimum element in nums equals nums.length - 1.\n---\n\nFor example, `nums = [1,2,3,4,5]` need `0` opearation because \n\n```\nminimum number is 1\nmaximum number is 5 \u2192 1 + len(nums) - 1(= 4) \n```\nHow about `nums = [4,1,3,2,5]`? we need `0` operation because The array `[4,1,3,2,5]` is simply a shuffled version of `[1,2,3,4,5]`. But shuffuled version makes us feel more diffucult and seems hard to solve the question.\n\nThat\'s why it\'s good idea to sort input array first then try to solve the question. Because we know that we create an array and value range should be `len(nums) - 1`. Seems sorting make the question easy.\n\n---\n\n\u2B50\uFE0F Points\n\nSort input array at first.\n\n---\n\n\nLet\'s think about this input\n```\nInput: [1,2,3,5]\n```\nIn this case, it\'s easy.\n```\n[1,2,3] is good, becuase they are in range 1 to 4.\n[5] should be changed to 4\n\nCalculation is 4 - 3 = 1\n4: length of nums\n3: length of [1,2,3]\n\nOutput: 1 (operation)\n```\nHow about this.\n```\nInput: [1,2,3,5,6]\n\nCalculation is 5 - 3 = 2\n5: length of nums\n3: length of [1,2,3]\n\nOutput: 2 (operations)\n\n```\n##### This is a wrong answer.\n\nThat\'s because if we change `1` to `4` or `6` to `4`, we can create `[2,3,4,5,6]` or `[1,2,3,4,5]`, so just one operation instead of two operations.\n\nFrom those examples, problem is we don\'t know which numbers we should keep and which number we should change.\n\n---\n\n\u2B50\uFE0F Points\n\nSo, we\'re determining the length of a subarray where all numbers are valid. The starting point of subarray should be each respective number.\n\nSince we check length of valid subarray, seems like we can use `sliding window` technique.\n\n---\n\n### How it works\n\nLet\'s see how it works. Initialize a left pointer and a right pointer with `0`.\n```\nInput: nums = [1,2,3,5,6]\n\nleft = 0\nright = 0\noperations = 5 (= len(nums))\n```\nEvery time we check like this.\n```\nnums[right] < nums[left] + length\n```\nBecuase `left pointer` is current starting point of window and valid numbers for current staring point should be `nums[left] + length - 1`.\n\nIf the condition is `true`, increament `right pointer` by `1`.\n\n```\nInput: nums = [1,2,3,5,6]\n\nvalid number is from 1 to 5.\nleft = 0\nright = 4 (until index 3, they are valid)\noperations = 5 (= len(nums)), we don\'t calcuate yet.\n```\nNow `right pointer` is index `4` and we don\'t meet \n```\nnums[right] < nums[left] + length\n= 6 < 1 + 5\n```\nThen, it\'s time to compare mininum operations. Condition should be\n```\n min_operations = min(min_operations, length - (right - left))\n```\n`right - left` is valid part, so if we subtract it from whole length of input array, we can get invalid part which is places where we should change. \n\n\n---\n\n\u2B50\uFE0F Points\n\nThat\'s because we sorted input array at first, so when we find invalid number which means later numbers are also invalid. we are sure that they are out of valid range.\n\n---\n\n\n```\nmin(min_operations, length - (right - left))\n= min(5, 5 - 4)\n= 1 \n```\nWe repeated this process from each index.\n\nBut one more important thing is \n\n---\n\n\u2B50\uFE0F Points\n\nWe can continue to use current right pointer position when we change staring position. we don\'t have to reset right pointer to 0 or something. Because previous starting point number is definitely smaller than current number.\n\n[1,2,3,5,6]\n\nLet\'s say current starting point is at index 1(2). In this case, index 0(1) is smaller than index 1(2) because we sorted the input array.\n\nWhen we start from index 0, we reach index 4(6) and index 4 is invalid. That means we are sure that at least until index 3, we know that all numbers are valid when we start from index 1 becuase\n\nfrom value 1, valid max number is 5 (1 + len(nums) - 1)\nfrom value 2, valid max number is 6 (2 + len(nums) - 1)\n\nIn this case, 6 includes range 2 to 5 from 1 to 5.\n\nThat\'s why we can use current right position when starting point is changed.\n\n---\n\n### Why do we need to start from each number?\n\nAs I told you, problem is we don\'t know which numbers we should keep and which number we should change. But there is another reason.\n\nLet\'s think about this case.\n```\nInput: [1,10,11,12]\n```\nWhen start from index `0`\n```\nvalid: [1]\ninvalid: [10,11,12]\n\n4 - 1 = 3\n\n4: total length of input\n1: valid length\n\nwe need 3 operations.\n```\nWhen start from index `1`\n```\nvalid: [10,11,12]\ninvalid: [1]\n\n4 - 3 = 1\n\n4: total length of input\n3: valid length\n\nwe need 1 operation.\n```\n\n---\n\n\u2B50\uFE0F Points\n\nStarting index 0 is not always minimum operation.\n\n---\n\n### What if we have duplicate numbers in input array?\n\nOne more important point is when we have duplicate numbers in the input array.\n```\nInput: [1,2,3,5,5]\n```\nLet\'s start from index 0, in this case, valid max value is \n```\n1 + (5 - 1) = 5\n```\nWe go through entire array and reach out of bounds from index 0. So output is `0`?\n\nIt\'s not. Do you rememeber we have two constraints and one of them says "All elements in nums are unique", so it\'s a wrong answer.\n\nHow can we avoid this? My idea is to remove duplicate by `Set` before interation.\n\n```\n[1,2,3,5,5]\n\u2193\n[1,2,3,5]\n```\nAfter removing duplicate number, valid range from index 0 should be from `1` to `4`\n\n```\nvalid: [1,2,3]\ninvalid: [5]\n\noperation = 4 - 3 = 1\n```\n\nIf we change one of 5s to 4, we can create `[1,2,3,4,5]` from `[1,2,3,5,5]`.\n\n---\n\n\u2B50\uFE0F Points\n\nRemove duplicate numbers from input array.\n\n---\n\nThat is long thought process. I spent 2 hours to write this.\nI felt like crying halfway through LOL.\n\nOkay, now I hope you have knowledge of important points. Let\'s see a real algorithm!\n\n### Algorithm Overview:\n\n1. Calculate the length of the input array.\n2. Initialize `min_operations` with the length of the array.\n3. Create a sorted set of unique elements from the input array.\n4. Initialize a variable `right` to 0.\n5. Iterate through the sorted unique elements:\n - For each element, find the rightmost index within the range `[element, element + length]`.\n - Calculate the minimum operations needed for the current element.\n6. Return the minimum operations.\n\n### Detailed Explanation:\n\n1. Calculate the length of the input array:\n - `length = len(nums)`\n\n2. Initialize `min_operations` with the length of the array:\n - `min_operations = length`\n\n3. Create a sorted set of unique elements from the input array:\n - `unique_nums = sorted(set(nums))`\n - This ensures that we have a sorted list of unique elements to work with.\n\n4. Initialize a variable `right` to 0:\n - `right = 0`\n - This will be used to keep track of the right pointer in our traversal.\n\n5. Iterate through the sorted unique elements:\n - `for left in range(len(unique_nums)):`\n\n - For each element, find the rightmost index within the range `[element, element + length]`:\n - While `right` is within bounds and the element at `right` is less than `element + length`, increment `right`.\n\n - Calculate the minimum operations needed for the current element:\n - Update `min_operations` as the minimum of its current value and `length - (right - left)`.\n\n6. Return the minimum operations:\n - `return min_operations`\n\n\n---\n\n\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n\nFor just in case, somebody might think this is $$O(n^2)$$ because of nested loop.\n\nActually the left pointer and the right pointer touch each number once because the left pointer is obvious and we don\'t reset the right pointer with 0 or something. we continue to use the right pointer from previous loop.\n\nSo, this nested loop works like $$O(2n)$$ instead of $$O(n^2)$$. That\'s why time complexity of this nested loop is $$O(n)$$.\n\n- Space complexity: $$O(n)$$\n\n\n```python []\nclass Solution:\n def minOperations(self, nums: List[int]) -> int:\n length = len(nums)\n min_operations = length\n unique_nums = sorted(set(nums))\n right = 0\n \n for left in range(len(unique_nums)):\n while right < len(unique_nums) and unique_nums[right] < unique_nums[left] + length:\n right += 1\n \n min_operations = min(min_operations, length - (right - left))\n\n return min_operations\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minOperations = function(nums) {\n const length = nums.length;\n let minOperations = length;\n const uniqueNums = new Set(nums);\n const sortedUniqueNums = Array.from(uniqueNums).sort((a, b) => a - b);\n let right = 0;\n\n for (let left = 0; left < sortedUniqueNums.length; left++) {\n while (right < sortedUniqueNums.length && sortedUniqueNums[right] < sortedUniqueNums[left] + length) {\n right++;\n }\n\n minOperations = Math.min(minOperations, length - (right - left));\n }\n\n return minOperations; \n};\n```\n```java []\nclass Solution {\n public int minOperations(int[] nums) {\n int length = nums.length;\n int minOperations = length;\n Set<Integer> uniqueNums = new HashSet<>();\n for (int num : nums) {\n uniqueNums.add(num);\n }\n Integer[] sortedUniqueNums = uniqueNums.toArray(new Integer[uniqueNums.size()]);\n Arrays.sort(sortedUniqueNums);\n int right = 0;\n\n for (int left = 0; left < sortedUniqueNums.length; left++) {\n while (right < sortedUniqueNums.length && sortedUniqueNums[right] < sortedUniqueNums[left] + length) {\n right++;\n }\n\n minOperations = Math.min(minOperations, length - (right - left));\n }\n\n return minOperations; \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minOperations(vector<int>& nums) {\n int length = nums.size();\n int minOperations = length;\n sort(nums.begin(), nums.end());\n nums.erase(unique(nums.begin(), nums.end()), nums.end());\n int right = 0;\n\n for (int left = 0; left < nums.size(); left++) {\n while (right < nums.size() && nums[right] < nums[left] + length) {\n right++;\n }\n\n minOperations = min(minOperations, length - (right - left));\n }\n\n return minOperations; \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\u2B50\uFE0F Next daily coding challenge post and video\n\nPost\n\n\n\n\n\n\nMy previous post for daily coding challenge\n\nPost\n\n\n\u2B50\uFE0F Yesterday\'s daily challenge video\n\n\n
100,689
Find if Path Exists in Graph
find-if-path-exists-in-graph
There is a bi-directional graph with n vertices, where each vertex is labeled from 0 to n - 1 (inclusive). The edges in the graph are represented as a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional edge between vertex ui and vertex vi. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. You want to determine if there is a valid path that exists from vertex source to vertex destination. Given edges and the integers n, source, and destination, return true if there is a valid path from source to destination, or false otherwise.
Depth-First Search,Breadth-First Search,Graph
Easy
null
8,772
52
DFS\n```\nclass Solution:\n def validPath(self, n: int, edges: List[List[int]], start: int, end: int) -> bool:\n neighbors = defaultdict(list)\n for n1, n2 in edges:\n neighbors[n1].append(n2)\n neighbors[n2].append(n1)\n \n def dfs(node, end, seen):\n if node == end:\n return True\n if node in seen:\n return False\n \n seen.add(node)\n for n in neighbors[node]:\n if dfs(n, end, seen):\n return True\n \n return False\n \n seen = set() \n return dfs(start, end, seen)\n```\nBFS \n```class Solution:\n def validPath(self, n: int, edges: List[List[int]], start: int, end: int) -> bool:\n neighbors = defaultdict(list)\n for n1, n2 in edges:\n neighbors[n1].append(n2)\n neighbors[n2].append(n1)\n \n q = deque([start])\n seen = set([start])\n while q:\n node = q.popleft() \n if node == end:\n return True \n for n in neighbors[node]:\n if n not in seen:\n seen.add(n)\n q.append(n)\n \n return False\n```\n\n\n\n
100,760
Count Special Quadruplets
count-special-quadruplets
Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
Array,Enumeration
Easy
N is very small, how can we use that? Can we check every possible quadruplet?
9,388
120
Java:\n```\nclass Solution {\n public int countQuadruplets(int[] nums) {\n int res = 0;\n int len = nums.length;\n \n Map<Integer, Integer> count = new HashMap<>();\n count.put(nums[len-1] - nums[len-2], 1);\n \n for (int b = len - 3; b >= 1; b--) {\n for (int a = b - 1; a >= 0; a--) {\n res += count.getOrDefault(nums[a] + nums[b], 0);\n }\n \n for (int x = len - 1; x > b; x--) {\n count.put(nums[x] - nums[b], count.getOrDefault(nums[x] - nums[b], 0) + 1);\n }\n }\n \n return res;\n }\n}\n```\n\nC++:\n```\nclass Solution {\npublic:\n int countQuadruplets(vector<int>& nums) {\n int res = 0;\n int len = nums.size();\n \n unordered_map<int, int> count;\n count[nums[len-1] - nums[len-2]] = 1;\n \n for (int b = len - 3; b >= 1; b--) {\n for (int a = b - 1; a >= 0; a--) {\n res += count[nums[a] + nums[b]];\n }\n \n for (int x = len - 1; x > b; x--) {\n count[nums[x] - nums[b]]++;\n }\n }\n \n return res;\n }\n};\n```\n\nPython:\n```\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n res = 0\n l = len(nums)\n \n count = defaultdict(lambda: 0)\n count[nums[l-1] - nums[l-2]] = 1\n \n for b in range(l - 3, 0, -1):\n for a in range(b - 1, -1, -1):\n res += count[nums[a] + nums[b]]\n \n for x in range(l - 1, b, -1):\n count[nums[x] - nums[b]] += 1\n \n return res\n```\n\nA little explanation:\n```\nThe target is to find the number of quadruplet (a, b, c, d), which satisfies: nums[a] + nums[b] + nums[c] = nums[d],\nWe can transform it to: nums[a] + nums[b] = nums[d] - nums[c]\n\nWe can iterate a and b, get the sum of nums[a] and nums[b], and then see how many pairs of (c, d), such that\nnums[a] + nums[b] = nums[d] - nums[c]\n\nFor example:\n nums = [1, 2, 3, 4, 9, 5, 10]\n a b\n\n if we have a = 1, b = 2 (a, b are index)\n then nums[a] + nums[b] = 2 + 3 = 5\n then let\'s see how many pairs (c, d) such that nums[d] - nums[c] = 5\n\n Actually, here are two pairs (c = 3, d = 4) and (c = 5, d = 6), which meet the requirement.\n nums = [1, 2, 3, 4, 9, 5, 10]\n a b c d\n\n nums = [1, 2, 3, 4, 9, 5, 10]\n a b c d\n\nSo while we are at the index pair (a, b), we want to know the number of (c, d), which satisfy two conditions:\n \u2022 nums[a] + nums[b] = nums[d] - nums[c]\n \u2022 a < b < c < d \nActually, we can just enumerate all the (c, d) pairs after the index b, but it is too slow, which is O(n^2),\nso the total will be O(n^4)\n\nWe can use map, the key is the difference: nums[d] - nums[c], the value is the number of pairs: (c, d)\nWhile we iterate (a, b), we can also update this map.\n\nWe need to iterate (a, b) in the reverse order, because the difference map can be updated easily.\nWe still use nums = [1, 2, 3, 4, 9, 5, 10] as an example:\n1st round:\n nums = [1, 2, 3, 4, 9, 5, 10]\n b \n map = {5: 1} because there is one pair (c = 5, d = 6), diff = nums[6] - nums[5] = 5\n \n2nd round:\n nums = [1, 2, 3, 4, 9, 5, 10]\n b\n map will be updated, there are two new pairs: (c = 4, d = 5), (c = 4, d = 6) \n So map = {5: 1, 1: 1, -4: 1}\n\n3rd round:\n nums = [1, 2, 3, 4, 9, 5, 10]\n b\n map will be updated, there are three new pairs: (c = 3, d = 4), (c = 3, d = 5), (c = 3, d = 6) \n So map = {5: 2, 1: 2, -4: 1, 6: 1}\n\nYou can see each time we update the map, we can directly use all the index x after the index b, and get\nthe difference: nums[x] - nums[b], and then use it to update the map.\n```\n\n
100,766
Count Special Quadruplets
count-special-quadruplets
Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
Array,Enumeration
Easy
N is very small, how can we use that? Can we check every possible quadruplet?
1,096
6
Brute force is good enough. \n`itertools.combinations` could make the code shorter, instead of nested for loops.\nedit: Thanks to @FCookie, we don\'t have to sort comination indices `i, j, k, l`.\n```\n def countQuadruplets(self, nums: List[int]) -> int:\n res = 0\n for i,j,k,l in itertools.combinations(range(len(nums)), 4):\n # i,j,k,l = sorted([i,j,k,l])\n if nums[i] + nums[j] + nums[k] == nums[l]:\n res += 1\n \n return res\n```
100,785
Count Special Quadruplets
count-special-quadruplets
Given a 0-indexed integer array nums, return the number of distinct quadruplets (a, b, c, d) such that:
Array,Enumeration
Easy
N is very small, how can we use that? Can we check every possible quadruplet?
1,317
7
```\nclass Solution:\n def countQuadruplets(self, nums: List[int]) -> int:\n idx = defaultdict(list)\n for i in range(len(nums)-1):\n for j in range(i+1, len(nums)):\n idx[nums[j]-nums[i]].append(i)\n \n count = 0 \n for i in range(len(nums)-3):\n for j in range(i+1, len(nums)-2):\n count += sum(k > j for k in idx[nums[i]+nums[j]])\n \n return count\n```
100,796
The Number of Weak Characters in the Game
the-number-of-weak-characters-in-the-game
You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei. Return the number of weak characters.
Array,Stack,Greedy,Sorting,Monotonic Stack
Medium
Sort the array on the basis of the attack values and group characters with the same attack together. How can you use these groups? Characters in one group will always have a lesser attack value than the characters of the next group. Hence, we will only need to check if there is a higher defense value present in the next groups.
4,305
52
Please check out [LeetCode The Hard Way]() for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord]().\nIf you like it, please give a star, watch my [Github Repository]() and upvote this post.\n\n**Solution 1: Hash Map + STL**\n\n```cpp\nclass Solution {\npublic:\n // the idea is to\n // 1. rearrange the order of attack and defense\n // 2. count weak characters (those defenses less than the current maximum defense)\n // 3. update the maximum defense\n int numberOfWeakCharacters(vector<vector<int>>& p) {\n // the final answer to be returned\n int weakCharacters = 0;\n // record maximum defense. since 1 <= defense_i <= 10 ^ 5\n // we can set the init value to x where x < 1\n int maxDefense = 0;\n // use a hash map to map the attack and defense with greater<int> as a key_compare\n map<int, vector<int>, greater<int>> m;\n for(auto x : p) m[x[0]].push_back(x[1]);\n // for each attack\n for(auto x : m) {\n // we count the number of weak characters \n // and add it to `weakCharacters`\n weakCharacters += count_if(x.second.begin(), x.second.end(), [&](int curDefense){ return curDefense < maxDefense;});\n // then update `maxDefense` which is the maximum value in current defenses\n maxDefense = max(maxDefense, *max_element(x.second.begin(), x.second.end()));\n }\n return weakCharacters;\n }\n};\n```\n\n**Solution 2: Sort**\n\n```cpp\nclass Solution {\npublic:\n // the idea is to\n // 1. rearrange the order of attack and defense\n // 2. count weak characters (those defenses less than the current maximum defense)\n // 3. update the maximum defense\n int numberOfWeakCharacters(vector<vector<int>>& p) {\n // the final answer to be returned\n int weakCharacters = 0;\n // record maximum defense. since 1 <= defense_i <= 10 ^ 5\n // we can set the init value to x where x < 1\n int maxDefense = 0;\n // sort properties with custom sort comparator\n sort(p.begin(), p.end(), [](const vector<int>& x, const vector<int>& y) {\n // if the attack is same, then sort defense in ascending order \n // otherwise, sort attack in in descending order \n return x[0] == y[0] ? x[1] < y[1] : x[0] > y[0];\n });\n // by doing so, we don\'t need to compare starting from the back\n for (auto& x : p) {\n // x[1] is defense of properties[i]\n // if it is less than current maxDefense, then it means it is a weak character\n weakCharacters += x[1] < maxDefense;\n // update maxDefense\n maxDefense = max(maxDefense, x[1]);\n }\n return weakCharacters;\n }\n};\n```\n\n**Python**\n\n```py\nclass Solution:\n # the idea is to\n # 1. rearrange the order of attack and defense\n # 2. count weak characters (those defenses less than the current maximum defense)\n # 3. update the maximum defense\n def numberOfWeakCharacters(self, p: List[List[int]]) -> int:\n # the final answer to be returned\n weakCharacters = 0\n # record maximum defense. since 1 <= defense_i <= 10 ^ 5\n # we can set the init value to x where x < 1\n maxDefense = 0\n # sort properties with custom sort comparator\n # if the attack is same, then sort defense in descending order \n # otherwise, sort attack in in ascending order \n p.sort(key = lambda x: (x[0], -x[1]), reverse = True)\n\t\t# or we can do it like \n\t\t# p.sort(key = lambda x: (-x[0], x[1]))\n for _, defense in p:\n # if it is less than current maxDefense, then it means it is a weak character\n if defense < maxDefense: weakCharacters += 1\n # update maxDefense\n else: maxDefense = defense\n return weakCharacters\n```\n
100,819
The Number of Weak Characters in the Game
the-number-of-weak-characters-in-the-game
You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei. Return the number of weak characters.
Array,Stack,Greedy,Sorting,Monotonic Stack
Medium
Sort the array on the basis of the attack values and group characters with the same attack together. How can you use these groups? Characters in one group will always have a lesser attack value than the characters of the next group. Hence, we will only need to check if there is a higher defense value present in the next groups.
1,087
9
**Time Complexity : O(n*logn)**\n**Java**\n```\nclass Solution {\n public int numberOfWeakCharacters(int[][] properties) {\n Arrays.sort(properties, (a,b) -> (a[0] == b[0]) ? (a[1]-b[1]) : (b[0]-a[0]));\n int count = 0, max = 0;\n for(int[] arr: properties){\n if(arr[1] < max) count++;\n max = Math.max(max, arr[1]);\n }\n return count;\n }\n}\n```\n**JavaScript**\n```\nvar numberOfWeakCharacters = function(properties) {\n properties.sort((a,b) => (a[0] == b[0]) ? (a[1]-b[1]) : (b[0]-a[0]))\n let count = 0, max = 0\n for(let arr of properties){\n if(arr[1] < max) count++\n max = Math.max(max, arr[1])\n }\n return count\n};\n```\n**Python**\n```\nclass Solution(object):\n def numberOfWeakCharacters(self, properties):\n properties.sort(key = lambda x: (-x[0], x[1]))\n count, mx = 0, 0\n for arr in properties:\n if arr[1] < mx:\n count += 1\n mx = max(mx, arr[1])\n return count\n```
100,822
The Number of Weak Characters in the Game
the-number-of-weak-characters-in-the-game
You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei. Return the number of weak characters.
Array,Stack,Greedy,Sorting,Monotonic Stack
Medium
Sort the array on the basis of the attack values and group characters with the same attack together. How can you use these groups? Characters in one group will always have a lesser attack value than the characters of the next group. Hence, we will only need to check if there is a higher defense value present in the next groups.
10,852
215
**Solution 1:**\n\n```\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n \n properties.sort(key=lambda x: (-x[0],x[1]))\n \n ans = 0\n curr_max = 0\n \n for _, d in properties:\n if d < curr_max:\n ans += 1\n else:\n curr_max = d\n return ans\n```\n\n**Soultion 2: Stack**\n```\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n \n properties.sort(key=lambda x: (x[0], -x[1]))\n \n stack = []\n ans = 0\n \n for a, d in properties:\n while stack and stack[-1] < d:\n stack.pop()\n ans += 1\n stack.append(d)\n return ans\n```
100,824
The Number of Weak Characters in the Game
the-number-of-weak-characters-in-the-game
You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei. Return the number of weak characters.
Array,Stack,Greedy,Sorting,Monotonic Stack
Medium
Sort the array on the basis of the attack values and group characters with the same attack together. How can you use these groups? Characters in one group will always have a lesser attack value than the characters of the next group. Hence, we will only need to check if there is a higher defense value present in the next groups.
660
5
The idea is simple:\n1. We sort by one of the properties (**attack** in the code below) in descending order\n2. We then iterate over the sorted sequence and keep track of the max **defense** value that we found among characters with attack *strictly greater* than current attack.\n3. If that max defense value is bigger than defense of the current character then we count it as weak\n\n```\nclass Solution:\n def numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n properties.sort(key=itemgetter(0), reverse=True)\n\n cur_attack = properties[0][0]\n prev_best_defense = 0 # best defense among characters with strictly greater attack\n cur_best_defense = 0 # best defense among all characters observed so far\n\n res = 0\n \n for attack, defense in properties:\n if attack != cur_attack:\n # this means that all characters observed so far have attack strictly greater.\n\t\t\t\t# so we merge latest best defense update into the value we use for comparison.\n\t\t\t\t# best defense can really only go up, so prev_best_defense is guaranteed to be\n\t\t\t\t# less or equal than cur_best_defense\n\t\t\t\tprev_best_defense = cur_best_defense\n cur_attack = attack\n \n cur_best_defense = max(cur_best_defense, defense)\n\t\t\t\n\t\t\tif defense < prev_best_defense:\n res += 1\n \n return res\n```\n\nTime complexity - **O(n log n)**. This could be reduced to **O(m log m + n)** where `m` is the number of *distinct* values of **attack**, if we grouped all the characters in squads based on the same attack value. But this would make the code more complicated, plus this solution ran at 2120ms, which is faster than 97.92% of Python submissions, so I\'d consider this quick enough:\n\n![image]()\n\nIf you have any questions, don\'t hesitate to ask =)\nAlso, **please consider upvoting this post if you found it useful**
100,828
The Number of Weak Characters in the Game
the-number-of-weak-characters-in-the-game
You are playing a game that contains multiple characters, and each of the characters has two main properties: attack and defense. You are given a 2D integer array properties where properties[i] = [attacki, defensei] represents the properties of the ith character in the game. A character is said to be weak if any other character has both attack and defense levels strictly greater than this character's attack and defense levels. More formally, a character i is said to be weak if there exists another character j where attackj > attacki and defensej > defensei. Return the number of weak characters.
Array,Stack,Greedy,Sorting,Monotonic Stack
Medium
Sort the array on the basis of the attack values and group characters with the same attack together. How can you use these groups? Characters in one group will always have a lesser attack value than the characters of the next group. Hence, we will only need to check if there is a higher defense value present in the next groups.
2,462
45
# Explanation\n\nThis solution makes use of sorting the array with two keys. The first key, which takes priority, is the negative value of the `attack` of a given character. This causes the array to be sorted in descending value by attack. \n\nThe second key is used when the `attack` of two characters is equal (breaking ties), and it is the `defense` of a given character, which causes characters with the same `attack` to be sorted in ascending order of `defense`.\n\nIn code, this is done by assigning a tuple to the lambda:\n```python\nproperties.sort(key=lambda x: (-x[0], x[1]))\n```\n\nBecause we have sorted this array, we now have two constraints for every element we encounter as we loop through the array:\n1. Every element in the array *must have* an `attack` less than or equal to what we have already seen\n2. If the element has the same attack value as an element we have already encountered, the the defense *must be* greater than or equal to what we have already seen\n\nThis allows to arrive at the key insight in the solution to this question:\nIf the `defense` of character `i` is less than the maximum defense we have seen so far, then `i` is a weak character.\n\nThis is true because any character `k`, `k < i` has an `attack` greater than or equal to than `i`\'s `attack`. Therefore, if `i`\'s `defense` is less than the max `defense` seen so far, then `i` is a weak character. \n\nThe problem of characters potentially having the same `attack` is solved by sorting the characters with the same `attack` by `defense`.\n\n# Code\n```python\n\tdef numberOfWeakCharacters(self, properties: List[List[int]]) -> int:\n # sort properties in descending order of attack but ascending order of defense\n properties.sort(key=lambda x: (-x[0], x[1]))\n \n max_defense = 0\n weak_count = 0\n \n for _, defense in properties:\n # for any given element:\n # - every attack must be less than or equal to what we have already seen\n # - if the attack is the same, then the defense must be greater than what we have already seen for this attack value\n if defense < max_defense:\n weak_count += 1\n else:\n max_defense = defense\n \n return weak_count\n```\n# Runtime + Space Complexity\nThe time complexity is `O(n log n)` due to the sort and the single pass over the array.\nThe space complexity is `O(1)` becuase we are not using any additional data structures (other than the single variable to track the max defense)\n\n# Feedback\nFirst time posting a solution, please leave any comments if anything is not clear or incorrect, or if my solution helped you out :)\n\nHope this helps understand the problem!
100,831
GCD Sort of an Array
gcd-sort-of-an-array
You are given an integer array nums, and you can perform the following operation any number of times on nums: Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.
Array,Math,Union Find,Sorting
Hard
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
2,904
36
Brief explanation: The sequence of numbers can be sorted iff for all indices i, sorted(nums)[i] can be connected to nums[i] through a series of swaps. But to use union-find to connect all nums[i] and nums[j] that are not coprime will take quadratic time. To simplify the task, we connect nums[i] to all of its prime factors.\n\nThe Union-Find was implemented by dictionary in Python3 for simplicity, and by array in C++ (~150ms) and Java(~60ms) for efficiency. \n\n<iframe src="" frameBorder="0" width="1000" height="500"></iframe>
100,919
GCD Sort of an Array
gcd-sort-of-an-array
You are given an integer array nums, and you can perform the following operation any number of times on nums: Return true if it is possible to sort nums in non-decreasing order using the above swap method, or false otherwise.
Array,Math,Union Find,Sorting
Hard
Can we build a graph with all the prime numbers and the original array? We can use union-find to determine which indices are connected (i.e., which indices can be swapped).
897
11
Please check out this [commit]() for solutions of weekly 257.\n```\nclass UnionFind:\n \n def __init__(self, n): \n self.parent = list(range(n))\n self.rank = [1] * n\n \n def find(self, p): \n if p != self.parent[p]: \n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n\n def union(self, p, q):\n prt, qrt = self.find(p), self.find(q)\n if prt == qrt: return False \n if self.rank[prt] > self.rank[qrt]: prt, qrt = qrt, prt\n self.parent[prt] = qrt\n self.rank[qrt] += self.rank[prt]\n return True \n \n\nclass Solution:\n def gcdSort(self, nums: List[int]) -> bool:\n m = max(nums)\n uf = UnionFind(m+1)\n \n seen = set(nums)\n \n # modified sieve of eratosthenes\n sieve = [1]*(m+1)\n sieve[0] = sieve[1] = 0\n for k in range(m//2 + 1): \n if sieve[k]: \n for x in range(2*k, m+1, k): \n sieve[x] = 0\n if x in seen: uf.union(k, x)\n return all(uf.find(x) == uf.find(y) for x, y in zip(nums, sorted(nums)))\n```\n\n**Related problems**\n[952. Largest Component Size by Common Factor]()\n[1998. GCD Sort of an Array]()
100,923
Reverse Prefix of Word
reverse-prefix-of-word
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. Return the resulting string.
Two Pointers,String
Easy
Find the first index where ch appears. Find a way to reverse a substring of word.
684
8
\n\n# Code\n```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n """\n #method 1:\n for i in range(len(word)):\n if word[i]==ch:\n return word[:i+1][::-1]+word[i+1:]\n return word"""\n #method 2:\n l=0\n r=word.find(ch)\n word=list(word)\n while l<r:\n word[l],word[r]=word[r],word[l]\n l+=1\n r-=1\n return "".join(word)\n \n\n \n\n\n \n\n \n```
101,062
Reverse Prefix of Word
reverse-prefix-of-word
Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing. Return the resulting string.
Two Pointers,String
Easy
Find the first index where ch appears. Find a way to reverse a substring of word.
2,457
21
```\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n idx=word.find(ch) \n if idx:\n return word[:idx+1][::-1]+ word[idx+1:]\n return word\n```
101,065
Number of Pairs of Interchangeable Rectangles
number-of-pairs-of-interchangeable-rectangles
You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle. Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division). Return the number of pairs of interchangeable rectangles in rectangles.
Array,Hash Table,Math,Counting,Number Theory
Medium
Store the rectangle height and width ratio in a hashmap. Traverse the ratios, and for each ratio, use the frequency of the ratio to add to the total pair count.
1,512
10
```\nclass Solution:\n def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:\n ratios = defaultdict(int)\n for x, y in rectangles:\n ratios[x/y] += 1\n res = 0\n for val in ratios.values():\n res += (val*(val-1)//2)\n return res\n```\n\nI thought of this as an union-find question at first and then understood it\'s a hashing problem
101,087
Maximum Product of the Length of Two Palindromic Subsequences
maximum-product-of-the-length-of-two-palindromic-subsequences
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.
String,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
Could you generate all possible pairs of disjoint subsequences? Could you find the maximum length palindrome in each subsequence for a pair of disjoint subsequences?
1,273
9
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse mask to save all combination in hashmap and use "&" bit manipulation to check if two mask have repeated letter.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O((2^n)^2)$ => $O(4^n)$ \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe worst case is need save every combination, for example the string of length 12 that only contains one kind of letter.\n$O(2^n)$\n\n# Code\nMathod using bit mask\n``` java []\nclass Solution {\n public int maxProduct(String s) {\n char[] strArr = s.toCharArray();\n int n = strArr.length;\n Map<Integer, Integer> pali = new HashMap<>();\n // save all elligible combination into hashmap\n for (int mask = 0; mask < 1<<n; mask++){\n String subseq = "";\n for (int i = 0; i < 12; i++){\n if ((mask & 1<<i) > 0)\n subseq += strArr[i];\n }\n if (isPalindromic(subseq))\n pali.put(mask, subseq.length());\n }\n // use & opertion between any two combination\n int res = 0;\n for (int mask1 : pali.keySet()){\n for (int mask2 : pali.keySet()){\n if ((mask1 & mask2) == 0)\n res = Math.max(res, pali.get(mask1)*pali.get(mask2));\n }\n }\n\n return res;\n }\n\n public boolean isPalindromic(String str){\n int j = str.length() - 1;\n char[] strArr = str.toCharArray();\n for (int i = 0; i < j; i ++){\n if (strArr[i] != strArr[j])\n return false;\n j--;\n }\n return true;\n }\n}\n```\n``` python3 []\nclass Solution:\n def maxProduct(self, s: str) -> int:\n n, pali = len(s), {} # bitmask : length\n for mask in range(1, 1 << n):\n subseq = ""\n for i in range(n):\n if mask & (1 << i):\n subseq += s[i]\n if subseq == subseq[::-1]: # valid is palindromic\n pali[mask] = len(subseq)\n res = 0\n for mask1, length1 in pali.items():\n for mask2, length2 in pali.items():\n if mask1 & mask2 == 0: \n res = max(res, length1 * length2)\n return res\n```\n\nThere is another method using recursion\n``` java []\nclass Solution {\n int res = 0;\n \n public int maxProduct(String s) {\n char[] strArr = s.toCharArray();\n dfs(strArr, 0, "", "");\n return res;\n }\n\n public void dfs(char[] strArr, int i, String s1, String s2){\n if(i >= strArr.length){\n if(isPalindromic(s1) && isPalindromic(s2))\n res = Math.max(res, s1.length()*s2.length());\n return;\n }\n dfs(strArr, i+1, s1 + strArr[i], s2);\n dfs(strArr, i+1, s1, s2 + strArr[i]);\n dfs(strArr, i+1, s1, s2);\n }\n\n public boolean isPalindromic(String str){\n int j = str.length() - 1;\n char[] strArr = str.toCharArray();\n for (int i = 0; i < j; i ++){\n if (strArr[i] != strArr[j])\n return false;\n j--;\n }\n return true;\n }\n}\n```\n\n**Please upvate if helpful!!**\n\n![image.png]()
101,121
Maximum Product of the Length of Two Palindromic Subsequences
maximum-product-of-the-length-of-two-palindromic-subsequences
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.
String,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
Could you generate all possible pairs of disjoint subsequences? Could you find the maximum length palindrome in each subsequence for a pair of disjoint subsequences?
3,456
36
```python\nclass Solution:\n def maxProduct(self, s: str) -> int:\n # n <= 12, which means the search space is small\n n = len(s)\n arr = []\n \n for mask in range(1, 1<<n):\n subseq = \'\'\n for i in range(n):\n # convert the bitmask to the actual subsequence\n if mask & (1 << i) > 0:\n subseq += s[i]\n if subseq == subseq[::-1]:\n arr.append((mask, len(subseq)))\n \n result = 1\n for (mask1, len1), (mask2, len2) in product(arr, arr):\n # disjoint\n if mask1 & mask2 == 0:\n result = max(result, len1 * len2)\n return result\n```\n\nA slightly improved version, to break early when checking the results\n\n```python\nclass Solution:\n def maxProduct(self, s: str) -> int:\n # n <= 12, which means the search space is small\n n = len(s)\n arr = []\n \n for mask in range(1, 1<<n):\n subseq = \'\'\n for i in range(n):\n # convert the bitmask to the actual subsequence\n if mask & (1 << i) > 0:\n subseq += s[i]\n if subseq == subseq[::-1]:\n arr.append((mask, len(subseq)))\n \n arr.sort(key=lambda x: x[1], reverse=True)\n result = 1\n for i in range(len(arr)):\n mask1, len1 = arr[i]\n # break early\n if len1 ** 2 < result: break\n for j in range(i+1, len(arr)):\n mask2, len2 = arr[j]\n # disjoint\n if mask1 & mask2 == 0 and len1 * len2 > result:\n result = len1 * len2\n break\n \n return result\n```
101,123
Maximum Product of the Length of Two Palindromic Subsequences
maximum-product-of-the-length-of-two-palindromic-subsequences
Given a string s, find two disjoint palindromic subsequences of s such that the product of their lengths is maximized. The two subsequences are disjoint if they do not both pick a character at the same index. Return the maximum possible product of the lengths of the two palindromic subsequences. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string is palindromic if it reads the same forward and backward.
String,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
Could you generate all possible pairs of disjoint subsequences? Could you find the maximum length palindrome in each subsequence for a pair of disjoint subsequences?
794
7
We have 3 possibilities i.e, \n1) not considering the current char for either subsequence \n2) considering it for first one \n3) considering it for second subsequence\n[Follow here]()\n```\nclass Solution:\n def maxProduct(self, s: str) -> int:\n self.res = 0\n def isPalindrome(word):\n l, r = 0, len(word)-1\n while l < r:\n if word[l] != word[r]:\n return False\n l += 1; r -= 1\n return True\n \n @functools.lru_cache(None)\n def dfs(i, word1, word2):\n if i >= len(s):\n if isPalindrome(word1) and isPalindrome(word2):\n self.res = max(self.res, len(word1) * len(word2))\n return\n \n\t\t\tdfs(i + 1, word1, word2) # 1st case \n dfs(i + 1, word1 + s[i], word2) # 2nd case\n dfs(i + 1, word1, word2 + s[i]) # 3rd case\n \n dfs(0, \'\', \'\')\n\t\t\n return self.res\n```
101,138
Convert 1D Array Into 2D Array
convert-1d-array-into-2d-array
You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
Array,Matrix,Simulation
Easy
When is it possible to convert original into a 2D array and when is it impossible? It is possible if and only if m * n == original.length If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array.
103
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 construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n ans=[]\n if m*n==len(original):\n a=0\n for i in range(0,m):\n t=[]\n for j in range(0,n):\n t.append(original[a])\n a=a+1\n ans.append(t)\n #return ans\n return ans\n```
101,216
Convert 1D Array Into 2D Array
convert-1d-array-into-2d-array
You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
Array,Matrix,Simulation
Easy
When is it possible to convert original into a 2D array and when is it impossible? It is possible if and only if m * n == original.length If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array.
446
5
# Code\n```\nclass Solution {\n public int[][] construct2DArray(int[] original, int m, int n) {\n if (m * n != original.length) {\n\t\t return new int[][]{};\n }\n\n int[][] result = new int[m][n];\n int k = 0;\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n result[i][j] = original[k++];\n }\n }\n\n return result; \n }\n}\n```
101,242
Convert 1D Array Into 2D Array
convert-1d-array-into-2d-array
You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
Array,Matrix,Simulation
Easy
When is it possible to convert original into a 2D array and when is it impossible? It is possible if and only if m * n == original.length If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array.
5,151
42
Please check out this [commit]() for solutions of biweekly 62. \n```\nclass Solution:\n def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n ans = []\n if len(original) == m*n: \n for i in range(0, len(original), n): \n ans.append(original[i:i+n])\n return ans \n```
101,243
Convert 1D Array Into 2D Array
convert-1d-array-into-2d-array
You are given a 0-indexed 1-dimensional (1D) integer array original, and two integers, m and n. You are tasked with creating a 2-dimensional (2D) array with m rows and n columns using all the elements from original. The elements from indices 0 to n - 1 (inclusive) of original should form the first row of the constructed 2D array, the elements from indices n to 2 * n - 1 (inclusive) should form the second row of the constructed 2D array, and so on. Return an m x n 2D array constructed according to the above procedure, or an empty 2D array if it is impossible.
Array,Matrix,Simulation
Easy
When is it possible to convert original into a 2D array and when is it impossible? It is possible if and only if m * n == original.length If it is possible to convert original to a 2D array, keep an index i such that original[i] is the next element to add to the 2D array.
2,197
16
One line:\n```\nclass Solution:\n def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n return [original[i:i+n] for i in range(0, len(original), n)] if m*n == len(original) else []\n \n```\n\nWhich is equivalent to\n```\nclass Solution:\n def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]:\n if m*n != len(original):\n return []\n \n q = []\n\n for i in range(0, len(original), n):\n q.append(original[i:i+n])\n \n return q\n \n```
101,263
Number of Pairs of Strings With Concatenation Equal to Target
number-of-pairs-of-strings-with-concatenation-equal-to-target
Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.
Array,String
Medium
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
4,012
20
```java\n public int numOfPairs(String[] nums, String target) {\n int cnt = 0, n = target.length();\n Map<Integer, Integer> prefix = new HashMap<>(), suffix = new HashMap<>();\n for (String num : nums) {\n int sz = num.length();\n if (target.startsWith(num)) {\n cnt += suffix.getOrDefault(n - sz, 0);\n }\n if (target.endsWith(num)) {\n cnt += prefix.getOrDefault(n - sz, 0);\n }\n if (target.startsWith(num)) {\n prefix.put(sz, 1 + prefix.getOrDefault(sz, 0));\n }\n if (target.endsWith(num)) {\n suffix.put(sz, 1 + suffix.getOrDefault(sz, 0));\n }\n }\n return cnt;\n }\n```\n```python\n def numOfPairs(self, nums: List[str], target: str) -> int:\n prefix, suffix = Counter(), Counter()\n cnt = 0\n for num in nums:\n if target.startswith(num):\n cnt += suffix[len(target) - len(num)]\n if target.endswith(num):\n cnt += prefix[len(target) - len(num)]\n if target.startswith(num):\n prefix[len(num)] += 1\n if target.endswith(num):\n suffix[len(num)] += 1\n return cnt\n```\n**Analysis:**\n\nLet `N = nums.length`, `M` be the average size of the digits in `nums`, and `T = target.length()`, then each `startsWith()` cost time O(min(M, T)), therefore the total time is `O(N * M)`, space cost `O(N)`.
101,273
Number of Pairs of Strings With Concatenation Equal to Target
number-of-pairs-of-strings-with-concatenation-equal-to-target
Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.
Array,String
Medium
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
4,427
45
Please check out this [commit]() for solutions of biweekly 62. \n```\nclass Solution:\n def numOfPairs(self, nums: List[str], target: str) -> int:\n freq = Counter(nums)\n ans = 0 \n for k, v in freq.items(): \n if target.startswith(k): \n suffix = target[len(k):]\n ans += v * freq[suffix]\n if k == suffix: ans -= freq[suffix]\n return ans \n```
101,274
Number of Pairs of Strings With Concatenation Equal to Target
number-of-pairs-of-strings-with-concatenation-equal-to-target
Given an array of digit strings nums and a digit string target, return the number of pairs of indices (i, j) (where i != j) such that the concatenation of nums[i] + nums[j] equals target.
Array,String
Medium
Try to concatenate every two different strings from the list. Count the number of pairs with concatenation equals to target.
1,065
5
```\nclass Solution:\n def numOfPairs(self, nums, target):\n return sum(i + j == target for i, j in permutations(nums, 2))\n```
101,296
Maximum Number of Ways to Partition an Array
maximum-number-of-ways-to-partition-an-array
You are given a 0-indexed integer array nums of length n. The number of ways to partition nums is the number of pivot indices that satisfy both conditions: You are also given an integer k. You can choose to change the value of one element of nums to k, or to leave the array unchanged. Return the maximum possible number of ways to partition nums to satisfy both conditions after changing at most one element.
Array,Hash Table,Counting,Enumeration,Prefix Sum
Hard
A pivot point splits the array into equal prefix and suffix. If no change is made to the array, the goal is to find the number of pivot p such that prefix[p-1] == suffix[p]. Consider how prefix and suffix will change when we change a number nums[i] to k. When sweeping through each element, can you find the total number of pivots where the difference of prefix and suffix happens to equal to the changes of k-nums[i].
1,315
19
**Explanation**\n\n* For each pivot `p`, `1 <= p <= n-1`, we can test whether it is a valid partition point by checking whether `sum(nums[:p]) == sum(nums[p:])`, which can be determined in constant time after computing prefix sums.\n\n* If a pivot `p` is not valid, we compute `gap[p] = sum(nums[p:]) - sum(nums[:p])`. This `gap[p]` is how much we need to add to an element strictly before index `p`, or subtract from an element at or after index `p`, in order to make `p` a valid pivot.\n* Now, for each element `nums[i]`, find the number of valid pivots in the new array after changing `nums[i]` to `k`, or in other words, adding `k-nums[i]` at index `i`. \n* This value, for a fixed `i`, is the count of indices `j` with `j > i` that satisfy `gap[j] == k - nums[i]`, \nplus the number of indices `j` with `1 <= j <= i` such that `-gap[j] == k - nums[i]`. \n* Use two dictionaries (for earlier gap counts and later gap counts) plus a prefix sum array, and update the dictionaries as we traverse.\n\n\n**Complexity**\n\nTime complexity: `O(n)`, Space complexity `O(n)`\n\n**Python**\n\n```\nclass Solution:\n def waysToPartition(self, nums: List[int], k: int) -> int:\n prefix_sums = list(accumulate(nums))\n total_sum = prefix_sums[-1]\n best = 0\n if total_sum % 2 == 0:\n best = prefix_sums[:-1].count(total_sum // 2) # If no change\n\n after_counts = Counter(total_sum - 2 * prefix_sum\n for prefix_sum in prefix_sums[:-1])\n before_counts = Counter()\n\n best = max(best, after_counts[k - nums[0]]) # If we change first num\n\n for prefix, x in zip(prefix_sums, nums[1:]):\n gap = total_sum - 2 * prefix\n after_counts[gap] -= 1\n before_counts[gap] += 1\n\n best = max(best, after_counts[k - x] + before_counts[x - k])\n\n return best\n```\n\nEdit: Thanks to user @zeck008 for pointing out a swapped pair of inequality signs in the original explanation.
101,372
Final Value of Variable After Performing Operations
final-value-of-variable-after-performing-operations
There is a programming language with only four operations and one variable X: Initially, the value of X is 0. Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
Array,String,Simulation
Easy
There are only two operations to keep track of. Use a variable to store the value after each operation.
5,443
37
We can use simple python count function to get count value of given conditions\nand solve it very easily and with compact solution :\n\n```class Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n \n \n A=operations.count("++X")\n B=operations.count("X++")\n C=operations.count("--X") \n D=operations.count("X--")\n\t\t\n return A+B-C-D #it will automatically return the required results value\n```\n\nPlease Upvote if You Find this solution helpful\n
101,444
Final Value of Variable After Performing Operations
final-value-of-variable-after-performing-operations
There is a programming language with only four operations and one variable X: Initially, the value of X is 0. Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
Array,String,Simulation
Easy
There are only two operations to keep track of. Use a variable to store the value after each operation.
1,768
5
Checking for specifis \n\n```\nclass Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n X = 0\n for op in operations:\n if "+" in op: X+=1\n elif "-" in op: X-=1\n return X\n```\n\nOr you can see the pattern, here we only need to check the middle symbol as it won\'t be X in "X++", "X--","++X", "--X".\n\nThe middle will be different all the time.\n\n```\nclass Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n value = 0\n for i in operations:\n if i[1] == "+":\n value += 1\n else:\n value -= 1\n return value\n```
101,450
Final Value of Variable After Performing Operations
final-value-of-variable-after-performing-operations
There is a programming language with only four operations and one variable X: Initially, the value of X is 0. Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
Array,String,Simulation
Easy
There are only two operations to keep track of. Use a variable to store the value after each operation.
2,845
9
\n## Please Upvote if it Helps \uD83D\uDE4F\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# Code\n```\nclass Solution {\npublic:\n int finalValueAfterOperations(vector<string>& operations) {\n int n = operations.size() , X=0;\n for(int i=0;i<n;i++){\n if(operations[i]=="--X" || operations[i]=="X--" ) X--;\n else X++;\n }\n return X;\n }\n};\n```
101,452
Final Value of Variable After Performing Operations
final-value-of-variable-after-performing-operations
There is a programming language with only four operations and one variable X: Initially, the value of X is 0. Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations.
Array,String,Simulation
Easy
There are only two operations to keep track of. Use a variable to store the value after each operation.
2,532
13
```\nclass Solution:\n def finalValueAfterOperations(self, operations: List[str]) -> int:\n return reduce(lambda a, b: a + (1 if b[1] == \'+\' else -1) , operations, 0)\n```
101,461
Sum of Beauty in the Array
sum-of-beauty-in-the-array
You are given a 0-indexed integer array nums. For each index i (1 <= i <= nums.length - 2) the beauty of nums[i] equals: Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.
Array
Medium
Use suffix/prefix arrays. prefix[i] records the maximum value in range (0, i - 1) inclusive. suffix[i] records the minimum value in range (i + 1, n - 1) inclusive.
2,026
18
\n\n\n\n* **Case1**: for each index in nums if every element before this is smaller and every element after this is bigger \nthan we have to increase count by 2\nfor this can we can make two array which will store minimum and maximum till now for each index\n* **Case2**: simply compare with left and right neighbour ,if condition satisfies we will increase count by 1\n\n```\n\ndef sumOfBeauties(self, nums) :\n N=len(nums)\n \n # for each index we have to check if all element before it is smaller than this\n min_=[None for _ in range(N)]\n mi_=float(\'-inf\')\n for i in range(N):\n min_[i]=mi_\n mi_=max(nums[i],mi_)\n \n # for each index we have to check if all element after it is bigger than this \n max_=[None for _ in range(N)]\n mx_=float(\'inf\')\n for i in range(N-1,-1,-1):\n max_[i]=mx_\n mx_=min(mx_,nums[i])\n \n ans=0\n for i in range(1,N-1):\n if min_[i]<nums[i]<max_[i]:\n ans+=2\n elif nums[i-1]<nums[i]<nums[i+1]:\n ans+=1\n return ans\n```\n\t\t\n* **TC - O(N)**
101,476
Detect Squares
detect-squares
You are given a stream of points on the X-Y plane. Design an algorithm that: An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. Implement the DetectSquares class:
Array,Hash Table,Design,Counting
Medium
Maintain the frequency of all the points in a hash map. Traverse the hash map and if any point has the same y-coordinate as the query point, consider this point and the query point to form one of the horizontal lines of the square.
1,201
8
# Please upvote if helpful!\n\n# Approach\n**Adding Points** - Since duplicate points can be used to form distinct, countable squares, we will use a dictionary to track the number of times that point has been added. In order for us to track the point in a dictionary, it must be hashable, so we will convert the point from a list (non-hashable) to a tuple (hashable).\n\n*Note: `defaultdict(int)` defaults to 0 for new values*\n\n\n**Counting Squares** - To reduce the amount of iterating, we loop through the items of `self.points` searching for points that can serve as the opposite corner of a square. For each such point found, we check if `self.points` contains the other two necessary corners. If so, we calculate how many identical squares can be created by multiplying the instances of each of the three points in `self.points`. We add this number to the running count, which we return once the for loop is completed.\n\n\n# Code\n```\nclass DetectSquares:\n\n def __init__(self):\n self.points = collections.defaultdict(int)\n\n def add(self, point: List[int]) -> None:\n self.points[tuple(point)] += 1\n\n def count(self, point: List[int]) -> int:\n square_count = 0\n x1, y1 = point\n\n for (x2, y2), n in self.points.items():\n x_dist, y_dist = abs(x1 - x2), abs(y1 - y2)\n if x_dist == y_dist and x_dist > 0:\n corner1 = (x1, y2)\n corner2 = (x2, y1)\n if corner1 in self.points and corner2 in self.points:\n square_count += n * self.points[corner1] * self.points[corner2]\n\n return square_count\n \n```
101,536
Detect Squares
detect-squares
You are given a stream of points on the X-Y plane. Design an algorithm that: An axis-aligned square is a square whose edges are all the same length and are either parallel or perpendicular to the x-axis and y-axis. Implement the DetectSquares class:
Array,Hash Table,Design,Counting
Medium
Maintain the frequency of all the points in a hash map. Traverse the hash map and if any point has the same y-coordinate as the query point, consider this point and the query point to form one of the horizontal lines of the square.
779
5
```\nclass DetectSquares:\n\n def __init__(self):\n self.mapp = {}\n \n def add(self, point: List[int]) -> None:\n if tuple(point) not in self.mapp:\n self.mapp[tuple(point)] = 0\n self.mapp[tuple(point)] += 1\n\n def count(self, point: List[int]) -> int:\n res = 0 \n px,py = point\n for x,y in self.mapp.keys():\n if abs(px - x) != abs(py - y) or px == x or py == y:\n continue\n if (x,py) in self.mapp and (px,y) in self.mapp:\n res += self.mapp[(x,py)] * self.mapp[(px,y)] * self.mapp[(x,y)]\n return res \n```
101,552
Longest Subsequence Repeated k Times
longest-subsequence-repeated-k-times
You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times. Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
String,Backtracking,Greedy,Counting,Enumeration
Hard
The length of the longest subsequence does not exceed n/k. Do you know why? Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times. Try all possible candidates in reverse lexicographic order, and check the string for the subsequence condition.
1,209
12
(It\'s my first time getting 4 questions in a contest lol.) \n\nSince each char has to appear at least k times, we only need to keep track of these `chars` (found in one pass).\n\nLet\'s keep a list of valid candidates `old_cand` that appear at least k times in string `s`. Initially, chunk length m=1, it\'s the same as `chars`. To get the next level (chunks of length m+1), try to append each character in the `chars` we found earlier, and if it is valid, add to `new_cand`. Do this until `new_cand` is empty, or maximum length `n/k` is reached. \n\n* In order to validate a subsequence t (repeated k times) in s, we just need O(n) string match. See `find()` below.\n* Finally, return the lexicographically largest candidate. Always try appending the largest valid char first, so we won\'t need to sort at the end.\n\n\n\n```\nclass Solution:\n def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n n = len(s)\n max_chunk_sz = n // k\n \n d = collections.Counter(s)\n chars = sorted([c for c in d if d[c] >= k], reverse=True)\n if not chars:\n return \'\'\n \n old_cand = chars\n for m in range(2, max_chunk_sz+1):\n new_cand = []\n for t in self.get_next_level(old_cand, chars):\n if self.find(s, t*k):\n new_cand.append(t)\n \n if len(new_cand) == 0:\n break\n old_cand = new_cand\n return old_cand[0]\n \n def get_next_level(self, cand, chars):\n for s in cand:\n for ch in chars:\n yield s + ch\n \n def find(self, s, t):\n # find subsequence t in s\n j = 0\n for i in range(len(s)):\n if s[i] == t[j]:\n j += 1\n if j == len(t):\n return True\n return False\n```
101,573
Longest Subsequence Repeated k Times
longest-subsequence-repeated-k-times
You are given a string s of length n, and an integer k. You are tasked to find the longest subsequence repeated k times in string s. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A subsequence seq is repeated k times in the string s if seq * k is a subsequence of s, where seq * k represents a string constructed by concatenating seq k times. Return the longest subsequence repeated k times in string s. If multiple such subsequences are found, return the lexicographically largest one. If there is no such subsequence, return an empty string.
String,Backtracking,Greedy,Counting,Enumeration
Hard
The length of the longest subsequence does not exceed n/k. Do you know why? Find the characters that could be included in the potential answer. A character occurring more than or equal to k times can be used in the answer up to (count of the character / k) times. Try all possible candidates in reverse lexicographic order, and check the string for the subsequence condition.
774
11
Please check out this [commit]() for solutions of weekly 259. \n```\nclass Solution:\n def longestSubsequenceRepeatedK(self, s: str, k: int) -> str:\n freq = [0] * 26\n for ch in s: freq[ord(ch)-97] += 1\n \n cand = [chr(i+97) for i, x in enumerate(freq) if x >= k] # valid candidates \n \n def fn(ss): \n """Return True if ss is a k-repeated sub-sequence of s."""\n i = cnt = 0\n for ch in s: \n if ss[i] == ch: \n i += 1\n if i == len(ss): \n if (cnt := cnt + 1) == k: return True \n i = 0\n return False \n \n ans = ""\n queue = deque([""])\n while queue: \n x = queue.popleft()\n for ch in cand: \n xx = x + ch\n if fn(xx): \n ans = xx\n queue.append(xx)\n return ans\n```
101,575
Maximum Difference Between Increasing Elements
maximum-difference-between-increasing-elements
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1.
Array
Easy
Could you keep track of the minimum element visited while traversing? We have a potential candidate for the answer if the prefix min is lesser than nums[i].
3,317
35
**Python :**\n\n```\ndef maximumDifference(self, nums: List[int]) -> int:\n\tmaxDiff = -1\n\n\tminNum = nums[0]\n\n\tfor i in range(len(nums)):\n\t\tmaxDiff = max(maxDiff, nums[i] - minNum)\n\t\tminNum = min(minNum, nums[i])\n\n\treturn maxDiff if maxDiff != 0 else -1\n```\n\n**Like it ? please upvote !**
101,628
Maximum Difference Between Increasing Elements
maximum-difference-between-increasing-elements
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1.
Array
Easy
Could you keep track of the minimum element visited while traversing? We have a potential candidate for the answer if the prefix min is lesser than nums[i].
4,935
30
**Similar Problem:** [121. Best Time to Buy and Sell Stock]()\n\n----\n\nTraverse input, compare current number to the minimum of the previous ones. then update the max difference.\n```java\n public int maximumDifference(int[] nums) {\n int diff = -1;\n for (int i = 1, min = nums[0]; i < nums.length; ++i) {\n if (nums[i] > min) {\n diff = Math.max(diff, nums[i] - min);\n }\n min = Math.min(min, nums[i]);\n }\n return diff;\n }\n```\n```python\n def maximumDifference(self, nums: List[int]) -> int:\n diff, mi = -1, math.inf\n for i, n in enumerate(nums):\n if i > 0 and n > mi:\n diff = max(diff, n - mi) \n mi = min(mi, n)\n return diff \n```
101,629
Maximum Difference Between Increasing Elements
maximum-difference-between-increasing-elements
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j]. Return the maximum difference. If no such i and j exists, return -1.
Array
Easy
Could you keep track of the minimum element visited while traversing? We have a potential candidate for the answer if the prefix min is lesser than nums[i].
1,036
6
Please check out this [commit]() for solutions of weekly 260. \n```\nclass Solution:\n def maximumDifference(self, nums: List[int]) -> int:\n ans = -1 \n prefix = inf\n for i, x in enumerate(nums): \n if i and x > prefix: ans = max(ans, x - prefix)\n prefix = min(prefix, x)\n return ans \n```
101,655
Grid Game
grid-game
You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)). At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another. The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.
Array,Matrix,Prefix Sum
Medium
There are n choices for when the first robot moves to the second row. Can we use prefix sums to help solve this problem?
6,796
81
Since the robots cannot go up, we need to find the best point `i` for the first robot to go down. \n\nFor the second robot, we only have two choices - go down right away, or stay up till the end.\n\nFor a point `i`, the second robot can either collect `bottom = sum(grid[1][0] .. grid[1][i - 1])` if it goes down, or `top = sum(grid[0][i + 1] ... grid[0][n - 1])` otherwise.\n\nWe can compute those values using prefix/suffix sum in O(1), and then find the minimum of `max(top, bottom)`.\n\n> Note that the prefix/suffix sum can overflow int, so we need to use a 64-bit integer in C++ and Java.\n\n**Python 3**\n```python\nclass Solution:\n def gridGame(self, g: List[List[int]]) -> int:\n top, bottom, res = sum(g[0]), 0, math.inf\n for g0, g1 in zip(g[0], g[1]):\n top -= g0\n res = min(res, max(top, bottom))\n bottom += g1\n return res\n```\n\n**Java**\n```java\npublic long gridGame(int[][] g) {\n long top = Arrays.stream(g[0]).asLongStream().sum(), bottom = 0, res = Long.MAX_VALUE;\n for(int i = 0; i < g[0].length; ++i) {\n top -= g[0][i];\n res = Math.min(res, Math.max(top, bottom));\n bottom += g[1][i];\n }\n return res; \n}\n```\n\n**C++**\n```cpp\nlong long gridGame(vector<vector<int>>& g) {\n long long top = accumulate(begin(g[0]), end(g[0]), 0ll), bottom = 0, res = LLONG_MAX;\n for(int i = 0; i < g[0].size(); ++i) {\n top -= g[0][i];\n res = min(res, max(top, bottom));\n bottom += g[1][i];\n }\n return res;\n}\n```
101,672
Grid Game
grid-game
You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)). At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another. The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.
Array,Matrix,Prefix Sum
Medium
There are n choices for when the first robot moves to the second row. Can we use prefix sums to help solve this problem?
1,450
13
Key observation: **Robot 2 can ONLY choose the lower left part or the upper right part of the the column that Rob 1 traversed.** Therefore, we compute the *max values* of the two parts when traversing the two-cell-columns from left and right. The mininum out of the afore-mentioned *max values* is the solution.\n```java\n public long gridGame(int[][] grid) {\n long ans = Long.MAX_VALUE, lowerLeft = 0, upperRight = IntStream.of(grid[0]).mapToLong(i -> i).sum();\n for (int i = 0; i < grid[0].length; ++i) {\n upperRight -= grid[0][i];\n ans = Math.min(ans, Math.max(upperRight, lowerLeft));\n lowerLeft += grid[1][i];\n }\n return ans;\n }\n```\nPer **@aravinth3108**\'s suggestion, the following code might be more friendly to the beginners:\n\n```java\n public long gridGame(int[][] grid) {\n long ans = Long.MAX_VALUE, lowerLeft = 0, upperRight = 0;\n for (int cell : grid[0]) {\n upperRight += cell;\n }\n for (int i = 0; i < grid[0].length; ++i) {\n upperRight -= grid[0][i];\n ans = Math.min(ans, Math.max(upperRight, lowerLeft));\n lowerLeft += grid[1][i];\n }\n return ans;\n }\n```\n\n----\n\n```python\n def gridGame(self, grid: List[List[int]]) -> int:\n upper_right, lower_left, ans = sum(grid[0]), 0, math.inf\n for upper, lower in zip(grid[0], grid[1]):\n upper_right -= upper\n ans = min(ans, max(upper_right, lower_left))\n lower_left += lower\n return ans\n```\n**Analysis:**\n\nTime: `O(n)`, space: `O(1)`, where `n = grid[0].length`.
101,685
Grid Game
grid-game
You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix. Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)). At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another. The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.
Array,Matrix,Prefix Sum
Medium
There are n choices for when the first robot moves to the second row. Can we use prefix sums to help solve this problem?
672
5
Logic:\n\n* The constraints state that there are exactly 2 rows in the grid.\n\n* Therefore, player1 must go down in the grid at somepoint and only once. \n\n* Because Player1 must go down in the grid. If Player1 decides to go down at index i, this leaves all the indexes i+1 onwards open for the taking in the first row.\n\n * Conversely, if player1 goes down in the grid at point i, this will leave all the indexes from 0 to i-1 open for the taking on the second row (They cannot move left). \n \n * Therefore if we have an example where player1 decides to move downwards in the grid at index 5, we can calculate the max score of player2 as max(suffix[5], prefix[5]). Where the suffix is them choosing to take the remaining elements on the top row, and the prefix is them choosing to take the remaining elements left on the second row.\n\n---\n\nPopulate a prefix and a suffix array and then iterate through. Player2 will be attempting to take the max of the prefix/suffix sum at index i, and player1 will be attempting to minimize this amount for all the possibilities.\n\nHopefully the code makes it more clear.\n\n```\nclass Solution:\n def gridGame(self, grid: List[List[int]]) -> int:\n \n #Populate a suffix sum array\n suffix = [ele for ele in grid[0]]\n suffixSum = 0\n for i in range(len(suffix)-1,-1,-1):\n suffix[i] = suffixSum\n suffixSum += grid[0][i]\n \n \n #Populate a prefix sum array\n prefix = [ele for ele in grid[1]]\n prefixSum = 0\n for i in range(len(prefix)):\n prefix[i] = prefixSum\n prefixSum += grid[1][i] \n \n #Want the lowest of the worst-case scenerio.\n #Player 2 will attempt to pick the biggest of prefix[i] or suffix[i].\n #Player 1 will attempt to pick the case that will minimize this.\n lowest = float("inf")\n for i in range(len(prefix)):\n lowest = min(lowest, max(prefix[i], suffix[i]))\n \n return lowest\n```\n\nTime: O(N)\nSpace: O(N)\n\nCan be optimized to O(1) with sliding count for prefix/suffix, no need for Prefix/Suffix array in that case.
101,690