title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python Solution with 92% better Time Complexity
di-string-match
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n res = [0]*(len(s)+1)\n i,j = 0,len(s)\n for k in range(len(s)):\n if s[k] == "I":\n res[k] = i\n i+=1\n else:\n res[k] = j\n j-=1\n if s[-1] == "I":\n res[-1] = i\n else:\n res[-1] = j\n return res \n\n\n```
1
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return _the **minimum** number of moves required to make every node have **exactly** one coin_. **Example 1:** **Input:** root = \[3,0,0\] **Output:** 2 **Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child. **Example 2:** **Input:** root = \[0,3,0\] **Output:** 3 **Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child. **Constraints:** * The number of nodes in the tree is `n`. * `1 <= n <= 100` * `0 <= Node.val <= n` * The sum of all `Node.val` is `n`.
null
Solution
di-string-match
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> diStringMatch(string s) {\n int n = s.length();\n vector<int>v;\n int j = n;\n int k = 0;\n for(int i = 0;i<n+1;i++){\n if(s[i]==\'I\'){\n v.push_back(k);\n k++;\n }\n else if(s[i]==\'D\'){\n v.push_back(j);\n j--;}\n }\n v.push_back(k);\n return v;}\n};\n```\n\n```Python3 []\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n ans = []\n low = 0\n high = len(s)\n for c in s:\n if c == \'I\':\n ans.append(low)\n low+=1\n else:\n ans.append(high)\n high-=1\n return ans + [high]\n```\n\n```Java []\nclass Solution {\n public int[] diStringMatch(String s) {\n int len = s.length(),b=0,e=len,i=0;\n int res[]= new int[len+1];\n int id=-1;\n char ch[]=s.toCharArray();\n for(i=0;i<len;i++){\n if(ch[i]==\'I\'){\n res[i]=b;\n b++;\n }\n else{\n res[i]=e;\n e--;\n }\n }\n res[i]=b;\n return res;\n }\n}\n```\n
2
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
Solution
di-string-match
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> diStringMatch(string s) {\n int n = s.length();\n vector<int>v;\n int j = n;\n int k = 0;\n for(int i = 0;i<n+1;i++){\n if(s[i]==\'I\'){\n v.push_back(k);\n k++;\n }\n else if(s[i]==\'D\'){\n v.push_back(j);\n j--;}\n }\n v.push_back(k);\n return v;}\n};\n```\n\n```Python3 []\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n ans = []\n low = 0\n high = len(s)\n for c in s:\n if c == \'I\':\n ans.append(low)\n low+=1\n else:\n ans.append(high)\n high-=1\n return ans + [high]\n```\n\n```Java []\nclass Solution {\n public int[] diStringMatch(String s) {\n int len = s.length(),b=0,e=len,i=0;\n int res[]= new int[len+1];\n int id=-1;\n char ch[]=s.toCharArray();\n for(i=0;i<len;i++){\n if(ch[i]==\'I\'){\n res[i]=b;\n b++;\n }\n else{\n res[i]=e;\n e--;\n }\n }\n res[i]=b;\n return res;\n }\n}\n```\n
2
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return _the **minimum** number of moves required to make every node have **exactly** one coin_. **Example 1:** **Input:** root = \[3,0,0\] **Output:** 2 **Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child. **Example 2:** **Input:** root = \[0,3,0\] **Output:** 3 **Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child. **Constraints:** * The number of nodes in the tree is `n`. * `1 <= n <= 100` * `0 <= Node.val <= n` * The sum of all `Node.val` is `n`.
null
[Python3] Simple And Readable Solution
di-string-match
0
1
```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n ans = []\n a , b = 0 , len(s)\n \n for i in s:\n if(i == \'I\'):\n ans.append(a)\n a += 1\n else:\n ans.append(b)\n b -= 1\n \n if(s[-1] == \'D\'):\n ans.append(a)\n else:\n ans.append(b)\n \n return ans\n```
7
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
[Python3] Simple And Readable Solution
di-string-match
0
1
```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n ans = []\n a , b = 0 , len(s)\n \n for i in s:\n if(i == \'I\'):\n ans.append(a)\n a += 1\n else:\n ans.append(b)\n b -= 1\n \n if(s[-1] == \'D\'):\n ans.append(a)\n else:\n ans.append(b)\n \n return ans\n```
7
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return _the **minimum** number of moves required to make every node have **exactly** one coin_. **Example 1:** **Input:** root = \[3,0,0\] **Output:** 2 **Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child. **Example 2:** **Input:** root = \[0,3,0\] **Output:** 3 **Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child. **Constraints:** * The number of nodes in the tree is `n`. * `1 <= n <= 100` * `0 <= Node.val <= n` * The sum of all `Node.val` is `n`.
null
DI String Match (simple solution)
di-string-match
0
1
# class Solution:\n def diStringMatch(self, s: str) -> List[int]:\n l=len(s)\n a=-1\n b=l+1\n c=0\n v=[]\n for i in s:\n if i==\'I\':\n a+=1\n c+=1\n v.append(a)\n else:\n b-=1\n v.append(b)\n v.append(c)\n return v\n
1
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
DI String Match (simple solution)
di-string-match
0
1
# class Solution:\n def diStringMatch(self, s: str) -> List[int]:\n l=len(s)\n a=-1\n b=l+1\n c=0\n v=[]\n for i in s:\n if i==\'I\':\n a+=1\n c+=1\n v.append(a)\n else:\n b-=1\n v.append(b)\n v.append(c)\n return v\n
1
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return _the **minimum** number of moves required to make every node have **exactly** one coin_. **Example 1:** **Input:** root = \[3,0,0\] **Output:** 2 **Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child. **Example 2:** **Input:** root = \[0,3,0\] **Output:** 3 **Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child. **Constraints:** * The number of nodes in the tree is `n`. * `1 <= n <= 100` * `0 <= Node.val <= n` * The sum of all `Node.val` is `n`.
null
Very simple solution in python, with explanations
di-string-match
0
1
the solution can be achieved with a combination of two steps:\n\n=> proceeding forward from s (s=0)\n=> proceeding backwards from l (l = length of string)\nthe code explains the rest. \n\nafter the loop breaks, you still have one more number to append, which that should be?\nEasy! after the loop terminates, s==l, so append any one. and you\'re good to go \n\n```\ndef diStringMatch(self, S: str) -> List[int]:\n\ts, l = 0, len(S)\n\tres = []\n\tfor c in S:\n\t\tif c=="I":\n\t\t\tres.append(s)\n\t\t\ts+=1\n\t\telse:\n\t\t\tres.append(l)\n\t\t\tl-=1\n\tres.append(s)\n\treturn res\n```
14
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
Very simple solution in python, with explanations
di-string-match
0
1
the solution can be achieved with a combination of two steps:\n\n=> proceeding forward from s (s=0)\n=> proceeding backwards from l (l = length of string)\nthe code explains the rest. \n\nafter the loop breaks, you still have one more number to append, which that should be?\nEasy! after the loop terminates, s==l, so append any one. and you\'re good to go \n\n```\ndef diStringMatch(self, S: str) -> List[int]:\n\ts, l = 0, len(S)\n\tres = []\n\tfor c in S:\n\t\tif c=="I":\n\t\t\tres.append(s)\n\t\t\ts+=1\n\t\telse:\n\t\t\tres.append(l)\n\t\t\tl-=1\n\tres.append(s)\n\treturn res\n```
14
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return _the **minimum** number of moves required to make every node have **exactly** one coin_. **Example 1:** **Input:** root = \[3,0,0\] **Output:** 2 **Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child. **Example 2:** **Input:** root = \[0,3,0\] **Output:** 3 **Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child. **Constraints:** * The number of nodes in the tree is `n`. * `1 <= n <= 100` * `0 <= Node.val <= n` * The sum of all `Node.val` is `n`.
null
Solution
find-the-shortest-superstring
1
1
```C++ []\nclass Solution {\npublic:\n string shortestSuperstring(vector<string>& A) {\n int dp[4096][12] = {0};\n int failure[12][20] = {0};\n int cost[12][12] = {0};\n int trace_table[4096][12] = {0};\n const int sz = A.size();\n const int dp_sz = 1 << sz;\n \n for (int i = 0; i < sz; i++) {\n const int str_sz = A[i].size();\n \n failure[i][0] = -1;\n \n for (int j = 1, k = -1; j < str_sz; j++) {\n while (k >= 0 && A[i][k + 1] != A[i][j])\n k = failure[i][k];\n \n if (A[i][k + 1] == A[i][j]) k++;\n \n failure[i][j] = k;\n }\n }\n for (int i = 0; i < sz; i++) {\n const int i_sz = A[i].size();\n \n for (int j = 0; j < sz; j++) {\n if (i != j) {\n const int j_sz = A[j].size();\n int h = -1;\n \n for (int k = 0; k < j_sz; k++) {\n while (h >= 0 && A[i][h + 1] != A[j][k])\n h = failure[i][h];\n \n if (A[i][h + 1] == A[j][k])\n h++;\n }\n cost[j][i] = i_sz - h - 1;\n }\n }\n }\n for (int i = 0; i < sz; i++)\n dp[1 << i][i] = A[i].size();\n \n for (int state = 1; state < dp_sz; state++) {\n for (int t1 = state, b1 = t1 & (-t1); t1 ; t1 ^= b1 , b1 = t1 & (-t1)) {\n const int state1 = state ^ b1;\n const int i = __builtin_ctz(b1);\n const int i_sz = A[i].size();\n \n for (int t2 = state1, b2 = t2 & (-t2); t2; t2 ^= b2, b2 = t2 & (-t2)) { \n const int j = __builtin_ctz(b2);\n const int tmp = dp[state1][j] + cost[j][i];\n \n if (!dp[state][i] || tmp < dp[state][i]) {\n dp[state][i] = tmp;\n trace_table[state][i] = j;\n }\n }\n }\n }\n const auto& last = dp[dp_sz - 1];\n string res;\n int i = std::distance(last, std::min_element(last, last + sz));\n \n for (int state = dp_sz - 1, j = trace_table[state][i]; state & (state - 1); state ^= (1 << i), i = j, j = trace_table[state][i])\n res = A[i].substr(A[i].size() - cost[j][i]) + res;\n \n return A[i] + res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n def getMinSuffix(w1, w2):\n n = min(len(w1), len(w2))\n for i in range(n, 0, -1):\n if w1[-i:] == w2[:i]:\n return w2[i:]\n return w2\n\n n = len(words)\n suffix = defaultdict(dict)\n for i in range(n):\n for j in range(n):\n suffix[i][j] = getMinSuffix(words[i], words[j])\n dp = [[\'\']*n for _ in range(1<<n)]\n for i in range(1, 1<<n):\n indexes = [j for j in range(n) if i&(1<<j)]\n for j in indexes:\n i2 = i&~(1<<j)\n strs = [dp[i2][j2]+suffix[j2][j] for j2 in indexes if j2 != j]\n dp[i][j] = min(strs, key=len) if strs else words[j]\n return min(dp[-1], key=len)\n```\n\n```Java []\nclass Solution {\n public String shortestSuperstring(String[] words) {\n int n = words.length;\n int[][] mat = new int[n][n];\n for (int i = 0; i < n; i++) \n for (int j = i+1; j < n; j++) {\n mat[i][j] = dist(words[i], words[j]);\n mat[j][i] = dist(words[j], words[i]);\n }\n int[][] dp = new int[1<<n][n];\n for (int[] row : dp)\n Arrays.fill(row, Integer.MAX_VALUE / 2);\n\n int[][] parents = new int[1<<n][n];\n for (int[] row : parents) \n Arrays.fill(row, -1);\n\n for (int i = 0; i < n; i++) \n dp[1<<i][i] = words[i].length();\n\n int min = Integer.MAX_VALUE;\n int cur = 0;\n for (int s = 1 ; s < (1<<n); s++) {\n for (int i = 0; i < n; i++) {\n if ((s & (1 <<i)) == 0) continue;\n int prevS = s & ~(1 << i);\n for (int j = 0; j < n; j++) {// i comes from j;\n if (dp[prevS][j] + mat[j][i] < dp[s][i]) {\n dp[s][i] = dp[prevS][j] + mat[j][i];\n parents[s][i] = j;\n }\n }\n if (s == (1<<n) - 1 && dp[s][i] < min) {\n min = dp[s][i];\n cur = i;\n } \n } \n }\n int s = (1<<n) - 1;\n String ans = "";\n while (s > 0 ) {\n int prev = parents[s][cur];\n if (prev < 0) ans = words[cur] + ans;\n else ans = words[cur].substring(words[cur].length() - mat[prev][cur]) + ans;\n s &= ~(1 << cur);\n cur = prev;\n }\n return ans;\n }\n private int dist(String a, String b) {\n int d = b.length();\n for (int k = 1; k <= Math.min(a.length(), b.length()); k++) {\n if (a.endsWith(b.substring(0, k)))\n d = b.length() - k;\n }\n return d;\n }\n}\n```\n
1
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Solution
find-the-shortest-superstring
1
1
```C++ []\nclass Solution {\npublic:\n string shortestSuperstring(vector<string>& A) {\n int dp[4096][12] = {0};\n int failure[12][20] = {0};\n int cost[12][12] = {0};\n int trace_table[4096][12] = {0};\n const int sz = A.size();\n const int dp_sz = 1 << sz;\n \n for (int i = 0; i < sz; i++) {\n const int str_sz = A[i].size();\n \n failure[i][0] = -1;\n \n for (int j = 1, k = -1; j < str_sz; j++) {\n while (k >= 0 && A[i][k + 1] != A[i][j])\n k = failure[i][k];\n \n if (A[i][k + 1] == A[i][j]) k++;\n \n failure[i][j] = k;\n }\n }\n for (int i = 0; i < sz; i++) {\n const int i_sz = A[i].size();\n \n for (int j = 0; j < sz; j++) {\n if (i != j) {\n const int j_sz = A[j].size();\n int h = -1;\n \n for (int k = 0; k < j_sz; k++) {\n while (h >= 0 && A[i][h + 1] != A[j][k])\n h = failure[i][h];\n \n if (A[i][h + 1] == A[j][k])\n h++;\n }\n cost[j][i] = i_sz - h - 1;\n }\n }\n }\n for (int i = 0; i < sz; i++)\n dp[1 << i][i] = A[i].size();\n \n for (int state = 1; state < dp_sz; state++) {\n for (int t1 = state, b1 = t1 & (-t1); t1 ; t1 ^= b1 , b1 = t1 & (-t1)) {\n const int state1 = state ^ b1;\n const int i = __builtin_ctz(b1);\n const int i_sz = A[i].size();\n \n for (int t2 = state1, b2 = t2 & (-t2); t2; t2 ^= b2, b2 = t2 & (-t2)) { \n const int j = __builtin_ctz(b2);\n const int tmp = dp[state1][j] + cost[j][i];\n \n if (!dp[state][i] || tmp < dp[state][i]) {\n dp[state][i] = tmp;\n trace_table[state][i] = j;\n }\n }\n }\n }\n const auto& last = dp[dp_sz - 1];\n string res;\n int i = std::distance(last, std::min_element(last, last + sz));\n \n for (int state = dp_sz - 1, j = trace_table[state][i]; state & (state - 1); state ^= (1 << i), i = j, j = trace_table[state][i])\n res = A[i].substr(A[i].size() - cost[j][i]) + res;\n \n return A[i] + res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n def getMinSuffix(w1, w2):\n n = min(len(w1), len(w2))\n for i in range(n, 0, -1):\n if w1[-i:] == w2[:i]:\n return w2[i:]\n return w2\n\n n = len(words)\n suffix = defaultdict(dict)\n for i in range(n):\n for j in range(n):\n suffix[i][j] = getMinSuffix(words[i], words[j])\n dp = [[\'\']*n for _ in range(1<<n)]\n for i in range(1, 1<<n):\n indexes = [j for j in range(n) if i&(1<<j)]\n for j in indexes:\n i2 = i&~(1<<j)\n strs = [dp[i2][j2]+suffix[j2][j] for j2 in indexes if j2 != j]\n dp[i][j] = min(strs, key=len) if strs else words[j]\n return min(dp[-1], key=len)\n```\n\n```Java []\nclass Solution {\n public String shortestSuperstring(String[] words) {\n int n = words.length;\n int[][] mat = new int[n][n];\n for (int i = 0; i < n; i++) \n for (int j = i+1; j < n; j++) {\n mat[i][j] = dist(words[i], words[j]);\n mat[j][i] = dist(words[j], words[i]);\n }\n int[][] dp = new int[1<<n][n];\n for (int[] row : dp)\n Arrays.fill(row, Integer.MAX_VALUE / 2);\n\n int[][] parents = new int[1<<n][n];\n for (int[] row : parents) \n Arrays.fill(row, -1);\n\n for (int i = 0; i < n; i++) \n dp[1<<i][i] = words[i].length();\n\n int min = Integer.MAX_VALUE;\n int cur = 0;\n for (int s = 1 ; s < (1<<n); s++) {\n for (int i = 0; i < n; i++) {\n if ((s & (1 <<i)) == 0) continue;\n int prevS = s & ~(1 << i);\n for (int j = 0; j < n; j++) {// i comes from j;\n if (dp[prevS][j] + mat[j][i] < dp[s][i]) {\n dp[s][i] = dp[prevS][j] + mat[j][i];\n parents[s][i] = j;\n }\n }\n if (s == (1<<n) - 1 && dp[s][i] < min) {\n min = dp[s][i];\n cur = i;\n } \n } \n }\n int s = (1<<n) - 1;\n String ans = "";\n while (s > 0 ) {\n int prev = parents[s][cur];\n if (prev < 0) ans = words[cur] + ans;\n else ans = words[cur].substring(words[cur].length() - mat[prev][cur]) + ans;\n s &= ~(1 << cur);\n cur = prev;\n }\n return ans;\n }\n private int dist(String a, String b) {\n int d = b.length();\n for (int k = 1; k <= Math.min(a.length(), b.length()); k++) {\n if (a.endsWith(b.substring(0, k)))\n d = b.length() - k;\n }\n return d;\n }\n}\n```\n
1
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Easy to understand TSP implementation (Top-Down/Bottom-Up)[python]
find-the-shortest-superstring
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nConsider this problem as a graph problem where we need to visit every single node with the minimal overall cost. The words will be our nodes and the nonOverlapping substring between two words will be our cost.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n^2 * 2^n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n * 2^n)$$\n\n# Code\n\n### Easy to understand - Top-Down DP\n```\nclass Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n n = len(words)\n overlap = [[\'\'] * n for _ in range(n)]\n\n def getOverlap(a, b):\n l, i = 0, 1\n while i <= min(len(a), len(b)):\n if a[len(a)-i:] == b[:i]:\n l = i\n i += 1\n return b[l:]\n\n for i in range(n):\n for j in range(n):\n if i != j: overlap[i][j] = getOverlap(words[i], words[j])\n\n def TSP(prev, mask, dp):\n if (prev, mask) in dp: return dp[(prev, mask)]\n if mask == ((1 << n) - 1): return \'\'\n ans = \'*\' * 1000000\n for i in range(n):\n if mask & (1 << i): continue\n word = overlap[prev][i] if prev != -1 else words[i]\n ans = min(ans, word + TSP(i, mask | (1 << i), dp), key=len)\n dp[(prev, mask)] = ans\n return ans\n\n return TSP(-1, 0, {})\n```\n\n### Bottom-Up DP\nNotice here that we apply a push-dp instead of a pull-dp. That is because, there is no way for us to know in advance what the best string would be for a mask (7) or (111) where all the strings will be included where n = 3.\n\nTherefore we start with a base case where only one string will be included and we build our dp by pushing values forward in the mask.\n\nFinally, we get the minimum string with all words included (mask = ($$2^n - 1$$))\n```\nclass Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n n = len(words)\n overlap = [[\'\'] * n for _ in range(n)]\n\n def getOverlap(a, b):\n l, i = 0, 1\n while i <= min(len(a), len(b)):\n if a[len(a)-i:] == b[:i]:\n l = i\n i += 1\n return b[l:]\n\n for i in range(n):\n for j in range(n):\n if i != j: overlap[i][j] = getOverlap(words[i], words[j])\n ans = \'*\' * (10**4)\n dp = [[ans] * (1 << n) for _ in range(n)]\n for i in range(n): dp[i][(1 << i)] = words[i]\n\n for mask in range(1, 1 << n):\n for i in range(n):\n if mask & (1 << i):\n for j in range(n):\n if i != j and mask & (1 << j): continue\n dp[j][mask | (1 << j)] = min(dp[j][mask | (1 << j)], dp[i][mask] + overlap[i][j], key=len)\n\n for i in range(n): ans = min(ans, dp[i][(1 << n) - 1], key=len)\n return ans\n```
0
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Easy to understand TSP implementation (Top-Down/Bottom-Up)[python]
find-the-shortest-superstring
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nConsider this problem as a graph problem where we need to visit every single node with the minimal overall cost. The words will be our nodes and the nonOverlapping substring between two words will be our cost.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n^2 * 2^n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n * 2^n)$$\n\n# Code\n\n### Easy to understand - Top-Down DP\n```\nclass Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n n = len(words)\n overlap = [[\'\'] * n for _ in range(n)]\n\n def getOverlap(a, b):\n l, i = 0, 1\n while i <= min(len(a), len(b)):\n if a[len(a)-i:] == b[:i]:\n l = i\n i += 1\n return b[l:]\n\n for i in range(n):\n for j in range(n):\n if i != j: overlap[i][j] = getOverlap(words[i], words[j])\n\n def TSP(prev, mask, dp):\n if (prev, mask) in dp: return dp[(prev, mask)]\n if mask == ((1 << n) - 1): return \'\'\n ans = \'*\' * 1000000\n for i in range(n):\n if mask & (1 << i): continue\n word = overlap[prev][i] if prev != -1 else words[i]\n ans = min(ans, word + TSP(i, mask | (1 << i), dp), key=len)\n dp[(prev, mask)] = ans\n return ans\n\n return TSP(-1, 0, {})\n```\n\n### Bottom-Up DP\nNotice here that we apply a push-dp instead of a pull-dp. That is because, there is no way for us to know in advance what the best string would be for a mask (7) or (111) where all the strings will be included where n = 3.\n\nTherefore we start with a base case where only one string will be included and we build our dp by pushing values forward in the mask.\n\nFinally, we get the minimum string with all words included (mask = ($$2^n - 1$$))\n```\nclass Solution:\n def shortestSuperstring(self, words: List[str]) -> str:\n n = len(words)\n overlap = [[\'\'] * n for _ in range(n)]\n\n def getOverlap(a, b):\n l, i = 0, 1\n while i <= min(len(a), len(b)):\n if a[len(a)-i:] == b[:i]:\n l = i\n i += 1\n return b[l:]\n\n for i in range(n):\n for j in range(n):\n if i != j: overlap[i][j] = getOverlap(words[i], words[j])\n ans = \'*\' * (10**4)\n dp = [[ans] * (1 << n) for _ in range(n)]\n for i in range(n): dp[i][(1 << i)] = words[i]\n\n for mask in range(1, 1 << n):\n for i in range(n):\n if mask & (1 << i):\n for j in range(n):\n if i != j and mask & (1 << j): continue\n dp[j][mask | (1 << j)] = min(dp[j][mask | (1 << j)], dp[i][mask] + overlap[i][j], key=len)\n\n for i in range(n): ans = min(ans, dp[i][(1 << n) - 1], key=len)\n return ans\n```
0
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Shortest Solution
find-the-shortest-superstring
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def shortestSuperstring(self, A):\n """\n :type A: List[str]\n :rtype: str\n """\n # construct a directed graph\n # node i => A[i]\n # weights are represented as an adjacency matrix:\n # shared[i][j] => length saved by concatenating A[i] and A[j]\n n = len(A)\n shared = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n for k in range(min(len(A[i]), len(A[j])), -1, -1):\n if A[i][-k:] == A[j][:k]:\n shared[i][j] = k\n break\n\n # The problem becomes finding the shortest path that visits all nodes exactly once.\n # Brute force DFS would take O(n!) time.\n # A DP solution costs O(n^2 2^n) time.\n # \n # Let\'s consider integer from 0 to 2^n - 1. \n # Each i contains 0-n 1 bits. Hence each i selects a unique set of strings in A.\n # Let\'s denote set(i) => {A[j] | j-th bit of i is 1}\n # dp[i][k] => shortest superstring of set(i) ending with A[k]\n #\n # e.g. \n # if i = 6 i.e. 110 in binary. dp[6][k] considers superstring of A[2] and A[1].\n # dp[6][1] => the shortest superstring of {A[2], A[1]} ending with A[1].\n # For this simple case dp[6][1] = concatenate(A[2], A[1])\n dp = [[\'\'] * 12 for _ in range(1 << 12)]\n for i in range(1 << n):\n for k in range(n):\n # skip if A[k] is not in set(i) \n if not (i & (1 << k)):\n continue\n # if set(i) == {A[k]}\n if i == 1 << k:\n dp[i][k] = A[k]\n continue\n for j in range(n):\n if j == k:\n continue\n if i & (1 << j):\n # the shortest superstring if we remove A[k] from the set(i)\n s = dp[i ^ (1 << k)][j]\n s += A[k][shared[j][k]:]\n if dp[i][k] == \'\' or len(s) < len(dp[i][k]):\n dp[i][k] = s\n\n min_len = float(\'inf\')\n result = \'\'\n\n # find the shortest superstring of all candidates ending with different string\n for i in range(n):\n s = dp[(1 << n) - 1][i]\n if len(s) < min_len:\n min_len, result = len(s), s\n return result\n```
0
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Shortest Solution
find-the-shortest-superstring
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def shortestSuperstring(self, A):\n """\n :type A: List[str]\n :rtype: str\n """\n # construct a directed graph\n # node i => A[i]\n # weights are represented as an adjacency matrix:\n # shared[i][j] => length saved by concatenating A[i] and A[j]\n n = len(A)\n shared = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n for k in range(min(len(A[i]), len(A[j])), -1, -1):\n if A[i][-k:] == A[j][:k]:\n shared[i][j] = k\n break\n\n # The problem becomes finding the shortest path that visits all nodes exactly once.\n # Brute force DFS would take O(n!) time.\n # A DP solution costs O(n^2 2^n) time.\n # \n # Let\'s consider integer from 0 to 2^n - 1. \n # Each i contains 0-n 1 bits. Hence each i selects a unique set of strings in A.\n # Let\'s denote set(i) => {A[j] | j-th bit of i is 1}\n # dp[i][k] => shortest superstring of set(i) ending with A[k]\n #\n # e.g. \n # if i = 6 i.e. 110 in binary. dp[6][k] considers superstring of A[2] and A[1].\n # dp[6][1] => the shortest superstring of {A[2], A[1]} ending with A[1].\n # For this simple case dp[6][1] = concatenate(A[2], A[1])\n dp = [[\'\'] * 12 for _ in range(1 << 12)]\n for i in range(1 << n):\n for k in range(n):\n # skip if A[k] is not in set(i) \n if not (i & (1 << k)):\n continue\n # if set(i) == {A[k]}\n if i == 1 << k:\n dp[i][k] = A[k]\n continue\n for j in range(n):\n if j == k:\n continue\n if i & (1 << j):\n # the shortest superstring if we remove A[k] from the set(i)\n s = dp[i ^ (1 << k)][j]\n s += A[k][shared[j][k]:]\n if dp[i][k] == \'\' or len(s) < len(dp[i][k]):\n dp[i][k] = s\n\n min_len = float(\'inf\')\n result = \'\'\n\n # find the shortest superstring of all candidates ending with different string\n for i in range(n):\n s = dp[(1 << n) - 1][i]\n if len(s) < min_len:\n min_len, result = len(s), s\n return result\n```
0
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Smallest Solution
find-the-shortest-superstring
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def shortestSuperstring(self, A):\n """\n :type A: List[str]\n :rtype: str\n """\n # construct a directed graph\n # node i => A[i]\n # weights are represented as an adjacency matrix:\n # shared[i][j] => length saved by concatenating A[i] and A[j]\n n = len(A)\n shared = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n for k in range(min(len(A[i]), len(A[j])), -1, -1):\n if A[i][-k:] == A[j][:k]:\n shared[i][j] = k\n break\n\n # The problem becomes finding the shortest path that visits all nodes exactly once.\n # Brute force DFS would take O(n!) time.\n # A DP solution costs O(n^2 2^n) time.\n # \n # Let\'s consider integer from 0 to 2^n - 1. \n # Each i contains 0-n 1 bits. Hence each i selects a unique set of strings in A.\n # Let\'s denote set(i) => {A[j] | j-th bit of i is 1}\n # dp[i][k] => shortest superstring of set(i) ending with A[k]\n #\n # e.g. \n # if i = 6 i.e. 110 in binary. dp[6][k] considers superstring of A[2] and A[1].\n # dp[6][1] => the shortest superstring of {A[2], A[1]} ending with A[1].\n # For this simple case dp[6][1] = concatenate(A[2], A[1])\n dp = [[\'\'] * 12 for _ in range(1 << 12)]\n for i in range(1 << n):\n for k in range(n):\n # skip if A[k] is not in set(i) \n if not (i & (1 << k)):\n continue\n # if set(i) == {A[k]}\n if i == 1 << k:\n dp[i][k] = A[k]\n continue\n for j in range(n):\n if j == k:\n continue\n if i & (1 << j):\n # the shortest superstring if we remove A[k] from the set(i)\n s = dp[i ^ (1 << k)][j]\n s += A[k][shared[j][k]:]\n if dp[i][k] == \'\' or len(s) < len(dp[i][k]):\n dp[i][k] = s\n\n min_len = float(\'inf\')\n result = \'\'\n\n # find the shortest superstring of all candidates ending with different string\n for i in range(n):\n s = dp[(1 << n) - 1][i]\n if len(s) < min_len:\n min_len, result = len(s), s\n return result\n```
0
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Smallest Solution
find-the-shortest-superstring
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def shortestSuperstring(self, A):\n """\n :type A: List[str]\n :rtype: str\n """\n # construct a directed graph\n # node i => A[i]\n # weights are represented as an adjacency matrix:\n # shared[i][j] => length saved by concatenating A[i] and A[j]\n n = len(A)\n shared = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n for k in range(min(len(A[i]), len(A[j])), -1, -1):\n if A[i][-k:] == A[j][:k]:\n shared[i][j] = k\n break\n\n # The problem becomes finding the shortest path that visits all nodes exactly once.\n # Brute force DFS would take O(n!) time.\n # A DP solution costs O(n^2 2^n) time.\n # \n # Let\'s consider integer from 0 to 2^n - 1. \n # Each i contains 0-n 1 bits. Hence each i selects a unique set of strings in A.\n # Let\'s denote set(i) => {A[j] | j-th bit of i is 1}\n # dp[i][k] => shortest superstring of set(i) ending with A[k]\n #\n # e.g. \n # if i = 6 i.e. 110 in binary. dp[6][k] considers superstring of A[2] and A[1].\n # dp[6][1] => the shortest superstring of {A[2], A[1]} ending with A[1].\n # For this simple case dp[6][1] = concatenate(A[2], A[1])\n dp = [[\'\'] * 12 for _ in range(1 << 12)]\n for i in range(1 << n):\n for k in range(n):\n # skip if A[k] is not in set(i) \n if not (i & (1 << k)):\n continue\n # if set(i) == {A[k]}\n if i == 1 << k:\n dp[i][k] = A[k]\n continue\n for j in range(n):\n if j == k:\n continue\n if i & (1 << j):\n # the shortest superstring if we remove A[k] from the set(i)\n s = dp[i ^ (1 << k)][j]\n s += A[k][shared[j][k]:]\n if dp[i][k] == \'\' or len(s) < len(dp[i][k]):\n dp[i][k] = s\n\n min_len = float(\'inf\')\n result = \'\'\n\n # find the shortest superstring of all candidates ending with different string\n for i in range(n):\n s = dp[(1 << n) - 1][i]\n if len(s) < min_len:\n min_len, result = len(s), s\n return result\n```
0
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Traveling Salesman Problem Dynamic Programming Held-Karp + Video
find-the-shortest-superstring
0
1
# Intuition\nBefore going on solution please see this video:\n\n[Traveling Salesman Problem Dynamic Programming Held-Karp\n](https://www.youtube.com/watch?v=-JjA4BLQyqE)\n# Code\n```\nclass Solution:\n def get_cost(self, copy_set, prev_vertex, dp):\n copy_set.remove(prev_vertex)\n cost = dp[(prev_vertex, frozenset(copy_set))]\n copy_set.add(prev_vertex)\n return cost\n\n def get_all_combination(self, vertices):\n output = [set()]\n for vertex in vertices:\n for i in range(len(output)):\n current_set = set(output[i])\n current_set.add(vertex)\n output.append(current_set)\n\n return sorted(output, key=lambda x: len(x))\n\n def concatenate(self, a, b):\n if len(b) == 1:\n if a.endswith(b):\n return ""\n else:\n return b\n offset = 0\n for i in range(len(b)):\n if a.endswith(b[:i]):\n offset = i\n return b[offset:]\n\n def print_tour(self, parent, vertices, start, dp):\n _set = set()\n for vertex in vertices:\n _set.add(vertex)\n\n stack = []\n while True:\n stack.append(start)\n _set.remove(start)\n start = parent.get((start, frozenset(_set)), None)\n if not start:\n break\n\n path = stack[0]\n stack = stack[1:]\n for i in stack[::-1]:\n path += self.concatenate(path, i)\n\n return path\n\n def problem(self, start, words):\n dp = {}\n parent = {}\n vertices = []\n for word in words:\n if word != start:\n vertices.append(word)\n\n combinations = self.get_all_combination(vertices)\n\n for combination in combinations:\n for current_vertex in vertices:\n if current_vertex in combination:\n continue\n min_cost = math.inf\n min_prev_vertex = 0\n\n copy_set = set(combination)\n for prev_vertex in combination:\n cost = self.distance[(prev_vertex, current_vertex)] + self.get_cost(copy_set, prev_vertex, dp)\n if cost <= min_cost:\n min_cost = cost\n min_prev_vertex = prev_vertex\n\n if len(combination) == 0:\n min_cost = self.distance[(start, current_vertex)]\n dp[(current_vertex, frozenset(combination))] = min_cost\n parent[(current_vertex, frozenset(combination))] = min_prev_vertex\n\n _set = set()\n for vertex in vertices:\n _set.add(vertex)\n\n vertices.append(start)\n _min = math.inf\n prevVertex = -1\n copySet = set(_set)\n for k in _set:\n cost = self.get_cost(copySet, k, dp)\n if cost < _min:\n _min = cost\n prevVertex = k\n\n parent[(start, frozenset(_set))] = prevVertex\n\n return self.print_tour(parent, vertices, start, dp)\n\n def calc(self, a, b):\n for k in range(min(len(a), len(b)), 0, -1):\n if b.startswith(a[-k:]):\n return len(b[k:])\n return len(b)\n\n def shortestSuperstring(self, words: List[str]) -> str:\n if len(words) == 1:\n return words[0]\n self.distance = {}\n\n for i in words:\n for j in words:\n self.distance[(i, j)] = self.calc(i, j)\n self.distance[(j, i)] = self.calc(j, i)\n output = []\n for idx, v in enumerate(words):\n output.append(self.problem(v, words=words[:idx] + words[idx + 1:]))\n\n output = sorted(output, key=lambda x: len(x))\n return output[0]\n```
0
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Traveling Salesman Problem Dynamic Programming Held-Karp + Video
find-the-shortest-superstring
0
1
# Intuition\nBefore going on solution please see this video:\n\n[Traveling Salesman Problem Dynamic Programming Held-Karp\n](https://www.youtube.com/watch?v=-JjA4BLQyqE)\n# Code\n```\nclass Solution:\n def get_cost(self, copy_set, prev_vertex, dp):\n copy_set.remove(prev_vertex)\n cost = dp[(prev_vertex, frozenset(copy_set))]\n copy_set.add(prev_vertex)\n return cost\n\n def get_all_combination(self, vertices):\n output = [set()]\n for vertex in vertices:\n for i in range(len(output)):\n current_set = set(output[i])\n current_set.add(vertex)\n output.append(current_set)\n\n return sorted(output, key=lambda x: len(x))\n\n def concatenate(self, a, b):\n if len(b) == 1:\n if a.endswith(b):\n return ""\n else:\n return b\n offset = 0\n for i in range(len(b)):\n if a.endswith(b[:i]):\n offset = i\n return b[offset:]\n\n def print_tour(self, parent, vertices, start, dp):\n _set = set()\n for vertex in vertices:\n _set.add(vertex)\n\n stack = []\n while True:\n stack.append(start)\n _set.remove(start)\n start = parent.get((start, frozenset(_set)), None)\n if not start:\n break\n\n path = stack[0]\n stack = stack[1:]\n for i in stack[::-1]:\n path += self.concatenate(path, i)\n\n return path\n\n def problem(self, start, words):\n dp = {}\n parent = {}\n vertices = []\n for word in words:\n if word != start:\n vertices.append(word)\n\n combinations = self.get_all_combination(vertices)\n\n for combination in combinations:\n for current_vertex in vertices:\n if current_vertex in combination:\n continue\n min_cost = math.inf\n min_prev_vertex = 0\n\n copy_set = set(combination)\n for prev_vertex in combination:\n cost = self.distance[(prev_vertex, current_vertex)] + self.get_cost(copy_set, prev_vertex, dp)\n if cost <= min_cost:\n min_cost = cost\n min_prev_vertex = prev_vertex\n\n if len(combination) == 0:\n min_cost = self.distance[(start, current_vertex)]\n dp[(current_vertex, frozenset(combination))] = min_cost\n parent[(current_vertex, frozenset(combination))] = min_prev_vertex\n\n _set = set()\n for vertex in vertices:\n _set.add(vertex)\n\n vertices.append(start)\n _min = math.inf\n prevVertex = -1\n copySet = set(_set)\n for k in _set:\n cost = self.get_cost(copySet, k, dp)\n if cost < _min:\n _min = cost\n prevVertex = k\n\n parent[(start, frozenset(_set))] = prevVertex\n\n return self.print_tour(parent, vertices, start, dp)\n\n def calc(self, a, b):\n for k in range(min(len(a), len(b)), 0, -1):\n if b.startswith(a[-k:]):\n return len(b[k:])\n return len(b)\n\n def shortestSuperstring(self, words: List[str]) -> str:\n if len(words) == 1:\n return words[0]\n self.distance = {}\n\n for i in words:\n for j in words:\n self.distance[(i, j)] = self.calc(i, j)\n self.distance[(j, i)] = self.calc(j, i)\n output = []\n for idx, v in enumerate(words):\n output.append(self.problem(v, words=words[:idx] + words[idx + 1:]))\n\n output = sorted(output, key=lambda x: len(x))\n return output[0]\n```
0
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Python | DP with memo to solve TSP, fully explained~
find-the-shortest-superstring
0
1
# FIRST THING FIRST\r\nVote me if you like this solution~\r\n\r\n# Intuition\r\nThis is actually a "Traveling Salesman Problem" if we consider each word as a city\r\nAnd the `ticket price` (or `cost`, more generalized) from city to city is the `number of chars` we need to add if we append that word\r\n\r\n# DP analysis of TSP\r\nmake `TSP(used, i)`: the minimum cost from words 0 to words i, with used words\r\n- optimal substructure:\r\n```\r\nTSP(used, i) = { cost(0, i) if range(len(used)==1) and i!=0\r\n { min( TSP(used-j, j) + cost(j, i) | for j in used and j != i)\r\nhere we treat {used} as a *set*, but we\'ll use bits in code for convenient\r\n```\r\n- overlap subproblems: YES\r\n- no after effect: NO\r\n\r\n# Approach\r\n0. add a word \'~\' as index 0, this word means we came from nowhere, and should\'t contain any lowercase English letters\r\n1. building cost matrix for TSP problem\r\n2. applying DP from top to bottom, Notice that this is not just looking for lowest price, we want traveling path in the end, so we also need to keep track on path\r\n3. building answer from path of the min cost TSP\r\n\r\n# Code\r\n```\r\nfrom functools import lru_cache\r\nfrom itertools import permutations\r\n\r\nclass Solution:\r\n def shortestSuperstring(self, words):\r\n words.insert(0, \'~\') # start from nowhere\r\n\r\n # build cost matrix\r\n L, prefix = len(words), {w: {w[:i + 1] for i in range(len(w))} for w in words}\r\n cost = [[0] * L for _ in range(L)]\r\n\r\n for l, r in permutations(range(L), 2):\r\n lw, rw = words[l], words[r]\r\n\r\n cost[l][r] = len(rw) # default\r\n for i in range(len(lw)): # greadily find shorter\r\n if lw[i] == rw[0] and lw[i:] in prefix[rw]:\r\n cost[l][r] = len(rw) - (len(lw) - i)\r\n break\r\n\r\n # solve traveling salesman problem\r\n @lru_cache(None)\r\n def tsp(used, i):\r\n nonlocal L\r\n assert (i != 0)\r\n if used & (used - 1) == 0: return (cost[0][i], [i])\r\n used -= (1 << i)\r\n\r\n min_tsp, min_path = float(\'inf\'), []\r\n for j in range(1, L):\r\n if j == i: continue\r\n if (used & (1 << j)) == 0: continue\r\n\r\n candidate, path = tsp(used, j)\r\n candidate += cost[j][i]\r\n\r\n if candidate <= min_tsp:\r\n min_tsp, min_path = candidate, path\r\n\r\n return (min_tsp, min_path + [i])\r\n\r\n used = 2**L - 1 - 1 # index 0 not consider, when L is 3, mask should be 1110\r\n _, path = min(tsp(used, i) for i in range(1, L))\r\n\r\n # building answer from DP result\r\n path, shortest_superstring = [0] + path, \'\'\r\n\r\n for i in range(1, len(path)):\r\n l, r = path[i - 1], path[i]\r\n if cost[l][r] == 0: continue\r\n shortest_superstring += words[r][-cost[l][r]:]\r\n\r\n return shortest_superstring\r\n```
0
Given an array of strings `words`, return _the smallest string that contains each string in_ `words` _as a substring_. If there are multiple valid strings of the smallest length, return **any of them**. You may assume that no string in `words` is a substring of another string in `words`. **Example 1:** **Input:** words = \[ "alex ", "loves ", "leetcode "\] **Output:** "alexlovesleetcode " **Explanation:** All permutations of "alex ", "loves ", "leetcode " would also be accepted. **Example 2:** **Input:** words = \[ "catg ", "ctaagt ", "gcta ", "ttca ", "atgcatc "\] **Output:** "gctaagttcatgcatc " **Constraints:** * `1 <= words.length <= 12` * `1 <= words[i].length <= 20` * `words[i]` consists of lowercase English letters. * All the strings of `words` are **unique**.
null
Python | DP with memo to solve TSP, fully explained~
find-the-shortest-superstring
0
1
# FIRST THING FIRST\r\nVote me if you like this solution~\r\n\r\n# Intuition\r\nThis is actually a "Traveling Salesman Problem" if we consider each word as a city\r\nAnd the `ticket price` (or `cost`, more generalized) from city to city is the `number of chars` we need to add if we append that word\r\n\r\n# DP analysis of TSP\r\nmake `TSP(used, i)`: the minimum cost from words 0 to words i, with used words\r\n- optimal substructure:\r\n```\r\nTSP(used, i) = { cost(0, i) if range(len(used)==1) and i!=0\r\n { min( TSP(used-j, j) + cost(j, i) | for j in used and j != i)\r\nhere we treat {used} as a *set*, but we\'ll use bits in code for convenient\r\n```\r\n- overlap subproblems: YES\r\n- no after effect: NO\r\n\r\n# Approach\r\n0. add a word \'~\' as index 0, this word means we came from nowhere, and should\'t contain any lowercase English letters\r\n1. building cost matrix for TSP problem\r\n2. applying DP from top to bottom, Notice that this is not just looking for lowest price, we want traveling path in the end, so we also need to keep track on path\r\n3. building answer from path of the min cost TSP\r\n\r\n# Code\r\n```\r\nfrom functools import lru_cache\r\nfrom itertools import permutations\r\n\r\nclass Solution:\r\n def shortestSuperstring(self, words):\r\n words.insert(0, \'~\') # start from nowhere\r\n\r\n # build cost matrix\r\n L, prefix = len(words), {w: {w[:i + 1] for i in range(len(w))} for w in words}\r\n cost = [[0] * L for _ in range(L)]\r\n\r\n for l, r in permutations(range(L), 2):\r\n lw, rw = words[l], words[r]\r\n\r\n cost[l][r] = len(rw) # default\r\n for i in range(len(lw)): # greadily find shorter\r\n if lw[i] == rw[0] and lw[i:] in prefix[rw]:\r\n cost[l][r] = len(rw) - (len(lw) - i)\r\n break\r\n\r\n # solve traveling salesman problem\r\n @lru_cache(None)\r\n def tsp(used, i):\r\n nonlocal L\r\n assert (i != 0)\r\n if used & (used - 1) == 0: return (cost[0][i], [i])\r\n used -= (1 << i)\r\n\r\n min_tsp, min_path = float(\'inf\'), []\r\n for j in range(1, L):\r\n if j == i: continue\r\n if (used & (1 << j)) == 0: continue\r\n\r\n candidate, path = tsp(used, j)\r\n candidate += cost[j][i]\r\n\r\n if candidate <= min_tsp:\r\n min_tsp, min_path = candidate, path\r\n\r\n return (min_tsp, min_path + [i])\r\n\r\n used = 2**L - 1 - 1 # index 0 not consider, when L is 3, mask should be 1110\r\n _, path = min(tsp(used, i) for i in range(1, L))\r\n\r\n # building answer from DP result\r\n path, shortest_superstring = [0] + path, \'\'\r\n\r\n for i in range(1, len(path)):\r\n l, r = path[i - 1], path[i]\r\n if cost[l][r] == 0: continue\r\n shortest_superstring += words[r][-cost[l][r]:]\r\n\r\n return shortest_superstring\r\n```
0
You are given an `m x n` integer array `grid` where `grid[i][j]` could be: * `1` representing the starting square. There is exactly one starting square. * `2` representing the ending square. There is exactly one ending square. * `0` representing empty squares we can walk over. * `-1` representing obstacles that we cannot walk over. Return _the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once_. **Example 1:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,2,-1\]\] **Output:** 2 **Explanation:** We have the following two paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2) 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2) **Example 2:** **Input:** grid = \[\[1,0,0,0\],\[0,0,0,0\],\[0,0,0,2\]\] **Output:** 4 **Explanation:** We have the following four paths: 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3) 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3) 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3) 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3) **Example 3:** **Input:** grid = \[\[0,1\],\[2,0\]\] **Output:** 0 **Explanation:** There is no path that walks over every empty square exactly once. Note that the starting and ending square can be anywhere in the grid. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 20` * `1 <= m * n <= 20` * `-1 <= grid[i][j] <= 2` * There is exactly one starting cell and one ending cell.
null
Solution
minimum-increment-to-make-array-unique
1
1
```C++ []\n#define rep(i,m,n) for(int i=m;i<n;i++)\n#define all(x) x.begin(),x.end()\n\nclass Solution {\npublic:\n int minIncrementForUnique(vector<int>& a) {\n int mx=*max_element(all(a));\n vector<int> cnt(mx+1,0);\n\n for(auto i:a)\n cnt[i]++;\n \n long ans=0;\n\n int carry=0;\n rep(i,0,mx+1)\n {\n carry+=cnt[i];\n if(carry>0)\n {\n carry--;\n ans+=carry;\n }\n }\n ans=ans + ((carry-1)*(carry))/2;\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n\n cntArray = [0]*(max(nums)+1)\n\n for num in nums:\n cntArray[num] += 1\n\n duplicatStack = []\n move = 0\n for i in range(len(cntArray)):\n if cntArray[i] >= 1:\n while cntArray[i] != 1:\n duplicatStack.append(i)\n cntArray[i] -= 1\n else:\n if len(duplicatStack) > 0:\n move += i - duplicatStack.pop()\n \n value = max(nums) + 1\n while len(duplicatStack)!=0:\n move += value -duplicatStack.pop()\n value+=1\n \n return move\n```\n\n```Java []\nclass Solution {\n public int minIncrementForUnique(int[] nums) {\n if (nums == null || nums.length == 0) {\n return 0;\n }\n int max = Integer.MIN_VALUE;\n for (int num : nums) {\n if (num > max) {\n max = num;\n }\n }\n int[] record = new int[max + nums.length];\n for (int num : nums) {\n record[num]++;\n }\n int moves = 0;\n for (int i = 0; i < record.length; i++) {\n if (record[i] > 1) {\n int remain = record[i] - 1;\n moves += remain;\n record[i + 1] += remain;\n }\n }\n return moves;\n }\n}\n```\n
1
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input:** nums = \[1,2,2\] **Output:** 1 **Explanation:** After 1 move, the array could be \[1, 2, 3\]. **Example 2:** **Input:** nums = \[3,2,1,2,1,7\] **Output:** 6 **Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values. **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Solution
minimum-increment-to-make-array-unique
1
1
```C++ []\n#define rep(i,m,n) for(int i=m;i<n;i++)\n#define all(x) x.begin(),x.end()\n\nclass Solution {\npublic:\n int minIncrementForUnique(vector<int>& a) {\n int mx=*max_element(all(a));\n vector<int> cnt(mx+1,0);\n\n for(auto i:a)\n cnt[i]++;\n \n long ans=0;\n\n int carry=0;\n rep(i,0,mx+1)\n {\n carry+=cnt[i];\n if(carry>0)\n {\n carry--;\n ans+=carry;\n }\n }\n ans=ans + ((carry-1)*(carry))/2;\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n\n cntArray = [0]*(max(nums)+1)\n\n for num in nums:\n cntArray[num] += 1\n\n duplicatStack = []\n move = 0\n for i in range(len(cntArray)):\n if cntArray[i] >= 1:\n while cntArray[i] != 1:\n duplicatStack.append(i)\n cntArray[i] -= 1\n else:\n if len(duplicatStack) > 0:\n move += i - duplicatStack.pop()\n \n value = max(nums) + 1\n while len(duplicatStack)!=0:\n move += value -duplicatStack.pop()\n value+=1\n \n return move\n```\n\n```Java []\nclass Solution {\n public int minIncrementForUnique(int[] nums) {\n if (nums == null || nums.length == 0) {\n return 0;\n }\n int max = Integer.MIN_VALUE;\n for (int num : nums) {\n if (num > max) {\n max = num;\n }\n }\n int[] record = new int[max + nums.length];\n for (int num : nums) {\n record[num]++;\n }\n int moves = 0;\n for (int i = 0; i < record.length; i++) {\n if (record[i] > 1) {\n int remain = record[i] - 1;\n moves += remain;\n record[i + 1] += remain;\n }\n }\n return moves;\n }\n}\n```\n
1
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 12 **Explanation:** We could choose the following i, j, k triples: (i=0, j=0, k=1) : 2 & 2 & 1 (i=0, j=1, k=0) : 2 & 1 & 2 (i=0, j=1, k=1) : 2 & 1 & 1 (i=0, j=1, k=2) : 2 & 1 & 3 (i=0, j=2, k=1) : 2 & 3 & 1 (i=1, j=0, k=0) : 1 & 2 & 2 (i=1, j=0, k=1) : 1 & 2 & 1 (i=1, j=0, k=2) : 1 & 2 & 3 (i=1, j=1, k=0) : 1 & 1 & 2 (i=1, j=2, k=0) : 1 & 3 & 2 (i=2, j=0, k=1) : 3 & 2 & 1 (i=2, j=1, k=0) : 3 & 1 & 2 **Example 2:** **Input:** nums = \[0,0,0\] **Output:** 27 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
PYTHON SOL || WELL EXPLAINED || SORTING ||GREEDY|| APPROACH EXPLAINED || SIMPLE || O(n*log(n))||
minimum-increment-to-make-array-unique
0
1
# EXPLANATION\n```\nWe need to make every number unique :\n Now for a number let\'s say 10 \n We can make it unique by incrementing the number only means we can\'t look below 10\n So the idea here is everytime we are making a number unique we can only go forward\n This gives the idea of sorting \n \n Because if we sort the array we exactly know that till which number have we used all of the unique numbers \n \n Let\'s say arr = [ 2,5,2,4,2,3]\n If we sort the arr : [2,2,2,3,4,5]\n Now for the index = 1: This element is not unique\n if i look before i know that i have used all unique element till 2 and i can use element 3 to make 2 unique here\n Don\'t worry using 3 won\'t make duplicacy as we will solve for 3 afterwards\n \n arr becomes : [2 , 3 , 2 , 3 , 4 , 5 ]\n Now for index 2 : it is not unique \n if we look at index 1 we can tell that we have used every unique from 2 to 3 \n So we use 4 to replace 2\n \n arr becomes : [ 2 , 3 , 4 , 3 , 4 , 5]\n At index 3 : it is not unique \n so by looking at index 2 we can tell that we have used all unique from 2 to 4 so use 5\n I am saying 2 to 4 because 2 is the min element and we can only increment to make unique\n Hence min unique element will always be 2 here\n \n arr becomes [ 2 , 3 , 4 , 5 , 4 , 5 ]\n So the idea is if arr[i] is less than or equals to arr[i-1] we say its not unique as\n we have used unique from arr[0] to arr[i-1] so to make it unique we use the nearest element i,e, arr[i-1]+1\n \n everytime we update calculate the difference which is arr[i-1] + 1 - arr[i] and add to answer.\n```\n\n# CODE\n```\nclass Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n ans = 0\n for i in range(1,n):\n if nums[i] <= nums[i-1]:\n # this is the case for making item unique\n diff = nums[i-1] + 1 - nums[i]\n ans += diff\n nums[i] = nums[i-1] + 1\n return ans\n```
24
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input:** nums = \[1,2,2\] **Output:** 1 **Explanation:** After 1 move, the array could be \[1, 2, 3\]. **Example 2:** **Input:** nums = \[3,2,1,2,1,7\] **Output:** 6 **Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values. **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
PYTHON SOL || WELL EXPLAINED || SORTING ||GREEDY|| APPROACH EXPLAINED || SIMPLE || O(n*log(n))||
minimum-increment-to-make-array-unique
0
1
# EXPLANATION\n```\nWe need to make every number unique :\n Now for a number let\'s say 10 \n We can make it unique by incrementing the number only means we can\'t look below 10\n So the idea here is everytime we are making a number unique we can only go forward\n This gives the idea of sorting \n \n Because if we sort the array we exactly know that till which number have we used all of the unique numbers \n \n Let\'s say arr = [ 2,5,2,4,2,3]\n If we sort the arr : [2,2,2,3,4,5]\n Now for the index = 1: This element is not unique\n if i look before i know that i have used all unique element till 2 and i can use element 3 to make 2 unique here\n Don\'t worry using 3 won\'t make duplicacy as we will solve for 3 afterwards\n \n arr becomes : [2 , 3 , 2 , 3 , 4 , 5 ]\n Now for index 2 : it is not unique \n if we look at index 1 we can tell that we have used every unique from 2 to 3 \n So we use 4 to replace 2\n \n arr becomes : [ 2 , 3 , 4 , 3 , 4 , 5]\n At index 3 : it is not unique \n so by looking at index 2 we can tell that we have used all unique from 2 to 4 so use 5\n I am saying 2 to 4 because 2 is the min element and we can only increment to make unique\n Hence min unique element will always be 2 here\n \n arr becomes [ 2 , 3 , 4 , 5 , 4 , 5 ]\n So the idea is if arr[i] is less than or equals to arr[i-1] we say its not unique as\n we have used unique from arr[0] to arr[i-1] so to make it unique we use the nearest element i,e, arr[i-1]+1\n \n everytime we update calculate the difference which is arr[i-1] + 1 - arr[i] and add to answer.\n```\n\n# CODE\n```\nclass Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n ans = 0\n for i in range(1,n):\n if nums[i] <= nums[i-1]:\n # this is the case for making item unique\n diff = nums[i-1] + 1 - nums[i]\n ans += diff\n nums[i] = nums[i-1] + 1\n return ans\n```
24
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 12 **Explanation:** We could choose the following i, j, k triples: (i=0, j=0, k=1) : 2 & 2 & 1 (i=0, j=1, k=0) : 2 & 1 & 2 (i=0, j=1, k=1) : 2 & 1 & 1 (i=0, j=1, k=2) : 2 & 1 & 3 (i=0, j=2, k=1) : 2 & 3 & 1 (i=1, j=0, k=0) : 1 & 2 & 2 (i=1, j=0, k=1) : 1 & 2 & 1 (i=1, j=0, k=2) : 1 & 2 & 3 (i=1, j=1, k=0) : 1 & 1 & 2 (i=1, j=2, k=0) : 1 & 3 & 2 (i=2, j=0, k=1) : 3 & 2 & 1 (i=2, j=1, k=0) : 3 & 1 & 2 **Example 2:** **Input:** nums = \[0,0,0\] **Output:** 27 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Python3 Solution beats > 85.00%, keep track of next closest unique number
minimum-increment-to-make-array-unique
0
1
# Intuition\n1. Sort the array\n2. Once the array has been sorted, combined with the fact we can **only ** increment numbers, we can keep track of the "next unqiue number"\n3. After sorting, loop through array.\n4. If num[i] is unique (aka not in the set), add number to set and set next_closest_unique_number to nums[i] + 1. (Since the array is sorted we know the next value will either be equal to the current value, or greater than it).\n5. If num[i+1] is greater, we know this value is unique (aka not in the set)\n6. If num[i+1] is == to num[i], we know the next closest value is simply to add 1. Add the new value to the set, and continue looping.\n\n\n\n# Complexity\n- Time complexity:\n$$O(nlog(n))$$\n\n- Space complexity:\nO(1) (Could be wrong)\n\n# Code\n```\nclass Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n """\n Time-complexity: O(nlogn)\n space-complexity: O(1)\n """\n # Sort nums:\n nums.sort()\n\n answer = 0\n\n # Store unqiue numbers in a set\n unique_nums = set()\n \n next_closest = 0\n\n for num in nums:\n\n if num in unique_nums:\n # Add current num to queue\n answer += next_closest - num\n unique_nums.add(next_closest)\n next_closest += 1\n else:\n unique_nums.add(num)\n next_closest = num + 1\n\n return answer\n\n \n```
0
You are given an integer array `nums`. In one move, you can pick an index `i` where `0 <= i < nums.length` and increment `nums[i]` by `1`. Return _the minimum number of moves to make every value in_ `nums` _**unique**_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input:** nums = \[1,2,2\] **Output:** 1 **Explanation:** After 1 move, the array could be \[1, 2, 3\]. **Example 2:** **Input:** nums = \[3,2,1,2,1,7\] **Output:** 6 **Explanation:** After 6 moves, the array could be \[3, 4, 1, 2, 5, 7\]. It can be shown with 5 or less moves that it is impossible for the array to have all unique values. **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Python3 Solution beats > 85.00%, keep track of next closest unique number
minimum-increment-to-make-array-unique
0
1
# Intuition\n1. Sort the array\n2. Once the array has been sorted, combined with the fact we can **only ** increment numbers, we can keep track of the "next unqiue number"\n3. After sorting, loop through array.\n4. If num[i] is unique (aka not in the set), add number to set and set next_closest_unique_number to nums[i] + 1. (Since the array is sorted we know the next value will either be equal to the current value, or greater than it).\n5. If num[i+1] is greater, we know this value is unique (aka not in the set)\n6. If num[i+1] is == to num[i], we know the next closest value is simply to add 1. Add the new value to the set, and continue looping.\n\n\n\n# Complexity\n- Time complexity:\n$$O(nlog(n))$$\n\n- Space complexity:\nO(1) (Could be wrong)\n\n# Code\n```\nclass Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n """\n Time-complexity: O(nlogn)\n space-complexity: O(1)\n """\n # Sort nums:\n nums.sort()\n\n answer = 0\n\n # Store unqiue numbers in a set\n unique_nums = set()\n \n next_closest = 0\n\n for num in nums:\n\n if num in unique_nums:\n # Add current num to queue\n answer += next_closest - num\n unique_nums.add(next_closest)\n next_closest += 1\n else:\n unique_nums.add(num)\n next_closest = num + 1\n\n return answer\n\n \n```
0
Given an integer array nums, return _the number of **AND triples**_. An **AND triple** is a triple of indices `(i, j, k)` such that: * `0 <= i < nums.length` * `0 <= j < nums.length` * `0 <= k < nums.length` * `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator. **Example 1:** **Input:** nums = \[2,1,3\] **Output:** 12 **Explanation:** We could choose the following i, j, k triples: (i=0, j=0, k=1) : 2 & 2 & 1 (i=0, j=1, k=0) : 2 & 1 & 2 (i=0, j=1, k=1) : 2 & 1 & 1 (i=0, j=1, k=2) : 2 & 1 & 3 (i=0, j=2, k=1) : 2 & 3 & 1 (i=1, j=0, k=0) : 1 & 2 & 2 (i=1, j=0, k=1) : 1 & 2 & 1 (i=1, j=0, k=2) : 1 & 2 & 3 (i=1, j=1, k=0) : 1 & 1 & 2 (i=1, j=2, k=0) : 1 & 3 & 2 (i=2, j=0, k=1) : 3 & 2 & 1 (i=2, j=1, k=0) : 3 & 1 & 2 **Example 2:** **Input:** nums = \[0,0,0\] **Output:** 27 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
valid_stack().py
validate-stack-sequences
0
1
SIMPLE STACK LIST\n# Code\n```\nclass Solution:\n def validateStackSequences(self, p: List[int], o: List[int]) -> bool:\n st=[]\n x=0\n for i in p:\n st.append(i)\n if len(st)>0 and st[len(st)-1]==o[x]:\n while len(st)>0 and st[len(st)-1]==o[x]:\n x+=1\n st.pop()\n return len(st)==0\n\n```
4
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
valid_stack().py
validate-stack-sequences
0
1
SIMPLE STACK LIST\n# Code\n```\nclass Solution:\n def validateStackSequences(self, p: List[int], o: List[int]) -> bool:\n st=[]\n x=0\n for i in p:\n st.append(i)\n if len(st)>0 and st[len(st)-1]==o[x]:\n while len(st)>0 and st[len(st)-1]==o[x]:\n x+=1\n st.pop()\n return len(st)==0\n\n```
4
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
3 ways to solve in python. Each improving on the other
validate-stack-sequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthree approaches to solve this problem\n1) Use an explicit data structure\n2) Use two while loops\n3) Use a while loop nested in a for each loop\n\n# Approach-1\n<!-- Describe your approach to solving the problem. -->\nuse an explicit stack and perform the operations iteratively on it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n n=len(pushed)\n m=len(popped)\n s=[] #initialize an empty stack.\n i=0 #keep track of top of the stack\n j=0 #keep track the next pop instruction to be executed\n while(True):\n print(s)\n if i==n or j==m:\n break\n\n if s!=[] and s[-1]==popped[j]: #pop when top of the stack matches with the pop instruction target.\n s.pop()\n j+=1\n else:\n s.append(pushed[i])\n i+=1\n\n#all push instructions are executed, not perform pop whenever possible\n\n while(j<m):\n if popped[j]==s[-1]: #pop sequnece is valid \n s.pop()\n j+=1\n else: #pop sequence is invalid\n return False\n\n\n if s==[]:\n return True\n return False\n \n```\n# Approach-2\nuse a loop, no need of a data structure.\nimagine a virtual stack whose top is being monitored by a variable i.\nWe use two pointers one to the top of the virtual stack and one pointing to the top of the stack in the pushed array and an other pointing to the element to be popped.\n\n# complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n n=len(pushed)\n m=len(popped)\n i=0 #points to the top of the stack\n j=0 #points to the pop instruction yet to be executed.\n\n while(i<len(pushed)): \n if i>-1 and pushed[i]==popped[j]: #perform pop whenever possible\n pushed.pop(i)\n i-=1 #update top of the stack\n j+=1\n else:\n i+=1 #proceed to push the next element\n \n i=len(pushed)-1\n while(j<m):\n if pushed[i]!=popped[j]:\n return False\n j+=1\n i-=1\n\n return True\n \n```\n\n\n# Approach-3\noptimize the code above further, by using just one loop to keep track of the pushed elements, and perform pop operations whenever possible.\n\n# complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n i=0 #keep track of top of the stack\n j=0 #keep track of the next pop instruction to be executed\n\n for num in pushed:\n pushed[i]=num #move to the next element in for each loop\n while i>-1 and pushed[i]==popped[j]: #remove all elements that can be removed.\n i-=1 #this is just changing the top of the stack as elements are popped\n j+=1 # goto the next pop operation\n i+=1\n return i==0\n \n```\n\nplease consider upvoting if this helps.\n
2
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
3 ways to solve in python. Each improving on the other
validate-stack-sequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthree approaches to solve this problem\n1) Use an explicit data structure\n2) Use two while loops\n3) Use a while loop nested in a for each loop\n\n# Approach-1\n<!-- Describe your approach to solving the problem. -->\nuse an explicit stack and perform the operations iteratively on it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n n=len(pushed)\n m=len(popped)\n s=[] #initialize an empty stack.\n i=0 #keep track of top of the stack\n j=0 #keep track the next pop instruction to be executed\n while(True):\n print(s)\n if i==n or j==m:\n break\n\n if s!=[] and s[-1]==popped[j]: #pop when top of the stack matches with the pop instruction target.\n s.pop()\n j+=1\n else:\n s.append(pushed[i])\n i+=1\n\n#all push instructions are executed, not perform pop whenever possible\n\n while(j<m):\n if popped[j]==s[-1]: #pop sequnece is valid \n s.pop()\n j+=1\n else: #pop sequence is invalid\n return False\n\n\n if s==[]:\n return True\n return False\n \n```\n# Approach-2\nuse a loop, no need of a data structure.\nimagine a virtual stack whose top is being monitored by a variable i.\nWe use two pointers one to the top of the virtual stack and one pointing to the top of the stack in the pushed array and an other pointing to the element to be popped.\n\n# complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n n=len(pushed)\n m=len(popped)\n i=0 #points to the top of the stack\n j=0 #points to the pop instruction yet to be executed.\n\n while(i<len(pushed)): \n if i>-1 and pushed[i]==popped[j]: #perform pop whenever possible\n pushed.pop(i)\n i-=1 #update top of the stack\n j+=1\n else:\n i+=1 #proceed to push the next element\n \n i=len(pushed)-1\n while(j<m):\n if pushed[i]!=popped[j]:\n return False\n j+=1\n i-=1\n\n return True\n \n```\n\n\n# Approach-3\noptimize the code above further, by using just one loop to keep track of the pushed elements, and perform pop operations whenever possible.\n\n# complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n i=0 #keep track of top of the stack\n j=0 #keep track of the next pop instruction to be executed\n\n for num in pushed:\n pushed[i]=num #move to the next element in for each loop\n while i>-1 and pushed[i]==popped[j]: #remove all elements that can be removed.\n i-=1 #this is just changing the top of the stack as elements are popped\n j+=1 # goto the next pop operation\n i+=1\n return i==0\n \n```\n\nplease consider upvoting if this helps.\n
2
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
Simple stack solution. Python/C++
validate-stack-sequences
0
1
\nUsing deque in Python\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n a = deque([])\n j = 0\n for i in range(len(pushed)):\n a.appendleft(pushed[i])\n while(a and a[0] == popped[j]):\n a.popleft()\n j+=1\n return not a\n```\n```\nclass Solution {\npublic:\n bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {\n stack<int> st;\n int n = pushed.size();\n int j = 0;\n for(int i = 0; i < n; i++){\n st.push(pushed[i]);\n while(!st.empty() && st.top() == popped[j]){\n st.pop();\n j++;\n }\n }\n return st.empty();\n }\n};\n```
2
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
Simple stack solution. Python/C++
validate-stack-sequences
0
1
\nUsing deque in Python\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n a = deque([])\n j = 0\n for i in range(len(pushed)):\n a.appendleft(pushed[i])\n while(a and a[0] == popped[j]):\n a.popleft()\n j+=1\n return not a\n```\n```\nclass Solution {\npublic:\n bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {\n stack<int> st;\n int n = pushed.size();\n int j = 0;\n for(int i = 0; i < n; i++){\n st.push(pushed[i]);\n while(!st.empty() && st.top() == popped[j]){\n st.pop();\n j++;\n }\n }\n return st.empty();\n }\n};\n```
2
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
🔥🔥BEATS 99.2%🔥🔥||EASY SOLUTION
validate-stack-sequences
0
1
\n\n# Approach\nStack :if top element of stack is equal to popped element index then pop the element\n\n# Complexity\n\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack=[]\n j=0\n for i in pushed:\n stack.append(i)\n while stack!=[] and stack[-1]==popped[j]:\n stack.pop()\n j+=1\n return stack==[]\n```
1
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
🔥🔥BEATS 99.2%🔥🔥||EASY SOLUTION
validate-stack-sequences
0
1
\n\n# Approach\nStack :if top element of stack is equal to popped element index then pop the element\n\n# Complexity\n\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack=[]\n j=0\n for i in pushed:\n stack.append(i)\n while stack!=[] and stack[-1]==popped[j]:\n stack.pop()\n j+=1\n return stack==[]\n```
1
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
easy stack python solution
validate-stack-sequences
0
1
```\nclass Solution:\n \n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack = []\n j = 0\n for i in range(len(pushed)):\n stack.append(pushed[i])\n # moving on the popped list with another pointer and updating the stack\n while stack and j < len(popped) and stack[-1] == popped[j] : \n stack.pop()\n j += 1\n return len(stack) == 0 #it must be empty because all elements must be popped\n \n
1
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
easy stack python solution
validate-stack-sequences
0
1
```\nclass Solution:\n \n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack = []\n j = 0\n for i in range(len(pushed)):\n stack.append(pushed[i])\n # moving on the popped list with another pointer and updating the stack\n while stack and j < len(popped) and stack[-1] == popped[j] : \n stack.pop()\n j += 1\n return len(stack) == 0 #it must be empty because all elements must be popped\n \n
1
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
PYTHON || STACK || beats(70%)
validate-stack-sequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nstack problem \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n- iterate through pushed array using stack with it \n- use pointer (idx) with popped array\n- use while loop with condition that (last element in stack equal first elemet in popped ) , pop it from stack and increase idx by 1\n- at end if stack is empty rteurn True otherwise false \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution(object):\n def validateStackSequences(self, pushed, popped):\n """\n :type pushed: List[int]\n :type popped: List[int]\n :rtype: bool\n """\n stack = []\n idx =0\n for v in pushed:\n stack.append(v)\n while stack and stack[-1] == popped[idx]:\n stack.pop()\n idx +=1\n return len(stack)==0 \n```
1
Given two integer arrays `pushed` and `popped` each with distinct values, return `true` _if this could have been the result of a sequence of push and pop operations on an initially empty stack, or_ `false` _otherwise._ **Example 1:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,5,3,2,1\] **Output:** true **Explanation:** We might do the following sequence: push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1 **Example 2:** **Input:** pushed = \[1,2,3,4,5\], popped = \[4,3,5,1,2\] **Output:** false **Explanation:** 1 cannot be popped before 2. **Constraints:** * `1 <= pushed.length <= 1000` * `0 <= pushed[i] <= 1000` * All the elements of `pushed` are **unique**. * `popped.length == pushed.length` * `popped` is a permutation of `pushed`.
null
PYTHON || STACK || beats(70%)
validate-stack-sequences
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nstack problem \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n- iterate through pushed array using stack with it \n- use pointer (idx) with popped array\n- use while loop with condition that (last element in stack equal first elemet in popped ) , pop it from stack and increase idx by 1\n- at end if stack is empty rteurn True otherwise false \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution(object):\n def validateStackSequences(self, pushed, popped):\n """\n :type pushed: List[int]\n :type popped: List[int]\n :rtype: bool\n """\n stack = []\n idx =0\n for v in pushed:\n stack.append(v)\n while stack and stack[-1] == popped[idx]:\n stack.pop()\n idx +=1\n return len(stack)==0 \n```
1
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
Solution
most-stones-removed-with-same-row-or-column
1
1
```C++ []\nclass Solution {\n static constexpr int K = 10001;\n int* ranks;\n int* repr;\n\n inline int dsuFind(int x) {\n if (x != repr[x]) {\n repr[x] = dsuFind(repr[x]);\n }\n return repr[x];\n }\n inline int dsuUnion(int x, int y) {\n x = dsuFind(x);\n y = dsuFind(y);\n\n if (x == y) {\n return 0;\n }\n if (ranks[x] >= ranks[y]) {\n repr[y] = x;\n } else if (ranks[x] < ranks[y]) {\n repr[x] = y;\n }\n if (ranks[x] == ranks[y]) {\n ++ranks[x];\n }\n return 1;\n }\npublic:\n int removeStones(const vector<vector<int>>& stones) {\n ranks = new int[K * 2];\n repr = new int[K * 2];\n\n int componentCount = 0;\n vector<bool> marked(K * 2);\n for (const auto& stone : stones) {\n if (!marked[stone[0]]) {\n ++componentCount;\n marked[stone[0]] = true;\n repr[stone[0]] = stone[0];\n ranks[stone[0]] = 1;\n }\n if (!marked[stone[1] + K]) {\n ++componentCount;\n marked[stone[1] + K] = true;\n repr[stone[1] + K] = stone[1] + K;\n ranks[stone[1] + K] = 1;\n }\n componentCount -= dsuUnion(stone[0], stone[1] + K);\n }\n delete[] ranks;\n delete[] repr;\n return stones.size() - componentCount;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def removeStones(self, stones: List[List[int]]) -> int:\n\n unused_group = 1\n\n row_group = dict()\n col_group = dict()\n\n linked_groups = dict()\n\n def ultimate_group(g):\n if linked_groups[g] == g:\n return g\n ult_g = ultimate_group(linked_groups[g])\n linked_groups[g] = ult_g\n return ult_g\n\n def merge_group(g1, g2):\n ultg1 = ultimate_group(g1)\n ultg2 = ultimate_group(g2)\n linked_groups[ultg1] = ultg2\n\n for row, col in stones:\n grow = row_group.get(row)\n gcol = col_group.get(col)\n\n if grow and gcol and grow != gcol:\n merge_group(grow, gcol)\n else:\n g = grow or gcol\n if not g:\n g = unused_group\n unused_group += 1\n linked_groups[g] = g\n else:\n g = ultimate_group(g)\n row_group[row] = g\n col_group[col] = g\n \n return len(stones) - len({ultimate_group(g) for _, g in linked_groups.items()})\n```\n\n```Java []\nclass Solution {\n public int numOfIslands = 0;\n public int removeStones(int[][] stones) {\n int[] parent = new int[20003];\n for(int[] stone:stones) {\n unionSets(stone[0]+1, stone[1] + 10002, parent);\n }\n return stones.length - numOfIslands;\n }\n public void unionSets(int a, int b, int[] parent) {\n int parA = findParent(a, parent), parB = findParent(b, parent);\n if(parA != parB) {\n parent[parB] = parA;\n numOfIslands--;\n }\n return;\n }\n public int findParent(int node, int[] parent) {\n if(parent[node] == 0) {\n parent[node] = node;\n numOfIslands++;\n }\n if(parent[node] == node) {\n return node;\n }\n int par = findParent(parent[node], parent);\n parent[node] = par;\n return par;\n }\n}\n```\n
1
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
Solution
most-stones-removed-with-same-row-or-column
1
1
```C++ []\nclass Solution {\n static constexpr int K = 10001;\n int* ranks;\n int* repr;\n\n inline int dsuFind(int x) {\n if (x != repr[x]) {\n repr[x] = dsuFind(repr[x]);\n }\n return repr[x];\n }\n inline int dsuUnion(int x, int y) {\n x = dsuFind(x);\n y = dsuFind(y);\n\n if (x == y) {\n return 0;\n }\n if (ranks[x] >= ranks[y]) {\n repr[y] = x;\n } else if (ranks[x] < ranks[y]) {\n repr[x] = y;\n }\n if (ranks[x] == ranks[y]) {\n ++ranks[x];\n }\n return 1;\n }\npublic:\n int removeStones(const vector<vector<int>>& stones) {\n ranks = new int[K * 2];\n repr = new int[K * 2];\n\n int componentCount = 0;\n vector<bool> marked(K * 2);\n for (const auto& stone : stones) {\n if (!marked[stone[0]]) {\n ++componentCount;\n marked[stone[0]] = true;\n repr[stone[0]] = stone[0];\n ranks[stone[0]] = 1;\n }\n if (!marked[stone[1] + K]) {\n ++componentCount;\n marked[stone[1] + K] = true;\n repr[stone[1] + K] = stone[1] + K;\n ranks[stone[1] + K] = 1;\n }\n componentCount -= dsuUnion(stone[0], stone[1] + K);\n }\n delete[] ranks;\n delete[] repr;\n return stones.size() - componentCount;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def removeStones(self, stones: List[List[int]]) -> int:\n\n unused_group = 1\n\n row_group = dict()\n col_group = dict()\n\n linked_groups = dict()\n\n def ultimate_group(g):\n if linked_groups[g] == g:\n return g\n ult_g = ultimate_group(linked_groups[g])\n linked_groups[g] = ult_g\n return ult_g\n\n def merge_group(g1, g2):\n ultg1 = ultimate_group(g1)\n ultg2 = ultimate_group(g2)\n linked_groups[ultg1] = ultg2\n\n for row, col in stones:\n grow = row_group.get(row)\n gcol = col_group.get(col)\n\n if grow and gcol and grow != gcol:\n merge_group(grow, gcol)\n else:\n g = grow or gcol\n if not g:\n g = unused_group\n unused_group += 1\n linked_groups[g] = g\n else:\n g = ultimate_group(g)\n row_group[row] = g\n col_group[col] = g\n \n return len(stones) - len({ultimate_group(g) for _, g in linked_groups.items()})\n```\n\n```Java []\nclass Solution {\n public int numOfIslands = 0;\n public int removeStones(int[][] stones) {\n int[] parent = new int[20003];\n for(int[] stone:stones) {\n unionSets(stone[0]+1, stone[1] + 10002, parent);\n }\n return stones.length - numOfIslands;\n }\n public void unionSets(int a, int b, int[] parent) {\n int parA = findParent(a, parent), parB = findParent(b, parent);\n if(parA != parB) {\n parent[parB] = parA;\n numOfIslands--;\n }\n return;\n }\n public int findParent(int node, int[] parent) {\n if(parent[node] == 0) {\n parent[node] = node;\n numOfIslands++;\n }\n if(parent[node] == node) {\n return node;\n }\n int par = findParent(parent[node], parent);\n parent[node] = par;\n return par;\n }\n}\n```\n
1
Given two integers `a` and `b`, return **any** string `s` such that: * `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, * The substring `'aaa'` does not occur in `s`, and * The substring `'bbb'` does not occur in `s`. **Example 1:** **Input:** a = 1, b = 2 **Output:** "abb " **Explanation:** "abb ", "bab " and "bba " are all correct answers. **Example 2:** **Input:** a = 4, b = 1 **Output:** "aabaa " **Constraints:** * `0 <= a, b <= 100` * It is guaranteed such an `s` exists for the given `a` and `b`.
null
Python || Easy || Union Find || Explained
most-stones-removed-with-same-row-or-column
0
1
**We can say that if a stone is in the same row or in same column then it is a part of one component and no. of stones that can be removed from one component is n1(no. of stones in component 1)-1. So, total no. of stones that can be removed is n(given no. of stones) - c(no. of components)**\n\n```\nclass Solution:\n def removeStones(self, stones: List[List[int]]) -> int:\n def find(u):\n if u==parent[u]:\n return u\n else:\n parent[u]=find(parent[u])\n return parent[u]\n def union(u,v):\n pu,pv=find(u),find(v)\n if pu==pv:\n return \n if size[pv]>size[pu]:\n parent[pu]=pv\n size[pv]+=size[pu]\n else:\n parent[pv]=pu\n size[pu]+=size[pv]\n \n n=len(stones)\n mr=mc=0\n for i,j in stones:\n mr=max(mr,i)\n mc=max(mc,j)\n parent=[i for i in range(mr+mc+2)]\n size=[1 for i in range(mr+mc+2)]\n d={} # created a dictionary to store the rows and columns which are visited\n for i,j in stones:\n union(i,j+mr+1)\n d[i]=1\n d[j+mr+1]=1\n c=0 \n for i in d:\n if find(i)==i:\n c+=1 # counting the no. of components\n return n-c\n```\n\n**An upvote will be encouraging**
2
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
Python || Easy || Union Find || Explained
most-stones-removed-with-same-row-or-column
0
1
**We can say that if a stone is in the same row or in same column then it is a part of one component and no. of stones that can be removed from one component is n1(no. of stones in component 1)-1. So, total no. of stones that can be removed is n(given no. of stones) - c(no. of components)**\n\n```\nclass Solution:\n def removeStones(self, stones: List[List[int]]) -> int:\n def find(u):\n if u==parent[u]:\n return u\n else:\n parent[u]=find(parent[u])\n return parent[u]\n def union(u,v):\n pu,pv=find(u),find(v)\n if pu==pv:\n return \n if size[pv]>size[pu]:\n parent[pu]=pv\n size[pv]+=size[pu]\n else:\n parent[pv]=pu\n size[pu]+=size[pv]\n \n n=len(stones)\n mr=mc=0\n for i,j in stones:\n mr=max(mr,i)\n mc=max(mc,j)\n parent=[i for i in range(mr+mc+2)]\n size=[1 for i in range(mr+mc+2)]\n d={} # created a dictionary to store the rows and columns which are visited\n for i,j in stones:\n union(i,j+mr+1)\n d[i]=1\n d[j+mr+1]=1\n c=0 \n for i in d:\n if find(i)==i:\n c+=1 # counting the no. of components\n return n-c\n```\n\n**An upvote will be encouraging**
2
Given two integers `a` and `b`, return **any** string `s` such that: * `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, * The substring `'aaa'` does not occur in `s`, and * The substring `'bbb'` does not occur in `s`. **Example 1:** **Input:** a = 1, b = 2 **Output:** "abb " **Explanation:** "abb ", "bab " and "bba " are all correct answers. **Example 2:** **Input:** a = 4, b = 1 **Output:** "aabaa " **Constraints:** * `0 <= a, b <= 100` * It is guaranteed such an `s` exists for the given `a` and `b`.
null
📌📌 For Beginners || Count Number of Connected Graphs O(N) || 94% Faster 🐍
most-stones-removed-with-same-row-or-column
0
1
## IDEA :\n\n*If you see the whole description with focus you will find that we have to find total number of distinguish connected points. So, We move this problem to a graph domain. When two stones row or column is same, we can say the they are connected.*\n\nAfter construcing the graph, we get a collection of one or more connected graphs In graph\'s terminology, this is called **strongly connected component.**\n\nNow, for every stronly connected component, one stone will remain, all others inside that component can be removed (because from that remaining stone, we can move to other stones in that component and remove them).\n\n**So, Our answer should be = Number ot stones - Number of strongly connected component**\n\n### Algorightm\n\n\tPrepare the graph\n\tFrom every stone\n\t\ta. If not visitied, run dfs to remove connected nodes.\n\t\tb. After removing a node, track that to avoid infinite loop\n\t\tc. When a strongly connected component is fully traversed, subtract 1 to track that remaining stone\n\tDo this until all stones are traversed \n\n### Implementation :\n\'\'\'\n\t\t\n\t\tclass Solution:\n\t\t\tdef removeStones(self, stones: List[List[int]]) -> int:\n\t\t\t\t\n\t\t\t\tdef remove_point(a,b): # Function to remove connected points from the ongoing graph. \n\t\t\t\t\tpoints.discard((a,b))\n\t\t\t\t\tfor y in x_dic[a]:\n\t\t\t\t\t\tif (a,y) in points:\n\t\t\t\t\t\t\tremove_point(a,y)\n\n\t\t\t\t\tfor x in y_dic[b]:\n\t\t\t\t\t\tif (x,b) in points:\n\t\t\t\t\t\t\tremove_point(x,b)\n\n\t\t\t\tx_dic = defaultdict(list)\n\t\t\t\ty_dic = defaultdict(list)\n\t\t\t\tpoints= {(i,j) for i,j in stones}\n\t\t\t\t\n\t\t\t\tfor i,j in stones: # Construction of graph by x_coordinates and y_coordinates.\n\t\t\t\t\tx_dic[i].append(j)\n\t\t\t\t\ty_dic[j].append(i)\n\n\t\t\t\tcnt = 0\n\t\t\t\tfor a,b in stones: # counting of distinct connected graph.\n\t\t\t\t\tif (a,b) in points:\n\t\t\t\t\t\tremove_point(a,b)\n\t\t\t\t\t\tcnt+=1\n\n\t\t\t\treturn len(stones)-cnt\n\t\t\t\t\n### **Thanks and Upvote if you like the Idea !!\uD83E\uDD17**
29
On a 2D plane, we place `n` stones at some integer coordinate points. Each coordinate point may have at most one stone. A stone can be removed if it shares either **the same row or the same column** as another stone that has not been removed. Given an array `stones` of length `n` where `stones[i] = [xi, yi]` represents the location of the `ith` stone, return _the largest possible number of stones that can be removed_. **Example 1:** **Input:** stones = \[\[0,0\],\[0,1\],\[1,0\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 5 **Explanation:** One way to remove 5 stones is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,1\]. 2. Remove stone \[2,1\] because it shares the same column as \[0,1\]. 3. Remove stone \[1,2\] because it shares the same row as \[1,0\]. 4. Remove stone \[1,0\] because it shares the same column as \[0,0\]. 5. Remove stone \[0,1\] because it shares the same row as \[0,0\]. Stone \[0,0\] cannot be removed since it does not share a row/column with another stone still on the plane. **Example 2:** **Input:** stones = \[\[0,0\],\[0,2\],\[1,1\],\[2,0\],\[2,2\]\] **Output:** 3 **Explanation:** One way to make 3 moves is as follows: 1. Remove stone \[2,2\] because it shares the same row as \[2,0\]. 2. Remove stone \[2,0\] because it shares the same column as \[0,0\]. 3. Remove stone \[0,2\] because it shares the same row as \[0,0\]. Stones \[0,0\] and \[1,1\] cannot be removed since they do not share a row/column with another stone still on the plane. **Example 3:** **Input:** stones = \[\[0,0\]\] **Output:** 0 **Explanation:** \[0,0\] is the only stone on the plane, so you cannot remove it. **Constraints:** * `1 <= stones.length <= 1000` * `0 <= xi, yi <= 104` * No two stones are at the same coordinate point.
null
📌📌 For Beginners || Count Number of Connected Graphs O(N) || 94% Faster 🐍
most-stones-removed-with-same-row-or-column
0
1
## IDEA :\n\n*If you see the whole description with focus you will find that we have to find total number of distinguish connected points. So, We move this problem to a graph domain. When two stones row or column is same, we can say the they are connected.*\n\nAfter construcing the graph, we get a collection of one or more connected graphs In graph\'s terminology, this is called **strongly connected component.**\n\nNow, for every stronly connected component, one stone will remain, all others inside that component can be removed (because from that remaining stone, we can move to other stones in that component and remove them).\n\n**So, Our answer should be = Number ot stones - Number of strongly connected component**\n\n### Algorightm\n\n\tPrepare the graph\n\tFrom every stone\n\t\ta. If not visitied, run dfs to remove connected nodes.\n\t\tb. After removing a node, track that to avoid infinite loop\n\t\tc. When a strongly connected component is fully traversed, subtract 1 to track that remaining stone\n\tDo this until all stones are traversed \n\n### Implementation :\n\'\'\'\n\t\t\n\t\tclass Solution:\n\t\t\tdef removeStones(self, stones: List[List[int]]) -> int:\n\t\t\t\t\n\t\t\t\tdef remove_point(a,b): # Function to remove connected points from the ongoing graph. \n\t\t\t\t\tpoints.discard((a,b))\n\t\t\t\t\tfor y in x_dic[a]:\n\t\t\t\t\t\tif (a,y) in points:\n\t\t\t\t\t\t\tremove_point(a,y)\n\n\t\t\t\t\tfor x in y_dic[b]:\n\t\t\t\t\t\tif (x,b) in points:\n\t\t\t\t\t\t\tremove_point(x,b)\n\n\t\t\t\tx_dic = defaultdict(list)\n\t\t\t\ty_dic = defaultdict(list)\n\t\t\t\tpoints= {(i,j) for i,j in stones}\n\t\t\t\t\n\t\t\t\tfor i,j in stones: # Construction of graph by x_coordinates and y_coordinates.\n\t\t\t\t\tx_dic[i].append(j)\n\t\t\t\t\ty_dic[j].append(i)\n\n\t\t\t\tcnt = 0\n\t\t\t\tfor a,b in stones: # counting of distinct connected graph.\n\t\t\t\t\tif (a,b) in points:\n\t\t\t\t\t\tremove_point(a,b)\n\t\t\t\t\t\tcnt+=1\n\n\t\t\t\treturn len(stones)-cnt\n\t\t\t\t\n### **Thanks and Upvote if you like the Idea !!\uD83E\uDD17**
29
Given two integers `a` and `b`, return **any** string `s` such that: * `s` has length `a + b` and contains exactly `a` `'a'` letters, and exactly `b` `'b'` letters, * The substring `'aaa'` does not occur in `s`, and * The substring `'bbb'` does not occur in `s`. **Example 1:** **Input:** a = 1, b = 2 **Output:** "abb " **Explanation:** "abb ", "bab " and "bba " are all correct answers. **Example 2:** **Input:** a = 4, b = 1 **Output:** "aabaa " **Constraints:** * `0 <= a, b <= 100` * It is guaranteed such an `s` exists for the given `a` and `b`.
null
Solution
bag-of-tokens
1
1
```C++ []\nclass Solution {\npublic:\n int bagOfTokensScore(vector<int>& nums, int power) {\n sort(nums.begin(),nums.end());\n int i=0,j=nums.size()-1,score=0,ans=0;\n while(i<=j && i<nums.size()){\n if(score<=0&&power<nums[i])break;\n if(power>=nums[i]){\n while(i<nums.size()&&power>=nums[i]){\n score++;\n ans=max(ans,score);\n power-=nums[i];\n i++;\n }\n }\n else if(score>0 ) {power+=nums[j];j--;score--;}\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n coins = 0\n left, right = 0, len(tokens) - 1\n result = 0\n while left <= right:\n while left <= right and power >= tokens[left]:\n power -= tokens[left]\n coins += 1\n left += 1\n result = max(result, coins)\n if coins > 0:\n coins -= 1\n power += tokens[right]\n right -= 1\n else:\n break\n return result\n```\n\n```Java []\nclass Solution {\n public int bagOfTokensScore(int[] tokens, int power) {\n int score = 0,last=tokens.length,ans=0,i=0;\n quicksort(tokens,0,last-1);\n while(i<last && (power >= tokens[i] || score > 0)){\n if(power >= tokens[i]){\n power -= tokens[i];\n score++;\n i++;\n }\n else{\n score--;\n power += tokens[--last];\n }\n ans = Math.max(score,ans);\n }\n return ans;\n }\n private void quicksort(int[] arr, int left, int right) \n {\n if (left < right) \n {\n int pivotIndex = partition(arr, left, right);\n quicksort(arr, left, pivotIndex - 1);\n quicksort(arr, pivotIndex + 1, right);\n }\n }\n private int partition(int[] arr, int left, int right) \n {\n int pivotValue = arr[right];\n int i = left - 1;\n for (int j = left; j < right; j++) \n {\n if (arr[j] < pivotValue) \n {\n i++;\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n int temp = arr[i + 1];\n arr[i + 1] = arr[right];\n arr[right] = temp;\n return i + 1;\n } \n}\n```\n
2
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Solution
bag-of-tokens
1
1
```C++ []\nclass Solution {\npublic:\n int bagOfTokensScore(vector<int>& nums, int power) {\n sort(nums.begin(),nums.end());\n int i=0,j=nums.size()-1,score=0,ans=0;\n while(i<=j && i<nums.size()){\n if(score<=0&&power<nums[i])break;\n if(power>=nums[i]){\n while(i<nums.size()&&power>=nums[i]){\n score++;\n ans=max(ans,score);\n power-=nums[i];\n i++;\n }\n }\n else if(score>0 ) {power+=nums[j];j--;score--;}\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n coins = 0\n left, right = 0, len(tokens) - 1\n result = 0\n while left <= right:\n while left <= right and power >= tokens[left]:\n power -= tokens[left]\n coins += 1\n left += 1\n result = max(result, coins)\n if coins > 0:\n coins -= 1\n power += tokens[right]\n right -= 1\n else:\n break\n return result\n```\n\n```Java []\nclass Solution {\n public int bagOfTokensScore(int[] tokens, int power) {\n int score = 0,last=tokens.length,ans=0,i=0;\n quicksort(tokens,0,last-1);\n while(i<last && (power >= tokens[i] || score > 0)){\n if(power >= tokens[i]){\n power -= tokens[i];\n score++;\n i++;\n }\n else{\n score--;\n power += tokens[--last];\n }\n ans = Math.max(score,ans);\n }\n return ans;\n }\n private void quicksort(int[] arr, int left, int right) \n {\n if (left < right) \n {\n int pivotIndex = partition(arr, left, right);\n quicksort(arr, left, pivotIndex - 1);\n quicksort(arr, pivotIndex + 1, right);\n }\n }\n private int partition(int[] arr, int left, int right) \n {\n int pivotValue = arr[right];\n int i = left - 1;\n for (int j = left; j < right; j++) \n {\n if (arr[j] < pivotValue) \n {\n i++;\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n int temp = arr[i + 1];\n arr[i + 1] = arr[right];\n arr[right] = temp;\n return i + 1;\n } \n}\n```\n
2
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\] **Output:** \[8,6,2,4\] **Explanation:** At the beginning, the array is \[1,2,3,4\]. After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6. After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2. After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4. **Example 2:** **Input:** nums = \[1\], queries = \[\[4,0\]\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `1 <= queries.length <= 104` * `-104 <= vali <= 104` * `0 <= indexi < nums.length`
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
bag-of-tokens
1
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/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](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n**C++**\n\n```\n// Time Complexity: O(NlogN) (O(NlogN) for sorting & O(N) for two pointers.)\n// Space Complexity: O(logN)\n// where N is the number of tokens\nclass Solution {\npublic:\n int bagOfTokensScore(vector<int>& tokens, int power) {\n // play i-th token face up -> lose tokens[i] power -> choose the smallest one\n // play i-th token face down -> gain tokens[i] power -> choose the largest one\n // hence, sort tokens first\n sort(tokens.begin(), tokens.end());\n // two pointes - l for tracking face up & r for tracking face down\n int l = 0, r = tokens.size() - 1;\n int cur_score = 0, mx_score = 0;\n while (l <= r) {\n // there are 3 cases\n if (tokens[l] <= power) {\n // case 1. play l-th tokens face up if its power <= the current power\n // ---\n // losing tokens[l] power\n power -= tokens[l];\n // and gaining 1 score\n cur_score += 1;\n // cur_score can be mx_score potentially\n mx_score = max(mx_score, cur_score);\n // move the pointer to the right\n l += 1;\n } else if (cur_score >= 1) {\n // case 2. play r-th tokens face down if the current score is at least 1\n // ---\n // gaining tokens[r] power\n power += tokens[r];\n // and losing 1 score\n cur_score -= 1;\n // move the pointer to the left\n r -= 1;\n } else {\n // case 3. impossible to play\n\t\t\t\t// ---\n // either you don\'t enough power or enough score\n break;\n }\n }\n return mx_score;\n }\n};\n```\n\n\n**Python**\n\n```\n# Time Complexity: O(NlogN) (O(NlogN) for sorting & O(N) for two pointers.)\n# Space Complexity: O(N) - python\'s inbuilt sort uses TimSort\n# where N is the number of tokens\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n # play i-th token face up -> lose tokens[i] power -> choose the smallest one\n # play i-th token face down -> gain tokens[i] power -> choose the largest one\n # hence, sort tokens first\n tokens.sort()\n # two pointes - l for tracking face up & r for tracking face down\n l, r = 0, len(tokens) - 1\n cur_score = mx_score = 0\n while l <= r:\n # there are 3 cases\n if tokens[l] <= power:\n # case 1. play l-th tokens face up if its power <= the current power\n # ---\n # losing tokens[l] power\n power -= tokens[l]\n # and gaining 1 score\n cur_score += 1\n # cur_score can be mx_score potentially\n mx_score = max(mx_score, cur_score)\n # move the pointer to the right\n l += 1\n elif cur_score >= 1:\n # case 2. play r-th tokens face down if the current score is at least 1\n # ---\n # gaining tokens[r] power\n power += tokens[r]\n # and losing 1 score\n cur_score -= 1\n # move the pointer to the left\n r -= 1\n else:\n # case 3. impossible to play\n # ---\n # either you don\'t enough power or enough score\n break\n return mx_score\n```\n\n\n**Java**\n\n```\n// Time Complexity: O(NlogN) (O(NlogN) for sorting & O(N) for two pointers.)\n// Space Complexity: O(logN)\n// where N is the number of tokens\nclass Solution {\n public int bagOfTokensScore(int[] tokens, int power) {\n // play i-th token face up -> lose tokens[i] power -> choose the smallest one\n // play i-th token face down -> gain tokens[i] power -> choose the largest one\n // hence, sort tokens first\n Arrays.sort(tokens);\n // two pointes - l for tracking face up & r for tracking face down\n int l = 0, r = tokens.length - 1;\n int cur_score = 0, mx_score = 0;\n while (l <= r) {\n // there are 3 cases\n if (tokens[l] <= power) {\n // case 1. play l-th tokens face up if its power <= the current power\n // ---\n // losing tokens[l] power\n power -= tokens[l];\n // and gaining 1 score\n cur_score += 1;\n // cur_score can be mx_score potentially\n mx_score = Math.max(mx_score, cur_score);\n // move the pointer to the right\n l += 1;\n } else if (cur_score >= 1) {\n // case 2. play r-th tokens face down if the current score is at least 1\n // ---\n // gaining tokens[r] power\n power += tokens[r];\n // and losing 1 score\n cur_score -= 1;\n // move the pointer to the left\n r -= 1;\n } else {\n // case 3. impossible to play\n // ---\n // either you don\'t enough power or enough score\n break;\n }\n }\n return mx_score;\n }\n}\n```
45
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line
bag-of-tokens
1
1
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/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](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n**C++**\n\n```\n// Time Complexity: O(NlogN) (O(NlogN) for sorting & O(N) for two pointers.)\n// Space Complexity: O(logN)\n// where N is the number of tokens\nclass Solution {\npublic:\n int bagOfTokensScore(vector<int>& tokens, int power) {\n // play i-th token face up -> lose tokens[i] power -> choose the smallest one\n // play i-th token face down -> gain tokens[i] power -> choose the largest one\n // hence, sort tokens first\n sort(tokens.begin(), tokens.end());\n // two pointes - l for tracking face up & r for tracking face down\n int l = 0, r = tokens.size() - 1;\n int cur_score = 0, mx_score = 0;\n while (l <= r) {\n // there are 3 cases\n if (tokens[l] <= power) {\n // case 1. play l-th tokens face up if its power <= the current power\n // ---\n // losing tokens[l] power\n power -= tokens[l];\n // and gaining 1 score\n cur_score += 1;\n // cur_score can be mx_score potentially\n mx_score = max(mx_score, cur_score);\n // move the pointer to the right\n l += 1;\n } else if (cur_score >= 1) {\n // case 2. play r-th tokens face down if the current score is at least 1\n // ---\n // gaining tokens[r] power\n power += tokens[r];\n // and losing 1 score\n cur_score -= 1;\n // move the pointer to the left\n r -= 1;\n } else {\n // case 3. impossible to play\n\t\t\t\t// ---\n // either you don\'t enough power or enough score\n break;\n }\n }\n return mx_score;\n }\n};\n```\n\n\n**Python**\n\n```\n# Time Complexity: O(NlogN) (O(NlogN) for sorting & O(N) for two pointers.)\n# Space Complexity: O(N) - python\'s inbuilt sort uses TimSort\n# where N is the number of tokens\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n # play i-th token face up -> lose tokens[i] power -> choose the smallest one\n # play i-th token face down -> gain tokens[i] power -> choose the largest one\n # hence, sort tokens first\n tokens.sort()\n # two pointes - l for tracking face up & r for tracking face down\n l, r = 0, len(tokens) - 1\n cur_score = mx_score = 0\n while l <= r:\n # there are 3 cases\n if tokens[l] <= power:\n # case 1. play l-th tokens face up if its power <= the current power\n # ---\n # losing tokens[l] power\n power -= tokens[l]\n # and gaining 1 score\n cur_score += 1\n # cur_score can be mx_score potentially\n mx_score = max(mx_score, cur_score)\n # move the pointer to the right\n l += 1\n elif cur_score >= 1:\n # case 2. play r-th tokens face down if the current score is at least 1\n # ---\n # gaining tokens[r] power\n power += tokens[r]\n # and losing 1 score\n cur_score -= 1\n # move the pointer to the left\n r -= 1\n else:\n # case 3. impossible to play\n # ---\n # either you don\'t enough power or enough score\n break\n return mx_score\n```\n\n\n**Java**\n\n```\n// Time Complexity: O(NlogN) (O(NlogN) for sorting & O(N) for two pointers.)\n// Space Complexity: O(logN)\n// where N is the number of tokens\nclass Solution {\n public int bagOfTokensScore(int[] tokens, int power) {\n // play i-th token face up -> lose tokens[i] power -> choose the smallest one\n // play i-th token face down -> gain tokens[i] power -> choose the largest one\n // hence, sort tokens first\n Arrays.sort(tokens);\n // two pointes - l for tracking face up & r for tracking face down\n int l = 0, r = tokens.length - 1;\n int cur_score = 0, mx_score = 0;\n while (l <= r) {\n // there are 3 cases\n if (tokens[l] <= power) {\n // case 1. play l-th tokens face up if its power <= the current power\n // ---\n // losing tokens[l] power\n power -= tokens[l];\n // and gaining 1 score\n cur_score += 1;\n // cur_score can be mx_score potentially\n mx_score = Math.max(mx_score, cur_score);\n // move the pointer to the right\n l += 1;\n } else if (cur_score >= 1) {\n // case 2. play r-th tokens face down if the current score is at least 1\n // ---\n // gaining tokens[r] power\n power += tokens[r];\n // and losing 1 score\n cur_score -= 1;\n // move the pointer to the left\n r -= 1;\n } else {\n // case 3. impossible to play\n // ---\n // either you don\'t enough power or enough score\n break;\n }\n }\n return mx_score;\n }\n}\n```
45
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\] **Output:** \[8,6,2,4\] **Explanation:** At the beginning, the array is \[1,2,3,4\]. After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6. After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2. After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4. **Example 2:** **Input:** nums = \[1\], queries = \[\[4,0\]\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `1 <= queries.length <= 104` * `-104 <= vali <= 104` * `0 <= indexi < nums.length`
null
Python | O(n logn) | Two-Pointer approach | Well-explained
bag-of-tokens
0
1
we need to check for two conditions \n1. `power >= tokens[i]`. Here, we lose power and gain score.\n2. `score >= 1`. Here, we lose score to gain power.\n\nKeeping `ans` variable to keep counter of max score we can achieve.\n\n* Sort the array in increasing order\n* Keep two pointers at extreme ends ```i = 0``` and ```j = len(tokens)```.\n* Keep looping till ` i < j`.\n* If we have enough` power ` to the selected `token[i]`, we will decrease `power = power - token[i]` and increase score by 1 `score += 1`. update `ans = max(ans, score)`.\n* If `score >= 1` we will increase `power += token[j]` and decrease `score -= 1`.\n* If nothing matches, means we found an ans, here we break the loop and `return ans`\n\n\n```\n\tn = len(tokens)\n i = 0\n j = n\n score = 0\n ans = 0\n tokens.sort()\n \n while i < j:\n if power >= tokens[i]:\n power -= tokens[i]\n score+=1\n i+=1\n ans = max(ans, score)\n elif score >= 1 and j > i + 1:\n j-=1\n power += tokens[j]\n score-=1\n else: \n return ans\n \n return ans\n```\n\n**Please Upvote if you like this solution!**
4
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Python | O(n logn) | Two-Pointer approach | Well-explained
bag-of-tokens
0
1
we need to check for two conditions \n1. `power >= tokens[i]`. Here, we lose power and gain score.\n2. `score >= 1`. Here, we lose score to gain power.\n\nKeeping `ans` variable to keep counter of max score we can achieve.\n\n* Sort the array in increasing order\n* Keep two pointers at extreme ends ```i = 0``` and ```j = len(tokens)```.\n* Keep looping till ` i < j`.\n* If we have enough` power ` to the selected `token[i]`, we will decrease `power = power - token[i]` and increase score by 1 `score += 1`. update `ans = max(ans, score)`.\n* If `score >= 1` we will increase `power += token[j]` and decrease `score -= 1`.\n* If nothing matches, means we found an ans, here we break the loop and `return ans`\n\n\n```\n\tn = len(tokens)\n i = 0\n j = n\n score = 0\n ans = 0\n tokens.sort()\n \n while i < j:\n if power >= tokens[i]:\n power -= tokens[i]\n score+=1\n i+=1\n ans = max(ans, score)\n elif score >= 1 and j > i + 1:\n j-=1\n power += tokens[j]\n score-=1\n else: \n return ans\n \n return ans\n```\n\n**Please Upvote if you like this solution!**
4
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\] **Output:** \[8,6,2,4\] **Explanation:** At the beginning, the array is \[1,2,3,4\]. After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6. After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2. After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4. **Example 2:** **Input:** nums = \[1\], queries = \[\[4,0\]\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `1 <= queries.length <= 104` * `-104 <= vali <= 104` * `0 <= indexi < nums.length`
null
Python3. || 12 lines, iterative, deque || T/M: 92%/40%
bag-of-tokens
0
1
It pretty much explains itself.\n```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n \n tokens, ans, score = deque(sorted(tokens)), 0, 0\n \n while tokens:\n if tokens[0] <= power:\n power -= tokens.popleft()\n score += 1\n ans = max(ans, score)\n\n elif score > 0:\n power += tokens.pop()\n score -= 1\n \n else:\n return ans\n \n return ans
3
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Python3. || 12 lines, iterative, deque || T/M: 92%/40%
bag-of-tokens
0
1
It pretty much explains itself.\n```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n \n tokens, ans, score = deque(sorted(tokens)), 0, 0\n \n while tokens:\n if tokens[0] <= power:\n power -= tokens.popleft()\n score += 1\n ans = max(ans, score)\n\n elif score > 0:\n power += tokens.pop()\n score -= 1\n \n else:\n return ans\n \n return ans
3
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\] **Output:** \[8,6,2,4\] **Explanation:** At the beginning, the array is \[1,2,3,4\]. After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6. After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2. After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4. **Example 2:** **Input:** nums = \[1\], queries = \[\[4,0\]\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `1 <= queries.length <= 104` * `-104 <= vali <= 104` * `0 <= indexi < nums.length`
null
[Python3] Runtime: 55 ms, faster than 98.92% | Memory: 13.9 MB, less than 97.17%
bag-of-tokens
0
1
```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n i,j = 0,len(tokens)-1\n points = maxPoints = 0\n while i<=j:\n if power>=tokens[i]:\n power-=tokens[i]\n points+=1\n maxPoints = max(maxPoints,points)\n i+=1\n elif points>0:\n points-=1\n power+=tokens[j]\n j-=1\n else:\n return maxPoints\n return maxPoints \n```
2
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
[Python3] Runtime: 55 ms, faster than 98.92% | Memory: 13.9 MB, less than 97.17%
bag-of-tokens
0
1
```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n i,j = 0,len(tokens)-1\n points = maxPoints = 0\n while i<=j:\n if power>=tokens[i]:\n power-=tokens[i]\n points+=1\n maxPoints = max(maxPoints,points)\n i+=1\n elif points>0:\n points-=1\n power+=tokens[j]\n j-=1\n else:\n return maxPoints\n return maxPoints \n```
2
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\] **Output:** \[8,6,2,4\] **Explanation:** At the beginning, the array is \[1,2,3,4\]. After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6. After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2. After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4. **Example 2:** **Input:** nums = \[1\], queries = \[\[4,0\]\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `1 <= queries.length <= 104` * `-104 <= vali <= 104` * `0 <= indexi < nums.length`
null
Easy Python Solution || Two Pointer approach
bag-of-tokens
0
1
```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n l,r = 0, len(tokens)-1\n curr_score = 0\n max_score = 0\n while l <= r:\n if(tokens[l] <= power):\n power -= tokens[l]\n curr_score += 1\n l += 1\n max_score = max(max_score, curr_score)\n elif(curr_score > 0):\n power += tokens[r]\n curr_score -= 1\n r -= 1\n max_score = max(max_score, curr_score)\n else:\n break\n return max_score\n```
2
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Easy Python Solution || Two Pointer approach
bag-of-tokens
0
1
```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n tokens.sort()\n l,r = 0, len(tokens)-1\n curr_score = 0\n max_score = 0\n while l <= r:\n if(tokens[l] <= power):\n power -= tokens[l]\n curr_score += 1\n l += 1\n max_score = max(max_score, curr_score)\n elif(curr_score > 0):\n power += tokens[r]\n curr_score -= 1\n r -= 1\n max_score = max(max_score, curr_score)\n else:\n break\n return max_score\n```
2
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\] **Output:** \[8,6,2,4\] **Explanation:** At the beginning, the array is \[1,2,3,4\]. After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6. After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2. After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4. **Example 2:** **Input:** nums = \[1\], queries = \[\[4,0\]\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `1 <= queries.length <= 104` * `-104 <= vali <= 104` * `0 <= indexi < nums.length`
null
Greedy || Single Loop solution || Python 3
bag-of-tokens
0
1
# Intuition\nIts a greedy problem where for addition of more score you have to choose min of token or for addition of power max token.\n\n# Approach\nSort your array (as you can choose in any order) and checkfew base cases :-\n`1. Is your token bag empty`\n`2. Is the power given is too less to even perform one head up (head up can only be performed if curr val < power)`\n`3. If tokens are there but powere is 0 (you cannot perform any head up)`\nNow by question we can add score by choosing numbers within power range so try to choose as min as possible so the resultant power(power - tokens[i]) is largest and then pop the element.\n`Why Pop?` Because you can perform only one activity at one token. \nOnce u exhaust all your min score choose a max score to update the power to its max value and try to perform choosing of min again.\nMaintain a maxScore count with every action perform.\n\n# Code\n```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n if not tokens or min(tokens) > power or (power == 0 and tokens):\n return 0\n tokens.sort()\n maxScore = score = i = 0\n while i < len(tokens) and tokens:\n if tokens[i] <= power:\n power -= tokens[i]\n score += 1\n tokens.pop(i)\n else:\n power += tokens[-1]\n score -= 1\n tokens.pop()\n continue\n maxScore = max(maxScore, score)\n return maxScore\n\n```
1
You have an initial **power** of `power`, an initial **score** of `0`, and a bag of `tokens` where `tokens[i]` is the value of the `ith` token (0-indexed). Your goal is to maximize your total **score** by potentially playing each token in one of two ways: * If your current **power** is at least `tokens[i]`, you may play the `ith` token face up, losing `tokens[i]` **power** and gaining `1` **score**. * If your current **score** is at least `1`, you may play the `ith` token face down, gaining `tokens[i]` **power** and losing `1` **score**. Each token may be played **at most** once and **in any order**. You do **not** have to play all the tokens. Return _the largest possible **score** you can achieve after playing any number of tokens_. **Example 1:** **Input:** tokens = \[100\], power = 50 **Output:** 0 **Explanation****:** Playing the only token in the bag is impossible because you either have too little power or too little score. **Example 2:** **Input:** tokens = \[100,200\], power = 150 **Output:** 1 **Explanation:** Play the 0th token (100) face up, your power becomes 50 and score becomes 1. There is no need to play the 1st token since you cannot play it face up to add to your score. **Example 3:** **Input:** tokens = \[100,200,300,400\], power = 200 **Output:** 2 **Explanation:** Play the tokens in this order to get a score of 2: 1. Play the 0th token (100) face up, your power becomes 100 and score becomes 1. 2. Play the 3rd token (400) face down, your power becomes 500 and score becomes 0. 3. Play the 1st token (200) face up, your power becomes 300 and score becomes 1. 4. Play the 2nd token (300) face up, your power becomes 0 and score becomes 2. **Constraints:** * `0 <= tokens.length <= 1000` * `0 <= tokens[i], power < 104`
null
Greedy || Single Loop solution || Python 3
bag-of-tokens
0
1
# Intuition\nIts a greedy problem where for addition of more score you have to choose min of token or for addition of power max token.\n\n# Approach\nSort your array (as you can choose in any order) and checkfew base cases :-\n`1. Is your token bag empty`\n`2. Is the power given is too less to even perform one head up (head up can only be performed if curr val < power)`\n`3. If tokens are there but powere is 0 (you cannot perform any head up)`\nNow by question we can add score by choosing numbers within power range so try to choose as min as possible so the resultant power(power - tokens[i]) is largest and then pop the element.\n`Why Pop?` Because you can perform only one activity at one token. \nOnce u exhaust all your min score choose a max score to update the power to its max value and try to perform choosing of min again.\nMaintain a maxScore count with every action perform.\n\n# Code\n```\nclass Solution:\n def bagOfTokensScore(self, tokens: List[int], power: int) -> int:\n if not tokens or min(tokens) > power or (power == 0 and tokens):\n return 0\n tokens.sort()\n maxScore = score = i = 0\n while i < len(tokens) and tokens:\n if tokens[i] <= power:\n power -= tokens[i]\n score += 1\n tokens.pop(i)\n else:\n power += tokens[-1]\n score -= 1\n tokens.pop()\n continue\n maxScore = max(maxScore, score)\n return maxScore\n\n```
1
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`. For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`. Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_. **Example 1:** **Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\] **Output:** \[8,6,2,4\] **Explanation:** At the beginning, the array is \[1,2,3,4\]. After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8. After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6. After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2. After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4. **Example 2:** **Input:** nums = \[1\], queries = \[\[4,0\]\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `1 <= queries.length <= 104` * `-104 <= vali <= 104` * `0 <= indexi < nums.length`
null
Easy | Python Solution | Strings | Permutations
largest-time-for-given-digits
0
1
# Code\n```\nfrom itertools import permutations\n\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n\n x = permutations(arr)\n ans = []\n currTime = ""\n for i in x:\n h, m = "", ""\n for j in i[:2]:\n h += str(j)\n for j in i[2:]:\n m += str(j)\n \n if h >= "00" and h <= "23" and m >= "00" and m <= "59":\n if currTime == "":\n currTime = f"{h}:{m}"\n else:\n if currTime < f"{h}:{m}":\n currTime = f"{h}:{m}"\n return currTime\n\n```
1
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Easy | Python Solution | Strings | Permutations
largest-time-for-given-digits
0
1
# Code\n```\nfrom itertools import permutations\n\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n\n x = permutations(arr)\n ans = []\n currTime = ""\n for i in x:\n h, m = "", ""\n for j in i[:2]:\n h += str(j)\n for j in i[2:]:\n m += str(j)\n \n if h >= "00" and h <= "23" and m >= "00" and m <= "59":\n if currTime == "":\n currTime = f"{h}:{m}"\n else:\n if currTime < f"{h}:{m}":\n currTime = f"{h}:{m}"\n return currTime\n\n```
1
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
Solution
largest-time-for-given-digits
1
1
```C++ []\nclass Solution {\npublic:\n string largestTimeFromDigits(vector<int>& arr) {\n sort(arr.begin(), arr.end(), greater<int>());\n do{\n int hours = arr[0] * 10 + arr[1];\n int minutes = arr[2] * 10 + arr[3];\n \n if(hours<24 && minutes<60){\n string time = "";\n if(hours<10){\n time+="0";\n }\n time += to_string(hours);\n time += ":";\n \n if(minutes<10){\n time += "0";\n }\n \n time += to_string(minutes);\n return time;\n }\n }while(prev_permutation(arr.begin(), arr.end()));\n \n return "";\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n curMax = -1\n curStr = ""\n for permutation in set(permutations(arr)):\n a, b, c, d = permutation\n hours = a*10 + b\n minutes = c*10 + d\n if hours > 23 or minutes > 59:\n pass\n elif hours*60 + minutes > curMax:\n curMax = hours*60 + minutes\n curStr = str(a) + str(b) + ":" + str(c) + str(d)\n\n return curStr\n```\n\n```Java []\nclass Solution {\n private boolean rearrange(int maxValue,int index,int[] a){\n int max = -1;\n\t\t\n for(int i = index; i<a.length;i++) if(a[i]<=maxValue && (max==-1 || a[max]<a[i])) max = i;\n if(max==-1) return false;\n\n int temp = a[max];\n a[max] = a[index];\n a[index] = temp;\n return true;\n }\n public String largestTimeFromDigits(int[] a) {\n boolean res = (rearrange(2,0,a) && (a[0]==2 ? rearrange(3,1,a) : rearrange(9,1,a)) && rearrange(5,2,a) && rearrange(9,3,a)) || (rearrange(1,0,a) && rearrange(9,1,a) && rearrange(5,2,a) && rearrange(9,3,a));\n \n StringBuilder sb = new StringBuilder();\n \n if(!res) return sb.toString();\n \n return sb.append(String.valueOf(a[0]))\n .append(String.valueOf(a[1]))\n .append(\':\')\n .append(String.valueOf(a[2]))\n .append(String.valueOf(a[3])).toString();\n }\n}\n```\n
3
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Solution
largest-time-for-given-digits
1
1
```C++ []\nclass Solution {\npublic:\n string largestTimeFromDigits(vector<int>& arr) {\n sort(arr.begin(), arr.end(), greater<int>());\n do{\n int hours = arr[0] * 10 + arr[1];\n int minutes = arr[2] * 10 + arr[3];\n \n if(hours<24 && minutes<60){\n string time = "";\n if(hours<10){\n time+="0";\n }\n time += to_string(hours);\n time += ":";\n \n if(minutes<10){\n time += "0";\n }\n \n time += to_string(minutes);\n return time;\n }\n }while(prev_permutation(arr.begin(), arr.end()));\n \n return "";\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n curMax = -1\n curStr = ""\n for permutation in set(permutations(arr)):\n a, b, c, d = permutation\n hours = a*10 + b\n minutes = c*10 + d\n if hours > 23 or minutes > 59:\n pass\n elif hours*60 + minutes > curMax:\n curMax = hours*60 + minutes\n curStr = str(a) + str(b) + ":" + str(c) + str(d)\n\n return curStr\n```\n\n```Java []\nclass Solution {\n private boolean rearrange(int maxValue,int index,int[] a){\n int max = -1;\n\t\t\n for(int i = index; i<a.length;i++) if(a[i]<=maxValue && (max==-1 || a[max]<a[i])) max = i;\n if(max==-1) return false;\n\n int temp = a[max];\n a[max] = a[index];\n a[index] = temp;\n return true;\n }\n public String largestTimeFromDigits(int[] a) {\n boolean res = (rearrange(2,0,a) && (a[0]==2 ? rearrange(3,1,a) : rearrange(9,1,a)) && rearrange(5,2,a) && rearrange(9,3,a)) || (rearrange(1,0,a) && rearrange(9,1,a) && rearrange(5,2,a) && rearrange(9,3,a));\n \n StringBuilder sb = new StringBuilder();\n \n if(!res) return sb.toString();\n \n return sb.append(String.valueOf(a[0]))\n .append(String.valueOf(a[1]))\n .append(\':\')\n .append(String.valueOf(a[2]))\n .append(String.valueOf(a[3])).toString();\n }\n}\n```\n
3
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
Python simple Solution Explained (video + code)
largest-time-for-given-digits
0
1
[](https://www.youtube.com/watch?v=QJeI-gBTp1k)\nhttps://www.youtube.com/watch?v=QJeI-gBTp1k\n```\nfrom itertools import permutations\nclass Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n arr = list(permutations(sorted(A, reverse=True)))\n \n for h1, h2, m1, m2 in arr:\n if h1 * 10 + h2 < 24 and m1 * 10 + m2 < 60:\n return f\'{h1}{h2}:{m1}{m2}\'\n return \'\'\n```
9
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Python simple Solution Explained (video + code)
largest-time-for-given-digits
0
1
[](https://www.youtube.com/watch?v=QJeI-gBTp1k)\nhttps://www.youtube.com/watch?v=QJeI-gBTp1k\n```\nfrom itertools import permutations\nclass Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n arr = list(permutations(sorted(A, reverse=True)))\n \n for h1, h2, m1, m2 in arr:\n if h1 * 10 + h2 < 24 and m1 * 10 + m2 < 60:\n return f\'{h1}{h2}:{m1}{m2}\'\n return \'\'\n```
9
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
Python3 - Easy understanding (With explanation)
largest-time-for-given-digits
0
1
```\nclass Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n# From 23:59 to 00:00 go over every minute of 24 hours. If A meets this requirement, then totaly 24 * 60 minutes. Since using sort during the ongoing judegment process, so the time complexity is low.\n A.sort()\n for h in range(23, -1, -1):\n for m in range(59, -1, -1):\n t = [h//10, h % 10, m // 10, m % 10]\n ts = sorted(t)\n if ts == A:\n return str(t[0]) + str(t[1]) +\':\' + str(t[2]) + str(t[3])\n return \'\'\n \n```
10
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Python3 - Easy understanding (With explanation)
largest-time-for-given-digits
0
1
```\nclass Solution:\n def largestTimeFromDigits(self, A: List[int]) -> str:\n# From 23:59 to 00:00 go over every minute of 24 hours. If A meets this requirement, then totaly 24 * 60 minutes. Since using sort during the ongoing judegment process, so the time complexity is low.\n A.sort()\n for h in range(23, -1, -1):\n for m in range(59, -1, -1):\n t = [h//10, h % 10, m // 10, m % 10]\n ts = sorted(t)\n if ts == A:\n return str(t[0]) + str(t[1]) +\':\' + str(t[2]) + str(t[3])\n return \'\'\n \n```
10
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
Python3 Solution using itertools.permutations()
largest-time-for-given-digits
0
1
# Code\n```\nfrom itertools import permutations \nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n time=[]\n for i in permutations(arr):\n if str(i[0])+str(i[1])<"24" and str(i[2])+str(i[3])<"60":\n time.append(str(i[0])+str(i[1])+":"+str(i[2])+str(i[3]))\n \n return max(time) if time else ""\n \n \n```
1
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Python3 Solution using itertools.permutations()
largest-time-for-given-digits
0
1
# Code\n```\nfrom itertools import permutations \nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n time=[]\n for i in permutations(arr):\n if str(i[0])+str(i[1])<"24" and str(i[2])+str(i[3])<"60":\n time.append(str(i[0])+str(i[1])+":"+str(i[2])+str(i[3]))\n \n return max(time) if time else ""\n \n \n```
1
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
Simple solution in Python
largest-time-for-given-digits
0
1
\n\n# Approach 1\nBy using simple iteration through loop and by using pointers.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: 41 ms\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.2 MB\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# class Solution:\n# def largestTimeFromDigits(self, arr: List[int]) -> str:\n# result = ""\n# for i in range(4):\n# for j in range(4):\n# for k in range(4): \n# if i==j or i==k or j==k:\n# continue\n# else:\n# hh = str(arr[i]) + str(arr[j])\n# mm = str(arr[k]) + str(arr[6-i-j-k])\n# time = hh + ":" + mm\n# if (hh < "24" and mm < "60" and time > result):\n# result = time\n# return result\n\n```\n\n# Approach 2\nBy using permutations module in python\n\n\n# Complexity\n- Time complexity: 47 ms\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.2 MB\n\n# Code\n\n```\nfrom itertools import permutations\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n A = list(permutations(sorted(arr, reverse=True)))\n \n for h1, h2, m1, m2 in A:\n if h1 * 10 + h2 < 24 and m1 * 10 + m2 < 60:\n return f\'{h1}{h2}:{m1}{m2}\'\n return \'\' \n```
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Simple solution in Python
largest-time-for-given-digits
0
1
\n\n# Approach 1\nBy using simple iteration through loop and by using pointers.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: 41 ms\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.2 MB\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# class Solution:\n# def largestTimeFromDigits(self, arr: List[int]) -> str:\n# result = ""\n# for i in range(4):\n# for j in range(4):\n# for k in range(4): \n# if i==j or i==k or j==k:\n# continue\n# else:\n# hh = str(arr[i]) + str(arr[j])\n# mm = str(arr[k]) + str(arr[6-i-j-k])\n# time = hh + ":" + mm\n# if (hh < "24" and mm < "60" and time > result):\n# result = time\n# return result\n\n```\n\n# Approach 2\nBy using permutations module in python\n\n\n# Complexity\n- Time complexity: 47 ms\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.2 MB\n\n# Code\n\n```\nfrom itertools import permutations\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n A = list(permutations(sorted(arr, reverse=True)))\n \n for h1, h2, m1, m2 in A:\n if h1 * 10 + h2 < 24 and m1 * 10 + m2 < 60:\n return f\'{h1}{h2}:{m1}{m2}\'\n return \'\' \n```
0
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
O(1) Brute force approach using itertools.permutations()
largest-time-for-given-digits
0
1
\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n max_time = -1\n\n for h1, h2, m1, m2 in permutations(arr):\n hours = h1 * 10 + h2\n minutes = m1 * 10 + m2\n\n curr_time = hours * 100 + minutes\n\n if 0 <= hours <= 23 and 0 <= minutes <= 59 and curr_time > max_time:\n max_time = curr_time\n\n return "{:02d}:{:02d}".format(max_time // 100, max_time % 100) if max_time != -1 else ""\n```
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
O(1) Brute force approach using itertools.permutations()
largest-time-for-given-digits
0
1
\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n max_time = -1\n\n for h1, h2, m1, m2 in permutations(arr):\n hours = h1 * 10 + h2\n minutes = m1 * 10 + m2\n\n curr_time = hours * 100 + minutes\n\n if 0 <= hours <= 23 and 0 <= minutes <= 59 and curr_time > max_time:\n max_time = curr_time\n\n return "{:02d}:{:02d}".format(max_time // 100, max_time % 100) if max_time != -1 else ""\n```
0
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
Solution with itertools.permutations method
largest-time-for-given-digits
0
1
# Complexity\n- Time complexity: `O(1)`\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)$$ -->\nSee coments for explanation ^\n\n# Code\n```\n# Clarification:\n\n# Test cases:\n\n# Notes:\n# earliest 00:00 and latest 23:59\n# hh < 24 and mm < 60\n\n# Plan:\n# sort the input array in reverse order, because we want to give the greatest valid number from left to right.\n# Get permutations with reversed sorted array and check if it\'s valid. The permutations will go from greatest to smallest, and so if valid, it will return the greatest valid hour.\n# Otherwise, if invalid, returns empty string.\n\n# Time: O(1)\n# Our string consists of four digits and we are given 4 digits in the input arr. For the first place we have N options, for the second we have N - 1, and so on, which is equivalent to N!.\n# However, since we know that our input array will always be 4:\n# Permutations = 4!\n# Sorting = 4 log (4)\n# Both of this result in O(1)\n\n# Space: O(1)\n# because list with permutations will contain 4! = O(1) space.\n\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n lst = list(permutations(sorted(arr, reverse = True)))\n\n for h1, h2, m1, m2 in lst:\n if h1 * 10 + h2 < 24 and m1 * 10 + m2 < 60:\n return f"{h1}{h2}:{m1}{m2}"\n \n return ""\n \n```
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Solution with itertools.permutations method
largest-time-for-given-digits
0
1
# Complexity\n- Time complexity: `O(1)`\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)$$ -->\nSee coments for explanation ^\n\n# Code\n```\n# Clarification:\n\n# Test cases:\n\n# Notes:\n# earliest 00:00 and latest 23:59\n# hh < 24 and mm < 60\n\n# Plan:\n# sort the input array in reverse order, because we want to give the greatest valid number from left to right.\n# Get permutations with reversed sorted array and check if it\'s valid. The permutations will go from greatest to smallest, and so if valid, it will return the greatest valid hour.\n# Otherwise, if invalid, returns empty string.\n\n# Time: O(1)\n# Our string consists of four digits and we are given 4 digits in the input arr. For the first place we have N options, for the second we have N - 1, and so on, which is equivalent to N!.\n# However, since we know that our input array will always be 4:\n# Permutations = 4!\n# Sorting = 4 log (4)\n# Both of this result in O(1)\n\n# Space: O(1)\n# because list with permutations will contain 4! = O(1) space.\n\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n lst = list(permutations(sorted(arr, reverse = True)))\n\n for h1, h2, m1, m2 in lst:\n if h1 * 10 + h2 < 24 and m1 * 10 + m2 < 60:\n return f"{h1}{h2}:{m1}{m2}"\n \n return ""\n \n```
0
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
Simple verbose python solution
largest-time-for-given-digits
0
1
\n# Complexity\n- Time complexity: since len(arr) is a constant the time compexity of this slution is O(1)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n \n \n hours = []\n # find all posible valid hour permutations in sorted order\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n hour = arr[i] * 10 + arr[j]\n if hour < 24:\n hours.append((hour, i, j))\n hour = arr[j] * 10 + arr[i] \n if hour < 24:\n hours.append((hour, j, i))\n hours = sorted(hours, reverse=True)\n\n # find all possible valid minute permutations that go with the \n # specific hour\n for hour, i, j in hours:\n \n for k in range(len(arr)):\n for l in range(k + 1, len(arr)):\n if k != i and k != j and l != i and l != j:\n minute1, minute2 = None, None\n min = arr[k] * 10 + arr[l]\n if min < 60:\n minute1 = min\n \n min = arr[l] * 10 + arr[k]\n if min < 60:\n minute2 = min\n \n if minute1 == None and minute2 == None:\n continue\n \n if minute1 == None:\n max_min = minute2\n \n elif minute2 == None:\n max_min = minute1\n else:\n max_min = max(minute1, minute2)\n \n hour_str = f"{hour}" if hour > 9 else f"0{hour}"\n min_str = f"{max_min}" if max_min > 9 else f"0{max_min}"\n \n return f"{hour_str}:{min_str}"\n return ""\n \n\n```
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Simple verbose python solution
largest-time-for-given-digits
0
1
\n# Complexity\n- Time complexity: since len(arr) is a constant the time compexity of this slution is O(1)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n \n \n hours = []\n # find all posible valid hour permutations in sorted order\n for i in range(len(arr)):\n for j in range(i + 1, len(arr)):\n hour = arr[i] * 10 + arr[j]\n if hour < 24:\n hours.append((hour, i, j))\n hour = arr[j] * 10 + arr[i] \n if hour < 24:\n hours.append((hour, j, i))\n hours = sorted(hours, reverse=True)\n\n # find all possible valid minute permutations that go with the \n # specific hour\n for hour, i, j in hours:\n \n for k in range(len(arr)):\n for l in range(k + 1, len(arr)):\n if k != i and k != j and l != i and l != j:\n minute1, minute2 = None, None\n min = arr[k] * 10 + arr[l]\n if min < 60:\n minute1 = min\n \n min = arr[l] * 10 + arr[k]\n if min < 60:\n minute2 = min\n \n if minute1 == None and minute2 == None:\n continue\n \n if minute1 == None:\n max_min = minute2\n \n elif minute2 == None:\n max_min = minute1\n else:\n max_min = max(minute1, minute2)\n \n hour_str = f"{hour}" if hour > 9 else f"0{hour}"\n min_str = f"{max_min}" if max_min > 9 else f"0{max_min}"\n \n return f"{hour_str}:{min_str}"\n return ""\n \n\n```
0
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
Most Intuitive Approach
largest-time-for-given-digits
0
1
# Complexity\n- Time complexity: $$O(1)$$.\n\n- Space complexity: $$O(1)$$.\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n time = []\n\n for dig in (2, 1, 0) if sum(1 for dig in arr if dig > 5) < 2 else (1, 0):\n if dig in arr:\n time.append(dig)\n arr.remove(dig)\n break\n\n if len(time) < 1:\n return \'\'\n \n for dig in (3, 2, 1, 0) if time[0] == 2 else range(9, -1, -1):\n if dig in arr:\n time.append(dig)\n arr.remove(dig)\n break\n\n if len(time) < 2:\n return \'\'\n \n for dig in range(5, -1, -1):\n if dig in arr:\n time.append(dig)\n arr.remove(dig)\n break\n \n if len(time) < 3:\n return \'\'\n \n time.append(arr[0])\n\n return f\'{time[0]}{time[1]}:{time[2]}{time[3]}\'\n```
0
Given an array `arr` of 4 digits, find the latest 24-hour time that can be made using each digit **exactly once**. 24-hour times are formatted as `"HH:MM "`, where `HH` is between `00` and `23`, and `MM` is between `00` and `59`. The earliest 24-hour time is `00:00`, and the latest is `23:59`. Return _the latest 24-hour time in `"HH:MM "` format_. If no valid time can be made, return an empty string. **Example 1:** **Input:** arr = \[1,2,3,4\] **Output:** "23:41 " **Explanation:** The valid 24-hour times are "12:34 ", "12:43 ", "13:24 ", "13:42 ", "14:23 ", "14:32 ", "21:34 ", "21:43 ", "23:14 ", and "23:41 ". Of these times, "23:41 " is the latest. **Example 2:** **Input:** arr = \[5,5,5,5\] **Output:** " " **Explanation:** There are no valid 24-hour times as "55:55 " is not valid. **Constraints:** * `arr.length == 4` * `0 <= arr[i] <= 9`
null
Most Intuitive Approach
largest-time-for-given-digits
0
1
# Complexity\n- Time complexity: $$O(1)$$.\n\n- Space complexity: $$O(1)$$.\n\n# Code\n```\nclass Solution:\n def largestTimeFromDigits(self, arr: List[int]) -> str:\n time = []\n\n for dig in (2, 1, 0) if sum(1 for dig in arr if dig > 5) < 2 else (1, 0):\n if dig in arr:\n time.append(dig)\n arr.remove(dig)\n break\n\n if len(time) < 1:\n return \'\'\n \n for dig in (3, 2, 1, 0) if time[0] == 2 else range(9, -1, -1):\n if dig in arr:\n time.append(dig)\n arr.remove(dig)\n break\n\n if len(time) < 2:\n return \'\'\n \n for dig in range(5, -1, -1):\n if dig in arr:\n time.append(dig)\n arr.remove(dig)\n break\n \n if len(time) < 3:\n return \'\'\n \n time.append(arr[0])\n\n return f\'{time[0]}{time[1]}:{time[2]}{time[3]}\'\n```
0
You are given two lists of closed intervals, `firstList` and `secondList`, where `firstList[i] = [starti, endi]` and `secondList[j] = [startj, endj]`. Each list of intervals is pairwise **disjoint** and in **sorted order**. Return _the intersection of these two interval lists_. A **closed interval** `[a, b]` (with `a <= b`) denotes the set of real numbers `x` with `a <= x <= b`. The **intersection** of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of `[1, 3]` and `[2, 4]` is `[2, 3]`. **Example 1:** **Input:** firstList = \[\[0,2\],\[5,10\],\[13,23\],\[24,25\]\], secondList = \[\[1,5\],\[8,12\],\[15,24\],\[25,26\]\] **Output:** \[\[1,2\],\[5,5\],\[8,10\],\[15,23\],\[24,24\],\[25,25\]\] **Example 2:** **Input:** firstList = \[\[1,3\],\[5,9\]\], secondList = \[\] **Output:** \[\] **Constraints:** * `0 <= firstList.length, secondList.length <= 1000` * `firstList.length + secondList.length >= 1` * `0 <= starti < endi <= 109` * `endi < starti+1` * `0 <= startj < endj <= 109` * `endj < startj+1`
null
Simple Approach
reveal-cards-in-increasing-order
0
1
# Code\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n def reveal(n):\n lst = list(range(n))\n ans = []\n i = 0\n while lst:\n if not i&1: ans.append(lst.pop(0))\n else: lst.append(lst.pop(0))\n i += 1\n return ans\n ans = reveal(len(deck))\n ans = sorted([v, i] for i, v in enumerate(ans))\n deck.sort()\n return (deck[j] for i,j in ans)\n```
1
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
Simple Approach
reveal-cards-in-increasing-order
0
1
# Code\n```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n def reveal(n):\n lst = list(range(n))\n ans = []\n i = 0\n while lst:\n if not i&1: ans.append(lst.pop(0))\n else: lst.append(lst.pop(0))\n i += 1\n return ans\n ans = reveal(len(deck))\n ans = sorted([v, i] for i, v in enumerate(ans))\n deck.sort()\n return (deck[j] for i,j in ans)\n```
1
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return _the **vertical order traversal** of the binary tree_. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Explanation:** Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. **Example 2:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. **Example 3:** **Input:** root = \[1,2,3,4,6,5,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 1000`
null
Solution
reveal-cards-in-increasing-order
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int>q;\n int n=deck.size();\n sort(deck.begin(),deck.end());;\n for(int i=0;i<n;i++)\n q.push(i);\n vector<int>res(n,0);\n int i=0;\n while(!q.empty() && i<n){\n int index=q.front();\n q.pop();\n res[index]=deck[i++];\n q.push(q.front());\n q.pop();\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution(object):\n def deckRevealedIncreasing(self, deck):\n N = len(deck)\n index = collections.deque(range(N))\n ans = [None] * N\n\n for card in sorted(deck):\n ans[index.popleft()] = card\n if index:\n index.append(index.popleft())\n\n return ans\n```\n\n```Java []\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n if(deck.length==1)\n return deck;\n Arrays.sort(deck);\n int res[]=new int[deck.length];\n int k=1;\n int c=0;\n res[0]=deck[0];\n while(k<deck.length)\n {\n for(int i=1;i<deck.length;i++)\n {\n if(res[i]==0){\n c++;\n if(c==2){\n res[i]=deck[k++];\n c=0;\n \n }\n } \n }\n }\n return res;\n }\n}\n```\n
3
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
Solution
reveal-cards-in-increasing-order
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> deckRevealedIncreasing(vector<int>& deck) {\n queue<int>q;\n int n=deck.size();\n sort(deck.begin(),deck.end());;\n for(int i=0;i<n;i++)\n q.push(i);\n vector<int>res(n,0);\n int i=0;\n while(!q.empty() && i<n){\n int index=q.front();\n q.pop();\n res[index]=deck[i++];\n q.push(q.front());\n q.pop();\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution(object):\n def deckRevealedIncreasing(self, deck):\n N = len(deck)\n index = collections.deque(range(N))\n ans = [None] * N\n\n for card in sorted(deck):\n ans[index.popleft()] = card\n if index:\n index.append(index.popleft())\n\n return ans\n```\n\n```Java []\nclass Solution {\n public int[] deckRevealedIncreasing(int[] deck) {\n if(deck.length==1)\n return deck;\n Arrays.sort(deck);\n int res[]=new int[deck.length];\n int k=1;\n int c=0;\n res[0]=deck[0];\n while(k<deck.length)\n {\n for(int i=1;i<deck.length;i++)\n {\n if(res[i]==0){\n c++;\n if(c==2){\n res[i]=deck[k++];\n c=0;\n \n }\n } \n }\n }\n return res;\n }\n}\n```\n
3
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return _the **vertical order traversal** of the binary tree_. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Explanation:** Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. **Example 2:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. **Example 3:** **Input:** root = \[1,2,3,4,6,5,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 1000`
null
Python, Using Deque, O(n) time complexity
reveal-cards-in-increasing-order
0
1
```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n d=deque(sorted(deck))\n res = deque()\n l = len(d)\n while l != len(res):\n t = d.pop()\n if len(res)>0:\n r = res.pop()\n res.appendleft(r)\n res.appendleft(t)\n return res\n```\n\n\n**Upvote If you like this solution else suggest how to optimize**
2
You are given an integer array `deck`. There is a deck of cards where every card has a unique integer. The integer on the `ith` card is `deck[i]`. You can order the deck in any order you want. Initially, all the cards start face down (unrevealed) in one deck. You will do the following steps repeatedly until all cards are revealed: 1. Take the top card of the deck, reveal it, and take it out of the deck. 2. If there are still cards in the deck then put the next top card of the deck at the bottom of the deck. 3. If there are still unrevealed cards, go back to step 1. Otherwise, stop. Return _an ordering of the deck that would reveal the cards in increasing order_. **Note** that the first entry in the answer is considered to be the top of the deck. **Example 1:** **Input:** deck = \[17,13,11,2,3,5,7\] **Output:** \[2,13,3,11,5,17,7\] **Explanation:** We get the deck in the order \[17,13,11,2,3,5,7\] (this order does not matter), and reorder it. After reordering, the deck starts as \[2,13,3,11,5,17,7\], where 2 is the top of the deck. We reveal 2, and move 13 to the bottom. The deck is now \[3,11,5,17,7,13\]. We reveal 3, and move 11 to the bottom. The deck is now \[5,17,7,13,11\]. We reveal 5, and move 17 to the bottom. The deck is now \[7,13,11,17\]. We reveal 7, and move 13 to the bottom. The deck is now \[11,17,13\]. We reveal 11, and move 17 to the bottom. The deck is now \[13,17\]. We reveal 13, and move 17 to the bottom. The deck is now \[17\]. We reveal 17. Since all the cards revealed are in increasing order, the answer is correct. **Example 2:** **Input:** deck = \[1,1000\] **Output:** \[1,1000\] **Constraints:** * `1 <= deck.length <= 1000` * `1 <= deck[i] <= 106` * All the values of `deck` are **unique**.
null
Python, Using Deque, O(n) time complexity
reveal-cards-in-increasing-order
0
1
```\nclass Solution:\n def deckRevealedIncreasing(self, deck: List[int]) -> List[int]:\n d=deque(sorted(deck))\n res = deque()\n l = len(d)\n while l != len(res):\n t = d.pop()\n if len(res)>0:\n r = res.pop()\n res.appendleft(r)\n res.appendleft(t)\n return res\n```\n\n\n**Upvote If you like this solution else suggest how to optimize**
2
Given the `root` of a binary tree, calculate the **vertical order traversal** of the binary tree. For each node at position `(row, col)`, its left and right children will be at positions `(row + 1, col - 1)` and `(row + 1, col + 1)` respectively. The root of the tree is at `(0, 0)`. The **vertical order traversal** of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values. Return _the **vertical order traversal** of the binary tree_. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[9\],\[3,15\],\[20\],\[7\]\] **Explanation:** Column -1: Only node 9 is in this column. Column 0: Nodes 3 and 15 are in this column in that order from top to bottom. Column 1: Only node 20 is in this column. Column 2: Only node 7 is in this column. **Example 2:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** Column -2: Only node 4 is in this column. Column -1: Only node 2 is in this column. Column 0: Nodes 1, 5, and 6 are in this column. 1 is at the top, so it comes first. 5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6. Column 1: Only node 3 is in this column. Column 2: Only node 7 is in this column. **Example 3:** **Input:** root = \[1,2,3,4,6,5,7\] **Output:** \[\[4\],\[2\],\[1,5,6\],\[3\],\[7\]\] **Explanation:** This case is the exact same as example 2, but with nodes 5 and 6 swapped. Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 1000`
null
Solution
flip-equivalent-binary-trees
1
1
```C++ []\nclass Solution {\npublic:\n bool flipEquiv(TreeNode* root1, TreeNode* root2) {\n if(!root1&&!root2){\n return 1;\n }\n if(!root1||!root2)\n {\n return 0;\n }\n return root1->val==root2->val&&(flipEquiv(root1->right,root2->right)&&flipEquiv(root1->left,root2->left)||flipEquiv(root1->left,root2->right)&&flipEquiv(root1->right,root2->left));\n }\n};\n```\n\n```Python3 []\nclass Solution(object):\n def flipEquiv(self, root1, root2):\n if root1 is root2:\n return True\n if not root1 or not root2 or root1.val != root2.val:\n return False\n\n return (self.flipEquiv(root1.left, root2.left) and\n self.flipEquiv(root1.right, root2.right) or\n self.flipEquiv(root1.left, root2.right) and\n self.flipEquiv(root1.right, root2.left))\n```\n\n```Java []\nclass Solution {\n public boolean flipEquiv(TreeNode root1, TreeNode root2) {\n \n if(root1 == null && root2 == null) return true;\n if(root1 == null || root2 == null) return false;\n if(root1.val != root2.val) return false;\n \n if (flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right)) {\n return true;\n }\n else if (flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left)) {\n return true;\n }\n else {\n return false;\n }\n }\n}\n```\n
3
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
Solution
flip-equivalent-binary-trees
1
1
```C++ []\nclass Solution {\npublic:\n bool flipEquiv(TreeNode* root1, TreeNode* root2) {\n if(!root1&&!root2){\n return 1;\n }\n if(!root1||!root2)\n {\n return 0;\n }\n return root1->val==root2->val&&(flipEquiv(root1->right,root2->right)&&flipEquiv(root1->left,root2->left)||flipEquiv(root1->left,root2->right)&&flipEquiv(root1->right,root2->left));\n }\n};\n```\n\n```Python3 []\nclass Solution(object):\n def flipEquiv(self, root1, root2):\n if root1 is root2:\n return True\n if not root1 or not root2 or root1.val != root2.val:\n return False\n\n return (self.flipEquiv(root1.left, root2.left) and\n self.flipEquiv(root1.right, root2.right) or\n self.flipEquiv(root1.left, root2.right) and\n self.flipEquiv(root1.right, root2.left))\n```\n\n```Java []\nclass Solution {\n public boolean flipEquiv(TreeNode root1, TreeNode root2) {\n \n if(root1 == null && root2 == null) return true;\n if(root1 == null || root2 == null) return false;\n if(root1.val != root2.val) return false;\n \n if (flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right)) {\n return true;\n }\n else if (flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left)) {\n return true;\n }\n else {\n return false;\n }\n }\n}\n```\n
3
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller**. * For example, `"ab "` is lexicographically smaller than `"aba "`. A leaf of a node is a node that has no children. **Example 1:** **Input:** root = \[0,1,2,3,4,3,4\] **Output:** "dba " **Example 2:** **Input:** root = \[25,1,3,1,3,0,2\] **Output:** "adz " **Example 3:** **Input:** root = \[2,2,1,null,1,0,null,0\] **Output:** "abc " **Constraints:** * The number of nodes in the tree is in the range `[1, 8500]`. * `0 <= Node.val <= 25`
null
Easy approach to solve this problem :)
flip-equivalent-binary-trees
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n\n def checkEqual(root1, root2):\n # check both the roots are not available\n if not root1 and not root2:\n return True\n\n # check both the roots are values with each other\n if not root1 or not root2 or root1.val != root2.val:\n return False\n\n # \n case1 = (checkEqual(root1.left,root2.left) and checkEqual(root1.right , root2.right) )\n\n case2 = (checkEqual(root1.left,root2.right) and checkEqual(root1.right , root2.left) )\n \n return case1 or case2\n \n return checkEqual(root1,root2)\n```
1
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
Easy approach to solve this problem :)
flip-equivalent-binary-trees
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n\n def checkEqual(root1, root2):\n # check both the roots are not available\n if not root1 and not root2:\n return True\n\n # check both the roots are values with each other\n if not root1 or not root2 or root1.val != root2.val:\n return False\n\n # \n case1 = (checkEqual(root1.left,root2.left) and checkEqual(root1.right , root2.right) )\n\n case2 = (checkEqual(root1.left,root2.right) and checkEqual(root1.right , root2.left) )\n \n return case1 or case2\n \n return checkEqual(root1,root2)\n```
1
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller**. * For example, `"ab "` is lexicographically smaller than `"aba "`. A leaf of a node is a node that has no children. **Example 1:** **Input:** root = \[0,1,2,3,4,3,4\] **Output:** "dba " **Example 2:** **Input:** root = \[25,1,3,1,3,0,2\] **Output:** "adz " **Example 3:** **Input:** root = \[2,2,1,null,1,0,null,0\] **Output:** "abc " **Constraints:** * The number of nodes in the tree is in the range `[1, 8500]`. * `0 <= Node.val <= 25`
null
98% Tc and 80% Sc easy python solution
flip-equivalent-binary-trees
0
1
```\ndef flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n\tlru_cache(None)\n\tdef dfs(n1, n2):\n\t\tif not(n1 or n2):\n\t\t\treturn True\n\t\tif not(n1 and n2) or n1.val != n2.val:\n\t\t\treturn False\n\t\tif((n1.left and n2.left) or (n1.right and n2.right)):\n\t\t\treturn (dfs(n1.left, n2.left) and dfs(n1.right, n2.right)) or (dfs(n1.right, n2.left) and dfs(n1.left, n2.right)) \n\t\telse:\n\t\t\treturn dfs(n1.right, n2.left) and dfs(n1.left, n2.right)\n\treturn dfs(root1, root2)\n```
1
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
98% Tc and 80% Sc easy python solution
flip-equivalent-binary-trees
0
1
```\ndef flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n\tlru_cache(None)\n\tdef dfs(n1, n2):\n\t\tif not(n1 or n2):\n\t\t\treturn True\n\t\tif not(n1 and n2) or n1.val != n2.val:\n\t\t\treturn False\n\t\tif((n1.left and n2.left) or (n1.right and n2.right)):\n\t\t\treturn (dfs(n1.left, n2.left) and dfs(n1.right, n2.right)) or (dfs(n1.right, n2.left) and dfs(n1.left, n2.right)) \n\t\telse:\n\t\t\treturn dfs(n1.right, n2.left) and dfs(n1.left, n2.right)\n\treturn dfs(root1, root2)\n```
1
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller**. * For example, `"ab "` is lexicographically smaller than `"aba "`. A leaf of a node is a node that has no children. **Example 1:** **Input:** root = \[0,1,2,3,4,3,4\] **Output:** "dba " **Example 2:** **Input:** root = \[25,1,3,1,3,0,2\] **Output:** "adz " **Example 3:** **Input:** root = \[2,2,1,null,1,0,null,0\] **Output:** "abc " **Constraints:** * The number of nodes in the tree is in the range `[1, 8500]`. * `0 <= Node.val <= 25`
null
Python || 4-line 93%
flip-equivalent-binary-trees
0
1
```\nclass Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n if not root1 or not root2:\n return not root1 and not root2\n if root1.val != root2.val: return False\n return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)) or (self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left))\n```
3
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
Python || 4-line 93%
flip-equivalent-binary-trees
0
1
```\nclass Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n if not root1 or not root2:\n return not root1 and not root2\n if root1.val != root2.val: return False\n return (self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)) or (self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left))\n```
3
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller**. * For example, `"ab "` is lexicographically smaller than `"aba "`. A leaf of a node is a node that has no children. **Example 1:** **Input:** root = \[0,1,2,3,4,3,4\] **Output:** "dba " **Example 2:** **Input:** root = \[25,1,3,1,3,0,2\] **Output:** "adz " **Example 3:** **Input:** root = \[2,2,1,null,1,0,null,0\] **Output:** "abc " **Constraints:** * The number of nodes in the tree is in the range `[1, 8500]`. * `0 <= Node.val <= 25`
null
Python recursive DFS solution with comments
flip-equivalent-binary-trees
0
1
```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:\n \n \'\'\'\n We think of root1 as the "match" tree, that we are looking to match \n by flipping parts of root2, the "flipper".\n \n We want to traverse the match, while trying a flip and a non-flip at each node in the flipper.\n This makes sure we try every combination of flips, and exit early when they don\'t match.\n Recursively do this.\n If the regular version matches or the flipped version matches, we return true.\n \'\'\'\n \n def dfs(match, flipper):\n \n # Both are None.\n if not match and not flipper:\n return True\n \n # Only one is None, so they don\'t match.\n if not (match and flipper):\n return False\n \n # They both exist, but values don\'t match.\n if match.val != flipper.val:\n return False\n \n # No flip.\n regular = dfs(match.left, flipper.left) and dfs(match.right, flipper.right)\n \n # Flip.\n flipped = dfs(match.left, flipper.right) and dfs(match.right, flipper.left)\n \n return regular or flipped\n \n return dfs(root1, root2)\n```
7
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
Python recursive DFS solution with comments
flip-equivalent-binary-trees
0
1
```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:\n \n \'\'\'\n We think of root1 as the "match" tree, that we are looking to match \n by flipping parts of root2, the "flipper".\n \n We want to traverse the match, while trying a flip and a non-flip at each node in the flipper.\n This makes sure we try every combination of flips, and exit early when they don\'t match.\n Recursively do this.\n If the regular version matches or the flipped version matches, we return true.\n \'\'\'\n \n def dfs(match, flipper):\n \n # Both are None.\n if not match and not flipper:\n return True\n \n # Only one is None, so they don\'t match.\n if not (match and flipper):\n return False\n \n # They both exist, but values don\'t match.\n if match.val != flipper.val:\n return False\n \n # No flip.\n regular = dfs(match.left, flipper.left) and dfs(match.right, flipper.right)\n \n # Flip.\n flipped = dfs(match.left, flipper.right) and dfs(match.right, flipper.left)\n \n return regular or flipped\n \n return dfs(root1, root2)\n```
7
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller**. * For example, `"ab "` is lexicographically smaller than `"aba "`. A leaf of a node is a node that has no children. **Example 1:** **Input:** root = \[0,1,2,3,4,3,4\] **Output:** "dba " **Example 2:** **Input:** root = \[25,1,3,1,3,0,2\] **Output:** "adz " **Example 3:** **Input:** root = \[2,2,1,null,1,0,null,0\] **Output:** "abc " **Constraints:** * The number of nodes in the tree is in the range `[1, 8500]`. * `0 <= Node.val <= 25`
null
simple approach + python
flip-equivalent-binary-trees
0
1
## Intuition\nThe intuition behind your solution is to compare the nodes of two binary trees recursively. Two trees are flip equivalent if the roots are the same and the left and right children of one tree are the flip equivalent of the right and left children of the other tree, respectively.\n\n## Approach\nrecursive function flipEquiv takes two nodes, root1 and root2, from each of the two trees. The function checks:\n\nIf both nodes are None, they are equivalent.\nIf one is None and the other is not, or if their values differ, the trees are not equivalent.\nThe function then recursively checks for flip equivalence in two scenarios:\nroot1.left with root2.left and root1.right with root2.right\nroot1.left with root2.right and root1.right with root2.left\nThe trees are considered flip equivalent if either of these recursive checks return True.\n\n# Complexity\n### Time complexity: The time complexity is O(N), where N is the smaller number of nodes in the two trees. In the worst case, you will need to visit each node once.\n### Space complexity: The space complexity is also O(N) due to the recursion stack. In the worst case, the tree could be completely unbalanced, leading to a depth of N.\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n if not root1 and not root2:\n return True\n if not root1 and root2 or not root2 and root1 or root1.val!=root2.val:\n return False\n a=self.flipEquiv(root1.left,root2.left) and self.flipEquiv(root1.right,root2.right)\n b=self.flipEquiv(root1.left,root2.right) and self.flipEquiv(root1.right,root2.left)\n return a or b\n\n```
0
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees. A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations. Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise. **Example 1:** **Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\] **Output:** true **Explanation:** We flipped at nodes with values 1, 3, and 5. **Example 2:** **Input:** root1 = \[\], root2 = \[\] **Output:** true **Example 3:** **Input:** root1 = \[\], root2 = \[1\] **Output:** false **Constraints:** * The number of nodes in each tree is in the range `[0, 100]`. * Each tree will have **unique node values** in the range `[0, 99]`.
null
simple approach + python
flip-equivalent-binary-trees
0
1
## Intuition\nThe intuition behind your solution is to compare the nodes of two binary trees recursively. Two trees are flip equivalent if the roots are the same and the left and right children of one tree are the flip equivalent of the right and left children of the other tree, respectively.\n\n## Approach\nrecursive function flipEquiv takes two nodes, root1 and root2, from each of the two trees. The function checks:\n\nIf both nodes are None, they are equivalent.\nIf one is None and the other is not, or if their values differ, the trees are not equivalent.\nThe function then recursively checks for flip equivalence in two scenarios:\nroot1.left with root2.left and root1.right with root2.right\nroot1.left with root2.right and root1.right with root2.left\nThe trees are considered flip equivalent if either of these recursive checks return True.\n\n# Complexity\n### Time complexity: The time complexity is O(N), where N is the smaller number of nodes in the two trees. In the worst case, you will need to visit each node once.\n### Space complexity: The space complexity is also O(N) due to the recursion stack. In the worst case, the tree could be completely unbalanced, leading to a depth of N.\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:\n if not root1 and not root2:\n return True\n if not root1 and root2 or not root2 and root1 or root1.val!=root2.val:\n return False\n a=self.flipEquiv(root1.left,root2.left) and self.flipEquiv(root1.right,root2.right)\n b=self.flipEquiv(root1.left,root2.right) and self.flipEquiv(root1.right,root2.left)\n return a or b\n\n```
0
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller**. * For example, `"ab "` is lexicographically smaller than `"aba "`. A leaf of a node is a node that has no children. **Example 1:** **Input:** root = \[0,1,2,3,4,3,4\] **Output:** "dba " **Example 2:** **Input:** root = \[25,1,3,1,3,0,2\] **Output:** "adz " **Example 3:** **Input:** root = \[2,2,1,null,1,0,null,0\] **Output:** "abc " **Constraints:** * The number of nodes in the tree is in the range `[1, 8500]`. * `0 <= Node.val <= 25`
null
Solution
largest-component-size-by-common-factor
1
1
```C++ []\nclass Solution {\npublic:\n int arr[(int)(1e5+5)];\n int visit[(int)(1e5+5)]={0};\n int member[(int)(1e5+5)];\n constexpr void build(vector<int>& primes, pair<int,int>* sp, int N){\n if(primes.empty()){\n visit[0] = visit[1] = 1;\n sp[1].first = sp[1].second = 1;\n for(int i=2;i<=1e5;i++){\n if(!visit[i]){\n primes.push_back(i);\n sp[i].first=i;\n sp[i].second = i;\n }for (int j=0; i*primes[j]<=1e5; j++){\n visit[i*primes[j]] = 1;\n sp[i*primes[j]].first = primes[j];\n sp[i*primes[j]].second = sp[i].first == primes[j] ? sp[i].second : i;\n if(i%primes[j]==0)break;\n }\n }\n }\n for(int i=0;i<=N;i++){\n arr[i] = i;\n }\n }\n int find(int x){\n while(arr[x]!=x)\n x=arr[x];\n return x;\n }\n void uni(int x, int y){\n x = find(x), y = find(y);\n if(x==y)return;\n member[y]+=member[x];\n member[x]=0;\n arr[x] = y;\n }\n int largestComponentSize(vector<int>& nums) {\n static vector<int> primes;\n static pair<int,int> sp[(int)(1e5+5)];\n build(primes, sp, *max_element(nums.begin(),nums.end()));\n int ans=1;\n for(auto& it:nums){\n int pre=sp[it].first;\n it = sp[it].second;\n while(it!=sp[it].first){\n uni(sp[it].first, pre);\n pre = sp[it].first;\n it = sp[it].second;\n }\n uni(sp[it].first, pre);\n member[find(pre)]++;\n ans = max(member[find(pre)], ans);\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nMAXN = 10**5 + 5\nspf = list(range(MAXN))\n\ndef sieve():\n\tspf[1] = 1\n\n\tfor i in range(4, MAXN, 2):\n\t\tspf[i] = 2\n\n\tfor i in range(3, ceil(sqrt(MAXN))):\n\t\tif (spf[i] == i):\n\t\t\tfor j in range(i * i, MAXN, i):\n\t\t\t\tif (spf[j] == j):\n\t\t\t\t\tspf[j] = i\n\ndef factors(x: int):\n\tfactors_set = set()\n\n\twhile x != 1:\n\t\tfactors_set.add(spf[x])\n\t\tx //= spf[x]\n\n\treturn factors_set\n\nsieve()\n\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n df = {}\n uf = UnionFind(len(nums))\n for pos, num in enumerate(nums):\n for factor in factors(num):\n if factor in df:\n uf.union(pos, df[factor])\n else:\n df[factor] = pos\n \n return uf.mx\n \nclass UnionFind:\n def __init__(self, n: int):\n self.root_lookup = list(range(n))\n self.rank_lookup = [1] * n\n self.mx = 1\n\n def find(self, num: int):\n root = self.root_lookup[num]\n while root != self.root_lookup[root]:\n root = self.root_lookup[root]\n self.root_lookup[num] = root\n return root\n \n def union(self, x, y):\n xr, yr = self.find(x), self.find(y)\n if xr == yr:\n return False\n if self.rank_lookup[xr] < self.rank_lookup[yr]:\n xr, yr = yr, xr\n self.root_lookup[yr] = xr\n self.rank_lookup[xr] += self.rank_lookup[yr]\n self.mx = max(self.mx,self.rank_lookup[xr])\n return True\n```\n\n```Java []\nclass Solution {\n public int gcd(int a, int b) {\n if(a < b) {\n int h = a;\n a = b;\n b = h;\n }\n while(b > 0) {\n int h = b;\n b = a % b;\n a = h;\n }\n return a;\n }\n public int largestComponentSize(int[] nums) {\n int n = nums.length;\n int max = 1;\n for(int num : nums) {\n max = Math.max(max, num);\n }\n int[] m = new int[max + 1];\n Arrays.fill(m, -1);\n boolean[] check = new boolean[max + 1];\n for(int i = 0; i < n; i++) {\n m[nums[i]] = i;\n }\n UnionFind uf = new UnionFind(n);\n for(int p = 2; p <= max; p++) {\n if(check[p])\n continue;\n\n int first = -1;\n for(int div = p; div <= max; div += p) {\n if(m[div] >= 0) {\n if(first == -1) {\n first = m[div];\n } else {\n uf.join(first, m[div]);\n }\n }\n check[div] = true;\n }\n }\n return uf.getMaxComponent();\n }\n}\npublic class UnionFind {\n private int[] parent;\n private int[] size;\n private int maxSize;\n\n public UnionFind(int n) {\n parent = new int[n];\n size = new int[n];\n maxSize = 1;\n\n for(int i = 0; i < n; i++) {\n parent[i] = i;\n size[i] = 1;\n }\n }\n public int find(int x) {\n return x != parent[x] ? parent[x] = find(parent[x]) : x;\n }\n public void join(int x, int y) {\n x = find(x);\n y = find(y);\n\n if(x != y) {\n if(size[x] < size[y]) {\n int h = x;\n x = y;\n y = h;\n }\n size[x] += size[y];\n maxSize = Math.max(maxSize, size[x]);\n parent[y] = x;\n }\n }\n public int getMaxComponent() {\n return maxSize;\n }\n}\n```\n
2
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
Solution
largest-component-size-by-common-factor
1
1
```C++ []\nclass Solution {\npublic:\n int arr[(int)(1e5+5)];\n int visit[(int)(1e5+5)]={0};\n int member[(int)(1e5+5)];\n constexpr void build(vector<int>& primes, pair<int,int>* sp, int N){\n if(primes.empty()){\n visit[0] = visit[1] = 1;\n sp[1].first = sp[1].second = 1;\n for(int i=2;i<=1e5;i++){\n if(!visit[i]){\n primes.push_back(i);\n sp[i].first=i;\n sp[i].second = i;\n }for (int j=0; i*primes[j]<=1e5; j++){\n visit[i*primes[j]] = 1;\n sp[i*primes[j]].first = primes[j];\n sp[i*primes[j]].second = sp[i].first == primes[j] ? sp[i].second : i;\n if(i%primes[j]==0)break;\n }\n }\n }\n for(int i=0;i<=N;i++){\n arr[i] = i;\n }\n }\n int find(int x){\n while(arr[x]!=x)\n x=arr[x];\n return x;\n }\n void uni(int x, int y){\n x = find(x), y = find(y);\n if(x==y)return;\n member[y]+=member[x];\n member[x]=0;\n arr[x] = y;\n }\n int largestComponentSize(vector<int>& nums) {\n static vector<int> primes;\n static pair<int,int> sp[(int)(1e5+5)];\n build(primes, sp, *max_element(nums.begin(),nums.end()));\n int ans=1;\n for(auto& it:nums){\n int pre=sp[it].first;\n it = sp[it].second;\n while(it!=sp[it].first){\n uni(sp[it].first, pre);\n pre = sp[it].first;\n it = sp[it].second;\n }\n uni(sp[it].first, pre);\n member[find(pre)]++;\n ans = max(member[find(pre)], ans);\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nMAXN = 10**5 + 5\nspf = list(range(MAXN))\n\ndef sieve():\n\tspf[1] = 1\n\n\tfor i in range(4, MAXN, 2):\n\t\tspf[i] = 2\n\n\tfor i in range(3, ceil(sqrt(MAXN))):\n\t\tif (spf[i] == i):\n\t\t\tfor j in range(i * i, MAXN, i):\n\t\t\t\tif (spf[j] == j):\n\t\t\t\t\tspf[j] = i\n\ndef factors(x: int):\n\tfactors_set = set()\n\n\twhile x != 1:\n\t\tfactors_set.add(spf[x])\n\t\tx //= spf[x]\n\n\treturn factors_set\n\nsieve()\n\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n df = {}\n uf = UnionFind(len(nums))\n for pos, num in enumerate(nums):\n for factor in factors(num):\n if factor in df:\n uf.union(pos, df[factor])\n else:\n df[factor] = pos\n \n return uf.mx\n \nclass UnionFind:\n def __init__(self, n: int):\n self.root_lookup = list(range(n))\n self.rank_lookup = [1] * n\n self.mx = 1\n\n def find(self, num: int):\n root = self.root_lookup[num]\n while root != self.root_lookup[root]:\n root = self.root_lookup[root]\n self.root_lookup[num] = root\n return root\n \n def union(self, x, y):\n xr, yr = self.find(x), self.find(y)\n if xr == yr:\n return False\n if self.rank_lookup[xr] < self.rank_lookup[yr]:\n xr, yr = yr, xr\n self.root_lookup[yr] = xr\n self.rank_lookup[xr] += self.rank_lookup[yr]\n self.mx = max(self.mx,self.rank_lookup[xr])\n return True\n```\n\n```Java []\nclass Solution {\n public int gcd(int a, int b) {\n if(a < b) {\n int h = a;\n a = b;\n b = h;\n }\n while(b > 0) {\n int h = b;\n b = a % b;\n a = h;\n }\n return a;\n }\n public int largestComponentSize(int[] nums) {\n int n = nums.length;\n int max = 1;\n for(int num : nums) {\n max = Math.max(max, num);\n }\n int[] m = new int[max + 1];\n Arrays.fill(m, -1);\n boolean[] check = new boolean[max + 1];\n for(int i = 0; i < n; i++) {\n m[nums[i]] = i;\n }\n UnionFind uf = new UnionFind(n);\n for(int p = 2; p <= max; p++) {\n if(check[p])\n continue;\n\n int first = -1;\n for(int div = p; div <= max; div += p) {\n if(m[div] >= 0) {\n if(first == -1) {\n first = m[div];\n } else {\n uf.join(first, m[div]);\n }\n }\n check[div] = true;\n }\n }\n return uf.getMaxComponent();\n }\n}\npublic class UnionFind {\n private int[] parent;\n private int[] size;\n private int maxSize;\n\n public UnionFind(int n) {\n parent = new int[n];\n size = new int[n];\n maxSize = 1;\n\n for(int i = 0; i < n; i++) {\n parent[i] = i;\n size[i] = 1;\n }\n }\n public int find(int x) {\n return x != parent[x] ? parent[x] = find(parent[x]) : x;\n }\n public void join(int x, int y) {\n x = find(x);\n y = find(y);\n\n if(x != y) {\n if(size[x] < size[y]) {\n int h = x;\n x = y;\n y = h;\n }\n size[x] += size[y];\n maxSize = Math.max(maxSize, size[x]);\n parent[y] = x;\n }\n }\n public int getMaxComponent() {\n return maxSize;\n }\n}\n```\n
2
The **array-form** of an integer `num` is an array representing its digits in left to right order. * For example, for `num = 1321`, the array form is `[1,3,2,1]`. Given `num`, the **array-form** of an integer, and an integer `k`, return _the **array-form** of the integer_ `num + k`. **Example 1:** **Input:** num = \[1,2,0,0\], k = 34 **Output:** \[1,2,3,4\] **Explanation:** 1200 + 34 = 1234 **Example 2:** **Input:** num = \[2,7,4\], k = 181 **Output:** \[4,5,5\] **Explanation:** 274 + 181 = 455 **Example 3:** **Input:** num = \[2,1,5\], k = 806 **Output:** \[1,0,2,1\] **Explanation:** 215 + 806 = 1021 **Constraints:** * `1 <= num.length <= 104` * `0 <= num[i] <= 9` * `num` does not contain any leading zeros except for the zero itself. * `1 <= k <= 104`
null
[Python3] union-find
largest-component-size-by-common-factor
0
1
\n`O(MlogM)` using sieve\n```\nclass UnionFind: \n \n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [1]*n\n \n def find(self, p): \n if p != self.parent[p]: \n self.parent[p] = self.find(self.parent[p])\n return self.parent[p]\n \n def union(self, p, q): \n prt, qrt = self.find(p), self.find(q)\n if prt == qrt: return False \n if self.rank[prt] > self.rank[qrt]: prt, qrt = qrt, prt\n self.parent[prt] = qrt\n self.rank[qrt] += self.rank[prt]\n return True \n\n\nclass Solution:\n def largestComponentSize(self, A: List[int]) -> int:\n m = max(A)\n uf = UnionFind(m+1)\n seen = set(A)\n \n # modified sieve of eratosthenes \n sieve = [1]*(m+1)\n sieve[0] = sieve[1] = 0 \n for k in range(m//2+1): \n if sieve[k]: \n prev = k if k in seen else 0\n for x in range(2*k, m+1, k): \n sieve[x] = 0\n if x in seen: \n if prev: uf.union(prev, x)\n else: prev = x\n return max(uf.rank)\n```\n\n**Related problems**\n[952. Largest Component Size by Common Factor](https://leetcode.com/problems/largest-component-size-by-common-factor/discuss/1546345/Python3-union-find)\n[1998. GCD Sort of an Array](https://leetcode.com/problems/gcd-sort-of-an-array/discuss/1445278/Python3-union-find)\n\nAlternative implemetation `O(Nsqrt(M))` assuming `O(1)` union & find.\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n m = max(nums)\n uf = UnionFind(m+1)\n for x in nums: \n for p in range(2, int(sqrt(x))+1): \n if x%p == 0: \n uf.union(x, p)\n uf.union(x, x//p)\n freq = Counter(uf.find(x) for x in nums)\n return max(freq.values())\n```\n\nAlternative implementation using `spf` `O((M+N)logM)`\n```\nclass Solution:\n def largestComponentSize(self, nums: List[int]) -> int:\n m = max(nums)\n spf = list(range(m+1))\n for x in range(4, m+1, 2): spf[x] = 2\n for x in range(3, int(sqrt(m+1))+1): \n if spf[x] == x: \n for xx in range(x*x, m+1, x): \n spf[xx] = x \n \n uf = UnionFind(len(nums))\n mp = {}\n for i, x in enumerate(nums): \n while x > 1: \n if spf[x] in mp: uf.union(i, mp[spf[x]])\n else: mp[spf[x]] = i\n x //= spf[x]\n return max(uf.rank)\n```
4
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null