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 |
---|---|---|---|---|---|---|---|
Simple Python Solution | xor-operation-in-an-array | 0 | 1 | Time Complexcity O(N)\nSpace Complexcity O(1)\n```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n re=start\n for i in range(1,n):\n ne=start+2*i\n re^=ne\n return re\n``` | 1 | You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane.
Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In other words, `posx` and `posy` cannot be changed. Your field of view in **degrees** is represented by `angle`, determining how wide you can see from any given view direction. Let `d` be the amount in degrees that you rotate counterclockwise. Then, your field of view is the **inclusive** range of angles `[d - angle/2, d + angle/2]`.
Your browser does not support the video tag or this video format.
You can **see** some set of points if, for each point, the **angle** formed by the point, your position, and the immediate east direction from your position is **in your field of view**.
There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.
Return _the maximum number of points you can see_.
**Example 1:**
**Input:** points = \[\[2,1\],\[2,2\],\[3,3\]\], angle = 90, location = \[1,1\]
**Output:** 3
**Explanation:** The shaded region represents your field of view. All points can be made visible in your field of view, including \[3,3\] even though \[2,2\] is in front and in the same line of sight.
**Example 2:**
**Input:** points = \[\[2,1\],\[2,2\],\[3,4\],\[1,1\]\], angle = 90, location = \[1,1\]
**Output:** 4
**Explanation:** All points can be made visible in your field of view, including the one at your location.
**Example 3:**
**Input:** points = \[\[1,0\],\[2,1\]\], angle = 13, location = \[1,1\]
**Output:** 1
**Explanation:** You can only see one of the two points, as shown above.
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `location.length == 2`
* `0 <= angle < 360`
* `0 <= posx, posy, xi, yi <= 100` | Simulate the process, create an array nums and return the Bitwise XOR of all elements of it. |
Python HashMap beats 100% with detailed comments | making-file-names-unique | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSee comments\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSee comments\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nNote that the while loop will run at most k (occurence of name) times for each name so IN TOTAL at most O(n) times, which does not add to complexity\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # map from name to current min k used for that name\n nameMinK = dict() \n res = []\n for name in names:\n if name not in nameMinK: # new name\n res.append(name)\n nameMinK[name] = 0\n else: # already added name\n k = nameMinK[name] + 1\n tmp = name + \'(\' + str(k) + \')\'\n while tmp in nameMinK:\n k += 1\n tmp = name + \'(\' + str(k) + \')\'\n # try until tmp not in usedName => add AND update minK\n res.append(tmp)\n nameMinK[name] = k # NOTE: very tricky here!!!, need to update both name & tmp\n nameMinK[tmp] = 0\n return res\n\n\n``` | 2 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Python HashMap beats 100% with detailed comments | making-file-names-unique | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSee comments\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSee comments\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nNote that the while loop will run at most k (occurence of name) times for each name so IN TOTAL at most O(n) times, which does not add to complexity\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # map from name to current min k used for that name\n nameMinK = dict() \n res = []\n for name in names:\n if name not in nameMinK: # new name\n res.append(name)\n nameMinK[name] = 0\n else: # already added name\n k = nameMinK[name] + 1\n tmp = name + \'(\' + str(k) + \')\'\n while tmp in nameMinK:\n k += 1\n tmp = name + \'(\' + str(k) + \')\'\n # try until tmp not in usedName => add AND update minK\n res.append(tmp)\n nameMinK[name] = k # NOTE: very tricky here!!!, need to update both name & tmp\n nameMinK[tmp] = 0\n return res\n\n\n``` | 2 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
noob solution | dpm07 | making-file-names-unique | 0 | 1 | \n```\nfrom typing import List\n\n"""\n1487. Making File Names Unique\n\ncreate n folders in your file system such that, at the ith minute, U will create a folder with the name names[i].\n\nSince 2 files cannot have the same name,\nif you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.\n\nReturn an arr of str of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.\n\n\nEX:\n["pes","fifa","gta","pes(2019)"]\nO/P -> ["pes","fifa","gta","pes(2019)"]\n\nEX:\n["gta","gta(1)","gta","avalon"]\no/p: ["gta","gta(1)","gta(2)","avalon"]\n\nEx:\n["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]\no/p: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]\n"""\n\n\nclass Solution:\n """\n if it\'s already in the seen dictionary,\n append a suffix k to the name until a unique name is found.\n\n Time: O(n^2) in the worst case where all file names are the same\n space: O(n)\n """\n def getFolderNames(self, names: List[str]) -> List[str]:\n\n ans = [] # stores unique file names\n seen = {}\n\n for name in names:\n if name not in seen:\n ans.append(name)\n seen[name] = 1\n else:\n k = seen[name]\n # creating variants\n while True:\n new_name = name + \'(\' + str(k) + \')\'\n if new_name not in seen:\n ans.append(new_name)\n seen[new_name] = 1\n break\n else:\n k += 1\n\n # save the latest version of variant so to avaoid above while\n # loop calculation\n seen[name] = k\n \n\n return ans\n\n``` | 1 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
noob solution | dpm07 | making-file-names-unique | 0 | 1 | \n```\nfrom typing import List\n\n"""\n1487. Making File Names Unique\n\ncreate n folders in your file system such that, at the ith minute, U will create a folder with the name names[i].\n\nSince 2 files cannot have the same name,\nif you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of (k), where, k is the smallest positive integer such that the obtained name remains unique.\n\nReturn an arr of str of length n where ans[i] is the actual name the system will assign to the ith folder when you create it.\n\n\nEX:\n["pes","fifa","gta","pes(2019)"]\nO/P -> ["pes","fifa","gta","pes(2019)"]\n\nEX:\n["gta","gta(1)","gta","avalon"]\no/p: ["gta","gta(1)","gta(2)","avalon"]\n\nEx:\n["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece"]\no/p: ["onepiece","onepiece(1)","onepiece(2)","onepiece(3)","onepiece(4)"]\n"""\n\n\nclass Solution:\n """\n if it\'s already in the seen dictionary,\n append a suffix k to the name until a unique name is found.\n\n Time: O(n^2) in the worst case where all file names are the same\n space: O(n)\n """\n def getFolderNames(self, names: List[str]) -> List[str]:\n\n ans = [] # stores unique file names\n seen = {}\n\n for name in names:\n if name not in seen:\n ans.append(name)\n seen[name] = 1\n else:\n k = seen[name]\n # creating variants\n while True:\n new_name = name + \'(\' + str(k) + \')\'\n if new_name not in seen:\n ans.append(new_name)\n seen[new_name] = 1\n break\n else:\n k += 1\n\n # save the latest version of variant so to avaoid above while\n # loop calculation\n seen[name] = k\n \n\n return ans\n\n``` | 1 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
[Python] ACCEPTED SOLUTION with dictionary (hashmap) and set | making-file-names-unique | 0 | 1 | **Explanation**\nUsing set we check the name which is already user or not, if not used we can keep name\'s version k and increment k until we reach our version.\nIn dictionary, key = name, value = version.\n\n**Complexity**\nTime ```O(N)``` \xA0\nSpace ```O(N)```\n\n```\n from collections import defaultdict\n def getFolderNames(self, names: List[str]) -> List[str]:\n used, hashmap = set(), defaultdict(int)\n result = []\n for name in names:\n k = hashmap[name]\n current = name\n while current in used:\n k += 1\n current = \'%s(%d)\' % (name, k) # alternative to current = name+\'(\'+str(k)+\')\'\n hashmap[name] = k\n result.append(current)\n used.add(current)\n return result\n``` | 22 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
[Python] ACCEPTED SOLUTION with dictionary (hashmap) and set | making-file-names-unique | 0 | 1 | **Explanation**\nUsing set we check the name which is already user or not, if not used we can keep name\'s version k and increment k until we reach our version.\nIn dictionary, key = name, value = version.\n\n**Complexity**\nTime ```O(N)``` \xA0\nSpace ```O(N)```\n\n```\n from collections import defaultdict\n def getFolderNames(self, names: List[str]) -> List[str]:\n used, hashmap = set(), defaultdict(int)\n result = []\n for name in names:\n k = hashmap[name]\n current = name\n while current in used:\n k += 1\n current = \'%s(%d)\' % (name, k) # alternative to current = name+\'(\'+str(k)+\')\'\n hashmap[name] = k\n result.append(current)\n used.add(current)\n return result\n``` | 22 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Python || Dict || No set || Self-Explainable | making-file-names-unique | 0 | 1 | ```\ndef getFolderNames(self, names: List[str]) -> List[str]:\n h = dict()\n ans = []\n \n for i in names:\n if i not in h :\n h[i] = 1\n ans.append(i)\n else:\n ct = h[i]\n tmp = i + \'(\' + str(ct) + \')\'\n while tmp in h:\n ct +=1\n tmp = i + \'(\' + str(ct) + \')\'\n h[tmp] = 1\n ans.append(tmp)\n h[i] = ct\n \n return ans\n```\nif you find good , upvot it | 15 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Python || Dict || No set || Self-Explainable | making-file-names-unique | 0 | 1 | ```\ndef getFolderNames(self, names: List[str]) -> List[str]:\n h = dict()\n ans = []\n \n for i in names:\n if i not in h :\n h[i] = 1\n ans.append(i)\n else:\n ct = h[i]\n tmp = i + \'(\' + str(ct) + \')\'\n while tmp in h:\n ct +=1\n tmp = i + \'(\' + str(ct) + \')\'\n h[tmp] = 1\n ans.append(tmp)\n h[i] = ct\n \n return ans\n```\nif you find good , upvot it | 15 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Very simple python3 solution using hashmap and comments | making-file-names-unique | 0 | 1 | Very simple and commented solution: \n\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # names : array of names\n # n : size of names\n \n # create folders at the i\'th minute for each name = names[i]\n # If name was used previously, append a suffix "(k)" - note parenthesis - where k is the smallest pos int\n \n # return an array of strings where ans[i] is the actual saved variant of names[i]\n \n n = len(names)\n \n dictNames = {}\n ans = [\'\']*n\n \n # enumerate to grab index so we can return ans list in order\n for idx, name in enumerate(names):\n # check if we have seen this name before\n if name in dictNames:\n # if we have grab the next k using last successful low (k) suffix\n k = dictNames[name]\n # track the name we started so we can update the dict\n namestart = name\n # cycle through values of increasing k until we are not in a previously used name\n while name in dictNames:\n name = namestart + f"({k})"\n k += 1\n # update the name we started with to the new lowest value of k\n dictNames[namestart] = k\n # add the new name with k = 1 so if we see this name with the suffix\n dictNames[name] = 1\n else:\n # we havent seen this name so lets start with 1\n dictNames[name] = 1\n # build the solution\n ans[idx] = name\n return ans\n``` | 3 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Very simple python3 solution using hashmap and comments | making-file-names-unique | 0 | 1 | Very simple and commented solution: \n\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n # names : array of names\n # n : size of names\n \n # create folders at the i\'th minute for each name = names[i]\n # If name was used previously, append a suffix "(k)" - note parenthesis - where k is the smallest pos int\n \n # return an array of strings where ans[i] is the actual saved variant of names[i]\n \n n = len(names)\n \n dictNames = {}\n ans = [\'\']*n\n \n # enumerate to grab index so we can return ans list in order\n for idx, name in enumerate(names):\n # check if we have seen this name before\n if name in dictNames:\n # if we have grab the next k using last successful low (k) suffix\n k = dictNames[name]\n # track the name we started so we can update the dict\n namestart = name\n # cycle through values of increasing k until we are not in a previously used name\n while name in dictNames:\n name = namestart + f"({k})"\n k += 1\n # update the name we started with to the new lowest value of k\n dictNames[namestart] = k\n # add the new name with k = 1 so if we see this name with the suffix\n dictNames[name] = 1\n else:\n # we havent seen this name so lets start with 1\n dictNames[name] = 1\n # build the solution\n ans[idx] = name\n return ans\n``` | 3 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Python3 O(n) using while loop to get the next key name | making-file-names-unique | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing while loop to get the next key name\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nusing while loop to get the next key name\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n cache = {}#store names\n\n for idx, name in enumerate(names):\n modified = name\n if name not in cache:\n #while(name)\n cache[name] = 0\n else:\n k = cache[name]\n while modified in cache:\n k += 1\n modified = f\'{name}({k})\'\n cache[name] = k\n cache[modified] = 0\n return cache.keys()\n #last: pes:0, pes(2):0, pes(1):0, pes(3):0\n\n\n\n #["pes","pes(2)", "pes", "pes"]\n#expected["pes","pes(2)", "pes(1)","pes(3)" ]\n #last: pes:3, pes(2):0, pes(1):0, pes(3):0\n #modified = pes(3)\n \'\'\'\n cache = {}#store names\n res = []\n\n for idx, i in enumea\n \n\n \n for i in names:\n #not found right away, then\n if i not in cache:\n if \'(\' in i and \')\' in i:\n for name in cache: #break this for loop\n \n if name in i:\n leng = len(name)\n if len(i) == leng + 3 and i[leng] == "(" and i[leng+2] == ")":\n #check if it is repeaded :\n if i in cache[name]:\n break #do nothing\n #check if i_k in within k:\n \n \n i_k = leng+1\n if i_k > k:\n cache[name][count] += 1\n k = cache[name][count]\n st = name + "(" + str(k) + ")"\n res.append(st)\n cache[name][i] = 1\n \n \n cache[name][count] += 1\n k = cache[name][count]\n st = name + "(" + str(k) + ")"\n res.append(st)\n break\n res.append(i)\n cache[i] = {}\n cache[i][count] = 0\n\n else:\n \n cache[i][count] += 1\n #res.append(i)\n k = cache[i][count]\n #cache\n st = i + "(" + str(k) + ")"\n res.append(st)\n cache[i][st] = 1\n\n return res \n\n\n ["pes","fifa","gta","pes(1)", "pes(2019)"]\n \'\'\'\n \n``` | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Python3 O(n) using while loop to get the next key name | making-file-names-unique | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing while loop to get the next key name\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nusing while loop to get the next key name\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n cache = {}#store names\n\n for idx, name in enumerate(names):\n modified = name\n if name not in cache:\n #while(name)\n cache[name] = 0\n else:\n k = cache[name]\n while modified in cache:\n k += 1\n modified = f\'{name}({k})\'\n cache[name] = k\n cache[modified] = 0\n return cache.keys()\n #last: pes:0, pes(2):0, pes(1):0, pes(3):0\n\n\n\n #["pes","pes(2)", "pes", "pes"]\n#expected["pes","pes(2)", "pes(1)","pes(3)" ]\n #last: pes:3, pes(2):0, pes(1):0, pes(3):0\n #modified = pes(3)\n \'\'\'\n cache = {}#store names\n res = []\n\n for idx, i in enumea\n \n\n \n for i in names:\n #not found right away, then\n if i not in cache:\n if \'(\' in i and \')\' in i:\n for name in cache: #break this for loop\n \n if name in i:\n leng = len(name)\n if len(i) == leng + 3 and i[leng] == "(" and i[leng+2] == ")":\n #check if it is repeaded :\n if i in cache[name]:\n break #do nothing\n #check if i_k in within k:\n \n \n i_k = leng+1\n if i_k > k:\n cache[name][count] += 1\n k = cache[name][count]\n st = name + "(" + str(k) + ")"\n res.append(st)\n cache[name][i] = 1\n \n \n cache[name][count] += 1\n k = cache[name][count]\n st = name + "(" + str(k) + ")"\n res.append(st)\n break\n res.append(i)\n cache[i] = {}\n cache[i][count] = 0\n\n else:\n \n cache[i][count] += 1\n #res.append(i)\n k = cache[i][count]\n #cache\n st = i + "(" + str(k) + ")"\n res.append(st)\n cache[i][st] = 1\n\n return res \n\n\n ["pes","fifa","gta","pes(1)", "pes(2019)"]\n \'\'\'\n \n``` | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Explication with Python Hash/Dict | making-file-names-unique | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$ average cases\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n #Inicialize hash and new names array\n frequency = {}\n uniqueNames = []\n \n #Foreach name in array names:\n for name in names:\n #If name is unique:\n if name not in frequency:\n uniqueNames.append(name)\n frequency[name] = 1\n #Name is not unique:\n else:\n namePlusNumber = name + "(" +str(frequency[name]) + ")"\n frequency[name]+=1\n #If new name is not unique:\n while(namePlusNumber in frequency):\n namePlusNumber = name + "(" +str(frequency[name]) + ")"\n frequency[name]+=1\n #Add new unique name to array and hash:\n uniqueNames.append(namePlusNumber)\n frequency[namePlusNumber] = 1\n \n return uniqueNames\n \n``` | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Explication with Python Hash/Dict | making-file-names-unique | 0 | 1 | # Complexity\n- Time complexity:\n$$O(n)$$ average cases\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n #Inicialize hash and new names array\n frequency = {}\n uniqueNames = []\n \n #Foreach name in array names:\n for name in names:\n #If name is unique:\n if name not in frequency:\n uniqueNames.append(name)\n frequency[name] = 1\n #Name is not unique:\n else:\n namePlusNumber = name + "(" +str(frequency[name]) + ")"\n frequency[name]+=1\n #If new name is not unique:\n while(namePlusNumber in frequency):\n namePlusNumber = name + "(" +str(frequency[name]) + ")"\n frequency[name]+=1\n #Add new unique name to array and hash:\n uniqueNames.append(namePlusNumber)\n frequency[namePlusNumber] = 1\n \n return uniqueNames\n \n``` | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Python - simple | making-file-names-unique | 0 | 1 | # Intuition\nBasically brute force. Store seen names in set, on already seen run dumb counter until you find first number that is not used.\n\n# Complexity\n- Time complexity:\nAverage $$O(NW)$$ - test cases support this \nTeorethical Worst case $$O(N^2W)$$ - for every name (N) processsing within hash table costs in worst case length of the name (W). Also there is counter loop in worst case of length N, imagine use case where there are 10000 same names. \n\n- Space complexity:\n$$O(NW)$$ - N number of names, W length of the name in characters\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n seen = set()\n result = []\n for name in names:\n candidate = name\n if candidate in seen:\n count = 1\n while (candidate := f\'{name}({count})\') in seen: count += 1\n result.append(candidate)\n seen.add(candidate)\n return result\n``` | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Python - simple | making-file-names-unique | 0 | 1 | # Intuition\nBasically brute force. Store seen names in set, on already seen run dumb counter until you find first number that is not used.\n\n# Complexity\n- Time complexity:\nAverage $$O(NW)$$ - test cases support this \nTeorethical Worst case $$O(N^2W)$$ - for every name (N) processsing within hash table costs in worst case length of the name (W). Also there is counter loop in worst case of length N, imagine use case where there are 10000 same names. \n\n- Space complexity:\n$$O(NW)$$ - N number of names, W length of the name in characters\n\n# Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n seen = set()\n result = []\n for name in names:\n candidate = name\n if candidate in seen:\n count = 1\n while (candidate := f\'{name}({count})\') in seen: count += 1\n result.append(candidate)\n seen.add(candidate)\n return result\n``` | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Clean python use dict beats >95% | making-file-names-unique | 0 | 1 | # Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n folders = dict()\n for i, name in enumerate(names):\n new_name = name\n if name not in folders:\n folders[name] = 0\n else:\n while new_name in folders:\n new_name = f"{name}({folders[name] + 1})"\n folders[name] += 1\n\n names[i] = new_name\n folders[new_name] = 0\n\n return names\n``` | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
Clean python use dict beats >95% | making-file-names-unique | 0 | 1 | # Code\n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n folders = dict()\n for i, name in enumerate(names):\n new_name = name\n if name not in folders:\n folders[name] = 0\n else:\n while new_name in folders:\n new_name = f"{name}({folders[name] + 1})"\n folders[name] += 1\n\n names[i] = new_name\n folders[new_name] = 0\n\n return names\n``` | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
easy solution | making-file-names-unique | 0 | 1 | \n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n op = {}\n for i in range(len(names)):\n if names[i] in op:\n b=names[i]+"("+str(op[names[i]])+")"\n op[names[i]]+=1\n while b in op:\n b=names[i]+"("+str(op[names[i]])+")"\n op[names[i]]+=1\n names[i] = b\n op[b]=1\n \n else:\n op[names[i]]=1\n return names\n``` | 0 | Given an array of strings `names` of size `n`. You will create `n` folders in your file system **such that**, at the `ith` minute, you will create a folder with the name `names[i]`.
Since two files **cannot** have the same name, if you enter a folder name that was previously used, the system will have a suffix addition to its name in the form of `(k)`, where, `k` is the **smallest positive integer** such that the obtained name remains unique.
Return _an array of strings of length_ `n` where `ans[i]` is the actual name the system will assign to the `ith` folder when you create it.
**Example 1:**
**Input:** names = \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Output:** \[ "pes ", "fifa ", "gta ", "pes(2019) "\]
**Explanation:** Let's see how the file system creates folder names:
"pes " --> not assigned before, remains "pes "
"fifa " --> not assigned before, remains "fifa "
"gta " --> not assigned before, remains "gta "
"pes(2019) " --> not assigned before, remains "pes(2019) "
**Example 2:**
**Input:** names = \[ "gta ", "gta(1) ", "gta ", "avalon "\]
**Output:** \[ "gta ", "gta(1) ", "gta(2) ", "avalon "\]
**Explanation:** Let's see how the file system creates folder names:
"gta " --> not assigned before, remains "gta "
"gta(1) " --> not assigned before, remains "gta(1) "
"gta " --> the name is reserved, system adds (k), since "gta(1) " is also reserved, systems put k = 2. it becomes "gta(2) "
"avalon " --> not assigned before, remains "avalon "
**Example 3:**
**Input:** names = \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece "\]
**Output:** \[ "onepiece ", "onepiece(1) ", "onepiece(2) ", "onepiece(3) ", "onepiece(4) "\]
**Explanation:** When the last folder is created, the smallest positive valid k is 4, and it becomes "onepiece(4) ".
**Constraints:**
* `1 <= names.length <= 5 * 104`
* `1 <= names[i].length <= 20`
* `names[i]` consists of lowercase English letters, digits, and/or round brackets. | Note you can allocate at most two families in one row. Greedily check if you can allocate seats for two families, one family or none. Process only rows that appear in the input, for other rows you can always allocate seats for two families. |
easy solution | making-file-names-unique | 0 | 1 | \n```\nclass Solution:\n def getFolderNames(self, names: List[str]) -> List[str]:\n op = {}\n for i in range(len(names)):\n if names[i] in op:\n b=names[i]+"("+str(op[names[i]])+")"\n op[names[i]]+=1\n while b in op:\n b=names[i]+"("+str(op[names[i]])+")"\n op[names[i]]+=1\n names[i] = b\n op[b]=1\n \n else:\n op[names[i]]=1\n return names\n``` | 0 | Given an integer `n`, you must transform it into `0` using the following operations any number of times:
* Change the rightmost (`0th`) bit in the binary representation of `n`.
* Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`.
Return _the minimum number of operations to transform_ `n` _into_ `0`_._
**Example 1:**
**Input:** n = 3
**Output:** 2
**Explanation:** The binary representation of 3 is "11 ".
"11 " -> "01 " with the 2nd operation since the 0th bit is 1.
"01 " -> "00 " with the 1st operation.
**Example 2:**
**Input:** n = 6
**Output:** 4
**Explanation:** The binary representation of 6 is "110 ".
"110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0.
"010 " -> "011 " with the 1st operation.
"011 " -> "001 " with the 2nd operation since the 0th bit is 1.
"001 " -> "000 " with the 1st operation.
**Constraints:**
* `0 <= n <= 109` | Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map. |
Python Soln (Greedy | Bisect | BinarySearch) + Comments ! | avoid-flood-in-the-city | 0 | 1 | # Intuition\nGreedy approach: empty the lake when needed\n\n#### Approach\nUse sorted array & binary search to discover which day is available to empty nth lake (S.T. day > n)\n\n#### Complexity\n- Time complexity: $$O(nlogn)$$\n- Space complexity: $$O(n)$$\n\n#### Code\n```\ndef find_gt(a, x):\n \'Find value higher than & closest to x\'\n i = bisect.bisect_right(a, x)\n if i != len(a):\n return a[i]\n return None \n\nclass Solution:\n def avoidFlood(self, rains: List[int]) -> List[int]:\n fullLakes = {}\n dryDays = []\n res = [-1]*len(rains)\n\n for day, lake in enumerate(rains):\n if lake == 0:\n dryDays.append(day)\n res[day] = 1 # by default select first lake to empty\n else:\n if lake in fullLakes:\n # Empty it\n dayOfFull = fullLakes[lake]\n dryDay = find_gt(dryDays, dayOfFull)\n if dryDay is None: return [] # cannot avoid Flood\n dryDays.remove(dryDay)\n res[dryDay] = lake\n\n fullLakes[lake] = day \n\n return res \n``` | 0 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
* `rains[i] > 0` means there will be rains over the `rains[i]` lake.
* `rains[i] == 0` means there are no rains this day and you can choose **one lake** this day and **dry it**.
Return _an array `ans`_ where:
* `ans.length == rains.length`
* `ans[i] == -1` if `rains[i] > 0`.
* `ans[i]` is the lake you choose to dry in the `ith` day if `rains[i] == 0`.
If there are multiple valid answers return **any** of them. If it is impossible to avoid flood return **an empty array**.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
**Example 1:**
**Input:** rains = \[1,2,3,4\]
**Output:** \[-1,-1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day full lakes are \[1,2,3\]
After the fourth day full lakes are \[1,2,3,4\]
There's no day to dry any lake and there is no flood in any lake.
**Example 2:**
**Input:** rains = \[1,2,0,0,2,1\]
**Output:** \[-1,-1,2,1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day, we dry lake 2. Full lakes are \[1\]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are \[2\].
After the sixth day, full lakes are \[1,2\].
It is easy that this scenario is flood-free. \[-1,-1,1,2,-1,-1\] is another acceptable scenario.
**Example 3:**
**Input:** rains = \[1,2,0,1,2\]
**Output:** \[\]
**Explanation:** After the second day, full lakes are \[1,2\]. We have to dry one lake in the third day.
After that, it will rain over lakes \[1,2\]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
**Constraints:**
* `1 <= rains.length <= 105`
* `0 <= rains[i] <= 109` | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
Python Soln (Greedy | Bisect | BinarySearch) + Comments ! | avoid-flood-in-the-city | 0 | 1 | # Intuition\nGreedy approach: empty the lake when needed\n\n#### Approach\nUse sorted array & binary search to discover which day is available to empty nth lake (S.T. day > n)\n\n#### Complexity\n- Time complexity: $$O(nlogn)$$\n- Space complexity: $$O(n)$$\n\n#### Code\n```\ndef find_gt(a, x):\n \'Find value higher than & closest to x\'\n i = bisect.bisect_right(a, x)\n if i != len(a):\n return a[i]\n return None \n\nclass Solution:\n def avoidFlood(self, rains: List[int]) -> List[int]:\n fullLakes = {}\n dryDays = []\n res = [-1]*len(rains)\n\n for day, lake in enumerate(rains):\n if lake == 0:\n dryDays.append(day)\n res[day] = 1 # by default select first lake to empty\n else:\n if lake in fullLakes:\n # Empty it\n dayOfFull = fullLakes[lake]\n dryDay = find_gt(dryDays, dayOfFull)\n if dryDay is None: return [] # cannot avoid Flood\n dryDays.remove(dryDay)\n res[dryDay] = lake\n\n fullLakes[lake] = day \n\n return res \n``` | 0 | A **[binary expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree)** is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes with two children) correspond to the operators. In this problem, we only consider the `'+'` operator (i.e. addition).
You are given the roots of two binary expression trees, `root1` and `root2`. Return `true` _if the two binary expression trees are equivalent_. Otherwise, return `false`.
Two binary expression trees are equivalent if they **evaluate to the same value** regardless of what the variables are set to.
**Example 1:**
**Input:** root1 = \[x\], root2 = \[x\]
**Output:** true
**Example 2:**
**Input:** root1 = \[+,a,+,null,null,b,c\], root2 = \[+,+,a,b,c\]
**Output:** true
**Explaination:** `a + (b + c) == (b + c) + a`
**Example 3:**
**Input:** root1 = \[+,a,+,null,null,b,c\], root2 = \[+,+,a,b,d\]
**Output:** false
**Explaination:** `a + (b + c) != (b + d) + a`
**Constraints:**
* The number of nodes in both trees are equal, odd and, in the range `[1, 4999]`.
* `Node.val` is `'+'` or a lower-case English letter.
* It's **guaranteed** that the tree given is a valid binary expression tree.
**Follow up:** What will you change in your solution if the tree also supports the `'-'` operator (i.e. subtraction)? | Keep An array of the last day there was rains over each city. Keep an array of the days you can dry a lake when you face one. When it rains over a lake, check the first possible day you can dry this lake and assign this day to this lake. |
HashMap + PQ | avoid-flood-in-the-city | 0 | 1 | # Code\n```\nfrom collections import defaultdict, deque\nfrom heapq import heappop, heappush\nclass Solution:\n def avoidFlood(self, rains: List[int]) -> List[int]:\n d = defaultdict(deque)\n n = len(rains)\n for i in range(n):\n if rains[i]: \n d[rains[i]].append(i)\n for lake in set(rains):\n if lake != 0: # pop the first instance\n d[lake].popleft()\n filled = set()\n q = []\n for i in range(n):\n if rains[i]:\n if rains[i] in filled: \n return []\n filled.add(rains[i])\n if d[rains[i]]:\n heappush(q, (d[rains[i]].popleft(), rains[i]))\n rains[i] = -1\n elif q:\n next_day, lake = heappop(q)\n filled.remove(lake)\n rains[i] = lake\n else:\n rains[i] = 1\n return rains\n\n\n``` | 0 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
* `rains[i] > 0` means there will be rains over the `rains[i]` lake.
* `rains[i] == 0` means there are no rains this day and you can choose **one lake** this day and **dry it**.
Return _an array `ans`_ where:
* `ans.length == rains.length`
* `ans[i] == -1` if `rains[i] > 0`.
* `ans[i]` is the lake you choose to dry in the `ith` day if `rains[i] == 0`.
If there are multiple valid answers return **any** of them. If it is impossible to avoid flood return **an empty array**.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
**Example 1:**
**Input:** rains = \[1,2,3,4\]
**Output:** \[-1,-1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day full lakes are \[1,2,3\]
After the fourth day full lakes are \[1,2,3,4\]
There's no day to dry any lake and there is no flood in any lake.
**Example 2:**
**Input:** rains = \[1,2,0,0,2,1\]
**Output:** \[-1,-1,2,1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day, we dry lake 2. Full lakes are \[1\]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are \[2\].
After the sixth day, full lakes are \[1,2\].
It is easy that this scenario is flood-free. \[-1,-1,1,2,-1,-1\] is another acceptable scenario.
**Example 3:**
**Input:** rains = \[1,2,0,1,2\]
**Output:** \[\]
**Explanation:** After the second day, full lakes are \[1,2\]. We have to dry one lake in the third day.
After that, it will rain over lakes \[1,2\]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
**Constraints:**
* `1 <= rains.length <= 105`
* `0 <= rains[i] <= 109` | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
HashMap + PQ | avoid-flood-in-the-city | 0 | 1 | # Code\n```\nfrom collections import defaultdict, deque\nfrom heapq import heappop, heappush\nclass Solution:\n def avoidFlood(self, rains: List[int]) -> List[int]:\n d = defaultdict(deque)\n n = len(rains)\n for i in range(n):\n if rains[i]: \n d[rains[i]].append(i)\n for lake in set(rains):\n if lake != 0: # pop the first instance\n d[lake].popleft()\n filled = set()\n q = []\n for i in range(n):\n if rains[i]:\n if rains[i] in filled: \n return []\n filled.add(rains[i])\n if d[rains[i]]:\n heappush(q, (d[rains[i]].popleft(), rains[i]))\n rains[i] = -1\n elif q:\n next_day, lake = heappop(q)\n filled.remove(lake)\n rains[i] = lake\n else:\n rains[i] = 1\n return rains\n\n\n``` | 0 | A **[binary expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree)** is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes with two children) correspond to the operators. In this problem, we only consider the `'+'` operator (i.e. addition).
You are given the roots of two binary expression trees, `root1` and `root2`. Return `true` _if the two binary expression trees are equivalent_. Otherwise, return `false`.
Two binary expression trees are equivalent if they **evaluate to the same value** regardless of what the variables are set to.
**Example 1:**
**Input:** root1 = \[x\], root2 = \[x\]
**Output:** true
**Example 2:**
**Input:** root1 = \[+,a,+,null,null,b,c\], root2 = \[+,+,a,b,c\]
**Output:** true
**Explaination:** `a + (b + c) == (b + c) + a`
**Example 3:**
**Input:** root1 = \[+,a,+,null,null,b,c\], root2 = \[+,+,a,b,d\]
**Output:** false
**Explaination:** `a + (b + c) != (b + d) + a`
**Constraints:**
* The number of nodes in both trees are equal, odd and, in the range `[1, 4999]`.
* `Node.val` is `'+'` or a lower-case English letter.
* It's **guaranteed** that the tree given is a valid binary expression tree.
**Follow up:** What will you change in your solution if the tree also supports the `'-'` operator (i.e. subtraction)? | Keep An array of the last day there was rains over each city. Keep an array of the days you can dry a lake when you face one. When it rains over a lake, check the first possible day you can dry this lake and assign this day to this lake. |
Python - short with priority qu | avoid-flood-in-the-city | 0 | 1 | # Basic idea\nEverything is described in problem hint.\nHold last index for very value. Process from start index.\nWhen value is met, if exists next index put it on priority queue. When zero pop from pqirioty queue.\nFail is when there is next index equal or smaller to current index or when everything is done and priority qu is not empty.\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def avoidFlood(self, rains):\n result, pq = [], []\n N, last = len(rains), defaultdict(deque)\n for i, v in enumerate(rains): last[v].append(i)\n\n for i, v in enumerate(rains):\n if v == 0:\n if pq: result.append(rains[heappop(pq)])\n else: result.append(1)\n else:\n if (last[v] and last[v][0] < i) or (pq and pq[0] <= i): return []\n if len(last[v]) > 1:\n last[v].popleft()\n heappush(pq, last[v][0])\n result.append(-1)\n \n return [] if pq else result\n``` | 0 | Your country has an infinite number of lakes. Initially, all the lakes are empty, but when it rains over the `nth` lake, the `nth` lake becomes full of water. If it rains over a lake that is **full of water**, there will be a **flood**. Your goal is to avoid floods in any lake.
Given an integer array `rains` where:
* `rains[i] > 0` means there will be rains over the `rains[i]` lake.
* `rains[i] == 0` means there are no rains this day and you can choose **one lake** this day and **dry it**.
Return _an array `ans`_ where:
* `ans.length == rains.length`
* `ans[i] == -1` if `rains[i] > 0`.
* `ans[i]` is the lake you choose to dry in the `ith` day if `rains[i] == 0`.
If there are multiple valid answers return **any** of them. If it is impossible to avoid flood return **an empty array**.
Notice that if you chose to dry a full lake, it becomes empty, but if you chose to dry an empty lake, nothing changes.
**Example 1:**
**Input:** rains = \[1,2,3,4\]
**Output:** \[-1,-1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day full lakes are \[1,2,3\]
After the fourth day full lakes are \[1,2,3,4\]
There's no day to dry any lake and there is no flood in any lake.
**Example 2:**
**Input:** rains = \[1,2,0,0,2,1\]
**Output:** \[-1,-1,2,1,-1,-1\]
**Explanation:** After the first day full lakes are \[1\]
After the second day full lakes are \[1,2\]
After the third day, we dry lake 2. Full lakes are \[1\]
After the fourth day, we dry lake 1. There is no full lakes.
After the fifth day, full lakes are \[2\].
After the sixth day, full lakes are \[1,2\].
It is easy that this scenario is flood-free. \[-1,-1,1,2,-1,-1\] is another acceptable scenario.
**Example 3:**
**Input:** rains = \[1,2,0,1,2\]
**Output:** \[\]
**Explanation:** After the second day, full lakes are \[1,2\]. We have to dry one lake in the third day.
After that, it will rain over lakes \[1,2\]. It's easy to prove that no matter which lake you choose to dry in the 3rd day, the other one will flood.
**Constraints:**
* `1 <= rains.length <= 105`
* `0 <= rains[i] <= 109` | Use dynamic programming to get the power of each integer of the intervals. Sort all the integers of the interval by the power value and return the k-th in the sorted list. |
Python - short with priority qu | avoid-flood-in-the-city | 0 | 1 | # Basic idea\nEverything is described in problem hint.\nHold last index for very value. Process from start index.\nWhen value is met, if exists next index put it on priority queue. When zero pop from pqirioty queue.\nFail is when there is next index equal or smaller to current index or when everything is done and priority qu is not empty.\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def avoidFlood(self, rains):\n result, pq = [], []\n N, last = len(rains), defaultdict(deque)\n for i, v in enumerate(rains): last[v].append(i)\n\n for i, v in enumerate(rains):\n if v == 0:\n if pq: result.append(rains[heappop(pq)])\n else: result.append(1)\n else:\n if (last[v] and last[v][0] < i) or (pq and pq[0] <= i): return []\n if len(last[v]) > 1:\n last[v].popleft()\n heappush(pq, last[v][0])\n result.append(-1)\n \n return [] if pq else result\n``` | 0 | A **[binary expression tree](https://en.wikipedia.org/wiki/Binary_expression_tree)** is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes with two children) correspond to the operators. In this problem, we only consider the `'+'` operator (i.e. addition).
You are given the roots of two binary expression trees, `root1` and `root2`. Return `true` _if the two binary expression trees are equivalent_. Otherwise, return `false`.
Two binary expression trees are equivalent if they **evaluate to the same value** regardless of what the variables are set to.
**Example 1:**
**Input:** root1 = \[x\], root2 = \[x\]
**Output:** true
**Example 2:**
**Input:** root1 = \[+,a,+,null,null,b,c\], root2 = \[+,+,a,b,c\]
**Output:** true
**Explaination:** `a + (b + c) == (b + c) + a`
**Example 3:**
**Input:** root1 = \[+,a,+,null,null,b,c\], root2 = \[+,+,a,b,d\]
**Output:** false
**Explaination:** `a + (b + c) != (b + d) + a`
**Constraints:**
* The number of nodes in both trees are equal, odd and, in the range `[1, 4999]`.
* `Node.val` is `'+'` or a lower-case English letter.
* It's **guaranteed** that the tree given is a valid binary expression tree.
**Follow up:** What will you change in your solution if the tree also supports the `'-'` operator (i.e. subtraction)? | Keep An array of the last day there was rains over each city. Keep an array of the days you can dry a lake when you face one. When it rains over a lake, check the first possible day you can dry this lake and assign this day to this lake. |
beats 96% memory wise :) | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | \n\n# Code\n```\nclass UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n \n def find_parent(self, p):\n if self.parent[p] != p:\n self.parent[p] = self.find_parent(self.parent[p])\n return self.parent[p]\n \n def union_sets(self, u, v):\n pu, pv = self.find_parent(u), self.find_parent(v)\n self.parent[pu] = pv\n\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n def find_MST(graph, block, e):\n uf = UnionFind(n)\n weight = 0\n \n if e != -1:\n weight += edges[e][2]\n uf.union_sets(edges[e][0], edges[e][1])\n \n for i in range(len(edges)):\n if i == block:\n continue\n \n if uf.find_parent(edges[i][0]) == uf.find_parent(edges[i][1]):\n continue\n \n uf.union_sets(edges[i][0], edges[i][1])\n weight += edges[i][2]\n \n for i in range(n):\n if uf.find_parent(i) != uf.find_parent(0):\n return float(\'inf\')\n \n return weight\n \n critical = []\n pseudo_critical = []\n \n for i, edge in enumerate(edges):\n edge.append(i)\n \n edges.sort(key=lambda x: x[2])\n mst_weight = find_MST(edges, -1, -1)\n \n for i, edge in enumerate(edges):\n if mst_weight < find_MST(edges, i, -1):\n critical.append(edge[3])\n elif mst_weight == find_MST(edges, -1, i):\n pseudo_critical.append(edge[3])\n \n return [critical, pseudo_critical]\n``` | 3 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
100% Best Solution And Easy Understanble With Comments || MST | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 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# plss Upvote For Me :(\n\n# Creating Class For MST Algorithm\nclass UnionFind:\n def __init__ (self, n):\n self.parents = list(range(n)) # Initialy Every Vertex Is It\'s Own Parent\n self.weight = 0 # Initialy Weight = 0\n self.edgeCount = 0 # Initialy edgeCount = 0\n\n def find(self, x): # Find Function TO Find The Parent Of X Recursively\n if x != self.parents[x]: # If X is not it\'s Own Parent\n self.parents[x] = self.find(self.parents[x]) # then Finding It\'s Parent\n return self.parents[x] # Returning The Parent Of X\n\n def union(self, x, y, w): # Union Function TO Creating MST Algo\n r1 = self.find(x) # Finding The X Parent\n r2 = self.find(y) # Finding The Y Parent\n\n if r1 != r2: # If the Parents Are Not Same\n self.parents[r2] = r1 # The create Parent of r2 to r1\n self.weight += w # Incresing the Weight\n self.edgeCount += 1 # Increasing The EsgeCount by 1\n\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n # Step 1: Sorting the edges List\n edges = [(w,a,b,i) for i, (a,b,w) in enumerate(edges)] # As we have to return i (index)\n edges.sort()\n\n # Step 2: Finding the First MinWeight In entire edges\n uf1 = UnionFind(n)\n for w, a, b, _ in edges:\n uf1.union(a, b, w)\n\n minWeight = uf1.weight\n\n # Step 3: Defining The Critical and Pseudo Critical Edges Empty \n ce = []\n pce = []\n m = len(edges)\n\n\n # step 4: Now Including And Excludeing the edges to find Critical and PsuedoCritical edges\n for i in range(m):\n uf2 = UnionFind(n) # Creting New uf2 UnionFind Class\n for j in range(m): # for every edge\n if i == j:\n continue\n w,a,b,_ = edges[j] \n uf2.union(a,b,w) # Unioning the x, y\n \n # if curr weight is greather or we didn\'t draw the proper graph\n if uf2.weight > minWeight or uf2.edgeCount < n-1:\n ce.append(edges[i][3]) # It is a Critical Edge\n\n\n else:\n # Forcefully adding the edge i and again doing MST Algo\n uf3 = UnionFind(n) # creating new object Class\n w,a,b,_ = edges[i] # taking the i edges\n uf3.union(a,b,w) # unioning the first i edge\n for j in range(m):\n w,a,b,_ = edges[j] # Uninoning the edges acordingly\n uf3.union(a,b,w)\n \n if uf3.weight == minWeight: # If curr weight == min wight\n pce.append(edges[i][3]) # it is a PseudoCritical Edge\n\n return ce, pce # Now Returning The Critical Edge And PseudoCretical Edge\n``` | 2 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
Python3 Solution | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | \n```\nclass Solution :\n def find(self,u,parent):\n if u==parent[u]:\n return u\n return self.find(parent[u],parent)\n\n def unionDSU(self,u,v,parent) :\n p1=self.find(u,parent)\n p2=self.find(v,parent)\n parent[p2]=p1\n\n def mst(self,k,edges,includeEdge,excludeEdge) :\n n=len(includeEdge)\n m=len(excludeEdge)\n parent=[]\n for i in range(k): \n parent.append(i);\n \n res=0\n count=0\n\n if n!= 0 :\n self.unionDSU(includeEdge[0], includeEdge[1], parent)\n res+=includeEdge[2]\n count+=1\n \n for edge in edges:\n u=edge[0];\n v=edge[1];\n cost=edge[2];\n\n if m!=0 and excludeEdge[0]==u and excludeEdge[1]==v and excludeEdge[2]==cost :\n continue\n \n if n!=0 and includeEdge[0]==u and includeEdge[1]==v and includeEdge[2]==cost :\n continue\n \n p1=self.find(u,parent)\n p2=self.find(v,parent)\n\n if p1!= p2:\n self.unionDSU(p1, p2, parent)\n res+= cost\n count += 1\n \n return res if count==k-1 else float(\'inf\')\n \n def findCriticalAndPseudoCriticalEdges(self, k:int, edges:List[List[int]]) -> List[List[int]]:\n \n originalEdges=[]\n for edge in edges : \n originalEdge=[edge[0],edge[1],edge[2]]\n originalEdges.append(originalEdge)\n \n X=len(originalEdges)\n ans=[]\n criticalEdges=[]\n pseudoCriticalEdges=[]\n\n \n edges=sorted(edges, key = lambda x: x[2])\n\n emptyVector=[]\n originalCost = self.mst(k, edges, emptyVector, emptyVector)\n \n for i in range(X): \n excludedCost = self.mst(k, edges, emptyVector, originalEdges[i])\n includedCost = self.mst(k, edges, originalEdges[i], emptyVector)\n\n if excludedCost > originalCost :\n criticalEdges.append(i)\n \n elif includedCost==originalCost : \n pseudoCriticalEdges.append(i)\n \n ans.append(criticalEdges)\n ans.append(pseudoCriticalEdges)\n return ans\n``` | 2 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
Ex-Amazon explains a solution with Python and Java | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 1 | 1 | # Solution Video\nI have to take care of my kids all day. Usually I put a solution video for each question but today, it seems to be hard to create the video.\n\n### Please subscribe to my channel from here. I have 245 videos as of August 19th.\n\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n---\n\n# Approach\nI have limited time today, so I solved this quesion with Python and Java. This is based on Python. Other might be different a bit.\n\n1. **Initialize UnionFind Class:**\n - Create a class named `UnionFind` to implement the Union-Find data structure.\n - Initialize the class with the `size` of elements. Initialize `parent` as a list of indices and set each element\'s size to 1 and `max_size` to 1.\n\n2. **Define `find` Method:**\n - Implement the `find` method within the `UnionFind` class.\n - Given an element `x`, recursively find its root element and update its parent to the root.\n - Return the root element.\n\n3. **Define `union` Method:**\n - Implement the `union` method within the `UnionFind` class.\n - Given elements `x` and `y`, find their root elements.\n - If the roots are not the same, merge the smaller tree under the larger tree.\n - Update the parent and size accordingly, and track the maximum size.\n\n4. **Initialize Variables:**\n - Create a function named `findCriticalAndPseudoCriticalEdges` within the `Solution` class.\n - Create a copy of the `edges` list named `sorted_edges` and append the index to each edge.\n - Sort `sorted_edges` based on the edge weight using a lambda function.\n\n5. **Calculate Minimum Spanning Tree (MST) Weight:**\n - Initialize an instance of the `UnionFind` class as `union_find_standard`.\n - Initialize `minimum_spanning_tree_weight` as 0.\n - Iterate through each edge `(u, v, weight, _)` in `sorted_edges`.\n - If `union_find_standard.union(u, v)` connects the nodes, update `minimum_spanning_tree_weight` by adding the edge weight.\n\n6. **Find Critical and Pseudo-Critical Edges:**\n - Initialize two empty lists `critical_edges` and `pseudo_critical_edges`.\n - Iterate through each edge `(u, v, weight, i)` in `sorted_edges`.\n - Initialize a temporary `UnionFind` instance as `union_find_temp` and a temporary weight `temp_weight` as 0.\n - For each edge `(x, y, w_temp, j)` in `sorted_edges`, calculate the total weight `temp_weight` if the current edge is ignored.\n - Check if `union_find_temp.max_size` is less than `n` or `temp_weight` is greater than `minimum_spanning_tree_weight`.\n - If true, add `i` to `critical_edges` and continue.\n - Otherwise, initialize a new `UnionFind` instance as `union_find_force` and initialize `force_weight` as `weight`.\n - Perform union on `(u, v)` using `union_find_force` and iterate through all edges to calculate `force_weight` if the current edge is forced.\n - Check if `force_weight` is equal to `minimum_spanning_tree_weight`.\n - If true, add `i` to `pseudo_critical_edges`.\n\n7. **Return Result:**\n - Return a list containing `critical_edges` and `pseudo_critical_edges`.\n\nThe code aims to find critical and pseudo-critical edges in a graph\'s minimum spanning tree (MST) using the Union-Find data structure. It sorts edges based on weight, calculates the MST weight, and checks for critical and pseudo-critical edges based on certain conditions.\n\n```python []\nclass Solution:\n\n class UnionFind:\n def __init__(self, size):\n self.parent = list(range(size))\n self.size = [1] * size\n self.max_size = 1\n\n def find(self, x):\n if x != self.parent[x]:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n\n def union(self, x, y):\n root_x = self.find(x)\n root_y = self.find(y)\n if root_x != root_y:\n if self.size[root_x] < self.size[root_y]:\n root_x, root_y = root_y, root_x\n self.parent[root_y] = root_x\n self.size[root_x] += self.size[root_y]\n self.max_size = max(self.max_size, self.size[root_x])\n return True\n return False\n\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n sorted_edges = [edge.copy() for edge in edges]\n\n for i, edge in enumerate(sorted_edges):\n edge.append(i)\n\n sorted_edges.sort(key=lambda x: x[2])\n\n union_find_standard = self.UnionFind(n)\n minimum_spanning_tree_weight = 0\n for u, v, weight, _ in sorted_edges:\n if union_find_standard.union(u, v):\n minimum_spanning_tree_weight += weight\n\n critical_edges = []\n pseudo_critical_edges = []\n for (u, v, weight, i) in sorted_edges:\n union_find_temp = self.UnionFind(n)\n temp_weight = 0\n for (x, y, w_temp, j) in sorted_edges:\n if i != j and union_find_temp.union(x, y):\n temp_weight += w_temp\n\n if union_find_temp.max_size < n or temp_weight > minimum_spanning_tree_weight:\n critical_edges.append(i)\n continue\n\n union_find_force = self.UnionFind(n)\n force_weight = weight\n union_find_force.union(u, v)\n for (x, y, w_force, j) in sorted_edges:\n if i != j and union_find_force.union(x, y):\n force_weight += w_force\n\n if force_weight == minimum_spanning_tree_weight:\n pseudo_critical_edges.append(i)\n\n return [critical_edges, pseudo_critical_edges]\n```\n```java []\nimport java.util.*;\n\nclass Solution {\n class UnionFind {\n int[] parent;\n int[] size;\n int maxSize;\n\n public UnionFind(int size) {\n this.parent = new int[size];\n this.size = new int[size];\n for (int i = 0; i < size; i++) {\n parent[i] = i;\n this.size[i] = 1;\n }\n this.maxSize = 1;\n }\n\n public int find(int x) {\n if (x != parent[x]) {\n parent[x] = find(parent[x]);\n }\n return parent[x];\n }\n\n public boolean union(int x, int y) {\n int rootX = find(x);\n int rootY = find(y);\n if (rootX != rootY) {\n if (size[rootX] < size[rootY]) {\n int temp = rootX;\n rootX = rootY;\n rootY = temp;\n }\n parent[rootY] = rootX;\n size[rootX] += size[rootY];\n maxSize = Math.max(maxSize, size[rootX]);\n return true;\n }\n return false;\n }\n }\n\n public List<List<Integer>> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) {\n List<List<Integer>> result = new ArrayList<>();\n List<int[]> sortedEdges = new ArrayList<>();\n for (int i = 0; i < edges.length; i++) {\n sortedEdges.add(new int[]{edges[i][0], edges[i][1], edges[i][2], i});\n }\n Collections.sort(sortedEdges, Comparator.comparingInt(a -> a[2]));\n\n UnionFind unionFindStandard = new UnionFind(n);\n int minimumSpanningTreeWeight = 0;\n for (int[] edge : sortedEdges) {\n if (unionFindStandard.union(edge[0], edge[1])) {\n minimumSpanningTreeWeight += edge[2];\n }\n }\n\n List<Integer> criticalEdges = new ArrayList<>();\n List<Integer> pseudoCriticalEdges = new ArrayList<>();\n for (int[] edge : sortedEdges) {\n UnionFind unionFindTemp = new UnionFind(n);\n int tempWeight = 0;\n for (int[] tempEdge : sortedEdges) {\n if (edge[3] != tempEdge[3] && unionFindTemp.union(tempEdge[0], tempEdge[1])) {\n tempWeight += tempEdge[2];\n }\n }\n\n if (unionFindTemp.maxSize < n || tempWeight > minimumSpanningTreeWeight) {\n criticalEdges.add(edge[3]);\n continue;\n }\n\n UnionFind unionFindForce = new UnionFind(n);\n int forceWeight = edge[2];\n unionFindForce.union(edge[0], edge[1]);\n for (int[] forceEdge : sortedEdges) {\n if (edge[3] != forceEdge[3] && unionFindForce.union(forceEdge[0], forceEdge[1])) {\n forceWeight += forceEdge[2];\n }\n }\n\n if (forceWeight == minimumSpanningTreeWeight) {\n pseudoCriticalEdges.add(edge[3]);\n }\n }\n\n result.add(criticalEdges);\n result.add(pseudoCriticalEdges);\n return result;\n }\n}\n``` | 9 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
Python 3 | Beats Edirotial in Time | Two criteria | O(E^2) | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | # Intuition\nWe need to find an approach to decide whether edge is critical, pseudo-critical or neither of them\n\n# Approach\n1. According to Kruskal\'s algorithm if edge is <ins>_unused_ AND _has minimum weight_ AND _connects two disjoint sets_</ins> **[1]** then there is MST (or MSTs) which includes this edge (remember, graph might have several MSTs \u2014 otherwise this problem wouldn\'t make sense). Since this edge is a part of some MST then this edge is critical or pseudo-critical. So this step helps us to filter out all edges which are neither critical or pseudo-critical (they don\'t satisfy criteria **[1]**)\n2. It remains only to decide whether edge is critical or pseudo-critical for each edge which satisfies criteria **[1]**. And there is another nice criteria: the edge with weight $w$ which connects two disjoint sets $A$ and $B$ is pseudo-critical if and only if <ins>_there is another edge with the same weight $w$ which connects the same two disjoint sets $A$ and $B$_ OR _using other edges of weight $w$ it\'s possible to connect $A$ and $B$_</ins> **[2]**. Actually the second condition includes the first one, but it\'s easier to comperehend and implement it this way.\n\nTo sum up, \n* If (criteria **[1]**):\n * if (criteria **[2]**):\n $\\rightarrow$ pseudo-critical\n * else:\n $\\rightarrow$ critical\n* else:\n $\\rightarrow$ none\n\n# Complexity\n- Time complexity: still $O(E^2)$ in the worst case (but actually works faster in average and at least beats editorial 92ms vs 1124ms)\n\n- Space complexity: $O(E)$\n\n# Code\n```\nclass DisjointSet:\n def __init__(self, n):\n self.node2root = {i:i for i in range(n)}\n self.node2rank = {i:0 for i in range(n)}\n \n def find(self, node):\n if self.node2root[node] != node:\n self.node2root[node] = self.find(self.node2root[node])\n return self.node2root[node]\n \n def union(self, node1, node2):\n root1 = self.find(node1)\n root2 = self.find(node2)\n if root1 == root2:\n return False\n rank1 = self.node2rank[root1]\n rank2 = self.node2rank[root2]\n if rank1 <= rank2:\n self.node2root[root1] = root2\n self.node2rank[root2] += (rank1 == rank2)\n else:\n self.node2root[root2] = root1\n return True\n\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n ds = DisjointSet(n)\n critical = []\n pseudo_critical = []\n\n Edge = namedtuple(\'Edge\', [\'ind\', \'src\', \'dst\', \'weight\'])\n sorted_edges = [Edge(i, *edge) for i, edge in enumerate(edges)]\n sorted_edges.sort(key=lambda e: e.weight)\n for weight, same_weight_edges in itertools.groupby(sorted_edges, key=lambda e: e.weight):\n graph = defaultdict(set)\n etype2edges = defaultdict(list)\n for edge_ind, s, d, w in same_weight_edges:\n root1 = ds.find(s)\n root2 = ds.find(d)\n if root1 != root2: # criteria 1\n graph[root1].add(root2)\n graph[root2].add(root1)\n etype = f\'{min(root1, root2)}<->{max(root1, root2)}\'\n etype2edges[etype].append(edge_ind)\n for etype, interchangeable_edges in etype2edges.items():\n root1, root2 = map(int, etype.split(\'<->\'))\n if len(interchangeable_edges) > 1 or self.edge_in_cycle(root1, root2, graph): # criteria 2\n for edge in interchangeable_edges:\n pseudo_critical.append(edge)\n else:\n critical.append(interchangeable_edges[0])\n ds.union(root1, root2)\n return [critical, pseudo_critical]\n\n def edge_in_cycle(self, src, dst, graph):\n graph[src].remove(dst)\n graph[dst].remove(src)\n still_has_path = self.find(src, dst, graph, set())\n graph[src].add(dst)\n graph[dst].add(src)\n return still_has_path\n\n def find(self, node, target, graph, seen):\n if node == target:\n return True\n if node in seen:\n return False\n seen.add(node)\n for neigh in graph[node]:\n if self.find(neigh, target, graph, seen):\n return True\n return False\n``` | 1 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
Prim's algo (python) | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nPrim\'s algo\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 findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n def prim(edges, forced_edge=None):\n visited = [False] * n\n edge_list = [[] for _ in range(n)]\n for i, (u, v, w) in enumerate(edges):\n edge_list[u].append((v, w, i))\n edge_list[v].append((u, w, i))\n\n weight = 0\n pq = []\n\n if forced_edge is not None:\n u, v, w = edges[forced_edge]\n visited[u] = True\n visited[v] = True\n weight += w\n for nxt, w, idx in edge_list[u]:\n heapq.heappush(pq, (w, nxt, idx))\n for nxt, w, idx in edge_list[v]:\n heapq.heappush(pq, (w, nxt, idx))\n else:\n heapq.heappush(pq, (0, 0, -1))\n\n while pq:\n w, v, idx = heapq.heappop(pq)\n if not visited[v]:\n visited[v] = True\n weight += w\n for nxt, nxt_w, nxt_idx in edge_list[v]:\n if not visited[nxt]:\n heapq.heappush(pq, (nxt_w, nxt, nxt_idx))\n\n if sum(visited) != n: # Not all vertices were visited\n return float(\'inf\')\n\n return weight\n\n # Find the weight of the original MST\n mst_weight = prim(edges)\n\n criticals, pseudo_criticals = [], []\n\n # Check for critical edges\n for i in range(len(edges)):\n new_weight = prim(edges[:i] + edges[i+1:])\n if new_weight > mst_weight:\n criticals.append(i)\n\n # Check for pseudo-critical edges\n for i in range(len(edges)):\n if i not in criticals:\n new_weight = prim(edges, i)\n if new_weight == mst_weight:\n pseudo_criticals.append(i)\n\n return [criticals, pseudo_criticals]\n\n``` | 1 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
Python: Simple and Elegant, Prim's (20lines) | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | # Intuition\n1. Calculate the cost of the Minimum Spanning Tree (MST) as $C$.\n2. For each edge, compute the cost if excluded, denoted as $C_e$, and the cost if included, denoted as $C_i$.\n3. An edge is considered critical if $C_e > C$, and pseudo-critical if $C_e = C = C_i$.\n\n# Complexity\n- Time complexity:\n$$O(E^2 logV)$$\n\n- Space complexity:\n$$O(E)$$\n\n# Code\n```\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n edges = [(a, b, c, i) for i, (a, b, c) in enumerate(edges)]\n edges.sort(key = lambda x: x[2])\n maxCost = 1000 * 100\n\n def getMSTCost(E, V, C):\n \'\'\' \n E: edge exclusive set\n V: nodes in MST\n C: current Cost\n \'\'\'\n nonlocal edges, n, maxCost\n if len(V) == n:\n return C\n else:\n for a, b, c, i in edges:\n if i not in E and (a in V and b not in V or a not in V and b in V):\n return getMSTCost(E | set([i]), V | set([a, b]), C + c)\n return maxCost\n \n C = getMSTCost(set(), set([0]), 0)\n\n critical, pseudo_critical = [], []\n for a, b, c, i in edges:\n if getMSTCost(set([i]), set([0]), 0) > C:\n critical += [i]\n elif getMSTCost(set([i]), set([a, b]), c) == C:\n pseudo_critical += [i]\n\n return [critical, pseudo_critical]\n```\n\nNote that this impl is not optimized. | 3 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
🔥🔥🔥🔥🔥Beats 100% | JS | TS | Java | C++ | C# | Python | python3 | Kotlin | 🔥🔥🔥🔥🔥 | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 1 | 1 | ---\n\n\n---\n\n```C++ []\nclass UnionFind {\npublic: \n vector<int> parent; \n UnionFind(int n){\n parent.resize(n);\n for(int i=0;i<n;i++)\n parent[i] = i; \n }\n \n int findParent(int p) {\n return parent[p] == p ? p : parent[p] = findParent(parent[p]); \n }\n \n void Union(int u , int v) {\n int pu = findParent(u) , pv = findParent(v); \n parent[pu] = pv;\n } \n};\n\nclass Solution {\npublic: \n static bool cmp(vector<int>&a , vector<int>&b) {\n return a[2] < b[2]; \n }\n \n vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<vector<int>>& edges) {\n vector<int> critical , pscritical ;\n //1\n for(int i=0;i<edges.size();i++)\n edges[i].push_back(i); \n \n //2 \n sort(edges.begin() , edges.end() , cmp) ;\n \n int mstwt = findMST(n,edges,-1,-1); //3\n for(int i=0;i<edges.size();i++){\n if(mstwt< findMST(n,edges,i,-1)) //5\n critical.push_back(edges[i][3]); \n else if(mstwt == findMST(n,edges,-1,i)) //6\n pscritical.push_back(edges[i][3]);\n }\n return {critical , pscritical}; \n }\n \nprivate:\n int findMST(int &n , vector<vector<int>>& edges , int block , int e) {\n UnionFind uf(n); \n int weight = 0 ;\n if(e != -1) {\n weight += edges[e][2]; \n uf.Union(edges[e][0] , edges[e][1]); \n }\n \n for(int i=0;i<edges.size();i++){\n if(i == block) \n continue; \n if(uf.findParent(edges[i][0]) == uf.findParent(edges[i][1])) //4\n continue; \n uf.Union(edges[i][0] , edges[i][1]); \n weight += edges[i][2]; \n }\n \n //Check if all vertices are included then only it is MST. \n for(int i=0;i<n;i++){\n if(uf.findParent(i) != uf.findParent(0))\n return INT_MAX;\n } \n \n return weight; \n }\n \n};\n```\n```Typescript []\nfunction findCriticalAndPseudoCriticalEdges(n: number, edges: number[][]): number[][] {\n let copyEdges=[...edges];\n \n let mst=findMst(n,copyEdges,[],[]);\n let critical:number[]=[];\n let pseudoCritical:number[]=[];\n \n for(let i =0;i<edges.length;i++)\n {\n \n let delMst=findMst(n,copyEdges,[],edges[i]);\n \n if(delMst!=mst){\n critical.push(i);\n continue; \n }\n let forceMst=findMst(n,copyEdges,edges[i],[]);\n \n if(forceMst==mst)\n pseudoCritical.push(i);\n \n }\n return [critical,pseudoCritical];\n\n};\n\nfunction filterRow(rowNum:number, arr:number[][]): number[][]{\n let copy:number[][]=[];\n \n for(let i=0;i<arr.length;i++)\n if(i!=rowNum)\n copy.push(arr[i]);\n \n return copy;\n \n \n}\n\nfunction findMst(n:number, edges: number[][],forceEdge:number[],deleteEdge:number[]): number {\n \n edges.sort((a,b)=>a[2]-b[2]);\n\n const parent= Array(n);\n const rank=Array(n).fill(0);\n \n for(let i=0;i<n;i++)\n parent[i]=i;\n \n \n\n \n let mst:number=0;\n let numEdges:number=0;\n \n \n if(forceEdge.length!=0)\n {\n let edge=forceEdge;\n let v1=edge[0];\n let v2=edge[1];\n let weight=edge[2];\n \n if(findParent(v1,parent)!=findParent(v2,parent))\n {\n numEdges++;\n mst+=weight;\n \n union(v1,v2,rank,parent);\n \n }\n }\n \n \n for(let i=0;i<edges.length;i++)\n { \n \n \n \n let edge=edges[i];\n let v1=edge[0];\n let v2=edge[1];\n let weight=edge[2];\n \n if(deleteEdge.length!=0 && v1==deleteEdge[0] && v2==deleteEdge[1])\n continue;\n \n \n if(findParent(v1,parent)!=findParent(v2,parent))\n {\n numEdges++;\n mst+=weight;\n union(v1,v2,rank,parent);\n \n }\n \n if(numEdges==n-1)\n break;\n \n }\n \n return mst;\n \n}\n\nfunction findParent(vertex: number, parent: number[]): number{\n if(parent[vertex]==vertex)\n return vertex;\n \n return parent[vertex]=findParent(parent[vertex],parent);\n \n \n}\n\n\nfunction union(v1:number, v2:number, rank:number[], parent:number[] ): void {\n v1=findParent(v1,parent);\n v2=findParent(v2,parent);\n \n if(rank[v1]>rank[v2])\n {\n parent[v2]=v1;\n }\n else if(rank[v2]>rank[v1])\n parent[v1]=v2;\n else{\n parent[v2]=v1;\n rank[v1]++;\n }\n}\n```\n```Java []\nimport java.util.*;\n\nclass UnionFind {\n private int[] parent;\n\n public UnionFind(int n) {\n parent = new int[n];\n for (int i = 0; i < n; i++)\n parent[i] = i;\n }\n\n public int findParent(int p) {\n return parent[p] == p ? p : (parent[p] = findParent(parent[p]));\n }\n\n public void union(int u, int v) {\n int pu = findParent(u), pv = findParent(v);\n parent[pu] = pv;\n }\n}\n\nclass Solution {\n public List<List<Integer>> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) {\n List<Integer> critical = new ArrayList<>();\n List<Integer> pseudoCritical = new ArrayList<>();\n \n for (int i = 0; i < edges.length; i++) {\n int[] edge = edges[i];\n edge = Arrays.copyOf(edge, edge.length + 1);\n edge[3] = i;\n edges[i] = edge;\n }\n \n Arrays.sort(edges, (a, b) -> Integer.compare(a[2], b[2]));\n\n int mstwt = findMST(n, edges, -1, -1);\n\n for (int i = 0; i < edges.length; i++) {\n if (mstwt < findMST(n, edges, i, -1))\n critical.add(edges[i][3]);\n else if (mstwt == findMST(n, edges, -1, i))\n pseudoCritical.add(edges[i][3]);\n }\n\n List<List<Integer>> result = new ArrayList<>();\n result.add(critical);\n result.add(pseudoCritical);\n return result;\n }\n\n private int findMST(int n, int[][] edges, int block, int e) {\n UnionFind uf = new UnionFind(n);\n int weight = 0;\n\n if (e != -1) {\n weight += edges[e][2];\n uf.union(edges[e][0], edges[e][1]);\n }\n\n for (int i = 0; i < edges.length; i++) {\n if (i == block)\n continue;\n\n if (uf.findParent(edges[i][0]) == uf.findParent(edges[i][1]))\n continue;\n\n uf.union(edges[i][0], edges[i][1]);\n weight += edges[i][2];\n }\n\n for (int i = 0; i < n; i++) {\n if (uf.findParent(i) != uf.findParent(0))\n return Integer.MAX_VALUE;\n }\n\n return weight;\n }\n}\n```\n```Python []\nclass UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n \n def find_parent(self, p):\n if self.parent[p] == p:\n return p\n self.parent[p] = self.find_parent(self.parent[p])\n return self.parent[p]\n \n def union(self, u, v):\n pu, pv = self.find_parent(u), self.find_parent(v)\n self.parent[pu] = pv\n\nclass Solution:\n @staticmethod\n def cmp(a, b):\n return a[2] < b[2]\n \n def findCriticalAndPseudoCriticalEdges(self, n, edges):\n critical = []\n pseudo_critical = []\n \n for i in range(len(edges)):\n edges[i].append(i)\n \n edges.sort(key=lambda x: x[2])\n \n mstwt = self.find_MST(n, edges, -1, -1)\n \n for i in range(len(edges)):\n if mstwt < self.find_MST(n, edges, i, -1):\n critical.append(edges[i][3])\n elif mstwt == self.find_MST(n, edges, -1, i):\n pseudo_critical.append(edges[i][3])\n \n return [critical, pseudo_critical]\n \n def find_MST(self, n, edges, block, e):\n uf = UnionFind(n)\n weight = 0\n \n if e != -1:\n weight += edges[e][2]\n uf.union(edges[e][0], edges[e][1])\n \n for i in range(len(edges)):\n if i == block:\n continue\n if uf.find_parent(edges[i][0]) == uf.find_parent(edges[i][1]):\n continue\n uf.union(edges[i][0], edges[i][1])\n weight += edges[i][2]\n \n for i in range(n):\n if uf.find_parent(i) != uf.find_parent(0):\n return float(\'inf\')\n \n return weight\n```\n```Python3 []\nclass UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n \n def find_parent(self, p):\n if self.parent[p] == p:\n return p\n self.parent[p] = self.find_parent(self.parent[p])\n return self.parent[p]\n \n def union(self, u, v):\n pu, pv = self.find_parent(u), self.find_parent(v)\n self.parent[pu] = pv\n\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n def cmp(a, b):\n return a[2] < b[2]\n \n critical, pseudo_critical = [], []\n \n for i in range(len(edges)):\n edges[i].append(i)\n \n edges.sort(key=lambda x: x[2])\n \n mst_wt = self.find_mst(n, edges, -1, -1)\n \n for i in range(len(edges)):\n if mst_wt < self.find_mst(n, edges, i, -1):\n critical.append(edges[i][3])\n elif mst_wt == self.find_mst(n, edges, -1, i):\n pseudo_critical.append(edges[i][3])\n \n return [critical, pseudo_critical]\n \n def find_mst(self, n, edges, block, e):\n uf = UnionFind(n)\n weight = 0\n \n if e != -1:\n weight += edges[e][2]\n uf.union(edges[e][0], edges[e][1])\n \n for i in range(len(edges)):\n if i == block:\n continue\n if uf.find_parent(edges[i][0]) == uf.find_parent(edges[i][1]):\n continue\n uf.union(edges[i][0], edges[i][1])\n weight += edges[i][2]\n \n for i in range(n):\n if uf.find_parent(i) != uf.find_parent(0):\n return float(\'inf\')\n \n return weight\n```\n```C# []\npublic class Solution {\n public class Edge{\n public int id{get;set;}\n public int from{get;set;}\n public int to{get;set;}\n public int cost{get;set;}\n }\n class DSU{\n int[] par, sz;\n public int componentCount;\n public DSU(int n){\n par = new int[n];\n componentCount = n;\n sz = new int[n];\n for(int i = 0; i < n;i++){\n par[i] = i;\n sz[i] = 1;\n }\n }\n public int FindParent(int u){\n if(par[u] == u) return u;\n int p = FindParent(par[u]);\n par[u] = p;\n return p;\n }\n public bool IsSameComponent(int u , int v) => FindParent(u) == FindParent(v);\n public void Join(int u,int v){\n u = FindParent(u);\n v = FindParent(v);\n if(u == v) return;\n if(sz[u] < sz[v]) (u,v) = (v,u);\n par[v] = u;\n sz[u]+=sz[v];\n componentCount--;\n }\n }\n int kruskal(PriorityQueue<Edge,int> edges, int nodes,Edge taken = null){\n int res = 0;\n DSU dsu = new DSU(nodes);\n if(taken != null){\n dsu.Join(taken.from, taken.to);\n res += taken.cost;\n }\n while(dsu.componentCount > 1 && edges.Count > 0){\n var e = edges.Dequeue();\n if(dsu.IsSameComponent(e.from, e.to)) continue;\n dsu.Join(e.from, e.to);\n res += e.cost;\n }\n if(dsu.componentCount > 1) return Int32.MaxValue;\n return res;\n }\n public PriorityQueue<Edge,int> GetEdges(int[][] edges,int skipedIdx = -1){\n PriorityQueue<Edge,int> edgesPq = new(Comparer<int>.Create((a, b) => a.CompareTo(b)));\n for(int i = 0;i < edges.Length;i++){\n if(i == skipedIdx) continue;\n edgesPq.Enqueue(new Edge{id = i,from = edges[i][0], to = edges[i][1],cost = edges[i][2]},edges[i][2]);\n }\n return edgesPq;\n }\n public IList<IList<int>> FindCriticalAndPseudoCriticalEdges(int n, int[][] edges) {\n int mstCost = kruskal(GetEdges(edges),n);\n List<IList<int>> res = new List<IList<int>>(){new List<int>(),new List<int>()};\n for(int i = 0; i < edges.Length;i++){\n int curCost = kruskal(GetEdges(edges,i),n);\n if(curCost > mstCost) res[0].Add(i);\n else{\n Edge taken = new Edge{id = i,from = edges[i][0], to = edges[i][1],cost = edges[i][2]};\n curCost = kruskal(GetEdges(edges),n,taken);\n if(curCost == mstCost)res[1].Add(i);\n } \n }\n return res;\n }\n}\n\n```\n```Javascript []\nclass UnionFind {\n constructor(n) {\n this.parents = [];\n for(let i = 0; i < n; i++) {\n this.parents.push(i);\n }\n this.count = n;\n }\n\n find(index) {\n const parent = this.parents[index];\n if(parent === index) return index;\n\n let root = this.find(parent);\n this.parents[index] = root;\n return root;\n }\n\n union(index1, index2) {\n let p1 = this.find(index1);\n let p2 = this.find(index2);\n\n if(p1 !== p2) {\n this.count--;\n this.parents[p1] = p2;\n return true;\n }\n\n return false;\n }\n}\n\nvar findCriticalAndPseudoCriticalEdges = function(n, edges) {\n let criticalEdges = [], psuedoCriticalEdges = [], map = new Map();\n \n edges.forEach((edge, i) => map.set(edge, i));\n \n edges.sort((a, b) => a[2] - b[2]);\n \n const buildMST = (pick, skip) => {\n let uf = new UnionFind(n), cost = 0;\n \n if(pick !== null) {\n uf.union(pick[0], pick[1]);\n cost += pick[2];\n }\n \n for(let edge of edges) {\n if(edge !== skip && uf.union(edge[0], edge[1])) {\n cost += edge[2];\n }\n }\n \n return uf.count === 1 ? cost : Number.MAX_SAFE_INTEGER;\n };\n \n const minCost = buildMST(null, null);\n \n for(let edge of edges) {\n const index = map.get(edge);\n const costWithout = buildMST(null, edge);\n if(costWithout > minCost) {\n criticalEdges.push(index);\n } else {\n const costWith = buildMST(edge, null);\n if(costWith === minCost) psuedoCriticalEdges.push(index);\n }\n }\n \n return [criticalEdges, psuedoCriticalEdges];\n};\n```\n```Kotlin []\nimport kotlin.math.*\nimport kotlin.comparisons.*\n\nclass Solution {\n data class Edge(\n val node1: Int,\n val node2: Int,\n val weight: Int,\n val number: Int\n )\n \n class UnionFind(val size: Int) {\n private val content: Array<Pair<Int, Int>> = Array(size) { it to 1 }\n \n fun union(first: Int, second: Int) {\n val firstRoot: Pair<Int, Int> = root(first)\n val secondRoot: Pair<Int, Int> = root(second)\n \n if (firstRoot.first != secondRoot.first) {\n // probably due to old kotlin version, this should work with lamda\n var higher: Pair<Int, Int> = maxOf(firstRoot, secondRoot, object: Comparator<Pair<Int, Int>> {\n override fun compare(firstPair: Pair<Int, Int>, secondPair: Pair<Int, Int>): Int {\n return firstPair.second - secondPair.second\n }\n })\n \n higher = Pair(higher.first, higher.second + min(firstRoot.second, secondRoot.second))\n \n content[firstRoot.first] = higher\n content[secondRoot.first] = higher\n }\n }\n \n fun connected(first: Int, second: Int): Boolean {\n return root(first).first == root(second).first\n }\n \n fun root(node: Int): Pair<Int, Int> {\n var cur = node\n \n while (content[cur].first != cur) {\n content[cur] = content[content[cur].first]\n cur = content[cur].first\n }\n \n return content[cur]\n }\n }\n \n fun findCriticalAndPseudoCriticalEdges(n: Int, edges: Array<IntArray>): List<List<Int>> {\n val critical: MutableList<Int> = mutableListOf()\n val pseudo: MutableList<Int> = mutableListOf()\n \n val sortedEdges = edges.asSequence()\n .mapIndexed { index, edge -> \n Edge(edge[0], edge[1], edge[2], index) \n }\n .sortedBy { it.weight }\n .toList()\n \n val minWeight = findMSTWeight(n, sortedEdges)\n for (edge in sortedEdges) { \n if (findMSTWeight(n, sortedEdges, blocked = edge) != minWeight) {\n critical.add(edge.number)\n } else if (findMSTWeight(n, sortedEdges, peeked = edge) == minWeight) {\n pseudo.add(edge.number)\n }\n }\n \n return listOf(critical, pseudo)\n }\n \n fun findMSTWeight(n: Int, edges: List<Edge>, blocked: Edge? = null, peeked: Edge? = null): Int {\n val union = UnionFind(n)\n var weight = 0;\n \n peeked?.let { \n union.union(it.node1, it.node2)\n weight += it.weight\n }\n \n for (edge in edges) {\n if (blocked?.number != edge.number && !union.connected(edge.node1, edge.node2)) {\n union.union(edge.node1, edge.node2)\n weight += edge.weight\n }\n }\n \n return weight\n }\n}\n```\n\n\n---\n\n\n--- | 68 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
Quick Easy Approach | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | \n\n# Code\n```\nclass UnionFindSet:\n def __init__(self, n=0):\n self.parents = {}\n self.ranks = {}\n self.count = 0\n for i in range(n):\n self.add(i)\n\n def add(self, p):\n self.parents[p] = p\n self.ranks[p] = 1\n self.count += 1\n\n def find(self, u):\n if u != self.parents[u]:\n self.parents[u] = self.find(self.parents[u])\n return self.parents[u]\n\n def union(self, u, v):\n pu, pv = self.find(u), self.find(v)\n if pu == pv: \n return False\n if self.ranks[pu] < self.ranks[pv]:\n self.parents[pu] = pv\n elif self.ranks[pu] > self.ranks[pv]:\n self.parents[pv] = pu\n else: \n self.parents[pv] = pu\n self.ranks[pu] += 1\n self.count -= 1\n return True\n \n# UnionFind + Kruskal + Enumerate edges\n# O(ElogE + E^2 + E^2)\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n # sort edges in asc order based on weight\n edges = [(u, v, w, i) for i, (u, v, w) in enumerate(edges)]\n edges.sort(key=lambda x: x[2])\n \n # do not use this edge\n def find_mst_without_this_edge(edge_idx):\n union_find_set = UnionFindSet(n)\n ans = 0\n for i, (u, v, w, _) in enumerate(edges):\n # do not use this edge\n if i == edge_idx:\n continue\n if union_find_set.union(u, v):\n ans += w\n parent = union_find_set.find(0)\n return ans if all(union_find_set.find(i) == parent for i in range(n)) else inf\n \n # need to use this edge\n def find_mst_with_this_edge(edge_idx):\n union_find_set = UnionFindSet(n)\n # use this edge first\n u0, v0, w0, _ = edges[edge_idx]\n ans = w0\n union_find_set.union(u0, v0)\n for i, (u, v, w, _) in enumerate(edges):\n # do not use this edge\n if i == edge_idx:\n continue\n if union_find_set.union(u, v):\n ans += w\n parent = union_find_set.find(0)\n return ans if all(union_find_set.find(i) == parent for i in range(n)) else inf\n \n # normal MST total weight\n base = find_mst_without_this_edge(-1)\n cri, p_cri = set(), set()\n for i in range(len(edges)):\n wgt_excl = find_mst_without_this_edge(i)\n # if not included, MST total weight would increase\n if wgt_excl > base:\n cri.add(edges[i][3])\n else:\n wgt_incl = find_mst_with_this_edge(i)\n # with this edge, MST total weight doesn\'t change\n if wgt_incl == base:\n p_cri.add(edges[i][3])\n \n return [cri, p_cri]\n``` | 15 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
✅ 100% - O(ElogE) Kruskal's Algorithm and DFS | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 0 | 1 | # Problem Understanding\n\nIn the problem "1489. Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree," we are presented with a weighted undirected connected graph consisting of `n` vertices, numbered from 0 to `n - 1`. The graph is described by an array `edges`, where each element `edges[i] = [ai, bi, weighti]` represents a bidirectional edge with a weight between nodes `ai` and `bi`. The primary objective is to identify and categorize edges within the minimum spanning tree (MST) of the graph.\n\n**The Task**\n\nOur task is twofold:\n\n1. **Critical Edges**: We need to identify the critical edges within the MST. A critical edge is an edge present in the MST such that removing it from the graph would lead to an increase in the overall weight of the MST.\n\n2. **Pseudo-Critical Edges**: Additionally, we aim to pinpoint pseudo-critical edges. A pseudo-critical edge is an edge that may appear in some of the MSTs but not necessarily in all of them.\n\nIn essence, our goal is to dissect the graph\'s MST and classify edges into these two categories: critical and pseudo-critical. By addressing this problem, we gain insights into the intricacies of graph theory and optimization, as well as the significance of edge classifications within minimum spanning trees. This exercise enhances our understanding of these fundamental graph concepts and their application to real-world scenarios.\n\n---\n\n# Live Coding:\nhttps://youtu.be/wkCHl9tpoyQ\n\n# Approach: Kruskal\'s Algorithm and DFS\n\nWe\'re tasked with finding both critical and pseudo-critical edges in a Minimum Spanning Tree (MST) of a given graph. To accomplish this, we employ a blend of two well-known algorithms:\n- **Kruskal\'s Algorithm** to determine the MST.\n- **Depth-First Search (DFS)** to traverse and inspect the MST for edge classifications.\n\n## Key Components\n\n1. **Union-Find Structure**: A classic data structure to manage sets or components. It facilitates checking whether two nodes are in the same component and joining two components.\n2. **Adjacency List**: A way of representing our graph, making it easier to traverse and inspect its edges and nodes.\n\n## Approach Steps\n\n### 1. Set the Stage:\n - Introduce the **Union-Find** data structure to help us decide if an edge can be safely added to the MST without forming a cycle.\n - Create an **Adjacency List** to represent our graph\'s structure and relationships.\n\n### 2. Construct the MST:\n - Begin by arranging the edges based on their weights, ensuring we always consider the smallest edge first.\n - Proceed through these edges, and if adding an edge doesn\'t form a cycle (verified using Union-Find), incorporate it into the MST.\n\n### 3. Traverse and Classify:\n - Use **DFS** to explore the MST. \n - As we traverse, we record the depth or "level" of each node.\n - Edges are then classified based on their significance to the structure and weight of the MST:\n - **Critical Edges**: Removing them results in a more massive MST.\n - **Pseudo-Critical Edges**: Edges that can be part of some MSTs but aren\'t mandatory for the minimum weight.\n\n### 4. Conclude:\n - Once all edges have been inspected and classified, present them in two separate lists: one for critical edges and another for pseudo-critical ones.\n\n## Complexity Insights\n\n- **Time Complexity**: Two aspects majorly influence our solution\'s speed:\n - **Sorting the edges**, costing $$O(E \\log E)$$ where $$E$$ is the number of edges.\n - **Union-Find operations**, taking $$O(E \\alpha(V))$$, where $$\\alpha(V)$$ is the inverse Ackermann function. This function grows very slowly, making this part almost linear in terms of time complexity.\n In essence, our algorithm roughly runs in $$O(E \\log E)$$.\n\n- **Space Complexity**: Our primary memory consumption sources are:\n - Storing the graph\'s edges and nodes.\n - The Union-Find and adjacency list structures.\n As a result, our space needs are roughly $$O(E + V)$$, where $$E$$ is the number of edges, and $$V$$ is the number of vertices.\n\n---\n\nIn a nutshell, our approach combines classical graph algorithms and data structures to effectively classify edges in an MST, offering valuable insights into the graph\'s structure and relationships.\n\n---\n\n# Performance:\n\n| Language | Runtime | Runtime Beats (%) | Memory | Memory Beats (%) |\n|-----------|-----------|-------------------|----------|------------------|\n| Python3 | 72 ms | 100% | 16.7 MB | 40.66% |\n\n\n\n---\n\n# Code\n``` Python []\n# Step 1: Union-Find Data Structure\nclass UnionFind:\n def __init__(self, n):\n self.parent = list(range(n))\n self.rank = [0] * n\n\n def find(self, x):\n if self.parent[x] != x:\n self.parent[x] = self.find(self.parent[x])\n return self.parent[x]\n\n def union(self, x, y):\n rootX, rootY = self.find(x), self.find(y)\n if rootX == rootY:\n return False\n if self.rank[rootX] > self.rank[rootY]:\n self.parent[rootY] = rootX\n else:\n self.parent[rootX] = rootY\n if self.rank[rootX] == self.rank[rootY]:\n self.rank[rootY] += 1\n return True\n\n# Step 2: Main Solution\nclass Solution:\n # Main Method\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: [[int]]) -> [[int]]:\n \n # Step 3: Depth-First Search (DFS) Helper Function\n def dfs(node, depth, ancestor):\n levels[node] = depth\n for neighbor, edge_index in adjacency_list[node]:\n if neighbor == ancestor:\n continue\n if levels[neighbor] == -1:\n levels[node] = min(levels[node], dfs(neighbor, depth + 1, node))\n else:\n levels[node] = min(levels[node], levels[neighbor])\n if levels[neighbor] >= depth + 1 and edge_index not in pseudo_critical:\n critical.add(edge_index)\n return levels[node]\n\n # Step 4: Initialize Sets\n critical, pseudo_critical = set(), set()\n\n # Step 5: Grouping Edges By Weight\n weight_to_edges = {w: [] for w in {edge[2] for edge in edges}}\n for i, (u, v, w) in enumerate(edges):\n weight_to_edges[w].append([u, v, i])\n \n # Step 6: Using Union-Find\n union_find = UnionFind(n)\n \n # Step 7: Iterating Through Weights\n for weight in sorted(weight_to_edges):\n edge_lookup = defaultdict(set)\n \n for u, v, edge_index in weight_to_edges[weight]:\n rootU, rootV = union_find.find(u), union_find.find(v)\n \n if rootU != rootV:\n union_pair = tuple(sorted((rootU, rootV)))\n edge_lookup[union_pair].add(edge_index)\n \n mst_edges, adjacency_list = [], defaultdict(list)\n \n for (rootU, rootV), edge_indexes in edge_lookup.items():\n if len(edge_indexes) > 1:\n pseudo_critical.update(edge_indexes)\n \n edge_idx = edge_indexes.pop()\n adjacency_list[rootU].append((rootV, edge_idx))\n adjacency_list[rootV].append((rootU, edge_idx))\n mst_edges.append((rootU, rootV, edge_idx))\n union_find.union(rootU, rootV)\n \n levels = [-1] * n\n \n for u, v, _ in mst_edges:\n if levels[u] == -1:\n dfs(u, 0, -1)\n \n for _, _, edge_index in mst_edges:\n if edge_index not in critical:\n pseudo_critical.add(edge_index)\n\n # Step 8: Return Result\n return [list(critical), list(pseudo_critical)]\n```\n\nThis problem beautifully showcases the application of Kruskal\'s algorithm and depth-first search (DFS) to identify critical and pseudo-critical edges in a minimum spanning tree. Solving this problem provides a deep understanding of these graph algorithms and their practical use in real-world scenarios. \uD83D\uDCA1\uD83C\uDF20\uD83D\uDC69\u200D\uD83D\uDCBB\uD83D\uDC68\u200D\uD83D\uDCBB | 23 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
🔥Easy Solution 🔥Python3/C/C#/C++/Java🔥Use MST algorihtm🔥With 🗺️Image🗺️ | find-critical-and-pseudo-critical-edges-in-minimum-spanning-tree | 1 | 1 | # Intuition\nTo your preferred programming language\nyou can turn.\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 UnionFind:\n def __init__ (self, n):\n self.parents = list(range(n))\n self.weight = 0\n self.edgeCount = 0\n\n def find(self, x):\n if x != self.parents[x]:\n self.parents[x] = self.find(self.parents[x])\n return self.parents[x]\n\n def union(self, x, y, w):\n r1 = self.find(x)\n r2 = self.find(y)\n\n if r1 != r2:\n self.parents[r2] = r1\n self.weight += w\n self.edgeCount += 1\n\nclass Solution:\n def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]:\n\n edges = [(w,a,b,i) for i, (a,b,w) in enumerate(edges)]\n edges.sort()\n\n uf1 = UnionFind(n)\n for w, a, b, _ in edges:\n uf1.union(a, b, w)\n\n\n minWeight = uf1.weight\n\n\n ce = []\n pce = []\n m = len(edges)\n\n\n for i in range(m):\n uf2 = UnionFind(n)\n for j in range(m):\n if i == j:\n continue\n w,a,b,_ = edges[j]\n uf2.union(a,b,w)\n \n if uf2.weight > minWeight or uf2.edgeCount < n-1:\n ce.append(edges[i][3])\n\n else:\n \n uf3 = UnionFind(n)\n w,a,b,_ = edges[i]\n uf3.union(a,b,w)\n for j in range(m):\n w,a,b,_ = edges[j]\n uf3.union(a,b,w)\n \n if uf3.weight == minWeight:\n pce.append(edges[i][3])\n return ce, pce\n``` | 9 | Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**. | By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it. |
Dynamic average calculation (to avoid overflow) | average-salary-excluding-the-minimum-and-maximum-salary | 0 | 1 | This approach works for the case when all the values are positive and array may contain values till $$10^9$$. In this case a simple summation will overflow.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n##### **Dynamic average calculation**\nCase 1: Element Incoming\n```\nnew_avg = avg + (element - avg)/(no. of elements after incoming)\n```\nCase 2: Element Outgoing\n```\nnew_avg = avg + (avg - element)/(no. of element after outgoing)\n```\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def average(self, salary: List[int]) -> float:\n avg,mn,mx,n = 0,salary[0],salary[0],len(salary)\n\n for i,sal in enumerate(salary):\n avg += (sal - avg)/(i+1)\n mn = min(mn,sal)\n mx = max(mx,sal)\n\n # print(avg)\n avg += (avg - mx)/(n-1)\n avg += (avg - mn)/(n-2)\n return avg\n``` | 1 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Output:** 2500.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
**Example 2:**
**Input:** salary = \[1000,2000,3000\]
**Output:** 2000.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
**Constraints:**
* `3 <= salary.length <= 100`
* `1000 <= salary[i] <= 106`
* All the integers of `salary` are **unique**. | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Dynamic average calculation (to avoid overflow) | average-salary-excluding-the-minimum-and-maximum-salary | 0 | 1 | This approach works for the case when all the values are positive and array may contain values till $$10^9$$. In this case a simple summation will overflow.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n##### **Dynamic average calculation**\nCase 1: Element Incoming\n```\nnew_avg = avg + (element - avg)/(no. of elements after incoming)\n```\nCase 2: Element Outgoing\n```\nnew_avg = avg + (avg - element)/(no. of element after outgoing)\n```\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def average(self, salary: List[int]) -> float:\n avg,mn,mx,n = 0,salary[0],salary[0],len(salary)\n\n for i,sal in enumerate(salary):\n avg += (sal - avg)/(i+1)\n mn = min(mn,sal)\n mx = max(mx,sal)\n\n # print(avg)\n avg += (avg - mx)/(n-1)\n avg += (avg - mn)/(n-2)\n return avg\n``` | 1 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the minimum cost to make all points connected._ All points are connected if there is **exactly one** simple path between any two points.
**Example 1:**
**Input:** points = \[\[0,0\],\[2,2\],\[3,10\],\[5,2\],\[7,0\]\]
**Output:** 20
**Explanation:**
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
**Example 2:**
**Input:** points = \[\[3,12\],\[-2,5\],\[-4,1\]\]
**Output:** 18
**Constraints:**
* `1 <= points.length <= 1000`
* `-106 <= xi, yi <= 106`
* All pairs `(xi, yi)` are distinct. | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Simple Python3 & Java Solution|| Upto 100% faster || O(n) | average-salary-excluding-the-minimum-and-maximum-salary | 1 | 1 | # Intuition\nWe first initializes two variables, max_sal and min_sal, to 0 and 100000 respectively. \nIt then loops over each element i in the input array salary and updates max_sal and min_sal if i is greater than max_sal or less than min_sal, respectively.\n\nThen sum minus max & min values and averge of the sum of salary.\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n# Code\n```python []\nclass Solution:\n def average(self, salary: List[int]) -> float:\n s = 0\n min_sal = 1000000\n max_sal = 0\n n= 0\n\n for i in salary:\n n+= 1\n s += i\n if min_sal>i:\n min_sal = i\n if max_sal< i:\n max_sal = i\n \n return (s-min_sal-max_sal)/(n-2)\n\n```\n\n```java []\nclass Solution {\n public double average(int[] salary) {\n int max_sal = 0;\n int min_sal = 100000;\n int sum = 0;\n for (int i : salary){\n if (i> max_sal){\n max_sal = i;\n }\n if (i<min_sal){\n min_sal = i;\n }\n sum += i;\n }\n return (double)(sum -min_sal-max_sal)/(salary.length - 2);\n }\n}\n```\n | 1 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Output:** 2500.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
**Example 2:**
**Input:** salary = \[1000,2000,3000\]
**Output:** 2000.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
**Constraints:**
* `3 <= salary.length <= 100`
* `1000 <= salary[i] <= 106`
* All the integers of `salary` are **unique**. | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Simple Python3 & Java Solution|| Upto 100% faster || O(n) | average-salary-excluding-the-minimum-and-maximum-salary | 1 | 1 | # Intuition\nWe first initializes two variables, max_sal and min_sal, to 0 and 100000 respectively. \nIt then loops over each element i in the input array salary and updates max_sal and min_sal if i is greater than max_sal or less than min_sal, respectively.\n\nThen sum minus max & min values and averge of the sum of salary.\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n# Code\n```python []\nclass Solution:\n def average(self, salary: List[int]) -> float:\n s = 0\n min_sal = 1000000\n max_sal = 0\n n= 0\n\n for i in salary:\n n+= 1\n s += i\n if min_sal>i:\n min_sal = i\n if max_sal< i:\n max_sal = i\n \n return (s-min_sal-max_sal)/(n-2)\n\n```\n\n```java []\nclass Solution {\n public double average(int[] salary) {\n int max_sal = 0;\n int min_sal = 100000;\n int sum = 0;\n for (int i : salary){\n if (i> max_sal){\n max_sal = i;\n }\n if (i<min_sal){\n min_sal = i;\n }\n sum += i;\n }\n return (double)(sum -min_sal-max_sal)/(salary.length - 2);\n }\n}\n```\n | 1 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the minimum cost to make all points connected._ All points are connected if there is **exactly one** simple path between any two points.
**Example 1:**
**Input:** points = \[\[0,0\],\[2,2\],\[3,10\],\[5,2\],\[7,0\]\]
**Output:** 20
**Explanation:**
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
**Example 2:**
**Input:** points = \[\[3,12\],\[-2,5\],\[-4,1\]\]
**Output:** 18
**Constraints:**
* `1 <= points.length <= 1000`
* `-106 <= xi, yi <= 106`
* All pairs `(xi, yi)` are distinct. | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Non_optimised.py | average-salary-excluding-the-minimum-and-maximum-salary | 0 | 1 | # Code\n```\nclass Solution:\n def average(self, salary: List[int]) -> float:\n salary.sort()\n ans=sum(salary)\n ans-=salary[0]\n ans-=salary[len(salary)-1]\n return ans/(len(salary)-2)\n``` | 1 | You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee.
Return _the average salary of employees excluding the minimum and maximum salary_. Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** salary = \[4000,3000,1000,2000\]
**Output:** 2500.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 4000 respectively.
Average salary excluding minimum and maximum salary is (2000+3000) / 2 = 2500
**Example 2:**
**Input:** salary = \[1000,2000,3000\]
**Output:** 2000.00000
**Explanation:** Minimum salary and maximum salary are 1000 and 3000 respectively.
Average salary excluding minimum and maximum salary is (2000) / 1 = 2000
**Constraints:**
* `3 <= salary.length <= 100`
* `1000 <= salary[i] <= 106`
* All the integers of `salary` are **unique**. | If in the step x all bulb shines then bulbs 1,2,3,..,x should shines too. |
Non_optimised.py | average-salary-excluding-the-minimum-and-maximum-salary | 0 | 1 | # Code\n```\nclass Solution:\n def average(self, salary: List[int]) -> float:\n salary.sort()\n ans=sum(salary)\n ans-=salary[0]\n ans-=salary[len(salary)-1]\n return ans/(len(salary)-2)\n``` | 1 | You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the minimum cost to make all points connected._ All points are connected if there is **exactly one** simple path between any two points.
**Example 1:**
**Input:** points = \[\[0,0\],\[2,2\],\[3,10\],\[5,2\],\[7,0\]\]
**Output:** 20
**Explanation:**
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
**Example 2:**
**Input:** points = \[\[3,12\],\[-2,5\],\[-4,1\]\]
**Output:** 18
**Constraints:**
* `1 <= points.length <= 1000`
* `-106 <= xi, yi <= 106`
* All pairs `(xi, yi)` are distinct. | Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2. |
Easy solution in python | the-kth-factor-of-n | 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 kthFactor(self, n: int, k: int) -> int:\n idx = 0\n for i in range(1, n + 1):\n if n % i == 0:\n idx += 1\n if idx == k:\n return i\n return -1\n\n\n \n``` | 1 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12, k = 3
**Output:** 3
**Explanation:** Factors list is \[1, 2, 3, 4, 6, 12\], the 3rd factor is 3.
**Example 2:**
**Input:** n = 7, k = 2
**Output:** 7
**Explanation:** Factors list is \[1, 7\], the 2nd factor is 7.
**Example 3:**
**Input:** n = 4, k = 4
**Output:** -1
**Explanation:** Factors list is \[1, 2, 4\], there is only 3 factors. We should return -1.
**Constraints:**
* `1 <= k <= n <= 1000`
**Follow up:**
Could you solve this problem in less than O(n) complexity? | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
Easy solution in python | the-kth-factor-of-n | 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 kthFactor(self, n: int, k: int) -> int:\n idx = 0\n for i in range(1, n + 1):\n if n % i == 0:\n idx += 1\n if idx == k:\n return i\n return -1\n\n\n \n``` | 1 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` results in `"12344 "`.
Return `true` if _it is possible to transform `s` into `t`_. Otherwise, return `false`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "84532 ", t = "34852 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"84532 " (from index 2 to 3) -> "84352 "
"84352 " (from index 0 to 2) -> "34852 "
**Example 2:**
**Input:** s = "34521 ", t = "23415 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"34521 " -> "23451 "
"23451 " -> "23415 "
**Example 3:**
**Input:** s = "12345 ", t = "12435 "
**Output:** false
**Constraints:**
* `s.length == t.length`
* `1 <= s.length <= 105`
* `s` and `t` consist of only digits. | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
Beats 100% memory☺ | the-kth-factor-of-n | 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 kthFactor(self, n: int, k: int) -> int:\n factors=0\n for i in range(1,n+1):\n if n%i==0:\n factors+=1\n if factors==k:\n return i\n return -1\n``` | 2 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12, k = 3
**Output:** 3
**Explanation:** Factors list is \[1, 2, 3, 4, 6, 12\], the 3rd factor is 3.
**Example 2:**
**Input:** n = 7, k = 2
**Output:** 7
**Explanation:** Factors list is \[1, 7\], the 2nd factor is 7.
**Example 3:**
**Input:** n = 4, k = 4
**Output:** -1
**Explanation:** Factors list is \[1, 2, 4\], there is only 3 factors. We should return -1.
**Constraints:**
* `1 <= k <= n <= 1000`
**Follow up:**
Could you solve this problem in less than O(n) complexity? | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
Beats 100% memory☺ | the-kth-factor-of-n | 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 kthFactor(self, n: int, k: int) -> int:\n factors=0\n for i in range(1,n+1):\n if n%i==0:\n factors+=1\n if factors==k:\n return i\n return -1\n``` | 2 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` results in `"12344 "`.
Return `true` if _it is possible to transform `s` into `t`_. Otherwise, return `false`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "84532 ", t = "34852 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"84532 " (from index 2 to 3) -> "84352 "
"84352 " (from index 0 to 2) -> "34852 "
**Example 2:**
**Input:** s = "34521 ", t = "23415 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"34521 " -> "23451 "
"23451 " -> "23415 "
**Example 3:**
**Input:** s = "12345 ", t = "12435 "
**Output:** false
**Constraints:**
* `s.length == t.length`
* `1 <= s.length <= 105`
* `s` and `t` consist of only digits. | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
[Python] naive -> factor pairs -> jump to next pair 🤯 | the-kth-factor-of-n | 0 | 1 | # (1) checking every factor\n\nSimply check for every number from $$2$$ to $$n$$ if it is divisible by $$n$$ and push it to the stack.\n\n### Code\n```Python\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n factors=[1]\n for i in range(2,n+1):\n if n%i==0:\n factors.append(i)\n return -1 if k>len(factors) else factors[k-1]\n```\n- time complexity: $$O(n)$$\n- space complexity: $$O(\\sqrt{n})$$\n\n# (2) factor pairs\n\nIf we consider any factor $$i$$ of $$n$$ then we can easily see that $$n/i$$ is also a factor of $$n$$. We can make use of this in the iteration by storing both $$i$$ and $$n/i$$ in two separate stacks if $$i$$ is a factor. We only need to check up to $$\\sqrt{n}$$ because every factor we encounter bigger than that will have been saved already. The only edge case we have to consider is when $$n$$ is a square number. In this case $$\\sqrt{n}$$ will be its on pair and we have to remove it from one of the stacks.\n### Code\n```Python\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n smol, big = [], []\n for i in range(1, int(sqrt(n))+1):\n if n%i==0:\n smol.append(i)\n big.append(n//i)\n if smol[-1]==big[-1]: big.pop()\n factors=smol+big[::-1]\n return -1 if len(factors)<k else factors[k-1]\n```\n- time complexity: $$O(\\sqrt{n})$$\n- space complexity: $$O(\\sqrt{n})$$\n# (3) jump to the next pair \uD83E\uDD2F\nThis approach uses the same idea as in (2) with an extra trick. If we have a factor $$i_1$$ we already know that $$i_2=n/i_1$$ is a factor too. If we want to get the next potentially bigger factor $$i_1\'$$, we first have to consider the number $$m=n/(i_1+1)$$.\n$$m$$ differs from $$i_2$$ because it can\'t divide $$i_1$$.\nAlso, $$m$$ must be the corresponding factor of the next potentially bigger factor $$i_1\'$$ because$$i_1<i_1+1$$ Great! So now we do the step in reverse to get $$i_1\'=n/m$$ and check if $$i_1\'$$ is a factor. (in the code $$m$$ is replaced with $$n/(i+1)$$ for simplicity)\n\nIntuitively you can see that this will run in $$O(\\sqrt{n})$$ time because $$i=\\frac{n}{\\frac{n}{i+1}}$$ is symmetric among $$i=\\sqrt{n}$$.\n### Code\n```Python\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n i=1\n res=[i]\n while i<n:\n i=n//(n//(i+1))\n if n%i==0:\n res.append(i)\n return -1 if k>len(res) else res[k-1]\n```\n\n- time complexity: $$O(\\sqrt{n})$$\n- space complexity: $$O(\\sqrt{n})$$\n\n<b>Further practice:</b> Try to find an implementation in $$ O(1) $$ space!\n\nShoutout to this post (https://leetcode.com/problems/the-kth-factor-of-n/solutions/959365/python-o-sqrt-n-solution-explained/) for solution (2)\nShoutout to my dad for solution (3)\n | 1 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12, k = 3
**Output:** 3
**Explanation:** Factors list is \[1, 2, 3, 4, 6, 12\], the 3rd factor is 3.
**Example 2:**
**Input:** n = 7, k = 2
**Output:** 7
**Explanation:** Factors list is \[1, 7\], the 2nd factor is 7.
**Example 3:**
**Input:** n = 4, k = 4
**Output:** -1
**Explanation:** Factors list is \[1, 2, 4\], there is only 3 factors. We should return -1.
**Constraints:**
* `1 <= k <= n <= 1000`
**Follow up:**
Could you solve this problem in less than O(n) complexity? | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
[Python] naive -> factor pairs -> jump to next pair 🤯 | the-kth-factor-of-n | 0 | 1 | # (1) checking every factor\n\nSimply check for every number from $$2$$ to $$n$$ if it is divisible by $$n$$ and push it to the stack.\n\n### Code\n```Python\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n factors=[1]\n for i in range(2,n+1):\n if n%i==0:\n factors.append(i)\n return -1 if k>len(factors) else factors[k-1]\n```\n- time complexity: $$O(n)$$\n- space complexity: $$O(\\sqrt{n})$$\n\n# (2) factor pairs\n\nIf we consider any factor $$i$$ of $$n$$ then we can easily see that $$n/i$$ is also a factor of $$n$$. We can make use of this in the iteration by storing both $$i$$ and $$n/i$$ in two separate stacks if $$i$$ is a factor. We only need to check up to $$\\sqrt{n}$$ because every factor we encounter bigger than that will have been saved already. The only edge case we have to consider is when $$n$$ is a square number. In this case $$\\sqrt{n}$$ will be its on pair and we have to remove it from one of the stacks.\n### Code\n```Python\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n smol, big = [], []\n for i in range(1, int(sqrt(n))+1):\n if n%i==0:\n smol.append(i)\n big.append(n//i)\n if smol[-1]==big[-1]: big.pop()\n factors=smol+big[::-1]\n return -1 if len(factors)<k else factors[k-1]\n```\n- time complexity: $$O(\\sqrt{n})$$\n- space complexity: $$O(\\sqrt{n})$$\n# (3) jump to the next pair \uD83E\uDD2F\nThis approach uses the same idea as in (2) with an extra trick. If we have a factor $$i_1$$ we already know that $$i_2=n/i_1$$ is a factor too. If we want to get the next potentially bigger factor $$i_1\'$$, we first have to consider the number $$m=n/(i_1+1)$$.\n$$m$$ differs from $$i_2$$ because it can\'t divide $$i_1$$.\nAlso, $$m$$ must be the corresponding factor of the next potentially bigger factor $$i_1\'$$ because$$i_1<i_1+1$$ Great! So now we do the step in reverse to get $$i_1\'=n/m$$ and check if $$i_1\'$$ is a factor. (in the code $$m$$ is replaced with $$n/(i+1)$$ for simplicity)\n\nIntuitively you can see that this will run in $$O(\\sqrt{n})$$ time because $$i=\\frac{n}{\\frac{n}{i+1}}$$ is symmetric among $$i=\\sqrt{n}$$.\n### Code\n```Python\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n i=1\n res=[i]\n while i<n:\n i=n//(n//(i+1))\n if n%i==0:\n res.append(i)\n return -1 if k>len(res) else res[k-1]\n```\n\n- time complexity: $$O(\\sqrt{n})$$\n- space complexity: $$O(\\sqrt{n})$$\n\n<b>Further practice:</b> Try to find an implementation in $$ O(1) $$ space!\n\nShoutout to this post (https://leetcode.com/problems/the-kth-factor-of-n/solutions/959365/python-o-sqrt-n-solution-explained/) for solution (2)\nShoutout to my dad for solution (3)\n | 1 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` results in `"12344 "`.
Return `true` if _it is possible to transform `s` into `t`_. Otherwise, return `false`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "84532 ", t = "34852 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"84532 " (from index 2 to 3) -> "84352 "
"84352 " (from index 0 to 2) -> "34852 "
**Example 2:**
**Input:** s = "34521 ", t = "23415 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"34521 " -> "23451 "
"23451 " -> "23415 "
**Example 3:**
**Input:** s = "12345 ", t = "12435 "
**Output:** false
**Constraints:**
* `s.length == t.length`
* `1 <= s.length <= 105`
* `s` and `t` consist of only digits. | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
Python | O(sqrt(n)) with Explaination | top 95% | the-kth-factor-of-n | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe obtain O(sqrt(n)) time utilizing the fact that n divided by a factor obtains two factors. For example, 12 / 3 = 4, so we know both 3 and 4 are factors. Thus, we only need to check factors up until sqrt(n) because all other factors larger than sqrt(n) may be derived.\n\nTwo steps:\n 1. Iterate all integers up until sqrt(n). Everytime we find a factor, decrease k by 1. If k is zero, return the factor. \n 2. Decend from sqrt(n) back to 1. If sqrt(n) is an integer, we CANNOT double count sqrt(n). If we find a factor, we return (n / factor).\n\nBe sure not to double count sqrt(n). I use a \'continue\' statement to check for this. The tricky part about this problem is making sure your loop bounds are correct. \n\n# Complexity\n- Time complexity: O(sqrt(n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n # accending to sqrt(n)\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n k -= 1\n if k == 0: return i\n \n # decending to 0\n for i in range(int(n**0.5), 0, -1):\n if i**2 == n: continue\n if n % i == 0:\n k -= 1\n if k == 0: return n // i\n \n return -1\n``` | 4 | You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`.
Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors.
**Example 1:**
**Input:** n = 12, k = 3
**Output:** 3
**Explanation:** Factors list is \[1, 2, 3, 4, 6, 12\], the 3rd factor is 3.
**Example 2:**
**Input:** n = 7, k = 2
**Output:** 7
**Explanation:** Factors list is \[1, 7\], the 2nd factor is 7.
**Example 3:**
**Input:** n = 4, k = 4
**Output:** -1
**Explanation:** Factors list is \[1, 2, 4\], there is only 3 factors. We should return -1.
**Constraints:**
* `1 <= k <= n <= 1000`
**Follow up:**
Could you solve this problem in less than O(n) complexity? | The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed. |
Python | O(sqrt(n)) with Explaination | top 95% | the-kth-factor-of-n | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe obtain O(sqrt(n)) time utilizing the fact that n divided by a factor obtains two factors. For example, 12 / 3 = 4, so we know both 3 and 4 are factors. Thus, we only need to check factors up until sqrt(n) because all other factors larger than sqrt(n) may be derived.\n\nTwo steps:\n 1. Iterate all integers up until sqrt(n). Everytime we find a factor, decrease k by 1. If k is zero, return the factor. \n 2. Decend from sqrt(n) back to 1. If sqrt(n) is an integer, we CANNOT double count sqrt(n). If we find a factor, we return (n / factor).\n\nBe sure not to double count sqrt(n). I use a \'continue\' statement to check for this. The tricky part about this problem is making sure your loop bounds are correct. \n\n# Complexity\n- Time complexity: O(sqrt(n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def kthFactor(self, n: int, k: int) -> int:\n # accending to sqrt(n)\n for i in range(1, int(n**0.5) + 1):\n if n % i == 0:\n k -= 1\n if k == 0: return i\n \n # decending to 0\n for i in range(int(n**0.5), 0, -1):\n if i**2 == n: continue\n if n % i == 0:\n k -= 1\n if k == 0: return n // i\n \n return -1\n``` | 4 | Given two strings `s` and `t`, transform string `s` into string `t` using the following operation any number of times:
* Choose a **non-empty** substring in `s` and sort it in place so the characters are in **ascending order**.
* For example, applying the operation on the underlined substring in `"14234 "` results in `"12344 "`.
Return `true` if _it is possible to transform `s` into `t`_. Otherwise, return `false`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "84532 ", t = "34852 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"84532 " (from index 2 to 3) -> "84352 "
"84352 " (from index 0 to 2) -> "34852 "
**Example 2:**
**Input:** s = "34521 ", t = "23415 "
**Output:** true
**Explanation:** You can transform s into t using the following sort operations:
"34521 " -> "23451 "
"23451 " -> "23415 "
**Example 3:**
**Input:** s = "12345 ", t = "12435 "
**Output:** false
**Constraints:**
* `s.length == t.length`
* `1 <= s.length <= 105`
* `s` and `t` consist of only digits. | The factors of n will be always in the range [1, n]. Keep a list of all factors sorted. Loop i from 1 to n and add i if n % i == 0. Return the kth factor if it exist in this list. |
✅Beat's 100% || C++ || JAVA || PYTHON || Beginner Friendly🔥🔥🔥 | longest-subarray-of-1s-after-deleting-one-element | 1 | 1 | # Intuition:\nThe Intuition is to use a sliding window approach to find the length of the longest subarray of 1\'s after removing at most one element (0 or 1) from the original array. It adjusts the window to have at most one zero, calculates the subarray length, and returns the maximum length found.\n\n# Explanation:\n\n1. The code aims to find the length of the longest subarray consisting of only 1\'s after deleting at most one element (0 or 1) from the original array.\n2. The variable `left` represents the left pointer of the sliding window, which defines the subarray.\n3. The variable `zeros` keeps track of the number of zeroes encountered in the current subarray.\n4. The variable `ans` stores the maximum length of the subarray found so far.\n5. The code iterates over the array using the right pointer `right`.\n6. If `nums[right]` is 0, it means we encountered a zero in the array. We increment `zeros` by 1.\n7. The while loop is used to adjust the window by moving the left pointer `left` to the right until we have at most one zero in the subarray.\n8. If `nums[left]` is 0, it means we are excluding a zero from the subarray, so we decrement `zeros` by 1.\n9. We update the `left` pointer by moving it to the right.\n10. After adjusting the window, we calculate the length of the current subarray by subtracting the number of zeroes from the total length `right - left + 1`. We update `ans` if necessary.\n11. Finally, we check if the entire array is the longest subarray. If it is, we subtract 1 from the maximum length to account for the one element we are allowed to delete. We return the resulting length.\n\n# Complexity:\n**Time complexity**: $$ O(N) $$\n- Each element in the array will be iterated over twice at max. Each element will be iterated over for the first time in the for loop; then, it might be possible to re-iterate while shrinking the window in the while loop. No element can be iterated more than twice.\n\n**Space complexity**: $$ O(1) $$\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n\n int left = 0;\n int zeros = 0;\n int ans = 0;\n\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0) {\n zeros++;\n }\n while (zeros > 1) {\n if (nums[left] == 0) {\n zeros--;\n }\n left++;\n }\n ans = max(ans, right - left + 1 - zeros);\n }\n return (ans == n) ? ans - 1 : ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int longestSubarray(int[] nums) {\n int n = nums.length;\n\n int left = 0;\n int zeros = 0;\n int ans = 0;\n\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0) {\n zeros++;\n }\n while (zeros > 1) {\n if (nums[left] == 0) {\n zeros--;\n }\n left++;\n }\n ans = Math.max(ans, right - left + 1 - zeros);\n }\n return (ans == n) ? ans - 1 : ans;\n }\n}\n```\n```Python3 []\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums)\n\n left = 0\n zeros = 0\n ans = 0\n\n for right in range(n):\n if nums[right] == 0:\n zeros += 1\n\n while zeros > 1:\n if nums[left] == 0:\n zeros -= 1\n left += 1\n\n ans = max(ans, right - left + 1 - zeros)\n\n return ans - 1 if ans == n else ans\n```\n\n# Code With Comments\n```C++ []\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size(); // The size of the input array\n\n int left = 0; // The left pointer of the sliding window\n int zeros = 0; // Number of zeroes encountered\n int ans = 0; // Maximum length of the subarray\n\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0) {\n zeros++; // Increment the count of zeroes\n }\n\n // Adjust the window to maintain at most one zero in the subarray\n while (zeros > 1) {\n if (nums[left] == 0) {\n zeros--; // Decrement the count of zeroes\n }\n left++; // Move the left pointer to the right\n }\n\n // Calculate the length of the current subarray and update the maximum length\n ans = max(ans, right - left + 1 - zeros);\n }\n\n // If the entire array is the subarray, return the size minus one; otherwise, return the maximum length\n return (ans == n) ? ans - 1 : ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int longestSubarray(int[] nums) {\n int n = nums.length; // The size of the input array\n\n int left = 0; // The left pointer of the sliding window\n int zeros = 0; // Number of zeroes encountered\n int ans = 0; // Maximum length of the subarray\n\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0) {\n zeros++; // Increment the count of zeroes\n }\n\n // Adjust the window to maintain at most one zero in the subarray\n while (zeros > 1) {\n if (nums[left] == 0) {\n zeros--; // Decrement the count of zeroes\n }\n left++; // Move the left pointer to the right\n }\n\n // Calculate the length of the current subarray and update the maximum length\n ans = Math.max(ans, right - left + 1 - zeros);\n }\n\n // If the entire array is the subarray, return the size minus one; otherwise, return the maximum length\n return (ans == n) ? ans - 1 : ans;\n }\n}\n```\n```Python3 []\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums) # The size of the input array\n\n left = 0 # The left pointer of the sliding window\n zeros = 0 # Number of zeroes encountered\n ans = 0 # Maximum length of the subarray\n\n for right in range(n):\n if nums[right] == 0:\n zeros += 1 # Increment the count of zeroes\n\n # Adjust the window to maintain at most one zero in the subarray\n while zeros > 1:\n if nums[left] == 0:\n zeros -= 1 # Decrement the count of zeroes\n left += 1 # Move the left pointer to the right\n\n # Calculate the length of the current subarray and update the maximum length\n ans = max(ans, right - left + 1 - zeros)\n\n # If the entire array is the subarray, return the size minus one; otherwise, return the maximum length\n return ans - 1 if ans == n else ans\n```\n\n\n\n\n**If you found my solution helpful, I would greatly appreciate your upvote, as it would motivate me to continue sharing more solutions.** | 217 | Given a binary array `nums`, you should delete one element from it.
Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray.
**Example 1:**
**Input:** nums = \[1,1,0,1\]
**Output:** 3
**Explanation:** After deleting the number in position 2, \[1,1,1\] contains 3 numbers with value of 1's.
**Example 2:**
**Input:** nums = \[0,1,1,1,0,1,1,0,1\]
**Output:** 5
**Explanation:** After deleting the number in position 4, \[0,1,1,1,1,1,0,1\] longest subarray with value of 1's is \[1,1,1,1,1\].
**Example 3:**
**Input:** nums = \[1,1,1\]
**Output:** 2
**Explanation:** You must delete one element.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. |
Binary Search + Sliding Window Solution | longest-subarray-of-1s-after-deleting-one-element | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs we have to maximize the answer and we know the minimum and maximum possible answer and this is a sub array problem, so why not think of a binary search and sliding window solution?\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe have guessed a solution using binary search and then checked the validity of the solution by doing a sliding window operation throughout the array\n\nbinary search:\n```\nlo = 0\nhi = len(nums)\n\nans = 0\n\nwhile lo<=hi:\n mid = (lo+hi)//2\n possible = self.find(nums,mid)\n if possible != -1:\n ans = max(ans,mid-1)\n lo=mid+1\n else:\n hi=mid-1\n```\n\nsliding window:\n\n```\ndef find(self,nums,guess):\n start = 0\n end = start + guess\n s = sum(nums[start:end])\n \n while end < len(nums):\n\n l = end - start\n if (l-s) <= 1:\n return True\n \n s-=nums[start]\n start+=1\n \n s+=nums[end]\n end+=1\n \n l = end - start\n if (l-s) <= 1:\n return True\n \n return False\n```\n\n\nLet\'s understand what is happening inside the sliding window operation\nwe are checking all possible substrings of len `guess` using sliding window \nduring checking we are ignoring if there is one 0 and we are also counting it as one as we can delete one item \n\n```\nif (l-s) <= 1:\n return True\n```\n\nfinally if an `guess` exists then as we always have to delete one item we are storing `guess-1`\n\n```\nans = max(ans,mid-1)\n\n```\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\n # def check(self)\n\n def find(self,nums,guess):\n start = 0\n end = start + guess\n s = sum(nums[start:end])\n \n while end < len(nums):\n\n l = end - start\n if (l-s) <= 1:\n return s\n \n s-=nums[start]\n start+=1\n \n s+=nums[end]\n end+=1\n \n l = end - start\n if (l-s) <= 1:\n return s\n \n return -1\n\n \n def longestSubarray(self, nums: List[int]) -> int:\n \n lo = 0\n hi = len(nums)\n\n ans = 0\n\n while lo<=hi:\n mid = (lo+hi)//2\n possible = self.find(nums,mid)\n if possible != -1:\n ans = max(ans,mid-1)\n lo=mid+1\n else:\n hi=mid-1\n\n return ans\n``` | 1 | Given a binary array `nums`, you should delete one element from it.
Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray.
**Example 1:**
**Input:** nums = \[1,1,0,1\]
**Output:** 3
**Explanation:** After deleting the number in position 2, \[1,1,1\] contains 3 numbers with value of 1's.
**Example 2:**
**Input:** nums = \[0,1,1,1,0,1,1,0,1\]
**Output:** 5
**Explanation:** After deleting the number in position 4, \[0,1,1,1,1,1,0,1\] longest subarray with value of 1's is \[1,1,1,1,1\].
**Example 3:**
**Input:** nums = \[1,1,1\]
**Output:** 2
**Explanation:** You must delete one element.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. |
Python short and clean. Functional programming. | longest-subarray-of-1s-after-deleting-one-element | 0 | 1 | # Approach\n1. For every element `x` in `nums`, calculate the length of streaks of `1s` upto `x` excluding itself.\n\n2. Select the streaks corresponding to `x == 0`, lets call it `streaks_at_0`. This acts as deleting the corresponding `x` and selecting the streaks of `1s` to the left of it.\n\n3. The longest possible `streak` of `1s` after removing a `0` is the maximum `pairwise` sum of `steaks_at_0`. This corresponds to merging 2 adjacent streaks of `1s` to form a longer streak.\n\n\nFor ex:\n```python\nnums = [1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1] 0 // Extra 0 at the end\nstreaks_of_1s = [0, 1, 0, 0, 1, 2, 3, 0, 1, 2, 0, 1]\nstreaks_at_0 = [ 1, 0, 3, 2, 1]\n\npairwise(...) = [(1, 0), (0, 3), (3, 2), (2, 1)]\npairwise_sum = [1, 3, 5, 3]\nmax_sum = 5 // Answer\n\n```\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```python\nclass Solution:\n def longestSubarray(self, nums: list[int]) -> int:\n streaks_of_1s = accumulate(nums, lambda a, x: (a + 1) * (x != 0), initial=0)\n streaks_at_0 = compress(streaks_of_1s, map(not_, chain(nums, (0,))))\n return max(starmap(add, pairwise(streaks_at_0)), default=len(nums) - 1)\n\n\n``` | 1 | Given a binary array `nums`, you should delete one element from it.
Return _the size of the longest non-empty subarray containing only_ `1`_'s in the resulting array_. Return `0` if there is no such subarray.
**Example 1:**
**Input:** nums = \[1,1,0,1\]
**Output:** 3
**Explanation:** After deleting the number in position 2, \[1,1,1\] contains 3 numbers with value of 1's.
**Example 2:**
**Input:** nums = \[0,1,1,1,0,1,1,0,1\]
**Output:** 5
**Explanation:** After deleting the number in position 4, \[0,1,1,1,1,1,0,1\] longest subarray with value of 1's is \[1,1,1,1,1\].
**Example 3:**
**Input:** nums = \[1,1,1\]
**Output:** 2
**Explanation:** You must delete one element.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`. | Use a variation of DFS with parameters 'curent_vertex' and 'current_time'. Update the probability considering to jump to one of the children vertices. |
Detailed Explanations + Diagrams + Annotated Code | parallel-courses-ii | 0 | 1 | ## 0. Preface\nThis is a *really* good problem. However, the solutions I found were either too complex or just did not make any sense. In this post, I\'ll attempt to explain everything from top to bottom.\n\n## 1. Understading the Problem\n**Given**:\n- There are courses from `1 to n`, both inclusive.\n- There are relations between the courses, given by a list of items: `[prev_course, next_course]`. This essentially means the following.\n\n\n\nThere\'s one last thing, that gives this problem all the flavour. The value `k` is given to you. This represents the maximum number of nodes, "courses", you can select at a given time instant, "sememter", in this problem.\n\n**Goal**:\nAs a college student, find the least numbers of semesters possible to complete all the courses ~~and escape the hell hole~~.\n\nNote how without the condition of `k`, this problem would just be a topological sorting problem.\n\n## 2. Examples\nI\'ll mention the examples mentioned in the question itself below, for the sake of completeness.\n\n**Example 1 (from question)**\n\n\n```\nInput: n = 4, dependencies = [[2,1],[3,1],[1,4]], k = 2\nOutput: 3 \nExplanation: The figure above represents the given graph.\nIn the first semester, you can take courses 2 and 3.\nIn the second semester, you can take course 1.\nIn the third semester, you can take course 4.\n```\n\n**Example 2 (from question)**\n\n```\nInput: n = 5, dependencies = [[2,1],[3,1],[4,1],[1,5]], k = 2\nOutput: 4 \nExplanation: The figure above represents the given graph.\nIn the first semester, you can take courses 2 and 3 only since you cannot take more than two per semester.\nIn the second semester, you can take course 4.\nIn the third semester, you can take course 1.\nIn the fourth semester, you can take course 5.\n```\n\n**Example 3 (from question)**\n```\nInput: n = 11, dependencies = [], k = 2\nOutput: 6\n```\n\n**Try it yourself**\nIn my opinion, all of the above are *sneaky* examples. I ended up wasting hours on a wrong solution, because I missed a test case like the one below. Try if you can find the most optimal solution for `k = 2`. (Quick note: labels are immaterial)\n\n\n\nTake a look at two such cases for this question.\n\n\nWhat\'s happening? Each semester\'s worth of courses are enclosed in green, and enumerated in order. What do you observe?\n- The selection of what you choose to be the first two (since `k = 2`) has a *drastic* impact on how you select the rest - and thus the answer. Think of it like the **butterfly effect**.\n- There is no way to tell who is what, and which particular combination is any good. We may not know anything till the very end.\n\n## 3. The Approach\n**Data Structures**\n1. We need to know the layout of the graph, who points to what. Let\'s keep a structure like `graph = {node: [children]}`\n2. We also need to encode the information of how may in-edges are there for each node. We store that in a list like: `in_degrees = [values]`. We keep the `in_degrees` and `graph` separate for implementation reasons.\n3. Implementation detail: the inputs are 1 indexed, we make everything 0-indexed for easier implementations.\n\n**Nodes**\nThere are two types of nodes:\n- There are nodes which have been already considered. Let\'s label them with `0`.\n- There are nodes which have not been taken yet. Let\'s label them with `1`.\n\nNote that even if a node is marked `1`, it *does not* mean its `in_degree[node]` is `0`. It only means it needs to be taken - either in the present or in the future. \n\nMoreover, labelling a node either `0` or `1` allows us to represent the status of the problem in a neat format. What we have done here is called **bit masking**. `mask = 10110` represents the nodes `1, 2, 4` are yet to be considered (aka the course is yet to be taken), and the rest have already been taken.\n\n**Recursion**\nWe know that decisions taken now can produce different results later on. This makes the recursive approach favourable. For each particular iteration, we consider **all** the possible **combinations** of the **currently available nodes** - `in_degree[node] == 0 and mask & 1 << node`. The second part is checking if the `node`th bit is set in `mask`.\n\n\n## 4. Annotated Code\n```\nfrom itertools import combinations # for picking k of n\nclass Solution:\n @lru_cache(None) # caching for faster lookups\n def recurse(self, mask, in_degrees):\n # if all the bits are 0, we have taken all the courses\n if not mask: return 0\n \n # all the nodes that *can* be taken now, following both the properties\n nodes = [i for i in range(self.n) if mask & 1 << i and in_degrees[i] == 0]\n \n ans = float(\'inf\')\n # enumerating all the possible combinations\n for k_nodes in combinations(nodes, min(self.k, len(nodes))):\n new_mask, new_in_degrees = mask, list(in_degrees)\n \n # updating what would happen to new_mask and new_in_degrees \n # if we considered the nodes in k_nodes\n for node in k_nodes:\n # since we know the bit is set, we un-set this bit, to mark it "considered"\n new_mask ^= 1 << node\n # updating each of the in-degrees, since the "parents" have been taken away\n for child in self.graph[node]:\n new_in_degrees[child] -= 1\n \n # the heart of recursion\n # note the +1!\n ans = min(ans, 1+self.recurse(new_mask, tuple(new_in_degrees)))\n return ans\n \n def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:\n # saving n and k for later use\n self.n = n\n self.k = k\n in_degrees = [0]*self.n\n # graph layout remains the same, although the in_degrees change. \n # This allows us to keep graph as self.graph \n # instead of passing it over and over.\n self.graph = defaultdict(list)\n for prev_course, next_course in relations:\n # remember, its 0-indexed now!\n in_degrees[next_course - 1] += 1\n self.graph[prev_course - 1].append(next_course - 1)\n \n # start with all the bits set\n return self.recurse((1 << self.n) - 1, tuple(in_degrees))\n```\n\n## 5. References\n- https://leetcode.com/problems/parallel-courses-ii/discuss/710229/Python-Short-DP-with-Binary-Masks-O(n2*2n)-explained\n- https://leetcode.com/problems/parallel-courses-ii/discuss/710229/Python-Short-DP-with-Binary-Masks-O(n2*2n)-explained/830096 < I took the code from this guy.\n\nAnyways, this wraps up the solution. If you found it helpful, upvote. More feedback or comments/criticisms? Let me know! | 115 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be taken before course `nextCoursei`. Also, you are given the integer `k`.
In one semester, you can take **at most** `k` courses as long as you have taken all the prerequisites in the **previous** semesters for the courses you are taking.
Return _the **minimum** number of semesters needed to take all courses_. The testcases will be generated such that it is possible to take every course.
**Example 1:**
**Input:** n = 4, relations = \[\[2,1\],\[3,1\],\[1,4\]\], k = 2
**Output:** 3
**Explanation:** The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
**Example 2:**
**Input:** n = 5, relations = \[\[2,1\],\[3,1\],\[4,1\],\[1,5\]\], k = 2
**Output:** 4
**Explanation:** The figure above represents the given graph.
In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.
In the second semester, you can take course 4.
In the third semester, you can take course 1.
In the fourth semester, you can take course 5.
**Constraints:**
* `1 <= n <= 15`
* `1 <= k <= n`
* `0 <= relations.length <= n * (n-1) / 2`
* `relations[i].length == 2`
* `1 <= prevCoursei, nextCoursei <= n`
* `prevCoursei != nextCoursei`
* All the pairs `[prevCoursei, nextCoursei]` are **unique**.
* The given graph is a directed acyclic graph. | null |
Python -- Hopefully a more readable solution, ~80% | parallel-courses-ii | 0 | 1 | \n<!-- Describe your first thoughts on how to solve this problem. -->\nHad to read and understand the approach by others to come up with this. Looks like FAANG is a pipe dream for me :(\n\nHopefully this share helps someone else in their journey :)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse bitmask to store possible states of courses taken. Use bitmask to store course requirements to compare against states to check for unlocked courses.\n\n# Complexity\n- Time complexity: O (n^2 * 2^n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O (2^n) ?\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom itertools import combinations\n\nclass Solution:\n def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:\n # store requirements as bits\n reqs = defaultdict(int)\n for pr, ne in relations:\n reqs[ne] |= 1 << pr\n \n memo = {}\n completeState = (1 << n + 1) - 1\n\n # O(2^n) possible states\n def getSems(state):\n if state == completeState: return 0\n if state in memo: return memo[state]\n\n # Add uncompleted and available courses by comparing\n # current state with course reqs using bitmask - O(n^2)\n nodes = []\n for i in range(1, n + 1):\n if (1 << i) & ~state and reqs[i] & state == reqs[i]:\n nodes.append(i)\n\n semsRes = float("inf")\n for chosen in combinations(nodes, min(k, len(nodes))):\n # Parse all possible combinations of available courses\n newState = state\n for c in chosen:\n newState |= (1 << c)\n semsRes = min(semsRes, 1 + getSems(newState))\n # Cache results from dfs\n memo[state] = semsRes\n return semsRes\n \n return getSems(1) # 1 because there is no course 0\n \n\n\n``` | 0 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be taken before course `nextCoursei`. Also, you are given the integer `k`.
In one semester, you can take **at most** `k` courses as long as you have taken all the prerequisites in the **previous** semesters for the courses you are taking.
Return _the **minimum** number of semesters needed to take all courses_. The testcases will be generated such that it is possible to take every course.
**Example 1:**
**Input:** n = 4, relations = \[\[2,1\],\[3,1\],\[1,4\]\], k = 2
**Output:** 3
**Explanation:** The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
**Example 2:**
**Input:** n = 5, relations = \[\[2,1\],\[3,1\],\[4,1\],\[1,5\]\], k = 2
**Output:** 4
**Explanation:** The figure above represents the given graph.
In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.
In the second semester, you can take course 4.
In the third semester, you can take course 1.
In the fourth semester, you can take course 5.
**Constraints:**
* `1 <= n <= 15`
* `1 <= k <= n`
* `0 <= relations.length <= n * (n-1) / 2`
* `relations[i].length == 2`
* `1 <= prevCoursei, nextCoursei <= n`
* `prevCoursei != nextCoursei`
* All the pairs `[prevCoursei, nextCoursei]` are **unique**.
* The given graph is a directed acyclic graph. | null |
Python3 clean and concise solution beating ~93% with dp and bitmask | parallel-courses-ii | 0 | 1 | DFS and BFS would fail without pruning or memoization as there are a lot of branches that share the same states. \n\nAs hinted, use \'seen\' which is a bitmask for coursed that are taken as the key in the dp that could be memoized. The other state marker would be the semesters it has taken so far. Seen would be of the magnitude 2^n and semesters would be somewhere like n / k, so I guess this be a O(2^n*n) solution.\n\nHelper function \'combination\' from python library helps a lot, thanks to the solution by @hxu10.\n\n**(seen ^ degree0[j]) & degree0[j] == 0**\n\nThis is the crucial condition in the loop that decides whether a course to be taken can be taken which need to be explained. Seen is the mask for all courses taken, degree0[j] is the prerequisite courses for course j. A course j can be taken when:\n\na. it doesn\'t require course i\nb. it requires course i and course i can be taken.\n\nThis would lead to a truth value table like:\n\ni j r\n1 1 1\n1 0 0\n0 0 1\n0 1 1\n\nSome calculations on the paper would show ~((i^j) & i) to work. \nSo (seen ^ degree0[j]) & degree0[j] == 0 would mean the course j and be taken.\n\n\n\n\n# Code\n```\nfrom itertools import combinations\nclass Solution:\n def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:\n if not relations:\n return ceil(n / k) // cheat cases when there is no dependencies at all\n degree0 = [0]*n\n for u,v in relations:\n degree0[v-1] += 1 << (u-1) // create the mask for the vth course, with the ith digit marked when needed\n @cache \n def dp(semesters, seen):\n if seen == 2**n -1:\n return semesters // exit where all courses are taken\n possiblesteps = []\n for j in range(n):\n if seen & (1<<j) == 0 and (seen ^ degree0[j]) & degree0[j] == 0: // condition 1 is simply \'course j has not been taken\'; condition 2 would require some explanation, see above\n possiblesteps.append(j)\n \n combs = list(combinations(possiblesteps,min(k,len(possiblesteps)))) // all combinations of at most k possible courses to be taken\n res = float(\'inf\')\n for seq in combs:\n newseen = seen\n for j in seq:\n newseen = newseen | (1<<j) // new mask\n res = min(res,dp(semesters+1,newseen))\n return res\n\n return dp(0,0)\n\n\n \n\n \n``` | 0 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be taken before course `nextCoursei`. Also, you are given the integer `k`.
In one semester, you can take **at most** `k` courses as long as you have taken all the prerequisites in the **previous** semesters for the courses you are taking.
Return _the **minimum** number of semesters needed to take all courses_. The testcases will be generated such that it is possible to take every course.
**Example 1:**
**Input:** n = 4, relations = \[\[2,1\],\[3,1\],\[1,4\]\], k = 2
**Output:** 3
**Explanation:** The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
**Example 2:**
**Input:** n = 5, relations = \[\[2,1\],\[3,1\],\[4,1\],\[1,5\]\], k = 2
**Output:** 4
**Explanation:** The figure above represents the given graph.
In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.
In the second semester, you can take course 4.
In the third semester, you can take course 1.
In the fourth semester, you can take course 5.
**Constraints:**
* `1 <= n <= 15`
* `1 <= k <= n`
* `0 <= relations.length <= n * (n-1) / 2`
* `relations[i].length == 2`
* `1 <= prevCoursei, nextCoursei <= n`
* `prevCoursei != nextCoursei`
* All the pairs `[prevCoursei, nextCoursei]` are **unique**.
* The given graph is a directed acyclic graph. | null |
SOLID Principles | Commented and Explained | Bellman Ford | parallel-courses-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo get the minimal semesters needed, we need a topological sorting approach. However, this question can never be well suited, as I\'ll point out below, so we are forced to try an exhaustive search methodology. However, some improvements can be made to reduce the space of search, which we take on in the approach section. \n\nTo start with, we have n courses that have some form of relation. We are guaranteed that there is a relation between all courses. However, what we are not gauranteed is the exact relationship between courses, and this proves to be this questions downfall. \n\nFrom a naive approach, we can simply take all prerequisites fisrt, and then take any courses for which we are already qualified once we have exhausted all prerequisites. This initially led me to a Kahn style method like in parallel courses one, where we would simply reduce the in degree of courses and add them when able. But in doing so, we avoid the fact that we cannot take courses concurrently and must take up to k every semester as we can. Because of this, Kahn does not quite fit, so we end up having to utilize Bellman Ford. \n\nAdditionally, the order of the courses is important overall, and each course id should have its own unique location in our search space. This leads to the idea of bit masking, where each course id is a sufficiently left shifted bit mask, leading to a specific binary key of value as we go through the semesters. \n\nFinally, to showcase how unsuited this problem is, assume we have courses with no post requisites, but that show up at differing times of prerequisite coverage. This means there is no way to determine exactly where and when best fit each of these could be placed in the scheduling of classes. In fact, picking the schedule that would lead to them is also impossible unless all our considered. Thus, we must consider all possible unique states of course progression, and not repeat our calculations. This means we need a memo the size of 2^n courses to account for all of the combinations, and that we only reach our goal at 2^n-1 for when we have exhausted all courses as a summation record key. \n\nIn the approach we\'ll detail some optimizations that help with this. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo start with, we consider our initialized process of storage and values. \nWe want a graph, an out degree and in degree for each node, a bit shifted course id container, a queue, and a seen array. We also want a start, goal, limit, number of courses, and max semesters value. \n\nWe then turn to set up where we pass the problems fields \nn is our number of courses, and we want a graph, outdegree and in degree of size n. \nSeen is our combination of courses, with size 2^n to account for all course key combinations. \nGoal is 2^n-1 so that we have completed all courses \nOur bit shifted courses are 1 << c_i, for the ith course in range n \nWe then process our relations \n- We set graph at post requisite course - 1 to increment by 1 << (prerequisite - 1) \n- We set out degree of pre requisite - 1 to increment by 1 and similar for in degree of post requisite - 1 \n\nIn our queue we start with self.start of 0 and 0 semesters \nWe set our limit to k \n\nNow we want to set up our truth finding functions for processing \nIf a course id is one we are qualified to take, the result of our record key & self.graph at course id should be the same as self.graph at course id. This is because the prerequisites for that course id should be in the record key and the graph at that course id stores the value of pre requisite courses only. \n\nIf a course id is not one we have taken, the result of our record key and the bit shifted course id should be zero, meaning we have no overlap. \n\nThis then lets us find our available courses given a current record key. \nWe can loop over our number of courses, and for course id we have in that range \n- if we have not taken the course and we are qualified to take the course \n - it is an available course to consider \n\nTo get the prerequisite courses in our available courses we will pass the function only those courses which have an out degree in our available courses. Once we do \n- we will sort these by the out degree from greatest to least \n- then, return the bit shifted course id of those in the sorted prerequisites \n- this ensures we process our prerequisites in order of greatest to least coverage \n\nTo get the terminal courses (courses with no post requisites) we again pass the specified available courses as a subset (ones with outdegree 0) \n- We then sort these by their in degree in increasing order. \n- And return the bit shifted course id of those in the sorted terminal courses \n- This ensures we process our terminals in order of least cost to have covered. We are in essence doing the most valuable terminals first \n\nIf we end up in a state where we do not have enough pure pre requisite classes and must instead process terminals with them, we will want to get our new processing output. To do so \n- calculate a new record key as the sum of the prerequisite course ids with the sum of the terminal keys up to limit minus the length of our prerequisites\n- If the new record key is now our goal, return semesters + 1 \n- otherwise, if we have not seen this record key, add it to the queue and mark it seen, then return 0 \n\nIf we have too many pre requisites to consider, we still will need to think of all possible combinations. Based on the combinations itertool processing however, we will generate the most valueable to least valueable using our already sorted prerequisites. This is one of our secret time saving tricks! As for how that works, in our process pre req combinations function we \n- generation combinations from itertools using prerequisites and our limit k \n - for each combination, get a new pre reqs key as the sum of the combination \n - make a new record key as the record key plus the pre reqs key \n - if the new record key magically is our goal \n - return semesters plus 1 \n - otherwise, if we have not seen it, add to queue and mark seen \n- at end, return 0 if you haven\'t already \n\nNow we are ready to process our queue. While we have a queue \n- get record key and semesters by popping from left of queue \n- get max semesters as max of semesters and current max semesters \n- get available, prerequisite, and terminals using our functions \n- if length of prerequisite is less than or equal to limit k, \n - set result equal to call of process pre reqs and terminals, passing pre reqs, terminals, record key and semesters \n - if result is not 0, return result \n- otherwise\n - set result equal to call of process prereq combinations, passing prereqs, recordkey, and semesters \n - if result is not 0, return it \nIf you exhaust the queue, return max semesters plus 1, as you\'ll always be one semester away \n\nNow we can do the problem by \n- calling setup, passing n, relations, and k \n- return the result of calling process queue, and know we will get a result of integer form no matter what \n\n# Complexity\n- Time complexity: O(min (2^V, V^2 * V choose k))\n - We do O(E) processing all relations \n - We do O(V) setting up bit shifted courses \n - We process at most O(V) times in the queue (course graph is a stick)\n - in which we do O(V) times in the available function\n - in which we do O(V) setting up for pre req and terminal\n - in side of which we do another v log v, but that is subsumed by O(V)\n - if we process pre reqs and terminals thats really O(k) to get sums of pre reqs and terminals \n - if we process pre req combinations thats O(V * V choose k) \n - total absolute worst run time complexity then is min(2^V, V^2 * V choose k)\n - We can ignore the E, which is unusual, as for this graph it is bound as V^2. Our queue process needs V * V * V choose k, which dominates this\n - We do have 2 ^ V as potentially smaller, which is when we visit all of the possible combinations. Whichever is better is our bound. \n\n- Space complexity : O(2^V)\n - We store E edges \n - We store in and out degree status of V nodes \n - We need V * V choose R for combinations \n - We need 2^V slots for seen\n - Of these, We see the same result as above, except we do not have the nested V for time complexity. This leaves us at 2^V as our space complexity simply. \n\n# Code\n```\nclass Solution:\n def __init__(self) : \n self.graph = []\n self.out_degree = []\n self.in_degree = []\n self.bit_shifted_courses = []\n self.queue = collections.deque()\n self.seen = []\n self.start = 0\n self.goal = 1\n self.limit = 1\n self.number_of_courses = 0\n self.max_semesters = 1 \n\n def set_up(self, n, relations, k) : \n # graph size and out degree for n nodes \n self.number_of_courses = n\n self.graph = [0]*n \n self.out_degree = [0]*n\n self.in_degree = [0]*n\n # seen is 2 ^ n combinations of bit shifts \n self.seen = [0] * (2**n)\n # goal is getting all of them \n self.goal = 2**n-1\n # bit shifted courses for all unique bit identity of courses \n self.bit_shifted_courses = [1<<c_i for c_i in range(n)]\n # off by one indexing \n for prerequisite, post in relations : \n self.graph[post-1] += 1 << (prerequisite - 1)\n self.out_degree[prerequisite - 1] += 1\n self.in_degree[post-1] += 1 \n # starting point and limit factor \n self.queue.append((self.start, 0))\n self.limit = k\n\n def qualified_to_take_course(self, record_key, course_id) : \n # if record key & self.graph[course_id] == self.graph[course_id] we have all prerequisites needed\n return record_key & self.graph[course_id] == self.graph[course_id]\n\n def have_not_taken_course(self, record_key, course_id) : \n # if record_key & bit shifted course at course id is 0, we have not taken it \n return record_key & self.bit_shifted_courses[course_id] == 0 \n\n def get_available_courses(self, record_key) : \n # using record key \n available = []\n # loop over number of courses \n for course_id in range(self.number_of_courses) : \n # if we have not taken it and can take it, add it \n if self.have_not_taken_course(record_key, course_id) and self.qualified_to_take_course(record_key, course_id) : \n available.append(course_id)\n # return when done \n return available\n\n def get_prerequisites_in_available_courses(self, available) : \n # return those that lead to other courses \n # sort by out degree in increasing fashion, so that we consider pre-reqs in order of maximal coverage \n available.sort(key = lambda course_id : self.out_degree[course_id], reverse=True)\n return [self.bit_shifted_courses[course_id] for course_id in available]\n\n def get_terminal_courses_in_available_courses(self, available) : \n # return those that do not lead to other courses \n # sort by in degree that have minimal requirements \n available.sort(key = lambda course_id : self.in_degree[course_id])\n return [self.bit_shifted_courses[course_id] for course_id in available]\n\n def process_pre_reqs_and_terminals(self, pre_reqs, terminals, record_key, semesters) :\n # get new record key as combination of pre reqs and terminals we qualify for \n record_key += sum(pre_reqs) + sum(terminals[:self.limit - len(pre_reqs)])\n # if record key is goal increment steps and return \n if record_key == self.goal : \n return semesters + 1 \n # otherwise, if we have not considered this combination yet \n if self.seen[record_key] == 0 : \n # consider it and mark it considered \n self.queue.append((record_key, semesters+1))\n self.seen[record_key] = 1 \n # return 0 if not goal\n return 0 \n\n def process_pre_req_combinations(self, pre_reqs, record_key, semesters) : \n # try all combinations \n for combination in itertools.combinations(pre_reqs, self.limit) : \n # getting the new pre reqs course bits \n pre_reqs_key = sum(combination)\n # and updating record key \n new_record_key = record_key + pre_reqs_key\n # if that completed what we needed \n if new_record_key == self.goal : \n # return steps plus 1 \n return semesters + 1 \n # otherwise, if we have not considered it \n if self.seen[new_record_key] == 0 : \n # consider it and mark as such \n self.queue.append((new_record_key, semesters+1))\n self.seen[new_record_key] = 1 \n # return 0 by default if we never returned otherwise \n return 0 \n\n def process_queue(self) : \n # process queue and return result when found \n while self.queue : \n # pop from front\n record_key, semesters = self.queue.popleft()\n # insurance incase of other mishaps \n self.max_semesters = max(self.max_semesters, semesters)\n # get available, pre_reqs, and terminals \n available = self.get_available_courses(record_key) \n pre_reqs = self.get_prerequisites_in_available_courses([course_id for course_id in available if self.out_degree[course_id]])\n terminals = self.get_terminal_courses_in_available_courses([course_id for course_id in available if self.out_degree[course_id]==0])\n # if length of prereqs is at or under limit for semester \n if len(pre_reqs) <= self.limit : \n # get result of processing pre reqs and terminals \n result = self.process_pre_reqs_and_terminals(pre_reqs, terminals, record_key, semesters)\n # if we got a finish result \n if result != 0 : \n # return it \n return result \n else : \n # similar to above, but now we have too many prerequisites \n result = self.process_pre_req_combinations(pre_reqs, record_key, semesters)\n # if we finish on account of this, return it \n if result != 0 : \n return result \n return self.max_semesters + 1 \n\n def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:\n self.set_up(n, relations, k)\n return self.process_queue()\n``` | 0 | You are given an integer `n`, which indicates that there are `n` courses labeled from `1` to `n`. You are also given an array `relations` where `relations[i] = [prevCoursei, nextCoursei]`, representing a prerequisite relationship between course `prevCoursei` and course `nextCoursei`: course `prevCoursei` has to be taken before course `nextCoursei`. Also, you are given the integer `k`.
In one semester, you can take **at most** `k` courses as long as you have taken all the prerequisites in the **previous** semesters for the courses you are taking.
Return _the **minimum** number of semesters needed to take all courses_. The testcases will be generated such that it is possible to take every course.
**Example 1:**
**Input:** n = 4, relations = \[\[2,1\],\[3,1\],\[1,4\]\], k = 2
**Output:** 3
**Explanation:** The figure above represents the given graph.
In the first semester, you can take courses 2 and 3.
In the second semester, you can take course 1.
In the third semester, you can take course 4.
**Example 2:**
**Input:** n = 5, relations = \[\[2,1\],\[3,1\],\[4,1\],\[1,5\]\], k = 2
**Output:** 4
**Explanation:** The figure above represents the given graph.
In the first semester, you can only take courses 2 and 3 since you cannot take more than two per semester.
In the second semester, you can take course 4.
In the third semester, you can take course 1.
In the fourth semester, you can take course 5.
**Constraints:**
* `1 <= n <= 15`
* `1 <= k <= n`
* `0 <= relations.length <= n * (n-1) / 2`
* `relations[i].length == 2`
* `1 <= prevCoursei, nextCoursei <= n`
* `prevCoursei != nextCoursei`
* All the pairs `[prevCoursei, nextCoursei]` are **unique**.
* The given graph is a directed acyclic graph. | null |
Beginner Friendly || Beats 95% || Fully Explained || [Java/C++/Python3] | path-crossing | 1 | 1 | # Approach\n1. **Initialization:** Initialize a HashSet (set) to store visited coordinates. Initialize x and y to represent the current position, and add the starting coordinate ("0,0") to the set.\n2. **Traversal:** Iterate through each character in the input path string. Update the coordinates based on the direction specified by the character.\n3. **Coordinate Check:** After updating the coordinates, form a string representation of the current coordinate and check if it is already present in the set. If it is, then the path has crossed itself, and the function returns true.\n4. **Update Set:** If the current coordinate is not already in the set, add it to the set to mark it as visited.\n5. **Return:** If the entire path is traversed without encountering any repeated coordinates, return false as the path does not cross itself.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` Java []\nclass Solution {\n public boolean isPathCrossing(String path) {\n Set<String> set = new HashSet<>();\n int x = 0;\n int y = 0;\n set.add(0+","+0);\n for(char ch : path.toCharArray()) {\n if(ch == \'N\') {\n y++;\n }\n else if(ch == \'S\'){\n y--;\n }\n else if(ch == \'E\') {\n x++;\n }\n else if(ch == \'W\') {\n x--;\n }\n String coordinate = x + "," + y;\n if(set.contains(coordinate)) {\n return true;\n }\n set.add(coordinate);\n }\n return false;\n }\n}\n```\n``` C++ []\n\nclass Solution {\npublic:\n bool isPathCrossing(string path) {\n\n unordered_set<string> set;\n int x = 0;\n int y = 0;\n set.insert("0,0");\n for (char ch : path) {\n if (ch == \'N\') {\n y++;\n } else if (ch == \'S\') {\n y--;\n } else if (ch == \'E\') {\n x++;\n } else if (ch == \'W\') {\n x--;\n }\n string coordinate = to_string(x) + "," + to_string(y);\n if (set.count(coordinate) > 0) {\n return true;\n }\n set.insert(coordinate);\n }\n return false;\n }\n};\n```\n``` Python3 []\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n coordinate_set = set()\n x, y = 0, 0\n coordinate_set.add("0,0")\n \n for ch in path:\n if ch == \'N\':\n y += 1\n elif ch == \'S\':\n y -= 1\n elif ch == \'E\':\n x += 1\n elif ch == \'W\':\n x -= 1\n \n coordinate = f"{x},{y}"\n if coordinate in coordinate_set:\n return True\n \n coordinate_set.add(coordinate)\n \n return False\n```\n | 1 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Beginner Friendly || Beats 95% || Fully Explained || [Java/C++/Python3] | path-crossing | 1 | 1 | # Approach\n1. **Initialization:** Initialize a HashSet (set) to store visited coordinates. Initialize x and y to represent the current position, and add the starting coordinate ("0,0") to the set.\n2. **Traversal:** Iterate through each character in the input path string. Update the coordinates based on the direction specified by the character.\n3. **Coordinate Check:** After updating the coordinates, form a string representation of the current coordinate and check if it is already present in the set. If it is, then the path has crossed itself, and the function returns true.\n4. **Update Set:** If the current coordinate is not already in the set, add it to the set to mark it as visited.\n5. **Return:** If the entire path is traversed without encountering any repeated coordinates, return false as the path does not cross itself.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` Java []\nclass Solution {\n public boolean isPathCrossing(String path) {\n Set<String> set = new HashSet<>();\n int x = 0;\n int y = 0;\n set.add(0+","+0);\n for(char ch : path.toCharArray()) {\n if(ch == \'N\') {\n y++;\n }\n else if(ch == \'S\'){\n y--;\n }\n else if(ch == \'E\') {\n x++;\n }\n else if(ch == \'W\') {\n x--;\n }\n String coordinate = x + "," + y;\n if(set.contains(coordinate)) {\n return true;\n }\n set.add(coordinate);\n }\n return false;\n }\n}\n```\n``` C++ []\n\nclass Solution {\npublic:\n bool isPathCrossing(string path) {\n\n unordered_set<string> set;\n int x = 0;\n int y = 0;\n set.insert("0,0");\n for (char ch : path) {\n if (ch == \'N\') {\n y++;\n } else if (ch == \'S\') {\n y--;\n } else if (ch == \'E\') {\n x++;\n } else if (ch == \'W\') {\n x--;\n }\n string coordinate = to_string(x) + "," + to_string(y);\n if (set.count(coordinate) > 0) {\n return true;\n }\n set.insert(coordinate);\n }\n return false;\n }\n};\n```\n``` Python3 []\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n coordinate_set = set()\n x, y = 0, 0\n coordinate_set.add("0,0")\n \n for ch in path:\n if ch == \'N\':\n y += 1\n elif ch == \'S\':\n y -= 1\n elif ch == \'E\':\n x += 1\n elif ch == \'W\':\n x -= 1\n \n coordinate = f"{x},{y}"\n if coordinate in coordinate_set:\n return True\n \n coordinate_set.add(coordinate)\n \n return False\n```\n | 1 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Path Crossing (Storing the traversed positonss...) | path-crossing | 0 | 1 | # Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nDepending upon the movements the positions is changed and the new position is added to a list and check whether the postion is already visited...\n\n Trace the position visited by using a pair of values [x,y] \nstart the pointer from 0,0 and traverse change the values of x and y depending upon the movements ...\n\n North:- x,y+1\n East:- x+1,y\n West:- x-1,y\n South:- x,y-1\n\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 isPathCrossing(self, path: str) -> bool:\n d=[[0,0]]\n x,y=0,0\n for i in path:\n if(i=="N"):\n y+=1\n elif(i=="E"):\n x+=1\n elif(i=="S"):\n y-=1\n else:\n x-=1\n if [x,y] in d:\n #check if the position is already visited in the list.....\n return True\n d.append([x,y])\n #update the position...\n return False\n``` | 3 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Path Crossing (Storing the traversed positonss...) | path-crossing | 0 | 1 | # Intuition & Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nDepending upon the movements the positions is changed and the new position is added to a list and check whether the postion is already visited...\n\n Trace the position visited by using a pair of values [x,y] \nstart the pointer from 0,0 and traverse change the values of x and y depending upon the movements ...\n\n North:- x,y+1\n East:- x+1,y\n West:- x-1,y\n South:- x,y-1\n\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 isPathCrossing(self, path: str) -> bool:\n d=[[0,0]]\n x,y=0,0\n for i in path:\n if(i=="N"):\n y+=1\n elif(i=="E"):\n x+=1\n elif(i=="S"):\n y-=1\n else:\n x-=1\n if [x,y] in d:\n #check if the position is already visited in the list.....\n return True\n d.append([x,y])\n #update the position...\n return False\n``` | 3 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
You don't need matrices and graphs to solve this!!! | path-crossing | 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 isPathCrossing(self, path: str) -> bool:\n path=list(path)\n i,j=0,0\n k=[]\n k.append([i,j])\n for l in path:\n \n if l==\'N\':\n j+=1\n if l==\'S\':\n j-=1\n if l==\'E\':\n i+=1\n if l==\'W\':\n i-=1\n k.append([i,j])\n print(k)\n for m in k:\n if k.count(m)>1:\n return True\n return False\n``` | 1 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
You don't need matrices and graphs to solve this!!! | path-crossing | 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 isPathCrossing(self, path: str) -> bool:\n path=list(path)\n i,j=0,0\n k=[]\n k.append([i,j])\n for l in path:\n \n if l==\'N\':\n j+=1\n if l==\'S\':\n j-=1\n if l==\'E\':\n i+=1\n if l==\'W\':\n i-=1\n k.append([i,j])\n print(k)\n for m in k:\n if k.count(m)>1:\n return True\n return False\n``` | 1 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python || Easy Clean Set Solution. | path-crossing | 0 | 1 | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n seen = set([\'0_0\'])\n curr = [0, 0]\n for point in path:\n if point == \'N\': \n curr[0] += 1\n elif point == \'S\': \n curr[0] -= 1\n elif point == \'E\': \n curr[1] += 1\n else: \n curr[1] -= 1\n if f\'{curr[0]}_{curr[1]}\' in seen:\n return True\n seen.add(f\'{curr[0]}_{curr[1]}\')\n return False\n \n```\n\n | 1 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python || Easy Clean Set Solution. | path-crossing | 0 | 1 | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n seen = set([\'0_0\'])\n curr = [0, 0]\n for point in path:\n if point == \'N\': \n curr[0] += 1\n elif point == \'S\': \n curr[0] -= 1\n elif point == \'E\': \n curr[1] += 1\n else: \n curr[1] -= 1\n if f\'{curr[0]}_{curr[1]}\' in seen:\n return True\n seen.add(f\'{curr[0]}_{curr[1]}\')\n return False\n \n```\n\n | 1 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Simple Python || Understandable & Clean | path-crossing | 0 | 1 | # My Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n (r, c) = (0, 0)\n coors = {(r, c)}\n for i in path:\n if i == \'N\': c += 1\n elif i == \'E\': r += 1\n elif i == \'S\': c -= 1\n else: r -= 1\n if (r, c) in coors: return True\n coors.add((r, c))\n return False\n``` | 2 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Simple Python || Understandable & Clean | path-crossing | 0 | 1 | # My Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n (r, c) = (0, 0)\n coors = {(r, c)}\n for i in path:\n if i == \'N\': c += 1\n elif i == \'E\': r += 1\n elif i == \'S\': c -= 1\n else: r -= 1\n if (r, c) in coors: return True\n coors.add((r, c))\n return False\n``` | 2 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python3 simple solution faster than 99% users | path-crossing | 0 | 1 | ```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n l = [(0,0)]\n x,y = 0,0\n for i in path:\n if i == \'N\':\n y += 1\n if i == \'S\':\n y -= 1\n if i == \'E\':\n x += 1\n if i == \'W\':\n x -= 1\n if (x,y) in l:\n return True\n else:\n l.append((x,y))\n return False\n```\n**If you like this solution, please upvote for this** | 4 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python3 simple solution faster than 99% users | path-crossing | 0 | 1 | ```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n l = [(0,0)]\n x,y = 0,0\n for i in path:\n if i == \'N\':\n y += 1\n if i == \'S\':\n y -= 1\n if i == \'E\':\n x += 1\n if i == \'W\':\n x -= 1\n if (x,y) in l:\n return True\n else:\n l.append((x,y))\n return False\n```\n**If you like this solution, please upvote for this** | 4 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
python dict beats 89% | path-crossing | 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 isPathCrossing(self, path: str) -> bool:\n data ={(0,0):1}\n pos = [0,0]\n for i in path:\n if i =="N":\n pos[0]+=1\n elif i =="S":\n pos[0]-=1\n elif i =="W":\n pos[1]-=1 \n else:\n pos[1]+=1\n if tuple(pos) in data:\n return True \n else:\n data[tuple(pos)] =1\n return False\n \n``` | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
python dict beats 89% | path-crossing | 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 isPathCrossing(self, path: str) -> bool:\n data ={(0,0):1}\n pos = [0,0]\n for i in path:\n if i =="N":\n pos[0]+=1\n elif i =="S":\n pos[0]-=1\n elif i =="W":\n pos[1]-=1 \n else:\n pos[1]+=1\n if tuple(pos) in data:\n return True \n else:\n data[tuple(pos)] =1\n return False\n \n``` | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Simple Hashing solution Beats 97% | path-crossing | 0 | 1 | # Intuition\nThe problem requires tracking a path determined by a series of directions and checking if the path crosses itself. Intuitively, this involves keeping track of all the points visited during the traversal of the path. If any point is visited more than once, the path crosses itself.\n\n# Approach\nTo implement this, we can use a set to store the coordinates of each point visited. As we iterate through the string of directions, we update the current position based on the direction (\'N\', \'S\', \'E\', \'W\'). After each update, we check if the new position has already been visited (i.e., if it is in the set). If it is, we return True as the path crosses itself. If we reach the end of the path without revisiting any point, we return False.\n\n# Complexity\n- Time complexity:\nWe iterate through each character in the input string once - O(n), where\nn is the length of the string. For each character, we perform a constant amount of work (updating coordinates and checking/inserting in a set).\n\n- Space complexity:\nThe space complexity is mainly due to the storage of visited points in a set. In the worst case, if the path doesn\'t cross itself, we might store every point in the path, leading to a space complexity of \nO(n), where n is the number of steps in the path.\n\n\n\n\n\n\n# Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n start = [0, 0]\n points = set() # Use a set for efficient lookup\n points.add(tuple(start)) # Add the starting point\n\n for letter in path:\n if letter == "N":\n start[1] += 1\n elif letter == "S": # Changed to elif for efficiency\n start[1] -= 1\n elif letter == "E":\n start[0] += 1\n elif letter == "W":\n start[0] -= 1\n\n # Convert to tuple and check if it\'s already in points\n if tuple(start) in points:\n return True\n points.add(tuple(start))\n\n return False\n``` | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Simple Hashing solution Beats 97% | path-crossing | 0 | 1 | # Intuition\nThe problem requires tracking a path determined by a series of directions and checking if the path crosses itself. Intuitively, this involves keeping track of all the points visited during the traversal of the path. If any point is visited more than once, the path crosses itself.\n\n# Approach\nTo implement this, we can use a set to store the coordinates of each point visited. As we iterate through the string of directions, we update the current position based on the direction (\'N\', \'S\', \'E\', \'W\'). After each update, we check if the new position has already been visited (i.e., if it is in the set). If it is, we return True as the path crosses itself. If we reach the end of the path without revisiting any point, we return False.\n\n# Complexity\n- Time complexity:\nWe iterate through each character in the input string once - O(n), where\nn is the length of the string. For each character, we perform a constant amount of work (updating coordinates and checking/inserting in a set).\n\n- Space complexity:\nThe space complexity is mainly due to the storage of visited points in a set. In the worst case, if the path doesn\'t cross itself, we might store every point in the path, leading to a space complexity of \nO(n), where n is the number of steps in the path.\n\n\n\n\n\n\n# Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n start = [0, 0]\n points = set() # Use a set for efficient lookup\n points.add(tuple(start)) # Add the starting point\n\n for letter in path:\n if letter == "N":\n start[1] += 1\n elif letter == "S": # Changed to elif for efficiency\n start[1] -= 1\n elif letter == "E":\n start[0] += 1\n elif letter == "W":\n start[0] -= 1\n\n # Convert to tuple and check if it\'s already in points\n if tuple(start) in points:\n return True\n points.add(tuple(start))\n\n return False\n``` | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python Solution with short circuit. | path-crossing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere we construct the locations of the path and short circut if at any time we arrive at a location we\'ve been previously. We achieve this with the use of a Counter whose keys are the immutable tuple locations.\n\n# Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n # Cardinal -> Cartesian representation\n direction = {\'N\': (0, 1), \'E\': (1, 0), \'S\': (0, -1), \'W\': (-1, 0)}\n \n # Initialize location counter dictionary\n locations = defaultdict(int)\n location = (0, 0)\n locations[location] = 1\n\n for move in path:\n # Update current location and count\n location = self.add_tuples(direction[move], location)\n locations[location] += 1\n\n # Short circuit computation having intersection.\n if locations[location] >= 2:\n return True\n\n # Having not encountered an intersection, indicate to caller.\n return False\n \n\n def add_tuples(self, tup, ple):\n return tuple(a + b for a, b in zip(tup, ple))\n``` | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python Solution with short circuit. | path-crossing | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHere we construct the locations of the path and short circut if at any time we arrive at a location we\'ve been previously. We achieve this with the use of a Counter whose keys are the immutable tuple locations.\n\n# Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n # Cardinal -> Cartesian representation\n direction = {\'N\': (0, 1), \'E\': (1, 0), \'S\': (0, -1), \'W\': (-1, 0)}\n \n # Initialize location counter dictionary\n locations = defaultdict(int)\n location = (0, 0)\n locations[location] = 1\n\n for move in path:\n # Update current location and count\n location = self.add_tuples(direction[move], location)\n locations[location] += 1\n\n # Short circuit computation having intersection.\n if locations[location] >= 2:\n return True\n\n # Having not encountered an intersection, indicate to caller.\n return False\n \n\n def add_tuples(self, tup, ple):\n return tuple(a + b for a, b in zip(tup, ple))\n``` | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python solution using set and dictionary | path-crossing | 0 | 1 | # Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n x,y=0,0\n coords = set()\n coords.add((x,y))\n dic = {\'N\':(0,1),\'E\':(1,0),\'S\':(0,-1),\'W\':(-1,0)}\n for p in path:\n x+= dic[p][0]\n y+= dic[p][1]\n if((x,y) in coords):\n return True\n coords.add((x,y))\n return False\n``` | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python solution using set and dictionary | path-crossing | 0 | 1 | # Code\n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n x,y=0,0\n coords = set()\n coords.add((x,y))\n dic = {\'N\':(0,1),\'E\':(1,0),\'S\':(0,-1),\'W\':(-1,0)}\n for p in path:\n x+= dic[p][0]\n y+= dic[p][1]\n if((x,y) in coords):\n return True\n coords.add((x,y))\n return False\n``` | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python3 - Fast (~97%) but memory heavy (~23%) | path-crossing | 0 | 1 | \n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n def get_next_point(point, prev):\n return [prev[0] + point[0], prev[1] + point[1]]\n\n start = [0, 0]\n coords = [start]\n\n N = [1, 0]\n S = [-1, 0]\n E = [0, 1]\n W = [0, -1]\n\n for point in path:\n prev = coords[-1]\n curr = None\n if point == "N":\n curr = get_next_point(N, prev)\n elif point == "S":\n curr = get_next_point(S, prev)\n elif point == "E":\n curr = get_next_point(E, prev)\n elif point == "W":\n curr = get_next_point(W, prev)\n\n if curr in coords:\n return True\n coords.append(curr)\n return False\n``` | 0 | Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`. | Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria. |
Python3 - Fast (~97%) but memory heavy (~23%) | path-crossing | 0 | 1 | \n```\nclass Solution:\n def isPathCrossing(self, path: str) -> bool:\n def get_next_point(point, prev):\n return [prev[0] + point[0], prev[1] + point[1]]\n\n start = [0, 0]\n coords = [start]\n\n N = [1, 0]\n S = [-1, 0]\n E = [0, 1]\n W = [0, -1]\n\n for point in path:\n prev = coords[-1]\n curr = None\n if point == "N":\n curr = get_next_point(N, prev)\n elif point == "S":\n curr = get_next_point(S, prev)\n elif point == "E":\n curr = get_next_point(E, prev)\n elif point == "W":\n curr = get_next_point(W, prev)\n\n if curr in coords:\n return True\n coords.append(curr)\n return False\n``` | 0 | Given an integer array `arr`, return _the mean of the remaining integers after removing the smallest `5%` and the largest `5%` of the elements._
Answers within `10-5` of the **actual answer** will be considered accepted.
**Example 1:**
**Input:** arr = \[1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3\]
**Output:** 2.00000
**Explanation:** After erasing the minimum and the maximum values of this array, all elements are equal to 2, so the mean is 2.
**Example 2:**
**Input:** arr = \[6,2,7,5,1,2,0,3,10,2,5,0,5,5,0,8,7,6,8,0\]
**Output:** 4.00000
**Example 3:**
**Input:** arr = \[6,0,7,0,7,5,7,8,3,4,0,7,8,1,6,8,1,1,2,4,8,1,9,5,4,3,8,5,10,8,6,6,1,0,6,10,8,2,3,4\]
**Output:** 4.77778
**Constraints:**
* `20 <= arr.length <= 1000`
* `arr.length` **is a multiple** of `20`.
* `0 <= arr[i] <= 105` | Simulate the process while keeping track of visited points. Use a set to store previously visited points. |
Python One liner Explained with 2 Original Solutions( The best explanation) | check-if-array-pairs-are-divisible-by-k | 0 | 1 | The idea is to check the total sum divisible by k.if there has to be n//2 pairs each sum divisible by k.And this worksout well because,even if there is a singlepair whose sum not divisible by k,the total sum concept fails.\n\nMaybe,its just `intuition` sometimes.I Solved it in the contest in 1sec with `one liner`.Read till the end you will not regret.\nMy solution:\n```python\nreturn sum(arr)%k==0\n````\nMy thought process`:\nThe idea is simple.When all numbers sumup to a number divisible by k,there\'s a fair chance of obtaining pairs whose sum is divisible by k.But,the one thing that confuses most is the \nquestion below:\n```\nWhat if the sum is divisible by k,but there exists pairs whose sum doesnt get divided by k?\n```\nThe answer is clearly simple.\nHere you go,\n```\nIf the total sum is divisible by k,but there exists some pairs whose sum is not divisible by k.\nImagine there is a pair (a,b) whose sum is not divisible by k,\nSo, sum(rest all pairs) is divisble by k. Is this possible? Damn never. because the total sum has to be divisible by k.\nso,if there is a pair (a,b) such that (a+b) % k !=0 then there should exist another pair (c,d) such that (c+d )% k !=0 \nSo,now since (a+b)%k!=0 and (c+d)%k!=0 and sum(rest all pairs)%k=0, clearly we derive (a+b+c+d)%k=0.\nIf you understood till this point you should know the next step.obviously why we would we even pair (a with b ),(c with d) when you can rearrange and get pairs whose sum is divisble by k.\n```\nUpvote if I got u the eureka point.\n\nTime : O(n),finding sum\nSpace::O(1)\n\n```python\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n return sum(arr)%k==0\n```\nSorry but that\'s my thought process behind the solution which fortunately got accepted during the contest. I just got lucky like hundreds of others.\nBut ,If you study the corner cases,you can find something like this \n```\n[2,2,2,2,2,2]\nk =6\n```\nsum = 12 and 12%6=0, but there is no pair whose sum is divisible by 6.\n\nNow let\'s discuss the original solutions and the real approaches needed in an interview setting. \nSolution-1 {AC}\n\n```\nThe math behind it\nx+y mod k =0\nso, y = -x mod k #finding the compliment residue\n```\nTime:O(N)\nSpace:O(k)\n\n```python\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n #The idea is to count the residues\n \n #If every residue has the counter residue\n #such that x+y == k,then we found a pair\n \n count = [0]*k\n for num in arr:\n count[num%k] +=1\n \n #Now since we have 0,1,2,.....k-1 as residues\n #If count[1] == count[k-1],pairs+=count[0] \n print(count)\n for x in range(k):\n comp = -x % k \n # x+comp = 0 mod k, or\n # (x+comp) mod k = 0\n print(comp)\n while count[x]>0:\n count[x]-=1\n count[comp]-=1\n if count[comp]<0:\n return False\n \n return True\n``` \n\n\nSolution-2\n{AC}\nTypical `Two pointer approach` to count the number of pairs.\nThis is the most intuitive way of doing in my opinion as it counts the number of pairs.\nWhen you find the equal number of (i,j) ,it just means we have enough counter parts of \na residue.When you find count[i]=count[k-i],just take down count[i] number of pairs.\n\nTime : O(N)\nSpace:O(k)\n\n```python\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n #The idea is to count the residues\n \n #If every residue has the counter residue\n #such that x+y == k,then we found a pair\n \n count = [0]*k\n for num in arr:\n count[num%k] +=1\n \n #Now since we have 0,1,2,.....k-1 as residues\n #If count[1] == count[k-1],pairs+=count[1]\n #since we have odd number of complimenting residues,\n #we should also care about residue=0 and residue=k//2\n \n i,j =1,k-1\n pairs = 0\n while i<j :\n if count[i]!=count[j]:\n return False\n pairs += count[i]\n i+=1\n j-=1\n if pairs>0 and i==j:\n pairs+=count[i]/2\n pairs+= count[0]/2\n n = len(arr)\n return pairs == n//2\n```\n\nThis is what you need to do in a real interview.Discuss all possible approaches,specify space and time complexities of all the solutions and also the tradeoffs and which solution might be better in which conditions.Get the bonus points by also mentioning the bogus solution I gave first.Who knows the interviewer might even wonder and hire you for your wide range of thoughts and approaches. Please upvote if you find this helpful. | 54 | You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**.
You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**.
The signal quality of the `ith` tower at a coordinate `(x, y)` is calculated with the formula `⌊qi / (1 + d)⌋`, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers.
Return _the array_ `[cx, cy]` _representing the **integral** coordinate_ `(cx, cy)` _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._
**Note:**
* A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either:
* `x1 < x2`, or
* `x1 == x2` and `y1 < y2`.
* `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function).
**Example 1:**
**Input:** towers = \[\[1,2,5\],\[2,1,7\],\[3,1,9\]\], radius = 2
**Output:** \[2,1\]
**Explanation:** At coordinate (2, 1) the total quality is 13.
- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7
- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2
- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4
No other coordinate has a higher network quality.
**Example 2:**
**Input:** towers = \[\[23,11,21\]\], radius = 9
**Output:** \[23,11\]
**Explanation:** Since there is only one tower, the network quality is highest right at the tower's location.
**Example 3:**
**Input:** towers = \[\[1,2,13\],\[2,1,7\],\[0,1,9\]\], radius = 2
**Output:** \[1,2\]
**Explanation:** Coordinate (1, 2) has the highest network quality.
**Constraints:**
* `1 <= towers.length <= 50`
* `towers[i].length == 3`
* `0 <= xi, yi, qi <= 50`
* `1 <= radius <= 50` | Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0 |
Python One liner Explained with 2 Original Solutions( The best explanation) | check-if-array-pairs-are-divisible-by-k | 0 | 1 | The idea is to check the total sum divisible by k.if there has to be n//2 pairs each sum divisible by k.And this worksout well because,even if there is a singlepair whose sum not divisible by k,the total sum concept fails.\n\nMaybe,its just `intuition` sometimes.I Solved it in the contest in 1sec with `one liner`.Read till the end you will not regret.\nMy solution:\n```python\nreturn sum(arr)%k==0\n````\nMy thought process`:\nThe idea is simple.When all numbers sumup to a number divisible by k,there\'s a fair chance of obtaining pairs whose sum is divisible by k.But,the one thing that confuses most is the \nquestion below:\n```\nWhat if the sum is divisible by k,but there exists pairs whose sum doesnt get divided by k?\n```\nThe answer is clearly simple.\nHere you go,\n```\nIf the total sum is divisible by k,but there exists some pairs whose sum is not divisible by k.\nImagine there is a pair (a,b) whose sum is not divisible by k,\nSo, sum(rest all pairs) is divisble by k. Is this possible? Damn never. because the total sum has to be divisible by k.\nso,if there is a pair (a,b) such that (a+b) % k !=0 then there should exist another pair (c,d) such that (c+d )% k !=0 \nSo,now since (a+b)%k!=0 and (c+d)%k!=0 and sum(rest all pairs)%k=0, clearly we derive (a+b+c+d)%k=0.\nIf you understood till this point you should know the next step.obviously why we would we even pair (a with b ),(c with d) when you can rearrange and get pairs whose sum is divisble by k.\n```\nUpvote if I got u the eureka point.\n\nTime : O(n),finding sum\nSpace::O(1)\n\n```python\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n return sum(arr)%k==0\n```\nSorry but that\'s my thought process behind the solution which fortunately got accepted during the contest. I just got lucky like hundreds of others.\nBut ,If you study the corner cases,you can find something like this \n```\n[2,2,2,2,2,2]\nk =6\n```\nsum = 12 and 12%6=0, but there is no pair whose sum is divisible by 6.\n\nNow let\'s discuss the original solutions and the real approaches needed in an interview setting. \nSolution-1 {AC}\n\n```\nThe math behind it\nx+y mod k =0\nso, y = -x mod k #finding the compliment residue\n```\nTime:O(N)\nSpace:O(k)\n\n```python\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n #The idea is to count the residues\n \n #If every residue has the counter residue\n #such that x+y == k,then we found a pair\n \n count = [0]*k\n for num in arr:\n count[num%k] +=1\n \n #Now since we have 0,1,2,.....k-1 as residues\n #If count[1] == count[k-1],pairs+=count[0] \n print(count)\n for x in range(k):\n comp = -x % k \n # x+comp = 0 mod k, or\n # (x+comp) mod k = 0\n print(comp)\n while count[x]>0:\n count[x]-=1\n count[comp]-=1\n if count[comp]<0:\n return False\n \n return True\n``` \n\n\nSolution-2\n{AC}\nTypical `Two pointer approach` to count the number of pairs.\nThis is the most intuitive way of doing in my opinion as it counts the number of pairs.\nWhen you find the equal number of (i,j) ,it just means we have enough counter parts of \na residue.When you find count[i]=count[k-i],just take down count[i] number of pairs.\n\nTime : O(N)\nSpace:O(k)\n\n```python\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n #The idea is to count the residues\n \n #If every residue has the counter residue\n #such that x+y == k,then we found a pair\n \n count = [0]*k\n for num in arr:\n count[num%k] +=1\n \n #Now since we have 0,1,2,.....k-1 as residues\n #If count[1] == count[k-1],pairs+=count[1]\n #since we have odd number of complimenting residues,\n #we should also care about residue=0 and residue=k//2\n \n i,j =1,k-1\n pairs = 0\n while i<j :\n if count[i]!=count[j]:\n return False\n pairs += count[i]\n i+=1\n j-=1\n if pairs>0 and i==j:\n pairs+=count[i]/2\n pairs+= count[0]/2\n n = len(arr)\n return pairs == n//2\n```\n\nThis is what you need to do in a real interview.Discuss all possible approaches,specify space and time complexities of all the solutions and also the tradeoffs and which solution might be better in which conditions.Get the bonus points by also mentioning the bogus solution I gave first.Who knows the interviewer might even wonder and hire you for your wide range of thoughts and approaches. Please upvote if you find this helpful. | 54 | Design a stack which supports the following operations. Implement the CustomStack class: | Use an array to represent the stack. Push will add new integer to the array. Pop removes the last element in the array and increment will add val to the first k elements of the array. This solution run in O(1) per push and pop and O(k) per increment. |
Most of the Solutions here are wrong. Correct solution is here. | check-if-array-pairs-are-divisible-by-k | 0 | 1 | I have seen other solutions but I dont think most of them will work. Test cases are weak actually.\nEx: arr = [2,2,2,2,2,2] k = 3\n\nThis is my implementation for this problem.\n```\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n ## RC ##\n ## APPROACH : 2 SUM ##\n ## LOGIC ##\n\t\t## 1. Store the remainders in the hashmap and check if the current number has remaining remainder available in the hashset ##\n\t\t\n if len(arr) % 2 == 1: return False\n lookup = collections.defaultdict(int)\n count = 0\n for i, num in enumerate(arr):\n key = k - (num % k)\n if key in lookup and lookup[key] >= 1:\n # print(key, num)\n count += 1\n lookup[key] -= 1\n else:\n lookup[(num % k) or k] += 1\n return count == len(arr) // 2\n```\nPLEASE UPVOTE IF YOU LIKE MY SOLUTION | 43 | You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**.
You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**.
The signal quality of the `ith` tower at a coordinate `(x, y)` is calculated with the formula `⌊qi / (1 + d)⌋`, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers.
Return _the array_ `[cx, cy]` _representing the **integral** coordinate_ `(cx, cy)` _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._
**Note:**
* A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either:
* `x1 < x2`, or
* `x1 == x2` and `y1 < y2`.
* `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function).
**Example 1:**
**Input:** towers = \[\[1,2,5\],\[2,1,7\],\[3,1,9\]\], radius = 2
**Output:** \[2,1\]
**Explanation:** At coordinate (2, 1) the total quality is 13.
- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7
- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2
- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4
No other coordinate has a higher network quality.
**Example 2:**
**Input:** towers = \[\[23,11,21\]\], radius = 9
**Output:** \[23,11\]
**Explanation:** Since there is only one tower, the network quality is highest right at the tower's location.
**Example 3:**
**Input:** towers = \[\[1,2,13\],\[2,1,7\],\[0,1,9\]\], radius = 2
**Output:** \[1,2\]
**Explanation:** Coordinate (1, 2) has the highest network quality.
**Constraints:**
* `1 <= towers.length <= 50`
* `towers[i].length == 3`
* `0 <= xi, yi, qi <= 50`
* `1 <= radius <= 50` | Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0 |
Most of the Solutions here are wrong. Correct solution is here. | check-if-array-pairs-are-divisible-by-k | 0 | 1 | I have seen other solutions but I dont think most of them will work. Test cases are weak actually.\nEx: arr = [2,2,2,2,2,2] k = 3\n\nThis is my implementation for this problem.\n```\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n ## RC ##\n ## APPROACH : 2 SUM ##\n ## LOGIC ##\n\t\t## 1. Store the remainders in the hashmap and check if the current number has remaining remainder available in the hashset ##\n\t\t\n if len(arr) % 2 == 1: return False\n lookup = collections.defaultdict(int)\n count = 0\n for i, num in enumerate(arr):\n key = k - (num % k)\n if key in lookup and lookup[key] >= 1:\n # print(key, num)\n count += 1\n lookup[key] -= 1\n else:\n lookup[(num % k) or k] += 1\n return count == len(arr) // 2\n```\nPLEASE UPVOTE IF YOU LIKE MY SOLUTION | 43 | Design a stack which supports the following operations. Implement the CustomStack class: | Use an array to represent the stack. Push will add new integer to the array. Pop removes the last element in the array and increment will add val to the first k elements of the array. This solution run in O(1) per push and pop and O(k) per increment. |
[Python 3] Two Sum Variation | Hashmap | O(n) | check-if-array-pairs-are-divisible-by-k | 0 | 1 | ```\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n hm = defaultdict(int)\n res = 0\n \n for i in arr:\n temp = i % k\n \n if temp == 0:\n res += 1\n elif k - temp in hm and hm[k - temp] != 0:\n res += 2\n hm[k - temp] -= 1\n else:\n hm[temp] += 1\n\n return res == len(arr)\n``` | 1 | You are given an array of network towers `towers`, where `towers[i] = [xi, yi, qi]` denotes the `ith` network tower with location `(xi, yi)` and quality factor `qi`. All the coordinates are **integral coordinates** on the X-Y plane, and the distance between the two coordinates is the **Euclidean distance**.
You are also given an integer `radius` where a tower is **reachable** if the distance is **less than or equal to** `radius`. Outside that distance, the signal becomes garbled, and the tower is **not reachable**.
The signal quality of the `ith` tower at a coordinate `(x, y)` is calculated with the formula `⌊qi / (1 + d)⌋`, where `d` is the distance between the tower and the coordinate. The **network quality** at a coordinate is the sum of the signal qualities from all the **reachable** towers.
Return _the array_ `[cx, cy]` _representing the **integral** coordinate_ `(cx, cy)` _where the **network quality** is maximum. If there are multiple coordinates with the same **network quality**, return the lexicographically minimum **non-negative** coordinate._
**Note:**
* A coordinate `(x1, y1)` is lexicographically smaller than `(x2, y2)` if either:
* `x1 < x2`, or
* `x1 == x2` and `y1 < y2`.
* `⌊val⌋` is the greatest integer less than or equal to `val` (the floor function).
**Example 1:**
**Input:** towers = \[\[1,2,5\],\[2,1,7\],\[3,1,9\]\], radius = 2
**Output:** \[2,1\]
**Explanation:** At coordinate (2, 1) the total quality is 13.
- Quality of 7 from (2, 1) results in ⌊7 / (1 + sqrt(0)⌋ = ⌊7⌋ = 7
- Quality of 5 from (1, 2) results in ⌊5 / (1 + sqrt(2)⌋ = ⌊2.07⌋ = 2
- Quality of 9 from (3, 1) results in ⌊9 / (1 + sqrt(1)⌋ = ⌊4.5⌋ = 4
No other coordinate has a higher network quality.
**Example 2:**
**Input:** towers = \[\[23,11,21\]\], radius = 9
**Output:** \[23,11\]
**Explanation:** Since there is only one tower, the network quality is highest right at the tower's location.
**Example 3:**
**Input:** towers = \[\[1,2,13\],\[2,1,7\],\[0,1,9\]\], radius = 2
**Output:** \[1,2\]
**Explanation:** Coordinate (1, 2) has the highest network quality.
**Constraints:**
* `1 <= towers.length <= 50`
* `towers[i].length == 3`
* `0 <= xi, yi, qi <= 50`
* `1 <= radius <= 50` | Keep an array of the frequencies of ((x % k) + k) % k for each x in arr. for each i in [0, k - 1] we need to check if freq[k] == freq[k - i] Take care of the case when i == k - i and when i == 0 |
[Python 3] Two Sum Variation | Hashmap | O(n) | check-if-array-pairs-are-divisible-by-k | 0 | 1 | ```\nclass Solution:\n def canArrange(self, arr: List[int], k: int) -> bool:\n hm = defaultdict(int)\n res = 0\n \n for i in arr:\n temp = i % k\n \n if temp == 0:\n res += 1\n elif k - temp in hm and hm[k - temp] != 0:\n res += 2\n hm[k - temp] -= 1\n else:\n hm[temp] += 1\n\n return res == len(arr)\n``` | 1 | Design a stack which supports the following operations. Implement the CustomStack class: | Use an array to represent the stack. Push will add new integer to the array. Pop removes the last element in the array and increment will add val to the first k elements of the array. This solution run in O(1) per push and pop and O(k) per increment. |
python3 code | number-of-subsequences-that-satisfy-the-given-sum-condition | 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 numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n left, right = 0, len(nums) - 1\n count = 0\n mod = 10 ** 9 + 7\n \n while left <= right:\n if nums[left] + nums[right] > target:\n right -= 1\n else:\n count += pow(2, right - left, mod)\n left += 1\n \n return count % mod\n\n``` | 2 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[3,5,6,7\], target = 9
**Output:** 4
**Explanation:** There are 4 subsequences that satisfy the condition.
\[3\] -> Min value + max value <= target (3 + 3 <= 9)
\[3,5\] -> (3 + 5 <= 9)
\[3,5,6\] -> (3 + 6 <= 9)
\[3,6\] -> (3 + 6 <= 9)
**Example 2:**
**Input:** nums = \[3,3,6,8\], target = 10
**Output:** 6
**Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
\[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\]
**Example 3:**
**Input:** nums = \[2,3,3,4,6,7\], target = 12
**Output:** 61
**Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]).
Number of valid subsequences (63 - 2 = 61).
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 106`
* `1 <= target <= 106` | null |
python3 code | number-of-subsequences-that-satisfy-the-given-sum-condition | 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 numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n left, right = 0, len(nums) - 1\n count = 0\n mod = 10 ** 9 + 7\n \n while left <= right:\n if nums[left] + nums[right] > target:\n right -= 1\n else:\n count += pow(2, right - left, mod)\n left += 1\n \n return count % mod\n\n``` | 2 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints.
Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** 5
**Explanation:** The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 3
**Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
**Example 3:**
**Input:** n = 30, k = 7
**Output:** 796297179
**Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
**Constraints:**
* `2 <= n <= 1000`
* `1 <= k <= n-1` | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
2_Pointor.py | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Approach\nTwo Pointer\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n\n# Code\n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n ans=0\n i,j=0,len(nums)-1\n while i<=j:\n if nums[i]+nums[j]>target:\n j-=1\n else:\n ans+=2**(j-i)\n ans=ans%(10**9+7)\n i+=1\n return ans%(10**9+7)\n``` | 2 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[3,5,6,7\], target = 9
**Output:** 4
**Explanation:** There are 4 subsequences that satisfy the condition.
\[3\] -> Min value + max value <= target (3 + 3 <= 9)
\[3,5\] -> (3 + 5 <= 9)
\[3,5,6\] -> (3 + 6 <= 9)
\[3,6\] -> (3 + 6 <= 9)
**Example 2:**
**Input:** nums = \[3,3,6,8\], target = 10
**Output:** 6
**Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
\[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\]
**Example 3:**
**Input:** nums = \[2,3,3,4,6,7\], target = 12
**Output:** 61
**Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]).
Number of valid subsequences (63 - 2 = 61).
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 106`
* `1 <= target <= 106` | null |
2_Pointor.py | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | # Approach\nTwo Pointer\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n\n# Code\n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n ans=0\n i,j=0,len(nums)-1\n while i<=j:\n if nums[i]+nums[j]>target:\n j-=1\n else:\n ans+=2**(j-i)\n ans=ans%(10**9+7)\n i+=1\n return ans%(10**9+7)\n``` | 2 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints.
Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** 5
**Explanation:** The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 3
**Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
**Example 3:**
**Input:** n = 30, k = 7
**Output:** 796297179
**Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
**Constraints:**
* `2 <= n <= 1000`
* `1 <= k <= n-1` | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
python3 Solution | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | \n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n ans=0\n mod=10**9+7\n for index,x in enumerate(nums):\n n=bisect.bisect_right(nums,target-x)-1\n if n-index-1>=0:\n ans+=pow(2,n-index,mod)-1\n\n if x*2<=target:\n ans+=1\n\n ans%=mod\n\n return ans%mod \n``` | 2 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[3,5,6,7\], target = 9
**Output:** 4
**Explanation:** There are 4 subsequences that satisfy the condition.
\[3\] -> Min value + max value <= target (3 + 3 <= 9)
\[3,5\] -> (3 + 5 <= 9)
\[3,5,6\] -> (3 + 6 <= 9)
\[3,6\] -> (3 + 6 <= 9)
**Example 2:**
**Input:** nums = \[3,3,6,8\], target = 10
**Output:** 6
**Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
\[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\]
**Example 3:**
**Input:** nums = \[2,3,3,4,6,7\], target = 12
**Output:** 61
**Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]).
Number of valid subsequences (63 - 2 = 61).
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 106`
* `1 <= target <= 106` | null |
python3 Solution | number-of-subsequences-that-satisfy-the-given-sum-condition | 0 | 1 | \n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n nums.sort()\n ans=0\n mod=10**9+7\n for index,x in enumerate(nums):\n n=bisect.bisect_right(nums,target-x)-1\n if n-index-1>=0:\n ans+=pow(2,n-index,mod)-1\n\n if x*2<=target:\n ans+=1\n\n ans%=mod\n\n return ans%mod \n``` | 2 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints.
Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** 5
**Explanation:** The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 3
**Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
**Example 3:**
**Input:** n = 30, k = 7
**Output:** 796297179
**Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
**Constraints:**
* `2 <= n <= 1000`
* `1 <= k <= n-1` | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
classify all the answer by [min, max] pairs | number-of-subsequences-that-satisfy-the-given-sum-condition | 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 numSubseq(self, nums: List[int], target: int) -> int:\n #patterns:\n #num of subsequence that satisfies specific condition\n #the order of the subsequence doesn\'t matter at all\n #so the sequence of [choose, don\'t choose, choose, ......] determined a specific subsequence\n #for a pair of [min, max] , if min+max<=target, then all the subsequence whose min/max num is min and max satisfy the requirements\n nums.sort() #order doesn\'t matter\n #after sorting, it is much easier to determine the min/max number of a sequence\n left = 0\n right = len(nums)-1\n #first determine all the possible min/max pairs\n res = 0\n while left < len(nums) and left <= right:\n while (right >= 0 and nums[left]+nums[right] > target):\n right -= 1\n #right can also be left+1, left+2, .... right-1\n #print(left, right)\n # for i in range(right-left):\n # res += 2**i\n #res += (2**(right-left-1)+2**(right-left-2)+...+2**(0))\n if right > left:\n res += 2**0 * (1-2**(right-left)) // (1-2)\n if nums[left]*2 <= target:\n res += 1\n if right <= left:\n break\n #for [left, right] there can be 2** right-left-1 subsequences\n left += 1\n return res % (10**9 + 7)\n \n\n\n``` | 1 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[3,5,6,7\], target = 9
**Output:** 4
**Explanation:** There are 4 subsequences that satisfy the condition.
\[3\] -> Min value + max value <= target (3 + 3 <= 9)
\[3,5\] -> (3 + 5 <= 9)
\[3,5,6\] -> (3 + 6 <= 9)
\[3,6\] -> (3 + 6 <= 9)
**Example 2:**
**Input:** nums = \[3,3,6,8\], target = 10
**Output:** 6
**Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
\[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\]
**Example 3:**
**Input:** nums = \[2,3,3,4,6,7\], target = 12
**Output:** 61
**Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]).
Number of valid subsequences (63 - 2 = 61).
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 106`
* `1 <= target <= 106` | null |
classify all the answer by [min, max] pairs | number-of-subsequences-that-satisfy-the-given-sum-condition | 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 numSubseq(self, nums: List[int], target: int) -> int:\n #patterns:\n #num of subsequence that satisfies specific condition\n #the order of the subsequence doesn\'t matter at all\n #so the sequence of [choose, don\'t choose, choose, ......] determined a specific subsequence\n #for a pair of [min, max] , if min+max<=target, then all the subsequence whose min/max num is min and max satisfy the requirements\n nums.sort() #order doesn\'t matter\n #after sorting, it is much easier to determine the min/max number of a sequence\n left = 0\n right = len(nums)-1\n #first determine all the possible min/max pairs\n res = 0\n while left < len(nums) and left <= right:\n while (right >= 0 and nums[left]+nums[right] > target):\n right -= 1\n #right can also be left+1, left+2, .... right-1\n #print(left, right)\n # for i in range(right-left):\n # res += 2**i\n #res += (2**(right-left-1)+2**(right-left-2)+...+2**(0))\n if right > left:\n res += 2**0 * (1-2**(right-left)) // (1-2)\n if nums[left]*2 <= target:\n res += 1\n if right <= left:\n break\n #for [left, right] there can be 2** right-left-1 subsequences\n left += 1\n return res % (10**9 + 7)\n \n\n\n``` | 1 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints.
Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** 5
**Explanation:** The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 3
**Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
**Example 3:**
**Input:** n = 30, k = 7
**Output:** 796297179
**Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
**Constraints:**
* `2 <= n <= 1000`
* `1 <= k <= n-1` | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
1498. Number of Subsequences That Satisfy the Given Sum Condition.py | number-of-subsequences-that-satisfy-the-given-sum-condition | 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 numSubseq(self, nums: List[int], target: int) -> int:\n mod = 10**9 + 7\n nums.sort()\n n = len(nums)\n left, right = 0,n-1\n ans = 0 \n while left <= right:\n if nums[left] + nums[right]> target:\n right -= 1\n else:\n ans += pow(2, right-left, mod)\n left +=1\n return ans%mod\n``` | 1 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[3,5,6,7\], target = 9
**Output:** 4
**Explanation:** There are 4 subsequences that satisfy the condition.
\[3\] -> Min value + max value <= target (3 + 3 <= 9)
\[3,5\] -> (3 + 5 <= 9)
\[3,5,6\] -> (3 + 6 <= 9)
\[3,6\] -> (3 + 6 <= 9)
**Example 2:**
**Input:** nums = \[3,3,6,8\], target = 10
**Output:** 6
**Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
\[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\]
**Example 3:**
**Input:** nums = \[2,3,3,4,6,7\], target = 12
**Output:** 61
**Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]).
Number of valid subsequences (63 - 2 = 61).
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 106`
* `1 <= target <= 106` | null |
1498. Number of Subsequences That Satisfy the Given Sum Condition.py | number-of-subsequences-that-satisfy-the-given-sum-condition | 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 numSubseq(self, nums: List[int], target: int) -> int:\n mod = 10**9 + 7\n nums.sort()\n n = len(nums)\n left, right = 0,n-1\n ans = 0 \n while left <= right:\n if nums[left] + nums[right]> target:\n right -= 1\n else:\n ans += pow(2, right-left, mod)\n left +=1\n return ans%mod\n``` | 1 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints.
Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** 5
**Explanation:** The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 3
**Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
**Example 3:**
**Input:** n = 30, k = 7
**Output:** 796297179
**Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
**Constraints:**
* `2 <= n <= 1000`
* `1 <= k <= n-1` | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
Python 3 Solution || Two Pointer || Easy to understand | number-of-subsequences-that-satisfy-the-given-sum-condition | 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- O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n) \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n mod = 10**9 +7\n result = 0\n nums.sort()\n left,right = 0, len(nums) - 1\n while left <= right:\n if nums[left] + nums[right] <= target:\n result = (result+ pow(2, right-left,mod))% mod\n left += 1\n else:\n right -= 1\n return result\n``` | 1 | You are given an array of integers `nums` and an integer `target`.
Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[3,5,6,7\], target = 9
**Output:** 4
**Explanation:** There are 4 subsequences that satisfy the condition.
\[3\] -> Min value + max value <= target (3 + 3 <= 9)
\[3,5\] -> (3 + 5 <= 9)
\[3,5,6\] -> (3 + 6 <= 9)
\[3,6\] -> (3 + 6 <= 9)
**Example 2:**
**Input:** nums = \[3,3,6,8\], target = 10
**Output:** 6
**Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
\[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\]
**Example 3:**
**Input:** nums = \[2,3,3,4,6,7\], target = 12
**Output:** 61
**Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]).
Number of valid subsequences (63 - 2 = 61).
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 106`
* `1 <= target <= 106` | null |
Python 3 Solution || Two Pointer || Easy to understand | number-of-subsequences-that-satisfy-the-given-sum-condition | 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- O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n) \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numSubseq(self, nums: List[int], target: int) -> int:\n mod = 10**9 +7\n result = 0\n nums.sort()\n left,right = 0, len(nums) - 1\n while left <= right:\n if nums[left] + nums[right] <= target:\n result = (result+ pow(2, right-left,mod))% mod\n left += 1\n else:\n right -= 1\n return result\n``` | 1 | Given `n` points on a 1-D plane, where the `ith` point (from `0` to `n-1`) is at `x = i`, find the number of ways we can draw **exactly** `k` **non-overlapping** line segments such that each segment covers two or more points. The endpoints of each segment must have **integral coordinates**. The `k` line segments **do not** have to cover all `n` points, and they are **allowed** to share endpoints.
Return _the number of ways we can draw_ `k` _non-overlapping line segments__._ Since this number can be huge, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 4, k = 2
**Output:** 5
**Explanation:** The two line segments are shown in red and blue.
The image above shows the 5 different ways {(0,2),(2,3)}, {(0,1),(1,3)}, {(0,1),(2,3)}, {(1,2),(2,3)}, {(0,1),(1,2)}.
**Example 2:**
**Input:** n = 3, k = 1
**Output:** 3
**Explanation:** The 3 ways are {(0,1)}, {(0,2)}, {(1,2)}.
**Example 3:**
**Input:** n = 30, k = 7
**Output:** 796297179
**Explanation:** The total number of possible ways to draw 7 line segments is 3796297200. Taking this number modulo 109 + 7 gives us 796297179.
**Constraints:**
* `2 <= n <= 1000`
* `1 <= k <= n-1` | Sort the array nums. Use two pointers approach: Given an index i (choose it as the minimum in a subsequence) find the maximum j where j ≥ i and nums[i] +nums[j] ≤ target. Count the number of subsequences. |
[Python3] heap | max-value-of-equation | 0 | 1 | Algo\nSince the target to be optimized is `yi + yj + |xi - xj|` (aka `xj + yj + yi - xi` given `j > i`), the value of interest is `yi - xi`. While we loop through the array with index `j`, we want to keep track of the largest `yi - xi` under the constraint that `xj - xi <= k`. \n\nWe could use a priority queue for this purpose. Since Python provides min-heap, we would stuff `(xj - yj, xj)` to the queue such that top of the queue has points with largest `y-x` and `x` could be used to verify if the constraint is met. \n\n```\nclass Solution:\n def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:\n ans = -inf\n hp = [] \n for xj, yj in points:\n while hp and xj - hp[0][1] > k: heappop(hp)\n if hp: \n ans = max(ans, xj + yj - hp[0][0])\n heappush(hp, (xj-yj, xj))\n return ans \n``` | 9 | You are given an array `points` containing the coordinates of points on a 2D plane, sorted by the x-values, where `points[i] = [xi, yi]` such that `xi < xj` for all `1 <= i < j <= points.length`. You are also given an integer `k`.
Return _the maximum value of the equation_ `yi + yj + |xi - xj|` where `|xi - xj| <= k` and `1 <= i < j <= points.length`.
It is guaranteed that there exists at least one pair of points that satisfy the constraint `|xi - xj| <= k`.
**Example 1:**
**Input:** points = \[\[1,3\],\[2,0\],\[5,10\],\[6,-10\]\], k = 1
**Output:** 4
**Explanation:** The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.
**Example 2:**
**Input:** points = \[\[0,0\],\[3,0\],\[9,2\]\], k = 3
**Output:** 3
**Explanation:** Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.
**Constraints:**
* `2 <= points.length <= 105`
* `points[i].length == 2`
* `-108 <= xi, yi <= 108`
* `0 <= k <= 2 * 108`
* `xi < xj` for all `1 <= i < j <= points.length`
* `xi` form a strictly increasing sequence. | Keep track of the engineers by their efficiency in decreasing order. Starting from one engineer, to build a team, it suffices to bring K-1 more engineers who have higher efficiencies as well as high speeds. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.