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 Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n ret = True\n for bit in bits[-2::-1]:\n if bit: ret = not ret\n else: break\n return ret\n```\n\n```Java []\nclass Solution {\n public boolean isOneBitCharacter(int[] bits) {\n return solve(0, bits, 0);\n }\n private boolean solve(int idx, int[] bits, int prev) { \n if (idx == bits.length) return prev == 0;\n\t\t\n return prev>= 2 \n\t\t\t? solve(idx+1, bits, bits[idx])\n\t\t\t : solve(idx+1, bits, (prev<<1) | bits[idx]);\n }\n}\n```\n | 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\]
**Output:** true
**Explanation:** The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
**Example 2:**
**Input:** bits = \[1,1,1,0\]
**Output:** false
**Explanation:** The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
**Constraints:**
* `1 <= bits.length <= 1000`
* `bits[i]` is either `0` or `1`. | 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: List[int]\n :rtype: bool\n """\n # Important Rules:\n # 1. If bit n is 0, bit n+1 must be a new char\n # 2. If bits end with 1, last bit must be a two bit char\n # However, this case had been rejected by question\n # 3. If 1s in row and end with 0, \n # we can use count or 1s to check last char\n # If count is even, last char is "0"\n # If count is odd, last char is "10"\n # Strategy:\n # 1. We don\'t care last element, since it must be 0.\n # 2. We check from reversed, and count 1s in a row\n # 3. Once 0 occur or list end, We stop counting\n # 4. We use count to determin result\n # 5. Since we will mod count by 2, we simplify it to bool\n ret = True\n for bit in bits[-2::-1]:\n if bit: ret = not ret\n else: break\n return ret\n``` | 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\]
**Output:** true
**Explanation:** The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
**Example 2:**
**Input:** bits = \[1,1,1,0\]
**Output:** false
**Explanation:** The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
**Constraints:**
* `1 <= bits.length <= 1000`
* `bits[i]` is either `0` or `1`. | 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 isOneBitCharacter(self, bits: List[int]) -> bool:\n skip = 0\n decoded = []\n for bit in bits:\n if skip:\n skip -= 1\n continue\n if bit == 0:\n decoded.append("A")\n else:\n decoded.append("B")\n skip = 1\n return decoded[-1] == "A"\n``` | 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\]
**Output:** true
**Explanation:** The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
**Example 2:**
**Input:** bits = \[1,1,1,0\]
**Output:** false
**Explanation:** The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
**Constraints:**
* `1 <= bits.length <= 1000`
* `bits[i]` is either `0` or `1`. | 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 return 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\]
**Output:** true
**Explanation:** The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
**Example 2:**
**Input:** bits = \[1,1,1,0\]
**Output:** false
**Explanation:** The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
**Constraints:**
* `1 <= bits.length <= 1000`
* `bits[i]` is either `0` or `1`. | 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\]
**Output:** true
**Explanation:** The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
**Example 2:**
**Input:** bits = \[1,1,1,0\]
**Output:** false
**Explanation:** The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
**Constraints:**
* `1 <= bits.length <= 1000`
* `bits[i]` is either `0` or `1`. | 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 \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\]
**Output:** true
**Explanation:** The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
**Example 2:**
**Input:** bits = \[1,1,1,0\]
**Output:** false
**Explanation:** The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
**Constraints:**
* `1 <= bits.length <= 1000`
* `bits[i]` is either `0` or `1`. | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def isOneBitCharacter(self, bits: List[int]) -> bool:\n a=len(bits)\n if a==1:\n return 1\n if a==2:\n if bits==[1,1] or bits==[1,0]:\n return 0\n else:\n return 1\n while len(bits)!=2 or len(bits)!=1:\n print(bits)\n if bits[0]==1:\n g=bits[2:]\n else:\n g=bits[1:]\n bits=g\n if len(bits)==1 or len(bits)==2:\n break\n if bits==[1,1] or bits==[1,0]:\n return 0\n return 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\]
**Output:** true
**Explanation:** The only way to decode it is two-bit character and one-bit character.
So the last character is one-bit character.
**Example 2:**
**Input:** bits = \[1,1,1,0\]
**Output:** false
**Explanation:** The only way to decode it is two-bit character and two-bit character.
So the last character is not one-bit character.
**Constraints:**
* `1 <= bits.length <= 1000`
* `bits[i]` is either `0` or `1`. | 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 current_size) {\n unordered_set<string_view> substrings;\n for (size_t i = 0; i <= s.size() - current_size; ++i) {\n substrings.emplace(s.data() + i, current_size);\n }\n for (size_t i = 0; i <= t.size() - current_size; ++i) {\n string_view view(t.data() + i, current_size);\n if (substrings.count(view)) {\n return true;\n }\n }\n return false;\n };\n size_t left = 0;\n size_t right = min(s.size(), t.size()) + 1;\n while (right - left > 1) {\n size_t mid = (left + right) / 2;\n if (isValid(mid)) {\n left = mid;\n } else {\n right = mid;\n }\n }\n return left;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n nums1, nums2 = "".join(map(chr, nums1)), "".join(map(chr, nums2))\n\n def has_subarray(n):\n seen = {nums1[i:i + n] for i in range(len(nums1) - n + 1)}\n return any(nums2[i:i + n] in seen for i in range(len(nums2) - n + 1))\n\n lo, hi = 0, min(len(nums1), len(nums2))\n while lo < hi:\n mid = (lo + hi + 1) // 2\n if has_subarray(mid):\n lo = mid\n else:\n hi = mid - 1\n return lo\n```\n\n```Java []\nclass Solution {\n public int findLength(int[] nums1, int[] nums2) {\n int len1 = nums1.length;\n int len2 = nums2.length;\n int len_12 = Math.max(len1,len2);\n\n long[] p = new long[len_12];\n long[] h1 = new long[len1];\n long[] h2 = new long[len2];\n int P = 1313131;\n p[0] = 1;\n h1[0] = nums1[0];\n h2[0] = nums2[0];\n\n for(int i=1;i<len_12;i++) p[i] = p[i-1] * P;\n for(int i=1;i<len1;i++) h1[i] = h1[i-1]*P+nums1[i];\n for(int i=1;i<len2;i++) h2[i] = h2[i-1]*P+nums2[i];\n \n int lo = 1;\n int hi = Math.min(len1,len2);\n while(lo<=hi){\n int mid = lo+(hi-lo)/2;\n if(check(nums1,nums2,mid,p,h1,h2)) lo = mid + 1;\n else hi = mid - 1;\n }\n return hi;\n }\n public boolean check(int[] nums1, int[] nums2, int l, long[] p, long[] h1, long[] h2){\n Set<Long> set = new HashSet<>();\n int len1 = nums1.length;\n int len2 = nums2.length;\n set.add(h1[l-1]);\n for(int i=1;i<=len1-l;i++){\n long tmp = h1[i+l-1]-h1[i-1]*p[l];\n set.add(tmp);\n }\n if(set.contains(h2[l-1])) return true;\n for(int i=1;i<=len2-l;i++){\n long tmp = h2[i+l-1]-h2[i-1]*p[l];\n if(set.contains(tmp)) return true;\n }\n return false;\n }\n}\n```\n | 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,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100` | 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 # for the common seq in nums1 and nums2. \n\n def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n \n n1, n2 = len(nums1), len(nums2) \n memo = [[0]*(n2+1) for _ in range(n1+1)] # <-- 1)\n \n for idx1 in range(n1)[::-1]:\n for idx2 in range(n2)[::-1]:\n \n if nums1[idx1] == nums2[idx2]:\n memo[idx1][idx2] = 1 + memo[idx1+1][idx2+1] # <-- 2)\n \n return max(chain(*memo)) # <-- 3) | 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,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100` | 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 Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n---\n\n**C++**\n\n```cpp\nclass Solution {\npublic:\n // DP Approach - Similar to 1143. Longest Common Subsequence\n int findLength(vector<int>& nums1, vector<int>& nums2) {\n int n = nums1.size(), m = nums2.size(), ans = 0;\n // dp[i][j] means the length of repeated subarray of nums1[:i] and nums2[:j]\n // initially the first row (i = 0) and the first col (j = 0) would be zero\n // dp[i][0] = 0 for all i and dp[0][j] = 0 for all j\n // if you use int dp[n + 1][m + 1], then you need to take care of this part\n vector<vector<int>> dp(n + 1, vector<int>(m + 1));\n\t\tfor (int i = 1; i <= n; i++) {\n\t\t\tfor (int j = 1; j <= m; j++) {\n // if both character is same\n\t\t\t\tif (nums1[i - 1] == nums2[j - 1]) {\n // then we add 1 to the previous state, which is dp[i - 1][j - 1]\n // in other word, we extend the repeated subarray by 1\n // e.g. a = [1], b = [1], length of repeated array is 1\n // a = [1,2], b = [1,2], length of repeated array is the previous result + 1 = 2\n\t\t\t\t\tdp[i][j] = dp[i - 1][j - 1] + 1;\n // record the max ans here\n\t\t\t\t\tans = max(ans, dp[i][j]);\n\t\t\t\t} else {\n // if you are looking for longest common sequence,\n // then you put dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); here\n // however, this problem is looking for subarray,\n // since both character is not equal, which means we need to break it here\n // hence, set dp[i][j] to 0\n // since we use vector<vector<int>> dp instead of int dp[n + 1][m + 1]\n // this part can be skipped as it is already 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn ans;\n }\n};\n```\n\n```cpp\nclass Solution {\npublic:\n // DP Approach - Space Optimized\n int findLength(vector<int>& nums1, vector<int>& nums2) {\n int n = nums1.size(), m = nums2.size(), ans = 0;\n // swap it to ensure n > m\n if (n < m) {\n // or you can call findLength(nums2, nums1); \n swap(nums1, nums2);\n swap(n, m);\n }\n // dp records current dp state\n // dp2 records the previous dp state\n vector<int> dp(n + 1), dp2(n + 1);\n for (int i = 1; i <= n; i++) {\n for (int j = 1; j <= m; j++) {\n if (nums1[i - 1] == nums2[j - 1]) {\n // extend from the previous dp state\n dp[j] = dp2[j - 1] + 1; \n } else {\n // reset to 0\n dp[j] = 0;\n }\n // record the max length\n ans = max(ans, dp[j]);\n }\n // the current state now becomes the previous state for next round\n dp2 = dp;\n }\n return ans;\n }\n};\n```\n\n```cpp\n// Rolling Hash Approach\nclass Solution {\npublic:\n // the idea is to use binary search to find the length `m`\n // then we check if there is any nums1[i : i + m] == nums2[i : i + m]\n // for c++, it may get TLE. so we can use rolling hash to speed up\n // we can see `nums1[i : j]` as a hash, then we insert all the possible hashes to a set\n // then we do the same on `nums2` to see if the hash exists in the set\n int findLength(vector<int>& nums1, vector<int>& nums2) {\n int N = nums1.size(), M = nums2.size();\n // build hashes for nums1\n PolyHash H1 = PolyHash(nums1);\n // build hashes for nums2\n PolyHash H2 = PolyHash(nums2);\n \n int l = 0, r = min(N, M);\n // binary search\n while (l < r) {\n // guess that the length is m\n int m = l + (r - l + 1) / 2, ok = 0;\n // use set to store all the possible hashes\n set<int> s;\n // for each subarray, we get the hash and store in set\n for (int i = 0; i < N - m + 1; i++) {\n s.insert(H1.get_hash(i, i + m - 1));\n }\n // see if we can get the same hash\n for (int i = 0; i < M - m + 1; i++) {\n if (s.find(H2.get_hash(i, i + m - 1)) != s.end()) {\n ok = 1;\n break;\n }\n }\n // include m\n if (ok) l = m;\n // exclude m\n else r = m - 1;\n }\n return l;\n }\n};\n```\n\n**Python**\n\n```py\nclass Solution:\n # DP Approach - Similar to 1143. Longest Common Subsequence\n def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n n, m = len(nums1), len(nums2)\n # dp[i][j] means the length of repeated subarray of nums1[:i] and nums2[:j]\n dp = [[0] * (m + 1) for _ in range(n + 1)]\n ans = 0\n for i in range(1, n + 1):\n for j in range(1, m + 1):\n # if both character is same\n if nums1[i - 1] == nums2[j - 1]:\n # then we add 1 to the previous state, which is dp[i - 1][j - 1]\n # in other word, we extend the repeated subarray by 1\n # e.g. a = [1], b = [1], length of repeated array is 1\n # a = [1,2], b = [1,2], length of repeated array is the previous result + 1 = 2\n dp[i][j] = dp[i - 1][j - 1] + 1\n # record the max ans here\n ans = max(ans, dp[i][j])\n # else:\n # if you are looking for longest common sequence,\n # then you put dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); here\n # however, this problem is looking for subarray,\n # since both character is not equal, which means we need to break it here\n # hence, set dp[i][j] to 0\n return ans\n```\n\n```py\nclass Solution:\n # Binary Search Approach\n def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n N, M = len(nums1), len(nums2)\n \n def ok(k):\n # the idea is to use binary search to find the length `k`\n # then we check if there is any nums1[i : i + k] == nums2[i : i + k]\n s = set(tuple(nums1[i : i + k]) for i in range(N - k + 1))\n return any(tuple(nums2[i : i + k]) in s for i in range(M - k + 1))\n \n # init possible boundary\n l, r = 0, min(N, M)\n while l < r:\n # get the middle one\n # for even number of elements, take the upper one\n m = (l + r + 1) // 2\n if ok(m): \n # include m\n l = m\n else:\n # exclude m\n r = m - 1\n return l\n``` | 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,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100` | 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))\n else:\n strmax = strmax[1:]\n return ans\n``` | 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,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100` | 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 + 1][j + 1] = dp[i][j] + 1\n\n\t\t\treturn max(map(max, dp))\n | 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,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100` | 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\n return cnt\n\n arr.sort()\n l, r, n = 0, arr[-1] - arr[0], len(arr)\n \n while l < r:\n mid = (l + r) >> 1 \n if count(mid) < k:\n l = mid + 1\n else:\n r = mid\n return l\n\n``` | 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 = \[1,3,1\], k = 1
**Output:** 0
**Explanation:** Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
**Example 2:**
**Input:** nums = \[1,1,1\], k = 2
**Output:** 0
**Example 3:**
**Input:** nums = \[1,6,1\], k = 3
**Output:** 5
**Constraints:**
* `n == nums.length`
* `2 <= n <= 104`
* `0 <= nums[i] <= 106`
* `1 <= k <= n * (n - 1) / 2` | 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 smallest distance. For each candidate distance, count the number of pairs with distances less than or equal to the candidate distance, and adjust the binary search range accordingly.\n\nHere\'s how you can implement this approach:\n\n1.After sorting the array, we perform a binary search to find the kth smallest distance. The binary search is conducted on the range of possible distances between elements in the array.\n\nWe initialize left to 0 (minimum possible distance) and right to the maximum possible difference between any two elements in the sorted array (nums[-1] - nums[0]).\nIn each iteration of the binary search, we calculate the midpoint mid between left and right.\nWe then use the countPairs function to count the number of pairs with distances less than or equal to mid. This function performs a linear scan through the array and counts such pairs.\nIf the count is less than k, we know that the kth smallest distance must be larger than mid, so we update left to mid + 1.\nIf the count is greater than or equal to k, we update right to mid because we need to find a smaller distance.\nThe binary search continues until left is no longer less than right, at which point left will be equal to the kth smallest distance.\n\n2.Counting Pairs with Distances Less than or Equal to mid:\nThe countPairs function performs a linear scan through the sorted array to count the number of pairs with distances less than or equal to mid. This count is achieved by maintaining two pointers, left and right, which point to the start and end of the sliding window of elements.\n\nWe start with left at index 0 and iterate through the array with right increasing from 0 to the end of the array.\nWhile the difference between nums[right] and nums[left] is greater than mid, we increment left to shrink the window.\nFor each right, the number of valid pairs with distances less than or equal to mid is the difference between right and left. This is because the array is sorted, and as long as the difference condition is met, all elements between left and right are valid pairs.\nThe function returns the total count of such pairs.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n# **O**(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# **O**(n)\n# Code\n```\nclass Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n def countPairs(nums, mid):\n count = 0\n left = 0\n for right in range(len(nums)):\n while nums[right] - nums[left] > mid:\n left += 1\n count += right - left\n return count\n \n nums.sort()\n left, right = 0, nums[-1] - nums[0]\n\n while left < right:\n mid = (left + right) // 2\n count = countPairs(nums, mid)\n\n if count < k:\n left = mid + 1\n else:\n right = mid\n\n return left\n``` | 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 = \[1,3,1\], k = 1
**Output:** 0
**Explanation:** Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
**Example 2:**
**Input:** nums = \[1,1,1\], k = 2
**Output:** 0
**Example 3:**
**Input:** nums = \[1,6,1\], k = 3
**Output:** 5
**Constraints:**
* `n == nums.length`
* `2 <= n <= 104`
* `0 <= nums[i] <= 106`
* `1 <= k <= n * (n - 1) / 2` | 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: # distance no greater than k\n cnt += j - i\n j += 1\n\n return cnt >= k # return whether at least k such pairs exist\n\n nums.sort()\n n, left, right = len(nums), 0, nums[-1] - nums[0]\n\n while left < right: # bin search \n\n mid = (left + right) // 2\n if check(mid): right = mid\n else: left = mid + 1\n\n return left\n```\n[https://leetcode.com/problems/find-k-th-smallest-pair-distance/submissions/884570068/](http://)\n\nI could be wrong, but I think that time complexity is *O*(*NlogN*) and space complexity is *O*(1). | 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 = \[1,3,1\], k = 1
**Output:** 0
**Explanation:** Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
**Example 2:**
**Input:** nums = \[1,1,1\], k = 2
**Output:** 0
**Example 3:**
**Input:** nums = \[1,6,1\], k = 3
**Output:** 5
**Constraints:**
* `n == nums.length`
* `2 <= n <= 104`
* `0 <= nums[i] <= 106`
* `1 <= k <= n * (n - 1) / 2` | 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.sort()\n\t\t\tl, r = 0, nums[-1] - nums[0]\n\n\t\t\twhile l < r:\n\t\t\t\tmid = (l + r) // 2\n\t\t\t\tres = getPairs(mid)\n\n\t\t\t\tif res >= k:\n\t\t\t\t\tr = mid\n\t\t\t\telse:\n\t\t\t\t\tl = mid + 1\n\n\t\t\treturn l | 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 = \[1,3,1\], k = 1
**Output:** 0
**Explanation:** Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
**Example 2:**
**Input:** nums = \[1,1,1\], k = 2
**Output:** 0
**Example 3:**
**Input:** nums = \[1,6,1\], k = 3
**Output:** 5
**Constraints:**
* `n == nums.length`
* `2 <= n <= 104`
* `0 <= nums[i] <= 106`
* `1 <= k <= n * (n - 1) / 2` | 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 complexity of this solution is $$O(N^2logk)$$ and the space complexity is $$O(k)$$. The range of $$k$$ is $$[1, N^2]$$. When $$k$$ is small the solution is much better; however, the amortized TC is in fact the same as the brute-force solution, which is $$O(N^2logN^2)$$. \n\nLet\'s see if we can improve the $$N^2$$ part. We have sorting algorithm as a candidate, which is $$O(NlogN)$$. On top of sorting we can find the minimum distance $$d$$ so that at least $$k$$ pairs satisfy the condition that their distance is no greater than $$d$$. We can use binary search to search for the target $$d$$, whose complexity is $$O(logM)$$ where $$M$$ is the maximum distance in the input. We know that to find $$M$$ the TC is $$O(NlogN)$$; so the overall amortized TC of the binary search is $$O(log(NlogN))$$, also $$O(logN)$$. And then we can use sliding window to count the number of valid pair satisfying the target condition, whose complexity is $$O(N)$$. In summary, the TC of this solution is $$O(NlogN + NlogN)$$ (first part is the sorting, and the second part is the binary search + counting pairs), hence amortized as $$O(NlogN)$$.\n\n# Complexity\n- Time complexity: $$O(NlogN)$$ for the sorting, and the binary search + counting of the valid pairs.\n\n- Space complexity: $$O(1)$$ as no extra space is required.\n\n# Code\n```python\nclass Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n # brute-force, push all pairs into PQ and rank them by dist |nums[i]-nums[j]| O(N^2)\n # sorting + binary search O(NlogN): say the distance is d, and see if the number of pairs <=d is < k; if yes, it suggest that d is too small and we need to count more pairs; otherwise, d is too large.\n\n nums = sorted(nums) # O(NlogN)\n n = len(nums)\n\n # count the number of pairs with dist less than or equal to d\n # we can achieve TC of O(N) using sliding window\n def countValidPairs(d: int) -> int:\n l = 0\n r = 1\n cnt = 0\n while r < n:\n if nums[r] - nums[l] <= d:\n cnt += r - l\n r += 1\n else:\n l += 1\n \n return cnt\n\n # use binary search to see if some distance can at least has k pairs\n left = min([nums[i+1] - nums[i] for i in range(n-1)]) # minimum possible distance\n right = nums[n-1]-nums[0] # maximum possible distance\n\n while left < right: # O(logN)\n mid = left + (right-left) // 2\n if countValidPairs(mid) < k:\n left = mid + 1\n else:\n right = mid\n \n return left\n\n``` | 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 = \[1,3,1\], k = 1
**Output:** 0
**Explanation:** Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
**Example 2:**
**Input:** nums = \[1,1,1\], k = 2
**Output:** 0
**Example 3:**
**Input:** nums = \[1,6,1\], k = 3
**Output:** 5
**Constraints:**
* `n == nums.length`
* `2 <= n <= 104`
* `0 <= nums[i] <= 106`
* `1 <= k <= n * (n - 1) / 2` | 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 smallestDistancePair(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n \n int left=0, right=nums[nums.size()-1]-nums[0];\n while(left<right) {\n int mid=left+(right-left)/2;\n if(rank(nums, mid) < k)\n left=mid+1;\n else\n right=mid;\n }\n return left;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def smallestDistancePair(self, nums: List[int], k: int) -> int:\n def DistancePair_helper(tmp_val):\n "GX: is there k or more pairs with distance <= tmp_val"\n count = left = 0\n for right, val in enumerate(nums):\n while val - nums[left] > tmp_val:\n left += 1\n count += right - left\n return count >= k\n\n nums.sort()\n min_val = 0\n max_val = nums[-1] - nums[0]\n\n while min_val < max_val:\n mid_val = (min_val + max_val) // 2\n if DistancePair_helper(mid_val):\n max_val = mid_val\n else:\n min_val = mid_val + 1\n print(nums)\n return min_val\n```\n\n```Java []\nclass Solution {\n public int smallestDistancePair(int[] nums, int k) {\n Arrays.sort(nums);\n int n = nums.length;\n int right = nums[n - 1] - nums[0];\n int left = 0;\n while (left < right) {\n int mid = left + (right - left) / 2;\n int count = 0;\n int slow = 0;\n for (int fast = 0; fast < n; fast++) {\n while (nums[fast] - nums[slow] > mid) slow++;\n count += fast - slow;\n }\n if (count < k) {\n left = mid + 1;\n } else {\n right = mid;\n }\n }\n return left;\n }\n private int helper(int[] nums, int start, int value) {\n for (int i = start; i < nums.length; i++) {\n if (nums[i] > value) return i;\n }\n return nums.length;\n }\n}\n```\n | 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 = \[1,3,1\], k = 1
**Output:** 0
**Explanation:** Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
**Example 2:**
**Input:** nums = \[1,1,1\], k = 2
**Output:** 0
**Example 3:**
**Input:** nums = \[1,6,1\], k = 3
**Output:** 5
**Constraints:**
* `n == nums.length`
* `2 <= n <= 104`
* `0 <= nums[i] <= 106`
* `1 <= k <= n * (n - 1) / 2` | 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 if word[:i+1] not in map:\n flag = False\n break\n if flag == True:\n if(len(result) < len(word)):\n result = word\n return result\n \n```\n---\n#### *Please don\'t forget to upvote if you\'ve liked my solution.* \u2B06\uFE0F\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 empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
**Example 1:**
**Input:** words = \[ "w ", "wo ", "wor ", "worl ", "world "\]
**Output:** "world "
**Explanation:** The word "world " can be built one character at a time by "w ", "wo ", "wor ", and "worl ".
**Example 2:**
**Input:** words = \[ "a ", "banana ", "app ", "appl ", "ap ", "apply ", "apple "\]
**Output:** "apple "
**Explanation:** Both "apply " and "apple " can be built from other words in the dictionary. However, "apple " is lexicographically smaller than "apply ".
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 30`
* `words[i]` consists of lowercase English letters. | 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 for c in word:\n if c not in cur.children:\n cur.children[c] = TrieNode()\n cur = cur.children[c]\n cur.endOfWord = True\n cur.val = word # definging the end value as whole word\n \n def bfs(self): # as I am starting from the root itself, so bfs have only argument self for referring the root\n q = [self.root]\n res = \'\'\n while q:\n cur = q.pop(0)\n for child in cur.children.values(): # traversing all the nodes of cur not keys\n if child.endOfWord: # ONLY go to the node which is of length 1 and end of a word also\n q.append(child)\n if len(child.val) > len(res): # for greater length as for lexicografical I have already sorted words \n res = child.val\n return res\n \nclass Solution:\n def longestWord(self, words: List[str]) -> str:\n words.sort() # sort in lexicografical order\n trie = Trie() # making object of the Trie Class\n for word in words: # adding all words to trie structre\n trie.addWord(word)\n \n return trie.bfs() # calling the bfs function \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 empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
**Example 1:**
**Input:** words = \[ "w ", "wo ", "wor ", "worl ", "world "\]
**Output:** "world "
**Explanation:** The word "world " can be built one character at a time by "w ", "wo ", "wor ", and "worl ".
**Example 2:**
**Input:** words = \[ "a ", "banana ", "app ", "appl ", "ap ", "apply ", "apple "\]
**Output:** "apple "
**Explanation:** Both "apply " and "apple " can be built from other words in the dictionary. However, "apple " is lexicographically smaller than "apply ".
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 30`
* `words[i]` consists of lowercase English letters. | 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 first.\n\n```\n word_set, ans = set([\'\']), \'\'\n```\nword_set: a set containing an empty string. This will be used to keep track of words we\'ve processed and can build upon. The reason we start with an empty string is so that words of length 1 can be directly added, since their prefix (an empty string) is present.\nans: an empty string that will store our current longest word that meets the criteria.\n\n```\n for word in words:\n```\nWe iterate over the sorted list of words.\n\n```\n if word[:-1] in word_set:\n```\nFor each word, we check if its prefix (i.e., the word without its last character) is present in word_set. This is the condition to see if the word can be built character by character from the words we\'ve seen so far.\n\n```\n if len(word) > len(ans):\n ans = word\n```\nIf the current word is longer than our current answer ans, we update ans to be the current word.\n\n```\n word_set.add(word)\n```\n\nAfter checking the current word, we add it to word_set because it can be used as a prefix for future words.\n\n```\n return ans\n```\nAfter processing all words, we return the answer ans.\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def longestWord(self, words: List[str]) -> str:\n words.sort()\n\n word_set, ans = set([\'\']), \'\'\n\n for word in words:\n if word[:-1] in word_set:\n if len(word) > len(ans):\n ans = word\n word_set.add(word)\n \n return ans\n\n``` | 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 empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
**Example 1:**
**Input:** words = \[ "w ", "wo ", "wor ", "worl ", "world "\]
**Output:** "world "
**Explanation:** The word "world " can be built one character at a time by "w ", "wo ", "wor ", and "worl ".
**Example 2:**
**Input:** words = \[ "a ", "banana ", "app ", "appl ", "ap ", "apply ", "apple "\]
**Output:** "apple "
**Explanation:** Both "apply " and "apple " can be built from other words in the dictionary. However, "apple " is lexicographically smaller than "apply ".
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 30`
* `words[i]` consists of lowercase English letters. | 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 visited: # check previous word ie. word[:len(word)-1] visited or not\n visited.add(word) # add this word to the set\n if len(word) > len(res): # current word have greater lenght and lexicographically smaller\n res = word # update res\n \n return res\n \n \n \n# Time: O(n log(n)) # for sorting the words\n# Space: O(n) # for making the set visited\n```\n\nSolution using Trie+BFS: https://leetcode.com/problems/longest-word-in-dictionary/discuss/2075062/Trie+BFS-or-Python-Solution-with-Comments-Easy-to-Understand | 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 empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
**Example 1:**
**Input:** words = \[ "w ", "wo ", "wor ", "worl ", "world "\]
**Output:** "world "
**Explanation:** The word "world " can be built one character at a time by "w ", "wo ", "wor ", and "worl ".
**Example 2:**
**Input:** words = \[ "a ", "banana ", "app ", "appl ", "ap ", "apply ", "apple "\]
**Output:** "apple "
**Explanation:** Both "apply " and "apple " can be built from other words in the dictionary. However, "apple " is lexicographically smaller than "apply ".
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 30`
* `words[i]` consists of lowercase English letters. | 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 TrieNode* p = root_;\n for (const auto& c : str) {\n if (p->children[c - \'a\'] == nullptr) {\n p->children[c - \'a\'] = new TrieNode();\n }\n p = p->children[c - \'a\'];\n }\n p->is_end = true;\n }\n TrieNode* getRoot() {\n return root_;\n }\nprivate:\n TrieNode* root_;\n};\nclass Solution {\npublic:\n string longestWord(vector<string>& words) {\n auto trie = std::make_unique<Trie>();\n for (const auto& word : words) {\n trie->insert(word);\n }\n TrieNode* root = trie->getRoot();\n std::string curr_str;\n std::string res;\n dfs(root, curr_str, res);\n return res;\n }\n void dfs(TrieNode* curr_node, std::string& curr_str, std::string& res) {\n if (!curr_node) return;\n if (curr_str.length() > res.length()) res = curr_str;\n for (int i = 0; i < 26; i++) {\n if (curr_node->children[i] && curr_node->children[i]->is_end) {\n curr_str.push_back(static_cast<char>(\'a\' + i)); \n dfs(curr_node->children[i], curr_str, res);\n curr_str.pop_back();\n }\n }\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def longestWord(self, words: List[str]) -> str:\n words.sort(key=len)\n buildable = set()\n\n for w in words:\n pre = w[:-1]\n if not pre or pre in buildable:\n buildable.add(w)\n\n res = \'\'\n for w in buildable:\n if len(w) > len(res) or (len(w) == len(res) and w < res):\n res = w\n return res\n```\n\n```Java []\nclass Solution {\n String result = "";\n public String longestWord(String[] words) {\n TrieNode root = new TrieNode();\n for (String word: words) {\n buildTrie(word, root);\n }\n dfs(root);\n return result;\n }\n private void dfs(TrieNode node) {\n if (node == null) return;\n if (node.word != null) {\n result = node.word.length() > result.length() ? node.word : result;\n }\n for (TrieNode child: node.children) {\n if (child != null && child.word != null)\n dfs(child);\n } \n }\n private void buildTrie(String word, TrieNode node) {\n for (int i = 0; i < word.length(); i++) {\n char c = word.charAt(i);\n if (node.children[c - \'a\'] == null) {\n node.children[c - \'a\'] = new TrieNode();\n }\n node = node.children[c - \'a\'];\n }\n node.word = word;\n }\n class TrieNode {\n TrieNode[] children;\n String word;\n TrieNode() {\n children = new TrieNode[26];\n }\n }\n}\n```\n | 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 empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
**Example 1:**
**Input:** words = \[ "w ", "wo ", "wor ", "worl ", "world "\]
**Output:** "world "
**Explanation:** The word "world " can be built one character at a time by "w ", "wo ", "wor ", and "worl ".
**Example 2:**
**Input:** words = \[ "a ", "banana ", "app ", "appl ", "ap ", "apply ", "apple "\]
**Output:** "apple "
**Explanation:** Both "apply " and "apple " can be built from other words in the dictionary. However, "apple " is lexicographically smaller than "apply ".
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 30`
* `words[i]` consists of lowercase English letters. | 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 word in words:\n cur = root\n for letter in word:\n if letter not in cur.children:\n cur.children[letter] = TrieNode()\n cur = cur.children[letter]\n cur.end = True\n \n res = \'\'\n \n # iterate over all the words\n # in our words array\n for word in words:\n # if the length of the word\n # isn\'t > our res, there\'s no\n # point in exploring further\n # since we want the longest word\n if len(word) < len(res): continue\n \n # start a temp cur var\n # init at root to iterate\n # trie for every word\n cur = root\n \n # for every letter in the current\n # word, traverse the trie and see\n # that for every letter in this\n # word, there\'s a node in the trie\n # which has end = True (i.e. a word \n # on its own, if not just break out)\n for letter in word:\n cur = cur.children[letter]\n if not cur.end: break\n \n # proceed only if you didn\'t break\n # out of the previous loop (cur.end == True)\n # and then check if the cur word is longer\n # than the cur res, or if they are equal in length\n # use the lexicographically smaller one (word < res)\n if cur.end and (len(word) > len(res) or (len(word) == len(res) and word < res)):\n res = word \n \n return res\n``` | 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 empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
**Example 1:**
**Input:** words = \[ "w ", "wo ", "wor ", "worl ", "world "\]
**Output:** "world "
**Explanation:** The word "world " can be built one character at a time by "w ", "wo ", "wor ", and "worl ".
**Example 2:**
**Input:** words = \[ "a ", "banana ", "app ", "appl ", "ap ", "apply ", "apple "\]
**Output:** "apple "
**Explanation:** Both "apply " and "apple " can be built from other words in the dictionary. However, "apple " is lexicographically smaller than "apply ".
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 30`
* `words[i]` consists of lowercase English letters. | 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.value == len(word)) and longer than previous res.\n\n```\nclass TrieNode:\n def __init__(self, val):\n self.children = {}\n self.value = val\n self.endOfWord = False\n \nclass Solution:\n def longestWord(self, words: List[str]) -> str:\n root = TrieNode(0)\n maxLen = 0\n res = ""\n for word in sorted(words):\n cur = root\n count = 0\n for letter in word:\n if letter not in cur.children:\n cur.children[letter] = TrieNode(count)\n cur = cur.children[letter]\n if cur.endOfWord: count += 1\n cur.endOfWord = True\n cur.value += 1\n if cur.value == len(word) and cur.value > maxLen:\n maxLen = cur.value\n res = word\n return res\n``` | 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 empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
**Example 1:**
**Input:** words = \[ "w ", "wo ", "wor ", "worl ", "world "\]
**Output:** "world "
**Explanation:** The word "world " can be built one character at a time by "w ", "wo ", "wor ", and "worl ".
**Example 2:**
**Input:** words = \[ "a ", "banana ", "app ", "appl ", "ap ", "apply ", "apple "\]
**Output:** "apple "
**Explanation:** Both "apply " and "apple " can be built from other words in the dictionary. However, "apple " is lexicographically smaller than "apply ".
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 30`
* `words[i]` consists of lowercase English letters. | 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(res):\n res = word\n st.add(word)\n \n return res | 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 empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
**Example 1:**
**Input:** words = \[ "w ", "wo ", "wor ", "worl ", "world "\]
**Output:** "world "
**Explanation:** The word "world " can be built one character at a time by "w ", "wo ", "wor ", and "worl ".
**Example 2:**
**Input:** words = \[ "a ", "banana ", "app ", "appl ", "ap ", "apply ", "apple "\]
**Output:** "apple "
**Explanation:** Both "apply " and "apple " can be built from other words in the dictionary. However, "apple " is lexicographically smaller than "apply ".
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 30`
* `words[i]` consists of lowercase English letters. | 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 smallest lexicographical order. Instead of sorting we can also check upon a tie whether the new path is lexicographically smaller.\n```Python\nfrom collections import defaultdict\nclass TrieNode:\n def __init__(self):\n self.children = defaultdict(TrieNode)\n self.isWord = False\n \nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n self.ret = ""\n\n def insert(self, word):\n node = self.root\n for letter in word:\n node = node.children[letter]\n node.isWord = True\n\nclass Solution: \n def longestWord(self, words: List[str]) -> str:\n def dfs(node, path):\n if not node.isWord:\n return\n if len(path) > len(self.ret):\n self.ret = "".join(path)\n for letter in node.children:\n dfs(node.children[letter], path+[letter])\n \n words.sort()\n trie = Trie()\n trie.root.isWord = True\n for word in words:\n trie.insert(word)\n self.ret = ""\n dfs(trie.root, [])\n return self.ret\n``` | 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 empty string.
Note that the word should be built from left to right with each additional character being added to the end of a previous word.
**Example 1:**
**Input:** words = \[ "w ", "wo ", "wor ", "worl ", "world "\]
**Output:** "world "
**Explanation:** The word "world " can be built one character at a time by "w ", "wo ", "wor ", and "worl ".
**Example 2:**
**Input:** words = \[ "a ", "banana ", "app ", "appl ", "ap ", "apply ", "apple "\]
**Output:** "apple "
**Explanation:** Both "apply " and "apple " can be built from other words in the dictionary. However, "apple " is lexicographically smaller than "apply ".
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 30`
* `words[i]` consists of lowercase English letters. | 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 self.parents[x]\n \nclass Solution:\n # 196 ms, 82.09%. \n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n uf = UF(len(accounts))\n \n # Creat unions between indexes\n ownership = {}\n for i, (_, *emails) in enumerate(accounts):\n for email in emails:\n if email in ownership:\n uf.union(i, ownership[email])\n ownership[email] = i\n \n # Append emails to correct index\n ans = collections.defaultdict(list)\n for email, owner in ownership.items():\n ans[uf.find(owner)].append(email)\n \n return [[accounts[i][0]] + sorted(emails) for i, emails in ans.items()]\n```\nI hope you learn something new. \nIf you think your solution is cleaner, I would love to learn how you do it. Please post it below. | 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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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 findUPar(int node) {\n if (node == parent[node])\n return node;\n return parent[node] = findUPar(parent[node]);\n }\n void unionByRank(int u, int v) {\n int ulp_u = findUPar(u);\n int ulp_v = findUPar(v);\n if (ulp_u == ulp_v) return;\n if (rank[ulp_u] < rank[ulp_v]) {\n parent[ulp_u] = ulp_v;\n }\n else if (rank[ulp_v] < rank[ulp_u]) {\n parent[ulp_v] = ulp_u;\n }\n else {\n parent[ulp_v] = ulp_u;\n rank[ulp_u]++;\n }\n }\n void unionBySize(int u, int v) {\n int ulp_u = findUPar(u);\n int ulp_v = findUPar(v);\n if (ulp_u == ulp_v) return;\n if (size[ulp_u] < size[ulp_v]) {\n parent[ulp_u] = ulp_v;\n size[ulp_v] += size[ulp_u];\n }\n else {\n parent[ulp_v] = ulp_u;\n size[ulp_u] += size[ulp_v];\n }\n }\n};\nclass Solution {\npublic:\n vector<vector<string>> accountsMerge(vector<vector<string>> &details) {\n int n = details.size();\n DisjointSet ds(n);\n unordered_map<string, int> mapMailNode;\n for (int i = 0; i < n; i++) {\n for (int j = 1; j < details[i].size(); j++) {\n string mail = details[i][j];\n if (mapMailNode.find(mail) == mapMailNode.end()) {\n mapMailNode[mail] = i;\n }else {\n ds.unionBySize(i, mapMailNode[mail]);\n }\n }\n }\n vector<string> mergedMail[n];\n for (auto it : mapMailNode) {\n string mail = it.first;\n int node = ds.findUPar(it.second);\n mergedMail[node].push_back(mail);\n }\n vector<vector<string>> ans;\n for (int i = 0; i < n; i++) {\n if (mergedMail[i].size() == 0) continue;\n sort(mergedMail[i].begin(), mergedMail[i].end());\n \n vector<string> temp;\n temp.push_back(details[i][0]);\n for (auto it : mergedMail[i]) temp.push_back(it);\n ans.push_back(temp);\n }\n return ans;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n n = len(accounts)\n\n par = [i for i in range(n)]\n rank = [1] * (n)\n\n def find(n):\n p = par[n]\n\n while p != par[p]:\n par[p] = par[par[p]]\n p = par[p]\n return p\n\n def union(n1,n2):\n p1, p2 = find(n1),find(n2)\n\n if p1 == p2:\n return False\n\n if rank[p1] > rank[p2]:\n par[p2] = p1\n rank[p1] += rank[p2]\n else:\n par[p1] = p2\n rank[p2] += rank[p1]\n return True\n\n emailtoAcc = {} #email -> index of acc\n for i,a in enumerate(accounts):\n for e in a[1:]:\n if e in emailtoAcc:\n union(i, emailtoAcc[e])\n else:\n emailtoAcc[e] = i\n\n emailGroup = defaultdict(list) #index of acc -> list of emails\n for e,i in emailtoAcc.items():\n leader = find(i)\n emailGroup[leader].append(e)\n\n res = []\n for i, email in emailGroup.items():\n name = accounts[i][0]\n res.append([name] + sorted(emailGroup[i]))\n return res\n```\n\n```Java []\nclass Solution {\n static class P {\n Map<String, Integer> emails = new HashMap<>();\n List<List<String>> groups = new ArrayList<>();\n\n void process(List<String> list) {\n Integer key = null;\n for (int i = 1; i < list.size(); i++) {\n String email = list.get(i);\n Integer existing = emails.get(email);\n if (existing != null) {\n if (key == null) {\n key = existing;\n } else if (!key.equals(existing)){\n key = merge(existing, key);\n }\n }\n }\n List<String> group;\n if (key == null) {\n key = groups.size();\n groups.add(group = new ArrayList<>());\n } else {\n group = groups.get(key);\n }\n for (int i = 1; i < list.size(); i++) {\n String email = list.get(i);\n if (emails.put(email, key) == null) {\n group.add(email);\n }\n }\n }\n Integer merge(Integer key1, Integer key2) {\n var gr1 = groups.get(key1);\n var gr2 = groups.get(key2);\n if (gr1.size() > gr2.size()) {\n return merge(key2, key1);\n }\n for (String email : gr1) {\n emails.put(email, key2);\n }\n gr2.addAll(gr1);\n groups.set(key1, null);\n return key2;\n }\n }\n public List<List<String>> accountsMerge(List<List<String>> accounts) {\n Map<String, P> map = new HashMap<>();\n for (List<String> list : accounts) {\n String name = list.get(0);\n map.computeIfAbsent(name, k -> new P()).process(list);\n }\n List<List<String>> result = new ArrayList<>();\n for (Map.Entry<String, P> entry : map.entrySet()) {\n for (var group : entry.getValue().groups) {\n if (group != null) {\n Collections.sort(group);\n var r = new ArrayList<String>(group.size() + 1);\n r.add(entry.getKey());\n r.addAll(group);\n result.add(r);\n }\n }\n }\n return result;\n }\n}\n```\n | 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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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 unionBySize(u,v):\n pu,pv=findParent(u),findParent(v)\n if pu==pv:\n return \n elif size[pu]<size[pv]:\n parent[pu]=pv\n size[pv]+=size[pu]\n else:\n parent[pv]=pu\n size[pu]+=size[pv]\n \n n=len(accounts)\n parent=[i for i in range(n)]\n size=[1]*n\n d={}\n for i in range(n):\n for j in range(1,len(accounts[i])):\n s=accounts[i][j]\n if s not in d:\n d[s]=i\n else:\n unionBySize(i,d[s])\n temp=defaultdict(list)\n for k,v in d.items():\n pv=findParent(v)\n temp[pv].append(k)\n res=[]\n for i in temp:\n temp2=sorted(temp[i])\n ans=[accounts[i][0]]\n ans.extend(temp2)\n res.append(ans)\n return res\n```\n\n**An upvote will be encouraging** | 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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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-Find (custom class)\n- dict & defaultdict (collections)\n- counter (itertools)\n- insort (bisect)\n\n\n# Code\n```\n# from bisect import insort\n# from collections import defaultdict\n# from itertools import count\n\nclass UnionFind:\n def __init__(self, n) -> None:\n self.parent = [i for i in range(n)] # parent of each group\n self.grpCnt = n # total groups \n \n def find(self, x):\n while x != self.parent[x]:\n x = self.parent[x]\n return x\n\n def union(self, x, y):\n pre_x = self.find(x)\n pre_y = self.find(y)\n if pre_x != pre_y: # if not merged already \n # Surely the first [x] would be the lead of group based on first come first serve\n self.parent[pre_y] = pre_x \n self.grpCnt -= 1\n\nclass Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n emailToAcc = {} # email -> account_idx\n uf = UnionFind(len(accounts))\n\n for idx, account in enumerate(accounts):\n for email in account[1:]:\n if email in emailToAcc:\n # Already account registered in some group\n rootGrpId = emailToAcc[email]\n uf.union(rootGrpId, idx) # club current account to registered group\n else:\n # Account not registered yet\n emailToAcc[email] = idx\n \n # Now the Accounts info is clubbed\n\n # counter mechanism to find the pos of unique grp in result list\n cntr = count()\n grpToPos = defaultdict(cntr.__next__)\n merged = [[] for _ in range(uf.grpCnt)]\n\n # Combine all emails to specific group\n for email, accId in emailToAcc.items():\n grpId = uf.find(accId) # this [accId] belongs to which grp ?\n pos = grpToPos[grpId]\n insort(merged[pos], email) # Insertion Sort to maintain order\n\n # Add name at the start of each merged result\n for accId, mergePos in grpToPos.items():\n name = accounts[accId][0]\n merged[mergePos].insert(0, name)\n\n return merged\n``` | 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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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 person. Two accounts belong to the same person if there is some common email to both accounts. A natural approach to solve this problem is to use a Union-Find data structure to keep track of which accounts belong to the same person.\n\n# Approach\n1. First, we define a `UnionFind` class that implements the Union-Find data structure. This class has three methods: `__init__`, `find`, and `union`. The `__init__` method initializes the parent and rank arrays. The `find` method finds the root of a given element using path compression. The `union` method merges two sets using union by rank.\n2. In the `accountsMerge` method, we create an instance of the `UnionFind` class with size equal to the number of accounts.\n3. We also create a dictionary `emailToAcc` that maps each email to the index of an account that contains that email.\n4. We iterate over each account and its emails. For each email, if it is already in the `emailToAcc` dictionary, we union the current account with the account that contains that email. Otherwise, we add the email and its corresponding account index to the `emailToAcc` dictionary.\n5. Next, we create a dictionary `emailGroup` that maps each account index to a list of emails that belong to that account.\n6. We iterate over each email and its corresponding account index in the `emailToAcc` dictionary. We find the leader of that account index using the `find` method of the `UnionFind` instance and append the email to the list of emails in the `emailGroup` dictionary corresponding to that leader.\n7. Finally, we iterate over each account index and its corresponding list of emails in the `emailGroup` dictionary. We get the name of that account from the input accounts list and append a new list containing the name and sorted emails to the result.\n\n# Complexity\n- Time complexity: $$O(A \\log A)$$ where $$A = \\sum_{i=1}^n |accounts[i]|$$ is the total number of emails.\n- Space complexity: $$O(A)$$ where $$A = \\sum_{i=1}^n |accounts[i]|$$ is the total number of emails.\n\n# Code\n```\nclass UnionFind:\n def __init__(self, n):\n self.par = [i for i in range(n)] # initialize parent array\n self.rank = [1] * n # initialize rank array\n \n def find(self, x):\n # find the root of x using path compression\n while x != self.par[x]:\n self.par[x] = self.par[self.par[x]]\n x = self.par[x]\n return x\n \n def union(self, x1, x2):\n # merge two sets using union by rank\n p1, p2 = self.find(x1), self.find(x2)\n if p1 == p2:\n return False\n if self.rank[p1] > self.rank[p2]:\n self.par[p2] = p1\n self.rank[p1] += self.rank[p2]\n else:\n self.par[p1] = p2\n self.rank[p2] += self.rank[p1]\n return True\n\nclass Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n uf = UnionFind(len(accounts)) # create UnionFind instance\n emailToAcc = {} # email -> index of acc\n\n for i, a in enumerate(accounts):\n for e in a[1:]:\n if e in emailToAcc:\n uf.union(i, emailToAcc[e]) # union accounts with common email\n else:\n emailToAcc[e] = i\n\n emailGroup = defaultdict(list) # index of acc -> list of emails\n for e, i in emailToAcc.items():\n leader = uf.find(i) # find leader of account index\n emailGroup[leader].append(e) # append email to leader\'s list of emails\n\n res = []\n for i, emails in emailGroup.items():\n name = accounts[i][0] # get account name\n res.append([name] + sorted(emailGroup[i])) # append name and sorted emails to result\n return res\n``` | 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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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 for account in accounts:\n name = account[0]\n key = account[1]\n for i in range(1, len(account)):\n self.accountConnections[key].add(account[i])\n self.accountConnections[account[i]].add(key)\n self.emailToName[account[i]] = name\n \n def walkAccountNode(self, accountNode):\n if accountNode in self.seen:\n return []\n \n self.seen.add(accountNode)\n connections = self.accountConnections[accountNode]\n result = [accountNode]\n \n for connection in connections:\n result += self.walkAccountNode(connection)\n \n return result\n \n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n self.buildConnections(accounts)\n mergedAccounts = []\n \n for account in self.accountConnections:\n localMerge = self.walkAccountNode(account)\n name = self.emailToName[account]\n if localMerge:\n localMerge.sort()\n mergedAccounts.append([name] + localMerge)\n \n return mergedAccounts\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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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 the email_to_name dictionary. Then, call the union method of the UnionFind instance to merge the first email with the current email.\n\n5. Create a dictionary components to store the components (sets of emails belonging to the same account).\n\n6. For each email in the email_to_name dictionary, find its root using the find method of the UnionFind instance and add it to the corresponding component in the components dictionary.\n\n7. Create an empty list result to store the final result.\n\n8. For each root in the components dictionary, get the name associated with it from the email_to_name dictionary, sort the list of emails associated with it in ascending order, and append a new list containing the name and sorted emails to the result list.\n\n\n\n# Complexity\n- Time complexity:\n$$O(NKlog(NK))$$ \n\n- Space complexity:\n$$O(NK)$$\n\nHere $N$ is the number of accounts and $K$ is the maximum length of an account.\n\nUnion by Rank and Find with path compression have a constant ammortized time complexity.\n\n# Code\n```\nclass UnionFind:\n def __init__(self):\n self.root = {}\n self.rank = {}\n\n def insert(self, element):\n # If the element is not already in the root dictionary, add it and set its rank to 1\n if element not in self.root:\n self.root[element] = element\n self.rank[element] = 1\n\n def find(self, element):\n # Insert the element if it\'s not already in the root dictionary\n self.insert(element)\n # If the element is its own root, return it\n if self.root[element] == element:\n return element\n # Otherwise, recursively find the root of the element and update its root in the dictionary\n self.root[element] = self.find(self.root[element])\n return self.root[element]\n\n def union(self, x, y):\n # Find the roots of x and y\n x_root = self.find(x)\n y_root = self.find(y)\n # If the roots are different, merge them\n if x_root != y_root:\n # Merge the root with smaller rank into the root with larger rank\n if self.rank[x_root] > self.rank[y_root]:\n self.root[y_root] = x_root\n elif self.rank[y_root] > self.rank[x_root]:\n self.root[x_root] = y_root\n else:\n # If the ranks are equal, merge y_root into x_root and increment the rank of x_root\n self.root[y_root] = x_root\n self.rank[x_root] += 1\n\nclass Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n email_to_name = {}\n uf = UnionFind()\n for account in accounts:\n name, *emails = account\n for email in emails:\n email_to_name[email] = name\n uf.union(emails[0], email)\n \n # Create a dictionary to store the components (sets of emails belonging to the same account)\n components = {}\n for email in email_to_name:\n root = uf.find(email)\n components[root] = components.get(root, []) + [email]\n \n result = []\n for root in components:\n name = email_to_name[root]\n emails = sorted(components[root])\n result.append([name] + emails)\n \n return result\n\n``` | 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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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. -->\nThe basic idea of disjoint set is simple and straightforward, using array p to reprent all the sets, to be specfic, i means the index of the set, p[i] means set i\'s parent set.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n def parent(i):\n root = i\n while root != p[root]:\n root = p[root]\n while root != p[i]:\n temp = p[i]\n p[i] = root\n i = temp\n return root\n\n def connect(i, j):\n pi, pj = parent(i), parent(j)\n p[pi] = pj\n\n p, email2Id, id2Email = [i for i in range(len(accounts))], {}, collections.defaultdict(set)\n for id, account in enumerate(accounts):\n for email in account[1:]:\n if email not in email2Id: email2Id[email] = id\n else: connect(email2Id[email], id)\n for id, account in enumerate(accounts):\n pi = parent(id)\n for email in account[1:]:\n id2Email[pi].add(email)\n return [[accounts[id][0]] + sorted(emails) for id, emails in id2Email.items()]\n\n\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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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\tif(par[u] != u):\n\t\t\tpar[u] = find(par[u])\n\t\treturn par[u]\n\trank, par, d = defaultdict(int), dict(), defaultdict(list)\n\tdef solve(l):\n\t\tfor listt in l:\n\t\t\tfor i in listt:\n\t\t\t\tif(i not in par): par[i] = i\n\t\t\t\tunion(listt[0], i)\n\t\tfor i in par:\n\t\t\tfind(i)\n\t\tdd = defaultdict(list)\n\t\tfor i in par:\n\t\t\tdd[par[i]].append(i)\n\t\treturn [dd[i] for i in dd]\n\tfor l in accounts:\n\t\td[l[0]].append(l[1:])\n\tans = []\n\tfor name in d:\n\t\tfor l in solve(d[name]):\n\t\t\tans.append([name] + sorted(l))\n\t\tpar.clear()\n\treturn ans\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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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 graph = collections.defaultdict(set)\n for account in accounts:\n for email in account[1:]:\n graph[account[1]].add(email)\n graph[email].add(account[1])\n #print(graph.items())\n \n visit = set()\n ans = []\n for account in accounts:\n name = account[0]\n for email in account[1:]:\n if email not in visit:\n self.res = []\n self.dfs(graph, email, visit)\n ans.append([name]+sorted(self.res))\n return ans | 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 some common email to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails **in sorted order**. The accounts themselves can be returned in **any order**.
**Example 1:**
**Input:** accounts = \[\[ "John ", "[email protected] ", "john\[email protected] "\],\[ "John ", "[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Output:** \[\[ "John ", "[email protected] ", "john\[email protected] ", "[email protected] "\],\[ "Mary ", "[email protected] "\],\[ "John ", "[email protected] "\]\]
**Explanation:**
The first and second John's are the same person as they have the common email "[email protected] ".
The third John and Mary are different people as none of their email addresses are used by other accounts.
We could return these lists in any order, for example the answer \[\['Mary', '[email protected]'\], \['John', '[email protected]'\],
\['John', '[email protected]', 'john\[email protected]', '[email protected]'\]\] would still be accepted.
**Example 2:**
**Input:** accounts = \[\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Output:** \[\[ "Ethan ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Gabe ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Hanzo ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Kevin ", "[email protected] ", "[email protected] ", "[email protected] "\],\[ "Fern ", "[email protected] ", "[email protected] ", "[email protected] "\]\]
**Constraints:**
* `1 <= accounts.length <= 1000`
* `2 <= accounts[i].length <= 10`
* `1 <= accounts[i][j].length <= 30`
* `accounts[i][0]` consists of English letters.
* `accounts[i][j] (for j > 0)` is a valid email. | 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] == \'/\') {\n if (!isComment) {\n if (i == (s.size() - 1)) {\n curr.push_back(s[i]);\n break;\n }\n if (s[i + 1] == \'/\') break;\n if (s[i + 1] == \'*\') {\n isComment = true;\n i++;\n } else curr.push_back(s[i]);\n } \n } else if (s[i] == \'*\') {\n if (!isComment) {\n curr.push_back(s[i]);\n } else if (i != (s.size() - 1) && s[i + 1] == \'/\') {\n isComment = false;\n i++;\n }\n } else if (!isComment) {\n curr.push_back(s[i]);\n }\n }\n if (!curr.empty()) {\n if (needJoin) {\n res.back() += curr;\n needJoin = false;\n } else {\n res.emplace_back(curr);\n }\n if (isComment) needJoin = true;\n } else if (needJoin && !isComment) {\n needJoin = false; \n }\n }\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution(object):\n def removeComments(self, source):\n res = []\n multi = False\n line = \'\'\n for s in source:\n i = 0\n while i < len(s):\n if not multi:\n if s[i] == \'/\' and i < len(s) - 1 and s[i + 1] == \'/\':\n break\n elif s[i] == \'/\' and i < len(s) - 1 and s[i + 1] == \'*\':\n multi = True\n i += 1\n else:\n line += s[i]\n else:\n if s[i] == \'*\' and i < len(s) - 1 and s[i + 1] == \'/\':\n multi = False\n i += 1\n i += 1\n if not multi and line:\n res.append(line)\n line = \'\'\n return res\n```\n\n```Java []\nclass Solution {\n private static final char slash = \'/\',\n asterisk = \'*\'; \n public List<String> removeComments(String[] source) {\n List<String> uncommentedSource = new ArrayList<>();\n StringBuilder uncommentedLine = new StringBuilder();\n boolean isBlockCodeComment = false;\n for (String commentedLine : source) {\n char[] line = commentedLine.toCharArray();\n int length = line.length;\n for (int index = 0; index < length; ++index)\n if (!isBlockCodeComment && line[index] == slash && index + 1 < length && line[index + 1] == asterisk) {\n isBlockCodeComment = true;\n index++;\n }\n else if (isBlockCodeComment && line[index] == asterisk && index + 1 < length && line[index + 1] == slash) {\n isBlockCodeComment = false;\n index++;\n }\n else if (!isBlockCodeComment && line[index] == slash && index + 1 < length && line[index + 1] == slash) \n break;\n else if (!isBlockCodeComment)\n uncommentedLine.append(line[index]);\n \n if (!isBlockCodeComment && uncommentedLine.length() != 0) {\n uncommentedSource.add(uncommentedLine.toString());\n uncommentedLine.setLength(0); \n } \n }\n return uncommentedSource;\n }\n}\n```\n | 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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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 if inComment:\n if c[i:i + 2] == \'*/\' and i + 1 < n:\n i += 2\n inComment = False\n continue\n i += 1\n # not in Comment, we find /* // and common character\n else:\n if c[i:i + 2] == \'/*\' and i + 1 < n:\n i += 2\n inComment = True\n continue\n if c[i:i + 2] == \'//\' and i + 1 < n:\n break\n new_str += c[i]\n i += 1\n if new_str and not inComment:\n ans.append(new_str)\n \n\n return ans\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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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_block_closed, regex_block_not_closed]) # order matters\n s = re.sub(regex, \'\', s)\n return list(filter(None, s.split(\'\\n\')))\n``` | 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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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 i += 2\n while i < len(all_string) and all_string[i] != "\\n":\n i += 1\n\n elif two == "/*":\n\n i += 2\n while all_string[i:i+2] != "*/":\n i += 1\n i += 2\n\n else:\n result_string += all_string[i]\n i += 1\n\n \n ans = []\n\n for line in result_string.split("\\n"):\n if line != "":\n ans.append(line)\n\n\n return ans\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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
✔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 and eliminate both block and line comments, leveraging the delimiter to simplify the removal process. Finally, the modified string is split using the same delimiter to reconstruct the list of source code lines without comments. This approach aims to streamline comment removal while maintaining code structure.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Concatenate Lines:\n\nCombine code lines into a single string using a delimiter " \' "(SINGLE QUOTATION).\n\n2. Iterate and Remove Comments:\n\nIterate through characters, removing block (\'/* */\') and line (\'//\') comments.Update the string during comment removal.\n\n3. Reconstruct Source Code:\n\nSplit the modified string using the delimiter "\'".\nRemove empty strings to reconstruct the list of code lines without comments.\n\n4. Return Result:\n\nReturn the reconstructed list of code lines without comments.\n\n\n\n\n\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> \n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> \n\n# Code\n```\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n \n \n new_s = []\n for i in source:\n new_s += i\n new_s += "\'"\n \n for i in range(len(new_s)):\n j = i + 2\n while j < len(new_s):\n\n if new_s[i] == "/" and new_s[i+1] == "*" and new_s[j] =="*" and new_s[j+1]=="/":\n new_s = new_s[:i] + new_s[j+2:]\n j = i + 2\n \n\n elif new_s[i] == "/" and new_s[i+1] == "/" and new_s[j] == "\'":\n new_s = new_s[:i] + new_s[j:]\n j = i + 2\n else:\n j += 1\n \n \n new_s = "".join(new_s)\n new_s = new_s.split("\'")\n while new_s.count(""):\n new_s.remove("")\n \n return new_s\n\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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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 \n line_start_idx = line.find(line_start)\n block_start_idx = line.find(block_start)\n \n if line_start_idx != -1 and block_start_idx != -1 and block_start_idx < line_start_idx:\n block_comment = True\n \n end_idx = 0\n \n for i in range(len(line) - 1):\n if block_start == (line[i] + line[i + 1]):\n end_idx = i\n break\n \n if end_idx == 0:\n line_break = True\n else:\n line_break = False\n \n new_line = line[:end_idx]\n rest_line = line[end_idx + 2:]\n \n if block_end in rest_line:\n end_idx = 0\n block_comment = False\n\n for i in range(len(rest_line) - 1):\n if block_end == (rest_line[i] + rest_line[i + 1]):\n end_idx = i\n break\n \n new_line2 = rest_line[end_idx + 2:]\n \n new_res = self.removeComments([new_line2])\n \n if len(new_line) != 0: \n res.append(new_line)\n \n if len(new_res) != 0 and line_break:\n res.append("".join(new_res))\n elif len(new_res) != 0 and not line_break:\n res[-1] = res[-1] + "".join(new_res)\n else:\n if new_res:\n res.append("".join(new_res))\n\n else:\n if len(new_line) != 0:\n res.append(new_line)\n elif line_start in line:\n\n end_idx = 0\n \n for i in range(len(line) - 1):\n if line_start == (line[i] + line[i + 1]):\n end_idx = i\n break\n \n new_line = line[:end_idx]\n \n if len(new_line) != 0:\n res.append(new_line)\n elif block_start in line:\n block_comment = True\n \n end_idx = 0\n \n for i in range(len(line) - 1):\n if block_start == (line[i] + line[i + 1]):\n end_idx = i\n break\n \n if end_idx == 0:\n line_break = True\n else:\n line_break = False\n \n new_line = line[:end_idx]\n rest_line = line[end_idx + 2:]\n \n if block_end in rest_line:\n end_idx = 0\n block_comment = False\n\n for i in range(len(rest_line) - 1):\n if block_end == (rest_line[i] + rest_line[i + 1]):\n end_idx = i\n break\n \n new_line2 = rest_line[end_idx + 2:]\n \n new_res = self.removeComments([new_line2])\n \n if len(new_line) != 0: \n res.append(new_line)\n \n if len(new_res) != 0 and line_break:\n res.append("".join(new_res))\n elif len(new_res) != 0 and not line_break:\n res[-1] = res[-1] + "".join(new_res)\n\n else:\n if len(new_line) != 0:\n res.append(new_line)\n\n else:\n if len(line) != 0:\n res.append(line)\n else:\n if block_end in line:\n \n end_idx = 0\n \n for i in range(len(line) - 1):\n if block_end == (line[i] + line[i + 1]):\n end_idx = (i + 1)\n break\n \n new_line = line[end_idx + 1:]\n new_res = self.removeComments([new_line])\n \n \n if len(new_res) != 0 and line_break:\n res.append("".join(new_res))\n elif len(new_res) != 0 and not line_break:\n res[-1] = res[-1] + "".join(new_res)\n \n block_comment = False\n\n return res\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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
💡💡 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<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n code = []\n comment = False\n for line in source:\n if not comment:\n newline = ""\n c = 0\n while(c < len(line)):\n if not comment:\n if line[c] == "/" and c+1 < len(line) and line[c+1] == "/":\n break\n elif line[c] == "/" and c+1 < len(line) and line[c+1] == "*":\n c += 1\n comment = True\n else:\n newline = newline + line[c]\n else:\n if line[c] == "*" and c+1 < len(line) and line[c+1] == "/":\n c += 1\n comment = False\n c += 1\n \n if not comment and len(newline):\n code.append(newline)\n return code\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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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 if state == "code":\n if ch != "/":\n output_line.append(ch)\n idx += 1\n else:\n if idx+1 < len(line) and line[idx+1] == "/":\n state = "line_comment"\n break\n elif idx+1 < len(line) and line[idx+1] == "*":\n state = "block_comment"\n idx += 2\n else:\n output_line.append(ch)\n idx += 1 \n else:\n # block comment\n if ch == "*" and idx+1 < len(line) and line[idx+1] == "/":\n state = "code"\n idx += 2\n else:\n idx += 1\n if state=="line_comment":\n state = "code"\n return state, output_line \n\n def removeComments(self, source: List[str]) -> List[str]:\n state = "code" # Block comment\n output = []\n prefix = ""\n for line in source:\n pre_state = state\n state, output_line = self.process_line(state, line)\n output_line = "".join(output_line)\n if state == "block_comment" and pre_state == "code":\n # code -> block_comment, get the prefix\n if output_line != "":\n prefix = output_line\n elif state == "code" and pre_state == "block_comment": \n # block_comment -> code, get the suffix\n if prefix+output_line!="":\n output.append(prefix+output_line)\n prefix = ""\n else:\n if output_line != "":\n output.append(output_line)\n return output\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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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 += 1\n elif line[i: i + 2] == \'//\':\n break\n elif line[i: i + 2] == \'/*\':\n i, cmt = i + 2, True\n else:\n i, s = i + 1, s + line[i]\n\n if s or cmt: res.append(s)\n\n return res\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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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)$$ -->\n\n# Code\n```\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n in_block_comment = False\n output = []\n new_line = []\n\n for line in source:\n if not in_block_comment:\n new_line = []\n\n i = 0\n while i < len(line):\n if line[i : i + 2] == \'/*\' and not in_block_comment:\n in_block_comment = True\n i += 1\n elif line[i : i + 2] == \'*/\' and in_block_comment:\n in_block_comment = False\n i += 1\n elif line[i : i + 2] == \'//\' and not in_block_comment:\n break\n elif not in_block_comment:\n new_line.append(line[i])\n\n i += 1\n\n if new_line and not in_block_comment:\n output.append(\'\'.join(new_line))\n\n return output\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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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 that indicates whether we\'re inside a block comment.\n\nIterate Over Lines: For each line in source, we iterate over its characters using the index i.\n\nBlock Comment Start Detection: If we\'re not currently inside a block comment and we detect the start of a block comment (i.e., "/*"), we set in_block to True and skip the next character.\n\nLine Comment Start Detection: If we\'re not inside a block comment and we detect the start of a line comment (i.e., "//"), we break out of the inner while loop because the rest of the line is a comment.\n\nBlock Comment End Detection: If we are inside a block comment and we detect its end (i.e., "*/"), we set in_block to False and skip the next character.\n\nCharacter Processing: If none of the above conditions are met, it means we\'re processing a regular character. If we\'re not inside a block comment, we add this character to our buffer.\n\nEnd of Line Processing: After processing a line, if we\'re not inside a block comment and our buffer is not empty, we append the buffer to res and then reset the buffer for the next line.\n\nReturn Result: After processing all lines, we return the res list which contains the source code lines without comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n res, buffer, in_block = [], "", False\n\n for line in source:\n i = 0\n while i < len(line):\n\n if not in_block and i + 1 < len(line) and line[i:i+2] == "/*":\n in_block = True\n i += 2\n\n elif not in_block and i + 1 < len(line) and line[i:i+2] == "//":\n break\n\n elif in_block and i + 1 < len(line) and line[i:i+2] == "*/":\n in_block = False\n i += 2\n\n else:\n if not in_block:\n buffer += line[i]\n i += 1\n\n if not in_block and buffer:\n res.append(buffer)\n buffer = ""\n\n return res\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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def removeComments(self, source: List[str]) -> List[str]:\n ret = []\n buffer = ""\n i = 0\n\n def parse_block(i, j):\n row = i\n col = j\n\n while row < len(source):\n s = source[row]\n\n while col < len(s):\n char = s[col]\n\n if char == "*" and col + 1 < len(s) and s[col + 1] == "/":\n # We reached the end of the comment\n return row, col + 1\n else:\n col += 1\n\n row += 1\n col = 0\n\n return len(source), len(source[-1])\n\n while i < len(source):\n s = source[i]\n j = 0\n buffer = ""\n\n while j < len(s):\n char = s[j]\n\n if char == "/":\n if j + 1 < len(s) and s[j+1] == "/":\n break\n \n elif j + 1 < len(s) and s[j+1] == "*":\n i , j = parse_block(i, j+2)\n if i >= len(source):\n break\n\n s = source[i]\n if j >= len(s):\n break\n else:\n buffer += char\n else:\n buffer += char\n\n j += 1\n \n if buffer:\n ret.append(buffer)\n\n i += 1\n \n return ret\n\n \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 block comments.
* The string `"// "` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored.
* The string `"/* "` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/ "` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/ "` does not yet end the block comment, as the ending would be overlapping the beginning.
The first effective comment takes precedence over others.
* For example, if the string `"// "` occurs in a block comment, it is ignored.
* Similarly, if the string `"/* "` occurs in a line or block comment, it is also ignored.
If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty.
There will be no control characters, single quote, or double quote characters.
* For example, `source = "string s = "/* Not a comment. */ "; "` will not be a test case.
Also, nothing else such as defines or macros will interfere with the comments.
It is guaranteed that every open block comment will eventually be closed, so `"/* "` outside of a line or block comment always starts a new comment.
Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details.
After removing the comments from the source code, return _the source code in the same format_.
**Example 1:**
**Input:** source = \[ "/\*Test program \*/ ", "int main() ", "{ ", " // variable declaration ", "int a, b, c; ", "/\* This is a test ", " multiline ", " comment for ", " testing \*/ ", "a = b + c; ", "} "\]
**Output:** \[ "int main() ", "{ ", " ", "int a, b, c; ", "a = b + c; ", "} "\]
**Explanation:** The line by line code is visualized as below:
/\*Test program \*/
int main()
{
// variable declaration
int a, b, c;
/\* This is a test
multiline
comment for
testing \*/
a = b + c;
}
The string /\* denotes a block comment, including line 1 and lines 6-9. The string // denotes line 4 as comments.
The line by line output code is visualized as below:
int main()
{
int a, b, c;
a = b + c;
}
**Example 2:**
**Input:** source = \[ "a/\*comment ", "line ", "more\_comment\*/b "\]
**Output:** \[ "ab "\]
**Explanation:** The original source string is "a/\*comment\\nline\\nmore\_comment\*/b ", where we have bolded the newline characters. After deletion, the implicit newline characters are deleted, leaving the string "ab ", which when delimited by newline characters becomes \[ "ab "\].
**Constraints:**
* `1 <= source.length <= 100`
* `0 <= source[i].length <= 80`
* `source[i]` consists of printable **ASCII** characters.
* Every open block comment is eventually closed.
* There are no single-quote or double-quote in the input. | 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 state to be *not* in a block.
* If we start a line comment and we aren't in a block, then we will ignore the rest of the line.
* If we aren't in a block comment (and it wasn't the start of a comment), we will record the character we are at.
* At the end of each line, if we aren't in a block, we will record the line. |
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 sum of first i numbers, not including nums[i]...\n int leftsum = 0;\n // Traverse the elements and add them to store the totalSum...\n for (int ele : nums)\n totalSum += ele;\n // Again traverse all the elements through the for loop and store the sum of i numbers from left to right...\n for (int i = 0; i < nums.length; leftsum += nums[i++])\n // sum to the left == leftsum.\n // sum to the right === totalSum - leftsum - nums[i]..\n // check if leftsum == totalSum - leftsum - nums[i]...\n if (leftsum * 2 == totalSum - nums[i])\n return i; // Return the pivot index...\n return -1; // If there is no index that satisfies the conditions in the problem statement...\n }\n}\n```\n\n# **C++ Solution:**\n```\n// Time Complexity : O(n)\nclass Solution {\npublic:\n int pivotIndex(vector<int>& nums) {\n // Initialize rightSum to store the sum of all the numbers strictly to the index\'s right...\n int rightSum = accumulate(nums.begin(), nums.end(), 0);\n // Initialize leftSum to store the sum of all the numbers strictly to the index\'s left...\n int leftSum = 0;\n // Traverse all elements through the loop...\n for (int idx = 0; idx < nums.size(); idx++) {\n // subtract current elements with from rightSum...\n rightSum -= nums[idx];\n // If 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...\n if (leftSum == rightSum)\n return idx; // Return the pivot index...\n // add current elements with leftSum...\n leftSum += nums[idx];\n }\n return -1; // If there is no index that satisfies the conditions in the problem statement...\n }\n};\n```\n\n# **Python/Python3 Solution:**\n```\n# Time Complexity : O(n)\n# Space Complexity : O(1)\nclass Solution(object):\n def pivotIndex(self, nums):\n # Initialize leftSum & rightSum to store the sum of all the numbers strictly to the index\'s left & right respectively...\n leftSum, rightSum = 0, sum(nums)\n # Traverse elements through the loop...\n for idx, ele in enumerate(nums):\n rightSum -= ele\n # If 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...\n if leftSum == rightSum:\n return idx # Return the pivot index...\n leftSum += ele\n return -1 # If there is no index that satisfies the conditions in the problem statement...\n```\n# **JavaScript Solution:**\n```\n// Time Complexity : O(n)\nvar pivotIndex = function(nums) {\n // Initialize total sum of the given array...\n let totalSum = 0\n // Traverse the elements and add them to store the totalSum...\n for(let i = 0; i < nums.length; i++) {\n totalSum += nums[i]\n }\n // Initialize \'leftsum\' as sum of first i numbers, not including nums[i]...\n let leftSum = 0\n // Again traverse all the elements through the for loop and store the sum of i numbers from left to right...\n for (let i = 0; i < nums.length; i++) {\n // sum to the left == leftsum.\n // sum to the right === totalSum - leftsum - nums[i]..\n // check if leftsum == totalSum - leftsum - nums[i]...\n if (leftSum * 2 == totalSum - nums[i])\n return i; // Return the pivot index...\n leftSum += nums[i]\n }\n return -1 // If there is no index that satisfies the conditions in the problem statement...\n};\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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 sum of first i numbers, not including nums[i]...\n int leftsum = 0;\n // Traverse the elements and add them to store the totalSum...\n for (int ele : nums)\n totalSum += ele;\n // Again traverse all the elements through the for loop and store the sum of i numbers from left to right...\n for (int i = 0; i < nums.length; leftsum += nums[i++])\n // sum to the left == leftsum.\n // sum to the right === totalSum - leftsum - nums[i]..\n // check if leftsum == totalSum - leftsum - nums[i]...\n if (leftsum * 2 == totalSum - nums[i])\n return i; // Return the pivot index...\n return -1; // If there is no index that satisfies the conditions in the problem statement...\n }\n}\n```\n\n# **C++ Solution:**\n```\n// Time Complexity : O(n)\nclass Solution {\npublic:\n int pivotIndex(vector<int>& nums) {\n // Initialize rightSum to store the sum of all the numbers strictly to the index\'s right...\n int rightSum = accumulate(nums.begin(), nums.end(), 0);\n // Initialize leftSum to store the sum of all the numbers strictly to the index\'s left...\n int leftSum = 0;\n // Traverse all elements through the loop...\n for (int idx = 0; idx < nums.size(); idx++) {\n // subtract current elements with from rightSum...\n rightSum -= nums[idx];\n // If 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...\n if (leftSum == rightSum)\n return idx; // Return the pivot index...\n // add current elements with leftSum...\n leftSum += nums[idx];\n }\n return -1; // If there is no index that satisfies the conditions in the problem statement...\n }\n};\n```\n\n# **Python/Python3 Solution:**\n```\n# Time Complexity : O(n)\n# Space Complexity : O(1)\nclass Solution(object):\n def pivotIndex(self, nums):\n # Initialize leftSum & rightSum to store the sum of all the numbers strictly to the index\'s left & right respectively...\n leftSum, rightSum = 0, sum(nums)\n # Traverse elements through the loop...\n for idx, ele in enumerate(nums):\n rightSum -= ele\n # If 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...\n if leftSum == rightSum:\n return idx # Return the pivot index...\n leftSum += ele\n return -1 # If there is no index that satisfies the conditions in the problem statement...\n```\n# **JavaScript Solution:**\n```\n// Time Complexity : O(n)\nvar pivotIndex = function(nums) {\n // Initialize total sum of the given array...\n let totalSum = 0\n // Traverse the elements and add them to store the totalSum...\n for(let i = 0; i < nums.length; i++) {\n totalSum += nums[i]\n }\n // Initialize \'leftsum\' as sum of first i numbers, not including nums[i]...\n let leftSum = 0\n // Again traverse all the elements through the for loop and store the sum of i numbers from left to right...\n for (let i = 0; i < nums.length; i++) {\n // sum to the left == leftsum.\n // sum to the right === totalSum - leftsum - nums[i]..\n // check if leftsum == totalSum - leftsum - nums[i]...\n if (leftSum * 2 == totalSum - nums[i])\n return i; // Return the pivot index...\n leftSum += nums[i]\n }\n return -1 // If there is no index that satisfies the conditions in the problem statement...\n};\n```\n**I am working hard for you guys...\nPlease upvote if you found any help with this code...** | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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 - left - ele\n # Checking if both sides are equal\n if right == left:\n return index\n # Updating left side\n left += ele\n # No answers found, so...\n return -1\n``` | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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 - left - ele\n # Checking if both sides are equal\n if right == left:\n return index\n # Updating left side\n left += ele\n # No answers found, so...\n return -1\n``` | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n s,count=sum(nums),0\n for ind in range(len(nums)):\n count+=nums[ind]\n if count==s:\n return ind\n s-=nums[ind]\n return -1\n #please upvote me it would encourage me alot\n\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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n s,count=sum(nums),0\n for ind in range(len(nums)):\n count+=nums[ind]\n if count==s:\n return ind\n s-=nums[ind]\n return -1\n #please upvote me it would encourage me alot\n\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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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, ```nums```: 7, ```left```: 1, ```right ```:20\n3. ```index```: 2, ```nums```: 3, ```left```: 8, ```right ```:17\n4. ```index```: 3, ```nums```: 6, ```left```: 11, ```right ```:11 <--Index found ```[left==right]```\n\n```So, Pivot are present in the index ```: 3\n\n```\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n left =0\n right = sum(nums)\n for index, nums in enumerate(nums):\n right-=nums\n if left==right:\n return index\n left+=nums \n return -1\n````\n```Happy learning!!\u2764``` | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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, ```nums```: 7, ```left```: 1, ```right ```:20\n3. ```index```: 2, ```nums```: 3, ```left```: 8, ```right ```:17\n4. ```index```: 3, ```nums```: 6, ```left```: 11, ```right ```:11 <--Index found ```[left==right]```\n\n```So, Pivot are present in the index ```: 3\n\n```\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n left =0\n right = sum(nums)\n for index, nums in enumerate(nums):\n right-=nums\n if left==right:\n return index\n left+=nums \n return -1\n````\n```Happy learning!!\u2764``` | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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 else:\n start_sum += nums[pivot]\n end_sum -= nums[pivot+1]\n pivot +=1\n return -1\n``` | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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 else:\n start_sum += nums[pivot]\n end_sum -= nums[pivot+1]\n pivot +=1\n return -1\n``` | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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 or traditional markets.\n\n\n#2.\nImagine each **number** from input list as a **weight**.\n\n\n\n\n\n#3\nTurn the finding of pivot index with left hand sum = right hand sum into the **procedure of reaching the balance on boths sides**.\n\n\n---\n\n**Algorithm**:\n\n---\n\nStep_#1:\n\nLet \n**Left hand side be empty**, and\n**Right hand side holds all weights**.\n\n---\n\nStep_#2:\n\nIterate weight_*i* from 0 to (n-1)\n\nDuring each iteration, **take away weight_#i from right hand side**, **check whether balance is met** or not.\n\n**If yes**, then the **index *i*** is the **pivot index**.\n\nIf no, **put weight_#*i* on the left hand side**, and **repeat the process** until balance is met or all weights are exchanged.\n\n---\n\nStep_#3:\n\nFinally, if all weights are exchanged and no balance is met, then pivot index does not exist, return -1.\n\n---\n\n\n```python []\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n \n # Initialization:\n # Left hand side be empty, and\n # Right hand side holds all weights.\n total_weight_on_left, total_weight_on_right = 0, sum(nums)\n\n for idx, current_weight in enumerate(nums):\n\n total_weight_on_right -= current_weight\n\n if total_weight_on_left == total_weight_on_right:\n # balance is met on both sides\n # i.e., sum( nums[ :idx] ) == sum( nums[idx+1: ] )\n return idx\n\n total_weight_on_left += current_weight\n\n return -1\n```\n```javascript []\nfunction Accumulation(arr){\n return arr.reduce((a,b)=>a+b); \n}\n\nvar pivotIndex = function(nums) {\n \n\n // Initialization:\n // Left hand side be empty, and\n // Right hand side holds all weights.\n \n let totalWeightOnLeft = 0;\n let totalWeightOnRight = Accumulation(nums);\n \n for( let i = 0 ; i < nums.length ; i++ ){\n \n let currentWeight = nums[i];\n \n totalWeightOnRight -= currentWeight;\n \n if( totalWeightOnLeft == totalWeightOnRight ){\n // balance is met on both sides\n return i;\n }\n \n totalWeightOnLeft += currentWeight\n \n \n }\n \n return -1;\n \n};\n```\n```java []\nclass Solution {\n public int pivotIndex(int[] nums) {\n \n // Initialization:\n // Left hand side be empty, and\n // Right hand side holds all weights.\n int totalWeightOnLeft = 0;\n int totalWeightOnRight = IntStream.of( nums ).sum();\n \n for( int i = 0 ; i < nums.length ; i++ ){\n \n int curWeight = nums[i];\n \n totalWeightOnRight -= curWeight;\n \n if( totalWeightOnLeft == totalWeightOnRight ){\n // balance is met on both sides\n return i;\n }\n \n totalWeightOnLeft += curWeight;\n }\n \n return -1;\n }\n}\n```\n```Go []\nfunc accumulation(nums []int) int{\n \n summation := 0\n \n for _, num := range nums{\n summation += num \n }\n \n return summation\n}\n\n\nfunc pivotIndex(nums []int) int {\n \n // Initialization\n // Left hand side be empty\n // Right hand side holds all weights\n totalWeightOnLeft := 0\n totalWeightOnRight := accumulation( nums )\n \n for idx, currentWeight := range nums{\n \n totalWeightOnRight -= currentWeight\n \n if totalWeightOnLeft == totalWeightOnRight{\n // balance is met on both sides\n return idx\n }\n \n totalWeightOnLeft += currentWeight\n }\n \n return -1\n \n}\n```\n```C++ []\nclass Solution {\npublic:\n int pivotIndex(vector<int>& nums) {\n \n // Initialization:\n // Left hand side be empty, and\n // Right hand side holds all weights.\n \n int totalWeightOnLeft = 0;\n int totalWeightOnRight = std::accumulate( nums.begin(), nums.end(), 0);\n \n \n for(std::size_t i = 0; i < nums.size() ; i++ ){\n \n int currentWeight = nums[i];\n \n totalWeightOnRight -= currentWeight;\n \n if( totalWeightOnLeft == totalWeightOnRight ){\n // balance is met on both sides\n return i;\n }\n \n totalWeightOnLeft += currentWeight;\n }\n \n \n return -1;\n }\n};\n```\n\n---\n\nTime Complexity: O(n) on for loop iteration, and summation of input array.\n\nSapce Complexity: O(1) on fixed size of temp variables.\n\n\n\n | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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 or traditional markets.\n\n\n#2.\nImagine each **number** from input list as a **weight**.\n\n\n\n\n\n#3\nTurn the finding of pivot index with left hand sum = right hand sum into the **procedure of reaching the balance on boths sides**.\n\n\n---\n\n**Algorithm**:\n\n---\n\nStep_#1:\n\nLet \n**Left hand side be empty**, and\n**Right hand side holds all weights**.\n\n---\n\nStep_#2:\n\nIterate weight_*i* from 0 to (n-1)\n\nDuring each iteration, **take away weight_#i from right hand side**, **check whether balance is met** or not.\n\n**If yes**, then the **index *i*** is the **pivot index**.\n\nIf no, **put weight_#*i* on the left hand side**, and **repeat the process** until balance is met or all weights are exchanged.\n\n---\n\nStep_#3:\n\nFinally, if all weights are exchanged and no balance is met, then pivot index does not exist, return -1.\n\n---\n\n\n```python []\nclass Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n \n # Initialization:\n # Left hand side be empty, and\n # Right hand side holds all weights.\n total_weight_on_left, total_weight_on_right = 0, sum(nums)\n\n for idx, current_weight in enumerate(nums):\n\n total_weight_on_right -= current_weight\n\n if total_weight_on_left == total_weight_on_right:\n # balance is met on both sides\n # i.e., sum( nums[ :idx] ) == sum( nums[idx+1: ] )\n return idx\n\n total_weight_on_left += current_weight\n\n return -1\n```\n```javascript []\nfunction Accumulation(arr){\n return arr.reduce((a,b)=>a+b); \n}\n\nvar pivotIndex = function(nums) {\n \n\n // Initialization:\n // Left hand side be empty, and\n // Right hand side holds all weights.\n \n let totalWeightOnLeft = 0;\n let totalWeightOnRight = Accumulation(nums);\n \n for( let i = 0 ; i < nums.length ; i++ ){\n \n let currentWeight = nums[i];\n \n totalWeightOnRight -= currentWeight;\n \n if( totalWeightOnLeft == totalWeightOnRight ){\n // balance is met on both sides\n return i;\n }\n \n totalWeightOnLeft += currentWeight\n \n \n }\n \n return -1;\n \n};\n```\n```java []\nclass Solution {\n public int pivotIndex(int[] nums) {\n \n // Initialization:\n // Left hand side be empty, and\n // Right hand side holds all weights.\n int totalWeightOnLeft = 0;\n int totalWeightOnRight = IntStream.of( nums ).sum();\n \n for( int i = 0 ; i < nums.length ; i++ ){\n \n int curWeight = nums[i];\n \n totalWeightOnRight -= curWeight;\n \n if( totalWeightOnLeft == totalWeightOnRight ){\n // balance is met on both sides\n return i;\n }\n \n totalWeightOnLeft += curWeight;\n }\n \n return -1;\n }\n}\n```\n```Go []\nfunc accumulation(nums []int) int{\n \n summation := 0\n \n for _, num := range nums{\n summation += num \n }\n \n return summation\n}\n\n\nfunc pivotIndex(nums []int) int {\n \n // Initialization\n // Left hand side be empty\n // Right hand side holds all weights\n totalWeightOnLeft := 0\n totalWeightOnRight := accumulation( nums )\n \n for idx, currentWeight := range nums{\n \n totalWeightOnRight -= currentWeight\n \n if totalWeightOnLeft == totalWeightOnRight{\n // balance is met on both sides\n return idx\n }\n \n totalWeightOnLeft += currentWeight\n }\n \n return -1\n \n}\n```\n```C++ []\nclass Solution {\npublic:\n int pivotIndex(vector<int>& nums) {\n \n // Initialization:\n // Left hand side be empty, and\n // Right hand side holds all weights.\n \n int totalWeightOnLeft = 0;\n int totalWeightOnRight = std::accumulate( nums.begin(), nums.end(), 0);\n \n \n for(std::size_t i = 0; i < nums.size() ; i++ ){\n \n int currentWeight = nums[i];\n \n totalWeightOnRight -= currentWeight;\n \n if( totalWeightOnLeft == totalWeightOnRight ){\n // balance is met on both sides\n return i;\n }\n \n totalWeightOnLeft += currentWeight;\n }\n \n \n return -1;\n }\n};\n```\n\n---\n\nTime Complexity: O(n) on for loop iteration, and summation of input array.\n\nSapce Complexity: O(1) on fixed size of temp variables.\n\n\n\n | 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 sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/) | 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 drawings. I\'m sure you understand the solution easily!\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n---\n\n# Approach\nThis is based on Python. Other might be different a bit.\n\n1. **Calculate the length of the linked list**\n - Initialize a variable `length` to 0 to keep track of the number of nodes in the linked list.\n - Initialize a pointer `current` to the head of the linked list.\n - Use a `while` loop to traverse the linked list while updating `current` and incrementing `length` for each node in the list.\n\n2. **Determine the size of each part**\n - Calculate `part_size` by dividing `length` by `k`. This gives you the base size of each part.\n - Calculate `larger_parts` by taking the remainder of `length` divided by `k`. This represents the number of parts that will have one extra element.\n\n3. **Split the linked list into parts**\n - Initialize an empty list `result` to store the resulting linked list parts.\n - Reset the `current` pointer to the head of the linked list.\n - Use a `for` loop to iterate `k` times, where `k` is the number of parts to split the list into.\n - Calculate `sublist_size` based on whether the current part (`i`) should have an extra element. If `i` is less than `larger_parts`, add 1 to `part_size`; otherwise, use `part_size`.\n - If `sublist_size` is 0 (which can happen if `k` is greater than the length of the linked list), append `None` to the `result` list to represent an empty part.\n - Otherwise, create a `sublist_head` pointer to the current node, which will be the head of the sublist.\n - Use a nested `for` loop to traverse the sublist until you reach the end of the sublist (which is `sublist_size - 1` nodes). Update the `current` pointer accordingly.\n - Store the next node (`next_node`) after the sublist in `next_node`.\n - Set the `next` pointer of the current node to `None` to separate the sublist from the original list.\n - Append the `sublist_head` to the `result` list, representing one of the parts of the split linked list.\n - Update the `current` pointer to `next_node` to prepare for the next iteration.\n\n4. **Return the result**\n - Return the `result` list, which contains the linked list split into parts.\n\nThis algorithm takes a linked list, calculates its length, determines the size of each part based on the desired number of parts, and then splits the linked list into those parts while maintaining the original order of elements.\n\n# Complexity\n- Time complexity: O(n) or O(n + k)\nDepends on size of n and k.\n\n- Space complexity: O(k)\n\n```python []\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 # Step 1: Calculate the length of the linked list\n length = 0\n current = head\n while current:\n length += 1\n current = current.next\n \n # Step 2: Determine the size of each part\n part_size = length // k\n larger_parts = length % k\n \n # Initialize a list to store the results\n result = []\n \n # Step 3: Split the linked list into parts\n current = head\n for i in range(k):\n sublist_size = part_size + 1 if i < larger_parts else part_size\n if sublist_size == 0:\n result.append(None)\n else:\n sublist_head = current\n for _ in range(sublist_size - 1):\n current = current.next\n next_node = current.next\n current.next = None\n result.append(sublist_head)\n current = next_node\n \n return result\n```\n```javascript []\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} head\n * @param {number} k\n * @return {ListNode[]}\n */\nvar splitListToParts = function(head, k) {\n // Step 1: Calculate the length of the linked list\n let length = 0;\n let current = head;\n while (current) {\n length += 1;\n current = current.next;\n }\n\n // Step 2: Determine the size of each part\n const partSize = Math.floor(length / k);\n const largerParts = length % k;\n\n // Initialize an array to store the results\n const result = [];\n\n // Step 3: Split the linked list into parts\n current = head;\n for (let i = 0; i < k; i++) {\n const sublistSize = i < largerParts ? partSize + 1 : partSize;\n if (sublistSize === 0) {\n result.push(null);\n } else {\n const sublistHead = current;\n for (let j = 0; j < sublistSize - 1; j++) {\n current = current.next;\n }\n const nextNode = current.next;\n current.next = null;\n result.push(sublistHead);\n current = nextNode;\n }\n }\n\n return result; \n};\n```\n```java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode[] splitListToParts(ListNode head, int k) {\n // Step 1: Calculate the length of the linked list\n int length = 0;\n ListNode current = head;\n while (current != null) {\n length += 1;\n current = current.next;\n }\n\n // Step 2: Determine the size of each part\n int partSize = length / k;\n int largerParts = length % k;\n\n // Initialize an array to store the results\n ListNode[] result = new ListNode[k];\n\n // Step 3: Split the linked list into parts\n current = head;\n for (int i = 0; i < k; i++) {\n int sublistSize = (i < largerParts) ? (partSize + 1) : partSize;\n if (sublistSize == 0) {\n result[i] = null;\n } else {\n ListNode sublistHead = current;\n for (int j = 0; j < sublistSize - 1; j++) {\n current = current.next;\n }\n ListNode nextNode = current.next;\n current.next = null;\n result[i] = sublistHead;\n current = nextNode;\n }\n }\n\n return result; \n }\n}\n```\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<ListNode*> splitListToParts(ListNode* head, int k) {\n // Step 1: Calculate the length of the linked list\n int length = 0;\n ListNode* current = head;\n while (current) {\n length += 1;\n current = current->next;\n }\n\n // Step 2: Determine the size of each part\n int partSize = length / k;\n int largerParts = length % k;\n\n // Initialize a vector to store the results\n vector<ListNode*> result(k);\n\n // Step 3: Split the linked list into parts\n current = head;\n for (int i = 0; i < k; i++) {\n int sublistSize = (i < largerParts) ? (partSize + 1) : partSize;\n if (sublistSize == 0) {\n result[i] = nullptr;\n } else {\n ListNode* sublistHead = current;\n for (int j = 0; j < sublistSize - 1; j++) {\n current = current->next;\n }\n ListNode* nextNode = current->next;\n current->next = nullptr;\n result[i] = sublistHead;\n current = nextNode;\n }\n }\n\n return result; \n }\n};\n```\n\n\n | 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 occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return _an array of the_ `k` _parts_.
**Example 1:**
**Input:** head = \[1,2,3\], k = 5
**Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\]
**Explanation:**
The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null.
The last element output\[4\] is null, but its string representation as a ListNode is \[\].
**Example 2:**
**Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3
**Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\]
**Explanation:**
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
**Constraints:**
* The number of nodes in the list is in the range `[0, 1000]`.
* `0 <= Node.val <= 1000`
* `1 <= k <= 50` | 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<!-- Describe your first thoughts on how to solve this problem. -->\nThe key insight here is that we can efficiently split the linked list into **equal-sized parts** by calculating the **minimum guaranteed size** of each part (n) and distributing any extra nodes (r) as evenly as possible among the first r parts. **This approach ensures that we meet both conditions specified in the problem statement**.\n\n**By maintaining two pointers (node and prev)** and updating them as we traverse the linked list, we can keep track of the current part and efficiently split the list into k parts.\n\n# Approach\n**To solve this problem efficiently, we can follow these steps:**\n<!-- Describe your approach to solving the problem. -->\n1. **Calculate the Length:** First, we need to **determine the length of the linked list**. This is **important because it helps** us evenly distribute the nodes among the k parts.\n```\nfor (ListNode* node = root; node; node = node->next)\n len++;\n```\n2. **Calculate Sizes:** Calculate the minimum guaranteed size of each part, n, **by dividing the total length by k**. **Also, calculate the number of extra nodes, r**, which will be spread among the first r parts (remainder of length / k).\n```\n // Calculate the minimum guaranteed part size (n) and the number of extra nodes (r).\n int n = len / k, r = len % k;\n```\n3. **Traverse and Split:** Initialize **two pointers**, node and prev, **to traverse the linked list.** Then, loop through each part:\n - **Store the current node** as the start of the current part in the parts array.\n - **Traverse n + 1 nodes** if there are remaining extra nodes (when r > 0). Otherwise, traverse only n nodes.\n - After traversing, **we disconnect the current part from the rest of the list by setting prev->next to nullptr**. This ensures that each part is isolated.\n```\n// Loop through each part.\n for (int i = 0; node && i < k; i++, r--) {\n // Store the current node as the start of the current part.\n parts[i] = node;\n // Traverse n + 1 nodes if there are remaining extra nodes (r > 0).\n // Otherwise, traverse only n nodes.\n for (int j = 0; j < n + (r > 0); j++) {\n prev = node;\n node = node->next;\n }\n // Disconnect the current part from the rest of the list by setting prev->next to nullptr.\n prev->next = nullptr;\n }\n``` \n4. **Return Result:** Return the parts array containing the k parts of the linked list.\n\n---\n\n\n# Till now if any doubt, Please see step by step Guide:\n1. **We start by creating an array parts of size k** to store the resulting linked list parts. Initially, all elements are set to nullptr.\n2. **We calculate the length of the input linked list by traversing it using a for loop**. This helps us determine the size of each part.\n3. **We calculate two important values:**\n - **n: The minimum guaranteed size of each part**, obtained by dividing the total length by k.\n - **r: The number of extra nodes that need to be distributed among the first r parts**, where r is the remainder of the division.\n4. **We initialize two pointers, node and prev**, to traverse the linked list. **node starts at the head of the linked list** (root), and **prev keeps track of the previous node.**\n5. We loop through **each part of the result:**\n\n - Store the current node **as the start of the current part in the parts array.**\n - **Traverse n + 1 nodes if there are remaining extra nodes** (when r > 0). Otherwise, traverse only n nodes.\n - **After traversing, we disconnect the current part** from the rest of the list by setting prev->next to nullptr. This ensures that each part is isolated.\n6. **Finally, we return the parts array** containing the k parts of the linked list.\n# Complexity\n- Time complexity: O(N), where N is the number of nodes in the linked list.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(K), where k is the number of parts in which the linked list is split.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n---\n\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n\n# Code\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<ListNode*> splitListToParts(ListNode* root, int k) {\n // Create a vector of ListNode pointers to store the k parts.\n vector<ListNode*> parts(k, nullptr);\n\n // Calculate the length of the linked list.\n int len = 0;\n for (ListNode* node = root; node; node = node->next)\n len++;\n\n // Calculate the minimum guaranteed part size (n) and the number of extra nodes (r).\n int n = len / k, r = len % k;\n\n // Initialize pointers to traverse the linked list.\n ListNode* node = root, *prev = nullptr;\n\n // Loop through each part.\n for (int i = 0; node && i < k; i++, r--) {\n // Store the current node as the start of the current part.\n parts[i] = node;\n // Traverse n + 1 nodes if there are remaining extra nodes (r > 0).\n // Otherwise, traverse only n nodes.\n for (int j = 0; j < n + (r > 0); j++) {\n prev = node;\n node = node->next;\n }\n // Disconnect the current part from the rest of the list by setting prev->next to nullptr.\n prev->next = nullptr;\n }\n\n // Return the array of k parts.\n return parts;\n }\n};\n```\n```Java []\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode[] splitListToParts(ListNode root, int k) {\n // Create an array of ListNode pointers to store the k parts.\n ListNode[] parts = new ListNode[k];\n\n // Calculate the length of the linked list.\n int len = 0;\n ListNode node = root;\n while (node != null) {\n len++;\n node = node.next;\n }\n\n // Calculate the minimum guaranteed part size (n) and the number of extra nodes (r).\n int n = len / k, r = len % k;\n\n // Reset the pointer to the beginning of the linked list.\n node = root;\n ListNode prev = null;\n\n // Loop through each part.\n for (int i = 0; node != null && i < k; i++, r--) {\n // Store the current node as the start of the current part.\n parts[i] = node;\n\n // Traverse n + 1 nodes if there are remaining extra nodes (r > 0).\n // Otherwise, traverse only n nodes.\n for (int j = 0; j < n + (r > 0 ? 1 : 0); j++) {\n prev = node;\n node = node.next;\n }\n\n // Disconnect the current part from the rest of the list by setting prev.next to null.\n if (prev != null) {\n prev.next = null;\n }\n }\n\n // Return the array of k parts.\n return parts;\n }\n}\n\n```\n```Python3 []\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n def splitListToParts(self, root, k):\n # Create a list of ListNode pointers to store the k parts.\n parts = [None] * k\n\n # Calculate the length of the linked list.\n len = 0\n node = root\n while node:\n len += 1\n node = node.next\n\n # Calculate the minimum guaranteed part size (n) and the number of extra nodes (r).\n n, r = divmod(len, k)\n\n # Reset the pointer to the beginning of the linked list.\n node = root\n prev = None\n\n # Loop through each part.\n for i in range(k):\n # Store the current node as the start of the current part.\n parts[i] = node\n\n # Traverse n + 1 nodes if there are remaining extra nodes (r > 0).\n # Otherwise, traverse only n nodes.\n for j in range(n + (1 if r > 0 else 0)):\n prev = node\n node = node.next\n\n # Disconnect the current part from the rest of the list by setting prev.next to None.\n if prev:\n prev.next = None\n\n # Decrement the count of extra nodes (r) if applicable.\n if r > 0:\n r -= 1\n\n # Return the list of k parts.\n return parts\n\n```\n``` Javascript []\n// Definition for singly-linked list.\nfunction ListNode(val, next) {\n this.val = val;\n this.next = next || null;\n}\n\nvar splitListToParts = function(root, k) {\n // Create an array of ListNode pointers to store the k parts.\n const parts = new Array(k).fill(null);\n\n // Calculate the length of the linked list.\n let len = 0;\n let node = root;\n while (node) {\n len++;\n node = node.next;\n }\n\n // Calculate the minimum guaranteed part size (n) and the number of extra nodes (r).\n const n = Math.floor(len / k);\n let r = len % k;\n\n // Reset the pointer to the beginning of the linked list.\n node = root;\n let prev = null;\n\n // Loop through each part.\n for (let i = 0; node && i < k; i++, r--) {\n // Store the current node as the start of the current part.\n parts[i] = node;\n\n // Traverse n + 1 nodes if there are remaining extra nodes (r > 0).\n // Otherwise, traverse only n nodes.\n for (let j = 0; j < n + (r > 0 ? 1 : 0); j++) {\n prev = node;\n node = node.next;\n }\n\n // Disconnect the current part from the rest of the list by setting prev.next to null.\n if (prev) {\n prev.next = null;\n }\n }\n\n // Return the array of k parts.\n return parts;\n};\n\n```\n\n---\n\n\n# SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated\uD83D\uDE0A\uD83D\uDE0A\n\n\n | 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 occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return _an array of the_ `k` _parts_.
**Example 1:**
**Input:** head = \[1,2,3\], k = 5
**Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\]
**Explanation:**
The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null.
The last element output\[4\] is null, but its string representation as a ListNode is \[\].
**Example 2:**
**Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3
**Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\]
**Explanation:**
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
**Constraints:**
* The number of nodes in the list is in the range `[0, 1000]`.
* `0 <= Node.val <= 1000`
* `1 <= k <= 50` | 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\n while cur:\n n+=1\n cur=cur.next\n\n part,left=n//k,n%k\n cur=head\n prev=None\n for i in range(k):\n ans.append(cur)\n for _ in range(part):\n if cur:\n prev=cur\n cur=cur.next\n\n if left and cur:\n prev=cur\n cur=cur.next\n left-=1\n\n if prev:\n prev.next=None\n\n return ans \n``` | 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 occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return _an array of the_ `k` _parts_.
**Example 1:**
**Input:** head = \[1,2,3\], k = 5
**Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\]
**Explanation:**
The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null.
The last element output\[4\] is null, but its string representation as a ListNode is \[\].
**Example 2:**
**Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3
**Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\]
**Explanation:**
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
**Constraints:**
* The number of nodes in the list is in the range `[0, 1000]`.
* `0 <= Node.val <= 1000`
* `1 <= k <= 50` | 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 fewer than k nodes in the linked list, then empty nodes should be placed in the remaining parts.\n\n`for detailed explanation you can refer to my youtube channel` \n\n[ Video in Hindi click here](https://youtube.com/@LetsCodeTogether72/videos)\n\nor link in my profile.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise explanation.\n\n# Solution Approach:\nTo solve this problem, we will first find the total length of the linked list. Then, we will calculate the number of elements in each part and the number of extra elements. After that, we will iterate through the list and create sublists, taking care to distribute the extra elements as evenly as possible among the parts.\n\n# Code Explanation:\nLet\'s break down the code step by step:\n\n1. Calculate the length of the linked list by traversing it using a temporary pointer \'temp.\'\n\n2. Create a vector \'v\' of ListNode pointers with size \'k\' to store the resulting sublists.\n\n3. Calculate \'p,\' which represents the minimum number of elements in each part, by dividing the total length by \'k.\'\n\n4. Calculate \'extra,\' which represents the number of extra elements that need to be distributed among the parts, by taking the modulus of the total length by \'k.\'\n\n5. Initialize \'temp\' to the head of the linked list and \'j\' to 0, which will help us keep track of the current part we are working on.\n\n6. Iterate through the linked list, creating sublists:\n\n a. Create a dummy node and a \'curr\' pointer to help build the sublist.\n \n b. For \'p\' times (or until we run out of elements), copy the value from the original list to the sublist.\n\n c. If \'extra\' is greater than 0, copy an extra element to the sublist and decrement \'extra.\'\n\n d. Assign the sublist (excluding the dummy node) to \'v[j]\' to store the result of this part.\n\n e. Increment \'j\' to move on to the next part.\n\n7. Return the vector \'v,\' which contains the k sublists.\n\n# Complexity\n- Time complexity:$$O(n)$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n vector<ListNode*> splitListToParts(ListNode* head, int k) {\n int len=0;\n ListNode*temp=head;\n while(temp!=NULL){\n len++;\n temp=temp->next;\n }\n vector<ListNode*>v(k,NULL);\n int p=len/k;\n int extra=len%k;\n temp=head;\n int j=0;\n while(temp!=NULL){\n ListNode*c=temp;\n ListNode*dummy=new ListNode(-1);\n ListNode*curr=dummy;\n for(int i=0;i<p;i++){\n curr->next=new ListNode(temp->val);\n temp=temp->next;\n curr=curr->next;\n }\n if(extra>0){\n curr->next=new ListNode(temp->val);\n temp=temp->next;\n curr=curr->next;\n extra--;\n }\n v[j]=dummy->next;\n j++;\n }\n return v;\n }\n};\n```\n```java []\n/**\n * Definition for singly-linked list.\n * class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\n\nclass Solution {\n public ListNode[] splitListToParts(ListNode head, int k) {\n int length = 0;\n ListNode temp = head;\n while (temp != null) {\n length++;\n temp = temp.next;\n }\n\n int partSize = length / k;\n int extra = length % k;\n\n ListNode[] result = new ListNode[k];\n temp = head;\n for (int i = 0; i < k; i++) {\n result[i] = temp;\n int currentPartSize = partSize + (extra-- > 0 ? 1 : 0);\n for (int j = 0; j < currentPartSize - 1; j++) {\n temp = temp.next;\n }\n if (temp != null) {\n ListNode next = temp.next;\n temp.next = null;\n temp = next;\n }\n }\n return result;\n }\n}\n\n```\n```python []\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\n\nclass Solution:\n def splitListToParts(self, head: ListNode, k: int) -> List[ListNode]:\n length = 0\n temp = head\n while temp:\n length += 1\n temp = temp.next\n\n part_size = length // k\n extra = length % k\n\n result = []\n temp = head\n for i in range(k):\n result.append(temp)\n current_part_size = part_size + 1 if extra > 0 else part_size\n extra -= 1\n for j in range(current_part_size - 1):\n temp = temp.next\n if temp:\n temp.next, temp = None, temp.next\n\n return result\n\n```\n\n | 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 occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return _an array of the_ `k` _parts_.
**Example 1:**
**Input:** head = \[1,2,3\], k = 5
**Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\]
**Explanation:**
The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null.
The last element output\[4\] is null, but its string representation as a ListNode is \[\].
**Example 2:**
**Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3
**Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\]
**Explanation:**
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
**Constraints:**
* The number of nodes in the list is in the range `[0, 1000]`.
* `0 <= Node.val <= 1000`
* `1 <= k <= 50` | 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)$$ -->\n\n# Code\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\n\nclass Solution:\n def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:\n l = 0\n temp = head\n while temp:\n l += 1\n temp = temp.next\n \n part_size = l // k\n extra = l % k\n \n result = []\n temp = head\n \n for i in range(k):\n if not temp:\n result.append(None) \n else:\n result.append(temp)\n cr = part_size + 1 if extra > 0 else part_size\n extra -= 1\n \n for j in range(cr - 1):\n temp = temp.next \n next_node = temp.next\n temp.next = None \n temp = next_node \n \n return result\n\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 occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return _an array of the_ `k` _parts_.
**Example 1:**
**Input:** head = \[1,2,3\], k = 5
**Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\]
**Explanation:**
The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null.
The last element output\[4\] is null, but its string representation as a ListNode is \[\].
**Example 2:**
**Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3
**Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\]
**Explanation:**
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
**Constraints:**
* The number of nodes in the list is in the range `[0, 1000]`.
* `0 <= Node.val <= 1000`
* `1 <= k <= 50` | 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 size 80\nn = 80\n\n# We need to split him at 7 chunks\nk = 7\n\n# At first we define a regular size of a chunk\nsize = n // k # 11\n\n# And than just distribute the mod after deletion\nmod = n % k # 3\nans = [12, 12, 12, 11, 11, 11, 11]\n```\n\n# Approach\n1. initialize `n` variable to store count (or **depth** of a list) of nodes\n2. start to iterate over linked list and increment `n`\n3. define `size`, `mod` and `ans` variables according to the logic above\n4. shift the pointer `cur` again at `head`\n5. create loops to iterate over `k` and `ans[i] - 1` as a nested loop\n6. check if we\'re out of nodes at `cur`\n7. shift the pointer `cur` to the next node at each iteration\n8. in the end of chunk store the referrence `tmp` as a next pointer and remove the existing ref in `cur.next`, then store tmp to the `ans`\n9. return `ans`\n\n# Complexity\n- Time complexity: **O(n+k)**, where `n` is the count of nodes and `k` - amount of chunks\n\n- Space complexity: **O(k)**, because of storing `ans` as size of `k`\n\n# Code\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 n = 0\n cur = head\n\n while cur:\n n += 1\n cur = cur.next\n\n size = n // k\n mod = n % k\n ans = [size for _ in range(k)]\n\n for i in range(mod):\n ans[i] += 1\n\n cur = head\n\n for i in range(k):\n if cur:\n ptr = cur\n \n for j in range(ans[i] - 1):\n cur = cur.next\n \n tmp = cur.next\n cur.next = None\n cur = tmp\n ans[i] = ptr\n else:\n ans[i] = None\n\n return ans\n \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 occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later.
Return _an array of the_ `k` _parts_.
**Example 1:**
**Input:** head = \[1,2,3\], k = 5
**Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\]
**Explanation:**
The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null.
The last element output\[4\] is null, but its string representation as a ListNode is \[\].
**Example 2:**
**Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3
**Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\]
**Explanation:**
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.
**Constraints:**
* The number of nodes in the list is in the range `[0, 1000]`.
* `0 <= Node.val <= 1000`
* `1 <= k <= 50` | 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 new formula\n if formula[i] == \'(\':\n i += 1\n # Initialize a new counter for the new formula\n count = Counter()\n # Add the new counter to the stack\n stack.append(count)\n # \')\' indicates the end of a formula\n elif formula[i] == \')\':\n i += 1\n # Find the end of the count that follows the \')\'\n end = i\n while i < n and formula[i].isdigit():\n i += 1\n # Get the count, default to 1 if no count is provided\n mult = int(formula[end:i] or 1)\n top = stack.pop()\n # Add the count of each atom in the popped counter to the top counter in the stack\n for name, v in top.items():\n stack[-1][name] += v * mult\n # Update the current counter to the top counter in the stack\n count = stack[-1]\n else:\n # If the current character is not \'(\' or \')\', it\'s an atom\n # Find the end of the atom name\n start = i\n i += 1\n while i < n and formula[i].islower():\n i += 1\n # Get the atom name\n name = formula[start:i]\n # Find the end of the count that follows the atom name\n start = i\n while i < n and formula[i].isdigit():\n i += 1\n # Get the count, default to 1 if no count is provided\n mult = int(formula[start:i] or 1)\n # Add the count of the atom to the top counter in the stack\n stack[-1][name] += mult\n\n # Return the count of all atoms in the format specified in the problem\n return "".join(name + (str(count[name]) if count[name] > 1 else \'\') for name in sorted(count))\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is 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 new formula\n if formula[i] == \'(\':\n i += 1\n # Initialize a new counter for the new formula\n count = Counter()\n # Add the new counter to the stack\n stack.append(count)\n # \')\' indicates the end of a formula\n elif formula[i] == \')\':\n i += 1\n # Find the end of the count that follows the \')\'\n end = i\n while i < n and formula[i].isdigit():\n i += 1\n # Get the count, default to 1 if no count is provided\n mult = int(formula[end:i] or 1)\n top = stack.pop()\n # Add the count of each atom in the popped counter to the top counter in the stack\n for name, v in top.items():\n stack[-1][name] += v * mult\n # Update the current counter to the top counter in the stack\n count = stack[-1]\n else:\n # If the current character is not \'(\' or \')\', it\'s an atom\n # Find the end of the atom name\n start = i\n i += 1\n while i < n and formula[i].islower():\n i += 1\n # Get the atom name\n name = formula[start:i]\n # Find the end of the count that follows the atom name\n start = i\n while i < n and formula[i].isdigit():\n i += 1\n # Get the count, default to 1 if no count is provided\n mult = int(formula[start:i] or 1)\n # Add the count of the atom to the top counter in the stack\n stack[-1][name] += mult\n\n # Return the count of all atoms in the format specified in the problem\n return "".join(name + (str(count[name]) if count[name] > 1 else \'\') for name in sorted(count))\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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.\nInitialize i to 0, which will be used to iterate over the formula.\n\nStep 2:\nUse a while loop to go through each character in the formula.\n\nStep 3:\nIf the character at index i is an uppercase letter, it signifies the start of an atom name. Extract the full name (which could include subsequent lowercase letters). Store this name in elem.\n\nStep 4:\nIf the character at index i is a digit, extract the full number following it. This number is the count for the atom stored in elem. Add this count to the current dictionary (top of the stack).\nIf the atom is followed by another uppercase letter or a parenthesis without any digits, it means the atom count is 1. This case should be handled explicitly.\n\nStep 5:\nIf the character at index i is an opening parenthesis (, push a new dictionary onto the stack. This is because atoms inside the parentheses may have different counts.\nIf the character at index i is a closing parenthesis ), pop the top dictionary from the stack. If the parenthesis is followed by a number, multiply all values in the dictionary by this number. Then, merge this dictionary with the one just below it (the new top) on the stack.\n\nStep 6:\nOnce all characters in the formula have been processed, the top dictionary on the stack contains the counts of all atoms. Convert this dictionary into the desired format: atom names followed by their counts (if count > 1).\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n stack, elem, i = [{}], "", 0\n \n while i < len(formula):\n # Extract the full element name\n if formula[i].isupper():\n j = i + 1\n while j < len(formula) and formula[j].islower():\n j += 1\n elem = formula[i:j]\n i = j\n # If no digits follow the element, assign a count of 1\n if i == len(formula) or not formula[i].isdigit() and not formula[i].islower():\n stack[-1][elem] = stack[-1].get(elem, 0) + 1\n # Extract the count\n elif formula[i].isdigit():\n j = i\n while j < len(formula) and formula[j].isdigit():\n j += 1\n count = int(formula[i:j])\n stack[-1][elem] = stack[-1].get(elem, 0) + count\n i = j\n # Handle open parentheses by pushing a new dict\n elif formula[i] == \'(\':\n stack.append({})\n i += 1\n # Handle close parentheses by merging with the previous dict\n elif formula[i] == \')\':\n i += 1\n j = i\n while j < len(formula) and formula[j].isdigit():\n j += 1\n multiplier = int(formula[i:j] or 1)\n top = stack.pop()\n for elem, count in top.items():\n stack[-1][elem] = stack[-1].get(elem, 0) + count * multiplier\n i = j\n \n # Convert the result to the desired format\n atoms = sorted(stack[0].items())\n return \'\'.join([atom + (str(count) if count > 1 else \'\') for atom, count in atoms])\n\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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.\nInitialize i to 0, which will be used to iterate over the formula.\n\nStep 2:\nUse a while loop to go through each character in the formula.\n\nStep 3:\nIf the character at index i is an uppercase letter, it signifies the start of an atom name. Extract the full name (which could include subsequent lowercase letters). Store this name in elem.\n\nStep 4:\nIf the character at index i is a digit, extract the full number following it. This number is the count for the atom stored in elem. Add this count to the current dictionary (top of the stack).\nIf the atom is followed by another uppercase letter or a parenthesis without any digits, it means the atom count is 1. This case should be handled explicitly.\n\nStep 5:\nIf the character at index i is an opening parenthesis (, push a new dictionary onto the stack. This is because atoms inside the parentheses may have different counts.\nIf the character at index i is a closing parenthesis ), pop the top dictionary from the stack. If the parenthesis is followed by a number, multiply all values in the dictionary by this number. Then, merge this dictionary with the one just below it (the new top) on the stack.\n\nStep 6:\nOnce all characters in the formula have been processed, the top dictionary on the stack contains the counts of all atoms. Convert this dictionary into the desired format: atom names followed by their counts (if count > 1).\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n stack, elem, i = [{}], "", 0\n \n while i < len(formula):\n # Extract the full element name\n if formula[i].isupper():\n j = i + 1\n while j < len(formula) and formula[j].islower():\n j += 1\n elem = formula[i:j]\n i = j\n # If no digits follow the element, assign a count of 1\n if i == len(formula) or not formula[i].isdigit() and not formula[i].islower():\n stack[-1][elem] = stack[-1].get(elem, 0) + 1\n # Extract the count\n elif formula[i].isdigit():\n j = i\n while j < len(formula) and formula[j].isdigit():\n j += 1\n count = int(formula[i:j])\n stack[-1][elem] = stack[-1].get(elem, 0) + count\n i = j\n # Handle open parentheses by pushing a new dict\n elif formula[i] == \'(\':\n stack.append({})\n i += 1\n # Handle close parentheses by merging with the previous dict\n elif formula[i] == \')\':\n i += 1\n j = i\n while j < len(formula) and formula[j].isdigit():\n j += 1\n multiplier = int(formula[i:j] or 1)\n top = stack.pop()\n for elem, count in top.items():\n stack[-1][elem] = stack[-1].get(elem, 0) + count * multiplier\n i = j\n \n # Convert the result to the desired format\n atoms = sorted(stack[0].items())\n return \'\'.join([atom + (str(count) if count > 1 else \'\') for atom, count in atoms])\n\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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 c = i+c\n elif i == \')\':\n if c:\n if not stack:\n stack.append(int(c))\n else:\n top = stack[-1]\n stack.append(top*int(c))\n c = ""\n elif i==\'(\':\n if stack:\n stack.pop()\n elif i.islower():\n s = i + s\n else:\n s = i + s\n if c:\n if stack:\n count[s] += int(c)*stack[-1]\n else:\n count[s] += int(c)\n c = ""\n else:\n if stack:\n count[s] += stack[-1] \n else:\n count[s] += 1\n s = ""\n \n ans = ""\n for i in sorted(count):\n if count[i]>1:\n ans += i + str(count[i])\n else:\n ans += i\n \n return ans\n\n\n\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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 c = i+c\n elif i == \')\':\n if c:\n if not stack:\n stack.append(int(c))\n else:\n top = stack[-1]\n stack.append(top*int(c))\n c = ""\n elif i==\'(\':\n if stack:\n stack.pop()\n elif i.islower():\n s = i + s\n else:\n s = i + s\n if c:\n if stack:\n count[s] += int(c)*stack[-1]\n else:\n count[s] += int(c)\n c = ""\n else:\n if stack:\n count[s] += stack[-1] \n else:\n count[s] += 1\n s = ""\n \n ans = ""\n for i in sorted(count):\n if count[i]>1:\n ans += i + str(count[i])\n else:\n ans += i\n \n return ans\n\n\n\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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)$$ -->\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n stack = []\n res = ""\n i = 0\n\n while i < len(formula):\n char = formula[i]\n if char.islower():\n stack[-1][0] += char\n elif not char.isdigit():\n stack.append([char, 1])\n else:\n while i+1 < len(formula) and formula[i+1].isdigit():\n char += formula[i+1]\n i += 1\n if stack[-1][0] != ")":\n stack[-1][1] *= int(char)\n else:\n popped = []\n while stack[-1][0] != "(":\n c, cnt = stack.pop()\n cnt *= int(char)\n popped.append([c, cnt])\n stack.pop()\n stack += popped\n i += 1 \n stack.sort()\n prev = \'\'\n cnt = 0\n for char, num in stack:\n if char.isalpha():\n if char != prev:\n if prev != "":\n res += prev + (str(cnt) if cnt > 1 else "")\n prev = char\n cnt = num\n else:\n cnt += num\n res += prev + (str(cnt) if cnt > 1 else "")\n return res\n \n\n\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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)$$ -->\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n stack = []\n res = ""\n i = 0\n\n while i < len(formula):\n char = formula[i]\n if char.islower():\n stack[-1][0] += char\n elif not char.isdigit():\n stack.append([char, 1])\n else:\n while i+1 < len(formula) and formula[i+1].isdigit():\n char += formula[i+1]\n i += 1\n if stack[-1][0] != ")":\n stack[-1][1] *= int(char)\n else:\n popped = []\n while stack[-1][0] != "(":\n c, cnt = stack.pop()\n cnt *= int(char)\n popped.append([c, cnt])\n stack.pop()\n stack += popped\n i += 1 \n stack.sort()\n prev = \'\'\n cnt = 0\n for char, num in stack:\n if char.isalpha():\n if char != prev:\n if prev != "":\n res += prev + (str(cnt) if cnt > 1 else "")\n prev = char\n cnt = num\n else:\n cnt += num\n res += prev + (str(cnt) if cnt > 1 else "")\n return res\n \n\n\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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.\n stack, i=[], 0\n\n while i<len(formula):\n # If we find an upper case letter.\n if formula[i].isupper():\n element=formula[i]\n j=i+1\n # If the element symbol not yet finished (lower case letters).\n while j<len(formula) and formula[j].islower():\n element+=formula[j]\n j+=1\n # Get the number.\n num=\'\'\n while j<len(formula) and formula[j].isdigit():\n num+=formula[j]\n j+=1\n # If no number is mentioned, it is 1.\n num=1 if num==\'\' else int(num)\n\n # If top of the stack is a dictionary, add this element to it.\n if len(stack)>0 and type(stack[-1])==type({}):\n if element in stack[-1]:\n stack[-1][element]+=num\n else:\n stack[-1][element]=num\n # Or else, create a new one.\n else:\n stack.append({element: num})\n # Update i.\n i=j\n\n # If we find an open bracket.\n elif formula[i]==\'(\':\n # Add this to the stack.\n stack.append(\'(\')\n i+=1\n \n elif formula[i]==\')\':\n j=i+1\n # Get the number.\n num=\'\'\n while j<len(formula) and formula[j].isdigit():\n num+=formula[j]\n j+=1\n # If no number is mentioned, it is 1.\n num=1 if num==\'\' else int(num)\n # Get the top of the stack.\n top=stack.pop(-1)\n # Multiply by num.\n for k in top:\n top[k]*=num\n \n # If top of the stack is (. Since the formula is valid, this is always true.\n if len(stack)>0 and stack[-1]==\'(\':\n # Remove this from the stack.\n stack.pop(-1)\n # Check if the stack is empty or the top is not a dictionary.\n if len(stack)==0 or type(stack[-1])!=type({}):\n # Add this dictionary to the stack.\n stack.append(top)\n else:\n # Merge this dictionary with the top dictionary of the stack.\n main=stack[-1]\n for i in top:\n if i in main:\n main[i]+=top[i]\n else:\n main[i]=top[i]\n i=j \n\n # Stack now consists of only 1 element. Convert it into output.\n output=\'\'\n for i in sorted(stack[-1].keys()):\n if stack[-1][i]>1:\n output+=f"{i}{stack[-1][i]}"\n else:\n output+=i\n # Return output\n return output\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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.\n stack, i=[], 0\n\n while i<len(formula):\n # If we find an upper case letter.\n if formula[i].isupper():\n element=formula[i]\n j=i+1\n # If the element symbol not yet finished (lower case letters).\n while j<len(formula) and formula[j].islower():\n element+=formula[j]\n j+=1\n # Get the number.\n num=\'\'\n while j<len(formula) and formula[j].isdigit():\n num+=formula[j]\n j+=1\n # If no number is mentioned, it is 1.\n num=1 if num==\'\' else int(num)\n\n # If top of the stack is a dictionary, add this element to it.\n if len(stack)>0 and type(stack[-1])==type({}):\n if element in stack[-1]:\n stack[-1][element]+=num\n else:\n stack[-1][element]=num\n # Or else, create a new one.\n else:\n stack.append({element: num})\n # Update i.\n i=j\n\n # If we find an open bracket.\n elif formula[i]==\'(\':\n # Add this to the stack.\n stack.append(\'(\')\n i+=1\n \n elif formula[i]==\')\':\n j=i+1\n # Get the number.\n num=\'\'\n while j<len(formula) and formula[j].isdigit():\n num+=formula[j]\n j+=1\n # If no number is mentioned, it is 1.\n num=1 if num==\'\' else int(num)\n # Get the top of the stack.\n top=stack.pop(-1)\n # Multiply by num.\n for k in top:\n top[k]*=num\n \n # If top of the stack is (. Since the formula is valid, this is always true.\n if len(stack)>0 and stack[-1]==\'(\':\n # Remove this from the stack.\n stack.pop(-1)\n # Check if the stack is empty or the top is not a dictionary.\n if len(stack)==0 or type(stack[-1])!=type({}):\n # Add this dictionary to the stack.\n stack.append(top)\n else:\n # Merge this dictionary with the top dictionary of the stack.\n main=stack[-1]\n for i in top:\n if i in main:\n main[i]+=top[i]\n else:\n main[i]=top[i]\n i=j \n\n # Stack now consists of only 1 element. Convert it into output.\n output=\'\'\n for i in sorted(stack[-1].keys()):\n if stack[-1][i]>1:\n output+=f"{i}{stack[-1][i]}"\n else:\n output+=i\n # Return output\n return output\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
[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 subformula. Specifically, we can start by iterating through the formula character by character, and for each character, we can either add an element to the counter, multiply the counter by a number, or recursively parse a subformula enclosed in parentheses. By doing so, we can obtain the total count of atoms in the formula.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can define a helper function parse that takes an index i and returns a tuple containing the updated index and a Counter object that stores the count of atoms in the subformula starting from i. The parse function works as follows:\n\n1. We initialize a Counter object to store the count of atoms in the subformula.\n2. We iterate through the formula starting from index i.\n3. If the current character is an uppercase letter, we add a new element to the counter and update the index to the next character.\n4. If the current character is a digit, we update the count of the previous element in the counter and update the index to the next character.\n5. If the current character is an opening parenthesis, we recursively call the parse function to obtain the count of atoms in the subformula enclosed in the parentheses, and multiply the count by a number if there is one. We then update the index to the next character after the closing parenthesis.\n6. If the current character is a closing parenthesis or the end of the formula, we return the updated index and the Counter object.\n7. Finally, we call the parse function with the starting index of 0 and obtain the count of atoms in the entire formula. We then sort the elements in the counter and concatenate them into a string to obtain the final result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n def parse(i) -> tuple[int, Counter]:\n counter = Counter()\n while i < len(formula):\n if formula[i].isupper():\n el = formula[i]\n i += 1\n while i < len(formula) and formula[i].islower():\n el += formula[i]\n i += 1\n counter[el] += 1\n elif formula[i].isdigit():\n count = \'\'\n while i < len(formula) and formula[i].isdigit():\n count += formula[i]\n i += 1\n count = int(count or \'1\')\n counter[el] += count - 1\n elif formula[i] == \'(\':\n i, sub_count = parse(i+1)\n group_count = \'\'\n while i < len(formula) and formula[i].isdigit():\n group_count += formula[i]\n i += 1\n group_count = int(group_count or \'1\')\n for item, item_count in sub_count.items():\n counter[item] += group_count * item_count\n else:\n return i + 1, counter\n return i + 1, counter\n \n _, res = parse(0)\n return \'\'.join(el + str(res[el] if res[el] > 1 else \'\') for el in sorted(res))\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
[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 subformula. Specifically, we can start by iterating through the formula character by character, and for each character, we can either add an element to the counter, multiply the counter by a number, or recursively parse a subformula enclosed in parentheses. By doing so, we can obtain the total count of atoms in the formula.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can define a helper function parse that takes an index i and returns a tuple containing the updated index and a Counter object that stores the count of atoms in the subformula starting from i. The parse function works as follows:\n\n1. We initialize a Counter object to store the count of atoms in the subformula.\n2. We iterate through the formula starting from index i.\n3. If the current character is an uppercase letter, we add a new element to the counter and update the index to the next character.\n4. If the current character is a digit, we update the count of the previous element in the counter and update the index to the next character.\n5. If the current character is an opening parenthesis, we recursively call the parse function to obtain the count of atoms in the subformula enclosed in the parentheses, and multiply the count by a number if there is one. We then update the index to the next character after the closing parenthesis.\n6. If the current character is a closing parenthesis or the end of the formula, we return the updated index and the Counter object.\n7. Finally, we call the parse function with the starting index of 0 and obtain the count of atoms in the entire formula. We then sort the elements in the counter and concatenate them into a string to obtain the final result.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n def parse(i) -> tuple[int, Counter]:\n counter = Counter()\n while i < len(formula):\n if formula[i].isupper():\n el = formula[i]\n i += 1\n while i < len(formula) and formula[i].islower():\n el += formula[i]\n i += 1\n counter[el] += 1\n elif formula[i].isdigit():\n count = \'\'\n while i < len(formula) and formula[i].isdigit():\n count += formula[i]\n i += 1\n count = int(count or \'1\')\n counter[el] += count - 1\n elif formula[i] == \'(\':\n i, sub_count = parse(i+1)\n group_count = \'\'\n while i < len(formula) and formula[i].isdigit():\n group_count += formula[i]\n i += 1\n group_count = int(group_count or \'1\')\n for item, item_count in sub_count.items():\n counter[item] += group_count * item_count\n else:\n return i + 1, counter\n return i + 1, counter\n \n _, res = parse(0)\n return \'\'.join(el + str(res[el] if res[el] > 1 else \'\') for el in sorted(res))\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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)$$ -->\n\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def countOfAtoms(self, formula: str) -> str: \n self.i = 0\n self.formula = formula\n self.n = len(formula)\n count = self.plus()\n return "".join([el + str(count[el]) if count[el] > 1 else el for el in sorted(count)] )\n \n def plus(self):\n count = Counter()\n while self.i < self.n:\n multi = self.multiply() \n if not multi: break \n count += multi\n return count\n\n def element(self):\n p = None\n if self.i < self.n and self.formula[self.i] == "(":\n self.i += 1\n p = self.plus()\n return p\n if self.i < self.n and self.formula[self.i] == ")":\n self.i += 1\n return \n el = self.formula[self.i]\n self.i += 1\n while self.i < self.n and self.formula[self.i].islower():\n el += self.formula[self.i]\n self.i += 1\n return Counter({el: 1})\n\n def multiply(self):\n count = self.element()\n if count:\n times = self.number()\n for el in count:\n count[el] *= times\n return count\n\n def number(self):\n number = \'\'\n while self.i < self.n and self.formula[self.i].isdigit():\n number += self.formula[self.i] \n self.i += 1\n return int(number) if number else 1\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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)$$ -->\n\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def countOfAtoms(self, formula: str) -> str: \n self.i = 0\n self.formula = formula\n self.n = len(formula)\n count = self.plus()\n return "".join([el + str(count[el]) if count[el] > 1 else el for el in sorted(count)] )\n \n def plus(self):\n count = Counter()\n while self.i < self.n:\n multi = self.multiply() \n if not multi: break \n count += multi\n return count\n\n def element(self):\n p = None\n if self.i < self.n and self.formula[self.i] == "(":\n self.i += 1\n p = self.plus()\n return p\n if self.i < self.n and self.formula[self.i] == ")":\n self.i += 1\n return \n el = self.formula[self.i]\n self.i += 1\n while self.i < self.n and self.formula[self.i].islower():\n el += self.formula[self.i]\n self.i += 1\n return Counter({el: 1})\n\n def multiply(self):\n count = self.element()\n if count:\n times = self.number()\n for el in count:\n count[el] *= times\n return count\n\n def number(self):\n number = \'\'\n while self.i < self.n and self.formula[self.i].isdigit():\n number += self.formula[self.i] \n self.i += 1\n return int(number) if number else 1\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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 group or element based on whether the first char is `(`\n* Get the bounds of a group by finding the matching `)` to the opening `(`\n* An element will have either one or two alpha chars. The first must be uppercase, and if it has a second, the second must be lowercase\n* Get the bounds of a quantity by checking for consecutive numeric chars\n\n# Code\n```\nfrom collections import defaultdict \n\n\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n return count_of_atoms(formula)\n\n\ndef count_of_atoms(formula: str) -> str: \n formula = "(" + formula + ")"\n counts = defaultdict(int)\n _ = count_group(counts, formula, 0)\n return generate_count_string(counts)\n\n\n"""\nGiven counts of atoms, print them sorted with their counts. If the\ncount is 1, only print the atom.\n"""\ndef generate_count_string(counts: defaultdict(int)) -> str:\n atoms = sorted(counts.keys())\n return "".join([atom + str(counts[atom]) if counts[atom] > 1 else atom for atom in atoms])\n\n\n"""\nGiven a string and the index of \'(\', return the index of the matching \')\'.\n"""\ndef find_matching_parenthesis(s: str, open: int) -> int:\n if open >= len(s):\n return -1\n if s[open] != "(":\n return -1\n nested = 0\n for i in range(open + 1, len(s)):\n if s[i] == "(":\n nested += 1\n elif s[i] == ")":\n if nested == 0:\n return i\n nested -= 1\n return -1\n\n\n"""\nGiven a string and the last index of a group or atom name,\nreturn a tuple containing the value of the number and the index \nimmediately after the number.\n"""\ndef extract_quantity(s: str, close: int) -> tuple:\n i = close + 1\n if i >= len(s) or not s[i].isnumeric():\n return (1, i)\n\n while i < len(s) and s[i].isnumeric():\n i += 1\n return (int(s[close + 1 : i]), i)\n\n\n"""\nGiven a string and the first index of an atom, return a tuple of the atom\nand the index immediately after the atom\n"""\ndef extract_atom(s: str, start: int) -> tuple:\n if start + 1 <= len(s) and s[start + 1].islower():\n return (s[start : start + 2], start + 2)\n return (s[start : start + 1], start + 1)\n\n\n"""\nGiven a dict, string, and starting index, count the atoms in a given\ngroup and return the index immediately after the group.\n"""\ndef count_group(outer_counts: defaultdict(int), s: str, start: int) -> int:\n nested_counts = defaultdict(int)\n end = find_matching_parenthesis(s, start)\n \n # Loop over group to count the atoms (one atom or group at a time).\n i = start + 1\n while i < len(s) and i < end:\n if s[i] == "(":\n i = count_group(nested_counts, s, i)\n continue\n atom, i = extract_atom(s, i)\n count = 1\n if i < len(s) and s[i].isnumeric():\n count, i = extract_quantity(s, i - 1)\n nested_counts[atom] += count\n\n group_count, next_i = extract_quantity(s, end)\n for atom in nested_counts:\n outer_counts[atom] += (group_count * nested_counts[atom])\n return next_i\n\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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 group or element based on whether the first char is `(`\n* Get the bounds of a group by finding the matching `)` to the opening `(`\n* An element will have either one or two alpha chars. The first must be uppercase, and if it has a second, the second must be lowercase\n* Get the bounds of a quantity by checking for consecutive numeric chars\n\n# Code\n```\nfrom collections import defaultdict \n\n\nclass Solution:\n def countOfAtoms(self, formula: str) -> str:\n return count_of_atoms(formula)\n\n\ndef count_of_atoms(formula: str) -> str: \n formula = "(" + formula + ")"\n counts = defaultdict(int)\n _ = count_group(counts, formula, 0)\n return generate_count_string(counts)\n\n\n"""\nGiven counts of atoms, print them sorted with their counts. If the\ncount is 1, only print the atom.\n"""\ndef generate_count_string(counts: defaultdict(int)) -> str:\n atoms = sorted(counts.keys())\n return "".join([atom + str(counts[atom]) if counts[atom] > 1 else atom for atom in atoms])\n\n\n"""\nGiven a string and the index of \'(\', return the index of the matching \')\'.\n"""\ndef find_matching_parenthesis(s: str, open: int) -> int:\n if open >= len(s):\n return -1\n if s[open] != "(":\n return -1\n nested = 0\n for i in range(open + 1, len(s)):\n if s[i] == "(":\n nested += 1\n elif s[i] == ")":\n if nested == 0:\n return i\n nested -= 1\n return -1\n\n\n"""\nGiven a string and the last index of a group or atom name,\nreturn a tuple containing the value of the number and the index \nimmediately after the number.\n"""\ndef extract_quantity(s: str, close: int) -> tuple:\n i = close + 1\n if i >= len(s) or not s[i].isnumeric():\n return (1, i)\n\n while i < len(s) and s[i].isnumeric():\n i += 1\n return (int(s[close + 1 : i]), i)\n\n\n"""\nGiven a string and the first index of an atom, return a tuple of the atom\nand the index immediately after the atom\n"""\ndef extract_atom(s: str, start: int) -> tuple:\n if start + 1 <= len(s) and s[start + 1].islower():\n return (s[start : start + 2], start + 2)\n return (s[start : start + 1], start + 1)\n\n\n"""\nGiven a dict, string, and starting index, count the atoms in a given\ngroup and return the index immediately after the group.\n"""\ndef count_group(outer_counts: defaultdict(int), s: str, start: int) -> int:\n nested_counts = defaultdict(int)\n end = find_matching_parenthesis(s, start)\n \n # Loop over group to count the atoms (one atom or group at a time).\n i = start + 1\n while i < len(s) and i < end:\n if s[i] == "(":\n i = count_group(nested_counts, s, i)\n continue\n atom, i = extract_atom(s, i)\n count = 1\n if i < len(s) and s[i].isnumeric():\n count, i = extract_quantity(s, i - 1)\n nested_counts[atom] += count\n\n group_count, next_i = extract_quantity(s, end)\n for atom in nested_counts:\n outer_counts[atom] += (group_count * nested_counts[atom])\n return next_i\n\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 count is `1`, no digits will follow.
* For example, `"H2O "` and `"H2O2 "` are possible, but `"H1O2 "` is impossible.
Two formulas are concatenated together to produce another formula.
* For example, `"H2O2He3Mg4 "` is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula.
* For example, `"(H2O2) "` and `"(H2O2)3 "` are formulas.
Return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than `1`), followed by the second name (in sorted order), followed by its count (if that count is more than `1`), and so on.
The test cases are generated so that all the values in the output fit in a **32-bit** integer.
**Example 1:**
**Input:** formula = "H2O "
**Output:** "H2O "
**Explanation:** The count of elements are {'H': 2, 'O': 1}.
**Example 2:**
**Input:** formula = "Mg(OH)2 "
**Output:** "H2MgO2 "
**Explanation:** The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
**Example 3:**
**Input:** formula = "K4(ON(SO3)2)2 "
**Output:** "K4N2O14S4 "
**Explanation:** The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
**Constraints:**
* `1 <= formula.length <= 1000`
* `formula` consists of English letters, digits, `'('`, and `')'`.
* `formula` is always valid. | 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 get the name, and add that (plus the multiplicity if there is one.) |
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 selfDividingNumbers(self, left: int, right: int) -> List[int]:\n answer = []\n for number in range(left, right + 1):\n string = str(number)\n if "0" in string:\n continue\n answer.append(number)\n for i in string:\n if number % int(i) != 0:\n answer.pop()\n break\n return answer \n\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 list of all the **self-dividing numbers** in the range_ `[left, right]`.
**Example 1:**
**Input:** left = 1, right = 22
**Output:** \[1,2,3,4,5,6,7,8,9,11,12,15,22\]
**Example 2:**
**Input:** left = 47, right = 85
**Output:** \[48,55,66,77\]
**Constraints:**
* `1 <= left <= right <= 104` | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n res=[]\n for i in range(left,right+1 ):\n ch=True\n for j in str(i):\n if j!=\'0\':\n if i%int(j)!=0:\n ch=False\n else:\n ch=False\n break \n if ch:\n res.append(i)\n return res\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 list of all the **self-dividing numbers** in the range_ `[left, right]`.
**Example 1:**
**Input:** left = 1, right = 22
**Output:** \[1,2,3,4,5,6,7,8,9,11,12,15,22\]
**Example 2:**
**Input:** left = 47, right = 85
**Output:** \[48,55,66,77\]
**Constraints:**
* `1 <= left <= right <= 104` | 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 list of all the **self-dividing numbers** in the range_ `[left, right]`.
**Example 1:**
**Input:** left = 1, right = 22
**Output:** \[1,2,3,4,5,6,7,8,9,11,12,15,22\]
**Example 2:**
**Input:** left = 47, right = 85
**Output:** \[48,55,66,77\]
**Constraints:**
* `1 <= left <= right <= 104` | 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 return False\n return True\n res = []\n for n in range(left,right+1):\n if selfdivision(n):\n res.append(n)\n return res\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 list of all the **self-dividing numbers** in the range_ `[left, right]`.
**Example 1:**
**Input:** left = 1, right = 22
**Output:** \[1,2,3,4,5,6,7,8,9,11,12,15,22\]
**Example 2:**
**Input:** left = 47, right = 85
**Output:** \[48,55,66,77\]
**Constraints:**
* `1 <= left <= right <= 104` | 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]. \nNow, initiated a flag element to check whether the number in the range is a self dividing number or not. Now, we checked if the number contanins zero, then it is not a self dividing number. \nIf it doestn\'t contain zero, then checked whether that number can be divided fully by all its digits, if yes then we append the number in the list.\nThen, finally we have returned the list.\n\n# Code\n```\nclass Solution(object):\n def selfDividingNumbers(self, left, right):\n """\n :type left: int\n :type right: int\n :rtype: List[int]\n """\n l=[]\n for i in range(left,right+1):\n fl,a=0,i\n if \'0\' in str(i):\n fl=1\n""" Please Upvote and support """\n else:\n while a!=0:\n if i%(a%10)!=0:\n fl=1\n break\n a=a//10\n if fl==0:\n l.append(i)\n return l\n\n``` | 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 list of all the **self-dividing numbers** in the range_ `[left, right]`.
**Example 1:**
**Input:** left = 1, right = 22
**Output:** \[1,2,3,4,5,6,7,8,9,11,12,15,22\]
**Example 2:**
**Input:** left = 47, right = 85
**Output:** \[48,55,66,77\]
**Constraints:**
* `1 <= left <= right <= 104` | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def selfDividingNumbers(self, left: int, right: int) -> List[int]:\n list1=[]\n count=0\n for i in range(left,right+1):\n count=0\n s=str(i)\n for j in s:\n j=int(j)\n if j!=0 and i%j==0:\n count+=1\n if count==len(s):\n list1.append(i)\n return list1\n\n \n\n\n\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 list of all the **self-dividing numbers** in the range_ `[left, right]`.
**Example 1:**
**Input:** left = 1, right = 22
**Output:** \[1,2,3,4,5,6,7,8,9,11,12,15,22\]
**Example 2:**
**Input:** left = 47, right = 85
**Output:** \[48,55,66,77\]
**Constraints:**
* `1 <= left <= right <= 104` | 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# Complexity 1\n- Time complexity: $$O(n*log(n))$$ for n bookings.\n- Space complexity: $$O(n)$$.\n\n# Code 1\n```\nfrom sortedcontainers import SortedList\n\n\nSTART = 0\nEND = 1\n\nclass MyCalendar:\n def __init__(self):\n self.booked = SortedList()\n\n\n def book(self, start: int, end: int) -> bool:\n if not self.booked:\n self.booked.add((start, end))\n return True\n \n # Check most left case\n left = self.booked[0]\n if end <= left[END]:\n if end <= left[START]:\n self.booked.add((start, end))\n return True\n return False\n \n # Check most right case\n right = self.booked[-1]\n if start >= right[START]:\n if start >= right[END]:\n self.booked.add((start, end))\n return True\n return False\n \n # Check middle case\n l, r = 0, len(self.booked)-1\n while l <= r:\n mid = (l + r)//2\n if self.booked[mid][START] <= start < self.booked[mid+1][START]:\n if self.booked[mid][END] <= start and end <= self.booked[mid+1][START]:\n self.booked.add((start, end))\n return True\n return False\n elif self.booked[mid][START] <= start:\n l = mid + 1\n else:\n r = mid - 1\n```\n\n\n# Approach 2\nAs in **Approach 1** we use binary search. But it is implemented with method ```bisect_right``` of ```SortedList``` - that makes solution more concise.\n\n# Complexity 2\n- Time complexity: $$O(n*log(n))$$ for n bookings.\n- Space complexity: $$O(n)$$.\n\n# Code 2\n```\nfrom sortedcontainers import SortedList\n\n\nSTART = 0\nEND = 1\n\nclass MyCalendar:\n def __init__(self):\n self.booked = SortedList()\n\n\n def book(self, start: int, end: int) -> bool:\n index = self.booked.bisect_right((start, end))\n if index > 0 and start < self.booked[index-1][END]:\n # Collision with previous interval\n return False\n elif index < len(self.booked) and self.booked[index][START] < end:\n # Collision with next interval\n return False\n\n self.booked.add((start, end))\n\n return True\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` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`.
Implement the `MyCalendar` class:
* `MyCalendar()` Initializes the calendar object.
* `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar.
**Example 1:**
**Input**
\[ "MyCalendar ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\]
**Output**
\[null, true, false, true\]
**Explanation**
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
**Constraints:**
* `0 <= start < end <= 109`
* At most `1000` calls will be made to `book`. | 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 node) with event and find the right place to insert\n\n# Code\n```\nclass Node:\n def __init__(self, start, end):\n # create root node\n self.start = start\n self.end = end\n # at the first time the left child and right child is None\n self.left = None\n self.right = None\n\n def insert(self, node):\n if node.start >= self.end:\n if not self.right:\n self.right = node\n return True\n return self.right.insert(node)\n elif node.end <= self.start:\n if not self.left:\n self.left = node\n return True\n return self.left.insert(node)\n else:\n return False\n\nclass MyCalendar(object):\n def __init__(self):\n self.root = None\n\n def book(self, start, end):\n if self.root is None:\n self.root = Node(start, end)\n return True\n return self.root.insert(Node(start, end))\n \n\n\n# Your MyCalendar object will be instantiated and called as such:\n# obj = MyCalendar()\n# param_1 = obj.book(start,end)\n``` | 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` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`.
Implement the `MyCalendar` class:
* `MyCalendar()` Initializes the calendar object.
* `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar.
**Example 1:**
**Input**
\[ "MyCalendar ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\]
**Output**
\[null, true, false, true\]
**Explanation**
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
**Constraints:**
* `0 <= start < end <= 109`
* At most `1000` calls will be made to `book`. | 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 not\n def check_booking(self, start, end):\n for x, y in self.booked:\n \n # invalid if start in [x, y-1] or end in [x+1, y]\n if (start >= x and start < y) or (end > x and end <= y): \n return False\n \n # invalid if already booked period is within the new booking\n if x > start and y < end:\n return False\n return True\n \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` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`.
Implement the `MyCalendar` class:
* `MyCalendar()` Initializes the calendar object.
* `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar.
**Example 1:**
**Input**
\[ "MyCalendar ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\]
**Output**
\[null, true, false, true\]
**Explanation**
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
**Constraints:**
* `0 <= start < end <= 109`
* At most `1000` calls will be made to `book`. | 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 if l==r else dp(l+1,r)+2\n\n return res %1_000_000_007\n\n return dp(0,len(s))\n```\n[https://leetcode.com/problems/count-different-palindromic-subsequences/submissions/1044092367/?submissionId=1044080869](http://)\n\n\n\nI could be wrong, but I think that time complexity is *O*(*N*^2) and space complexity is *O*(*N*^2), in which *N* ~ `len(s)`. | 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.
Two sequences `a1, a2, ...` and `b1, b2, ...` are different if there is some `i` for which `ai != bi`.
**Example 1:**
**Input:** s = "bccb "
**Output:** 6
**Explanation:** The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.
**Example 2:**
**Input:** s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba "
**Output:** 104860361
**Explanation:** There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.
**Constraints:**
* `1 <= s.length <= 1000`
* `s[i]` is either `'a'`, `'b'`, `'c'`, or `'d'`. | 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. -->\nThe approach I will take is to use a 2D dp array where dp[i][j] represents the number of unique palindromic subsequences in the substring from index i to j in the given string. We will fill the dp array using a nested loop, starting from the bottom right corner and moving towards the top left corner. At each index, we will check if the characters at the current indices (i and j) are the same. If they are the same, we will check for the presence of any other identical characters between these two indices, and adjust our dp value accordingly. If the characters are not the same, we will simply add the dp values at the next indices (i+1, j) and (i, j-1) and subtract the dp value at the next indices (i+1, j-1) to avoid double counting.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nAs we are using a nested loop to fill a 2D dp array of size n*n, the time complexity is O(n^2)\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nAs we are using a 2D dp array of size n*n to store the number of unique palindromic subsequences, the space complexity is O(n^2)\n# Code\n```\nclass Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n n = len(s)\n mod = 10**9 + 7\n dp = [[0] * n for _ in range(n)]\n for i in range(n):\n dp[i][i] = 1\n for i in range(n - 1, -1, -1):\n for j in range(i + 1, n):\n if s[i] == s[j]:\n left, right = i + 1, j - 1\n while left <= right and s[left] != s[i]:\n left += 1\n while left <= right and s[right] != s[i]:\n right -= 1\n if left > right:\n dp[i][j] = dp[i + 1][j - 1] * 2 + 2\n elif left == right:\n dp[i][j] = dp[i + 1][j - 1] * 2 + 1\n else:\n dp[i][j] = dp[i + 1][j - 1] * 2 - dp[left + 1][right - 1]\n else:\n dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]\n dp[i][j] = (dp[i][j] + mod) % mod\n return dp[0][n - 1]\n``` | 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.
Two sequences `a1, a2, ...` and `b1, b2, ...` are different if there is some `i` for which `ai != bi`.
**Example 1:**
**Input:** s = "bccb "
**Output:** 6
**Explanation:** The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.
**Example 2:**
**Input:** s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba "
**Output:** 104860361
**Explanation:** There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.
**Constraints:**
* `1 <= s.length <= 1000`
* `s[i]` is either `'a'`, `'b'`, `'c'`, or `'d'`. | 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, j) is already computed (memoized), it\'s returned directly to avoid re-computation.\n\nRecursive Case:\nIf s[i] == s[j], it means the two ends of the current substring are the same.\nIn this case, find the next occurrence of s[i] after i and the previous occurrence of s[j] before j. These are represented by l and r, respectively.\nIf l > r, it means there are no characters the same as s[i] or s[j] between i and j. So, the count is 2 * helper(i+1, j-1) + 2. The additional 2 is for counting the subsequences formed by only s[i] and the one formed by both s[i] and s[j].\nIf l == r, it means there\'s only one occurrence of the character. So, the count becomes 2 * helper(i+1, j-1) + 1.\nOtherwise, there are at least two occurrences of the character between i and j. In this case, we need to subtract the palindromic subsequences counted in between l and r to avoid over-counting.\nIf s[i] != s[j], the count becomes the sum of palindromic subsequences in the substring (i+1, j) and the substring (i, j-1). We subtract the count from substring (i+1, j-1) to avoid counting the same subsequences twice.\n\nMemoization:\nBefore returning the count, we store it in the memo dictionary to avoid redundant computations in future calls.\n\nReturn:\nThe function returns the count of different non-empty palindromic subsequences for the substring represented by indices i and j.\n\n# Complexity\n- Time complexity:\nO(n^3)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```\nclass Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n MOD = 10**9 + 7\n memo = {}\n \n def helper(i, j):\n if i > j: return 0\n if i == j: return 1\n if (i, j) in memo: return memo[(i, j)]\n \n if s[i] == s[j]:\n l, r = i + 1, j - 1\n while l <= r and s[l] != s[i]: l += 1\n while l <= r and s[r] != s[j]: r -= 1\n if l > r:\n count = 2 * helper(i+1, j-1) + 2\n elif l == r:\n count = 2 * helper(i+1, j-1) + 1\n else:\n count = 2 * helper(i+1, j-1) - helper(l+1, r-1)\n else:\n count = helper(i+1, j) + helper(i, j-1) - helper(i+1, j-1)\n \n memo[(i, j)] = count % MOD\n return memo[(i, j)]\n \n return helper(0, len(s)-1)\n\n```\nSecond version:\nTime and Space complexity O(n^2)\n```\nclass Solution:\n def countPalindromicSubsequences(self, s: str) -> int:\n MOD = 10**9 + 7\n memo = {}\n n = len(s)\n\n # Find the next occurrence of each character\n nexts = {ch: [-1] * n for ch in \'abcd\'}\n next_map = {ch: -1 for ch in \'abcd\'}\n for i in range(n-1, -1, -1):\n next_map[s[i]] = i\n for ch in \'abcd\':\n nexts[ch][i] = next_map[ch]\n\n # Find the previous occurrence of each character\n prevs = {ch: [-1] * n for ch in \'abcd\'}\n prev_map = {ch: -1 for ch in \'abcd\'}\n for i in range(n):\n prev_map[s[i]] = i\n for ch in \'abcd\':\n prevs[ch][i] = prev_map[ch]\n\n def helper(i, j):\n if i > j: return 0\n if i == j: return 1\n if (i, j) in memo: return memo[(i, j)]\n\n ans = 0\n for ch in \'abcd\':\n ni, nj = nexts[ch][i], prevs[ch][j]\n if ni != -1 and ni <= j:\n ans += 1 # for ch itself\n if nj != -1 and nj > ni:\n ans += 1 # for ch + ch\n ans += helper(ni+1, nj-1) # between the two ch\'s\n ans %= MOD\n memo[(i, j)] = ans\n return ans\n\n return helper(0, n-1)\n``` | 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.
Two sequences `a1, a2, ...` and `b1, b2, ...` are different if there is some `i` for which `ai != bi`.
**Example 1:**
**Input:** s = "bccb "
**Output:** 6
**Explanation:** The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.
**Example 2:**
**Input:** s = "abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba "
**Output:** 104860361
**Explanation:** There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 109 + 7.
**Constraints:**
* `1 <= s.length <= 1000`
* `s[i]` is either `'a'`, `'b'`, `'c'`, or `'d'`. | 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 if start < e and end > s:\n return False\n for booking in self.single_booked: \n s, e = booking[:]\n if start < e and end > s:\n self.double_booked.append((max(s, start), min(e, end)))\n self.single_booked.append((start, end)) \n return True\n \n \n# Your MyCalendarTwo object will be instantiated and called as such:\n# obj = MyCalendarTwo()\n# param_1 = obj.book(start,end)\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 integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`.
Implement the `MyCalendarTwo` class:
* `MyCalendarTwo()` Initializes the calendar object.
* `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **triple booking**. Otherwise, return `false` and do not add the event to the calendar.
**Example 1:**
**Input**
\[ "MyCalendarTwo ", "book ", "book ", "book ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\]
**Output**
\[null, true, true, true, false, true, true\]
**Explanation**
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked.
myCalendarTwo.book(50, 60); // return True, The event can be booked.
myCalendarTwo.book(10, 40); // return True, The event can be double booked.
myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in \[25, 40) will be double booked with the third event, the time \[40, 50) will be single booked, and the time \[50, 55) will be double booked with the second event.
**Constraints:**
* `0 <= start < end <= 109`
* At most `1000` calls will be made to `book`. | 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 __init__(self):\n self.calendar = []\n self.overlaps = []\n```\n```\ndef book(self, start: int, end: int) -> bool:\n```\nThis method is used to book an event between the start and end times.\n\n```\nfor i, j in self.overlaps:\n if start < j and end > i:\n return False\n```\n\nHere, the method checks the new event against all the current double bookings (overlaps). If there is an overlap, this new booking would cause a triple booking, so the method returns False.\n\n```\nfor i, j in self.calendar:\n if start < j and end > i:\n self.overlaps.append((max(start, i), min(end, j)))\n```\nIn this part, the method checks the new event against all previously booked events. If there is an overlap with any of the previously booked events, this overlap is added to the overlaps list as it represents a double booking.\n\n```\nself.calendar.append((start, end))\nreturn True\n```\nLastly, the new event is added to the calendar list and the method returns True indicating that the event was successfully booked.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass MyCalendarTwo:\n\n def __init__(self):\n self.calendar = []\n self.overlaps = []\n\n def book(self, start: int, end: int) -> bool:\n\n for i, j in self.overlaps:\n if start < j and end > i:\n return False\n \n\n for i, j in self.calendar:\n if start < j and end > i:\n self.overlaps.append((max(start, i), min(end, j)))\n \n\n self.calendar.append((start, end))\n return True\n\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 integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`.
Implement the `MyCalendarTwo` class:
* `MyCalendarTwo()` Initializes the calendar object.
* `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **triple booking**. Otherwise, return `false` and do not add the event to the calendar.
**Example 1:**
**Input**
\[ "MyCalendarTwo ", "book ", "book ", "book ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\]
**Output**
\[null, true, true, true, false, true, true\]
**Explanation**
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked.
myCalendarTwo.book(50, 60); // return True, The event can be booked.
myCalendarTwo.book(10, 40); // return True, The event can be double booked.
myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in \[25, 40) will be double booked with the third event, the time \[40, 50) will be single booked, and the time \[50, 55) will be double booked with the second event.
**Constraints:**
* `0 <= start < end <= 109`
* At most `1000` calls will be made to `book`. | 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 if l % 2:\n # we may create empty interval where s == intervals[l]\n if intervals[l] != s:\n intersection.append(s)\n else:\n l = l + 1\n\n intersection += intervals[l:r]\n\n if r % 2:\n # we may create empty interval where e == intervals[r-1]\n if intervals[r-1] != e:\n intersection.append(e)\n else:\n intersection.pop()\n\n return intersection\n \n def add(self, intervals, s, e):\n\n l = bisect.bisect_left(intervals, s)\n r = bisect.bisect_right(intervals, e)\n \n new = []\n if not l % 2:\n new.append(s)\n \n if not r % 2:\n new.append(e)\n\n intervals[l:r] = new\n\n def book(self, start: int, end: int) -> bool:\n\n if self.intersection(self.double_booked, start, end):\n return False\n \n intersection = self.intersection(self.single_booked, start, end)\n\n if intersection:\n for i in range(len(intersection) // 2):\n i1 = intersection[2*i]\n i2 = intersection[2*i+1]\n self.add(self.double_booked, i1, i2)\n\n self.add(self.single_booked, start, end)\n\n return True\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 integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`.
Implement the `MyCalendarTwo` class:
* `MyCalendarTwo()` Initializes the calendar object.
* `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **triple booking**. Otherwise, return `false` and do not add the event to the calendar.
**Example 1:**
**Input**
\[ "MyCalendarTwo ", "book ", "book ", "book ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\]
**Output**
\[null, true, true, true, false, true, true\]
**Explanation**
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked.
myCalendarTwo.book(50, 60); // return True, The event can be booked.
myCalendarTwo.book(10, 40); // return True, The event can be double booked.
myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in \[25, 40) will be double booked with the third event, the time \[40, 50) will be single booked, and the time \[50, 55) will be double booked with the second event.
**Constraints:**
* `0 <= start < end <= 109`
* At most `1000` calls will be made to `book`. | 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) {\n if(startTime >= endTime) return 0;\n if(startTime >= end) {\n if(right) return right->insert(startTime, endTime);\n right = new SegmentTreeNode(startTime, endTime);\n } else if(endTime <= start) {\n if(left) return left->insert(startTime, endTime);\n left = new SegmentTreeNode(startTime, endTime);\n } else {\n int x1 = min(startTime, start);\n int x2 = max(startTime, start);\n int y1 = min(endTime, end);\n int y2 = max(endTime, end);\n overlap++;\n int ret = overlap;\n if(end > endTime) {\n SegmentTreeNode *newRight = new SegmentTreeNode(y1, y2);\n newRight->overlap = overlap - 1;\n newRight->right = right;\n right = newRight;\n } else {\n ret = max(insert(y1, y2), ret);\n }\n if(start < startTime) {\n SegmentTreeNode *newLeft = new SegmentTreeNode(x1, x2);\n newLeft->overlap = overlap - 1;\n newLeft->left = left;\n left = newLeft;\n } else {\n ret = max(insert(x1, x2), ret);\n }\n start = x2;\n end = y1;\n return ret;\n }\n return 0;\n }\n};\nclass MyCalendarThree {\npublic:\n SegmentTreeNode *root;\n int ret;\n\n MyCalendarThree() {\n root = new SegmentTreeNode(-1, INT_MAX);\n ret = 0;\n }\n int book(int startTime, int endTime) {\n SegmentTreeNode *node = new SegmentTreeNode(startTime, endTime);\n\n int overlap = root->insert(startTime, endTime);\n ret = max(ret, overlap);\n\n return ret;\n }\n};\n```\n\n```Python3 []\nclass MyCalendarThree:\n def __init__(self):\n self.events_scheduled = [[0, 0]]\n self.max_overlap = 0\n\n def book(self, start:int, end:int) -> int:\n events = self.events_scheduled\n s = bisect_left(events, [start, 1])\n e = bisect_left(events, [end, 0])\n\n if s == len(events) or events[s][0] != start:\n events.insert(s, [start, events[s-1][1]])\n e += 1\n\n if e == len(events) or events[e][0] != end:\n events.insert(e, [end, events[e-1][1]])\n\n best = self.max_overlap\n for i in range(s, e):\n overlap = events[i][1] + 1\n best = max(best, overlap)\n events[i][1] = overlap\n \n self.max_overlap = max(self.max_overlap, best)\n return best\n```\n\n```Java []\nclass TreeNode {\n int start;\n int end;\n int count;\n TreeNode left;\n TreeNode right;\n public TreeNode(int start, int end, int count) {\n this.start = start;\n this.end = end;\n this.count = count;\n }\n}\nclass MyCalendarThree {\n private int max = 0;\n TreeNode root;\n public MyCalendarThree() {\n this.root = null;\n }\n public int book(int start, int end) {\n root = dfs(root, start, end, 1);\n return max;\n }\n private TreeNode dfs(TreeNode root, int start, int end, int count) {\n if(root == null) {\n max = Math.max(max, count);\n return new TreeNode(start, end, count);\n }else if(root.start >= end) {\n root.left = dfs(root.left, start, end, count);\n }else if(root.end <= start) {\n root.right = dfs(root.right, start, end, count);\n }else {\n int startMin = Math.min(root.start, start);\n int startMax = Math.max(root.start, start);\n int endMin = Math.min(root.end, end);\n int endMax = Math.max(root.end, end);\n if(startMin < startMax) {\n root.left = dfs(root.left, startMin, startMax, startMin == root.start ? root.count : count);\n }\n if(endMin < endMax) {\n root.right = dfs(root.right, endMin, endMax, endMax == root.end ? root.count : count);\n }\n root.count += count;\n root.start = startMax;\n root.end = endMin;\n max = Math.max(root.count, max);\n }\n return root;\n }\n}\n```\n | 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 `MyCalendarThree` class:
* `MyCalendarThree()` Initializes the object.
* `int book(int startTime, int endTime)` Returns an integer `k` representing the largest integer such that there exists a `k`\-booking in the calendar.
**Example 1:**
**Input**
\[ "MyCalendarThree ", "book ", "book ", "book ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\]
**Output**
\[null, 1, 1, 2, 3, 3, 3\]
**Explanation**
MyCalendarThree myCalendarThree = new MyCalendarThree();
myCalendarThree.book(10, 20); // return 1
myCalendarThree.book(50, 60); // return 1
myCalendarThree.book(10, 40); // return 2
myCalendarThree.book(5, 15); // return 3
myCalendarThree.book(5, 10); // return 3
myCalendarThree.book(25, 55); // return 3
**Constraints:**
* `0 <= startTime < endTime <= 109`
* At most `400` calls will be made to `book`. | 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 concurrent ongoing event at any time.\n\n\n# Code\n```\nfrom sortedcontainers import SortedDict\nfrom itertools import accumulate\nclass MyCalendarThree:\n \n def __init__(self):\n self.event = SortedDict()\n\n def book(self, start: int, end: int) -> int:\n \n # +1 added in event\n self.event[start] = self.event.get(start, 0) + 1\n # -1 deducted in event\n self.event[end] = self.event.get(end, 0) - 1\n\n return max(accumulate(self.event.values()))\n """\n\t\t# Below code is same as :- max(accumulate(self.event.values()))\n curr = best = 0\n for num in self.event.values():\n curr += num\n best = max(best, curr)\n return best"""\n```\n\n**If You like the Solution, Don\'t Forget To UpVote Me, Please UpVote! \uD83D\uDE4F\nRuntime: 850 ms, faster than 84.82% of Python3 online submissions for My Calendar III.\nMemory Usage: 14.9 MB, less than 24.31% of Python3 online submissions for My Calendar III.** | 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 `MyCalendarThree` class:
* `MyCalendarThree()` Initializes the object.
* `int book(int startTime, int endTime)` Returns an integer `k` representing the largest integer such that there exists a `k`\-booking in the calendar.
**Example 1:**
**Input**
\[ "MyCalendarThree ", "book ", "book ", "book ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\]
**Output**
\[null, 1, 1, 2, 3, 3, 3\]
**Explanation**
MyCalendarThree myCalendarThree = new MyCalendarThree();
myCalendarThree.book(10, 20); // return 1
myCalendarThree.book(50, 60); // return 1
myCalendarThree.book(10, 40); // return 2
myCalendarThree.book(5, 15); // return 3
myCalendarThree.book(5, 10); // return 3
myCalendarThree.book(25, 55); // return 3
**Constraints:**
* `0 <= startTime < endTime <= 109`
* At most `400` calls will be made to `book`. | 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.