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 |
---|---|---|---|---|---|---|---|
Python3||Beats 95.1% || Easy beginner solution | largest-number-at-least-twice-of-others | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n nums1 = sorted(nums)\n if nums1[len(nums1)-1]>= 2*nums1[len(nums1)-2]:\n for i in range(len(nums)):\n if nums[i] == nums1[len(nums1)-1]:\n return i\n break\n else:\n return -1\n```\n\n | 4 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Python 1-liner. Explained | shortest-completing-word | 0 | 1 | # Approach\nNormalize plate as `p`:\n1. lowercase\n2. filter out all non-letters\n3. build a Counter for easy "contain all" tests\n\nFind the minimum word by length considering only ones that matches criteria (p is lower or equalt Counter(word)).\n\nTo combine both steps into one line laverage:\n1. walrus operator (aka Assignment Expression, see PEP 572)\n2. fact that: `truthy_val and foo` gives `foo`\n\n`return p:=blablah and min(foo bar using p)`\nreturns the `min(...)`\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 shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n return (p:=Counter([c for c in licensePlate.lower() if c.isalpha()])) and min([w for w in words if Counter(w) >= p], key=len)\n\n``` | 1 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Python 1-liner. Explained | shortest-completing-word | 0 | 1 | # Approach\nNormalize plate as `p`:\n1. lowercase\n2. filter out all non-letters\n3. build a Counter for easy "contain all" tests\n\nFind the minimum word by length considering only ones that matches criteria (p is lower or equalt Counter(word)).\n\nTo combine both steps into one line laverage:\n1. walrus operator (aka Assignment Expression, see PEP 572)\n2. fact that: `truthy_val and foo` gives `foo`\n\n`return p:=blablah and min(foo bar using p)`\nreturns the `min(...)`\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 shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n return (p:=Counter([c for c in licensePlate.lower() if c.isalpha()])) and min([w for w in words if Counter(w) >= p], key=len)\n\n``` | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
748: Solution with step by step explanation | shortest-completing-word | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nlicense_chars = [char.lower() for char in licensePlate if char.isalpha()]\n```\nUsing a list comprehension, we loop through each character in the license Plate.\nWe only consider the character if it\'s an alphabet using the condition char.isalpha().\nConvert the character to lowercase using char.lower() since the problem states that the match is case-insensitive.\n\n```\nlicense_count = Counter(license_chars)\n```\n\nThe Counter is a container provided by Python\'s collections module that counts the occurrence of each item in a list.\nHere, we use it to count how many times each character appears in license_chars.\n\n```\nwords.sort(key=len)\n```\n\nWe want to return the shortest completing word. To optimize the search, we sort the words list by length so we process shorter words first.\n\n```\nfor word in words:\n word_count = Counter(word)\n if all(word_count[char] >= license_count[char] for char in license_count):\n return word\n```\nFor each word in the sorted words list, we calculate the character frequency using Counter.\nWe then check if this word contains all the required characters in the necessary quantities using the all() function combined with a generator expression.\nIf a word meets the criteria, it\'s returned immediately. Since the list is sorted by length, this word is the shortest possible completing word.\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 shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n \n license_chars = [char.lower() for char in licensePlate if char.isalpha()]\n \n license_count = Counter(license_chars)\n \n words.sort(key=len)\n\n for word in words:\n word_count = Counter(word)\n\n if all(word_count[char] >= license_count[char] for char in license_count):\n return word\n\n``` | 1 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
748: Solution with step by step explanation | shortest-completing-word | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nlicense_chars = [char.lower() for char in licensePlate if char.isalpha()]\n```\nUsing a list comprehension, we loop through each character in the license Plate.\nWe only consider the character if it\'s an alphabet using the condition char.isalpha().\nConvert the character to lowercase using char.lower() since the problem states that the match is case-insensitive.\n\n```\nlicense_count = Counter(license_chars)\n```\n\nThe Counter is a container provided by Python\'s collections module that counts the occurrence of each item in a list.\nHere, we use it to count how many times each character appears in license_chars.\n\n```\nwords.sort(key=len)\n```\n\nWe want to return the shortest completing word. To optimize the search, we sort the words list by length so we process shorter words first.\n\n```\nfor word in words:\n word_count = Counter(word)\n if all(word_count[char] >= license_count[char] for char in license_count):\n return word\n```\nFor each word in the sorted words list, we calculate the character frequency using Counter.\nWe then check if this word contains all the required characters in the necessary quantities using the all() function combined with a generator expression.\nIf a word meets the criteria, it\'s returned immediately. Since the list is sorted by length, this word is the shortest possible completing word.\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 shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n \n license_chars = [char.lower() for char in licensePlate if char.isalpha()]\n \n license_count = Counter(license_chars)\n \n words.sort(key=len)\n\n for word in words:\n word_count = Counter(word)\n\n if all(word_count[char] >= license_count[char] for char in license_count):\n return word\n\n``` | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Python Solution || Beginner Friendly | shortest-completing-word | 0 | 1 | # Code\n```\nclass Solution:\n def wordCheck(self, lis: List[str],word: str)-> int:\n temp=list(lis)\n for i in word:\n if i in temp:\n temp.remove(i)\n if len(temp)==0:\n return 1\n return 0\n \n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n lis=[]\n minLen=inf\n res=""\n for i in licensePlate:\n if (i>="A" and i<="Z") or (i>=\'a\' and i<=\'z\'):\n lis.append(i.lower())\n for i in words:\n if(Solution.wordCheck(self,lis,i)):\n if minLen>len(i):\n minLen=len(i)\n res=i\n return res\n \n``` | 1 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Python Solution || Beginner Friendly | shortest-completing-word | 0 | 1 | # Code\n```\nclass Solution:\n def wordCheck(self, lis: List[str],word: str)-> int:\n temp=list(lis)\n for i in word:\n if i in temp:\n temp.remove(i)\n if len(temp)==0:\n return 1\n return 0\n \n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n lis=[]\n minLen=inf\n res=""\n for i in licensePlate:\n if (i>="A" and i<="Z") or (i>=\'a\' and i<=\'z\'):\n lis.append(i.lower())\n for i in words:\n if(Solution.wordCheck(self,lis,i)):\n if minLen>len(i):\n minLen=len(i)\n res=i\n return res\n \n``` | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Python | Easy Solution✅ | shortest-completing-word | 0 | 1 | ```\ndef shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n # removing digit and space from licensePlate\n licensePlate = \'\'.join([i.lower() for i in licensePlate if i.isalpha()])\n # sorting words array based on length of item\n words = sorted(words, key=len)\n for word in words:\n for i in range(len(licensePlate)):\n if word.count(licensePlate[i]) < licensePlate.count(licensePlate[i]):\n break\n if i == len(licensePlate)-1:\n return word\n``` | 12 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Python | Easy Solution✅ | shortest-completing-word | 0 | 1 | ```\ndef shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n # removing digit and space from licensePlate\n licensePlate = \'\'.join([i.lower() for i in licensePlate if i.isalpha()])\n # sorting words array based on length of item\n words = sorted(words, key=len)\n for word in words:\n for i in range(len(licensePlate)):\n if word.count(licensePlate[i]) < licensePlate.count(licensePlate[i]):\n break\n if i == len(licensePlate)-1:\n return word\n``` | 12 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Python Elegant & Short | Two lines | Counter | shortest-completing-word | 0 | 1 | \tfrom collections import Counter\n\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(m*max(n,k))\n\t\tMemory: O(n+k)\n\n\t\tn - length of letters in license_plate\n\t\tm - length of words\n\t\tk - length of each word in words\n\t\t"""\n\n\t\tdef shortestCompletingWord(self, license_plate: str, words: List[str]) -> str:\n\t\t\tletters = Counter(ltr.lower() for ltr in license_plate if ltr.isalpha())\n\t\t\treturn min((word for word in words if not letters - Counter(word)), key=len)\n | 11 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Python Elegant & Short | Two lines | Counter | shortest-completing-word | 0 | 1 | \tfrom collections import Counter\n\n\n\tclass Solution:\n\t\t"""\n\t\tTime: O(m*max(n,k))\n\t\tMemory: O(n+k)\n\n\t\tn - length of letters in license_plate\n\t\tm - length of words\n\t\tk - length of each word in words\n\t\t"""\n\n\t\tdef shortestCompletingWord(self, license_plate: str, words: List[str]) -> str:\n\t\t\tletters = Counter(ltr.lower() for ltr in license_plate if ltr.isalpha())\n\t\t\treturn min((word for word in words if not letters - Counter(word)), key=len)\n | 11 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Python3 very simple Explanation | shortest-completing-word | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n- find all hidden alphabets in licensePlate and convert them to lowercase\n- now iterate through words array\n- if all alphabets from licensePlate in word and length of current word is minimum then save index of word\n- flag is used to check if any of alphabets not in word then move forward without checking minimum\n\n# Code\n```\nclass Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n hidden = []\n def hidden_alphabets():\n for i in range(len(licensePlate)):\n if not licensePlate[i].isdigit():\n if licensePlate[i] != " ": \n hidden.append(licensePlate[i].lower())\n hidden_alphabets()\n index = -1\n minimum = float("inf")\n flag = False\n for i,word in enumerate(words):\n flag = False\n for one_hidden_alphabet in hidden:\n if one_hidden_alphabet in word:\n word = word.replace(one_hidden_alphabet,\'\', 1)\n else:\n flag = True\n break\n if minimum > len(word) and not flag:\n minimum = len(word)\n index = i \n return words[index]\n``` | 1 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Python3 very simple Explanation | shortest-completing-word | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n- find all hidden alphabets in licensePlate and convert them to lowercase\n- now iterate through words array\n- if all alphabets from licensePlate in word and length of current word is minimum then save index of word\n- flag is used to check if any of alphabets not in word then move forward without checking minimum\n\n# Code\n```\nclass Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n hidden = []\n def hidden_alphabets():\n for i in range(len(licensePlate)):\n if not licensePlate[i].isdigit():\n if licensePlate[i] != " ": \n hidden.append(licensePlate[i].lower())\n hidden_alphabets()\n index = -1\n minimum = float("inf")\n flag = False\n for i,word in enumerate(words):\n flag = False\n for one_hidden_alphabet in hidden:\n if one_hidden_alphabet in word:\n word = word.replace(one_hidden_alphabet,\'\', 1)\n else:\n flag = True\n break\n if minimum > len(word) and not flag:\n minimum = len(word)\n index = i \n return words[index]\n``` | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Solution | shortest-completing-word | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n string shortestCompletingWord(string licensePlate, vector<string>& words) {\n int m = licensePlate.length();\n int n = words.size();\n\n int hashSize = 26;\n int i = 0;\n int *hash1 = new int[hashSize];\n int *hash2 = new int[hashSize];\n string res = "";\n\n getLetHash(licensePlate, hash1, hashSize);\n\n for (string &word : words) {\n getLetHash(word, hash2, hashSize);\n\n for (i = 0; i < hashSize; ++i) {\n if (hash2[i] < hash1[i]) {\n break;\n }\n }\n if (i == hashSize && (res.empty() || word.length() < res.length())) {\n res = word;\n }\n }\n return res;\n }\n void getLetHash(string &s, int *hash, int hashSize) {\n memset(hash, 0, sizeof(int) * hashSize);\n for (char c : s) {\n if (isLet(c)) {\n ++hash[toLow(c) - \'a\'];\n }\n }\n }\n bool isLet(char c) {\n return (c >= \'a\' && c <= \'z\') || (c >= \'A\' && c <= \'Z\');\n }\n char toLow(char c) {\n if (c >= \'A\' && c <= \'Z\') {\n c += \'a\' - \'A\';\n }\n return c;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n licensePlate = licensePlate.lower()\n lp_letters = []\n for i in licensePlate:\n if i.isalpha():\n lp_letters.append(i)\n\n words = sorted(words, key=len)\n for w in words:\n for i in range(len(lp_letters)):\n if w.count(lp_letters[i]) < lp_letters.count(lp_letters[i]):\n break\n \n if i == len(lp_letters) - 1:\n return w\n```\n\n```Java []\nclass Solution {\n public String shortestCompletingWord(String licensePlate, String[] words) {\n int[] count = new int[26];\n for (char c:licensePlate.toCharArray()){\n if (c>=\'a\'&& c<=\'z\')\n count[c-\'a\']++;\n else if (c>=\'A\' && c<=\'Z\')\n count[c-\'A\']++;\n }\n int len = Integer.MAX_VALUE;\n String res = "";\n for (String s:words){\n if (s.length()<len && isComp(s, count)){\n res = s;\n len = s.length();\n }\n }\n return res;\n }\n private boolean isComp(String s, int[] count){\n int[] curr = new int[26];\n for (char c:s.toCharArray())\n curr[c-\'a\']++;\n \n for (int i=0; i<curr.length; i++){\n if (curr[i]<count[i]) return false;\n }\n return true;\n }\n}\n```\n | 2 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Solution | shortest-completing-word | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n string shortestCompletingWord(string licensePlate, vector<string>& words) {\n int m = licensePlate.length();\n int n = words.size();\n\n int hashSize = 26;\n int i = 0;\n int *hash1 = new int[hashSize];\n int *hash2 = new int[hashSize];\n string res = "";\n\n getLetHash(licensePlate, hash1, hashSize);\n\n for (string &word : words) {\n getLetHash(word, hash2, hashSize);\n\n for (i = 0; i < hashSize; ++i) {\n if (hash2[i] < hash1[i]) {\n break;\n }\n }\n if (i == hashSize && (res.empty() || word.length() < res.length())) {\n res = word;\n }\n }\n return res;\n }\n void getLetHash(string &s, int *hash, int hashSize) {\n memset(hash, 0, sizeof(int) * hashSize);\n for (char c : s) {\n if (isLet(c)) {\n ++hash[toLow(c) - \'a\'];\n }\n }\n }\n bool isLet(char c) {\n return (c >= \'a\' && c <= \'z\') || (c >= \'A\' && c <= \'Z\');\n }\n char toLow(char c) {\n if (c >= \'A\' && c <= \'Z\') {\n c += \'a\' - \'A\';\n }\n return c;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n licensePlate = licensePlate.lower()\n lp_letters = []\n for i in licensePlate:\n if i.isalpha():\n lp_letters.append(i)\n\n words = sorted(words, key=len)\n for w in words:\n for i in range(len(lp_letters)):\n if w.count(lp_letters[i]) < lp_letters.count(lp_letters[i]):\n break\n \n if i == len(lp_letters) - 1:\n return w\n```\n\n```Java []\nclass Solution {\n public String shortestCompletingWord(String licensePlate, String[] words) {\n int[] count = new int[26];\n for (char c:licensePlate.toCharArray()){\n if (c>=\'a\'&& c<=\'z\')\n count[c-\'a\']++;\n else if (c>=\'A\' && c<=\'Z\')\n count[c-\'A\']++;\n }\n int len = Integer.MAX_VALUE;\n String res = "";\n for (String s:words){\n if (s.length()<len && isComp(s, count)){\n res = s;\n len = s.length();\n }\n }\n return res;\n }\n private boolean isComp(String s, int[] count){\n int[] curr = new int[26];\n for (char c:s.toCharArray())\n curr[c-\'a\']++;\n \n for (int i=0; i<curr.length; i++){\n if (curr[i]<count[i]) return false;\n }\n return true;\n }\n}\n```\n | 2 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
shortest-completing-word | shortest-completing-word | 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 shortestCompletingWord(self, t: str, s: List[str]) -> str:\n a = [i for i in t]\n l = []\n p = []\n c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\n for i in a:\n if i in c:\n l.append(i.lower())\n # print(l)\n for i in s:\n count = 0\n t = [j for j in i]\n f = list(set(t))\n for k in l:\n if k in f and t.count(k)>= l.count(k):\n count+=1\n elif t.count(k) < l.count(k):\n break \n if count==len(l):\n p.append(i)\n p.sort(key=len)\n return (p[0])\n \n\n\n\n\n \n \n``` | 1 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
shortest-completing-word | shortest-completing-word | 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 shortestCompletingWord(self, t: str, s: List[str]) -> str:\n a = [i for i in t]\n l = []\n p = []\n c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"\n for i in a:\n if i in c:\n l.append(i.lower())\n # print(l)\n for i in s:\n count = 0\n t = [j for j in i]\n f = list(set(t))\n for k in l:\n if k in f and t.count(k)>= l.count(k):\n count+=1\n elif t.count(k) < l.count(k):\n break \n if count==len(l):\n p.append(i)\n p.sort(key=len)\n return (p[0])\n \n\n\n\n\n \n \n``` | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Python3 Simple solution without Dictionary | shortest-completing-word | 0 | 1 | ```\nclass Solution:\n def shortestCompletingWord(self, P: str, words: List[str]) -> str:\n alphs=""\n res="" \n for p in P:\n if p.isalpha():\n alphs+=p.lower()\n for word in words: \n if all(alphs.count(alphs[i]) <= word.count(alphs[i]) for i in range(len(alphs))):\n if res=="" or len(res)>len(word):\n res=word\n \n return res\n``` | 4 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Python3 Simple solution without Dictionary | shortest-completing-word | 0 | 1 | ```\nclass Solution:\n def shortestCompletingWord(self, P: str, words: List[str]) -> str:\n alphs=""\n res="" \n for p in P:\n if p.isalpha():\n alphs+=p.lower()\n for word in words: \n if all(alphs.count(alphs[i]) <= word.count(alphs[i]) for i in range(len(alphs))):\n if res=="" or len(res)>len(word):\n res=word\n \n return res\n``` | 4 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
[Python] One-liner, The Best | shortest-completing-word | 0 | 1 | # Complexity\n- Time complexity: $$O(n|\\Sigma|)$$ for input length $$n$$ and word alphabet $$\\Sigma$$\n- Space complexity: $$O(|\\Sigma|)$$\n\nThe Best!\n\n# Code\n```py\ndef shortestCompletingWord(self, license: str, words: list[str]) -> str:\n return min((w for lic in [Counter(c.lower() for c in license if c.isalpha())]\n for w in words if not lic - Counter(w)), key=len)\n``` | 1 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
[Python] One-liner, The Best | shortest-completing-word | 0 | 1 | # Complexity\n- Time complexity: $$O(n|\\Sigma|)$$ for input length $$n$$ and word alphabet $$\\Sigma$$\n- Space complexity: $$O(|\\Sigma|)$$\n\nThe Best!\n\n# Code\n```py\ndef shortestCompletingWord(self, license: str, words: list[str]) -> str:\n return min((w for lic in [Counter(c.lower() for c in license if c.isalpha())]\n for w in words if not lic - Counter(w)), key=len)\n``` | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Simple & Clean | shortest-completing-word | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n characters = "".join([char for char in licensePlate if char.isalpha()]).lower()\n result = \'\'\n\n for word in words:\n isValid = len(result) == 0 or len(word) < len(result)\n\n if(isValid):\n for character in characters:\n if word.count(character) < characters.count(character):\n isValid = False\n \n if(isValid):\n result = word\n \n return result\n``` | 0 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
Simple & Clean | shortest-completing-word | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:\n characters = "".join([char for char in licensePlate if char.isalpha()]).lower()\n result = \'\'\n\n for word in words:\n isValid = len(result) == 0 or len(word) < len(result)\n\n if(isValid):\n for character in characters:\n if word.count(character) < characters.count(character):\n isValid = False\n \n if(isValid):\n result = word\n \n return result\n``` | 0 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
traverse words and compare | shortest-completing-word | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGet alphas from licencePlate and match with words list.\ncheck for duplicates and match\nget the minimum length.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGet alphas from licencePlate and match with words list.\ncheck for duplicates and match\nget the minimum length.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def shortestCompletingWord(self, lp,words):\n words_res=[]\n lp=\'\'.join([char for char in lp.casefold() if char.isalpha()])\n for word in words:\n for char in lp:\n if char not in word:\n break\n else:\n words_res.append(word)\n md={char:lp.count(char) for char in lp if lp.count(char)>1}\n result=[]\n if md:\n for word in words_res:\n for k,v in md.items():\n if word.count(k)>=v:\n result.append(word)\n else:\n result=words_res\n return min(result,key=len)\n \n``` | 0 | Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`.
A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more.
For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`.
Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`.
**Example 1:**
**Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\]
**Output:** "steps "
**Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'.
"step " contains 't' and 'p', but only contains 1 's'.
"steps " contains 't', 'p', and both 's' characters.
"stripe " is missing an 's'.
"stepple " is missing an 's'.
Since "steps " is the only word containing all the letters, that is the answer.
**Example 2:**
**Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\]
**Output:** "pest "
**Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3.
**Constraints:**
* `1 <= licensePlate.length <= 7`
* `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`.
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 15`
* `words[i]` consists of lower case English letters. | Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`.
Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`.
Otherwise, we should return `maxIndex`. |
traverse words and compare | shortest-completing-word | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGet alphas from licencePlate and match with words list.\ncheck for duplicates and match\nget the minimum length.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nGet alphas from licencePlate and match with words list.\ncheck for duplicates and match\nget the minimum length.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution:\n def shortestCompletingWord(self, lp,words):\n words_res=[]\n lp=\'\'.join([char for char in lp.casefold() if char.isalpha()])\n for word in words:\n for char in lp:\n if char not in word:\n break\n else:\n words_res.append(word)\n md={char:lp.count(char) for char in lp if lp.count(char)>1}\n result=[]\n if md:\n for word in words_res:\n for k,v in md.items():\n if word.count(k)>=v:\n result.append(word)\n else:\n result=words_res\n return min(result,key=len)\n \n``` | 0 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Solution | contain-virus | 1 | 1 | ```C++ []\nint mp[2652], *zp[2652], zc[2652], step, mk;\n\nint dfs(int *p) {\n *p = 2;\n int res = 0;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n int v = *nb;\n if (v == mk || v > 1) continue;\n if (v <= 0) *nb = mk, ++res; else res += dfs(nb);\n }\n return res;\n}\nint dfs2(int *p) {\n *p = 1000;\n int res = 0;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n int v = *nb;\n if (v == 2) res += dfs2(nb); else if (v <= 0) ++res, *nb = 0;\n }\n return res;\n}\nvoid dfs3(int *p) {\n *p = 1;\n for (int *nb : {p-step, p-1, p+1, p+step}) {\n int v = *nb;\n if (v == 2) dfs3(nb); else if (v <= 0) *nb = 1;\n }\n}\nclass Solution {\npublic:\n int containVirus(vector<vector<int>>& isInfected) {\n step = isInfected[0].size() + 1; mk = 0;\n {\n int *p = mp+step;\n fill(mp, p, 1000);\n for (const auto &r : isInfected) {\n for (int x : r) *p++ = x;\n *p++ = 1000;\n }\n fill(p, p+step, 1000);\n }\n int *lo = mp+step, *hi = lo + step*isInfected.size(), res = 0;\n while(1) {\n int nb = 0;\n for (int *p = lo; p != hi; ++p) if (*p == 1) zp[nb] = p, --mk, zc[nb++] = dfs(p);\n if (nb == 0) break;\n\n int best = 0;\n for (int i = 1; i < nb; ++i) if (zc[i] > zc[best]) best = i;\n if (!zc[best]) break;\n res += dfs2(zp[best]);\n\n for (int *p = lo; p != hi; ++p) if (*p == 2) dfs3(p);\n }\n return res;\n }\n};\n```\n\n```Python3 []\nimport math\n\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n\n def traverse_infected(r,c):\n\n q = [(r,c)]\n infected_cells = set(q)\n perimeter = 0\n bordering_cells = set()\n\n while len(q) > 0:\n next_iter = []\n\n for r,c in q:\n neighbors = [(r+1,c),(r-1,c),(r,c+1),(r,c-1)]\n for adj_r,adj_c in neighbors:\n if m > adj_r >= 0 and n > adj_c >= 0:\n if isInfected[adj_r][adj_c] == 1:\n if (adj_r,adj_c) not in infected_cells:\n infected_cells.add((adj_r,adj_c))\n next_iter.append((adj_r,adj_c))\n elif isInfected[adj_r][adj_c] == 0:\n perimeter += 1\n bordering_cells.add((adj_r,adj_c))\n q = next_iter\n \n return infected_cells,bordering_cells,perimeter\n \n m,n = len(isInfected),len(isInfected[0])\n\n walls = 0\n while 1:\n all_infected_cells = set()\n\n most_threatening = (0, None)\n\n regions_this_iter = []\n i = 0\n for r in range(m):\n for c in range(n):\n if isInfected[r][c] == 1 and (r,c) not in all_infected_cells:\n infected_region,region_borders,perimeter = traverse_infected(r,c)\n\n regions_this_iter.append((infected_region,region_borders,perimeter))\n\n if len(region_borders) > most_threatening[0]:\n most_threatening = (len(region_borders), i)\n \n all_infected_cells.update(infected_region)\n i += 1\n \n if most_threatening[0] != 0:\n walls += regions_this_iter[most_threatening[1]][2]\n for r,c in regions_this_iter[most_threatening[1]][0]:\n isInfected[r][c] = 2\n \n for i in range(len(regions_this_iter)):\n if i != most_threatening[1]:\n for r,c in regions_this_iter[i][1]:\n isInfected[r][c] = 1\n else:\n break\n return walls\n```\n\n```Java []\nclass Solution {\n class Region {\n Set<Integer> infected = new HashSet<>();\n Set<Integer> unInfected = new HashSet<>();\n int walls = 0;\n } \n public int containVirus(int[][] isInfected) {\n int ans = 0;\n int re = isInfected.length;\n int ce = isInfected[0].length;\n\n while (true) {\n List<Region> holder = new ArrayList<>();\n boolean[][] v = new boolean[re][ce];\n for (int r = 0; r < re; r++) {\n for (int c = 0; c < ce; c++) {\n if (isInfected[r][c] == 1 && !v[r][c]) {\n Region region = new Region();\n getRegion(isInfected, region, re, ce, v, r, c);\n holder.add(region);\n }\n }\n }\n int indexOfMaxUnInfected = 0;\n int sizeOfMaxUnInfected = 0;\n for (int i = 0; i < holder.size(); i++) {\n Region region = holder.get(i);\n\n if (region.unInfected.size() > sizeOfMaxUnInfected) {\n sizeOfMaxUnInfected = region.unInfected.size();\n indexOfMaxUnInfected = i;\n }\n }\n if (holder.size() == 0) {\n break;\n }\n Set<Integer> maxSet = holder.get(indexOfMaxUnInfected).infected;\n for (int rowCol : maxSet) {\n int r = rowCol / ce;\n int c = rowCol % ce;\n isInfected[r][c] = 2;\n }\n ans += holder.get(indexOfMaxUnInfected).walls;\n for (int i = 0; i < holder.size(); i++) {\n \n if (i == indexOfMaxUnInfected) {\n continue;\n }\n Region region = holder.get(i);\n Set<Integer> unInfected = region.unInfected;\n\n for (int rowCol : unInfected) {\n int r = rowCol / ce;\n int c = rowCol % ce;\n isInfected[r][c] = 1;\n }\n }\n }\n return ans;\n }\n int[][] dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n private void getRegion(int[][] isInfected, Region region, int re, int ce, \n boolean[][] v, int r, int c) {\n if (r < 0 || c < 0 || r == re || c == ce || isInfected[r][c] == 2) {\n return;\n }\n if (isInfected[r][c] == 1) {\n if (v[r][c]) {\n return;\n }\n region.infected.add(r * ce + c);\n }\n if (isInfected[r][c] == 0) {\n region.unInfected.add(r * ce + c);\n region.walls++;\n return;\n }\n v[r][c] = true;\n for (int[] dir : dirs) {\n int nr = r + dir[0];\n int nc = c + dir[1];\n getRegion(isInfected, region, re, ce, v, nr, nc);\n }\n }\n}\n```\n | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
749: Solution with step by step explanation | contain-virus | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nm, n = len(mat), len(mat[0])\nDIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n```\nm and n capture the dimensions of the matrix.\nDIRECTIONS is a list of four possible moves from a cell: up, down, left, and right.\n\n```\ndef dfs(i, j, visited):\n```\n\nThis function explores an infected region starting from cell (i, j) and computes:\n\nThe set of uninfected cells that can be infected by this region.\nThe number of walls needed to quarantine this region.\nThe function uses a DFS strategy and recursively explores all connected infected cells.\n\n```\ndef quarantine(i, j):\n```\n\nThis function sets all cells in an infected region (starting from (i, j)) to a state \'2\', indicating that they have been quarantined.\n\nMain Loop:\nThe main logic resides in a loop that runs until all infected regions are quarantined.\n\nvisited keeps track of the cells that have been already processed.\nregions stores details about each infected region (set of cells it can infect, number of walls to quarantine it, and a representative cell).\nEach round:\n\nFind all infected regions and the cells they can infect.\nChoose the region that can infect the maximum number of cells and quarantine it.\nLet the other regions infect their neighboring cells.\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 containVirus(self, mat: List[List[int]]) -> int:\n m, n = len(mat), len(mat[0])\n DIRECTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n \n def dfs(i, j, visited):\n if not (0 <= i < m and 0 <= j < n) or (i, j) in visited:\n return set(), 0\n if mat[i][j] == 2:\n return set(), 0\n elif mat[i][j] == 0:\n return {(i, j)}, 1\n \n visited.add((i, j))\n infected, walls = set(), 0\n for dx, dy in DIRECTIONS:\n ni, nj = i + dx, j + dy\n next_infected, next_walls = dfs(ni, nj, visited)\n infected |= next_infected\n walls += next_walls\n return infected, walls\n \n def quarantine(i, j):\n if 0 <= i < m and 0 <= j < n and mat[i][j] == 1:\n mat[i][j] = 2\n for dx, dy in DIRECTIONS:\n quarantine(i + dx, j + dy)\n \n ans = 0\n while True:\n visited, regions = set(), []\n for i in range(m):\n for j in range(n):\n if mat[i][j] == 1 and (i, j) not in visited:\n infected, walls = dfs(i, j, visited)\n if infected:\n regions.append((infected, walls, (i, j)))\n \n if not regions:\n break\n \n regions.sort(key=lambda x: (-len(x[0]), x[1]))\n max_infected, max_walls, start = regions[0]\n ans += max_walls\n quarantine(*start)\n \n for region in regions[1:]:\n for i, j in region[0]:\n mat[i][j] = 1\n \n return ans\n\n``` | 2 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Pyhon Easy Solution || DFS || Time O(m*n*max(m , n)) || Faster | contain-virus | 0 | 1 | ```\n class Solution:\n def containVirus(self, mat: List[List[int]]) -> int:\n m,n = len(mat),len(mat[0])\n\n def dfs(i,j,visited,nextInfected): # return no. of walls require to quarantined dfs area\n if 0<=i<m and 0<=j<n and (i,j) not in visited:\n if mat[i][j]==2: # Already quarantined cell\n return 0\n if mat[i][j]==0:\n nextInfected.add((i,j)) # add cell which will be infected next day\n return 1 # require one wall to quarantined cell from one side\n \n else:\n visited.add((i,j))\n return dfs(i-1,j,visited,nextInfected) + dfs(i+1,j,visited,nextInfected) + dfs(i,j-1,visited,nextInfected) + dfs(i,j+1,visited,nextInfected) # traverse all four direction\n else:\n return 0\n\t\t\t\t\n ans = 0 \n while True: # this loop running "how many days we should installing the walls" times\n # For every day check which area infect more cells\n visited = set() # Using in dfs\n All_nextinfect = set()\n stop , walls = set(),0 # here stop store the indices of maximum no. of cells in which we stop spreading of virus this day\n \n for i in range(m):\n for j in range(n):\n if mat[i][j]==1 and (i,j) not in visited:\n nextInfected = set()\n a = dfs(i,j,visited,nextInfected)\n \n if len(stop)<len(nextInfected):\n All_nextinfect = All_nextinfect | stop # leave previous saved area from virus\n stop = nextInfected # pick new area which we want to save\n walls = a # require walls\n p,q = i,j # starting position(indices) of this area\n else:\n All_nextinfect = All_nextinfect | nextInfected \n \n if not stop : # if our job is done i.e. No cell will be infect Later\n break\n ans += walls # add new walls installed this day\n \n # change each cell value to 2 which will be covered by quarantined area\n def fun(p,q):\n if 0<=p<m and 0<=q<n and mat[p][q]==1:\n mat[p][q]=2\n fun(p+1,q)\n fun(p-1,q)\n fun(p,q-1)\n fun(p,q+1)\n fun(p,q) # start dfs from start point of quarantined area\n \n for a,b in All_nextinfect: # set new infected cell value = 1 for iterating next day\n mat[a][b] = 1\n\n return ans # Final answer \n```\t\t\n\t\t\n\t\t\n**if you like the solution : please Upvote :)**\n\t\t\n\t\t\n\t\t\n\t\t\n \n | 8 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
[Python3] brute-force | contain-virus | 0 | 1 | \n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n m, n = len(isInfected), len(isInfected[0])\n ans = 0 \n while True: \n regions = []\n fronts = []\n walls = []\n seen = set()\n for i in range(m): \n for j in range(n): \n if isInfected[i][j] == 1 and (i, j) not in seen: \n seen.add((i, j))\n stack = [(i, j)]\n regions.append([(i, j)])\n fronts.append(set())\n walls.append(0)\n while stack: \n r, c = stack.pop()\n for rr, cc in (r-1, c), (r, c-1), (r, c+1), (r+1, c): \n if 0 <= rr < m and 0 <= cc < n: \n if isInfected[rr][cc] == 1 and (rr, cc) not in seen: \n seen.add((rr, cc))\n stack.append((rr, cc))\n regions[-1].append((rr, cc))\n elif isInfected[rr][cc] == 0: \n fronts[-1].add((rr, cc))\n walls[-1] += 1\n if not regions: break\n idx = fronts.index(max(fronts, key = len))\n ans += walls[idx]\n for i, region in enumerate(regions): \n if i == idx: \n for r, c in region: isInfected[r][c] = -1 # mark as quaranteened \n else: \n for r, c in fronts[i]: isInfected[r][c] = 1 # mark as infected \n return ans \n``` | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Another Explanation, Python3, O(R*C*max(R,C)) time and O(R*C) space, Faster than 95% | contain-virus | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThis is a pretty hard problem, there\'s a lot going on. There are a lot of considerations to make. But the idea is that the problem asks us to wall of clusters according to what happens each day/night, and explains the rules. So we simulate.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nI didn\'t come up with the solution, but thought that the existing solutions are kind of hard to read and understand what they\'re doing. So I made a `Cluster` structure and `findCluster` method to help break things up. The main loop is a lot easier to read after that.\n\nAs the problem says, for each day/night cycle:\n1. during the day, we find the cluster that threatens the most cells, then wall it off\n2. at night, the remaining cluster(s) expand by 1 in each cardinal direction\n\nSo to break it down, we need the following\n1. we need to identify all of the clusters\n2. for each cluster we need to know the cells in that cluster so we can wall it off, the adjacent healthy cells so we know how many there are, and the number of walls required to wall it off\n\nWhen we wall off a cluster, we set all of its cells to some marker value `-1`. Originally I struggled with marking off only the boundary to be more efficient. But that was making the solution too complicated so I simplified and just marked them all off.\n\nFollowing another solution, I made a little `Cluster` class that contains the details.\n\n**NOTE:** I struggled a lot initially because I tried to be fancy about unioning `Cluster`s together to avoid re-finding clusters at each step. Eventually I gave up because it was getting to complicated.\n\nTo make it work I\'d use something along the lines of union-find:\n* have an array that maps (r,c) to the index of the cluster containing it\n* have the usual findRoot and union methods of union-find to quickly unify clusters each night when they expand\n * having a set of coordinates for adjacent cells is easy to union: just merge the cells\n * to merge the number of walls, that\'s more complicated and where I started getting really confused. There\'s probably a simple expression after working through all the edge cases though\n\nIn the end, if all the complications are worked out and you only track boundary cells, the complexity of the solution problably drops to $O((R+C)*\\max(R,C))$.\n\n# Complexity\n- Time complexity: $$O(R*C*\\max(R,C)))$$\n\nI think that\'s right but I\'m not sure. The worst-case scenario is we have a bunch of isolated little clusters so we need a lot of iterations. The most iterations we will do is order $\\max(R,C)$ since clusters can\'t grow for more than that number of steps. In each iteration we do $O(R*C)$ work to find all the clusters.\n\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(R*C)$$\n\nAt worst we store every infected cell in 1 `Cluster`, and every healthy cel in 4 `Cluster`s. We also have the `visited` array with $R*C$ entries. So overall it\'s order $R*C$.\n\n# Code\n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n # ruh-roh...\n\n # each night we want to find\n # (1) all of the clusters\n # cells in the cluster\n # adjacent healthy cells\n # number of adjoining walls\n # (2) order clusters by num adjacent healthy cells\n # (3) pick cluster with most healthy cells\n\n R = len(isInfected)\n C = len(isInfected[0])\n\n class Cluster:\n def __init__(self):\n self.cells = set() # (r,c) of all infected cells in here\n self.risked = set() # (r,c) of all adjacent healthy cells\n self.walls = 0 # number of walls required to fence of this cluster\n\n def numRisked(self):\n return len(self.risked)\n\n def __repr__(self):\n return "Cluster(%i cells, %i risked, %i walls)" % (len(self.cells), len(self.risked), self.walls)\n\n fenced = -1\n\n def getCluster(i: int, j: int, visited: list[list[bool]]) -> \'Cluster\':\n cluster = Cluster()\n stack = [(i,j)]\n visited[i][j] = True\n while stack:\n (r,c) = stack.pop()\n cluster.cells.add((r,c))\n\n for dr,dc in [(-1,0), (+1,0), (0,-1), (0,+1)]:\n rr = r + dr\n cc = c + dc\n if rr >= 0 and rr < R and cc >= 0 and cc < C:\n if visited[rr][cc]:\n continue\n \n # not visited: is healthy or fenced off or infected\n if isInfected[rr][cc] == 1:\n # infected: add to stack and visited\n stack.append((rr,cc))\n visited[rr][cc] = True\n elif isInfected[rr][cc] == 0:\n # healthy\n cluster.walls += 1 # there\'s a border between (r,c) and (rr,cc)\n # print(" added wall between", (r,c), (rr,cc))\n cluster.risked.add((rr,cc))\n\n return cluster\n\n # when are we done? when there are no clusters\n # if there\'s one big cluster at the end (all infected), then number of fences will be zero because evrything is either\n # a fence for a boundary already\n\n walls = 0\n\n while True:\n clusters = []\n visited = [[False]*C for _ in range(R)]\n for r in range(R):\n for c in range(C):\n if isInfected[r][c] == 1 and not visited[r][c]:\n clusters.append(getCluster(r,c,visited))\n\n if not clusters:\n return walls\n\n # print(clusters)\n clusters.sort(key=lambda cluster: cluster.numRisked())\n\n # wall off the cluster that threatens the most cells\n walls += clusters[-1].walls\n\n # mark those cells as walled-off for the sake of later getCluster calls\n for (r,c) in clusters[-1].cells:\n isInfected[r][c] = -1\n\n # grow all other clusters\n clusters.pop()\n for cluster in clusters:\n for (r,c) in cluster.risked:\n isInfected[r][c] = 1\n``` | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Using BFS | contain-virus | 0 | 1 | # Code\n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n m, n = len(isInfected), len(isInfected[0])\n ans = 0\n while True:\n # 1. BFS\n # neighbors stores every to-spread/to-put-wall area. \n # firewalls stores the countings for every area. \n neighbors, firewalls = list(), list()\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] == 1:\n # detect the infected area \n q = deque([(i, j)])\n # index of this area\n idx = len(neighbors) + 1\n # record all cells in this to-spread/to-put-wall area\n neighbor = set()\n # count walls needed\n firewall = 0\n print(i,j,idx)\n # mark as visited\n isInfected[i][j] = -idx\n\n while q:\n x, y = q.popleft()\n for d in range(4):\n # detect around\n nx, ny = x + dirs[d][0], y + dirs[d][1]\n # ensure within the matrix\n if 0 <= nx < m and 0 <= ny < n:\n if isInfected[nx][ny] == 1:\n # update infected area\n q.append((nx, ny))\n # mark as visited\n isInfected[nx][ny] = -idx\n elif isInfected[nx][ny] == 0:\n # update counting and neighbor\n firewall += 1\n neighbor.add((nx, ny))\n\n \n \n # update neighbors and firewalls\n neighbors.append(neighbor)\n firewalls.append(firewall)\n print(neighbors)\n print(firewalls)\n\n # 2. none infected areas\n if not neighbors:\n break\n \n # 3. calculate the largest area:\n idx = 0\n for i in range(1, len(neighbors)):\n if len(neighbors[i]) > len(neighbors[idx]):\n idx = i\n \n # 4. update the ans\n ans += firewalls[idx]\n\n # if only 1 area in total, this is the final answer\n if len(neighbors) == 1:\n # return ans\n break \n \n\n # 5. mark as processed and modify the unprocessed\n print(idx)\n print(isInfected)\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] < 0:\n # unprocess\n if isInfected[i][j] != - (idx + 1):\n isInfected[i][j] = 1\n else:\n isInfected[i][j] = 2\n # 6. mark the spreaded\n for i, neighbor in enumerate(neighbors):\n if i != idx:\n # spread\n for x, y in neighbor:\n isInfected[x][y] = 1\n \n \n\n return ans\n``` | 0 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Easiest Solution | contain-virus | 1 | 1 | \n\n# Code\n``` java []\nclass Solution {\n \n private static final int[][] DIR = new int[][]{\n {1, 0}, {-1, 0}, {0, 1}, {0, -1}\n };\n \n public int containVirus(int[][] isInfected) {\n int m = isInfected.length, n = isInfected[0].length;\n int ans = 0;\n \n while( true ) {\n // infected regions, sorted desc according to the number of nearby \n // uninfected nodes\n PriorityQueue<Region> pq = new PriorityQueue<Region>();\n // already visited cells\n boolean[][] visited = new boolean[m][n];\n \n // find regions\n for(int i=0; i<m; i++) {\n for(int j=0; j<n; j++) {\n \n // if current cell is infected, and it\'s not visited\n if( isInfected[i][j] != 1 || visited[i][j] ) \n continue;\n \n // we found a new region, dfs to find all the infected\n // and uninfected cells in the current region\n Region reg = new Region();\n dfs(i, j, reg, isInfected, visited, new boolean[m][n], m, n);\n \n // if there are some uninfected nodes in this region, \n // we can contain it, so add it to priority queue\n if( reg.uninfected.size() != 0)\n pq.offer(reg);\n }\n }\n \n // if there are no regions to contain, break\n if( pq.isEmpty() )\n break;\n\n // Contain region with most uninfected nodes\n Region containReg = pq.poll();\n ans += containReg.wallsRequired;\n \n // use (2) to mark a cell as contained\n for(int[] cell : containReg.infected)\n isInfected[cell[0]][cell[1]] = 2;\n \n // Spread infection to uninfected nodes in other regions\n while( !pq.isEmpty() ) {\n Region spreadReg = pq.poll();\n \n for(int[] cell : spreadReg.uninfected)\n isInfected[cell[0]][cell[1]] = 1;\n }\n }\n return ans;\n }\n \n private void dfs(int i, int j, Region reg, int[][] grid, boolean[][] visited, boolean[][] uninfectedVis, int m, int n) {\n visited[i][j] = true;\n reg.addInfected(i, j);\n \n for(int[] dir : DIR) {\n int di = i + dir[0];\n int dj = j + dir[1];\n \n // continue, if out of bounds OR contained OR already visited\n if( di < 0 || dj < 0 || di == m || dj == n || grid[di][dj] == 2 || visited[di][dj] )\n continue;\n \n // if neighbour node is not infected\n if( grid[di][dj] == 0 ) {\n // a wall will require to stop the spread from cell (i,j) to (di, dj)\n reg.wallsRequired++;\n \n // if this uninfected node is not already visited for current region\n if( !uninfectedVis[di][dj] ) {\n uninfectedVis[di][dj] = true;\n reg.addUninfected(di, dj);\n }\n } else \n dfs(di, dj, reg, grid, visited, uninfectedVis, m, n);\n }\n }\n}\nclass Region implements Comparable<Region> {\n public List<int[]> infected;\n public List<int[]> uninfected;\n public int wallsRequired;\n \n public Region() {\n infected = new ArrayList();\n uninfected = new ArrayList();\n }\n \n public void addInfected(int row, int col) {\n infected.add(new int[]{ row, col });\n }\n \n public void addUninfected(int row, int col) {\n uninfected.add(new int[]{ row, col });\n }\n \n @Override\n public int compareTo(Region r2) {\n return Integer.compare(r2.uninfected.size(), uninfected.size());\n }\n}\n```\n```c++ []\nclass Solution {\npublic:\n int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};\n int walls=0;\n \n bool isValid(int i,int j,int m,int n,vector<vector<int>> &vis)\n {\n return (i>=0 && i<m && j>=0 && j<n && !vis[i][j]); \n }\n \n int find(int i,int j,int m,int n,vector<vector<int>>& a)\n {\n int c=0;\n \n queue<pair<int,int>> q;\n vector<vector<int>> vis(m,vector<int>(n,0));\n \n a[i][j]=2;\n q.push({i,j});\n \n while(!q.empty())\n {\n i=q.front().first;\n j=q.front().second;\n q.pop();\n \n for(int k=0;k<4;k++)\n {\n if(isValid(i+dx[k],j+dy[k],m,n,vis))\n {\n if(a[i+dx[k]][j+dy[k]]==0)\n c++;\n else if(a[i+dx[k]][j+dy[k]]==1)\n {\n a[i+dx[k]][j+dy[k]]=2;\n q.push({i+dx[k],j+dy[k]});\n }\n \n vis[i+dx[k]][j+dy[k]]=1;\n \n }\n }\n }\n \n return c;\n }\n \n void putwalls(pair<int,int> &change,int m,int n,vector<vector<int>>& a)\n {\n int i,j;\n i=change.first;\n j=change.second;\n \n queue<pair<int,int>> q;\n vector<vector<int>> vis(m,vector<int>(n,0));\n \n q.push({i,j});\n \n while(!q.empty())\n {\n i=q.front().first;\n j=q.front().second;\n a[i][j]=-1;\n q.pop();\n \n \n for(int k=0;k<4;k++)\n {\n if(isValid(i+dx[k],j+dy[k],m,n,vis))\n {\n if(a[i+dx[k]][j+dy[k]]==2)\n {\n q.push({i+dx[k],j+dy[k]});\n a[i+dx[k]][j+dy[k]]=-1;\n vis[i+dx[k]][j+dy[k]]=1; \n } \n else if(a[i+dx[k]][j+dy[k]]==0)\n walls++;\n }\n }\n }\n }\n \n void spread(int m,int n,vector<vector<int>>& a)\n {\n int i,j;\n queue<pair<int,int>> q;\n vector<vector<int>> vis(m,vector<int>(n,0));\n \n for(i=0;i<m;i++)\n {\n for(j=0;j<n;j++)\n {\n if(a[i][j]==2)\n {\n a[i][j]=1;\n q.push({i,j});\n\n }\n }\n }\n \n while(!q.empty())\n {\n i=q.front().first;\n j=q.front().second;\n q.pop();\n \n for(int k=0;k<4;k++)\n {\n if(isValid(i+dx[k],j+dy[k],m,n,vis) && a[i+dx[k]][j+dy[k]]==0)\n {\n a[i+dx[k]][j+dy[k]]=1;\n vis[i+dx[k]][j+dy[k]]=1; \n }\n }\n }\n }\n \n int containVirus(vector<vector<int>>& a) {\n int m=a.size(),n=a[0].size();\n int i,j;\n \n int infected=INT_MIN;\n pair<int,int> change;\n \n while(infected!=0)\n {\n infected=0;\n for(i=0;i<m;i++)\n {\n for(j=0;j<n;j++)\n {\n if(a[i][j]==1)\n {\n int x=find(i,j,m,n,a);\n if(x>infected)\n {\n change={i,j};\n infected=x;\n }\n }\n }\n }\n \n if(infected!=0)\n {\n putwalls(change,m,n,a);\n spread(m,n,a);\n }\n }\n \n return walls;\n }\n};\n```\n```python3 []\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n \'\'\'\n isInfected[r][c]:\n 0 : Uninfected\n 1 : Infected\n 2 : Infected & restricted\n \'\'\'\n m = len(isInfected)\n n = len(isInfected[0])\n\n borders = 0\n threatened = 0\n def dfs(r, c, id):\n nonlocal borders, threatened\n if r < 0 or r>=m or c < 0 or c>=n:\n return\n\n if isInfected[r][c] == 1:\n if visited[r][c] == 0:\n visited[r][c] = 1\n dfs(r-1, c, id)\n dfs(r+1, c, id)\n dfs(r, c-1, id)\n dfs(r, c+1, id)\n else:\n pass\n elif isInfected[r][c] == 0:\n if visited[r][c] == id:\n borders += 1\n else:\n borders += 1\n threatened += 1\n visited[r][c] = id\n \n def flood(r, c, find, repl):\n if r < 0 or r>=m or c < 0 or c>=n or isInfected[r][c] != find:\n return\n isInfected[r][c] = repl\n flood(r-1, c, find, repl)\n flood(r+1, c, find, repl)\n flood(r, c-1, find, repl)\n flood(r, c+1, find, repl)\n \n def expand(r, c, id):\n if r < 0 or r>=m or c < 0 or c>=n or visited[r][c] == 1:\n return\n visited[r][c] = 1\n if isInfected[r][c] == 0:\n isInfected[r][c] = 1\n elif isInfected[r][c] == 1:\n expand(r+1, c, id)\n expand(r-1, c, id)\n expand(r, c-1, id)\n expand(r, c+1, id) \n\n total_walls = 0\n\n while True:\n # Day ---------------------------------------------------\n max_th = 0\n max_th_loc = (None, None)\n max_th_border = 0\n id = 3\n visited = [[0] * n for _ in range(m)]\n\n for r in range(m):\n for c in range(n):\n if isInfected[r][c]==1 and visited[r][c] == 0:\n \n borders = 0\n threatened = 0\n dfs(r, c, id)\n id += 1\n if threatened > max_th:\n max_th = threatened\n max_th_loc = r, c\n max_th_border = borders\n \n if max_th == 0:\n break\n total_walls += max_th_border\n # Restrict bordered region by making them dormant\n flood(*max_th_loc, 1, 2)\n\n # Night -------------------------------------------------\n\n visited = [[0] * n for _ in range(m)]\n for r in range(m):\n for c in range(n):\n if isInfected[r][c]==1 and visited[r][c] == 0:\n expand(r, c, id)\n id += 1\n\n return total_walls\n\n\n\n\n\n``` | 0 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Detailed and clear solution | contain-virus | 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 containVirus(self, isInfected: List[List[int]]) -> int:\n \'\'\'\n isInfected[r][c]:\n 0 : Uninfected\n 1 : Infected\n 2 : Infected & restricted\n \'\'\'\n m = len(isInfected)\n n = len(isInfected[0])\n\n borders = 0\n threatened = 0\n def dfs(r, c, id):\n nonlocal borders, threatened\n if r < 0 or r>=m or c < 0 or c>=n:\n return\n\n if isInfected[r][c] == 1:\n if visited[r][c] == 0:\n visited[r][c] = 1\n dfs(r-1, c, id)\n dfs(r+1, c, id)\n dfs(r, c-1, id)\n dfs(r, c+1, id)\n else:\n pass\n elif isInfected[r][c] == 0:\n if visited[r][c] == id:\n borders += 1\n else:\n borders += 1\n threatened += 1\n visited[r][c] = id\n \n def flood(r, c, find, repl):\n if r < 0 or r>=m or c < 0 or c>=n or isInfected[r][c] != find:\n return\n isInfected[r][c] = repl\n flood(r-1, c, find, repl)\n flood(r+1, c, find, repl)\n flood(r, c-1, find, repl)\n flood(r, c+1, find, repl)\n \n def expand(r, c, id):\n if r < 0 or r>=m or c < 0 or c>=n or visited[r][c] == 1:\n return\n visited[r][c] = 1\n if isInfected[r][c] == 0:\n isInfected[r][c] = 1\n elif isInfected[r][c] == 1:\n expand(r+1, c, id)\n expand(r-1, c, id)\n expand(r, c-1, id)\n expand(r, c+1, id) \n\n total_walls = 0\n\n while True:\n # Day ---------------------------------------------------\n max_th = 0\n max_th_loc = (None, None)\n max_th_border = 0\n id = 3\n visited = [[0] * n for _ in range(m)]\n\n for r in range(m):\n for c in range(n):\n if isInfected[r][c]==1 and visited[r][c] == 0:\n \n borders = 0\n threatened = 0\n dfs(r, c, id)\n id += 1\n if threatened > max_th:\n max_th = threatened\n max_th_loc = r, c\n max_th_border = borders\n \n if max_th == 0:\n break\n total_walls += max_th_border\n # Restrict bordered region by making them dormant\n flood(*max_th_loc, 1, 2)\n\n # Night -------------------------------------------------\n\n visited = [[0] * n for _ in range(m)]\n for r in range(m):\n for c in range(n):\n if isInfected[r][c]==1 and visited[r][c] == 0:\n expand(r, c, id)\n id += 1\n\n return total_walls\n\n\n\n\n\n\n``` | 0 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Python Short and Easy to Understand Solution | contain-virus | 0 | 1 | \n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n walls_needed = 0\n\n # identify infected and uninfected cells\n infected = [(i, j) for i in range(len(isInfected)) for j in range(len(isInfected[0])) if isInfected[i][j] == 1]\n uninfected = [(i, j) for i in range(len(isInfected)) for j in range(len(isInfected[0])) if isInfected[i][j] != 1]\n\n # group infected cells\n def grp_infected(infected):\n grp = []\n while infected:\n cur = [infected.pop()]\n cur_grp = [cur[0]]\n while cur:\n cur_dot = cur.pop()\n south = (cur_dot[0] - 1, cur_dot[1]); north = (cur_dot[0] + 1, cur_dot[1])\n west = (cur_dot[0], cur_dot[1] - 1); east = (cur_dot[0], cur_dot[1] + 1)\n for i in [south, north, west, east]:\n if i in infected:\n cur_grp.append(i)\n cur.append(i)\n infected.remove(i)\n grp.append(cur_grp)\n return grp\n grp = grp_infected(infected)\n\n # identify next-to-be infected cells and select the correct group to quarantine\n while grp and uninfected:\n next_grp = []\n for i in grp:\n next_grp_temp = []\n for cur_dot in i:\n south = (cur_dot[0] - 1, cur_dot[1]); north = (cur_dot[0] + 1, cur_dot[1])\n west = (cur_dot[0], cur_dot[1] - 1); east = (cur_dot[0], cur_dot[1] + 1)\n for k in [south, north, west, east]:\n if k in uninfected:\n next_grp_temp.append(k)\n next_grp.append(next_grp_temp)\n\n max_infected = [len(set(i)) for i in next_grp]\n idx = max_infected.index(max(max_infected))\n walls_needed += len(next_grp[idx])\n\n del next_grp[idx]\n del grp[idx]\n grp = [i + j for i, j in zip(next_grp, grp)]\n next_grp = list(set(j for i in next_grp for j in i))\n for i in next_grp:\n uninfected.remove(i)\n grp = grp_infected(list(set(j for i in grp for j in i)))\n return walls_needed\n``` | 0 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
[Python] DFS and simulation. explained | contain-virus | 0 | 1 | * (1) DFS to find all the infected regions\n* (2) Pick the region that will infect the largetest number of cells in the next day, and build a wall around it\n* (3) Update the infected regions\nthe cells that are in the wall is updated with "controlled" state (i.e., value 2)\nthe cells that is on the boundary of uncontrolled regions are updated with "infected" state (i.e., value 1)\n* (4) Go back to step (1) until all the regions are controlled or all the cells are infected.\n\n```\nimport heapq\n\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n self.n_row = len(isInfected)\n self.n_col = len(isInfected[0])\n self.ifstat = isInfected\n \n self.visited = []\n for _ in range(self.n_row):\n self.visited.append([False for _ in range(self.n_col)])\n self.directions = {(0, 1), (1, 0), (0, -1), (-1, 0)}\n self.infect_region = []\n self.infect_boundary_wall_cnt = [] # a list of the number of walls required to control a region\n self.infect_boundary_mheap = [] \n \n\t\t# step 1: find all the regions that are infected, including the number of walls required to "control" this region\n visited = copy.deepcopy(self.visited)\n region_idx = 0\n for i in range(self.n_row):\n for j in range(self.n_col):\n if self.ifstat[i][j] == 1 and (not visited[i][j]):\n tr, tb, tbc = list(), set(), [0]\n self.dfsFindVirus(i, j, tr, tb, tbc, visited)\n self.infect_region.append(tr)\n self.infect_boundary_wall_cnt.append(tbc[0])\n heapq.heappush(self.infect_boundary_mheap, (-(len(tb)), region_idx, list(tb)))\n region_idx += 1\n \n # step 2, simulation the progress of virus infection\n ans = 0\n while self.infect_boundary_mheap:\n # pick the region that can infect largest region next day, and build a wall for it\n _, ridx, _ = heapq.heappop(self.infect_boundary_mheap)\n for i, j in self.infect_region[ridx]:\n self.ifstat[i][j] = 2\n ans += self.infect_boundary_wall_cnt[ridx]\n\t\t\t\n # update the cells will be infected next day\n while self.infect_boundary_mheap:\n _, _, b_list = heapq.heappop(self.infect_boundary_mheap)\n for i, j in b_list:\n self.ifstat[i][j] = 1\n # check the map and find the new region and boundary\n visited = copy.deepcopy(self.visited)\n region_idx = 0\n t_ir = []\n t_ibc = []\n self.infect_boundary_wall_cnt.clear()\n while self.infect_region:\n start = self.infect_region.pop()\n i, j = start[0]\n if self.ifstat[i][j] == 1 and (not visited[i][j]):\n tr, tb, tbc = list(), set(), [0]\n self.dfsFindVirus(i, j, tr, tb, tbc, visited)\n t_ir.append(tr)\n t_ibc.append(tbc[0])\n heapq.heappush(self.infect_boundary_mheap, (-(len(tb)), region_idx, list(tb)))\n region_idx += 1\n self.infect_boundary_wall_cnt = t_ibc\n self.infect_region = t_ir\n return ans\n \n \n def dfsFindVirus(self, i, j, region, boundary, bcnt, visited):\n if visited[i][j] or self.ifstat[i][j] == 2:\n return\n \n if self.ifstat[i][j] == 0:\n # this is a boundary\n boundary.add((i, j))\n bcnt[0] += 1\n return\n \n visited[i][j] = True\n region.append((i, j))\n \n for nidx in self.directions:\n ni = i + nidx[0]\n nj = j + nidx[1]\n \n if ni >= 0 and ni < self.n_row and nj >= 0 and nj < self.n_col and (not visited[ni][nj]):\n self.dfsFindVirus(ni, nj, region, boundary, bcnt, visited)\n\n \n``` | 0 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
Python Object Oriented Solution - Easy to understand | contain-virus | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is Python version:\nFor explanation please refer [CPP Version](https://leetcode.com/problems/contain-virus/solutions/847507/cpp-dfs-solution-explained/)\nCredit goes to: [rai02](https://leetcode.com/rai02/)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDFS with Creating Cluster objects(for walls,tobeContaminated cells)\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(M*N)^^2\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(M*N)\n# Code\n```\nfrom heapq import heapify,heappush,heappop\nclass Cluster:\n def __init__(self):\n self.contaminated = set()\n self.toBeContaminated = set()\n self.wallCnt = 0\n # sorting based on # of toBeContaminated in reverse order\n def __lt__(self,nxt):\n return len(self.toBeContaminated) > len(nxt.toBeContaminated)\n\nclass Solution:\n\n def containVirus(self, isInfected: List[List[int]]) -> int:\n rows = len(isInfected)\n cols = len(isInfected[0])\n ans = 0\n \n def dfs(i,j,cluster):\n dirs = [(1,0),(-1,0),(0,1),(0,-1)]\n for r,c in dirs:\n nr = i + r\n nc = j + c\n if 0<=nr<rows and 0<=nc<cols:\n if isInfected[nr][nc]==1 and (nr,nc) not in visited:\n cluster.contaminated.add((nr,nc))\n visited.add((nr,nc))\n dfs(nr,nc,cluster)\n elif isInfected[nr][nc]==0:\n # note: we dont add to visited here as two virus cells can attack common normal cell\n cluster.wallCnt += 1\n cluster.toBeContaminated.add((nr,nc))\n\n\n while True:\n visited = set()\n hh = []\n for i in range(rows):\n for j in range(cols):\n if isInfected[i][j]==1 and (i,j) not in visited:\n cluster = Cluster()\n cluster.contaminated.add((i,j))\n visited.add((i,j))\n dfs(i,j,cluster)\n hh.append(cluster)\n if not hh:\n break\n heapify(hh)\n # this will return cluster with max toBeContaminated cells\n cluster = heappop(hh)\n # stopping the virus by building walls\n for i,j in cluster.contaminated:\n isInfected[i][j] = -1\n ans += cluster.wallCnt\n\n while hh:\n cluster = hh.pop()\n for i,j in cluster.toBeContaminated:\n isInfected[i][j] = 1\n\n return ans\n\n\n\n\n\n\n\n\n``` | 0 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
BFS: A Step-by-Step Guide with Comments. | contain-virus | 0 | 1 | # Template for BFS\n```\n1. bfs = deque() # to store the node first meets the requirements\n2. while bfs: # there are still nodes to visit\n3. node = bfs.popleft()\n4. # Mark as visited\n5. # Expand the node in all four directions\n6. if not visited and within the valid range:\n7. # update and do something\n```\n# Breaking Down the Solution"\n\n```\n# 1. BFS\n# Get to-spread/to-put-wall area. \n# Get nums of walls for every area. \n\n# Situation 1:\n# 2. none infected areas\n if not neighbors:\n break\n\n# Situation 2: \n# 3. Keep going\n# calculate the largest area:\n# 4. update the ans\n\n# 5. mark as processed and modify the unprocessed\n \n# 6. mark the spreaded\n \n```\n\n\n\n# Code\n```\nclass Solution:\n def containVirus(self, isInfected: List[List[int]]) -> int:\n dirs = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n m, n = len(isInfected), len(isInfected[0])\n ans = 0\n while True:\n # 1. BFS\n # neighbors stores every to-spread/to-put-wall area. \n # firewalls stores the countings for every area. \n neighbors, firewalls = list(), list()\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] == 1:\n # detect the infected area \n q = deque([(i, j)])\n # index of this area\n idx = len(neighbors) + 1\n # record all cells in this to-spread/to-put-wall area\n neighbor = set()\n # count walls needed\n firewall = 0\n # mark as visited\n isInfected[i][j] = -idx\n\n while q:\n x, y = q.popleft()\n for d in range(4):\n # detect around\n nx, ny = x + dirs[d][0], y + dirs[d][1]\n # ensure within the matrix\n if 0 <= nx < m and 0 <= ny < n:\n if isInfected[nx][ny] == 1:\n # update infected area\n q.append((nx, ny))\n # mark as visited\n isInfected[nx][ny] = -idx\n elif isInfected[nx][ny] == 0:\n # update counting and neighbor\n firewall += 1\n neighbor.add((nx, ny))\n\n \n \n # update neighbors and firewalls\n neighbors.append(neighbor)\n firewalls.append(firewall)\n\n # 2. none infected areas\n if not neighbors:\n break\n \n # 3. calculate the largest area:\n idx = 0\n for i in range(1, len(neighbors)):\n if len(neighbors[i]) > len(neighbors[idx]):\n idx = i\n \n # 4. update the ans\n ans += firewalls[idx]\n\n # if only 1 area in total, this is the final answer\n if len(neighbors) == 1:\n # return ans\n break \n \n\n # 5. mark as processed and modify the unprocessed\n for i in range(m):\n for j in range(n):\n if isInfected[i][j] < 0:\n # unprocess\n if isInfected[i][j] != - (idx + 1):\n isInfected[i][j] = 1\n else:\n isInfected[i][j] = 2\n # 6. mark the spreaded\n for i, neighbor in enumerate(neighbors):\n if i != idx:\n # spread\n for x, y in neighbor:\n isInfected[x][y] = 1\n \n \n\n return ans\n``` | 1 | A virus is spreading rapidly, and your task is to quarantine the infected area by installing walls.
The world is modeled as an `m x n` binary grid `isInfected`, where `isInfected[i][j] == 0` represents uninfected cells, and `isInfected[i][j] == 1` represents cells contaminated with the virus. A wall (and only one wall) can be installed between any two **4-directionally** adjacent cells, on the shared boundary.
Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall. Resources are limited. Each day, you can install walls around only one region (i.e., the affected area (continuous block of infected cells) that threatens the most uninfected cells the following night). There **will never be a tie**.
Return _the number of walls used to quarantine all the infected regions_. If the world will become fully infected, return the number of walls used.
**Example 1:**
**Input:** isInfected = \[\[0,1,0,0,0,0,0,1\],\[0,1,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,1\],\[0,0,0,0,0,0,0,0\]\]
**Output:** 10
**Explanation:** There are 2 contaminated regions.
On the first day, add 5 walls to quarantine the viral region on the left. The board after the virus spreads is:
On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
**Example 2:**
**Input:** isInfected = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** 4
**Explanation:** Even though there is only one cell saved, there are 4 walls built.
Notice that walls are only built on the shared boundary of two different cells.
**Example 3:**
**Input:** isInfected = \[\[1,1,1,0,0,0,0,0,0\],\[1,0,1,0,1,1,1,1,1\],\[1,1,1,0,0,0,0,0,0\]\]
**Output:** 13
**Explanation:** The region on the left only builds two new walls.
**Constraints:**
* `m == isInfected.length`
* `n == isInfected[i].length`
* `1 <= m, n <= 50`
* `isInfected[i][j]` is either `0` or `1`.
* There is always a contiguous viral region throughout the described process that will **infect strictly more uncontaminated squares** in the next round. | Count only the letters (possibly converted to lowercase) of each word. If a word is shorter and the count of each letter is at least the count of that letter in the licensePlate, it is the best answer we've seen yet. |
752: Beats 98.86%, Solution with step by step explanation | open-the-lock | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ndef neighbors(node):\n for i in range(4):\n x = int(node[i])\n for d in (-1, 1): \n y = (x + d) % 10\n yield node[:i] + str(y) + node[i+1:]\n```\nThe neighbors function generates the immediate neighbors of the current combination of the lock. For each position in the 4-digit combination, it tries moving the digit up or down (hence the for d in (-1, 1) loop). If it moves from \'9\' it goes to \'0\' and vice versa, which is handled by the modulo operation.\n\n```\ndead = set(deadends)\nif "0000" in dead:\n return -1\nif target == "0000":\n return 0\n```\nWe convert the deadends list to a set for O(1) lookups. If the initial combination "0000" is a deadend, we return -1 as it\'s not possible to open the lock. If the target is "0000", we return 0 as it\'s already at the desired state.\n\n```\nbegin = set()\nend = set()\nbegin.add("0000")\nend.add(target)\n```\nWe initialize two sets, begin and end. begin starts with the initial state "0000" and end starts with the target. The idea of bidirectional BFS is to simultaneously search from the starting point and the ending point, and meet in the middle, which can be more efficient than a standard BFS from just the starting point.\n\n```\ndepth = 0\nwhile begin and end:\n temp = set()\n for node in begin:\n if node in dead:\n continue\n if node in end:\n return depth\n dead.add(node)\n for nei in neighbors(node):\n temp.add(nei)\n depth += 1\n begin = end\n end = temp\n```\n\nWe maintain a depth variable to count the number of moves required. We explore every node in begin. If we find a node that\'s in end, then we\'ve found a path from the starting state to the target. If a node is a deadend, we skip it. Otherwise, we mark the node as visited by adding it to dead. We then generate its neighbors and add them to temp. After exploring all nodes at the current depth, we swap begin and end and continue.\n\n```\nreturn -1\n```\nIf the while loop completes and we haven\'t returned from the function, then there\'s no possible way to reach the target, so we return -1.\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n \n def neighbors(node):\n for i in range(4):\n x = int(node[i])\n for d in (-1, 1): \n y = (x + d) % 10\n yield node[:i] + str(y) + node[i+1:]\n\n dead = set(deadends)\n\n if "0000" in dead:\n return -1\n if target == "0000":\n return 0\n \n begin = set()\n end = set()\n begin.add("0000")\n end.add(target)\n \n depth = 0\n while begin and end:\n temp = set()\n for node in begin:\n if node in dead:\n continue\n if node in end:\n return depth\n dead.add(node) \n for nei in neighbors(node):\n temp.add(nei)\n depth += 1\n begin = end\n end = temp\n \n return -1\n\n``` | 1 | You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot.
The lock initially starts at `'0000'`, a string representing the state of the 4 wheels.
You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
**Example 1:**
**Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 "
**Output:** 6
**Explanation:**
A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ".
Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102 ".
**Example 2:**
**Input:** deadends = \[ "8888 "\], target = "0009 "
**Output:** 1
**Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ".
**Example 3:**
**Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 "
**Output:** -1
**Explanation:** We cannot reach the target without getting stuck.
**Constraints:**
* `1 <= deadends.length <= 500`
* `deadends[i].length == 4`
* `target.length == 4`
* target **will not be** in the list `deadends`.
* `target` and `deadends[i]` consist of digits only. | Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n. |
752: Beats 98.86%, Solution with step by step explanation | open-the-lock | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ndef neighbors(node):\n for i in range(4):\n x = int(node[i])\n for d in (-1, 1): \n y = (x + d) % 10\n yield node[:i] + str(y) + node[i+1:]\n```\nThe neighbors function generates the immediate neighbors of the current combination of the lock. For each position in the 4-digit combination, it tries moving the digit up or down (hence the for d in (-1, 1) loop). If it moves from \'9\' it goes to \'0\' and vice versa, which is handled by the modulo operation.\n\n```\ndead = set(deadends)\nif "0000" in dead:\n return -1\nif target == "0000":\n return 0\n```\nWe convert the deadends list to a set for O(1) lookups. If the initial combination "0000" is a deadend, we return -1 as it\'s not possible to open the lock. If the target is "0000", we return 0 as it\'s already at the desired state.\n\n```\nbegin = set()\nend = set()\nbegin.add("0000")\nend.add(target)\n```\nWe initialize two sets, begin and end. begin starts with the initial state "0000" and end starts with the target. The idea of bidirectional BFS is to simultaneously search from the starting point and the ending point, and meet in the middle, which can be more efficient than a standard BFS from just the starting point.\n\n```\ndepth = 0\nwhile begin and end:\n temp = set()\n for node in begin:\n if node in dead:\n continue\n if node in end:\n return depth\n dead.add(node)\n for nei in neighbors(node):\n temp.add(nei)\n depth += 1\n begin = end\n end = temp\n```\n\nWe maintain a depth variable to count the number of moves required. We explore every node in begin. If we find a node that\'s in end, then we\'ve found a path from the starting state to the target. If a node is a deadend, we skip it. Otherwise, we mark the node as visited by adding it to dead. We then generate its neighbors and add them to temp. After exploring all nodes at the current depth, we swap begin and end and continue.\n\n```\nreturn -1\n```\nIf the while loop completes and we haven\'t returned from the function, then there\'s no possible way to reach the target, so we return -1.\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n \n def neighbors(node):\n for i in range(4):\n x = int(node[i])\n for d in (-1, 1): \n y = (x + d) % 10\n yield node[:i] + str(y) + node[i+1:]\n\n dead = set(deadends)\n\n if "0000" in dead:\n return -1\n if target == "0000":\n return 0\n \n begin = set()\n end = set()\n begin.add("0000")\n end.add(target)\n \n depth = 0\n while begin and end:\n temp = set()\n for node in begin:\n if node in dead:\n continue\n if node in end:\n return depth\n dead.add(node) \n for nei in neighbors(node):\n temp.add(nei)\n depth += 1\n begin = end\n end = temp\n \n return -1\n\n``` | 1 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
SUCCICNT EXPLANATION, BFS | open-the-lock | 0 | 1 | ```\nLet\'s say target = \'7120\'\n\nAs the target starts with \'7\', obviously we have to go by \n \'9000\' --> \'8000\' --> \'7000\' --> \'7100\' --> \'7110\' --> \'7120\' --> \'7120\'\nBut what if all of those string are already in "deadends"? Then maybe the shortest way from\n\'1000\' .....\n\nSo we\'ve to check every possible combination level by level which is BFS.\n\n \'0000\'\n \n\'1000\' \'0100\' \'0010\' \'0001\' [YOU CAN GET THESE BY FLIPPING ONCE FROM \'0000\']\n\nI can put 1 in any of these way. This is forward but in backward there might be short path,\nso we also need to go backward also.\n\n\'9000\' \'0900\' \'0090\' \'0009\' [YOU CAN GET THESE BY FLIPPING ONCE FROM \'0000\']\n\n\n From \'1000\' the below 4 type string we can get :\n\n2000 1100 1010 1001 [YOU CAN GET THESE BY FLIPPING TWICE FROM \'0000\']\n |__________________________|\n |--- Some combinations with only 1\n\nThis way from 0100, 0010 and 0001 we will find some string with 1s.\nYou can clearly see we will have all type of combinations slowly LEVEL BY LEVEL.\n\nHERE IN THIS BFS EACH \'LEVEL\' REPRESENTING WHATEVER STRING WE CAN GET IN THIS LEVEL BY \nTURNING ONE CHARACTER INTO ANOTHER \'IS THE MINIMUM TURNS REQUIRED TO GET THOSE STRINGS\' and \nif any of these string == target, we return the level.\n----\n \n```\n```CPP []\nclass Solution {\npublic:\n int openLock(vector<string>& deadends, string target) \n {\n if(target == "0000") return 0;\n unordered_set<string> visited(begin(deadends), end(deadends));\n if(visited.count("0000")) return -1;\n \n queue<string> q(deque<string> {"0000"});\n string main, cur, prev;\n\n for(int size = 1, level = 1; !q.empty(); size = q.size(), level++)\n {\n while(size--) \n {\n main = cur = prev = q.front(); q.pop();\n for(int i=0; i<4; i++)\n {\n cur[i] += (cur[i] == \'9\'? -9 : 1);\n if(cur == target) return level;\n if(!visited.count(cur)) q.push(cur), visited.insert(cur);\n\n prev[i] -= (prev[i] == \'0\'? -9 : 1);\n if(prev == target) return level;\n if(!visited.count(prev)) q.push(prev), visited.insert(prev);\n\n cur = prev = main;\n }\n }\n }\n\n return -1;\n }\n};\n```\n```Python []\nclass Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n if target == \'0000\': return 0\n visited = set(deadends)\n if \'0000\' in visited: return -1\n q, level = deque([\'0000\']), 1\n\n while q:\n for _ in range(len(q)):\n\n main = q.popleft()\n for i in range(4):\n nextt = main[:i] + (\'0\' if main[i] == \'9\' else str(int(main[i]) + 1)) + main[i+1:]\n if nextt == target: return level\n if nextt not in visited :\n q.append(nextt)\n visited.add(nextt)\n \n prev = main[:i] + (\'9\' if main[i] == \'0\' else str(int(main[i]) - 1)) + main[i+1:]\n if prev == target: return level\n if prev not in visited :\n q.append(prev)\n visited.add(prev)\n\n level += 1\n\n return -1\n```\n<!-- ```\nTime complexity :\nSpace complexity :\n``` --> | 1 | You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot.
The lock initially starts at `'0000'`, a string representing the state of the 4 wheels.
You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
**Example 1:**
**Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 "
**Output:** 6
**Explanation:**
A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ".
Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102 ".
**Example 2:**
**Input:** deadends = \[ "8888 "\], target = "0009 "
**Output:** 1
**Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ".
**Example 3:**
**Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 "
**Output:** -1
**Explanation:** We cannot reach the target without getting stuck.
**Constraints:**
* `1 <= deadends.length <= 500`
* `deadends[i].length == 4`
* `target.length == 4`
* target **will not be** in the list `deadends`.
* `target` and `deadends[i]` consist of digits only. | Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n. |
SUCCICNT EXPLANATION, BFS | open-the-lock | 0 | 1 | ```\nLet\'s say target = \'7120\'\n\nAs the target starts with \'7\', obviously we have to go by \n \'9000\' --> \'8000\' --> \'7000\' --> \'7100\' --> \'7110\' --> \'7120\' --> \'7120\'\nBut what if all of those string are already in "deadends"? Then maybe the shortest way from\n\'1000\' .....\n\nSo we\'ve to check every possible combination level by level which is BFS.\n\n \'0000\'\n \n\'1000\' \'0100\' \'0010\' \'0001\' [YOU CAN GET THESE BY FLIPPING ONCE FROM \'0000\']\n\nI can put 1 in any of these way. This is forward but in backward there might be short path,\nso we also need to go backward also.\n\n\'9000\' \'0900\' \'0090\' \'0009\' [YOU CAN GET THESE BY FLIPPING ONCE FROM \'0000\']\n\n\n From \'1000\' the below 4 type string we can get :\n\n2000 1100 1010 1001 [YOU CAN GET THESE BY FLIPPING TWICE FROM \'0000\']\n |__________________________|\n |--- Some combinations with only 1\n\nThis way from 0100, 0010 and 0001 we will find some string with 1s.\nYou can clearly see we will have all type of combinations slowly LEVEL BY LEVEL.\n\nHERE IN THIS BFS EACH \'LEVEL\' REPRESENTING WHATEVER STRING WE CAN GET IN THIS LEVEL BY \nTURNING ONE CHARACTER INTO ANOTHER \'IS THE MINIMUM TURNS REQUIRED TO GET THOSE STRINGS\' and \nif any of these string == target, we return the level.\n----\n \n```\n```CPP []\nclass Solution {\npublic:\n int openLock(vector<string>& deadends, string target) \n {\n if(target == "0000") return 0;\n unordered_set<string> visited(begin(deadends), end(deadends));\n if(visited.count("0000")) return -1;\n \n queue<string> q(deque<string> {"0000"});\n string main, cur, prev;\n\n for(int size = 1, level = 1; !q.empty(); size = q.size(), level++)\n {\n while(size--) \n {\n main = cur = prev = q.front(); q.pop();\n for(int i=0; i<4; i++)\n {\n cur[i] += (cur[i] == \'9\'? -9 : 1);\n if(cur == target) return level;\n if(!visited.count(cur)) q.push(cur), visited.insert(cur);\n\n prev[i] -= (prev[i] == \'0\'? -9 : 1);\n if(prev == target) return level;\n if(!visited.count(prev)) q.push(prev), visited.insert(prev);\n\n cur = prev = main;\n }\n }\n }\n\n return -1;\n }\n};\n```\n```Python []\nclass Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n if target == \'0000\': return 0\n visited = set(deadends)\n if \'0000\' in visited: return -1\n q, level = deque([\'0000\']), 1\n\n while q:\n for _ in range(len(q)):\n\n main = q.popleft()\n for i in range(4):\n nextt = main[:i] + (\'0\' if main[i] == \'9\' else str(int(main[i]) + 1)) + main[i+1:]\n if nextt == target: return level\n if nextt not in visited :\n q.append(nextt)\n visited.add(nextt)\n \n prev = main[:i] + (\'9\' if main[i] == \'0\' else str(int(main[i]) - 1)) + main[i+1:]\n if prev == target: return level\n if prev not in visited :\n q.append(prev)\n visited.add(prev)\n\n level += 1\n\n return -1\n```\n<!-- ```\nTime complexity :\nSpace complexity :\n``` --> | 1 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
Simple BFS solution | open-the-lock | 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```\nfrom collections import deque\nclass Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n queue = deque()\n queue.append("0000")\n visited = set("0000")\n steps = 0\n if "0000" in deadends:\n return -1\n if target == "0000":\n return steps\n while (size:=len(queue)) != 0:\n steps += 1\n for i in range(size):\n curr = queue.popleft()\n for wheel in range(4):\n for move in (1,-1):\n new_combo = curr[:wheel] + str((ord(curr[wheel]) - ord(\'0\') + move) % 10) + curr[wheel+1:]\n if new_combo == target:\n return steps\n if new_combo in visited or new_combo in deadends:\n continue\n else:\n visited.add(new_combo)\n queue.append(new_combo)\n return -1\n\n\n``` | 2 | You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot.
The lock initially starts at `'0000'`, a string representing the state of the 4 wheels.
You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
**Example 1:**
**Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 "
**Output:** 6
**Explanation:**
A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ".
Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102 ".
**Example 2:**
**Input:** deadends = \[ "8888 "\], target = "0009 "
**Output:** 1
**Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ".
**Example 3:**
**Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 "
**Output:** -1
**Explanation:** We cannot reach the target without getting stuck.
**Constraints:**
* `1 <= deadends.length <= 500`
* `deadends[i].length == 4`
* `target.length == 4`
* target **will not be** in the list `deadends`.
* `target` and `deadends[i]` consist of digits only. | Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n. |
Simple BFS solution | open-the-lock | 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```\nfrom collections import deque\nclass Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n queue = deque()\n queue.append("0000")\n visited = set("0000")\n steps = 0\n if "0000" in deadends:\n return -1\n if target == "0000":\n return steps\n while (size:=len(queue)) != 0:\n steps += 1\n for i in range(size):\n curr = queue.popleft()\n for wheel in range(4):\n for move in (1,-1):\n new_combo = curr[:wheel] + str((ord(curr[wheel]) - ord(\'0\') + move) % 10) + curr[wheel+1:]\n if new_combo == target:\n return steps\n if new_combo in visited or new_combo in deadends:\n continue\n else:\n visited.add(new_combo)\n queue.append(new_combo)\n return -1\n\n\n``` | 2 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
BFS | open-the-lock | 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. -->\nWe start by defining the openLock function, which takes in two parameters: deadends (a list of dead-end combinations) and target (the target combination to unlock the lock).\n\nWe set the initial state of the lock to \'0000\' and check if it is in the deadends list. If it is, we know that the lock cannot be opened, so we return -1.\n\nWe convert the deadends list to a set for faster lookup later on. We also initialize a queue (implemented as a deque) to store the lock combinations to be processed, and a set called visited to keep track of the combinations we have already visited.\n\nWe start a while loop that continues until the queue is empty. Inside the loop, we pop the first combination from the queue and store it in variables current and turns (representing the current combination and the number of turns taken to reach it).\n\nWe check if the current combination is equal to the target. If it is, we have successfully unlocked the lock, so we return the number of turns taken.\n\nIf the current combination is not the target, we generate all possible next combinations by rotating each wheel (digit) in both directions (adding or subtracting 1). We use nested loops to iterate over each digit and direction.\n\nFor each new combination, we check if it has already been visited or if it is a dead-end combination. If it is neither, we add it to the visited set and enqueue it into the queue along with the updated number of turns.\n\nIf the target combination cannot be reached, the queue will eventually become empty. In this case, we return -1 to indicate that it is impossible to unlock the lock.\n\nThe code is followed by an example usage, where we define a list of dead-end combinations deadends and a target combination target. We call the openLock function with these inputs and print the result.\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 openLock(self, deadends: List[str], target: str) -> int:\n start = \'0000\'\n if start in deadends:\n return -1\n \n deadends = set(deadends)\n queue = deque([(start, 0)])\n visited = set([start])\n \n while queue:\n current, turns = queue.popleft()\n \n if current == target:\n return turns\n \n for i in range(4):\n for move in [-1, 1]:\n new_digit = str((int(current[i]) + move) % 10)\n new_code = current[:i] + new_digit + current[i+1:]\n \n if new_code not in visited and new_code not in deadends:\n visited.add(new_code)\n queue.append((new_code, turns + 1))\n \n return -1\n``` | 1 | You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: `'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'`. The wheels can rotate freely and wrap around: for example we can turn `'9'` to be `'0'`, or `'0'` to be `'9'`. Each move consists of turning one wheel one slot.
The lock initially starts at `'0000'`, a string representing the state of the 4 wheels.
You are given a list of `deadends` dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.
Given a `target` representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
**Example 1:**
**Input:** deadends = \[ "0201 ", "0101 ", "0102 ", "1212 ", "2002 "\], target = "0202 "
**Output:** 6
**Explanation:**
A sequence of valid moves would be "0000 " -> "1000 " -> "1100 " -> "1200 " -> "1201 " -> "1202 " -> "0202 ".
Note that a sequence like "0000 " -> "0001 " -> "0002 " -> "0102 " -> "0202 " would be invalid,
because the wheels of the lock become stuck after the display becomes the dead end "0102 ".
**Example 2:**
**Input:** deadends = \[ "8888 "\], target = "0009 "
**Output:** 1
**Explanation:** We can turn the last wheel in reverse to move from "0000 " -> "0009 ".
**Example 3:**
**Input:** deadends = \[ "8887 ", "8889 ", "8878 ", "8898 ", "8788 ", "8988 ", "7888 ", "9888 "\], target = "8888 "
**Output:** -1
**Explanation:** We cannot reach the target without getting stuck.
**Constraints:**
* `1 <= deadends.length <= 500`
* `deadends[i].length == 4`
* `target.length == 4`
* target **will not be** in the list `deadends`.
* `target` and `deadends[i]` consist of digits only. | Convert the ip addresses to and from (long) integers. You want to know what is the most addresses you can put in this block starting from the "start" ip, up to n. It is the smallest between the lowest bit of start and the highest bit of n. Then, repeat this process with a new start and n. |
BFS | open-the-lock | 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. -->\nWe start by defining the openLock function, which takes in two parameters: deadends (a list of dead-end combinations) and target (the target combination to unlock the lock).\n\nWe set the initial state of the lock to \'0000\' and check if it is in the deadends list. If it is, we know that the lock cannot be opened, so we return -1.\n\nWe convert the deadends list to a set for faster lookup later on. We also initialize a queue (implemented as a deque) to store the lock combinations to be processed, and a set called visited to keep track of the combinations we have already visited.\n\nWe start a while loop that continues until the queue is empty. Inside the loop, we pop the first combination from the queue and store it in variables current and turns (representing the current combination and the number of turns taken to reach it).\n\nWe check if the current combination is equal to the target. If it is, we have successfully unlocked the lock, so we return the number of turns taken.\n\nIf the current combination is not the target, we generate all possible next combinations by rotating each wheel (digit) in both directions (adding or subtracting 1). We use nested loops to iterate over each digit and direction.\n\nFor each new combination, we check if it has already been visited or if it is a dead-end combination. If it is neither, we add it to the visited set and enqueue it into the queue along with the updated number of turns.\n\nIf the target combination cannot be reached, the queue will eventually become empty. In this case, we return -1 to indicate that it is impossible to unlock the lock.\n\nThe code is followed by an example usage, where we define a list of dead-end combinations deadends and a target combination target. We call the openLock function with these inputs and print the result.\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 openLock(self, deadends: List[str], target: str) -> int:\n start = \'0000\'\n if start in deadends:\n return -1\n \n deadends = set(deadends)\n queue = deque([(start, 0)])\n visited = set([start])\n \n while queue:\n current, turns = queue.popleft()\n \n if current == target:\n return turns\n \n for i in range(4):\n for move in [-1, 1]:\n new_digit = str((int(current[i]) + move) % 10)\n new_code = current[:i] + new_digit + current[i+1:]\n \n if new_code not in visited and new_code not in deadends:\n visited.add(new_code)\n queue.append((new_code, turns + 1))\n \n return -1\n``` | 1 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
753: Solution with step by step explanation | cracking-the-safe | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nif n == 1:\n return \'\'.join(map(str, range(k)))\n```\n\nIf n is 1, we simply return a string made of all numbers from 0 to k-1. This is because for n=1, every single digit is a possible password. We use map to convert numbers to strings and join to combine them into a single string.\n\n```\nseen = set()\nresult = []\n\nstart_node = "0" * (n - 1)\n```\nseen is a set that will store all the sequences we have seen (or visited) so far. This helps to avoid revisiting sequences.\nresult is the list that will store the final sequence to unlock the safe.\nstart_node is initialized to a string of n-1 zeros, which will be our starting point.\n\n```\nself.dfs(start_node, k, seen, result)\n```\nWe call the depth-first search (DFS) function starting from the start_node. The goal of this DFS is to find the Eulerian path in the de Bruijn graph. An Eulerian path visits every edge exactly once.\n\n```\ndef dfs(self, node, k, seen, result):\n for i in range(k):\n edge = node + str(i)\n\n if edge not in seen:\n seen.add(edge)\n self.dfs(edge[1:], k, seen, result)\n result.append(str(i))\n```\nFor each node in the graph (which is a string of length n-1), we try to extend it by one character (from 0 to k-1) to form an edge. If this edge has not been seen before, we add it to the seen set. Then, we recursively call the DFS function with the next node, which is the last n-1 characters of the edge. After we have explored all possible extensions from the current node, we add the current digit to our result.\n\n```\nreturn "".join(result) + start_node\n```\nWe convert the result list into a string and append the start_node to it. This is because our DFS would have traversed the graph in such a way that appending the start_node at the end ensures all n-length combinations appear in the sequence.\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 crackSafe(self, n: int, k: int) -> str:\n if n == 1:\n return \'\'.join(map(str, range(k)))\n \n seen = set()\n result = []\n \n start_node = "0" * (n - 1)\n self.dfs(start_node, k, seen, result)\n \n return "".join(result) + start_node\n\n def dfs(self, node, k, seen, result):\n for i in range(k):\n edge = node + str(i)\n\n if edge not in seen:\n seen.add(edge)\n\n self.dfs(edge[1:], k, seen, result)\n result.append(str(i))\n\n``` | 2 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
753: Solution with step by step explanation | cracking-the-safe | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nif n == 1:\n return \'\'.join(map(str, range(k)))\n```\n\nIf n is 1, we simply return a string made of all numbers from 0 to k-1. This is because for n=1, every single digit is a possible password. We use map to convert numbers to strings and join to combine them into a single string.\n\n```\nseen = set()\nresult = []\n\nstart_node = "0" * (n - 1)\n```\nseen is a set that will store all the sequences we have seen (or visited) so far. This helps to avoid revisiting sequences.\nresult is the list that will store the final sequence to unlock the safe.\nstart_node is initialized to a string of n-1 zeros, which will be our starting point.\n\n```\nself.dfs(start_node, k, seen, result)\n```\nWe call the depth-first search (DFS) function starting from the start_node. The goal of this DFS is to find the Eulerian path in the de Bruijn graph. An Eulerian path visits every edge exactly once.\n\n```\ndef dfs(self, node, k, seen, result):\n for i in range(k):\n edge = node + str(i)\n\n if edge not in seen:\n seen.add(edge)\n self.dfs(edge[1:], k, seen, result)\n result.append(str(i))\n```\nFor each node in the graph (which is a string of length n-1), we try to extend it by one character (from 0 to k-1) to form an edge. If this edge has not been seen before, we add it to the seen set. Then, we recursively call the DFS function with the next node, which is the last n-1 characters of the edge. After we have explored all possible extensions from the current node, we add the current digit to our result.\n\n```\nreturn "".join(result) + start_node\n```\nWe convert the result list into a string and append the start_node to it. This is because our DFS would have traversed the graph in such a way that appending the start_node at the end ensures all n-length combinations appear in the sequence.\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 crackSafe(self, n: int, k: int) -> str:\n if n == 1:\n return \'\'.join(map(str, range(k)))\n \n seen = set()\n result = []\n \n start_node = "0" * (n - 1)\n self.dfs(start_node, k, seen, result)\n \n return "".join(result) + start_node\n\n def dfs(self, node, k, seen, result):\n for i in range(k):\n edge = node + str(i)\n\n if edge not in seen:\n seen.add(edge)\n\n self.dfs(edge[1:], k, seen, result)\n result.append(str(i))\n\n``` | 2 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
Solution | cracking-the-safe | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n using VT = pair<vector<string>,unordered_map<string,int>>;\n VT gNodes(int n, int k) {\n if (n==1) return VT({""},{{"",0}});\n VT ns;\n auto prev = gNodes(n-1,k).first;\n for (auto s: prev) {\n s += " ";\n for (int i=0; i<k; ++i) {\n s.back() = \'0\'+i;\n ns.second[s] = ns.first.size();\n ns.first.push_back(s);\n }\n }\n return ns;\n }\n string crackSafe(int n, int k) {\n if (n<2) return string("0123456789").substr(0,k);\n auto [ns,hn] = gNodes(n,k);\n auto N = ns.size();\n vector<pair<int,int>> arcs;\n for (auto [s,x]: hn) {\n auto t = s.substr(1,-1)+" "; \n for (int i=0; i<k; ++i) {\n t.back() = \'0\'+i;\n arcs.emplace_back(x,hn[t]);\n }\n }\n vector<vector<int>> unused(N,[k](){vector<int> t(k); iota(t.begin(),t.end(),0); return t;}());\n string code;\n int ss = 0;\n while (ss>=0) {\n auto cm(0);\n code += ns[ss];\n bool cont(true);\n while (cont) {\n auto nx = \'0\'+unused[ss].back();\n unused[ss].pop_back();\n code += nx;\n ss = hn[code.substr(code.length()-n+1,n-1)];\n cont = !unused[ss].empty();\n }\n ss = -1;\n }\n return code;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n if n == 1:\n return \'\'.join([str(i) for i in range(k)])\n if k == 1:\n return \'0\' * n\n suffix_map = {}\n all_combinations = [\'0\']*(n-1)\n for _ in range(k**n):\n suffix = \'\'.join(all_combinations[1-n:])\n suffix_map[suffix] = suffix_map.get(suffix, k) - 1\n all_combinations.append(str(suffix_map[suffix]))\n return \'\'.join(all_combinations)\n```\n\n```Java []\nclass Solution {\n public String crackSafe(int n, int k) {\n if(n==1){\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < k; i++){\n sb.append(i);\n }\n return sb.toString();\n }\n int[] biggest_edge = new int[(int) Math.pow(k, n - 1)];\n Arrays.fill(biggest_edge, k - 1);\n StringBuilder sb = new StringBuilder("0".repeat(n - 1));\n int current = 0;\n while (biggest_edge[current] != -1) {\n int edge = biggest_edge[current]--;\n sb.append(edge);\n current = (current * k) % (int) Math.pow(k, n-1) + edge;\n }\n return sb.toString();\n }\n public static String mergeTwoStringShortest(String left, String right) {\n int noOverlap =longestHeadTailIntersection(left,right);\n return left.substring(0, left.length()) + right.substring(noOverlap, right.length());\n }\n private static int longestHeadTailIntersection( String T, String P) {\n int n = T.length(), m = P.length();\n int[] pi = computePrefixFunction(P);\n int q = 0;\n for (int i = 0; i < n; i++) {\n while (q > 0 && P.charAt(q) != T.charAt(i)) {\n q = pi[q];\n }\n if (P.charAt(q) == T.charAt(i)) {\n q++;\n }\n if (q == m) {\n q = pi[q];\n }\n }\n return q;\n }\n private static int[] computePrefixFunction( String P) {\n int m = P.length();\n int[] pi = new int[m + 1];\n pi[1] = 0;\n for (int q = 1, k = 0; q < m; q++) {\n while (k > 0 && P.charAt(k) != P.charAt(q)) {\n k = pi[k];\n }\n if (P.charAt(k) == P.charAt(q)) {\n k++;\n }\n pi[q + 1] = k;\n }\n return pi;\n }\n public static boolean next(int[] arr, int k) {\n boolean remain = false;\n for (int i = arr.length - 1; i >= 0; i--) {\n arr[i]++;\n if (arr[i] == k) {\n arr[i] = 0;\n remain = true;\n } else {\n remain = false;\n break;\n }\n }\n return !remain;\n }\n private static String numArrToString(int[] arr) {\n StringBuilder sb = new StringBuilder();\n for (var i : arr) {\n sb.append(i);\n }\n return sb.toString();\n }\n}\n```\n | 2 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
Solution | cracking-the-safe | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n using VT = pair<vector<string>,unordered_map<string,int>>;\n VT gNodes(int n, int k) {\n if (n==1) return VT({""},{{"",0}});\n VT ns;\n auto prev = gNodes(n-1,k).first;\n for (auto s: prev) {\n s += " ";\n for (int i=0; i<k; ++i) {\n s.back() = \'0\'+i;\n ns.second[s] = ns.first.size();\n ns.first.push_back(s);\n }\n }\n return ns;\n }\n string crackSafe(int n, int k) {\n if (n<2) return string("0123456789").substr(0,k);\n auto [ns,hn] = gNodes(n,k);\n auto N = ns.size();\n vector<pair<int,int>> arcs;\n for (auto [s,x]: hn) {\n auto t = s.substr(1,-1)+" "; \n for (int i=0; i<k; ++i) {\n t.back() = \'0\'+i;\n arcs.emplace_back(x,hn[t]);\n }\n }\n vector<vector<int>> unused(N,[k](){vector<int> t(k); iota(t.begin(),t.end(),0); return t;}());\n string code;\n int ss = 0;\n while (ss>=0) {\n auto cm(0);\n code += ns[ss];\n bool cont(true);\n while (cont) {\n auto nx = \'0\'+unused[ss].back();\n unused[ss].pop_back();\n code += nx;\n ss = hn[code.substr(code.length()-n+1,n-1)];\n cont = !unused[ss].empty();\n }\n ss = -1;\n }\n return code;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n if n == 1:\n return \'\'.join([str(i) for i in range(k)])\n if k == 1:\n return \'0\' * n\n suffix_map = {}\n all_combinations = [\'0\']*(n-1)\n for _ in range(k**n):\n suffix = \'\'.join(all_combinations[1-n:])\n suffix_map[suffix] = suffix_map.get(suffix, k) - 1\n all_combinations.append(str(suffix_map[suffix]))\n return \'\'.join(all_combinations)\n```\n\n```Java []\nclass Solution {\n public String crackSafe(int n, int k) {\n if(n==1){\n StringBuilder sb = new StringBuilder();\n for(int i = 0; i < k; i++){\n sb.append(i);\n }\n return sb.toString();\n }\n int[] biggest_edge = new int[(int) Math.pow(k, n - 1)];\n Arrays.fill(biggest_edge, k - 1);\n StringBuilder sb = new StringBuilder("0".repeat(n - 1));\n int current = 0;\n while (biggest_edge[current] != -1) {\n int edge = biggest_edge[current]--;\n sb.append(edge);\n current = (current * k) % (int) Math.pow(k, n-1) + edge;\n }\n return sb.toString();\n }\n public static String mergeTwoStringShortest(String left, String right) {\n int noOverlap =longestHeadTailIntersection(left,right);\n return left.substring(0, left.length()) + right.substring(noOverlap, right.length());\n }\n private static int longestHeadTailIntersection( String T, String P) {\n int n = T.length(), m = P.length();\n int[] pi = computePrefixFunction(P);\n int q = 0;\n for (int i = 0; i < n; i++) {\n while (q > 0 && P.charAt(q) != T.charAt(i)) {\n q = pi[q];\n }\n if (P.charAt(q) == T.charAt(i)) {\n q++;\n }\n if (q == m) {\n q = pi[q];\n }\n }\n return q;\n }\n private static int[] computePrefixFunction( String P) {\n int m = P.length();\n int[] pi = new int[m + 1];\n pi[1] = 0;\n for (int q = 1, k = 0; q < m; q++) {\n while (k > 0 && P.charAt(k) != P.charAt(q)) {\n k = pi[k];\n }\n if (P.charAt(k) == P.charAt(q)) {\n k++;\n }\n pi[q + 1] = k;\n }\n return pi;\n }\n public static boolean next(int[] arr, int k) {\n boolean remain = false;\n for (int i = arr.length - 1; i >= 0; i--) {\n arr[i]++;\n if (arr[i] == k) {\n arr[i] = 0;\n remain = true;\n } else {\n remain = false;\n break;\n }\n }\n return !remain;\n }\n private static String numArrToString(int[] arr) {\n StringBuilder sb = new StringBuilder();\n for (var i : arr) {\n sb.append(i);\n }\n return sb.toString();\n }\n}\n```\n | 2 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
Python Eulerian Path (Eulerian Trail) Solution | cracking-the-safe | 0 | 1 | # Intuition\nThe original problem can be formulated as finding the Eulerian Path in a finite connected graph. If you are not familiar with the concept of the Eulerian Path, please read [this Wikipedia page](https://en.wikipedia.org/wiki/Eulerian_path).\n\nLet\'s say the length of the correct password is `n`, and the possible digits are in the range `[0, k-1]`. If we enumerate all the possible permutations of length `n-1` and model them as vertices, then we get a graph. Let\'s use a concrete example, let\'s say `n = 3`, `k = 3`. Then if we draw all the permutations with length `2`, we get the following graph.\n\n\n\nNow we add one more digit to the end of these permutations. The available digits are in the range `[0, k-1]`. We model the added digit as an outgoing edge. Let\'s use the vertex `00` in the above graph as an example. After appending one more digit to this vertex, the graph will look like the following.\n \n\n\nThe formed length `n` permutations are `000, 001, 002`. These three permutations are all the permutations of length `n` with the prefix `00`. We do the same thing to all the other vertices, and then the graph will contain all the possible permutations of length `n` on a size-k alphabet. Each edge represents a distinct permutation. Since there is `k` to the power of `n` permutations, the number of edges in the graph will also be `k^n`. The suffixes of the permutations `000, 001, 002` are `00, 01, 02`. If we treat vertices in the graph as suffixes, then we can connect the vertex `00` to `02` to represent the transformation between two different vertices(suffixes).\n\n\n\nNow we connect all the vertices in this way. Then we get a connected graph. Each edge in the graph represents a permutation of length `n`. In the example we used, `n = 3`.\n\n\n\nLet\'s go back to the problem itself. It asks us to find the shortest length of unlocking the safe. Imagine that you are pressing the keyboard and entering a sequence of digits, trying to break the safe. The sequence of digits you used is the following:\n\n\n\nThe `n` is `3`, and `k` is in the range `[0, 2]`. The first password you tried is `002`, the second is `022`, the third is `221`, and so on. The suffixes of these passwords are `02`, `22`, `21`, and so on. In the graph, it equivalents to you starting from node `00`, passing through `02`, `22`, and arrived at node `21`. The path you have gone through is shown in the following graph.\n\n\n\nIn fact, you can think of the sequence of digits that you just entered as a flattened graph. Every subsequence of length `n-1` (In this example, `n-1` is `2`.) is a vertex in the graph.\n\n\n\nNow the original problem has been completely transformed into a graph traversing problem. To make the sequence as short as possible, we just need to make sure that we traverse the above graph as short as possible. Also, since we also want to make sure the safe can be cracked in the end, we want to make sure we try each possible password of length `n` at least once. Each edge of the above graph represents a distinct password. All edges represent all possible passwords. So we want to traverse each edge at least once. Combining all these, ***we want to find a path in the graph that traverses each edge exactly once.*** If such a path exists, then we have found the shortest sequence of digits, which can surely crack the safe.\n\nThe definition of the Eulerian Path is exactly the same: it is a path in a finite graph that visits every edge exactly once. So the problem actually asks us to determine whether there is an Eulerian Path in the above graph. If so, then find it. The Eulerian Theorem tells us: \n\n* A connected graph has an Euler cycle if and only if every vertex has an even degree.\n\nIn the above graph, each vertex has `k` incoming edges and `k` outcoming edges. Therefore each vertex has `2k` connected edges, which means the above graph has an Euler cycle. The Euler cycle is also one kind of Eulerian path. Therefore we know there must be a path that covers each edge exactly once in the above graph. Now the question is: how to find it?\n\nThe solution we used is to start from node `00`. At each vertex, we choose the highest possible `k` edge. In the end, we surely go back to node `00,` and the path we have traversed is the answer. Why? How do we prove that we always got all the edge using the algorithm I described above?\n\nFirst, we can prove that we would never get stuck in any vertex except for the node where we start. In other words, we can prove that starting from any arbitrary vertex in the graph, we will surely be able to go back to this starting node. \n\nWe can use contradiction to prove this. Let\'s say the node below is where we get stuck, and this node is not the starting node. The incoming red edge is where the stuck occurred.\n\n\n\nWe are stuck at this node because all the outcoming edges have been used once. As a result, when we traverse into this node by the incoming red edge, there is no way for us to get out of this node. Since each node has the same number of incoming edges and outcoming edges, the number of used outcoming edges is `3`. That means we must also have used `3` incoming different edges before. However, we only have `3` incoming edges in total. That means we only used `2` incoming edges. This is a contradiction. Therefore we proved that we would never get stuck at any node in the middle. We can also prove that the only node we will get stuck in is the node where we started. We can use the same logic above to prove this. The difference between the starting node and the middle node is that we used the outcoming edge first in the starting node. However, for the other node, we used their incoming edge first.\n\nNow we have proved that we would only get stuck at the starting node after we have used all its outcoming and incoming edges. In other words, when the traversal ends, all edges of the starting node have been traversed. Now, if we can prove that all the edges of other nodes have been traversed, we are done. Not all kinds of traversals cover all edges of the graph. See the following example.\n\n\n\nIn this example, `n = 2` and `k = 2`. If the starting node is the vertex with value `1`, and the algorithm picks the edges from the highest value to the lowest value, then when the traversal ends, there is one edge that has not been traveled - the edge in red in the graph. How do we prove that the traversal used in our algorithm does cover all the edges?\n\nBelow is the graph of our previous example.\n\n\n\nTo remind you, the algorithm we used traverses the graph from the node `00`, and always pick the highest-value untraveled edge to go at each step. As we said before, when the algorithm ends, all the edges of the starting node are traversed. Now we go backward and look at the nodes `20` and `10`. When the algorithm goes from `20` or `10` to the node `00`, all the other edges of these two nodes must have been traversed. The reason is the edges connecting `20` or `10` to the node `00` have the lowest edge value, `0`. According to the algorithm, it means all the outcoming edges with higher values (`2`, `0`) have been traversed. Since one outcoming edge must be paired with one incoming edge, we know that when the algorithm picks the lowest-value outcoming edge, all the edges of this node must have been traversed. Thus, we can conclude that all the edges connected to nodes `20` and `10` have been covered.\n\nWe can go backward further and make the same conclusion for the nodes `22`, `12`, `02`, `01`, `21`, and `11`. Specifically, when the length of the password is `n`, starting from the starting node `0...0`, we can go `n-1` layers backward and make the same conclusion for all nodes in these `n-1` layers. The number of nodes in these layers is:\n\n`(k-1) + (k-1)*k + (k-1)*k^2 + ...... + (k-1)*k^(n-2)`\n\nWe can simplify this to:\n\n`k^(n-1) - 1`\n\nAdding the starting node, the number of nodes becomes:\n\n`k^(n-1)`\n\nTherefore, up until now, we have proved there are `k^(n-1)` nodes having all connected edges covered. The number of nodes in the graph is also `k^(n-1)`, since the number of permutations of length `n-1` is `k^(n-1)`. That proves all edges of all nodes in the graph have been traversed.\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n ava_edge = defaultdict(lambda: k-1)\n res = [\'0\'] * (n-1)\n suffix = \'\'.join(res)\n while ava_edge[suffix] >= 0:\n res.append(str(ava_edge[suffix]))\n ava_edge[suffix] -= 1\n suffix = \'\'.join(res[1-n:] if n > 1 else [])\n return \'\'.join(res)\n```\n\n | 5 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
Python Eulerian Path (Eulerian Trail) Solution | cracking-the-safe | 0 | 1 | # Intuition\nThe original problem can be formulated as finding the Eulerian Path in a finite connected graph. If you are not familiar with the concept of the Eulerian Path, please read [this Wikipedia page](https://en.wikipedia.org/wiki/Eulerian_path).\n\nLet\'s say the length of the correct password is `n`, and the possible digits are in the range `[0, k-1]`. If we enumerate all the possible permutations of length `n-1` and model them as vertices, then we get a graph. Let\'s use a concrete example, let\'s say `n = 3`, `k = 3`. Then if we draw all the permutations with length `2`, we get the following graph.\n\n\n\nNow we add one more digit to the end of these permutations. The available digits are in the range `[0, k-1]`. We model the added digit as an outgoing edge. Let\'s use the vertex `00` in the above graph as an example. After appending one more digit to this vertex, the graph will look like the following.\n \n\n\nThe formed length `n` permutations are `000, 001, 002`. These three permutations are all the permutations of length `n` with the prefix `00`. We do the same thing to all the other vertices, and then the graph will contain all the possible permutations of length `n` on a size-k alphabet. Each edge represents a distinct permutation. Since there is `k` to the power of `n` permutations, the number of edges in the graph will also be `k^n`. The suffixes of the permutations `000, 001, 002` are `00, 01, 02`. If we treat vertices in the graph as suffixes, then we can connect the vertex `00` to `02` to represent the transformation between two different vertices(suffixes).\n\n\n\nNow we connect all the vertices in this way. Then we get a connected graph. Each edge in the graph represents a permutation of length `n`. In the example we used, `n = 3`.\n\n\n\nLet\'s go back to the problem itself. It asks us to find the shortest length of unlocking the safe. Imagine that you are pressing the keyboard and entering a sequence of digits, trying to break the safe. The sequence of digits you used is the following:\n\n\n\nThe `n` is `3`, and `k` is in the range `[0, 2]`. The first password you tried is `002`, the second is `022`, the third is `221`, and so on. The suffixes of these passwords are `02`, `22`, `21`, and so on. In the graph, it equivalents to you starting from node `00`, passing through `02`, `22`, and arrived at node `21`. The path you have gone through is shown in the following graph.\n\n\n\nIn fact, you can think of the sequence of digits that you just entered as a flattened graph. Every subsequence of length `n-1` (In this example, `n-1` is `2`.) is a vertex in the graph.\n\n\n\nNow the original problem has been completely transformed into a graph traversing problem. To make the sequence as short as possible, we just need to make sure that we traverse the above graph as short as possible. Also, since we also want to make sure the safe can be cracked in the end, we want to make sure we try each possible password of length `n` at least once. Each edge of the above graph represents a distinct password. All edges represent all possible passwords. So we want to traverse each edge at least once. Combining all these, ***we want to find a path in the graph that traverses each edge exactly once.*** If such a path exists, then we have found the shortest sequence of digits, which can surely crack the safe.\n\nThe definition of the Eulerian Path is exactly the same: it is a path in a finite graph that visits every edge exactly once. So the problem actually asks us to determine whether there is an Eulerian Path in the above graph. If so, then find it. The Eulerian Theorem tells us: \n\n* A connected graph has an Euler cycle if and only if every vertex has an even degree.\n\nIn the above graph, each vertex has `k` incoming edges and `k` outcoming edges. Therefore each vertex has `2k` connected edges, which means the above graph has an Euler cycle. The Euler cycle is also one kind of Eulerian path. Therefore we know there must be a path that covers each edge exactly once in the above graph. Now the question is: how to find it?\n\nThe solution we used is to start from node `00`. At each vertex, we choose the highest possible `k` edge. In the end, we surely go back to node `00,` and the path we have traversed is the answer. Why? How do we prove that we always got all the edge using the algorithm I described above?\n\nFirst, we can prove that we would never get stuck in any vertex except for the node where we start. In other words, we can prove that starting from any arbitrary vertex in the graph, we will surely be able to go back to this starting node. \n\nWe can use contradiction to prove this. Let\'s say the node below is where we get stuck, and this node is not the starting node. The incoming red edge is where the stuck occurred.\n\n\n\nWe are stuck at this node because all the outcoming edges have been used once. As a result, when we traverse into this node by the incoming red edge, there is no way for us to get out of this node. Since each node has the same number of incoming edges and outcoming edges, the number of used outcoming edges is `3`. That means we must also have used `3` incoming different edges before. However, we only have `3` incoming edges in total. That means we only used `2` incoming edges. This is a contradiction. Therefore we proved that we would never get stuck at any node in the middle. We can also prove that the only node we will get stuck in is the node where we started. We can use the same logic above to prove this. The difference between the starting node and the middle node is that we used the outcoming edge first in the starting node. However, for the other node, we used their incoming edge first.\n\nNow we have proved that we would only get stuck at the starting node after we have used all its outcoming and incoming edges. In other words, when the traversal ends, all edges of the starting node have been traversed. Now, if we can prove that all the edges of other nodes have been traversed, we are done. Not all kinds of traversals cover all edges of the graph. See the following example.\n\n\n\nIn this example, `n = 2` and `k = 2`. If the starting node is the vertex with value `1`, and the algorithm picks the edges from the highest value to the lowest value, then when the traversal ends, there is one edge that has not been traveled - the edge in red in the graph. How do we prove that the traversal used in our algorithm does cover all the edges?\n\nBelow is the graph of our previous example.\n\n\n\nTo remind you, the algorithm we used traverses the graph from the node `00`, and always pick the highest-value untraveled edge to go at each step. As we said before, when the algorithm ends, all the edges of the starting node are traversed. Now we go backward and look at the nodes `20` and `10`. When the algorithm goes from `20` or `10` to the node `00`, all the other edges of these two nodes must have been traversed. The reason is the edges connecting `20` or `10` to the node `00` have the lowest edge value, `0`. According to the algorithm, it means all the outcoming edges with higher values (`2`, `0`) have been traversed. Since one outcoming edge must be paired with one incoming edge, we know that when the algorithm picks the lowest-value outcoming edge, all the edges of this node must have been traversed. Thus, we can conclude that all the edges connected to nodes `20` and `10` have been covered.\n\nWe can go backward further and make the same conclusion for the nodes `22`, `12`, `02`, `01`, `21`, and `11`. Specifically, when the length of the password is `n`, starting from the starting node `0...0`, we can go `n-1` layers backward and make the same conclusion for all nodes in these `n-1` layers. The number of nodes in these layers is:\n\n`(k-1) + (k-1)*k + (k-1)*k^2 + ...... + (k-1)*k^(n-2)`\n\nWe can simplify this to:\n\n`k^(n-1) - 1`\n\nAdding the starting node, the number of nodes becomes:\n\n`k^(n-1)`\n\nTherefore, up until now, we have proved there are `k^(n-1)` nodes having all connected edges covered. The number of nodes in the graph is also `k^(n-1)`, since the number of permutations of length `n-1` is `k^(n-1)`. That proves all edges of all nodes in the graph have been traversed.\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n ava_edge = defaultdict(lambda: k-1)\n res = [\'0\'] * (n-1)\n suffix = \'\'.join(res)\n while ava_edge[suffix] >= 0:\n res.append(str(ava_edge[suffix]))\n ava_edge[suffix] -= 1\n suffix = \'\'.join(res[1-n:] if n > 1 else [])\n return \'\'.join(res)\n```\n\n | 5 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
✅Python 3 - fast (95%+) - explained 😃 - de Bruijn sequence | cracking-the-safe | 0 | 1 | \n\n\n# Intuition\nIt is very intuitive that two **adjacent passwords** should **differ by first and last digits**\n- example for `n = 3`, `k = 2`:\n```\nwe have 8 (2 ** 3) different passwords\n\nsolution: 0001011100 (one of several possible solutions)\npassword 1: 000| | |\npassword 2: 001 | |\npassword 3: 010 | |\npassword 4: 101| |\npassword 5: 011 |\npassword 6: 111 |\npassword 7: 110|\npassword 8: 100\n\nlength of solution = 2 ** 3 + (3 - 1) = 10\n```\n\n# Approach\n\n---\n\n**de Bruijn sequence** - a **cyclic sequence** in which every substring **occurs exactly once**\n- description on [wiki](https://en.wikipedia.org/wiki/De_Bruijn_sequence)\n- thanks to [leetCode community](https://leetcode.com/problems/cracking-the-safe/solutions/153039/dfs-with-explanations/)\n\n---\n\n\n\n\n1. cyclic sequence (standard case)\n$$length = k^n$$\n\n- for `n = 2`, `k = 2` (c) [wiki](https://en.wikipedia.org/wiki/De_Bruijn_sequence)\n\n- for `n = 3`, `k = 2` (c) [wiki](https://en.wikipedia.org/wiki/De_Bruijn_sequence#Construction)\n\n\n\n\n\n2. non-cyclic sequense (our problem)\n$$length = k^n + (n - 1)$$\n> A de Bruijn sequence can be used to **shorten a brute-force attack on a PIN-code lock** that does not have an "enter" key and accepts the last n digits entered. \nFor example, a digital door lock with a **4-digit** code (each digit **from 0 to 9**) would have **at most 10000 + 3 = 10003**, whereas trying all codes separately would require **4 \xD7 10000 = 40000** presses. (c) [wiki - de Bruijn sequence - attacks on locks](https://en.wikipedia.org/wiki/De_Bruijn_sequence#Brute-force_attacks_on_locks)\n- once we found the **target length** for solution, we can use a simple backTracking algorithm to find it \n\n\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n\n def dfs(prv, res, res_l):\n if len(res) == trg_l: # reached target length\n res_arr.append(res)\n return\n\n prv = prv[1:] # remove first number\n for i in map(str, range(k)): # convert integer to string\n \n cur = prv + i \n if cur in visited: continue # already have current password -> skip\n\n visited.add(cur) \n dfs(cur, res + i, res_l + 1) # try to find next password\n visited.remove(cur) # this try was unsuccessful -> remove current password from set \n\n if res_arr: return # interruption: find solution -> interrupt\n\n\n\n res_arr = []\n start_p = \'0\' * n # initial password \'0..0\'\n visited = set([start_p]) \n trg_l = k ** n + (n - 1) # (n - 1) - because there is no cycle\n \n dfs(start_p, start_p, n) # previous password, solution, current length of solution \n\n return res_arr[0]\n``` | 2 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
✅Python 3 - fast (95%+) - explained 😃 - de Bruijn sequence | cracking-the-safe | 0 | 1 | \n\n\n# Intuition\nIt is very intuitive that two **adjacent passwords** should **differ by first and last digits**\n- example for `n = 3`, `k = 2`:\n```\nwe have 8 (2 ** 3) different passwords\n\nsolution: 0001011100 (one of several possible solutions)\npassword 1: 000| | |\npassword 2: 001 | |\npassword 3: 010 | |\npassword 4: 101| |\npassword 5: 011 |\npassword 6: 111 |\npassword 7: 110|\npassword 8: 100\n\nlength of solution = 2 ** 3 + (3 - 1) = 10\n```\n\n# Approach\n\n---\n\n**de Bruijn sequence** - a **cyclic sequence** in which every substring **occurs exactly once**\n- description on [wiki](https://en.wikipedia.org/wiki/De_Bruijn_sequence)\n- thanks to [leetCode community](https://leetcode.com/problems/cracking-the-safe/solutions/153039/dfs-with-explanations/)\n\n---\n\n\n\n\n1. cyclic sequence (standard case)\n$$length = k^n$$\n\n- for `n = 2`, `k = 2` (c) [wiki](https://en.wikipedia.org/wiki/De_Bruijn_sequence)\n\n- for `n = 3`, `k = 2` (c) [wiki](https://en.wikipedia.org/wiki/De_Bruijn_sequence#Construction)\n\n\n\n\n\n2. non-cyclic sequense (our problem)\n$$length = k^n + (n - 1)$$\n> A de Bruijn sequence can be used to **shorten a brute-force attack on a PIN-code lock** that does not have an "enter" key and accepts the last n digits entered. \nFor example, a digital door lock with a **4-digit** code (each digit **from 0 to 9**) would have **at most 10000 + 3 = 10003**, whereas trying all codes separately would require **4 \xD7 10000 = 40000** presses. (c) [wiki - de Bruijn sequence - attacks on locks](https://en.wikipedia.org/wiki/De_Bruijn_sequence#Brute-force_attacks_on_locks)\n- once we found the **target length** for solution, we can use a simple backTracking algorithm to find it \n\n\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n\n def dfs(prv, res, res_l):\n if len(res) == trg_l: # reached target length\n res_arr.append(res)\n return\n\n prv = prv[1:] # remove first number\n for i in map(str, range(k)): # convert integer to string\n \n cur = prv + i \n if cur in visited: continue # already have current password -> skip\n\n visited.add(cur) \n dfs(cur, res + i, res_l + 1) # try to find next password\n visited.remove(cur) # this try was unsuccessful -> remove current password from set \n\n if res_arr: return # interruption: find solution -> interrupt\n\n\n\n res_arr = []\n start_p = \'0\' * n # initial password \'0..0\'\n visited = set([start_p]) \n trg_l = k ** n + (n - 1) # (n - 1) - because there is no cycle\n \n dfs(start_p, start_p, n) # previous password, solution, current length of solution \n\n return res_arr[0]\n``` | 2 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
Not too complicated | cracking-the-safe | 0 | 1 | # Intuition\n\n\n# Approach\nFirstly create a directed graph where verticies are all k**n possible passwords, and there is an edge a-b if an end of a vertex "a" is a start of vertex "b" (a[1:] == b[:-1]). Then You just need to get a tour: a noncyclic way through all verticies. Starting with "0" * n vertex, append only the last digit of each other vertex dfs goes through. \n\n# Complexity\n- Time complexity:\nobviously O(k**n) ~ 45 ms\n\n- Space complexity:\nO(k**n) ~ 21.5 mb\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n from itertools import product\n\n def get_graph(span: int, pass_len: int) -> (int, dict[str, list[tuple[str]]]):\n\n graph = {}\n n_vertx = 0\n\n for element in product(map(str, range(span)), repeat=pass_len):\n graph.setdefault(element[:-1], []).append(element)\n n_vertx += 1\n\n return n_vertx, graph\n\n\n def solve(graph: dict[str, list[tuple[str]]], n_vertex: int, n: int):\n\n def go(seen: set[tuple[str]], way: list[str], vertex: tuple[str]):\n if len(seen) == n_vertex:\n return way\n\n for neib in graph[vertex[1:]]:\n if neib not in seen:\n way.append(neib[-1])\n seen.add(neib)\n ret = go(seen, way, neib)\n if ret: return way\n way.pop()\n seen.discard(neib)\n return False\n\n start = tuple(\'0\' for _ in range(n))\n seen = set()\n seen.add(start)\n result = go(seen, [\'\'.join(start)], start)\n return \'\'.join(result)\n \n if n == 1: return \'\'.join(map(str, range(k)))\n if k == 1: return "0" * n\n n_v, gr = get_graph(k, n)\n return solve(gr, n_v, n)\n\n``` | 0 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
Not too complicated | cracking-the-safe | 0 | 1 | # Intuition\n\n\n# Approach\nFirstly create a directed graph where verticies are all k**n possible passwords, and there is an edge a-b if an end of a vertex "a" is a start of vertex "b" (a[1:] == b[:-1]). Then You just need to get a tour: a noncyclic way through all verticies. Starting with "0" * n vertex, append only the last digit of each other vertex dfs goes through. \n\n# Complexity\n- Time complexity:\nobviously O(k**n) ~ 45 ms\n\n- Space complexity:\nO(k**n) ~ 21.5 mb\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n from itertools import product\n\n def get_graph(span: int, pass_len: int) -> (int, dict[str, list[tuple[str]]]):\n\n graph = {}\n n_vertx = 0\n\n for element in product(map(str, range(span)), repeat=pass_len):\n graph.setdefault(element[:-1], []).append(element)\n n_vertx += 1\n\n return n_vertx, graph\n\n\n def solve(graph: dict[str, list[tuple[str]]], n_vertex: int, n: int):\n\n def go(seen: set[tuple[str]], way: list[str], vertex: tuple[str]):\n if len(seen) == n_vertex:\n return way\n\n for neib in graph[vertex[1:]]:\n if neib not in seen:\n way.append(neib[-1])\n seen.add(neib)\n ret = go(seen, way, neib)\n if ret: return way\n way.pop()\n seen.discard(neib)\n return False\n\n start = tuple(\'0\' for _ in range(n))\n seen = set()\n seen.add(start)\n result = go(seen, [\'\'.join(start)], start)\n return \'\'.join(result)\n \n if n == 1: return \'\'.join(map(str, range(k)))\n if k == 1: return "0" * n\n n_v, gr = get_graph(k, n)\n return solve(gr, n_v, n)\n\n``` | 0 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
hamilton path --> eulerian path | cracking-the-safe | 0 | 1 | It\'s easy to generate all the possible passwords of length n using k digits. At first glance, this problem seems like an eulerian path finding problem. However, if we think of each password as a node in the graph, soon we can see it\'s not about finding eulerian path (going through each edge once) but about finding hamilton path (going through each vertex once). Hamilton path is hard, darn hard. \n\nBut we can in fact reduce this problem to an eulerian path problem. Take n=2, k=2 example, all possible passwords are:\n\n```\n00\n01\n10\n11\n```\n\nIf we think of each password as an edge, then each edge is connecting state 0/1 with each other or to itself.\n\nTry n=3,k=3:\n```\n000: 00 -> 00\n001: 00 -> 01\n002: 00 -> 02\n010: 01 -> 10\n011: 01 -> 11\n012: 01 -> 12\n020: 02 -> 20\n021: 02 -> 21\n022: 02 -> 22\n100: 10 -> 00\n101: 10 -> 01\n102: 10 -> 02\n110: 11 -> 10\n111: 11 -> 11\n112: 11 -> 12\n120: 12 -> 20\n121: 12 -> 21\n122: 12 -> 22\n200: 20 -> 00\n201: 20 -> 01\n202: 20 -> 02\n210: 21 -> 10\n211: 21 -> 11\n212: 21 -> 12\n220: 22 -> 20\n221: 22 -> 21\n222: 22 -> 22\n```\n\ni.e. for edge of length n, we\'re connecting state `edge[:-1]` to state `edge[1:]`. Since there are k digits, it means state `edge[:-1]` can go out to k different states, and `edge[1:]` can come from k different states. So the indegree is always equal to the outdegree, this means an eulerian cycle.\n\nSince we know for sure there\'s a cycle, we can simply use similar algorithm to these problems, more details in the following links:\n- https://leetcode.com/problems/reconstruct-itinerary/solutions/4372637/eulerian-path-linear-time/\n- https://leetcode.com/problems/valid-arrangement-of-pairs/solutions/4372277/eulerian-path-linear-time/\n\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n digits = [str(i) for i in range(k)]\n if n == 1:\n return "".join(digits)\n def gen_states(path, edges):\n if len(path) == n:\n edges.append("".join(path))\n return\n\n for d in digits:\n path.append(d)\n gen_states(path, edges)\n path.pop()\n\n edges = []\n gen_states([], edges)\n\n # each edge connects node edge[:-1] to node edge[1:]\n # it\'s easy to see that this way each node has exactly indegree=outdegree=k\n # hence finding the eulerian path within this graph will result in going through\n # each edge once, which is what we want\n from collections import defaultdict\n graph = defaultdict(list)\n for edge in edges:\n fr = edge[:-1]\n to = edge[1:]\n graph[fr].append(to)\n \n # eulerian path finding, since there is a cycle we can start from any node\n stack = [edges[0][:-1]]\n res = []\n while stack:\n top = stack[-1]\n if not graph[top]:\n res.append(stack.pop())\n else:\n stack.append(graph[top].pop())\n \n res = res[::-1]\n path = [res[0]]\n for i in range(1, len(res)):\n path.append(res[i][-1])\n return "".join(path)\n\n\n``` | 0 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
hamilton path --> eulerian path | cracking-the-safe | 0 | 1 | It\'s easy to generate all the possible passwords of length n using k digits. At first glance, this problem seems like an eulerian path finding problem. However, if we think of each password as a node in the graph, soon we can see it\'s not about finding eulerian path (going through each edge once) but about finding hamilton path (going through each vertex once). Hamilton path is hard, darn hard. \n\nBut we can in fact reduce this problem to an eulerian path problem. Take n=2, k=2 example, all possible passwords are:\n\n```\n00\n01\n10\n11\n```\n\nIf we think of each password as an edge, then each edge is connecting state 0/1 with each other or to itself.\n\nTry n=3,k=3:\n```\n000: 00 -> 00\n001: 00 -> 01\n002: 00 -> 02\n010: 01 -> 10\n011: 01 -> 11\n012: 01 -> 12\n020: 02 -> 20\n021: 02 -> 21\n022: 02 -> 22\n100: 10 -> 00\n101: 10 -> 01\n102: 10 -> 02\n110: 11 -> 10\n111: 11 -> 11\n112: 11 -> 12\n120: 12 -> 20\n121: 12 -> 21\n122: 12 -> 22\n200: 20 -> 00\n201: 20 -> 01\n202: 20 -> 02\n210: 21 -> 10\n211: 21 -> 11\n212: 21 -> 12\n220: 22 -> 20\n221: 22 -> 21\n222: 22 -> 22\n```\n\ni.e. for edge of length n, we\'re connecting state `edge[:-1]` to state `edge[1:]`. Since there are k digits, it means state `edge[:-1]` can go out to k different states, and `edge[1:]` can come from k different states. So the indegree is always equal to the outdegree, this means an eulerian cycle.\n\nSince we know for sure there\'s a cycle, we can simply use similar algorithm to these problems, more details in the following links:\n- https://leetcode.com/problems/reconstruct-itinerary/solutions/4372637/eulerian-path-linear-time/\n- https://leetcode.com/problems/valid-arrangement-of-pairs/solutions/4372277/eulerian-path-linear-time/\n\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n digits = [str(i) for i in range(k)]\n if n == 1:\n return "".join(digits)\n def gen_states(path, edges):\n if len(path) == n:\n edges.append("".join(path))\n return\n\n for d in digits:\n path.append(d)\n gen_states(path, edges)\n path.pop()\n\n edges = []\n gen_states([], edges)\n\n # each edge connects node edge[:-1] to node edge[1:]\n # it\'s easy to see that this way each node has exactly indegree=outdegree=k\n # hence finding the eulerian path within this graph will result in going through\n # each edge once, which is what we want\n from collections import defaultdict\n graph = defaultdict(list)\n for edge in edges:\n fr = edge[:-1]\n to = edge[1:]\n graph[fr].append(to)\n \n # eulerian path finding, since there is a cycle we can start from any node\n stack = [edges[0][:-1]]\n res = []\n while stack:\n top = stack[-1]\n if not graph[top]:\n res.append(stack.pop())\n else:\n stack.append(graph[top].pop())\n \n res = res[::-1]\n path = [res[0]]\n for i in range(1, len(res)):\n path.append(res[i][-1])\n return "".join(path)\n\n\n``` | 0 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
easy solution from iu7-11b bmstu to Kvasnikov V2 with recursion | cracking-the-safe | 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 ans = \'\'\n def crackSafe(self, n: int, k: int) -> str:\n def gCd(seq):\n subSeq = seq[1:]\n for i in range(k-1, -1, -1):\n if subSeq + str(i) not in dict_seq.keys():\n self.ans += str(i)\n dict_seq[subSeq + str(i)] = True\n gCd(subSeq + str(i))\n return\n dict_seq = {\'0\'*n: True}\n self.ans = \'0\'*n\n gCd(self.ans)\n return self.ans\n``` | 0 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
easy solution from iu7-11b bmstu to Kvasnikov V2 with recursion | cracking-the-safe | 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 ans = \'\'\n def crackSafe(self, n: int, k: int) -> str:\n def gCd(seq):\n subSeq = seq[1:]\n for i in range(k-1, -1, -1):\n if subSeq + str(i) not in dict_seq.keys():\n self.ans += str(i)\n dict_seq[subSeq + str(i)] = True\n gCd(subSeq + str(i))\n return\n dict_seq = {\'0\'*n: True}\n self.ans = \'0\'*n\n gCd(self.ans)\n return self.ans\n``` | 0 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
easy solution from iu7-11b bmstu to Kvasnikov | cracking-the-safe | 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 crackSafe(self, n: int, k: int) -> str:\n \n alph=\'\'\n for i in range(k):\n alph+=str(i)\n\n parol=\'0\'*n\n sklad=[]\n sklad.append(parol)\n c = k - 1\n h = i = 0\n\n while len(sklad) < k ** n:\n p=parol[i+1 - h:]+alph[c]\n if p not in sklad:\n c = k - 1\n sklad.append(p)\n parol += p[-1]\n else:\n h+=1\n c-=1\n i+=1\n return parol\n``` | 0 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
easy solution from iu7-11b bmstu to Kvasnikov | cracking-the-safe | 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 crackSafe(self, n: int, k: int) -> str:\n \n alph=\'\'\n for i in range(k):\n alph+=str(i)\n\n parol=\'0\'*n\n sklad=[]\n sklad.append(parol)\n c = k - 1\n h = i = 0\n\n while len(sklad) < k ** n:\n p=parol[i+1 - h:]+alph[c]\n if p not in sklad:\n c = k - 1\n sklad.append(p)\n parol += p[-1]\n else:\n h+=1\n c-=1\n i+=1\n return parol\n``` | 0 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
Easiest Hard Problem Logic Explained | cracking-the-safe | 0 | 1 | # Intuition\nFind the string which follow this property strictly:-\nEvery following string must contain n-1 digits from previous string\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBacktrack to find the only solution maintaining the property as discussed can have any permutation as starting\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(k**n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(k**n) storing done \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n done={\'0\'*n}\n ans=[\'\']\n def do(c):\n if(len(done)==k**n):\n return (\'\',True)\n for i in range(k):\n if(c[1:]+str(i) not in done):\n done.add(c[1:]+str(i))\n fin=do(c[1:]+str(i))\n if(fin[-1]):\n return (str(i)+fin[0],True)\n done.remove(c[1:]+str(i))\n return (\'\',False)\n return \'0\'*n+do("0"*n)[0]\n \n \n``` | 0 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
Easiest Hard Problem Logic Explained | cracking-the-safe | 0 | 1 | # Intuition\nFind the string which follow this property strictly:-\nEvery following string must contain n-1 digits from previous string\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBacktrack to find the only solution maintaining the property as discussed can have any permutation as starting\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(k**n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(k**n) storing done \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n done={\'0\'*n}\n ans=[\'\']\n def do(c):\n if(len(done)==k**n):\n return (\'\',True)\n for i in range(k):\n if(c[1:]+str(i) not in done):\n done.add(c[1:]+str(i))\n fin=do(c[1:]+str(i))\n if(fin[-1]):\n return (str(i)+fin[0],True)\n done.remove(c[1:]+str(i))\n return (\'\',False)\n return \'0\'*n+do("0"*n)[0]\n \n \n``` | 0 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
DFS | Making password and checking if already exists | cracking-the-safe | 0 | 1 | \n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n # the requirement is to have minimum length substring which contains all possible passwords of length n using [0,k-1] digits \n\n # Approach is simple , start with a possible password and in next step take last n-1 digits and add one of [0,k-1] to get next password and check if we already have create the password to avoid redundancy , this will always be optimal . \n\n strt = "".join("0" for _ in range(n)) \n strtAns = [strt]\n visited = set() \n visited.add(strt)\n \n\n def dfs(curr , visited , ttl) :\n if(len(visited) ==ttl ) : return True \n\n for i in range(k) :\n ch = str(i) \n newP = ch \n if(n != 1) :\n newP = curr[0][-(n-1) :] + ch\n print(newP)\n if(newP not in visited) :\n visited.add(newP) \n curr[0] = curr[0]+ch\n if(dfs(curr , visited , ttl)) : return True \n visited.remove(newP)\n curr[0] = curr[0][:-1]\n return False \n\n\n dfs(strtAns , visited , k**n) \n return strtAns[0]\n\n``` | 0 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
DFS | Making password and checking if already exists | cracking-the-safe | 0 | 1 | \n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n # the requirement is to have minimum length substring which contains all possible passwords of length n using [0,k-1] digits \n\n # Approach is simple , start with a possible password and in next step take last n-1 digits and add one of [0,k-1] to get next password and check if we already have create the password to avoid redundancy , this will always be optimal . \n\n strt = "".join("0" for _ in range(n)) \n strtAns = [strt]\n visited = set() \n visited.add(strt)\n \n\n def dfs(curr , visited , ttl) :\n if(len(visited) ==ttl ) : return True \n\n for i in range(k) :\n ch = str(i) \n newP = ch \n if(n != 1) :\n newP = curr[0][-(n-1) :] + ch\n print(newP)\n if(newP not in visited) :\n visited.add(newP) \n curr[0] = curr[0]+ch\n if(dfs(curr , visited , ttl)) : return True \n visited.remove(newP)\n curr[0] = curr[0][:-1]\n return False \n\n\n dfs(strtAns , visited , k**n) \n return strtAns[0]\n\n``` | 0 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
Very short DFS without backtracking in Python, faster than 94% | cracking-the-safe | 0 | 1 | # Complexity\n- Time complexity: $$O(n^k)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^k)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n visited = set()\n mod = 10 ** n\n def dfs(v):\n visited.add(v)\n for i in list(range(v % 10 + 1, k)) + list(range(v % 10, -1, -1)):\n if (u := (v * 10 + i) % mod) not in visited:\n return str(i) + dfs(u)\n return ""\n return "0" * n + dfs(0) \n```\n\nThe recursion can be revised to loop easily. The following implementation faster than 98%.\n\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n visited = set()\n mod = 10 ** n\n ans = "0" * n\n v = 0\n while True:\n visited.add(v)\n for i in list(range(v % 10 + 1, k)) + list(range(v % 10, -1, -1)):\n if (u := (v * 10 + i) % mod) not in visited:\n ans += str(i)\n v = u\n break\n else:\n break\n return ans | 0 | There is a safe protected by a password. The password is a sequence of `n` digits where each digit can be in the range `[0, k - 1]`.
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the **most recent** `n` **digits** that were entered each time you type a digit.
* For example, the correct password is `"345 "` and you enter in `"012345 "`:
* After typing `0`, the most recent `3` digits is `"0 "`, which is incorrect.
* After typing `1`, the most recent `3` digits is `"01 "`, which is incorrect.
* After typing `2`, the most recent `3` digits is `"012 "`, which is incorrect.
* After typing `3`, the most recent `3` digits is `"123 "`, which is incorrect.
* After typing `4`, the most recent `3` digits is `"234 "`, which is incorrect.
* After typing `5`, the most recent `3` digits is `"345 "`, which is correct and the safe unlocks.
Return _any string of **minimum length** that will unlock the safe **at some point** of entering it_.
**Example 1:**
**Input:** n = 1, k = 2
**Output:** "10 "
**Explanation:** The password is a single digit, so enter each digit. "01 " would also unlock the safe.
**Example 2:**
**Input:** n = 2, k = 2
**Output:** "01100 "
**Explanation:** For each possible password:
- "00 " is typed in starting from the 4th digit.
- "01 " is typed in starting from the 1st digit.
- "10 " is typed in starting from the 3rd digit.
- "11 " is typed in starting from the 2nd digit.
Thus "01100 " will unlock the safe. "10011 ", and "11001 " would also unlock the safe.
**Constraints:**
* `1 <= n <= 4`
* `1 <= k <= 10`
* `1 <= kn <= 4096` | We can think of this problem as a shortest path problem on a graph: there are `10000` nodes (strings `'0000'` to `'9999'`), and there is an edge between two nodes if they differ in one digit, that digit differs by 1 (wrapping around, so `'0'` and `'9'` differ by 1), and if *both* nodes are not in `deadends`. |
Very short DFS without backtracking in Python, faster than 94% | cracking-the-safe | 0 | 1 | # Complexity\n- Time complexity: $$O(n^k)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^k)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n visited = set()\n mod = 10 ** n\n def dfs(v):\n visited.add(v)\n for i in list(range(v % 10 + 1, k)) + list(range(v % 10, -1, -1)):\n if (u := (v * 10 + i) % mod) not in visited:\n return str(i) + dfs(u)\n return ""\n return "0" * n + dfs(0) \n```\n\nThe recursion can be revised to loop easily. The following implementation faster than 98%.\n\n```\nclass Solution:\n def crackSafe(self, n: int, k: int) -> str:\n visited = set()\n mod = 10 ** n\n ans = "0" * n\n v = 0\n while True:\n visited.add(v)\n for i in list(range(v % 10 + 1, k)) + list(range(v % 10, -1, -1)):\n if (u := (v * 10 + i) % mod) not in visited:\n ans += str(i)\n v = u\n break\n else:\n break\n return ans | 0 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
Solution | reach-a-number | 1 | 1 | ```C++ []\nclass Solution {\n public:\n int reachNumber(int target) {\n const int newTarget = abs(target);\n int ans = 0;\n int pos = 0;\n\n while (pos < newTarget)\n pos += ++ans;\n while ((pos - newTarget) & 1)\n pos += ++ans;\n\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def reachNumber(self, target: int) -> int:\n target = abs(target)\n n = (((1 + 8 * target)**(1/2) - 1) / 2) // 1\n n = ceil((((1 + 8 * target)**(1/2) - 1) / 2))\n\n total = n * (n + 1) / 2\n reste = total - target\n if reste % 2 == 0:\n return int(n)\n\n if n % 2 == 0:\n supp = 1\n else:\n supp = 2\n\n return int(n + supp)\n```\n\n```Java []\nclass Solution {\n public int reachNumber(int target) {\n target=Math.abs(target);\n int start=1,end=target,mid,steps=0,pos=0;\n long sum=0;\n while(start<=end)\n {\n mid=start+(end-start)/2;\n sum=(long)mid*(mid+1)/2;\n if(sum>=target)\n {\n pos=(int)sum;\n steps=mid;\n end=mid-1;\n }\n else\n start=mid+1;\n }\n while((pos-target)%2!=0)\n {\n steps++;\n pos+=steps;\n }\n return steps;\n }\n}\n```\n | 1 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
754: Solution with step by step explanation | reach-a-number | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ntarget = abs(target)\n```\nThe direction to the target (left or right) doesn\'t really matter because moving to a positive target t would take the same number of moves as moving to its negative -t due to the symmetric nature of the number line. So, we can always consider the target as positive.\n\n```\nn, sum_n = 0, 0\n```\nWe initialize two variables:\n\nn represents the number of moves made.\nsum_n is the cumulative sum of the moves made. It represents the total distance covered in n moves if we only move right.\n\n```\nwhile sum_n < target or (sum_n - target) % 2 != 0:\n n += 1\n sum_n += n\n```\n\nWe need to keep moving until two conditions are met:\n\nThe total distance covered (sum_n) is at least the target.\nThe difference between sum_n and the target is even. This is because, to adjust our position to land exactly on the target, we may need to switch some of the rightward steps to leftward steps. Switching a rightward step of size i to a leftward one changes our position by -2i (because we lose i steps in the rightward direction and gain i in the leftward one). This operation always changes our position by an even number, hence the requirement for (sum_n - target) % 2 to be even.\n\n```\nreturn n\n```\n\nAfter exiting the loop, n will contain the minimum number of moves required to reach the target, so we return it.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def reachNumber(self, target: int) -> int:\n target = abs(target)\n n, sum_n = 0, 0\n \n while sum_n < target or (sum_n - target) % 2 != 0:\n n += 1\n sum_n += n\n \n return n\n``` | 1 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
✅ O(1) Walkthrough with 3 solutions + Intuition (Python) | reach-a-number | 0 | 1 | # 1. Brute Force Approach\n\n> At each step, there are only 2 choices: Go right or go left\n\n## Intuition\n1. At each step, there are only 2 choices: Go right or go left\n\t1. For instance, at our 1st step starting from 0, we can either go to -1 or 1\n2. We can form a state space, where each node represents the total of our addition and subtraction steps\n\n\n\n\n3. We can use BFS to find the optimal number of steps\n\t1. If we reach a node that is equal to the target, we found the optimal solution\n\t2. The depth of this solution node is what we need to return\n\t3. BFS guarantees that we find the optimal solution first, since we check all of the nodes depth by depth\n\n## Approach\n\n1. Initialize queue and variable to track depth\n2. While queue is not empty:\n\t1. Pop all nodes at current depth\n\t2. Expand nodes (i.e. +depth and -depth)\n\t3. If expanded node equals to target, return depth\n\t4. Append expanded nodes to queue\n\t5. depth += 1\n\n## Code\n\n```python\nclass Solution:\n\tdef reachNumber(self, target: int) -> int:\n\t\tqueue = [0]\n\t\tstep = 1\n\n\t\twhile queue:\n\t\t\tcurr_level = len(queue)\n\t\t\tfor i in range(curr_level):\n\t\t\t\tcurrent = queue.pop(0)\n\t\t\t\tgo_left = current - step\n\t\t\t\tgo_right = current + step\n\t\t\t\t\n\t\t\t\tif go_left == target or go_right == target:\n\t\t\t\t\treturn step\n\t\t\t\t\n\t\t\t\tqueue += [go_left, go_right]\n\t\t\tstep += 1\n\t\t\n\t\treturn -1\n```\n\n## Complexity\n- Time complexity: $O(2^n)$\n\t- Each level doubles the number of nodes of the previous level\n\t- We traverse through each node of the state space\n- Space complexity: $O(2^n)$\n\t- We use a queue for our BFS, which at most stores the nodes at 1 level\n\t- The number of nodes at 1 level is upper-bounded by the total number of nodes $2^n$\n\n## Can We Always Reach a Solution?\n- **Important question to answer**: Since if there is no solution, the BFS will not terminate\n- Answer: **Yes**\n\t- We can always move by 1, by going in opposite directions for 2 steps (i.e. $-1 + 2 = 1$)\n\t- Using this method, we can reach any integer\n\n## Potential Optimizations\n- From the above diagram, we can see that we run into repeated states. We can use a hash table to skip visited states\n\t- We save on time using space\n- But this solution gives us Time Limit Exceeded (TLE). How can we further optimize this?\n\n# 2. Mathematical Approach\n\n## Intuition\n\nLet\'s run through some examples to understand the problem more:\n\n1. Target: 6\n\t- Solution: 3 steps; $0 + 1 + 2 + 3 = 6$\n\t- **Observation #1**: Given that it\'s possible, least number of steps to reach a target is done by always going in 1 direction\n2. Target: 8\n\t- Impossible to reach 8 within 3 steps, since the maximum we can reach is 6\n\t- Next possible minimum number of moves is 4\n\t- If we add all of the 4 steps (i.e. $0 + 1 + 2 + 3 + 4 = 10$), we go over 8\n\t- Intuitively, how can we subtract 2 from 10 to reach 8?\n\t\t- The intuitive way of flipping $+2$ to $-2$ does not work, since that subtracts 4 from 10\n\t\t- We can flip the $+1$ to $-1$\n\t- Solution: 4 steps; $0 - 1 + 2 + 3 + 4 = 8$\n\t- **Observation #2**: Flipping sign of some integer $n$ results in change of $2n$\n\t\t- Let $S_m$ be the first sum of positive direction steps that is greater than or equal to the target $T$ (i.e. $S_4 = 0+1+2+3+4 = 10$ when $T = 8$) and let $m$ be the number of steps to reach $S_m$\n\t\t- Given the difference $D_m = S_m - T$, can we find some integer $D_m/2$ to flip?\n\t\t- For instance, if $T = 8$ and $S_4 = 10$, $D_4 = S_4 - T = 10 - 8 = 2$. We can flip $D_4/2 = 2/2 = +1$ to $-1$ to subtract the difference of 2\n\t\t- Does this method work for all numbers?\n3. Target: 9\n\t- Same as before: \n\t\t- Impossible to reach 9 within 3 steps, since the maximum we can reach is 6\n\t\t- Next possible minimum number of moves is 4\n\t\t- If we add all of the 4 steps (i.e. $0 + 1 + 2 + 3 + 4 = 10$), we go over 9\n\t- $D_4 = S_4 - T = 10 - 9 = 1$. But there is no $1/2$ to flip\n\t- **Observation #3**: Given an odd difference between $S_m$ and $T$, we cannot reach the target by simply flipping signs\n\t\t- Why? From observation #2, flipping signs can only result in an even change to $S_m$\n\t- Impossible to reach 9 within 4 steps\n\t- Next possible minimum number of moves is 5\n\t- Let $S_{5}= 0+1+2+3+4+5 = 15$ (i.e. Sum from adding another step)\n\t- $D_{5} = S_{5} - T = 15-9 = 6$. We can use same method of flipping the sign for $D/2 = 6/2 = +3$\n\t- Solution: 5 steps; $0+1+2-3+4+5 = 9$\n- But what if the difference $D_{m+1}$ after adding another step is still odd?\n\n| $D_m$ | $D_{m+1}$ | $D_{m+2}$ |\n| ----- | --------- | --------- |\n| Odd | Odd | ? |\n\n- For this to happen, $m+1$ must be even, since only $odd + even = odd$\n- This implies that $m + 2$ must be odd, since the parity of the steps alternate at each step\n\n| $D_m$ | $D_{m+1}$ | $D_{m+2}$ |\n| ----- | --------- | --------- |\n| Odd | Odd | Even |\n\n- Since we always get an even difference eventually by adding more steps, we can use the $D/2$ method to find an integer to flip\n- Thus, the solution will be either $m$ or $m +1$ or $m+2$\n- Let\'s try the method out!\n4. Target: 5\n\t- Impossible to reach 5 within 2 steps, since the maximum we can reach is 3\n\t- Next possible minimum number of moves is 3\n\t- $S_3 = 0 + 1 + 2+ 3 = 6$\n\t- $D_3 = S_3 - T = 6-5 = 1$. But there is no $1/2$ to flip\n\t- Impossible to reach 5 within 3 steps. Next possible minimum number of moves is 4\n\t- $S_{4} = 0+1+2+3+4=10$\n\t- $D_{4} = S_{4} - T = 10-5 = 5$. But there is no $5/2$ to flip\n\t- Impossible to reach 5 within 4 steps. Next possible minimum number of moves is 5\n\t- $S_{5} = 0+1+2+3+4+5=15$\n\t- $D_{5} = S_{5} - T = 15-5 = 10$\n\t- $D_5/2 = 10/2 = +5$. We can flip $+5$ to $-5$\n\t- Solution: 5 steps; $0+1+2+3+4-5=5$\n\t- Nice, seems we have an approach! But what about negative targets?\n5. Target: -6\n\t- Solution: 3 steps; $0 - 1 - 2 - 3 = -6$\n\t- Same number of steps as when target is 6, except we flip all of the signs\n\t- **Observation #4**: Given target $n$, $reachNumber(n) = reachNumber(-n)$\n\n### Summary\n1. Given that it\'s possible, least number of steps to reach a target is done by always going in 1 direction\n2. Flipping sign of some integer $n$ results in change of $2n$\n3. Given an odd difference between $S_m$ and $T$, we cannot reach the target by simply flipping signs\n4. Given target $n$, $reachNumber(n) = reachNumber(-n)$\n\n## Approach\n\n1. Take absolute value of target\n2. Initialize variable to track number of steps and sum\n3. Loop to get $S_m$ such that $S_m$ is the first sum of positive direction steps that is greater than or equal to the target $T$\n4. If difference between $S_m$ and target is even, return number of steps\n5. Else, keep adding more steps until difference is even\n\n## Code\n```python\nclass Solution:\n def reachNumber(self, target: int) -> int:\n target = abs(target)\n step = total = 0\n\n while total < target:\n step += 1\n total += step\n \n while (total - target) % 2 != 0:\n step += 1\n total += step\n\n return step\n \n```\n\n## Time Complexity\n- Time complexity: $O(\\sqrt{n})$\n\t- Only the 1st loop to get that initial $S_m$ is costly. How many additions do we perform to reach $n$? $O(\\sqrt n)$\n\t\t- This [video](https://youtu.be/9TlHvipP5yA) explains quite nicely on how to derive this. Start from 6:09.\n\t- The 2nd loop is guaranteed to end after 2 iterations, so it\'s constant regardless of $n$\n\t- But can we optimize both of these loops more?\n- Space complexity: $O(1)$\n\n# 3. $O(1)$ Approach\n\n## Intuition\n- From the previous approach, the 1st loop finds the initial $S_m$ and $m$. Can we find them without a loop?\n- In other words, we want to find $m = \\lceil n \\rceil$ (i.e. Rounded up) where $0+1+2+...+n = T$\n- Note that $0+1+2+...+n$ is an arithmetic series, which has a formula:\n\t- $S_n = \\frac{n}{2} (2a + (n-1)d)$ where $a$ is starting number and $d$ is the difference between numbers in the sequence\n\t- In $0+1+2+...+n$, $a = 1$ and $d = 1$\n\t- $0+1+2+...+n = \\frac{n}{2} (2(1)+(n-1)(1)) = \\frac{n}{2} (n+1)$\n- We can simplify the above equation to:\n\t- $\\frac{n}{2} (n+1) = T$\n\t- $n^2 + n = 2T$\n\t- $n^2 + n - 2T = 0$\n\t- $n = \\frac{-1 \\pm \\sqrt{1+8T}}{2}$ (Using [quadratic formula](https://en.wikipedia.org/wiki/Quadratic_formula))\n\t- $n = \\frac{-1 + \\sqrt{1+8T}}{2}$ (Reject negative sign, since number of steps needs to be positive)\n\t- **Observation #5**: $m = \\lceil n \\rceil = \\lceil \\frac{-1 + \\sqrt{1+8T}}{2} \\rceil$\n- From the previous approach, the 2nd loop adds more steps until the difference is even\n\t- Though the 2nd loop is $O(1)$, a small and neat optimization can be made from the following observation\n\t- **Observation #6**: The edge case of $m + 2$ steps only happens when $m$ is odd\n\n| $D_m$ | $D_{m+1}$ | $D_{m+2}$ |\n| ----- | --------- | --------- |\n| Odd | Odd | Even |\n\n- Recall from previous approach: $m + 1$ must be even\n- Thus, $m$ must be odd\n\n## Approach\n\n1. Take absolute value of target\n2. Find $m= \\lceil \\frac{-1 + \\sqrt{1+8T}}{2} \\rceil$ and $S_m = \\frac{m}{2} (m+1)$\n3. If difference between $S_m$ and target is even, return $m$\n\t1. This covers the case of when $S_m$ is equal to target\n4. Else, it means that we need to add more steps (i.e. Solution is either $m+1$ or $m+2$)\n5. Return $m+2$ if $m$ is odd\n6. Return $m+1$ if $m$ is even\n\n## Code\n\n```python\nclass Solution:\n\tdef reachNumber(self, target: int) -> int:\n\t\ttarget = abs(target)\n\t\tm = math.ceil((math.sqrt(1 + 8 * target) - 1) / 2)\n\t\ttotal = m * (m + 1) / 2\n\t\t\n\t\tif (total - target) % 2 == 0:\n\t\t\treturn n\n\t\treturn n + 2 if n % 2 == 1 else n + 1\n```\n\n \n\n## Complexity\n\n- Time complexity: $O(1)$\n- Space complexity: $O(1)$\n\n# 4. Conclusion\n\nWhile this question is quite \'mathey\', I hope I showed the process of deriving this solution logically and intuitively. Hope this walkthrough helped you! :) | 10 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
"Python" easy explanation blackboard | reach-a-number | 0 | 1 | **The approach is explained in the image**\n*Simple and easy python3 solution*\nNote:- The minimum steps to target is same as the minimum steps to abs(target).\n\n\n```\nclass Solution:\n def reachNumber(self, target: int) -> int:\n ans, k = 0, 0\n target = abs(target)\n while ans < target:\n ans += k\n k += 1\n while (ans - target) % 2:\n ans += k\n k += 1\n return k - 1 \n```\n | 24 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
Python 3 Binary Search/Math Explained | reach-a-number | 0 | 1 | ```\nclass Solution:\n def reachNumber(self, target: int) -> int:\n """\n This program uses math and binary search to determine\n the minimum number of steps needed to reach the given\n target value (target).\n\n :param target: target number to reach\n :type target: int\n :return: minimum steps to reach target\n :rtype: int\n """\n\n def enough_steps(steps) -> bool:\n """\n This routine determines whether the candidate number\n of steps (steps) is enough to equal or exceed the\n target.\n\n :param steps: candidate number of steps to reach\n target\n :type steps: int\n :return: True if steps, the variable, is greater\n than or equal to the number of steps needed\n to reach target, else False\n :rtype: bool\n """\n\n """\n Return True if the total distance traveled by the\n candidate number of steps equals or exceeds target.\n Otherwise, return False.\n """\n if steps * (steps + 1) // 2 >= target:\n return True\n return False\n\n """\n Binary Search:\n - Since the number of steps to reach target and -target\n are the same, we use the positive value of target.\n - Find minimum number of steps (min_steps) such that:\n min_steps * (min_steps + 1) // 2 >= target\n - The left index (left) will point to the correct value\n of the binary search.\n """\n target = abs(target)\n left = 1\n right = target\n while left < right:\n min_steps = left + (right - left) // 2\n if enough_steps( min_steps ):\n right = min_steps\n else:\n left = min_steps + 1\n min_steps = left\n\n """\n Adjust min_steps:\n - Determine the difference (diff) between the total\n distance traveled, min_steps * (min_steps + 1) // 2,\n and target.\n - If diff is 0, min_steps does not change.\n - If diff is even, it is possible to flip a step from\n positive to negative to get target. Again, min_steps\n does not change.\n - If diff is odd, we need to add one or two steps to\n create an even difference, at which point we can flip\n one or more steps to get target.\n """\n diff = min_steps * (min_steps + 1) // 2 - target\n if diff % 2:\n min_steps += min_steps % 2 + 1\n return min_steps\n\n``` | 9 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
O(1) math solution beats 100% with detailed explanation | reach-a-number | 1 | 1 | # Intuition\n\n<details>\n\nFirst, any negative target will require the same number of moves as its positive counterpart. You simply need to flip the signs in the sum for the movements. As such, you can make the target positive for the purposes of this function.\n- For example, $7$ requires $1 + 2 + 3 - 4 + 5$ and $-7$ requires $-1 - 2 - 3 + 4 - 5$.\n\nSecond, it is reasonable to intuit that reaching a positive target will require primarily right movements. Let\'s say these right movements are $s = 1 + 2 + \\cdots + n = \\frac{n (n + 1)}{2}$ such that the sum of the $n$ movements is at or just above the target. That is, let $n$ be an integer defined such that $s \\ge \\text{target}$ and $s - n < \\text{target}$.\n\nThen, from these $n$ right movements, let us assume that at most one movement $k$ needs to be reversed to reach the target. So, we would change $k$ in $1 + 2 + \\cdots + k + \\cdots + n$ to $-k$. This means that $s - 2k = \\text{target}$ since we not only subtract $k$ but also remove the addition of $k$. (I\'ll prove this after the code for those interested, but this is quite math intensive.)\n\nThen, we must note that $2k$ is even. When you subtract an even number from an even number, the result is even. When you subtract an even number from an odd number, the result is odd. As such, in order for $s - 2k = \\text{target}$ to be possible, $s$ and target must have the same parity (must both be even or must both be odd) for this to be possible.\n</details>\n\n# Approach\n\n<details>\n\nUsing the above intuition, we will first calculate $n$ such that it fits the above definition for $n$. Then, to ensure we have a sequence such that $s - 2k$ is viable, we will keep increasing $n$ until both the sum and target have the same parity.\n\nTo calculate $n$, we must solve $\\frac{n (n + 1)}{2} \\ge \\text{target}$ for $n$.\n\n$$\n\\begin{aligned}\n \\frac{n (n + 1)}{2} &\\ge \\text{target} \\\\\n n (n + 1) &\\ge 2 \\cdot \\text{target} \\\\\n n^2 + n - 2 \\cdot \\text{target} &\\ge 0 \\\\\n\\end{aligned}\n$$\n\nNow, we can plug this into the quadratic formula.\n\n$$\n\\begin{aligned}\n n &\\ge \\frac{-1 \\pm \\sqrt{1 - 4(1)(-2 \\cdot \\text{target})}}{2 (1)} \\\\\n n &\\ge \\frac{-1 \\pm \\sqrt{1 + 8 \\cdot \\text{target}}}{2} \\\\\n\\end{aligned}\n$$\n\nSubtracting the result of the square root from $-1$ would result in a negative value for $n$, which makes no sense in our case. As such, only the addition case for $\\pm$ is viable. So, we can replace $\\pm$ with $+$.\n\n$$\n\\begin{aligned}\n n \\ge \\frac{-1 + \\sqrt{1 + 8 \\cdot \\text{target}}}{2}\n\\end{aligned}\n$$\n\nThen, from this point, we can keep adding movements to $n$ until $\\frac{n (n+1)}{2} \\equiv \\text{target } (\\text{mod } 2)$. That is, until both sum and target have the same parity. This will require at most 2 additions since $n + 1$ and $n + 2$ have different parities and adding an even and odd number to a number changes the result\'s parity.\n\n</details>\n\n# Complexity\n\n<details>\n\n- Time complexity: $\\Theta (1)$\n\n- Space complexity: $\\Theta (1)$\n\n</details>\n\n# Code\n\n<details open>\n\nNote: I use some bitwise operations to replace some operations in the below code as shown below, but both are logically equivalent.\n- `(target - sum) % 2 == 1` is equivalent to `((target - sum) & 1) == 1`\n- `value / 2` (`value // 2` in Python) is equivalent to `value >> 1`\n\n```cpp []\npublic:\n int reachNumber(int target) {\n target = abs(target);\n \n /*\n * Note: You must use 8.0 instead of 8. Otherwise, for certain\n * permitted inputs, it will cause an integer overflow. Using 8.0\n * results in using a double, which has greater bounds, fixing the\n * issue.\n */\n const int numMovesMin = ceil(sqrt(1 + 8.0 * target) / 2 - 0.5);\n \n const int sum = numMovesMin * (numMovesMin + 1) >> 1;\n \n /*\n * If the parities of the sum and target match, keep the number of\n * moves as is. Otherwise, increase the number of moves until they\n * do (at most 2).\n */\n return (sum - target & 1) == 0\n ? numMovesMin\n : numMovesMin + 1 + (sum - target + numMovesMin + 1 & 1);\n }\n```\n\n```java []\npublic static int reachNumber(int target) {\n target = Math.abs(target);\n \n /*\n * Note: You must use 8.0 instead of 8. Otherwise, for certain\n * permitted inputs, it will cause an integer overflow. Using 8.0\n * results in using a double, which has greater bounds, fixing the\n * issue.\n */\n final int numMovesMin = (int) Math.ceil(Math.sqrt(1 + 8.0 * target) / 2 - 0.5);\n \n final int sum = numMovesMin * (numMovesMin + 1) >> 1;\n \n /*\n * If the parities of the sum and target match, keep the number of\n * moves as is. Otherwise, increase the number of moves until they\n * do (at most 2).\n */\n return (sum - target & 1) == 0\n ? numMovesMin\n : numMovesMin + 1 + (sum - target + numMovesMin + 1 & 1);\n}\n```\n\n```python []\ndef reachNumber(self, target: int) -> int:\n target = abs(target)\n \n num_moves_min = ceil(sqrt(1 + 8 * target) / 2 - 0.5)\n \n current_sum = num_moves_min * (num_moves_min + 1) >> 1\n \n # If the parities of the sum and target match, keep the number of\n # moves as is. Otherwise, increase the number of moves until they\n # do (at most 2).\n if current_sum - target & 1 == 0:\n return num_moves_min\n else:\n return num_moves_min + 1 + (current_sum - target + num_moves_min + 1 & 1)\n```\n\n</details>\n\n# Proofs\n\n<details>\n\n#### Proof that there exists a $\\bm{k}$ where $\\bm{1 \\le k \\le n}$ such that $\\bm{s - 2k = \\textbf{target}}$ if $\\bm{s > \\textbf{target}}$:\n\nWe know that $s$ and $\\text{target}$ have the same parity due to the algorithm. Therefore, we have two cases: $s$ and $\\text{target}$ are both even and $s$ and $\\text{target}$ are both odd.\n\nCase 1: $s$ and $\\text{target}$ are even:\n\n1. Then, there exists integers $m$ and $u$ such that $2m = s$ and $2u = \\text{target}$.\n2. Substituting this into the equation, we get $2m - 2k = 2u$.\n3. Manipulating the above equation, we get $k = m - u$.\n4. As $m$ and $u$ are both integers, the difference of the two is an integer. Therefore, $k$ is also a valid integer.\n5. We have confirmed that $k$ is a valid integer. Now, let us also prove that $1 \\le k \\le n$. We have two cases: $s > \\text{target}$ and $s - n < \\text{target}$ and $s - n > \\text{target}$ and $s - n - (n - 1)< \\text{target}$ (not $s = \\text{target}$ because then there is no need for a $k$).\n6. Case 1a: $s > \\text{target}$ and $s - n < \\text{target}$\n a. $s - 2k = \\text{target}$\n b. $s > s - 2k$ and $s - n < s - 2k$ (substitution with case 1a condition)\n c. $0 > -2k$ and $-n < -2k$\n d. $0 < k$ and $\\frac{n}{2} > k$\n e. $0 < k$ and $k < \\frac{n}{2}$\n f. $1 \\le k$ and $k < \\frac{n}{2}$ (since $k$ is an integer)\n Therefore as $\\frac{n}{2} \\le n$, $1 \\le k \\le n$.\n7. Case 1b: $s - n > \\text{target}$ and $s - n - (n - 1) < \\text{target}$\n a. $s - 2k = \\text{target}$\n b. $s - n > s - 2k$ and $s - n - (n - 1) < s - 2k$ (substitution with case 1b condition)\n c. $-n > -2k$ and $-2n + 1 < -2k$\n d. $\\frac{n}{2} < k$ and $n - \\frac{1}{2} > k$\n e. $\\frac{n}{2} < k$ and $k < n - \\frac{n}{2}$\n f. If $s > \\text{target}$, then $2 \\le n$. This is because $n = 1$ is only valid for the $\\text{target} = 1$ case and $n$ must be positive. Therefore, dividing both sides by $2$, we have $1 \\le \\frac{n}{2}$. As such, $1 \\le k$ and $k < n - \\frac{1}{2}$.\n g. As $n - \\frac{1}{2} < n$, we have $1 \\le k \\le n$.\n\nCase 2: $s$ and $\\text{target}$ are odd:\n1. Then, there exists integers $m$ and $u$ such that $2m + 1 = s$ and $2u + 1 = \\text{target}$.\n2. Substituting this into the equation, we get $2m + 1 - 2k = 2u + 1$.\n3. Manipulating the above equation, we get $k = m - u$.\n4. As $m$ and $u$ are both integers, the difference of the two is an integer. Therefore, $k$ is also a valid integer.\n5. We have confirmed that $k$ is a valid integer. Now, let us also prove that $1 \\le k \\le n$. We have two cases: $s > \\text{target}$ and $s - n < \\text{target}$ and $s - n > \\text{target}$ and $s - n - (n - 1)< \\text{target}$ (not $s = \\text{target}$ because then there is no need for a $k$). Without loss of generality, the same proofs for the subcases in case 1 apply here.\n\nTherefore, if $s > \\text{target}$, then there exists a $k$ such that $s - 2k = \\text{target}$ where $1 \\le k \\le n$.\n\n#### Proof of optimality\n\n1. Assume that there is a better algorithm that can reach the target in fewer or equal moves than the given algorithm with at least one case in which it is fewer.\n2. Let $a$ be the number of moves required by the current algorithm above and $b$ be the number of moves required by the better algorithm.\n3. As we know above from the intuition section, the solution for a positive target and its negative counterpart are the same. So, for the purposes of the proof, we will assume that the target is positive as things are easier to visualize.\n4. We can divide $a$ into two groups: moves that are made in the same direction as the target (right) $r_a$ and moves that are made in the opposite direction of the target (left) $l_a$. We can similarly divide $b$ into $r_b$ and $l_b$.\n5. As mentioned before, in order for the better algorithm to be better, $b \\le a$ with at least one case in which $b < a$, which means that $r_b + l_b \\le r_a + l_a$.\n6. First, if $l_a = 0$ (only right moves), then $b = a$ as there cannot be fewer right moves (won\'t reach the target) and adding any left moves will increase the total number of moves. Therefore, we need only consider cases in which $l_b > 0$.\n7. Further, since our current algorithm is optimal for 1 left move ($l_a = 1$), making the parity of the target and sum the same so that the single subtraction is possible, we need only consider cases in which $l_b > 1$.\n8. As such, we know that we only need to consider the case in which $l_b > l_a$ to find cases in which $b < a$. So, the only way that $b < a$ would be that $r_b < r_a$, specifically $r_b < r_a + 1$ as $l_b > l_a$.\n9. We also know that $r_a$ can exceed $r_b$ by at most $2$ as $r_a$ is at most $2$ more than the minimum number of moves required to reach or just exceed the target. So, $r_a - r_b \\le 2$.\n10. With the above constraints, in order for $b < a$, we are only left with the following possible case: $l_b = l_a + 1 = 2$ and $r_b = r_a - 2$. Adding any more left or right moves would make it so that $b \\ge a$, and neither can be decreased further without violating the aforementioned constraints.\n11. Then, if the above is true, then there are two integers $k_1$ and $k_2$ where $1 \\le k_1 < k_2 \\le n$ such that $s - 2 (k_1 + k_2) = t$.\n12. As there can be no more added to the right moves, we have $s - n < t < s$ based on our logic for the sum.\n13. $s - n < s - 2 (k_1 + k_2) < s$ (plugging 11 into 12).\n14. $-n < -2 (k_1 + k_2) < 0$.\n15. $\\frac{n}{2} > k_1 + k_2 > 0$.\n16. As $k_1$ and $k_2$ are less than $\\frac{n}{2}$, there exists an integer $k = k_1 + k_2$ such that $1 \\le k \\le n$ that can be negated to reach the target.\n17. Therefore, by contradiction, there is no better algorithm than the given algorithm.\n\nIf anyone has any clever ways to shorten any of the above proofs while still keeping it reasonably intuitive and understandable to the average person, please let me know!\n\n</details>\n | 0 | You are standing at position `0` on an infinite number line. There is a destination at position `target`.
You can make some number of moves `numMoves` so that:
* On each move, you can either go left or right.
* During the `ith` move (starting from `i == 1` to `i == numMoves`), you take `i` steps in the chosen direction.
Given the integer `target`, return _the **minimum** number of moves required (i.e., the minimum_ `numMoves`_) to reach the destination_.
**Example 1:**
**Input:** target = 2
**Output:** 3
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to -1 (2 steps).
On the 3rd move, we step from -1 to 2 (3 steps).
**Example 2:**
**Input:** target = 3
**Output:** 2
**Explanation:**
On the 1st move, we step from 0 to 1 (1 step).
On the 2nd move, we step from 1 to 3 (2 steps).
**Constraints:**
* `-109 <= target <= 109`
* `target != 0` | We can think of this problem as the problem of finding an Euler path (a path visiting every edge exactly once) on the following graph: there are $$k^{n-1}$$ nodes with each node having $$k$$ edges. It turns out this graph always has an Eulerian circuit (path starting where it ends.)
We should visit each node in "post-order" so as to not get stuck in the graph prematurely. |
Python Elegant & Short | Backtracking | No TLE | pyramid-transition-matrix | 0 | 1 | # Complexity\n- Time complexity: $$O(2^n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n + m)$$, where $$n$$ - length of ```bottom``` and $$m$$ - ```allowed``` size\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n @cache\n def dfs(level: str) -> bool:\n if len(level) == 1:\n return True\n\n return any(\n dfs(next_level)\n for next_level in product(*(pool[x + y] for x, y in pairwise(level)))\n )\n\n pool = defaultdict(list)\n\n for pattern in allowed:\n pool[pattern[:2]].append(pattern[2])\n\n return dfs(bottom)\n``` | 2 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains **one less block** than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific **triangular patterns** that are allowed. A triangular pattern consists of a **single block** stacked on top of **two blocks**. The patterns are given as a list of three-letter strings `allowed`, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
* For example, `"ABC "` represents a triangular pattern with a `'C'` block stacked on top of an `'A'` (left) and `'B'` (right) block. Note that this is different from `"BAC "` where `'B'` is on the left bottom and `'A'` is on the right bottom.
You start with a bottom row of blocks `bottom`, given as a single string, that you **must** use as the base of the pyramid.
Given `bottom` and `allowed`, return `true` _if you can build the pyramid all the way to the top such that **every triangular pattern** in the pyramid is in_ `allowed`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** bottom = "BCD ", allowed = \[ "BCC ", "CDE ", "CEA ", "FFF "\]
**Output:** true
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE " on level 2 and then build "A " on level 1.
There are three triangular patterns in the pyramid, which are "BCC ", "CDE ", and "CEA ". All are allowed.
**Example 2:**
**Input:** bottom = "AAAA ", allowed = \[ "AAB ", "AAC ", "BCD ", "BBE ", "DEF "\]
**Output:** false
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
**Constraints:**
* `2 <= bottom.length <= 6`
* `0 <= allowed.length <= 216`
* `allowed[i].length == 3`
* The letters in all input strings are from the set `{'A', 'B', 'C', 'D', 'E', 'F'}`.
* All the values of `allowed` are **unique**. | null |
Solution | pyramid-transition-matrix | 1 | 1 | ```C++ []\nclass Solution {\n unordered_set<string> invalid;\n bool solve(string bottom, int i, unordered_map<string,string> mp, string z)\n {\n int n=bottom.size();\n int m=z.size();\n if(n<2)\n return true;\n if(invalid.count(bottom))\n return false;\n if(m==n-1)\n return solve(z, 0, mp, "");\n if(m>1 && mp.find(z.substr(m-2,2))==mp.end())\n return false;\n for(char ch:mp[bottom.substr(i,2)]){\n z.push_back(ch);\n if(solve(bottom, i+1, mp, z))\n return true;\n z.pop_back();\n }\n invalid.insert(bottom);\n return false;\n }\npublic:\n bool pyramidTransition(string bottom, vector<string>& allowed) {\n unordered_map<string,string> mp;\n for(int i=0;i<allowed.size();i++)\n {\n mp[allowed[i].substr(0,2)].push_back(allowed[i][2]);\n }\n return solve(bottom, 0, mp, "");\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n n = len(bottom)\n mat = [[(\'X\', -1) for _ in range(n-1-i)] for i in range(n-1)]\n stack = [(row, l-row) for l in range(n-1) for row in range(l+1)]\n mapping = {}\n for a in allowed:\n if a[:2] not in mapping:\n mapping[a[:2]] = [a[2]]\n else:\n mapping[a[:2]].append(a[2])\n pos = 0\n def find_parents(row, col):\n if row == 0:\n return bottom[col:col+2]\n return mat[row-1][col][0] + mat[row-1][col+1][0]\n\n while pos >= 0 and pos < len(stack):\n row, col = stack[pos]\n me, idx = mat[row][col]\n parents = find_parents(row, col)\n options = mapping.get(parents, [])\n if idx+1 < len(options):\n idx += 1\n me = options[idx]\n mat[row][col] = (me, idx)\n pos += 1\n else:\n pos -= 1\n return pos >= len(stack)\n```\n\n```Java []\nclass Solution {\n public boolean pyramidTransition(String bottom, List<String> allowed) {\n Map<String, Set<Character>> map = new HashMap<>();\n for (String s : allowed) {\n String k = s.substring(0, 2);\n Set<Character> set = map.getOrDefault(k, new HashSet<>());\n set.add(s.charAt(2));\n map.put(k, set);\n }\n Map<String, Integer> dp = new HashMap<>();\n boolean res = search2(bottom + "#", map, dp);\n return res;\n }\n private boolean search2(String s, Map<String, Set<Character>> map, Map<String, Integer> dp) {\n if (s.length() == 1) return true;\n if (dp.containsKey(s)) return dp.get(s) == 1;\n String key = s.substring(0, 2);\n if (key.charAt(1) == \'#\') return search2(s.substring(2) + "#", map, dp);\n for (Character c : map.getOrDefault(key, new HashSet<>())) {\n boolean r = search2(s.substring(1) + c, map, dp);\n if (r) {\n dp.put(s, 1);\n return true;\n }\n }\n dp.put(s, 0);\n return false;\n }\n private boolean search(String s, Map<String, Set<Character>> map, Map<String, Integer> dp) {\n if (s.length() == 2) {\n return map.containsKey(s);\n }\n if (s.length() < 2) return false;\n List<String> nextLevel = new ArrayList<>();\n nextLevel.add("");\n for (int i = 0; i < s.length() - 1; i++) {\n List<String> list = new ArrayList<>();\n String k = s.substring(i, i + 2);\n if (!map.containsKey(k)) return false;\n for (Character e : map.get(k)) {\n for (String ps : nextLevel) {\n list.add(ps + e);\n }\n }\n nextLevel = list;\n }\n boolean res = false;\n for (String e : nextLevel) {\n res = search(e, map, dp);\n if (res) return true;\n }\n return false;\n } \n}\n```\n | 1 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains **one less block** than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific **triangular patterns** that are allowed. A triangular pattern consists of a **single block** stacked on top of **two blocks**. The patterns are given as a list of three-letter strings `allowed`, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
* For example, `"ABC "` represents a triangular pattern with a `'C'` block stacked on top of an `'A'` (left) and `'B'` (right) block. Note that this is different from `"BAC "` where `'B'` is on the left bottom and `'A'` is on the right bottom.
You start with a bottom row of blocks `bottom`, given as a single string, that you **must** use as the base of the pyramid.
Given `bottom` and `allowed`, return `true` _if you can build the pyramid all the way to the top such that **every triangular pattern** in the pyramid is in_ `allowed`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** bottom = "BCD ", allowed = \[ "BCC ", "CDE ", "CEA ", "FFF "\]
**Output:** true
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE " on level 2 and then build "A " on level 1.
There are three triangular patterns in the pyramid, which are "BCC ", "CDE ", and "CEA ". All are allowed.
**Example 2:**
**Input:** bottom = "AAAA ", allowed = \[ "AAB ", "AAC ", "BCD ", "BBE ", "DEF "\]
**Output:** false
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
**Constraints:**
* `2 <= bottom.length <= 6`
* `0 <= allowed.length <= 216`
* `allowed[i].length == 3`
* The letters in all input strings are from the set `{'A', 'B', 'C', 'D', 'E', 'F'}`.
* All the values of `allowed` are **unique**. | null |
756: Solution with step by step explanation | pyramid-transition-matrix | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ntransition = {}\nfor triplet in allowed:\n transition.setdefault(triplet[:2], []).append(triplet[2])\n```\nFor each triplet in the allowed list, we take its first two characters (which represent the bottom blocks) and map them to the third character (which represents the top block).\nThe setdefault method ensures that if the key doesn\'t already exist in the dictionary, it\'s set to an empty list.\n\n```\nmemo = {}\n```\nMemoization is a technique used to store the results of expensive function calls and return the cached result when the same inputs occur again.\nWe\'re using a dictionary called memo to store results of previously computed rows. This helps in avoiding redundant work and speeds up the solution.\n\nThe recursive function can_build is designed to check if we can build the pyramid from the given row upwards.\n\n```\nif len(row) == 1: \n return True\n```\nIf the row has only one block, then we\'ve successfully built the pyramid, so we return True.\n\n```\nnext_row = []\nfor i in range(len(row) - 1):\n if row[i:i+2] not in transition:\n return False\n next_row.append(transition[row[i:i+2]])\n```\nFor each pair of blocks in the current row, we check if there\'s a block that can be placed on top of them using the transition dictionary.\nIf a pair doesn\'t have any transitions, then we cannot build the pyramid and return False.\nOtherwise, we add all possible top blocks for this pair to the next_row\n\n```\nmemo[row] = any(can_build("".join(candidate)) for candidate in itertools.product(*next_row))\nreturn memo[row]\n```\n\nUsing itertools.product, we generate all possible combinations of the next row from the blocks in next_row.\nWe recursively call can_build on each combination.\nIf any of the combinations lead to a valid pyramid, we store the result as True in memo and return it.\n\n```\nreturn can_build(bottom)\n```\n\nStart the recursion from the given bottom row.\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 pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n transition = {}\n for triplet in allowed:\n transition.setdefault(triplet[:2], []).append(triplet[2])\n\n memo = {}\n \n def can_build(row):\n if row in memo:\n return memo[row]\n \n if len(row) == 1: \n return True\n \n next_row = []\n for i in range(len(row) - 1):\n if row[i:i+2] not in transition:\n return False\n next_row.append(transition[row[i:i+2]])\n \n memo[row] = any(can_build("".join(candidate)) for candidate in itertools.product(*next_row))\n return memo[row]\n \n return can_build(bottom)\n\n``` | 1 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains **one less block** than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific **triangular patterns** that are allowed. A triangular pattern consists of a **single block** stacked on top of **two blocks**. The patterns are given as a list of three-letter strings `allowed`, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
* For example, `"ABC "` represents a triangular pattern with a `'C'` block stacked on top of an `'A'` (left) and `'B'` (right) block. Note that this is different from `"BAC "` where `'B'` is on the left bottom and `'A'` is on the right bottom.
You start with a bottom row of blocks `bottom`, given as a single string, that you **must** use as the base of the pyramid.
Given `bottom` and `allowed`, return `true` _if you can build the pyramid all the way to the top such that **every triangular pattern** in the pyramid is in_ `allowed`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** bottom = "BCD ", allowed = \[ "BCC ", "CDE ", "CEA ", "FFF "\]
**Output:** true
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE " on level 2 and then build "A " on level 1.
There are three triangular patterns in the pyramid, which are "BCC ", "CDE ", and "CEA ". All are allowed.
**Example 2:**
**Input:** bottom = "AAAA ", allowed = \[ "AAB ", "AAC ", "BCD ", "BBE ", "DEF "\]
**Output:** false
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
**Constraints:**
* `2 <= bottom.length <= 6`
* `0 <= allowed.length <= 216`
* `allowed[i].length == 3`
* The letters in all input strings are from the set `{'A', 'B', 'C', 'D', 'E', 'F'}`.
* All the values of `allowed` are **unique**. | null |
[Python 3] BFS and DFS | pyramid-transition-matrix | 0 | 1 | BFS solution: gives TLE\n\n\tclass Solution:\n\t\t\tdef get_states(self,s,i,new,allowed):\n\t\t\t\tif i==len(s):\n\t\t\t\t\tself.res.append(\'\'.join(new))\n\t\t\t\t\treturn \n\t\t\t\tfor x in allowed[s[i-1]+s[i]]:\n\t\t\t\t\tnew.append(x)\n\t\t\t\t\tself.get_states(s,i+1,new,allowed)\n\t\t\t\t\tnew.pop()\n\n\t\t\tdef pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n\t\t\t\ta=defaultdict(list)\n\t\t\t\tfor s in allowed:\n\t\t\t\t\ta[s[:2]].append(s[2])\n\t\t\t\tself.res=[bottom]\n\t\t\t\tfor x in self.res:\n\t\t\t\t\tif len(x)==1:\n\t\t\t\t\t\treturn True\n\t\t\t\t\tself.get_states(x,1,[],a)\n\t\t\t\treturn False\n\t\t\t\t\nDFS solution: \n\n\tclass Solution:\n\t\t@cache \n\t\tdef dfs(self ,state, i, nxt):\n\t\t\tif len(state) == 1:\n\t\t\t\treturn True\n\t\t\tif len(state) - 1 == len(nxt): # we have reached the next state completely so this state is valid\n\t\t\t\treturn dfs(nxt, 0, "")\n\t\t\tif i == len(state) - 1: # we have reached the last index without moving to next state it shows this state is invalid\n\t\t\t\treturn False\n\t\t\tfor c in a[state[i]+state[i+1]]:\n\t\t\t\tif dfs(state, i+1, nxt + c):\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\n\t\tdef pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n\t\t\ta = defaultdict(list)\n\t\t\tfor s in allowed:\n\t\t\t\ta[s[:2]].append(s[2])\n\t\t\treturn self.dfs(bottom, 0, "") | 4 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains **one less block** than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific **triangular patterns** that are allowed. A triangular pattern consists of a **single block** stacked on top of **two blocks**. The patterns are given as a list of three-letter strings `allowed`, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
* For example, `"ABC "` represents a triangular pattern with a `'C'` block stacked on top of an `'A'` (left) and `'B'` (right) block. Note that this is different from `"BAC "` where `'B'` is on the left bottom and `'A'` is on the right bottom.
You start with a bottom row of blocks `bottom`, given as a single string, that you **must** use as the base of the pyramid.
Given `bottom` and `allowed`, return `true` _if you can build the pyramid all the way to the top such that **every triangular pattern** in the pyramid is in_ `allowed`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** bottom = "BCD ", allowed = \[ "BCC ", "CDE ", "CEA ", "FFF "\]
**Output:** true
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE " on level 2 and then build "A " on level 1.
There are three triangular patterns in the pyramid, which are "BCC ", "CDE ", and "CEA ". All are allowed.
**Example 2:**
**Input:** bottom = "AAAA ", allowed = \[ "AAB ", "AAC ", "BCD ", "BBE ", "DEF "\]
**Output:** false
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
**Constraints:**
* `2 <= bottom.length <= 6`
* `0 <= allowed.length <= 216`
* `allowed[i].length == 3`
* The letters in all input strings are from the set `{'A', 'B', 'C', 'D', 'E', 'F'}`.
* All the values of `allowed` are **unique**. | null |
Backtracking/Python | pyramid-transition-matrix | 0 | 1 | This is a classic backtracking problem with two important base conditions:\n1) if length of the bottom layer becomes 1, then you were able to make a pyramid\n2) if you reached the end of the bottom array, then make the top layer as current bottom layer\n```\nclass Solution:\n def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n d=defaultdict(list)\n for word in allowed:\n d[word[:2]].append(word[2])\n def dfs(bottom,i,next_layer):\n if len(bottom)==1:\n return True\n elif i==len(bottom)-1:\n if dfs(next_layer,0,""):\n return True\n else:\n return False\n else:\n word = bottom[i]+bottom[i+1]\n for char in d[word]:\n if dfs(bottom,i+1,next_layer+char):\n return True\n return False\n return dfs(bottom,0,"")\n``` | 0 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains **one less block** than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific **triangular patterns** that are allowed. A triangular pattern consists of a **single block** stacked on top of **two blocks**. The patterns are given as a list of three-letter strings `allowed`, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
* For example, `"ABC "` represents a triangular pattern with a `'C'` block stacked on top of an `'A'` (left) and `'B'` (right) block. Note that this is different from `"BAC "` where `'B'` is on the left bottom and `'A'` is on the right bottom.
You start with a bottom row of blocks `bottom`, given as a single string, that you **must** use as the base of the pyramid.
Given `bottom` and `allowed`, return `true` _if you can build the pyramid all the way to the top such that **every triangular pattern** in the pyramid is in_ `allowed`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** bottom = "BCD ", allowed = \[ "BCC ", "CDE ", "CEA ", "FFF "\]
**Output:** true
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE " on level 2 and then build "A " on level 1.
There are three triangular patterns in the pyramid, which are "BCC ", "CDE ", and "CEA ". All are allowed.
**Example 2:**
**Input:** bottom = "AAAA ", allowed = \[ "AAB ", "AAC ", "BCD ", "BBE ", "DEF "\]
**Output:** false
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
**Constraints:**
* `2 <= bottom.length <= 6`
* `0 <= allowed.length <= 216`
* `allowed[i].length == 3`
* The letters in all input strings are from the set `{'A', 'B', 'C', 'D', 'E', 'F'}`.
* All the values of `allowed` are **unique**. | null |
Easy Back tracking with no bit manipulation | pyramid-transition-matrix | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n`dfs` solution not worked for me (TLE). \n`dp way` for example, `dp[i][bottom_blocks][upper_blocks]` also not worked. (TLE)\n\nI found out that all i need to know is possibilty of generating pyramid with `allowed`, no need to find all cases. \n\n\nprouning if you can\'t find valid triangle block `XXX` for current cases `XAXAX`. \n\n\n1. make tree with `allowed`\n> for example, "AAB","AAD"\n> -- tree \n> --- node "A"\n> ---- "A"\'s node "A"\n> ----- "AA"\'s leaf is set {"B", "D"}\n\n\n\n\n\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 pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n graph = defaultdict(lambda : defaultdict(set))\n for block in allowed:\n graph[block[0]][block[1]].add(block[2])\n \n\n def backtrack(i, layer, next_layer):\n if len(layer)==0:\n return True\n\n if i == len(layer)-1:\n return backtrack(0, next_layer, "")\n \n if graph.get(layer[i], -1) == -1:\n return False\n \n if graph[layer[i]].get(layer[i+1], -1) != -1:\n for next in graph[layer[i]][layer[i+1]]:\n if backtrack(i+1, layer, next_layer+next):\n return True\n return False\n \n return backtrack(0, bottom, "")\n \n``` | 0 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains **one less block** than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific **triangular patterns** that are allowed. A triangular pattern consists of a **single block** stacked on top of **two blocks**. The patterns are given as a list of three-letter strings `allowed`, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
* For example, `"ABC "` represents a triangular pattern with a `'C'` block stacked on top of an `'A'` (left) and `'B'` (right) block. Note that this is different from `"BAC "` where `'B'` is on the left bottom and `'A'` is on the right bottom.
You start with a bottom row of blocks `bottom`, given as a single string, that you **must** use as the base of the pyramid.
Given `bottom` and `allowed`, return `true` _if you can build the pyramid all the way to the top such that **every triangular pattern** in the pyramid is in_ `allowed`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** bottom = "BCD ", allowed = \[ "BCC ", "CDE ", "CEA ", "FFF "\]
**Output:** true
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE " on level 2 and then build "A " on level 1.
There are three triangular patterns in the pyramid, which are "BCC ", "CDE ", and "CEA ". All are allowed.
**Example 2:**
**Input:** bottom = "AAAA ", allowed = \[ "AAB ", "AAC ", "BCD ", "BBE ", "DEF "\]
**Output:** false
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
**Constraints:**
* `2 <= bottom.length <= 6`
* `0 <= allowed.length <= 216`
* `allowed[i].length == 3`
* The letters in all input strings are from the set `{'A', 'B', 'C', 'D', 'E', 'F'}`.
* All the values of `allowed` are **unique**. | null |
Python, straightforward DFS with heuristic pruning | pyramid-transition-matrix | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n\nClassical DFS may got TLE.\n\nTwo heuristic pruning strategies are added to reduce the running time.\n(1) We check whether this block can make a potential base with the previous block.\n(2) We check whether this block is the "left" block of some base.\n\n# Code\n```\nclass Solution:\n def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n mem = dict()\n mem2 = set()\n for a in allowed:\n if a[:2] not in mem:\n mem[a[:2]] = list()\n \n mem2.add(a[0])\n\n mem[a[:2]].append(a[-1])\n \n n = len(bottom)\n\n def helper(cur_sol, i, j):\n if i == n:\n return True\n \n l, r = cur_sol[i - 1][j], cur_sol[i - 1][j + 1]\n if l + r in mem:\n for candidate in mem[l + r]:\n if j == 0 or (j > 0 and cur_sol[i][j - 1] + candidate in mem):\n if j == n - i - 1 or (j < n - i - 1 and candidate in mem2):\n cur_sol[i].append(candidate)\n if j < n - i - 1:\n next_i, next_j = i, j + 1\n else:\n next_i, next_j = i + 1, 0\n if helper(cur_sol, next_i, next_j):\n return True\n\n cur_sol[i].pop()\n\n return False\n\n cur_sol = [list(bottom)] + [list() for _ in range(n - 1)]\n return helper(cur_sol, 1, 0) \n\n\n``` | 0 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains **one less block** than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific **triangular patterns** that are allowed. A triangular pattern consists of a **single block** stacked on top of **two blocks**. The patterns are given as a list of three-letter strings `allowed`, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
* For example, `"ABC "` represents a triangular pattern with a `'C'` block stacked on top of an `'A'` (left) and `'B'` (right) block. Note that this is different from `"BAC "` where `'B'` is on the left bottom and `'A'` is on the right bottom.
You start with a bottom row of blocks `bottom`, given as a single string, that you **must** use as the base of the pyramid.
Given `bottom` and `allowed`, return `true` _if you can build the pyramid all the way to the top such that **every triangular pattern** in the pyramid is in_ `allowed`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** bottom = "BCD ", allowed = \[ "BCC ", "CDE ", "CEA ", "FFF "\]
**Output:** true
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE " on level 2 and then build "A " on level 1.
There are three triangular patterns in the pyramid, which are "BCC ", "CDE ", and "CEA ". All are allowed.
**Example 2:**
**Input:** bottom = "AAAA ", allowed = \[ "AAB ", "AAC ", "BCD ", "BBE ", "DEF "\]
**Output:** false
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
**Constraints:**
* `2 <= bottom.length <= 6`
* `0 <= allowed.length <= 216`
* `allowed[i].length == 3`
* The letters in all input strings are from the set `{'A', 'B', 'C', 'D', 'E', 'F'}`.
* All the values of `allowed` are **unique**. | null |
Python || Recursion || Memoization | pyramid-transition-matrix | 0 | 1 | ```\nclass Solution:\n def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:\n allowed=set(allowed)\n letters=[\'A\',\'B\',\'C\',\'D\',\'E\',\'F\']\n @lru_cache(None)\n def solve(bottom):\n if len(bottom)==1: return True\n tops=[""]\n n=len(bottom)\n ans=False\n for i in range(n-1):\n temp=[]\n while tops:\n top=tops.pop(0)\n for letter in letters:\n if bottom[i]+bottom[i+1]+letter in allowed:\n temp.append(top+letter)\n tops=temp\n for top in tops:\n ans=ans or solve(top)\n return ans\n return solve(bottom)\n \n \n \n``` | 1 | You are stacking blocks to form a pyramid. Each block has a color, which is represented by a single letter. Each row of blocks contains **one less block** than the row beneath it and is centered on top.
To make the pyramid aesthetically pleasing, there are only specific **triangular patterns** that are allowed. A triangular pattern consists of a **single block** stacked on top of **two blocks**. The patterns are given as a list of three-letter strings `allowed`, where the first two characters of a pattern represent the left and right bottom blocks respectively, and the third character is the top block.
* For example, `"ABC "` represents a triangular pattern with a `'C'` block stacked on top of an `'A'` (left) and `'B'` (right) block. Note that this is different from `"BAC "` where `'B'` is on the left bottom and `'A'` is on the right bottom.
You start with a bottom row of blocks `bottom`, given as a single string, that you **must** use as the base of the pyramid.
Given `bottom` and `allowed`, return `true` _if you can build the pyramid all the way to the top such that **every triangular pattern** in the pyramid is in_ `allowed`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** bottom = "BCD ", allowed = \[ "BCC ", "CDE ", "CEA ", "FFF "\]
**Output:** true
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 3), we can build "CE " on level 2 and then build "A " on level 1.
There are three triangular patterns in the pyramid, which are "BCC ", "CDE ", and "CEA ". All are allowed.
**Example 2:**
**Input:** bottom = "AAAA ", allowed = \[ "AAB ", "AAC ", "BCD ", "BBE ", "DEF "\]
**Output:** false
**Explanation:** The allowed triangular patterns are shown on the right.
Starting from the bottom (level 4), there are multiple ways to build level 3, but trying all the possibilites, you will get always stuck before building level 1.
**Constraints:**
* `2 <= bottom.length <= 6`
* `0 <= allowed.length <= 216`
* `allowed[i].length == 3`
* The letters in all input strings are from the set `{'A', 'B', 'C', 'D', 'E', 'F'}`.
* All the values of `allowed` are **unique**. | null |
Solution | set-intersection-size-at-least-two | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int intersectionSizeTwo(vector<vector<int>>& intervals) {\n sort(intervals.begin(), intervals.end(), [](vector<int>& a, vector<int>& b) {\n return a[1] < b[1] || (a[1] == b[1] && a[0] > b[0]); \n });\n int n = intervals.size(), ans = 0, p1 = -1, p2 = -1;\n for (int i = 0; i < n; i++) {\n if (intervals[i][0] <= p1) continue;\n if (intervals[i][0] > p2) {\n ans += 2;\n p2 = intervals[i][1];\n p1 = p2-1;\n }\n else {\n ans++;\n p1 = p2;\n p2 = intervals[i][1];\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda x:(x[1], -x[0]))\n e1, e2 = -1, -1\n ans = 0\n for s, e in intervals:\n if s > e2:\n e1, e2 = e-1, e\n ans += 2\n elif s > e1:\n e1, e2 = e2, e\n ans += 1\n return ans\n```\n\n```Java []\nimport java.util.Arrays;\n\nclass Solution {\n public int intersectionSizeTwo(int[][] intervals) {\n int n = 0;\n long[] endStartPairs = new long[intervals.length];\n for (int[] interval : intervals) {\n endStartPairs[n] = -interval[0] & 0xFFFFFFFFL;\n endStartPairs[n++] |= (long) (interval[1]) << 32;\n }\n Arrays.sort(endStartPairs);\n int min = -2;\n int max = -1;\n int curStart;\n int curEnd;\n int res = 0;\n for (long endStartPair : endStartPairs) {\n curStart = -(int) endStartPair;\n curEnd = (int) (endStartPair >> 32);\n if (curStart <= min) {\n continue;\n }\n if (curStart <= max) {\n res += 1;\n min = max;\n } else {\n res += 2;\n min = curEnd - 1;\n }\n max = curEnd;\n }\n return res;\n }\n}\n```\n | 1 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
Solution | set-intersection-size-at-least-two | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int intersectionSizeTwo(vector<vector<int>>& intervals) {\n sort(intervals.begin(), intervals.end(), [](vector<int>& a, vector<int>& b) {\n return a[1] < b[1] || (a[1] == b[1] && a[0] > b[0]); \n });\n int n = intervals.size(), ans = 0, p1 = -1, p2 = -1;\n for (int i = 0; i < n; i++) {\n if (intervals[i][0] <= p1) continue;\n if (intervals[i][0] > p2) {\n ans += 2;\n p2 = intervals[i][1];\n p1 = p2-1;\n }\n else {\n ans++;\n p1 = p2;\n p2 = intervals[i][1];\n }\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda x:(x[1], -x[0]))\n e1, e2 = -1, -1\n ans = 0\n for s, e in intervals:\n if s > e2:\n e1, e2 = e-1, e\n ans += 2\n elif s > e1:\n e1, e2 = e2, e\n ans += 1\n return ans\n```\n\n```Java []\nimport java.util.Arrays;\n\nclass Solution {\n public int intersectionSizeTwo(int[][] intervals) {\n int n = 0;\n long[] endStartPairs = new long[intervals.length];\n for (int[] interval : intervals) {\n endStartPairs[n] = -interval[0] & 0xFFFFFFFFL;\n endStartPairs[n++] |= (long) (interval[1]) << 32;\n }\n Arrays.sort(endStartPairs);\n int min = -2;\n int max = -1;\n int curStart;\n int curEnd;\n int res = 0;\n for (long endStartPair : endStartPairs) {\n curStart = -(int) endStartPair;\n curEnd = (int) (endStartPair >> 32);\n if (curStart <= min) {\n continue;\n }\n if (curStart <= max) {\n res += 1;\n min = max;\n } else {\n res += 2;\n min = curEnd - 1;\n }\n max = curEnd;\n }\n return res;\n }\n}\n```\n | 1 | We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8` | null |
757: Solution with step by step explanation | set-intersection-size-at-least-two | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n intervals.sort(key = lambda e: (e[1], -e[0]))\n```\n\nHere, we sort the intervals list based on two criteria:\n\nAscending order of the interval\'s end values (e[1]).\nFor intervals with the same end value, we sort by descending order of their start values (e[0]). This makes sure that the wider intervals come first.\n\n```\n res = [intervals[0][1]-1, intervals[0][1]]\n```\n\nWe initialize our result set res with the two largest numbers from the first interval after sorting.\n\n```\n for e in intervals[1:]:\n```\nWe iterate through the rest of the intervals.\n\n```\n if res[-2] < e[0] and res[-1] >= e[0]:\n res.append(e[1])\n```\nFor each interval, we first check if the last number in our result (res[-1]) is part of this interval and the second last number in our result (res[-2]) is not. If this is the case, we add the largest number of this interval (e[1]) to our result set.\n\n```\n elif e[0] > res[-1]:\n res.extend([e[1]-1, e[1]])\n```\nIf neither of the last two numbers in our result are in the current interval, we add the two largest numbers of this interval to our result set.\n\n```\n return len(res)\n```\nFinally, we return the length of our result set, which represents the minimum number of numbers we need to pick.\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals.sort(key = lambda e: (e[1], -e[0]))\n\n res = [intervals[0][1]-1, intervals[0][1]]\n\n for e in intervals[1:]:\n\n if res[-2] < e[0] and res[-1] >= e[0]:\n res.append(e[1])\n\n elif e[0] > res[-1]:\n res.extend([e[1]-1, e[1]])\n\n return len(res)\n\n``` | 2 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
757: Solution with step by step explanation | set-intersection-size-at-least-two | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n intervals.sort(key = lambda e: (e[1], -e[0]))\n```\n\nHere, we sort the intervals list based on two criteria:\n\nAscending order of the interval\'s end values (e[1]).\nFor intervals with the same end value, we sort by descending order of their start values (e[0]). This makes sure that the wider intervals come first.\n\n```\n res = [intervals[0][1]-1, intervals[0][1]]\n```\n\nWe initialize our result set res with the two largest numbers from the first interval after sorting.\n\n```\n for e in intervals[1:]:\n```\nWe iterate through the rest of the intervals.\n\n```\n if res[-2] < e[0] and res[-1] >= e[0]:\n res.append(e[1])\n```\nFor each interval, we first check if the last number in our result (res[-1]) is part of this interval and the second last number in our result (res[-2]) is not. If this is the case, we add the largest number of this interval (e[1]) to our result set.\n\n```\n elif e[0] > res[-1]:\n res.extend([e[1]-1, e[1]])\n```\nIf neither of the last two numbers in our result are in the current interval, we add the two largest numbers of this interval to our result set.\n\n```\n return len(res)\n```\nFinally, we return the length of our result set, which represents the minimum number of numbers we need to pick.\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals.sort(key = lambda e: (e[1], -e[0]))\n\n res = [intervals[0][1]-1, intervals[0][1]]\n\n for e in intervals[1:]:\n\n if res[-2] < e[0] and res[-1] >= e[0]:\n res.append(e[1])\n\n elif e[0] > res[-1]:\n res.extend([e[1]-1, e[1]])\n\n return len(res)\n\n``` | 2 | We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8` | null |
Python [Explained] | O(nlogn) | set-intersection-size-at-least-two | 0 | 1 | # Intuition :\n- This problem is similar to [Meeting rooms II](https://leetcode.com/problems/meeting-rooms-ii/) in which we have to find the minimum number of rooms required to organize all the conferences.\n- Similarly in this problem we have to find the minimum size of set that contain atleast two integers from each interval.\n- -----------------\n\n# Approach :\n- Suppose we have two intervals `[start1, end1]` and `[start2, end2]`.\n- Now let\'s consider three cases here :\n- 1. when these two intervals do not overlap :\n - `end1 < start2`, means `start2-end1 > 0` --> we will select two integers from both sets.\n- 2. when these two intervals overlap edge to edge :\n - `end1 == start2`, means `start2-end1 == 0`--> we will select one common element from the sets and one distinct element from previous interval.\n- 3. when these two intervals overlap(not edge to edge) :\n - `end1 > start2`, means `start2-end1 < 0` --> we will select two elements that will be common from both the sets.\n--------------------\n\n- To make this approach working first we have to sort all the intervals on the basis of ending time of the intervals.\n- If intervals overlap we will select only one element from the previous interval because in the next iteration second(common) element will be picked up from the current interval.\n- If intervals do not overlap then we will select two elements from previous interval only, because elements form the current interval will be selected automatically in the next iteration.\n-------------------\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(1)\n- -------------------\n\n# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals.sort(key = lambda x:x[1])\n size = 0\n prev_start = -1\n prev_end = -1\n\n for curr_start, curr_end in intervals:\n if prev_start == -1 or prev_end < curr_start: #if intervals do not overlap\n size += 2\n prev_start = curr_end-1\n prev_end = curr_end\n\n elif prev_start < curr_start: #if intervals overlap\n if prev_end != curr_end:\n prev_start = prev_end\n prev_end = curr_end\n \n else:\n prev_start = curr_end-1\n prev_end = curr_end\n\n size += 1\n\n return size\n\n \n```\n---------------------\n**Upvote the post if you find it helpful.\nHappy coding.** | 10 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
Python [Explained] | O(nlogn) | set-intersection-size-at-least-two | 0 | 1 | # Intuition :\n- This problem is similar to [Meeting rooms II](https://leetcode.com/problems/meeting-rooms-ii/) in which we have to find the minimum number of rooms required to organize all the conferences.\n- Similarly in this problem we have to find the minimum size of set that contain atleast two integers from each interval.\n- -----------------\n\n# Approach :\n- Suppose we have two intervals `[start1, end1]` and `[start2, end2]`.\n- Now let\'s consider three cases here :\n- 1. when these two intervals do not overlap :\n - `end1 < start2`, means `start2-end1 > 0` --> we will select two integers from both sets.\n- 2. when these two intervals overlap edge to edge :\n - `end1 == start2`, means `start2-end1 == 0`--> we will select one common element from the sets and one distinct element from previous interval.\n- 3. when these two intervals overlap(not edge to edge) :\n - `end1 > start2`, means `start2-end1 < 0` --> we will select two elements that will be common from both the sets.\n--------------------\n\n- To make this approach working first we have to sort all the intervals on the basis of ending time of the intervals.\n- If intervals overlap we will select only one element from the previous interval because in the next iteration second(common) element will be picked up from the current interval.\n- If intervals do not overlap then we will select two elements from previous interval only, because elements form the current interval will be selected automatically in the next iteration.\n-------------------\n\n# Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(1)\n- -------------------\n\n# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals.sort(key = lambda x:x[1])\n size = 0\n prev_start = -1\n prev_end = -1\n\n for curr_start, curr_end in intervals:\n if prev_start == -1 or prev_end < curr_start: #if intervals do not overlap\n size += 2\n prev_start = curr_end-1\n prev_end = curr_end\n\n elif prev_start < curr_start: #if intervals overlap\n if prev_end != curr_end:\n prev_start = prev_end\n prev_end = curr_end\n \n else:\n prev_start = curr_end-1\n prev_end = curr_end\n\n size += 1\n\n return size\n\n \n```\n---------------------\n**Upvote the post if you find it helpful.\nHappy coding.** | 10 | We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8` | null |
✅greedy || sorting || python | set-intersection-size-at-least-two | 0 | 1 | \n# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n arr=sorted(intervals, key = lambda x: (x[1], x[0]))\n ans=[]\n for v in arr:\n l=0\n r=len(ans)-1\n a=-1\n while(l<=r):\n if(a!=-1 and len(ans)-a>=2):break\n mid=(l+r)//2\n if(v[0]<=ans[mid]):\n a=mid\n r=mid-1\n else:\n l=mid+1\n if(a==-1):\n ans.append(v[1]-1)\n ans.append(v[1])\n elif(a!=-1 and len(ans)-a>=2):continue\n else:\n if(ans[-1]==v[1]):\n ans[-1]=v[1]-1\n ans.append(v[1])\n else:\n ans.append(v[1])\n # print(ans,a)\n return len(ans)\n\n``` | 0 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
✅greedy || sorting || python | set-intersection-size-at-least-two | 0 | 1 | \n# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n arr=sorted(intervals, key = lambda x: (x[1], x[0]))\n ans=[]\n for v in arr:\n l=0\n r=len(ans)-1\n a=-1\n while(l<=r):\n if(a!=-1 and len(ans)-a>=2):break\n mid=(l+r)//2\n if(v[0]<=ans[mid]):\n a=mid\n r=mid-1\n else:\n l=mid+1\n if(a==-1):\n ans.append(v[1]-1)\n ans.append(v[1])\n elif(a!=-1 and len(ans)-a>=2):continue\n else:\n if(ans[-1]==v[1]):\n ans[-1]=v[1]-1\n ans.append(v[1])\n else:\n ans.append(v[1])\n # print(ans,a)\n return len(ans)\n\n``` | 0 | We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8` | null |
Unbeatable Python Code for Intersection Size Accepted 100%🥰 | set-intersection-size-at-least-two | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem seems to be about finding the minimum number of points that intersect all the given intervals. The code sorts the intervals based on their end points and then iteratively checks the intersections.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Sorting Intervals:** The intervals are sorted by their end points in ascending order, and if two intervals have the same end point, the one with the larger start point comes first. This is done using the lambda function in the sort method.\nIterating through Intervals: The code then iterates through the sorted intervals and keeps track of the last two points that were added to the result (p1 and p2). Depending on the start and end points of the current interval, the code decides whether to add one or two new points to the result.\n\n**Checking Intersection:** If the start of the current interval is greater than p2, two new points are added. If the start is greater than p1 but less than or equal to p2, only one new point is added.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the code is O(nlogn),where n is the number of intervals. Sorting the intervals takesO(nlogn) time, and the subsequent iteration takes O(n) time.\n\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n The space complexity isO(1), as no additional space is used that grows with the input size.\n\n# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[1], -x[0]))\n res = 0\n p1, p2 = -1, -1\n for s, e in intervals:\n if s > p2:\n res += 2\n p1, p2 = e - 1, e\n elif s > p1:\n res += 1\n p1, p2 = p2, e\n return res\n```\n# Code Explanation :\n\nCode Explanation\n- intervals.sort(key=lambda x: (x[1], -x[0])): Sorts the intervals by end points, and if two end points are the same, the one with the larger start point comes first.\n- res = 0; p1, p2 = -1, -1: Initializes the result and the last two points added to the result.\n- for s, e in intervals: Iterates through the sorted intervals.\n- if s > p2: If the start of the current interval is greater than p2, two new points are added.\n- elif s > p1: If the start is greater than p1 but less than or equal to p2, one new point is added.\n- return res: Returns the result, which is the minimum number of points that intersect all the intervals.\n- I hope this explanation helps you understand the code! If you have any specific questions or need further clarification on any part, please let me know!\n\n | 0 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
Unbeatable Python Code for Intersection Size Accepted 100%🥰 | set-intersection-size-at-least-two | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem seems to be about finding the minimum number of points that intersect all the given intervals. The code sorts the intervals based on their end points and then iteratively checks the intersections.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Sorting Intervals:** The intervals are sorted by their end points in ascending order, and if two intervals have the same end point, the one with the larger start point comes first. This is done using the lambda function in the sort method.\nIterating through Intervals: The code then iterates through the sorted intervals and keeps track of the last two points that were added to the result (p1 and p2). Depending on the start and end points of the current interval, the code decides whether to add one or two new points to the result.\n\n**Checking Intersection:** If the start of the current interval is greater than p2, two new points are added. If the start is greater than p1 but less than or equal to p2, only one new point is added.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the code is O(nlogn),where n is the number of intervals. Sorting the intervals takesO(nlogn) time, and the subsequent iteration takes O(n) time.\n\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n The space complexity isO(1), as no additional space is used that grows with the input size.\n\n# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[1], -x[0]))\n res = 0\n p1, p2 = -1, -1\n for s, e in intervals:\n if s > p2:\n res += 2\n p1, p2 = e - 1, e\n elif s > p1:\n res += 1\n p1, p2 = p2, e\n return res\n```\n# Code Explanation :\n\nCode Explanation\n- intervals.sort(key=lambda x: (x[1], -x[0])): Sorts the intervals by end points, and if two end points are the same, the one with the larger start point comes first.\n- res = 0; p1, p2 = -1, -1: Initializes the result and the last two points added to the result.\n- for s, e in intervals: Iterates through the sorted intervals.\n- if s > p2: If the start of the current interval is greater than p2, two new points are added.\n- elif s > p1: If the start is greater than p1 but less than or equal to p2, one new point is added.\n- return res: Returns the result, which is the minimum number of points that intersect all the intervals.\n- I hope this explanation helps you understand the code! If you have any specific questions or need further clarification on any part, please let me know!\n\n | 0 | We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8` | null |
91 in runtime and 100 in memory , unique solution using Greedy | set-intersection-size-at-least-two | 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 intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n # Sort intervals by their end values and start values in descending order\n intervals.sort(key=lambda x: (x[1], -x[0]))\n\n # Initialize the result variable and the last two elements of the containing set\n result, last1, last2 = 0, -1, -1\n\n for start, end in intervals:\n # Check if the current interval has at least two uncovered numbers\n if start > last2:\n result += 2\n last1, last2 = end - 1, end\n # Check if the current interval has only one uncovered number\n elif start > last1:\n result += 1\n last1, last2 = last2, end\n\n return result\n``` | 0 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
91 in runtime and 100 in memory , unique solution using Greedy | set-intersection-size-at-least-two | 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 intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n # Sort intervals by their end values and start values in descending order\n intervals.sort(key=lambda x: (x[1], -x[0]))\n\n # Initialize the result variable and the last two elements of the containing set\n result, last1, last2 = 0, -1, -1\n\n for start, end in intervals:\n # Check if the current interval has at least two uncovered numbers\n if start > last2:\n result += 2\n last1, last2 = end - 1, end\n # Check if the current interval has only one uncovered number\n elif start > last1:\n result += 1\n last1, last2 = last2, end\n\n return result\n``` | 0 | We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8` | null |
done :) | set-intersection-size-at-least-two | 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 intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n # Sort intervals by their end values and start values in descending order\n intervals.sort(key=lambda x: (x[1], -x[0]))\n\n # Initialize the result variable and the last two elements of the containing set\n result, last1, last2 = 0, -1, -1\n\n for start, end in intervals:\n # Check if the current interval has at least two uncovered numbers\n if start > last2:\n result += 2\n last1, last2 = end - 1, end\n # Check if the current interval has only one uncovered number\n elif start > last1:\n result += 1\n last1, last2 = last2, end\n\n return result\n\n``` | 0 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
done :) | set-intersection-size-at-least-two | 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 intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n # Sort intervals by their end values and start values in descending order\n intervals.sort(key=lambda x: (x[1], -x[0]))\n\n # Initialize the result variable and the last two elements of the containing set\n result, last1, last2 = 0, -1, -1\n\n for start, end in intervals:\n # Check if the current interval has at least two uncovered numbers\n if start > last2:\n result += 2\n last1, last2 = end - 1, end\n # Check if the current interval has only one uncovered number\n elif start > last1:\n result += 1\n last1, last2 = last2, end\n\n return result\n\n``` | 0 | We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8` | null |
Python (Simple Maths) | set-intersection-size-at-least-two | 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 intersectionSizeTwo(self, intervals):\n if len(intervals) == 1:\n return 2\n\n intervals.sort(key = lambda x:(x[1],-x[0]))\n\n total, ans = 0, []\n\n for s,e in intervals:\n if not ans or s > ans[1]:\n total += 2\n ans = [e-1,e]\n elif ans[0] < s <= ans[1]:\n total += 1\n ans = [ans[1],e]\n\n return total\n\n\n\n\n\n\n\n\n\n \n\n\n\n \n \n``` | 0 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
Python (Simple Maths) | set-intersection-size-at-least-two | 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 intersectionSizeTwo(self, intervals):\n if len(intervals) == 1:\n return 2\n\n intervals.sort(key = lambda x:(x[1],-x[0]))\n\n total, ans = 0, []\n\n for s,e in intervals:\n if not ans or s > ans[1]:\n total += 2\n ans = [e-1,e]\n elif ans[0] < s <= ans[1]:\n total += 1\n ans = [ans[1],e]\n\n return total\n\n\n\n\n\n\n\n\n\n \n\n\n\n \n \n``` | 0 | We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8` | null |
O(nlogn) solution | set-intersection-size-at-least-two | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is that we need to find a way to maximize the number of points that are included in the intersection of all intervals. We can do this by selecting the intervals that have the most overlap with other intervals, and then selecting the points that have the most overlap with other intervals within those intervals.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach to solving this problem is to first sort the intervals based on their end points, and then iterate through the intervals and select the points that have the most overlap with other intervals. We can do this by keeping track of the last two points selected in the intersection, and only adding a new point if it is not already covered by the last two points.\n# Complexity\n- Time complexity: $$O(n log 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 intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[1], -x[0]))\n ans = []\n for i in intervals:\n if not ans or ans[-1] < i[0]:\n ans.append(i[1]-1)\n ans.append(i[1])\n elif ans[-2] < i[0]:\n ans.append(i[1])\n return len(ans)\n``` | 0 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
O(nlogn) solution | set-intersection-size-at-least-two | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is that we need to find a way to maximize the number of points that are included in the intersection of all intervals. We can do this by selecting the intervals that have the most overlap with other intervals, and then selecting the points that have the most overlap with other intervals within those intervals.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMy approach to solving this problem is to first sort the intervals based on their end points, and then iterate through the intervals and select the points that have the most overlap with other intervals. We can do this by keeping track of the last two points selected in the intersection, and only adding a new point if it is not already covered by the last two points.\n# Complexity\n- Time complexity: $$O(n log 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 intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n intervals.sort(key=lambda x: (x[1], -x[0]))\n ans = []\n for i in intervals:\n if not ans or ans[-1] < i[0]:\n ans.append(i[1]-1)\n ans.append(i[1])\n elif ans[-2] < i[0]:\n ans.append(i[1])\n return len(ans)\n``` | 0 | We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8` | null |
Python3 🐍 concise solution beats 99% | set-intersection-size-at-least-two | 0 | 1 | # Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([y-1, y])\n return len(ans)\n``` | 0 | You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively.
A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`.
* For example, if `intervals = [[1,3], [3,7], [8,9]]`, then `[1,2,4,7,8,9]` and `[2,3,4,8,9]` are **containing sets**.
Return _the minimum possible size of a containing set_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[3,7\],\[8,9\]\]
**Output:** 5
**Explanation:** let nums = \[2, 3, 4, 8, 9\].
It can be shown that there cannot be any containing array of size 4.
**Example 2:**
**Input:** intervals = \[\[1,3\],\[1,4\],\[2,5\],\[3,5\]\]
**Output:** 3
**Explanation:** let nums = \[2, 3, 4\].
It can be shown that there cannot be any containing array of size 2.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[2,4\],\[4,5\]\]
**Output:** 5
**Explanation:** let nums = \[1, 2, 3, 4, 5\].
It can be shown that there cannot be any containing array of size 4.
**Constraints:**
* `1 <= intervals.length <= 3000`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 108` | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.