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 | 1-bit-and-2-bit-characters | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n bool isOneBitCharacter(vector<int>& bits) {\n auto parity = 0;\n for (int i = static_cast<int>(bits.size()) - 2;\n i >= 0 && bits[i]; --i) {\n parity ^= bits[i];\n }\n return parity == 0;\n }\n};\n```\n\n```Python3 []\nclass... | 1 | We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0... | Keep track of where the next character starts. At the end, you want to know if you started on the last bit. |
python, Time: O(n) [99.7%], Space: O(1) [100.0%], easy understand, clean, full comment | 1-bit-and-2-bit-characters | 0 | 1 | A simple solution by count backward 1s in a row\n\n```python\n# Dev: Chumicat\n# Date: 2019/11/30\n# Submission: https://leetcode.com/submissions/detail/282638543/\n# (Time, Space) Complexity : O(n), O(1)\n\nclass Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n """\n :type bits: Lis... | 19 | We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0... | Keep track of where the next character starts. At the end, you want to know if you started on the last bit. |
Full decoder | 1-bit-and-2-bit-characters | 0 | 1 | # Intuition\nSimulate decoder\n\n# Approach\nConsume bit one by one.\nIn case of bit==1 remember to skip next bit.\n\nIf you like it, please up-vote. Thank you!\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$ for full decoder, can be $$O(1)$$\n\n# Code\n```\nclass Solution:\n def isOneBi... | 2 | We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0... | Keep track of where the next character starts. At the end, you want to know if you started on the last bit. |
Python - Clean and Simple! | 1-bit-and-2-bit-characters | 0 | 1 | **Solution**:\n```\nclass Solution:\n def isOneBitCharacter(self, bits):\n i, n, numBits = 0, len(bits), 0\n while i < n:\n bit = bits[i]\n if bit == 1:\n i += 2\n numBits = 2\n else:\n i += 1\n numBits = 1\n ... | 4 | We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0... | Keep track of where the next character starts. At the end, you want to know if you started on the last bit. |
Python Simple Solution!! | 1-bit-and-2-bit-characters | 0 | 1 | # Code\n```\nclass Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n\n index: int = 0\n while index < len(bits) - 1:\n\n if bits[index] == 0: index += 1\n else: index += 2\n \n return index == len(bits) - 1\n``` | 0 | We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0... | Keep track of where the next character starts. At the end, you want to know if you started on the last bit. |
Python solution | 1-bit-and-2-bit-characters | 0 | 1 | ```\nclass Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n i, _len = 0, len(bits)\n\n while i < _len:\n if bits[i] == 0:\n i += 1\n else:\n i += 2\n if i > _len - 1: return False\n \n return True ... | 0 | We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0... | Keep track of where the next character starts. At the end, you want to know if you started on the last bit. |
kishore code | 1-bit-and-2-bit-characters | 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 | We have two special characters:
* The first character can be represented by one bit `0`.
* The second character can be represented by two bits (`10` or `11`).
Given a binary array `bits` that ends with `0`, return `true` if the last character must be a one-bit character.
**Example 1:**
**Input:** bits = \[1,0,0... | Keep track of where the next character starts. At the end, you want to know if you started on the last bit. |
Solution | maximum-length-of-repeated-subarray | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int findLength(vector<int>& nums1, vector<int>& nums2) {\n if (nums1.size() > nums2.size()) {\n nums1.swap(nums2);\n }\n string s(nums1.begin(), nums1.end());\n string t(nums2.begin(), nums2.end());\n\n auto isValid = [&](size_t cur... | 1 | Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0... | Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:]. |
python3 || 7 lines, memo, w/explanation || T/M: 81%/79% | maximum-length-of-repeated-subarray | 0 | 1 | ```\nclass Solution: # 1) We build memo, a 2Darray, 2) iterate thru nums1 & nums2\n # in reverse to populate memo, and then 3) find the max element\n # in memo; its row and col in memo shows the starting indices\n ... | 3 | Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0... | Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:]. |
🔥 [LeetCode The Hard Way] 🔥 Explained Line By Line | maximum-length-of-repeated-subarray | 0 | 1 | Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. \nI\'ll explain my solution line by line daily and you can find the full list in my [Discord](https://discord.gg/Nqm4jJcyBf).\nIf you like it, please give a star, watch my [Github R... | 40 | Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0... | Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:]. |
[Python3] Runtime: 178 ms, faster than 99.92% | Memory: 13.8 MB, less than 99.81% | maximum-length-of-repeated-subarray | 0 | 1 | ```\nclass Solution:\n def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n strnum2 = \'\'.join([chr(x) for x in nums2])\n strmax = \'\'\n ans = 0\n for num in nums1:\n strmax += chr(num)\n if strmax in strnum2:\n ans = max(ans,len(strmax... | 35 | Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0... | Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:]. |
Python Elegant & Short | Bottom-Up DP | maximum-length-of-repeated-subarray | 0 | 1 | \tclass Solution:\n\t\t"""\n\t\tTime: O(n*m)\n\t\tMemory: O(n*m)\n\t\t"""\n\n\t\tdef findLength(self, a: List[int], b: List[int]) -> int:\n\t\t\tn, m = len(a), len(b)\n\t\t\tdp = [[0] * (m + 1) for _ in range(n + 1)]\n\n\t\t\tfor i in range(n):\n\t\t\t\tfor j in range(m):\n\t\t\t\t\tif a[i] == b[j]:\n\t\t\t\t\t\tdp[i... | 2 | Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0... | Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:]. |
Python Clean & Simple Binary Search Implementation eliminating TLE 🔥🔥🔥 | find-k-th-smallest-pair-distance | 0 | 1 | \n# Code\n```\nclass Solution:\n def smallestDistancePair(self, arr: List[int], k: int) -> int:\n def count(x):\n i = j = cnt = 0\n while i < n:\n while j < n and arr[j] - arr[i] <= x:\n j += 1\n cnt += j - i - 1 \n i += 1\... | 1 | The **distance of a pair** of integers `a` and `b` is defined as the absolute difference between `a` and `b`.
Given an integer array `nums` and an integer `k`, return _the_ `kth` _smallest **distance among all the pairs**_ `nums[i]` _and_ `nums[j]` _where_ `0 <= i < j < nums.length`.
**Example 1:**
**Input:** nums =... | Binary search for the answer. How can you check how many pairs have distance <= X? |
Simple brute force to beat 100% using BST | find-k-th-smallest-pair-distance | 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. -->\nTo solve this problem, you can use a binary search approach. First, sort the array nums. Then, perform binary search on the possible range of distances to find the kth... | 1 | The **distance of a pair** of integers `a` and `b` is defined as the absolute difference between `a` and `b`.
Given an integer array `nums` and an integer `k`, return _the_ `kth` _smallest **distance among all the pairs**_ `nums[i]` _and_ `nums[j]` _where_ `0 <= i < j < nums.length`.
**Example 1:**
**Input:** nums =... | Binary search for the answer. How can you check how many pairs have distance <= X? |
Python 3 || 14 lines, two ptrs and bin search || T/M: 80% / 94% | find-k-th-smallest-pair-distance | 0 | 1 | ```\nclass Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n \n def check(dist: int)-> bool:\n\n i = j = cnt = 0\n\n for i in range(n): # Use two ptrs to count pairs with\n while j < n and nums[j] - nums[i] <= dist: ... | 6 | The **distance of a pair** of integers `a` and `b` is defined as the absolute difference between `a` and `b`.
Given an integer array `nums` and an integer `k`, return _the_ `kth` _smallest **distance among all the pairs**_ `nums[i]` _and_ `nums[j]` _where_ `0 <= i < j < nums.length`.
**Example 1:**
**Input:** nums =... | Binary search for the answer. How can you check how many pairs have distance <= X? |
Simple python binary search | find-k-th-smallest-pair-distance | 0 | 1 | \tclass Solution:\n\t\tdef smallestDistancePair(self, nums: List[int], k: int) -> int:\n\n\t\t\tdef getPairs(diff):\n\t\t\t\tl = 0\n\t\t\t\tcount = 0\n\n\t\t\t\tfor r in range(len(nums)):\n\t\t\t\t\twhile nums[r] - nums[l] > diff:\n\t\t\t\t\t\tl += 1\n\t\t\t\t\tcount += r - l\n\n\t\t\t\treturn count\n\n\n\t\t\tnums.sor... | 2 | The **distance of a pair** of integers `a` and `b` is defined as the absolute difference between `a` and `b`.
Given an integer array `nums` and an integer `k`, return _the_ `kth` _smallest **distance among all the pairs**_ `nums[i]` _and_ `nums[j]` _where_ `0 <= i < j < nums.length`.
**Example 1:**
**Input:** nums =... | Binary search for the answer. How can you check how many pairs have distance <= X? |
Sorting + Binary Search | find-k-th-smallest-pair-distance | 0 | 1 | # Intuition\nA brute-force way is to count the total number of pairs and rank them based on the distance. The time complexity of this solution is $$O(N^2 + N^2logN^2)$$ and the space complexity is $$O(N^2)$$.\n\nAn improved solution is to use a min heap with capacity k to find the kth smallest on the fly. The time comp... | 1 | The **distance of a pair** of integers `a` and `b` is defined as the absolute difference between `a` and `b`.
Given an integer array `nums` and an integer `k`, return _the_ `kth` _smallest **distance among all the pairs**_ `nums[i]` _and_ `nums[j]` _where_ `0 <= i < j < nums.length`.
**Example 1:**
**Input:** nums =... | Binary search for the answer. How can you check how many pairs have distance <= X? |
Solution | find-k-th-smallest-pair-distance | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int rank(vector<int>& nums, int dis) {\n int count=0, lo=0, hi=1;\n while(hi<nums.size()) {\n while(nums[hi]-nums[lo] > dis)\n lo++;\n count += hi-lo;\n hi++;\n }\n return count;\n }\n int smalles... | 2 | The **distance of a pair** of integers `a` and `b` is defined as the absolute difference between `a` and `b`.
Given an integer array `nums` and an integer `k`, return _the_ `kth` _smallest **distance among all the pairs**_ `nums[i]` _and_ `nums[j]` _where_ `0 <= i < j < nums.length`.
**Example 1:**
**Input:** nums =... | Binary search for the answer. How can you check how many pairs have distance <= X? |
Easy Python Solution !! Prefix !! Clean Code | longest-word-in-dictionary | 1 | 1 | # Python Code\n---\n```\nclass Solution:\n def longestWord(self, words: List[str]) -> str:\n map = {}\n for word in words:\n map[word] = 1\n result = ""\n words.sort()\n for word in words:\n flag = True\n for i in range(len(word)-1):\n ... | 5 | Given an array of strings `words` representing an English Dictionary, return _the longest word in_ `words` _that can be built one character at a time by other words in_ `words`.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the... | For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set. |
Trie+BFS | [Python] Solution with Comments Easy to Understand | longest-word-in-dictionary | 0 | 1 | ```\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.endOfWord = False\n self.val = \'\' # to define the value of end node as word\n\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n \n def addWord(self, word):\n cur = self.root\n ... | 6 | Given an array of strings `words` representing an English Dictionary, return _the longest word in_ `words` _that can be built one character at a time by other words in_ `words`.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the... | For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set. |
720. Longest Word in Dictionary, Solution with step by step explanation | longest-word-in-dictionary | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n words.sort()\n```\nWe sort the list of words in lexicographical order. This ensures that when two words of equal length qualify as an answer, the word which appears first in lexicographical order will be considered ... | 1 | Given an array of strings `words` representing an English Dictionary, return _the longest word in_ `words` _that can be built one character at a time by other words in_ `words`.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the... | For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set. |
[Python] O(n log(n)) Time, O(n) Space Faster Than 95% | longest-word-in-dictionary | 0 | 1 | ```\nclass Solution:\n def longestWord(self, words: List[str]) -> str:\n words.sort() # for smallest lexicographical order\n visited = {""} # hashset to keep a track of visited words\n res = \'\'\n \n for word in words:\n if word[:-1] in v... | 4 | Given an array of strings `words` representing an English Dictionary, return _the longest word in_ `words` _that can be built one character at a time by other words in_ `words`.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the... | For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set. |
Solution | longest-word-in-dictionary | 1 | 1 | ```C++ []\nstruct TrieNode {\npublic:\n TrieNode() : is_end{false} {\n for (int i = 0; i < 26; i++) children[i] = nullptr;\n } \npublic:\n TrieNode* children[26];\n bool is_end;\n};\nclass Trie {\npublic:\n Trie() : root_{new TrieNode()} {}\n void insert(const std::string& str) {\n Tri... | 2 | Given an array of strings `words` representing an English Dictionary, return _the longest word in_ `words` _that can be built one character at a time by other words in_ `words`.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the... | For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set. |
[Python] Trie solution explained | longest-word-in-dictionary | 0 | 1 | ```\nclass TrieNode(object):\n def __init__(self):\n self.children = {}\n self.end = False\n\nclass Solution:\n def longestWord(self, words: List[str]) -> str:\n root = TrieNode()\n\n # populate all the elements in the trie\n # word by word, no need for sorting here\n for... | 9 | Given an array of strings `words` representing an English Dictionary, return _the longest word in_ `words` _that can be built one character at a time by other words in_ `words`.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the... | For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set. |
Simple Python code || Trie, single scan | longest-word-in-dictionary | 0 | 1 | Sort the list to make sure it\'s in alphabetic order (so that we don\'t need to update previously-visited longer words\' values, and also make sure for same length of result, the alphabetic order is in place).\n\nWe just scan each word and add to Trie, while keep counting whether it can be built letter by letter (cur.v... | 2 | Given an array of strings `words` representing an English Dictionary, return _the longest word in_ `words` _that can be built one character at a time by other words in_ `words`.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the... | For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set. |
easy peasy python solution using sorting and set | longest-word-in-dictionary | 0 | 1 | \tdef longestWord(self, words: List[str]) -> str:\n #sort the words, then keep in the set and check for nextWord[:-1] in the set\n words.sort()\n st, res = set(), "" #res == result\n st.add("")\n for word in words:\n if word[:-1] in st:\n if len(word) > len(r... | 14 | Given an array of strings `words` representing an English Dictionary, return _the longest word in_ `words` _that can be built one character at a time by other words in_ `words`.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the... | For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set. |
Python Trie+DFS solution | longest-word-in-dictionary | 0 | 1 | We first insert all the words to the Trie. Then, we go through the words again and look for the longest word in the dictionary using DFS. As soon as we see that any word leading up to a word doesn\'t exist in the Trie we can stop searching deeper. Since we sort the words beforehand we have the longest word with the sma... | 4 | Given an array of strings `words` representing an English Dictionary, return _the longest word in_ `words` _that can be built one character at a time by other words in_ `words`.
If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the... | For every word in the input list, we can check whether all prefixes of that word are in the input list by using a Set. |
[Python] The clean Union-Find solution you are looking for | accounts-merge | 0 | 1 | ```python\nclass UF:\n def __init__(self, N):\n self.parents = list(range(N))\n def union(self, child, parent):\n self.parents[self.find(child)] = self.find(parent)\n def find(self, x):\n if x != self.parents[x]:\n self.parents[x] = self.find(self.parents[x])\n return sel... | 217 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
Solution | accounts-merge | 1 | 1 | ```C++ []\nclass DisjointSet {\n vector<int> rank, parent, size;\npublic:\n DisjointSet(int n) {\n rank.resize(n + 1, 0);\n parent.resize(n + 1);\n size.resize(n + 1);\n for (int i = 0; i <= n; i++) {\n parent[i] = i;\n size[i] = 1;\n }\n }\n int find... | 2 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
Python || Easy || Disjoint Sets Union | accounts-merge | 0 | 1 | ```\nclass Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n def findParent(u):\n if u==parent[u]:\n return u\n else:\n parent[u]=findParent(parent[u])\n return parent[u]\n \n def unionB... | 2 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
:=) Python Solution ( Union-Find | Map | Counter | Insort ) + Explanation ! | accounts-merge | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSolve the problem via majorly 2 Data Structure in combination i.e\nUnion-Find + HashMap\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUnion and Find to reduce the accounts to unique groups\n\nConcepts :\n- Union-... | 2 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
✅[Python] Simple and Clean, beats 88%✅ | accounts-merge | 0 | 1 | ### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n*This is an NFT*\n\n\n# Intuition\nThe problem requires us to merge accounts that belong to the same p... | 6 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
Python DFS Solution - Intuitive | accounts-merge | 0 | 1 | I broke it down into small pieces as it\'s more intuitive for people trying to learn and understand.\n\n```\nclass Solution:\n def __init__(self):\n self.accountConnections = defaultdict(set)\n self.emailToName = dict()\n self.seen = set()\n \n def buildConnections(self, accounts):\n ... | 1 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
Python straightforward Union Find approach with explanation and comments | accounts-merge | 0 | 1 | # Approach\n1. Define a UnionFind class that has Union by Rank and Find with path compression. \n\n2. Create a dictionary email_to_name to map each email to the name associated with it.\n\n3. Create an instance of the UnionFind class.\n\n4. For each account in the accounts list, iterate over its emails and add them to ... | 3 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
Python3 solution using Union Find (disjoint set). | accounts-merge | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen there are many sets (accounts in this problem) but some of them are connected, you might use disjoint set(also called union find) to get the number of seperated sets.\n\n# Approach\n<!-- Describe your approach to solving the problem.... | 1 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
75% TC and 82% SC "only" union-find python solution | accounts-merge | 0 | 1 | ```\ndef accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n\tdef union(u, v):\n\t\tx, y = find(u), find(v)\n\t\tif(x != y):\n\t\t\tif(rank[x] > rank[y]):\n\t\t\t\tpar[y] = x\n\t\t\telif(rank[x] < rank[y]):\n\t\t\t\tpar[x] = y\n\t\t\telse:\n\t\t\t\tpar[x] = y\n\t\t\t\trank[y] += 1\n\tdef find(u):\n\t\t... | 1 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
Python easy to read and understand | DFS | accounts-merge | 0 | 1 | ```\nclass Solution:\n def dfs(self, graph, node, visit):\n visit.add(node)\n for nei in graph[node]:\n if nei not in visit:\n self.dfs(graph, nei, visit)\n self.res.append(node)\n \n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n ... | 11 | Given a list of `accounts` where each element `accounts[i]` is a list of strings, where the first element `accounts[i][0]` is a name, and the rest of the elements are **emails** representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is... | For every pair of emails in the same account, draw an edge between those emails. The problem is about enumerating the connected components of this graph. |
Solution | remove-comments | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<string> removeComments(vector<string>& source) {\n bool isComment = false, needJoin = false;\n vector<string> res;\n for (auto& s : source) {\n string curr;\n for (int i = 0; i < s.size(); ++i) {\n if (s[i] == \'/... | 1 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
Easy to understand using Python | remove-comments | 0 | 1 | ```\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n ans, inComment = [], False\n new_str = ""\n for c in source:\n if not inComment: new_str = ""\n i, n = 0, len(c)\n # inComment, we find */\n while i < n:\n ... | 3 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
Python regex 10 lines | remove-comments | 0 | 1 | ```\nimport re\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n s = \'\\n\'.join(source)\n regex_single = r"\\/\\/.*"\n regex_block_closed = r"(?s:\\/\\*.*?\\*\\/)"\n regex_block_not_closed = r"\\/\\*.*" \n regex = \'|\'.join([regex_single, regex_bl... | 11 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
Python3 Easy solution | remove-comments | 0 | 1 | \n\n\n\n def removeComments(self, source: List[str]) -> List[str]:\n \n all_string = "\\n".join(source)\n result_string = ""\n\n i = 0\n while i < len(all_string):\n\n two = all_string[i:i+2]\n if two == "//":\n\n ... | 2 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
✔Beginer Friendly Easy Solution | remove-comments | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves removing comments from source code. The initial insight is to concatenate the code lines into a single string, using a specific delimiter for easier manipulation. Iterating through the concatenated string, we identify... | 0 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
Python Another Long Solution, 140 Lines | remove-comments | 0 | 1 | ```\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]: \n block_comment = False\n new_line = False\n block_start, block_end, line_start = "/*", "*/", "//"\n res = []\n \n for line in source:\n if not block_comment:\n ... | 0 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
💡💡 Neatly coded solution in python3 | remove-comments | 0 | 1 | # Intuition behind the approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nTraverse through the course and check for comment symbols. Process the strings accordingly. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!--... | 0 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
Python3 one-pass state machine | remove-comments | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIdea similar to state machine.\n\n# Code\n```\nclass Solution:\n\n def process_line(self, state, line):\n state = state\n output_line = []\n idx = 0\n while idx < len(line):\n ch = line[idx]\n ... | 0 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
Simple Python | remove-comments | 0 | 1 | ```python\ndef solve(source: list[str]) -> list[str]:\n\n res, cmt = [], False\n for line in source:\n i, s = 0, \'\' if not cmt else res.pop()\n while i < len(line):\n if line[i: i + 2] == \'*/\' and cmt:\n i, cmt = i + 2, False\n elif cmt:\n i +=... | 0 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
Python | O(n) | Easy to understand | remove-comments | 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 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
722. Remove Comments, solution with step by step explanation | remove-comments | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nInitialization: We initialize an empty result list res to store the final lines after removing comments. The buffer string will store the intermediate content of each line after removing comments. in_block is a boolean flag ... | 0 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
Painful Solution | remove-comments | 0 | 1 | # Intuition\nNo intuition... just a painful solution\n\n# Approach\n1. Maintain a buffer of chars. We add chars to the buffer until we encouner a newline or a comment\n2. If we see a `//` , add the buffer to the return array and go to next line\n3. If we see a `/*` ignore everything until we find a `*/`\n4. ??? Profit\... | 0 | Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`.
In C++, there are two types of comments, line comments, and b... | Carefully parse each line according to the following rules:
* If we start a block comment and we aren't in a block, then we will skip over the next two characters and change our state to be in a block.
* If we end a block comment and we are in a block, then we will skip over the next two characters and change our... |
Very Easy || 100% || Fully Explained || Java, C++, Python, JS, Python3 | find-pivot-index | 1 | 1 | # **Java Solution:**\n```\n// Runtime: 1 ms, faster than 92.94% of Java online submissions for Find Pivot Index.\n// Time Complexity : O(n)\nclass Solution {\n public int pivotIndex(int[] nums) {\n // Initialize total sum of the given array...\n int totalSum = 0;\n // Initialize \'leftsum\' as s... | 753 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Very Easy || 100% || Fully Explained || Java, C++, Python, JS, Python3 | find-pivot-index | 1 | 1 | # **Java Solution:**\n```\n// Runtime: 1 ms, faster than 92.94% of Java online submissions for Find Pivot Index.\n// Time Complexity : O(n)\nclass Solution {\n public int pivotIndex(int[] nums) {\n // Initialize total sum of the given array...\n int totalSum = 0;\n // Initialize \'leftsum\' as s... | 753 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Simple Python Approach | find-pivot-index | 0 | 1 | # Code\n```\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n # Total value of the nums\n tot = sum(nums)\n left = 0\n\n # Iterating through the list\n for index, ele in enumerate(nums):\n # Calculating the right side value\n right = tot - lef... | 4 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Simple Python Approach | find-pivot-index | 0 | 1 | # Code\n```\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n # Total value of the nums\n tot = sum(nums)\n left = 0\n\n # Iterating through the list\n for index, ele in enumerate(nums):\n # Calculating the right side value\n right = tot - lef... | 4 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Awesome Approach Python3 | find-pivot-index | 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)$$ --... | 54 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Awesome Approach Python3 | find-pivot-index | 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)$$ --... | 54 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Python solution ✅|| O(N) and O(1) || Easy To Understand With Explanation🔥 | find-pivot-index | 0 | 1 | **Time complexity:- O(N)\nSpace complexity:- O(1)**\n\n**Dry Run:-**\n\nInput: ``` [1,7,3,6,5,6]```\n**Note**: the nums[i] element are include in right sum that\'s why we use right+=num first.\n\n```The total sum of nums```: 28\n\n1. ```index```: 0, ```nums```: 1, ```left```: 0, ```right ```:27\n2. ```index```: 1, `... | 2 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Python solution ✅|| O(N) and O(1) || Easy To Understand With Explanation🔥 | find-pivot-index | 0 | 1 | **Time complexity:- O(N)\nSpace complexity:- O(1)**\n\n**Dry Run:-**\n\nInput: ``` [1,7,3,6,5,6]```\n**Note**: the nums[i] element are include in right sum that\'s why we use right+=num first.\n\n```The total sum of nums```: 28\n\n1. ```index```: 0, ```nums```: 1, ```left```: 0, ```right ```:27\n2. ```index```: 1, `... | 2 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Binary Search | find-pivot-index | 0 | 1 | \n# Code\n```\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n \n nums.append(0)\n start_sum = 0\n pivot = 0\n end_sum = sum(nums[1:])\n \n while(pivot < len(nums)-1):\n if start_sum == end_sum:\n return pivot\n e... | 1 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Binary Search | find-pivot-index | 0 | 1 | \n# Code\n```\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n \n nums.append(0)\n start_sum = 0\n pivot = 0\n end_sum = sum(nums[1:])\n \n while(pivot < len(nums)-1):\n if start_sum == end_sum:\n return pivot\n e... | 1 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Python/Go/Java/JS/C++ O(n) sol. by Balance scale. [w/ explanation] 有中文解題文章 | find-pivot-index | 1 | 1 | [Tutorial video in Chinese \u4E2D\u6587\u89E3\u984C\u5F71\u7247](https://www.youtube.com/watch?v=hK9gdtn2zq0)\n\n[\u4E2D\u6587\u8A73\u89E3 \u89E3\u984C\u6587\u7AE0](https://vocus.cc/article/655b6d6ffd89780001b34a15)\n\nO(n) sol. by Balance scale.\n\n---\n\n**Hint**:\n\n#1.\nThink of the **Balance scale** in laboratory ... | 177 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
Python/Go/Java/JS/C++ O(n) sol. by Balance scale. [w/ explanation] 有中文解題文章 | find-pivot-index | 1 | 1 | [Tutorial video in Chinese \u4E2D\u6587\u89E3\u984C\u5F71\u7247](https://www.youtube.com/watch?v=hK9gdtn2zq0)\n\n[\u4E2D\u6587\u8A73\u89E3 \u89E3\u984C\u6587\u7AE0](https://vocus.cc/article/655b6d6ffd89780001b34a15)\n\nO(n) sol. by Balance scale.\n\n---\n\n**Hint**:\n\n#1.\nThink of the **Balance scale** in laboratory ... | 177 | Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left... | We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i]. |
【Video】Simple and Easy Solution - Python, JavaScript, Java, C++ | split-linked-list-in-parts | 1 | 1 | # Intuition\nCalculate length of linked list and get length of each sub list.\n\n---\n\n# Solution Video\n\n### Please subscribe to my channel from here. I have 256 videos as of September 6th, 2023.\n\nhttps://youtu.be/ir-tDj1kM5g\n\n### In the video, the steps of approach below are visualized using diagrams and drawin... | 24 | Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occ... | If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one. |
✅95%||✅Full Explanation🔥||Beginner Friendly🔥||Two-Pass Method✅ | split-linked-list-in-parts | 1 | 1 | # Problem Understanding\nThe problem asks us to **split a singly linked list into k consecutive** linked list parts while maintaining two important conditions:\n\n1. The length of each part should be **as equal as possible**.\n2. **No two parts should have a size differing by more than one**.\n# Intuition\n<!-- Describ... | 254 | Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occ... | If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one. |
Python3 Solution | split-linked-list-in-parts | 0 | 1 | \n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:\n ans=[]\n cur=head\n n=0... | 2 | Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occ... | If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one. |
Beats 100% || Step by step || Easy Explanation || C++ || Java || Python | split-linked-list-in-parts | 1 | 1 | \n# Problem Description:\nGiven the head of a singly-linked list and an integer k, you need to split the list into k consecutive linked list "parts." The size of each part should be as equal as possible and parts occurring earlier should always have a size greater than or equal to parts occurring later.. If there are f... | 36 | Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occ... | If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one. |
Easiest Solution | split-linked-list-in-parts | 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 the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occ... | If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one. |
Beginner-friendly || Simple solution in Python3 | split-linked-list-in-parts | 0 | 1 | # Intuition\nThe problem description is the following:\n- there\'s a **linked list** of n-nodes\n- we need to **split** a list into `k`- chunks\n- the size of a particular part **must** be equal or **greater by one** to the next chunk size \n\nThe logic is quite straightforward:\n```\n# Imagine we have a list with siz... | 1 | Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts.
The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null.
The parts should be in the order of occ... | If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one. |
Python Commented in Detail | number-of-atoms | 0 | 1 | ```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n i, n = 0, len(formula)\n # Initialize a counter to keep track of the atoms\n count = Counter()\n stack = [count]\n\n # Loop through the formula\n while i < n:\n # \'(\' indicates the start of a ... | 1 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to... |
Python Commented in Detail | number-of-atoms | 0 | 1 | ```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n i, n = 0, len(formula)\n # Initialize a counter to keep track of the atoms\n count = Counter()\n stack = [count]\n\n # Loop through the formula\n while i < n:\n # \'(\' indicates the start of a ... | 1 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to g... |
726. Number of Atoms, solution with step by step explanation | number-of-atoms | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nStep 1:\nCreate a stack to keep track of the atoms and their counts. Initialize it with an empty dictionary. The stack will help manage atoms within nested parentheses.\nDefine elem to store the current atom name.\nInitializ... | 1 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to... |
726. Number of Atoms, solution with step by step explanation | number-of-atoms | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nStep 1:\nCreate a stack to keep track of the atoms and their counts. Initialize it with an empty dictionary. The stack will help manage atoms within nested parentheses.\nDefine elem to store the current atom name.\nInitializ... | 1 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to g... |
Easy Peesy Lemon Squeezy!! Nice and Clear Solution | number-of-atoms | 0 | 1 | # Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n n = len(formula)\n stack = []\n count = defaultdict(lambda:0)\n c, s = "", ""\n for i in formula[::-1]:\n if i.isdigit():\n ... | 1 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to... |
Easy Peesy Lemon Squeezy!! Nice and Clear Solution | number-of-atoms | 0 | 1 | # Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n n = len(formula)\n stack = []\n count = defaultdict(lambda:0)\n c, s = "", ""\n for i in formula[::-1]:\n if i.isdigit():\n ... | 1 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to g... |
Simple Python Solution | number-of-atoms | 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 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to... |
Simple Python Solution | number-of-atoms | 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 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to g... |
Python | Runtime 34ms Beats 97.02% of users | number-of-atoms | 0 | 1 | # Complexity\n- Time complexity: $$O(n*26) = O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n # If the formula length is 1, just return it.\n if len(formula)==1:\n return formula\n \n # Create an empty stack... | 0 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to... |
Python | Runtime 34ms Beats 97.02% of users | number-of-atoms | 0 | 1 | # Complexity\n- Time complexity: $$O(n*26) = O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n # If the formula length is 1, just return it.\n if len(formula)==1:\n return formula\n \n # Create an empty stack... | 0 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to g... |
[Python3] Readable Recursive Solution | number-of-atoms | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to count the number of atoms in a chemical formula, which can include parentheses and digits. To solve this problem, we can use a recursive approach to parse the formula and count the number of atoms in each subfor... | 0 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to... |
[Python3] Readable Recursive Solution | number-of-atoms | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires us to count the number of atoms in a chemical formula, which can include parentheses and digits. To solve this problem, we can use a recursive approach to parse the formula and count the number of atoms in each subfor... | 0 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to g... |
Recursion Descent in Python | number-of-atoms | 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 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to... |
Recursion Descent in Python | number-of-atoms | 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 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to g... |
Python -- lots of helper functions + comments, recursive | number-of-atoms | 0 | 1 | # Intuition\n```\nformula := <block>[blocks...]\n\nblock := <element>|<group>\n\ngroup := "("<formula>")"[quantity]\n\nelement := <upper case char>[lower case char][quantity]\n\nquantity := <positive integer as a string> \n```\n\n# Approach\n* Use a loop to iterate over blocks in the formula\n* Check if a block is a gr... | 0 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to... |
Python -- lots of helper functions + comments, recursive | number-of-atoms | 0 | 1 | # Intuition\n```\nformula := <block>[blocks...]\n\nblock := <element>|<group>\n\ngroup := "("<formula>")"[quantity]\n\nelement := <upper case char>[lower case char][quantity]\n\nquantity := <positive integer as a string> \n```\n\n# Approach\n* Use a loop to iterate over blocks in the formula\n* Check if a block is a gr... | 0 | Given a string `formula` representing a chemical formula, return _the count of each atom_.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than `1`. If the ... | To parse formula[i:], when we see a `'('`, we will parse recursively whatever is inside the brackets (up to the correct closing ending bracket) and add it to our count, multiplying by the following multiplicity if there is one.
Otherwise, we should see an uppercase character: we will parse the rest of the letters to g... |
Solution of self dividing numbers problem | self-dividing-numbers | 0 | 1 | # Approach\n- Step one: create list for answer\n- Step two: add number, which doesn\'t contain "0" and number is a number that is divisible by every digit it contains.\n- Step three: return answer\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def sel... | 1 | A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a l... | For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number. |
Python Easy Solution || 100% || | self-dividing-numbers | 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 | A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a l... | For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number. |
Very slow solution but very short and easy to understand | self-dividing-numbers | 0 | 1 | # Code\n```\nclass Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n a = []\n for i in range(left, right+1):\n if len(str(i)) == sum(1 if int(j)!=0 and i%int(j)==0 else 0 for j in str(i)): a.append(i)\n return a\n``` | 1 | A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a l... | For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number. |
Solution using strings beats 90% | self-dividing-numbers | 0 | 1 | \n# Code\n```\nclass Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n def selfdivision(n):\n s_n = str(n)\n for char in s_n:\n if char == \'0\':\n return False\n if n % int(char) != 0:\n r... | 1 | A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a l... | For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number. |
Beating 99.2% Easiest Explained Python Solution | self-dividing-numbers | 0 | 1 | \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirstly, initiated one empty list. Then staretd a loop from left to right to find the self dividing numbers in the range[left,right].... | 4 | A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a l... | For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number. |
simple python | self-dividing-numbers | 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)$$ --... | 2 | A **self-dividing number** is a number that is divisible by every digit it contains.
* For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`.
A **self-dividing number** is not allowed to contain the digit zero.
Given two integers `left` and `right`, return _a l... | For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number. |
✅ Easy Binary Search Approach ! | my-calendar-i | 0 | 1 | # Approach 1\nWe work with sorted list of intervals - ```SortedList``` from ```sortedcontainers``` keeps order sorted and provides $$O(log(n))$$ for insertions.\nFirstly we check cases of most left and most right insertions. Then we check if it is possible to insert inside the list of intervals using binary search.\n\n... | 5 | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**.
A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.).
The event can be represented as a pair of integers `start... | Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added. |
Python3 | BST | With Explanation | Easy to Understand | my-calendar-i | 0 | 1 | # Idea\n<!-- Describe your first thoughts on how to solve this problem. -->\nbinary search tree\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. take each event as a tree node\n2. when trying to insert an event in the tree, recursively compare node\'s start value and end value (start from root... | 3 | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**.
A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.).
The event can be represented as a pair of integers `start... | Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added. |
python3 | easy | explained | my-calendar-i | 0 | 1 | ```\nclass MyCalendar:\n\n def __init__(self):\n self.booked = []\n\n def book(self, start: int, end: int) -> bool:\n if self.check_booking(start, end):\n self.booked.append([start, end])\n return True\n return False\n \n # to check -> new booking is valid or n... | 2 | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**.
A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.).
The event can be represented as a pair of integers `start... | Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added. |
Python 3 || 7 lines, dp || T/S: 96% / 51% | count-different-palindromic-subsequences | 0 | 1 | ```\nclass Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n\n @lru_cache(None)\n def dp(left: int, rght: int, res = 0):\n\n for ch in \'abcd\':\n\n l, r = s.find(ch,left,rght), s.rfind(ch,left,rght)\n \n res+= 0 if l==-1 else 1... | 3 | Given a string s, return _the number of different non-empty palindromic subsequences in_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`.
A subsequence of a string is obtained by deleting zero or more characters from the string.
A sequence is palindromic if it is equal to the sequence reversed... | Let dp(i, j) be the answer for the string T = S[i:j+1] including the empty sequence. The answer is the number of unique characters in T, plus palindromes of the form "a_a", "b_b", "c_c", and "d_d", where "_" represents zero or more characters. |
Fast Python solution | count-different-palindromic-subsequences | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking us to find the number of unique palindromic subsequences in a given string. My first thought would be to use dynamic programming to solve this problem.\n# Approach\n<!-- Describe your approach to solving the problem.... | 2 | Given a string s, return _the number of different non-empty palindromic subsequences in_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`.
A subsequence of a string is obtained by deleting zero or more characters from the string.
A sequence is palindromic if it is equal to the sequence reversed... | Let dp(i, j) be the answer for the string T = S[i:j+1] including the empty sequence. The answer is the number of unique characters in T, plus palindromes of the form "a_a", "b_b", "c_c", and "d_d", where "_" represents zero or more characters. |
730. Count Different Palindromic Subsequences, solution with step by step explanation | count-different-palindromic-subsequences | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBase Cases:\nIf i > j, it means the substring is empty, so the function returns 0.\nIf i == j, it means the substring has only one character, which is a palindrome itself. Hence, it returns 1.\nIf the result for indices (i, ... | 0 | Given a string s, return _the number of different non-empty palindromic subsequences in_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`.
A subsequence of a string is obtained by deleting zero or more characters from the string.
A sequence is palindromic if it is equal to the sequence reversed... | Let dp(i, j) be the answer for the string T = S[i:j+1] including the empty sequence. The answer is the number of unique characters in T, plus palindromes of the form "a_a", "b_b", "c_c", and "d_d", where "_" represents zero or more characters. |
Maintain Two lists to keep track of single and double booking | my-calendar-ii | 0 | 1 | ```\nclass MyCalendarTwo:\n\n def __init__(self):\n self.single_booked = []\n self.double_booked = []\n\n def book(self, start: int, end: int) -> bool:\n # first check for a overlap interval in double booked\n for booking in self.double_booked:\n s, e = booking[:]\n ... | 1 | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **triple booking**.
A **triple booking** happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).
The event can be represented as a pair of inte... | Store two sorted lists of intervals: one list will be all times that are at least single booked, and another list will be all times that are definitely double booked. If none of the double bookings conflict, then the booking will succeed, and you should update your single and double bookings accordingly. |
731: Solution with step by step explanation | my-calendar-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIn the initialization of the MyCalendarTwo class, two lists are created:\n\ncalendar - This list will store all individual bookings.\noverlaps - This list will store all intervals where a double booking occurs.\n\n```\ndef _... | 1 | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **triple booking**.
A **triple booking** happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).
The event can be represented as a pair of inte... | Store two sorted lists of intervals: one list will be all times that are at least single booked, and another list will be all times that are definitely double booked. If none of the double bookings conflict, then the booking will succeed, and you should update your single and double bookings accordingly. |
Python3 almost log N RangeModule style solution | my-calendar-ii | 0 | 1 | ```\nclass MyCalendarTwo:\n\n def __init__(self):\n self.single_booked = []\n self.double_booked = []\n \n def intersection(self, intervals, s, e):\n\n l = bisect.bisect_left(intervals, s)\n r = bisect.bisect_right(intervals, e)\n \n intersection = []\n \n ... | 0 | You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **triple booking**.
A **triple booking** happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).
The event can be represented as a pair of inte... | Store two sorted lists of intervals: one list will be all times that are at least single booked, and another list will be all times that are definitely double booked. If none of the double bookings conflict, then the booking will succeed, and you should update your single and double bookings accordingly. |
Solution | my-calendar-iii | 1 | 1 | ```C++ []\nclass SegmentTreeNode {\npublic:\n SegmentTreeNode *left, *right;\n int start, end;\n int overlap;\n\n SegmentTreeNode(int _start, int _end) {\n start = _start;\n end = _end;\n left = right = nullptr;\n overlap = 0;\n }\n int insert(int startTime, int endTime) {\... | 1 | A `k`\-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.)
You are given some events `[startTime, endTime)`, after each given event, return an integer `k` representing the maximum `k`\-booking between all the previous events.
Implement the `MyC... | Treat each interval [start, end) as two events "start" and "end", and process them in sorted order. |
Python using HashMap - {Time Limit Exceeded - Solved} | my-calendar-iii | 0 | 1 | # Solution\nWe can solved the **Time Limit Exceeded** Solution using **accumulate()**. \nSince **build-in function** work **3x times** faster than normal **for loop** code.\n\n# Logic \nStart the event by **adding +1** and terminate the event by **subrating -1** in the timeline.\nNow we have find the maximum number of ... | 1 | A `k`\-booking happens when `k` events have some non-empty intersection (i.e., there is some time that is common to all `k` events.)
You are given some events `[startTime, endTime)`, after each given event, return an integer `k` representing the maximum `k`\-booking between all the previous events.
Implement the `MyC... | Treat each interval [start, end) as two events "start" and "end", and process them in sorted order. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.