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
Solution
linked-list-components
1
1
```C++ []\nclass Solution {\npublic:\n int numComponents(ListNode* head, vector<int>& nums) {\n ListNode* cur = head;\n int n = 0;\n while (cur) {\n n++;\n cur = cur->next;\n }\n std::vector<int> found (n);\n for (auto& val : nums) {\n found[...
2
You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values. Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_. **Example 1:** **Input:** head...
null
Solution
linked-list-components
1
1
```C++ []\nclass Solution {\npublic:\n int numComponents(ListNode* head, vector<int>& nums) {\n ListNode* cur = head;\n int n = 0;\n while (cur) {\n n++;\n cur = cur->next;\n }\n std::vector<int> found (n);\n for (auto& val : nums) {\n found[...
2
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values. We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. W...
null
89% TC and 77% SC easy python solution
linked-list-components
0
1
```\ndef numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:\n\tcurr = head\n\tans = 0\n\ts = set(nums)\n\twhile(curr):\n\t\tif(curr.val in s and not(curr.next and curr.next.val in s)):\n\t\t\tans += 1\n\t\tcurr = curr.next\n\treturn ans\n```
4
You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values. Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_. **Example 1:** **Input:** head...
null
89% TC and 77% SC easy python solution
linked-list-components
0
1
```\ndef numComponents(self, head: Optional[ListNode], nums: List[int]) -> int:\n\tcurr = head\n\tans = 0\n\ts = set(nums)\n\twhile(curr):\n\t\tif(curr.val in s and not(curr.next and curr.next.val in s)):\n\t\t\tans += 1\n\t\tcurr = curr.next\n\treturn ans\n```
4
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values. We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. W...
null
Brute Force -> O(n) - Python/Java - Union Find
linked-list-components
1
1
> # Intuition\n\nThe "brute force" for this question is essentially Union Find. Understanding Union Find makes the O(n) for this question much more intuitive.\n\nWe perform a modified Union Find as we traverse the linked list, and decrement our total disjoint sets until we hit the end of the list. Also not sure why ord...
0
You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values. Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_. **Example 1:** **Input:** head...
null
Brute Force -> O(n) - Python/Java - Union Find
linked-list-components
1
1
> # Intuition\n\nThe "brute force" for this question is essentially Union Find. Understanding Union Find makes the O(n) for this question much more intuitive.\n\nWe perform a modified Union Find as we traverse the linked list, and decrement our total disjoint sets until we hit the end of the list. Also not sure why ord...
0
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values. We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. W...
null
✅ Simple BFS Solution || Time and Space Complexity O(log n) 🚀😀
race-car
0
1
# Intuition\nThis whole problem seems to be a shortest path question, where we have to reach from 0 to target position with minimum steps.\nAnd for this type of question it is better to proceed with BFS.\n\n# Approach\nMake decision of either accelerating or taking a reverse with the help of these conditions:\n- If our...
6
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse): * When you get an instruction `'A'`, your car does the following: * `position += spee...
null
✅ Simple BFS Solution || Time and Space Complexity O(log n) 🚀😀
race-car
0
1
# Intuition\nThis whole problem seems to be a shortest path question, where we have to reach from 0 to target position with minimum steps.\nAnd for this type of question it is better to proceed with BFS.\n\n# Approach\nMake decision of either accelerating or taking a reverse with the help of these conditions:\n- If our...
6
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles ove...
null
BFS and DP with inline explanations
race-car
0
1
\n```python\n# Naive BFS\n# O(2^target)\n# TLE\nclass Solution:\n def racecar(self, target: int) -> int:\n q = deque([(0, 0, 1)])\n visited = set([0, 0, 1])\n \n while q:\n actions, x, v = q.popleft()\n if x == target:\n return actions\n \n ...
12
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse): * When you get an instruction `'A'`, your car does the following: * `position += spee...
null
BFS and DP with inline explanations
race-car
0
1
\n```python\n# Naive BFS\n# O(2^target)\n# TLE\nclass Solution:\n def racecar(self, target: int) -> int:\n q = deque([(0, 0, 1)])\n visited = set([0, 0, 1])\n \n while q:\n actions, x, v = q.popleft()\n if x == target:\n return actions\n \n ...
12
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles ove...
null
Python3 BFS Explanation
race-car
0
1
At every position, we have two choice\n* Either accelerate\n* Or reverse\n\nNote: If you are thinking of accelerating till `curren position < target` and when `current position becomes > target to reverse`, it wont work because sometimes we would have to decelerate first and then accelerate even though` current positio...
15
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse): * When you get an instruction `'A'`, your car does the following: * `position += spee...
null
Python3 BFS Explanation
race-car
0
1
At every position, we have two choice\n* Either accelerate\n* Or reverse\n\nNote: If you are thinking of accelerating till `curren position < target` and when `current position becomes > target to reverse`, it wont work because sometimes we would have to decelerate first and then accelerate even though` current positio...
15
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles ove...
null
Python easy to read and understand | BFS
race-car
0
1
```\nclass Solution:\n def racecar(self, target: int) -> int:\n q = [(0, 1)]\n steps = 0\n \n while q:\n num = len(q)\n for i in range(num):\n pos, speed = q.pop(0)\n if pos == target:\n return steps\n q...
2
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse): * When you get an instruction `'A'`, your car does the following: * `position += spee...
null
Python easy to read and understand | BFS
race-car
0
1
```\nclass Solution:\n def racecar(self, target: int) -> int:\n q = [(0, 1)]\n steps = 0\n \n while q:\n num = len(q)\n for i in range(num):\n pos, speed = q.pop(0)\n if pos == target:\n return steps\n q...
2
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles ove...
null
📌📌 Greedy Approach || Normal conditions || 94% faster || Well-Coded 🐍
race-car
0
1
## IDEA:\n* The key point is move close to that point and then start reversing the gear based on conditions.\n\n* **If you are still before to the target and speed is reverse(i.e. deaccelerating) or if you are ahead of target and speed is positive (i.e. accelerating) then reverse the speed.**\n\nThere are two strategie...
10
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse): * When you get an instruction `'A'`, your car does the following: * `position += spee...
null
📌📌 Greedy Approach || Normal conditions || 94% faster || Well-Coded 🐍
race-car
0
1
## IDEA:\n* The key point is move close to that point and then start reversing the gear based on conditions.\n\n* **If you are still before to the target and speed is reverse(i.e. deaccelerating) or if you are ahead of target and speed is positive (i.e. accelerating) then reverse the speed.**\n\nThere are two strategie...
10
An axis-aligned rectangle is represented as a list `[x1, y1, x2, y2]`, where `(x1, y1)` is the coordinate of its bottom-left corner, and `(x2, y2)` is the coordinate of its top-right corner. Its top and bottom edges are parallel to the X-axis, and its left and right edges are parallel to the Y-axis. Two rectangles ove...
null
Solution
most-common-word
1
1
```C++ []\nclass Solution {\npublic:\n string mostCommonWord(string str, vector<string>& banned) {\n unordered_map<string, int> hash;\n for(auto& it : str)\n\t\t it = ispunct(it) ? \' \' : tolower(it);\n\n unordered_set<string> st(banned.begin(), banned.end()); \n string res, temp; ...
1
Given a string `paragraph` and a string array of the banned words `banned`, return _the most frequent word that is not banned_. It is **guaranteed** there is **at least one word** that is not banned, and that the answer is **unique**. The words in `paragraph` are **case-insensitive** and the answer should be returned ...
null
Solution
most-common-word
1
1
```C++ []\nclass Solution {\npublic:\n string mostCommonWord(string str, vector<string>& banned) {\n unordered_map<string, int> hash;\n for(auto& it : str)\n\t\t it = ispunct(it) ? \' \' : tolower(it);\n\n unordered_set<string> st(banned.begin(), banned.end()); \n string res, temp; ...
1
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Simple Python Solution (Counter)
most-common-word
0
1
```\n#Import RegEx\nimport re\n\nclass Solution:\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n #List words in paragraph, replacing punctuation with \' \' and all lower case\n paragraph = re.subn("[.,!?;\']", \' \', paragraph.lower())[0].split(\' \')\n \n #Remove ...
1
Given a string `paragraph` and a string array of the banned words `banned`, return _the most frequent word that is not banned_. It is **guaranteed** there is **at least one word** that is not banned, and that the answer is **unique**. The words in `paragraph` are **case-insensitive** and the answer should be returned ...
null
Simple Python Solution (Counter)
most-common-word
0
1
```\n#Import RegEx\nimport re\n\nclass Solution:\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n #List words in paragraph, replacing punctuation with \' \' and all lower case\n paragraph = re.subn("[.,!?;\']", \' \', paragraph.lower())[0].split(\' \')\n \n #Remove ...
1
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
easy solution in python ....
most-common-word
0
1
\nimport re\nclass Solution:\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n res = re.sub(r\'[^\\w\\s]\', \' \', paragraph)\n dic={}\n c=1\n s=\'\'\n l=res.split(" ")\n print(l)\n for i in l:\n if(i!=""):\n i=i.lower()...
1
Given a string `paragraph` and a string array of the banned words `banned`, return _the most frequent word that is not banned_. It is **guaranteed** there is **at least one word** that is not banned, and that the answer is **unique**. The words in `paragraph` are **case-insensitive** and the answer should be returned ...
null
easy solution in python ....
most-common-word
0
1
\nimport re\nclass Solution:\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n res = re.sub(r\'[^\\w\\s]\', \' \', paragraph)\n dic={}\n c=1\n s=\'\'\n l=res.split(" ")\n print(l)\n for i in l:\n if(i!=""):\n i=i.lower()...
1
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Python 3 three lines easy and explained
most-common-word
0
1
Runtime: 36 ms, faster than 40.27% of Python3 online submissions for Most Common Word.\nMemory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Most Common Word.\n\n```Python 3\nimport re\n\nclass Solution:\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n\t\t\n\t\t# convert ...
25
Given a string `paragraph` and a string array of the banned words `banned`, return _the most frequent word that is not banned_. It is **guaranteed** there is **at least one word** that is not banned, and that the answer is **unique**. The words in `paragraph` are **case-insensitive** and the answer should be returned ...
null
Python 3 three lines easy and explained
most-common-word
0
1
Runtime: 36 ms, faster than 40.27% of Python3 online submissions for Most Common Word.\nMemory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Most Common Word.\n\n```Python 3\nimport re\n\nclass Solution:\n def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:\n\t\t\n\t\t# convert ...
25
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Python3 library Function Runtime: 49ms 62.31% Memory: 14mb 37.05%
most-common-word
0
1
```\nimport re\nfrom collections import Counter\n\n# Runtime: 49ms 62.31% Memory: 14mb 37.05%\nclass Solution:\n def mostCommonWord(self, string: str, banned: List[str]) -> str:\n string = re.sub(r"[^a-zA-Z]", \' \', string).lower()\n freq = Counter(string.split())\n for x in banned:\n ...
2
Given a string `paragraph` and a string array of the banned words `banned`, return _the most frequent word that is not banned_. It is **guaranteed** there is **at least one word** that is not banned, and that the answer is **unique**. The words in `paragraph` are **case-insensitive** and the answer should be returned ...
null
Python3 library Function Runtime: 49ms 62.31% Memory: 14mb 37.05%
most-common-word
0
1
```\nimport re\nfrom collections import Counter\n\n# Runtime: 49ms 62.31% Memory: 14mb 37.05%\nclass Solution:\n def mostCommonWord(self, string: str, banned: List[str]) -> str:\n string = re.sub(r"[^a-zA-Z]", \' \', string).lower()\n freq = Counter(string.split())\n for x in banned:\n ...
2
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outc...
null
Solution
short-encoding-of-words
1
1
```C++ []\nclass Solution {\npublic:\nstruct reverseComparer {\n bool operator()(const string& a, const string& b) {\n for (auto pa = a.rbegin(), pb = b.rbegin(); pa != a.rend() && pb != b.rend(); ++pa, ++pb) if (*pa != *pb) return *pa < *pb;\n return a.size() < b.size();\n }\n};\nint minimumLengthEncoding(vect...
1
A **valid encoding** of an array of `words` is any reference string `s` and array of indices `indices` such that: * `words.length == indices.length` * The reference string `s` ends with the `'#'` character. * For each index `indices[i]`, the **substring** of `s` starting from `indices[i]` and up to (but not incl...
null
Solution
short-encoding-of-words
1
1
```C++ []\nclass Solution {\npublic:\nstruct reverseComparer {\n bool operator()(const string& a, const string& b) {\n for (auto pa = a.rbegin(), pb = b.rbegin(); pa != a.rend() && pb != b.rend(); ++pa, ++pb) if (*pa != *pb) return *pa < *pb;\n return a.size() < b.size();\n }\n};\nint minimumLengthEncoding(vect...
1
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
[Python] Concise Brute Force & Trie Solutions with Explanation
short-encoding-of-words
0
1
### Introduction\n\nGiven a list of words, find the length of the shortest string which contains all the words in the list appended with a hash "#" symbol.\n\nRunning through some test cases, we quickly see that the only way for the resultant string to be shorter than the sum of all lengths of the words in the list is ...
25
A **valid encoding** of an array of `words` is any reference string `s` and array of indices `indices` such that: * `words.length == indices.length` * The reference string `s` ends with the `'#'` character. * For each index `indices[i]`, the **substring** of `s` starting from `indices[i]` and up to (but not incl...
null
[Python] Concise Brute Force & Trie Solutions with Explanation
short-encoding-of-words
0
1
### Introduction\n\nGiven a list of words, find the length of the shortest string which contains all the words in the list appended with a hash "#" symbol.\n\nRunning through some test cases, we quickly see that the only way for the resultant string to be shorter than the sum of all lengths of the words in the list is ...
25
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
📌 Python3 solution using Trie and DFS
short-encoding-of-words
0
1
```\nclass TriNode:\n def __init__(self, val):\n self.val = val\n self.children = [0]*26\n\nclass Solution:\n def minimumLengthEncoding(self, words: List[str]) -> int:\n root = TriNode("")\n result = [0]\n \n def insertInTrie(word):\n curr = root\n f...
6
A **valid encoding** of an array of `words` is any reference string `s` and array of indices `indices` such that: * `words.length == indices.length` * The reference string `s` ends with the `'#'` character. * For each index `indices[i]`, the **substring** of `s` starting from `indices[i]` and up to (but not incl...
null
📌 Python3 solution using Trie and DFS
short-encoding-of-words
0
1
```\nclass TriNode:\n def __init__(self, val):\n self.val = val\n self.children = [0]*26\n\nclass Solution:\n def minimumLengthEncoding(self, words: List[str]) -> int:\n root = TriNode("")\n result = [0]\n \n def insertInTrie(word):\n curr = root\n f...
6
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
Without Trie || Sorting || Easy to Understand || Python
short-encoding-of-words
0
1
**The main idea is that larger string will never be suffix of smaller string.**\n* So,Simply sort (descending order) the list on the basis of length. \n* Then we\'ll traverse the array mantaining a string variable ( i.e st in code ) and \n\t* keep checking whether the current word + "#" is present in the string st or ...
4
A **valid encoding** of an array of `words` is any reference string `s` and array of indices `indices` such that: * `words.length == indices.length` * The reference string `s` ends with the `'#'` character. * For each index `indices[i]`, the **substring** of `s` starting from `indices[i]` and up to (but not incl...
null
Without Trie || Sorting || Easy to Understand || Python
short-encoding-of-words
0
1
**The main idea is that larger string will never be suffix of smaller string.**\n* So,Simply sort (descending order) the list on the basis of length. \n* Then we\'ll traverse the array mantaining a string variable ( i.e st in code ) and \n\t* keep checking whether the current word + "#" is present in the string st or ...
4
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
Easy Python Solution using hashmap with Explanation and Comments
short-encoding-of-words
0
1
# Easy Python Solution using hashmap with Explanation and Comments\n\n**Question**\nThe question\'s phrasing is complex to understand.\n\nSimplifying the question:\n1. We have an array (`words`) of words\n2. Create another array `new_words` in which we have all the words which are not a suffix of any other word in `wor...
4
A **valid encoding** of an array of `words` is any reference string `s` and array of indices `indices` such that: * `words.length == indices.length` * The reference string `s` ends with the `'#'` character. * For each index `indices[i]`, the **substring** of `s` starting from `indices[i]` and up to (but not incl...
null
Easy Python Solution using hashmap with Explanation and Comments
short-encoding-of-words
0
1
# Easy Python Solution using hashmap with Explanation and Comments\n\n**Question**\nThe question\'s phrasing is complex to understand.\n\nSimplifying the question:\n1. We have an array (`words`) of words\n2. Create another array `new_words` in which we have all the words which are not a suffix of any other word in `wor...
4
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
Trie Solution| Industry Level Code
short-encoding-of-words
0
1
```\nclass TreeNode:\n def __init__(self):\n self.children = [None]*26\n self.word = \'\'\nclass Trie:\n def __init__(self):\n self.root = TreeNode()\n def insert(self,word):\n cur_node = self.root\n for s in word:\n index = ord(s)-ord(\'a\')\n if cur_no...
2
A **valid encoding** of an array of `words` is any reference string `s` and array of indices `indices` such that: * `words.length == indices.length` * The reference string `s` ends with the `'#'` character. * For each index `indices[i]`, the **substring** of `s` starting from `indices[i]` and up to (but not incl...
null
Trie Solution| Industry Level Code
short-encoding-of-words
0
1
```\nclass TreeNode:\n def __init__(self):\n self.children = [None]*26\n self.word = \'\'\nclass Trie:\n def __init__(self):\n self.root = TreeNode()\n def insert(self,word):\n cur_node = self.root\n for s in word:\n index = ord(s)-ord(\'a\')\n if cur_no...
2
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
Python, Trie
short-encoding-of-words
0
1
# Idea\nFirst, build the Trie data structure from the reversed words.\nThen, do a DFS and find out the total length of all the paths from the root to leaves:\n# Complexity:\nTime / Memory: O(N)\n\n```\ndef minimumLengthEncoding(self, words: List[str]) -> int:\n\ttrie = {}\n\tfor word in words:\n\t\tnode = trie\n\t\tfor...
12
A **valid encoding** of an array of `words` is any reference string `s` and array of indices `indices` such that: * `words.length == indices.length` * The reference string `s` ends with the `'#'` character. * For each index `indices[i]`, the **substring** of `s` starting from `indices[i]` and up to (but not incl...
null
Python, Trie
short-encoding-of-words
0
1
# Idea\nFirst, build the Trie data structure from the reversed words.\nThen, do a DFS and find out the total length of all the paths from the root to leaves:\n# Complexity:\nTime / Memory: O(N)\n\n```\ndef minimumLengthEncoding(self, words: List[str]) -> int:\n\ttrie = {}\n\tfor word in words:\n\t\tnode = trie\n\t\tfor...
12
Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal. For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "`...
null
easy solution
shortest-distance-to-a-character
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)$$ --...
1
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`. The **distance** between two indices `i` and `j` is `abs(i - j)`, where...
null
easy solution
shortest-distance-to-a-character
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)$$ --...
1
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room i...
null
Python || 99.92% Faster || Two Pointers || O(n) Solution
shortest-distance-to-a-character
0
1
```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n a,n=[],len(s)\n for i in range(n):\n if s[i]==c:\n a.append(i)\n answer=[]\n j=0\n for i in range(n):\n if s[i]==c:\n answer.append(0)\n ...
15
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`. The **distance** between two indices `i` and `j` is `abs(i - j)`, where...
null
Python || 99.92% Faster || Two Pointers || O(n) Solution
shortest-distance-to-a-character
0
1
```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n a,n=[],len(s)\n for i in range(n):\n if s[i]==c:\n a.append(i)\n answer=[]\n j=0\n for i in range(n):\n if s[i]==c:\n answer.append(0)\n ...
15
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room i...
null
Python3 ✅✅✅ || Long but Fast || Faster than 97.10%
shortest-distance-to-a-character
0
1
# Code\n```\nclass Solution:\n def getIndicies(self, s, c):\n indicies = []\n for i in range(len(s)):\n if s[i] == c:\n indicies.append(i)\n return indicies\n def getShortest(self, idx, indicies):\n if idx in indicies: return 0\n if idx < indicies[0]: r...
1
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`. The **distance** between two indices `i` and `j` is `abs(i - j)`, where...
null
Python3 ✅✅✅ || Long but Fast || Faster than 97.10%
shortest-distance-to-a-character
0
1
# Code\n```\nclass Solution:\n def getIndicies(self, s, c):\n indicies = []\n for i in range(len(s)):\n if s[i] == c:\n indicies.append(i)\n return indicies\n def getShortest(self, idx, indicies):\n if idx in indicies: return 0\n if idx < indicies[0]: r...
1
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room i...
null
Python3 🐍 || explicit approach || memory 🤜🏻 88%
shortest-distance-to-a-character
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)$$ --...
1
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`. The **distance** between two indices `i` and `j` is `abs(i - j)`, where...
null
Python3 🐍 || explicit approach || memory 🤜🏻 88%
shortest-distance-to-a-character
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)$$ --...
1
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room i...
null
Python3 O(n) || O(n) # Runtime: 53ms 78.92% Memory: 13.9mb 91.60%
shortest-distance-to-a-character
0
1
```\nclass Solution:\n def shortestToChar(self, string: str, char: str) -> List[int]:\n return self.optimalSolution(string, char)\n# O(n) || O(n)\n# Runtime: 53ms 78.92% Memory: 13.9mb 91.60%\n def optimalSolution(self, string, char):\n n = len(string)\n leftArray, rightArray, result = ([...
2
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`. The **distance** between two indices `i` and `j` is `abs(i - j)`, where...
null
Python3 O(n) || O(n) # Runtime: 53ms 78.92% Memory: 13.9mb 91.60%
shortest-distance-to-a-character
0
1
```\nclass Solution:\n def shortestToChar(self, string: str, char: str) -> List[int]:\n return self.optimalSolution(string, char)\n# O(n) || O(n)\n# Runtime: 53ms 78.92% Memory: 13.9mb 91.60%\n def optimalSolution(self, string, char):\n n = len(string)\n leftArray, rightArray, result = ([...
2
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room i...
null
Solution
shortest-distance-to-a-character
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int n = s.length();\n\tvector<int>v;\n\tfor (int i = 0;i < n;i++) {\n\t\tint distance = 0;\n\t\tfor (int j = i, k = i;j < n || k >= 0;j++, k--) {\n\t\t\tif ((k >= 0 && s[k] == c) || (j < n && s[j] == c )) {\n\t\t\t\tv.push...
2
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`. The **distance** between two indices `i` and `j` is `abs(i - j)`, where...
null
Solution
shortest-distance-to-a-character
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> shortestToChar(string s, char c) {\n int n = s.length();\n\tvector<int>v;\n\tfor (int i = 0;i < n;i++) {\n\t\tint distance = 0;\n\t\tfor (int j = i, k = i;j < n || k >= 0;j++, k--) {\n\t\t\tif ((k >= 0 && s[k] == c) || (j < n && s[j] == c )) {\n\t\t\t\tv.push...
2
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room i...
null
Python O(n) by propagation 85%+ [w/ Diagram]
shortest-distance-to-a-character
0
1
Python O(n) by propagation\n\n---\n\n**Hint**:\n\nImagine parameter C as a flag on the line.\n\nThink of propagation technique:\n**1st-pass** iteration **propagates distance** from C on the **left hand side**\n**2nd-pass** iteration **propagates distance** from C on the **right hand side** with min( 1st-pass result, 2n...
16
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`. The **distance** between two indices `i` and `j` is `abs(i - j)`, where...
null
Python O(n) by propagation 85%+ [w/ Diagram]
shortest-distance-to-a-character
0
1
Python O(n) by propagation\n\n---\n\n**Hint**:\n\nImagine parameter C as a flag on the line.\n\nThink of propagation technique:\n**1st-pass** iteration **propagates distance** from C on the **left hand side**\n**2nd-pass** iteration **propagates distance** from C on the **right hand side** with min( 1st-pass result, 2n...
16
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room i...
null
Python 3 Solution, Brute Force and Two Pointers - 2 Solutions
shortest-distance-to-a-character
0
1
Brute Force:\n```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n req = []\n ind_list = []\n for i in range(len(s)):\n if s[i] == c:\n ind_list.append(i)\n min_dis = len(s)\n for j in range(len(s)):\n for k in range(l...
6
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`. The **distance** between two indices `i` and `j` is `abs(i - j)`, where...
null
Python 3 Solution, Brute Force and Two Pointers - 2 Solutions
shortest-distance-to-a-character
0
1
Brute Force:\n```\nclass Solution:\n def shortestToChar(self, s: str, c: str) -> List[int]:\n req = []\n ind_list = []\n for i in range(len(s)):\n if s[i] == c:\n ind_list.append(i)\n min_dis = len(s)\n for j in range(len(s)):\n for k in range(l...
6
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room i...
null
Solution
card-flipping-game
1
1
```C++ []\nclass Solution {\n void better(int &x, int y) {\n if (x == 0 || x > y) {\n x = y;\n }\n }\npublic:\n int flipgame(vector<int>& fronts, vector<int>& backs) {\n unordered_set<int> bad;\n const int n = backs.size();\n for (int i = 0; i < n; ++i) {\n ...
1
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
Solution
card-flipping-game
1
1
```C++ []\nclass Solution {\n void better(int &x, int y) {\n if (x == 0 || x > y) {\n x = y;\n }\n }\npublic:\n int flipgame(vector<int>& fronts, vector<int>& backs) {\n unordered_set<int> bad;\n const int n = backs.size();\n for (int i = 0; i < n; ++i) {\n ...
1
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Minimum Outside Doubles
card-flipping-game
0
1
# Intuition\nThe only exclusion criteria for a number in the pile is the existance of a card with that number on both the back and front. We simply take the minimum of the remaining numbers.\n\n# Approach\nGather the numbers that are on both the front and back of the same card (call that a "double") and find the minimu...
0
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
Minimum Outside Doubles
card-flipping-game
0
1
# Intuition\nThe only exclusion criteria for a number in the pile is the existance of a card with that number on both the back and front. We simply take the minimum of the remaining numbers.\n\n# Approach\nGather the numbers that are on both the front and back of the same card (call that a "double") and find the minimu...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Easy Python Solution | Beats 88% | Using Set | O(n)
card-flipping-game
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe fronts and backs are identical, i.e., we can flip any card to change its back to front and vice versa. Just try to see what if you have both the front and back values of a particular card same. In this case, that number cannot be good...
0
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
Easy Python Solution | Beats 88% | Using Set | O(n)
card-flipping-game
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe fronts and backs are identical, i.e., we can flip any card to change its back to front and vice versa. Just try to see what if you have both the front and back values of a particular card same. In this case, that number cannot be good...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Python simple solution with set
card-flipping-game
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)$$ --...
0
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
Python simple solution with set
card-flipping-game
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)$$ --...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
O(N) time and space, simple explanation of problem and approach
card-flipping-game
0
1
# Intuition\nThe only time a number CANNOT be good is if it appears on 2 sides of the SAME card, so you just have to find the smallest number that only appears on one side. It doesn\'t matter how many times the card appears, only that it is never on both sides of the same card.\ne.g. (front,back) (1,1), (3,2), (3,3), (...
0
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
O(N) time and space, simple explanation of problem and approach
card-flipping-game
0
1
# Intuition\nThe only time a number CANNOT be good is if it appears on 2 sides of the SAME card, so you just have to find the smallest number that only appears on one side. It doesn\'t matter how many times the card appears, only that it is never on both sides of the same card.\ne.g. (front,back) (1,1), (3,2), (3,3), (...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Thought puzzle
card-flipping-game
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Proposition A: If the number $num$ satisfies the requirement, then among all the cards, there must be at least one side that is not equal to $num$.\n2. A is true.\n3. The inverse contrapositive proposition of A, denoted as A\': If on o...
0
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
Thought puzzle
card-flipping-game
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Proposition A: If the number $num$ satisfies the requirement, then among all the cards, there must be at least one side that is not equal to $num$.\n2. A is true.\n3. The inverse contrapositive proposition of A, denoted as A\': If on o...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Python3 - Sorting + Set
card-flipping-game
0
1
# Intuition\nThe only way you can\'t have a good integer is if you have a card with it on both sides. You want the minimum, so just sort, giving you the lowest, and check if any card has it on both sides.\n\n# Code\n```\nclass Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n bad ...
0
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
Python3 - Sorting + Set
card-flipping-game
0
1
# Intuition\nThe only way you can\'t have a good integer is if you have a card with it on both sides. You want the minimum, so just sort, giving you the lowest, and check if any card has it on both sides.\n\n# Code\n```\nclass Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n bad ...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Python3 🐍 concise solution beats 99%
card-flipping-game
0
1
# Code\n```\nclass Solution:\n def flipgame(self, fronts, backs):\n dict1, res = defaultdict(int), []\n\n for i,j in zip(fronts,backs):\n dict1[i] += 1\n dict1[j] += 1\n\n for i,j in zip(fronts,backs):\n if i == j and i in dict1:\n del dict1[i]\n\n...
0
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
Python3 🐍 concise solution beats 99%
card-flipping-game
0
1
# Code\n```\nclass Solution:\n def flipgame(self, fronts, backs):\n dict1, res = defaultdict(int), []\n\n for i,j in zip(fronts,backs):\n dict1[i] += 1\n dict1[j] += 1\n\n for i,j in zip(fronts,backs):\n if i == j and i in dict1:\n del dict1[i]\n\n...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Python (Simple Hashmap)
card-flipping-game
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)$$ --...
0
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
Python (Simple Hashmap)
card-flipping-game
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)$$ --...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Python3 simple solution using a for() loop
card-flipping-game
0
1
```\nclass Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n """\n O(n) time complexity: n is length of fronts\n O(n) space complexity\n """\n same = {x for i, x in enumerate(fronts) if x == backs[i]}\n res = 9999\n for i in range(len(front...
2
You are given two **0-indexed** integer arrays `fronts` and `backs` of length `n`, where the `ith` card has the positive integer `fronts[i]` printed on the front and `backs[i]` printed on the back. Initially, each card is placed on a table such that the front number is facing up and the other is facing down. You may fl...
null
Python3 simple solution using a for() loop
card-flipping-game
0
1
```\nclass Solution:\n def flipgame(self, fronts: List[int], backs: List[int]) -> int:\n """\n O(n) time complexity: n is length of fronts\n O(n) space complexity\n """\n same = {x for i, x in enumerate(fronts) if x == backs[i]}\n res = 9999\n for i in range(len(front...
2
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
🔥🧭Beats 99.99% |🚩Optimised Code Using Dynamic Programming | 💡🚀🔥
binary-trees-with-factors
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about finding the number of binary trees that can be formed using a given array of integers. Each integer can be used multiple times, and the non-leaf nodes\' values should be the product of the values of their children. Th...
11
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
🔥🧭Beats 99.99% |🚩Optimised Code Using Dynamic Programming | 💡🚀🔥
binary-trees-with-factors
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is about finding the number of binary trees that can be formed using a given array of integers. Each integer can be used multiple times, and the non-leaf nodes\' values should be the product of the values of their children. Th...
11
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
🔥Efficient Method🔥| Explained Intuition & Approach | Java | C++ | Python | JavaScript | C# | PHP
binary-trees-with-factors
1
1
# Intuition \uD83D\uDE80\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key idea here is to use dynamic programming to count the number of valid binary trees efficiently. The intuition is as follows:\n\n1. Sort the input array: Start by sorting the array in ascending order because you need to...
32
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
🔥Efficient Method🔥| Explained Intuition & Approach | Java | C++ | Python | JavaScript | C# | PHP
binary-trees-with-factors
1
1
# Intuition \uD83D\uDE80\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe key idea here is to use dynamic programming to count the number of valid binary trees efficiently. The intuition is as follows:\n\n1. Sort the input array: Start by sorting the array in ascending order because you need to...
32
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
【Video】Give me 10 minutes - How we think about a solution - Python, JavaScript, Java, C++
binary-trees-with-factors
1
1
# Intuition\nUse Dynamic Programming\n\n---\n\n# Solution Video\n\nhttps://youtu.be/LrnKFjcjsqo\n\n\u25A0 Timeline of video\n`0:04` Understand question exactly and approach to solve this question\n`1:33` How can you calculate number of subtrees?\n`4:12` Demonstrate how it works\n`8:40` Coding\n`11:32` Time Complexity a...
58
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
【Video】Give me 10 minutes - How we think about a solution - Python, JavaScript, Java, C++
binary-trees-with-factors
1
1
# Intuition\nUse Dynamic Programming\n\n---\n\n# Solution Video\n\nhttps://youtu.be/LrnKFjcjsqo\n\n\u25A0 Timeline of video\n`0:04` Understand question exactly and approach to solve this question\n`1:33` How can you calculate number of subtrees?\n`4:12` Demonstrate how it works\n`8:40` Coding\n`11:32` Time Complexity a...
58
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
🌟[PYTHON] Simplest DP Solution Explained🌟
binary-trees-with-factors
0
1
# Approach - DP\n<!-- Describe your approach to solving the problem. -->\n> NOTE --> DP array will store the number of tree that can be formed keeping that index element as the root\n\n1. Sort the given `arr` and then make another dp array `dp` of same length with all elements as `1` because every element will make...
1
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
🌟[PYTHON] Simplest DP Solution Explained🌟
binary-trees-with-factors
0
1
# Approach - DP\n<!-- Describe your approach to solving the problem. -->\n> NOTE --> DP array will store the number of tree that can be formed keeping that index element as the root\n\n1. Sort the given `arr` and then make another dp array `dp` of same length with all elements as `1` because every element will make...
1
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
✅ Beats 100% 🔥 || Easiest Approach in 3 Points || DP & HashMap
binary-trees-with-factors
1
1
##### TypeScript Result:\n![image.png](https://assets.leetcode.com/users/images/9ff22734-7791-410d-a9c8-db3b124aebda_1698290459.4343364.png)\n\n\n# Intuition :\n**In order to build a tree, we need to know the number of left children and right children. \nIf we know the number of left children and right children, the to...
15
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
✅ Beats 100% 🔥 || Easiest Approach in 3 Points || DP & HashMap
binary-trees-with-factors
1
1
##### TypeScript Result:\n![image.png](https://assets.leetcode.com/users/images/9ff22734-7791-410d-a9c8-db3b124aebda_1698290459.4343364.png)\n\n\n# Intuition :\n**In order to build a tree, we need to know the number of left children and right children. \nIf we know the number of left children and right children, the to...
15
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
EASY PYTHON SOLUTION
binary-trees-with-factors
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)$$ --...
1
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
EASY PYTHON SOLUTION
binary-trees-with-factors
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)$$ --...
1
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
Solution
binary-trees-with-factors
1
1
```C++ []\nclass Solution {\npublic:\n int numFactoredBinaryTrees(vector<int>& arr)\n {\n sort(arr.begin(), arr.end());\n int len = arr.size();\n long ans = 0;\n unordered_map<int, long> fmap;\n for (int num : arr) {\n long ways = 1;\n double lim = sqrt(nu...
1
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
Solution
binary-trees-with-factors
1
1
```C++ []\nclass Solution {\npublic:\n int numFactoredBinaryTrees(vector<int>& arr)\n {\n sort(arr.begin(), arr.end());\n int len = arr.size();\n long ans = 0;\n unordered_map<int, long> fmap;\n for (int num : arr) {\n long ways = 1;\n double lim = sqrt(nu...
1
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
Python3 Solution
binary-trees-with-factors
0
1
\n```\nclass Solution:\n def numFactoredBinaryTrees(self, arr: List[int]) -> int:\n mod=10**9+7\n arr.sort()\n ans=defaultdict(int)\n for a in arr:\n tmp=1\n for b in arr:\n if b>a:\n break\n tmp+=(ans[b]*ans[a/b])\n ...
5
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
Python3 Solution
binary-trees-with-factors
0
1
\n```\nclass Solution:\n def numFactoredBinaryTrees(self, arr: List[int]) -> int:\n mod=10**9+7\n arr.sort()\n ans=defaultdict(int)\n for a in arr:\n tmp=1\n for b in arr:\n if b>a:\n break\n tmp+=(ans[b]*ans[a/b])\n ...
5
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
binary-trees-with-factors
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Maps)***\n1. Initialize a modulo value `mod` to prevent integer overflow and create a map `mp` to store the count of factored binary trees for each number.\n1. `Sort` the input array in ascending order for effi...
3
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
binary-trees-with-factors
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Maps)***\n1. Initialize a modulo value `mod` to prevent integer overflow and create a map `mp` to store the count of factored binary trees for each number.\n1. `Sort` the input array in ascending order for effi...
3
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
🔥 Python || Detailed Explanation ✅ || Easily Understood || DP || O(n * sqrt(n))
binary-trees-with-factors
0
1
**Appreciate if you could upvote this solution**\n\nMethod: `DP`\n\nSince the parent node is the product of the children, the value of the parent nodes must larger than the values of its children.\nThus, we can sort the `arr` first, and start to calculate the combination of products **from smallest node to the largest ...
37
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary tre...
null
🔥 Python || Detailed Explanation ✅ || Easily Understood || DP || O(n * sqrt(n))
binary-trees-with-factors
0
1
**Appreciate if you could upvote this solution**\n\nMethod: `DP`\n\nSince the parent node is the product of the children, the value of the parent nodes must larger than the values of its children.\nThus, we can sort the `arr` first, and start to calculate the combination of products **from smallest node to the largest ...
37
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
Python3 code
goat-latin
0
1
# Intuition\n1.Split the input sentence into individual words using the .split() method, and store them in a list called w.\n2.Initialize empty lists l and v to store the modified words and the final modified words, respectively.\n3.Iterate over each word i in the list w.\n4.Check if the first letter of the word i is a...
1
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `...
null
Python3 code
goat-latin
0
1
# Intuition\n1.Split the input sentence into individual words using the .split() method, and store them in a list called w.\n2.Initialize empty lists l and v to store the modified words and the final modified words, respectively.\n3.Iterate over each word i in the list w.\n4.Check if the first letter of the word i is a...
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of th...
null
Solution
goat-latin
1
1
```C++ []\nclass Solution {\npublic:\n string toGoatLatin(string s) {\n string res;\n int count=0;\n for(int i=0; i<s.length(); i++){\n string temp;\n while(s[i]!=\' \' && i<s.length()){\n temp +=s[i];\n i++;\n }\n count++...
1
You are given a string `sentence` that consist of words separated by spaces. Each word consists of lowercase and uppercase letters only. We would like to convert the sentence to "Goat Latin " (a made-up language similar to Pig Latin.) The rules of Goat Latin are as follows: * If a word begins with a vowel (`'a'`, `...
null
Solution
goat-latin
1
1
```C++ []\nclass Solution {\npublic:\n string toGoatLatin(string s) {\n string res;\n int count=0;\n for(int i=0; i<s.length(); i++){\n string temp;\n while(s[i]!=\' \' && i<s.length()){\n temp +=s[i];\n i++;\n }\n count++...
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of th...
null