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 |
|---|---|---|---|---|---|---|---|
Python 3: Hashmap Solution - O(N) Time Complexity | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
Python 3: Hashmap Solution - O(N) Time Complexity | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
0(n) Run Time Solution | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
0(n) Run Time Solution | swap-for-longest-repeated-character-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
[Python3] Run-Length Solution | swap-for-longest-repeated-character-substring | 0 | 1 | # Code\n```\nclass Solution:\n def maxRepOpt1(self, text: str) -> int:\n chCnt = [0]*26\n for ch in text:\n chCnt[ord(ch)-ord(\'a\')]+=1\n \n runLength = []\n ans = 1\n prev = \'$\'\n cnt = 1\n for ch in text:\n if prev != ch:\n ... | 0 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
[Python3] Run-Length Solution | swap-for-longest-repeated-character-substring | 0 | 1 | # Code\n```\nclass Solution:\n def maxRepOpt1(self, text: str) -> int:\n chCnt = [0]*26\n for ch in text:\n chCnt[ord(ch)-ord(\'a\')]+=1\n \n runLength = []\n ans = 1\n prev = \'$\'\n cnt = 1\n for ch in text:\n if prev != ch:\n ... | 0 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
Python O(n) approach using spans. | swap-for-longest-repeated-character-substring | 0 | 1 | \n# Code\n```\nclass Solution:\n def maxRepOpt1(self, text: str) -> int:\n p = text[0]\n rec = dict()\n\n # Get spans \n left, right = 0, 1\n for i_, c in enumerate(text[1:]+\' \'):\n i = i_ + 1\n if c == p:\n right += 1\n else:\n ... | 0 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
Python O(n) approach using spans. | swap-for-longest-repeated-character-substring | 0 | 1 | \n# Code\n```\nclass Solution:\n def maxRepOpt1(self, text: str) -> int:\n p = text[0]\n rec = dict()\n\n # Get spans \n left, right = 0, 1\n for i_, c in enumerate(text[1:]+\' \'):\n i = i_ + 1\n if c == p:\n right += 1\n else:\n ... | 0 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
Python Groupby | swap-for-longest-repeated-character-substring | 0 | 1 | # Code\n```\nclass Solution:\n def maxRepOpt1(self, S):\n # We get the group\'s key and length first, e.g. \'aaabaaa\' -> [[a , 3], [b, 1], [a, 3]\n A = [[c, len(list(g))] for c, g in itertools.groupby(S)]\n # We also generate a count dict for easy look up e.g. \'aaabaaa\' -> {a: 6, b: 1}\n ... | 0 | You are given a string `text`. You can swap two of the characters in the `text`.
Return _the length of the longest substring with repeated characters_.
**Example 1:**
**Input:** text = "ababa "
**Output:** 3
**Explanation:** We can swap the first 'b' with the last 'a', or the last 'b' with the first 'a'. Then, the ... | Split the string into words, then look at adjacent triples of words. |
Python Groupby | swap-for-longest-repeated-character-substring | 0 | 1 | # Code\n```\nclass Solution:\n def maxRepOpt1(self, S):\n # We get the group\'s key and length first, e.g. \'aaabaaa\' -> [[a , 3], [b, 1], [a, 3]\n A = [[c, len(list(g))] for c, g in itertools.groupby(S)]\n # We also generate a count dict for easy look up e.g. \'aaabaaa\' -> {a: 6, b: 1}\n ... | 0 | Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode... | There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases. |
Python (Simple Maths) | online-majority-element-in-subarray | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Design a data structure that efficiently finds the **majority element** of a given subarray.
The **majority element** of a subarray is an element that occurs `threshold` times or more in the subarray.
Implementing the `MajorityChecker` class:
* `MajorityChecker(int[] arr)` Initializes the instance of the class wit... | Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient. |
Python (Simple Maths) | online-majority-element-in-subarray | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_.
**Example 1:**
**Input:** nums = \[3,6,5,1,8\]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
**Example 2:**
**Input:** nums = \... | What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper n... |
Python O(logn) with explanation | online-majority-element-in-subarray | 0 | 1 | ## Intuition\nLet\'s imagine that we\'re solving a simpler problem. Write a class that gets initialized with an array `num` and then calls `verify_num_threshold(left: int, right: int, num: int, threshold: int)`. \n#### PART 1: Verify Candidate [O(logn)]\nOur function should return `true` if `num` occurs `>= threshold` ... | 5 | Design a data structure that efficiently finds the **majority element** of a given subarray.
The **majority element** of a subarray is an element that occurs `threshold` times or more in the subarray.
Implementing the `MajorityChecker` class:
* `MajorityChecker(int[] arr)` Initializes the instance of the class wit... | Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient. |
Python O(logn) with explanation | online-majority-element-in-subarray | 0 | 1 | ## Intuition\nLet\'s imagine that we\'re solving a simpler problem. Write a class that gets initialized with an array `num` and then calls `verify_num_threshold(left: int, right: int, num: int, threshold: int)`. \n#### PART 1: Verify Candidate [O(logn)]\nOur function should return `true` if `num` occurs `>= threshold` ... | 5 | Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_.
**Example 1:**
**Input:** nums = \[3,6,5,1,8\]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
**Example 2:**
**Input:** nums = \... | What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper n... |
Naïve working solution in Python | online-majority-element-in-subarray | 0 | 1 | # Approach\nCache the counter for subarrays.\n\n# Code\n```\nclass MajorityChecker:\n\n def __init__(self, arr: List[int]):\n self.arr = arr\n \n @functools.cache\n def sub_arr_ctr(self, left: int, right: int):\n return collections.Counter(self.arr[left:right+1])\n\n def query(self, left: i... | 0 | Design a data structure that efficiently finds the **majority element** of a given subarray.
The **majority element** of a subarray is an element that occurs `threshold` times or more in the subarray.
Implementing the `MajorityChecker` class:
* `MajorityChecker(int[] arr)` Initializes the instance of the class wit... | Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient. |
Naïve working solution in Python | online-majority-element-in-subarray | 0 | 1 | # Approach\nCache the counter for subarrays.\n\n# Code\n```\nclass MajorityChecker:\n\n def __init__(self, arr: List[int]):\n self.arr = arr\n \n @functools.cache\n def sub_arr_ctr(self, left: int, right: int):\n return collections.Counter(self.arr[left:right+1])\n\n def query(self, left: i... | 0 | Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_.
**Example 1:**
**Input:** nums = \[3,6,5,1,8\]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
**Example 2:**
**Input:** nums = \... | What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper n... |
Python3 FT 100%: Query Planning! TC O(sqrt(N*log(N))) Per Query, SC O(N) | online-majority-element-in-subarray | 0 | 1 | # Intuition\n\nWelcome to Big Chungus\'s ~4th ever FT 100% solution. Strap yourself in.\n\nThis is by far the most "fun" time complexity of any solution I\'ve submitted. $O\\left(\\sqrt{N \\log(N)}\\right)$ per query is a weird one. I\'ll prove it later.\n\n## Option 1: The Obvious\n\nWe can find the frequency of all e... | 0 | Design a data structure that efficiently finds the **majority element** of a given subarray.
The **majority element** of a subarray is an element that occurs `threshold` times or more in the subarray.
Implementing the `MajorityChecker` class:
* `MajorityChecker(int[] arr)` Initializes the instance of the class wit... | Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient. |
Python3 FT 100%: Query Planning! TC O(sqrt(N*log(N))) Per Query, SC O(N) | online-majority-element-in-subarray | 0 | 1 | # Intuition\n\nWelcome to Big Chungus\'s ~4th ever FT 100% solution. Strap yourself in.\n\nThis is by far the most "fun" time complexity of any solution I\'ve submitted. $O\\left(\\sqrt{N \\log(N)}\\right)$ per query is a weird one. I\'ll prove it later.\n\n## Option 1: The Obvious\n\nWe can find the frequency of all e... | 0 | Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_.
**Example 1:**
**Input:** nums = \[3,6,5,1,8\]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
**Example 2:**
**Input:** nums = \... | What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper n... |
1157. Online Majority Element In Subarray | online-majority-element-in-subarray | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Design a data structure that efficiently finds the **majority element** of a given subarray.
The **majority element** of a subarray is an element that occurs `threshold` times or more in the subarray.
Implementing the `MajorityChecker` class:
* `MajorityChecker(int[] arr)` Initializes the instance of the class wit... | Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient. |
1157. Online Majority Element In Subarray | online-majority-element-in-subarray | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_.
**Example 1:**
**Input:** nums = \[3,6,5,1,8\]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
**Example 2:**
**Input:** nums = \... | What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper n... |
Solution using Counter and lru_cache | online-majority-element-in-subarray | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought was, this is a question involving counting, so\nwhy not use Python\'s nifty ```Counter``` class.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each query, construct a Counter using the elements... | 0 | Design a data structure that efficiently finds the **majority element** of a given subarray.
The **majority element** of a subarray is an element that occurs `threshold` times or more in the subarray.
Implementing the `MajorityChecker` class:
* `MajorityChecker(int[] arr)` Initializes the instance of the class wit... | Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient. |
Solution using Counter and lru_cache | online-majority-element-in-subarray | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought was, this is a question involving counting, so\nwhy not use Python\'s nifty ```Counter``` class.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each query, construct a Counter using the elements... | 0 | Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_.
**Example 1:**
**Input:** nums = \[3,6,5,1,8\]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
**Example 2:**
**Input:** nums = \... | What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper n... |
Python Easy Solution | online-majority-element-in-subarray | 0 | 1 | # Code\n```\nclass MajorityChecker(object):\n\n def __init__(self, A):\n a2i = collections.defaultdict(list)\n for i, x in enumerate(A):\n a2i[x].append(i)\n self.A, self.a2i = A, a2i\n\n def query(self, left, right, threshold):\n for _ in range(20):\n a = self.A[... | 0 | Design a data structure that efficiently finds the **majority element** of a given subarray.
The **majority element** of a subarray is an element that occurs `threshold` times or more in the subarray.
Implementing the `MajorityChecker` class:
* `MajorityChecker(int[] arr)` Initializes the instance of the class wit... | Consider a DFS traversal of the tree. You can keep track of the current path sum from root to this node, and you can also use DFS to return the minimum value of any path from this node to the leaf. This will tell you if this node is insufficient. |
Python Easy Solution | online-majority-element-in-subarray | 0 | 1 | # Code\n```\nclass MajorityChecker(object):\n\n def __init__(self, A):\n a2i = collections.defaultdict(list)\n for i, x in enumerate(A):\n a2i[x].append(i)\n self.A, self.a2i = A, a2i\n\n def query(self, left, right, threshold):\n for _ in range(20):\n a = self.A[... | 0 | Given an integer array `nums`, return _the **maximum possible sum** of elements of the array such that it is divisible by three_.
**Example 1:**
**Input:** nums = \[3,6,5,1,8\]
**Output:** 18
**Explanation:** Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
**Example 2:**
**Input:** nums = \... | What's special about a majority element ? A majority element appears more than half the length of the array number of times. If we tried a random index of the array, what's the probability that this index has a majority element ? It's more than 50% if that array has a majority element. Try a random index for a proper n... |
【Video】Give me 5 minutes - How we think about a solution | find-words-that-can-be-formed-by-characters | 1 | 1 | # Intuition\nCount frequency of each character.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/6LrW0uIlqX8\n\n\u25A0 Timeline of the video\n\n`0:05` How we can solve "Find Words That Can Be Formed by Characters"\n`3:48` What if we have extra character when specific character was already 0 in HashMap?\n`4:17` Coding\n`7... | 22 | You are given an array of strings `words` and a string `chars`.
A string is **good** if it can be formed by characters from chars (each character can only be used once).
Return _the sum of lengths of all good strings in words_.
**Example 1:**
**Input:** words = \[ "cat ", "bt ", "hat ", "tree "\], chars = "atach "... | Try to build the string with a backtracking DFS by considering what you can put in every position. |
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥 | find-words-that-can-be-formed-by-characters | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Count With Hash Map)***\n1. **Initialization:**\n\n - The function initializes an unordered map `counts` to store the count of characters in the `chars` string.\n1. **Counting Characters:**\n\n - It itera... | 3 | You are given an array of strings `words` and a string `chars`.
A string is **good** if it can be formed by characters from chars (each character can only be used once).
Return _the sum of lengths of all good strings in words_.
**Example 1:**
**Input:** words = \[ "cat ", "bt ", "hat ", "tree "\], chars = "atach "... | Try to build the string with a backtracking DFS by considering what you can put in every position. |
Beats 99.51% of users with Python3 | Simple Solution | find-words-that-can-be-formed-by-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)$$ --... | 9 | You are given an array of strings `words` and a string `chars`.
A string is **good** if it can be formed by characters from chars (each character can only be used once).
Return _the sum of lengths of all good strings in words_.
**Example 1:**
**Input:** words = \[ "cat ", "bt ", "hat ", "tree "\], chars = "atach "... | Try to build the string with a backtracking DFS by considering what you can put in every position. |
💯Faster✅💯 Lesser✅4 Methods🔥 Brute Force🔥Hash Map 🔥Counting Characters🔥Optimized Hash Map | find-words-that-can-be-formed-by-characters | 1 | 1 | # \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share 4 ways to solve this question with detailed explanation of each approach:\n\n# Problem Explaination: \nWe are given an array of strings `words` and a string `chars`. Our task is to find the su... | 33 | You are given an array of strings `words` and a string `chars`.
A string is **good** if it can be formed by characters from chars (each character can only be used once).
Return _the sum of lengths of all good strings in words_.
**Example 1:**
**Input:** words = \[ "cat ", "bt ", "hat ", "tree "\], chars = "atach "... | Try to build the string with a backtracking DFS by considering what you can put in every position. |
Easy Python Solution| Mapping | Beats 99% | find-words-that-can-be-formed-by-characters | 0 | 1 | # Intuition\n1) Count the frequency of characters in `chars` \n2) Compare with each individual word in `words` if at any point frequency(`chars`)< frequency(`word`) making the word is not possible\n\nNote: making a mapping of `chars` is problematic because it is possible a character was used in `word` but not in `chars... | 1 | You are given an array of strings `words` and a string `chars`.
A string is **good** if it can be formed by characters from chars (each character can only be used once).
Return _the sum of lengths of all good strings in words_.
**Example 1:**
**Input:** words = \[ "cat ", "bt ", "hat ", "tree "\], chars = "atach "... | Try to build the string with a backtracking DFS by considering what you can put in every position. |
Solution of find words that can be formed by characters problem | find-words-that-can-be-formed-by-characters | 0 | 1 | # Approach\n- Step one: get out word from words list\n- Step two: ckeck out if every charachers in chars list\n- Step three: summarise length of word and add it to the counter\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$ - as we use double loop\n\n- Space complexity:\n$$O(1)$$ - as no extra space is required\n\n# Co... | 1 | You are given an array of strings `words` and a string `chars`.
A string is **good** if it can be formed by characters from chars (each character can only be used once).
Return _the sum of lengths of all good strings in words_.
**Example 1:**
**Input:** words = \[ "cat ", "bt ", "hat ", "tree "\], chars = "atach "... | Try to build the string with a backtracking DFS by considering what you can put in every position. |
⭐🔥One-Liner🔥CheatCode in 🐍 || Beats 66%⭐ | find-words-that-can-be-formed-by-characters | 0 | 1 | \n\n# Code\n```\nfrom typing import List\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n return sum(len(word) for word in words if all(word.count(char) <= char... | 1 | You are given an array of strings `words` and a string `chars`.
A string is **good** if it can be formed by characters from chars (each character can only be used once).
Return _the sum of lengths of all good strings in words_.
**Example 1:**
**Input:** words = \[ "cat ", "bt ", "hat ", "tree "\], chars = "atach "... | Try to build the string with a backtracking DFS by considering what you can put in every position. |
Python3 Solution | find-words-that-can-be-formed-by-characters | 0 | 1 | \n```\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n return sum(len(word) for word in words if Counter(word)<=Counter(chars))\n \n``` | 1 | You are given an array of strings `words` and a string `chars`.
A string is **good** if it can be formed by characters from chars (each character can only be used once).
Return _the sum of lengths of all good strings in words_.
**Example 1:**
**Input:** words = \[ "cat ", "bt ", "hat ", "tree "\], chars = "atach "... | Try to build the string with a backtracking DFS by considering what you can put in every position. |
Python Logic Based Approach Using Dictionary | find-words-that-can-be-formed-by-characters | 0 | 1 | \n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def countCharacters(self, words: List[str], chars: str) -> int:\n l=list(chars)\n count=0\n m={}\n for i in chars :\n if i in m :\n m[i]+=1\n el... | 1 | You are given an array of strings `words` and a string `chars`.
A string is **good** if it can be formed by characters from chars (each character can only be used once).
Return _the sum of lengths of all good strings in words_.
**Example 1:**
**Input:** words = \[ "cat ", "bt ", "hat ", "tree "\], chars = "atach "... | Try to build the string with a backtracking DFS by considering what you can put in every position. |
✅ Explained - Simple and Clear Python3 Code✅ | maximum-level-sum-of-a-binary-tree | 0 | 1 | \n# Approach\nThe logic of the code involves recursively traversing the binary tree and maintaining a list of sums at each level. Starting from the root, the code calculates the sum of node values at each level and stores them in the list. After the traversal, it determines the maximum sum from the list and returns the... | 5 | Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on.
Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**.
**Example 1:**
**Input:** root = \[1,7,0,7,-8,null,null\]
**Output:** 2
**Explanation:**
Level 1 s... | null |
Python Elegant & Short | DFS & Generators | maximum-level-sum-of-a-binary-tree | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def maxLevelSum(self, root: Optional[TreeNode]) -> List[float]:\n level_sum = defaultdict(int)\n\n for lvl, val in self.inorder(root):\n level_sum[lvl + 1] += val\n\n return max(l... | 2 | Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on.
Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**.
**Example 1:**
**Input:** root = \[1,7,0,7,-8,null,null\]
**Output:** 2
**Explanation:**
Level 1 s... | null |
Level Order. Readable code - Python / C++ | maximum-level-sum-of-a-binary-tree | 0 | 1 | \n# Code\n\n```python []\nclass Solution:\n def maxLevelSum(self, root: Optional[TreeNode]) -> int:\n a = []\n\n def dfs(node, h):\n if not node:\n return\n if len(a) == h:\n a.append([])\n\n dfs(node.left, h+1)\n a[h].append(nod... | 2 | Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on.
Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**.
**Example 1:**
**Input:** root = \[1,7,0,7,-8,null,null\]
**Output:** 2
**Explanation:**
Level 1 s... | null |
Python3 Solution | maximum-level-sum-of-a-binary-tree | 0 | 1 | \n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def helper(self,root,level):\n if root:\n self.level[level]+=root.val\n ... | 2 | Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on.
Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**.
**Example 1:**
**Input:** root = \[1,7,0,7,-8,null,null\]
**Output:** 2
**Explanation:**
Level 1 s... | null |
BFS Traversal | maximum-level-sum-of-a-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs to return the maximum sum of each level, its better to use BFS. Can use DFS traversal too but the solution become a little bit complex.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will traverse each level... | 1 | Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on.
Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**.
**Example 1:**
**Input:** root = \[1,7,0,7,-8,null,null\]
**Output:** 2
**Explanation:**
Level 1 s... | null |
Maximum level sum of a binary tree | maximum-level-sum-of-a-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on.
Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**.
**Example 1:**
**Input:** root = \[1,7,0,7,-8,null,null\]
**Output:** 2
**Explanation:**
Level 1 s... | null |
1161. Maximum Level Sum of a Binary Tree | maximum-level-sum-of-a-binary-tree | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the solution is to perform a level-order traversal of the binary tree and calculate the sum of node values at each level. By comparing the sums of different levels, we can identify the smallest level with the maximal ... | 1 | Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on.
Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**.
**Example 1:**
**Input:** root = \[1,7,0,7,-8,null,null\]
**Output:** 2
**Explanation:**
Level 1 s... | null |
Python - Iterative DFS with stack | maximum-level-sum-of-a-binary-tree | 0 | 1 | # Intuition\nSimple iterative DFS approach.\n\n# Approach\n1. Init stack with root node and a default dict used to keep track of the sum for each level\n2. Traverse the tree by using a stack keeping track of the current node level\n3. Each time I pop from the stack I update the current level sum\n4. Once the traversal ... | 1 | Given the `root` of a binary tree, the level of its root is `1`, the level of its children is `2`, and so on.
Return the **smallest** level `x` such that the sum of all the values of nodes at level `x` is **maximal**.
**Example 1:**
**Input:** root = \[1,7,0,7,-8,null,null\]
**Output:** 2
**Explanation:**
Level 1 s... | null |
|| 🐍 Python3 O(2n²) Easiest ✔ Solution 🔥 || Beats 80% (Runtime) & 41% (Memory) || | as-far-from-land-as-possible | 0 | 1 | # Intuition\n- Get all the index of land, check if there is only land if no, then one-by-one convert all adjacent indices(Breadth-First-Search approach) to land while incrementing the distance. At last return the last distance of land.\n\n# Approach\n1. Initializing,\n - `n` for matrix of `n x n`\n - `land` to ch... | 2 | Given an `n x n` `grid` containing only values `0` and `1`, where `0` represents water and `1` represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return `-1`.
The distance used in this problem is the Manhatta... | null |
Python3 using BFS with deque easy to understand. | as-far-from-land-as-possible | 0 | 1 | # Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```\nclass Solution:\n def maxDistance(self, grid: List[List[int]]) -> int:\n q = deque()\n n = len(grid)\n ans = -1\n visited = set()\n\n for r in range(n):\n for c in range(n):\n ... | 1 | Given an `n x n` `grid` containing only values `0` and `1`, where `0` represents water and `1` represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return `-1`.
The distance used in this problem is the Manhatta... | null |
Python solution beatas 99%. With explanantion | last-substring-in-lexicographical-order | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is to find the lexicographically largest substring of a given string. My first thought is to start by comparing characters at different positions in the string and keep track of the substring with the highest lexicographic val... | 4 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
PYTHON | EXPLANATION WITH PHOTO | LINEAR TIME | EASY | INTUITIVE | | last-substring-in-lexicographical-order | 0 | 1 | \n# EXPLANATION\n```\nLet us start with Brute Force :\n1.Find all substring and store them in a list : list\n2.Sort the string list : list \n3.return list[-1]\n\nWe can optimize the above problem :\n\nAlways remember that "aaaba" > "aaab" so ans of this problem is always a suffix of string\n\n1. think carefully the las... | 1 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
One-line solution in Python | last-substring-in-lexicographical-order | 0 | 1 | # Intuition\nThe lexicographically maximum substring in `s` will start with the letter `max(s)` and continue to the end of `s`.\n\n# Code\n```\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n return max(s[m.start() :] for m in re.finditer(max(s), s))\n``` | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
Easy brute force in python3 that barely passes | last-substring-in-lexicographical-order | 0 | 1 | # Code\n```\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n res = s\n N = len(s)\n for i in range(N):\n res = max(res,s[i:])\n return res\n\n``` | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
slow | last-substring-in-lexicographical-order | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n n = len(s)\n max_substring = ""\n max_char = ""\n\n for i in range(n - 1, -1, -1):\n if s[i] > max_char:\n max_char = s[i]\n max_substring = s[i:]\n elif s[i] =... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
[Python] Two pointers - 2023/06/06 | last-substring-in-lexicographical-order | 0 | 1 | # Intuition\n\nfirst, find indices of lexicographically largest character by hashmap {ch: [...indices]}\n\nsince answer must be within every possible suffix string `s[i:] where i in index[biggestCh] `\n\nlet\'s choose first 2 smallest indices since the longer the larger and maintain `i` **always smaller than** `j`\n\n`... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
Solution | last-substring-in-lexicographical-order | 1 | 1 | ```C++ []\nclass Solution {\n public:\n string lastSubstring(string s) {\n int i = 0, j = 1, k = 0, n = int(s.length());\n while ((j + k) < n) {\n if (s[i + k] == s[j + k]) k++;\n else if (s[i + k] > s[j + k]) {\n j += k + 1;\n k = 0;\n } else {\n i = std::m... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
Python3 easy solution | last-substring-in-lexicographical-order | 0 | 1 | # Code\n```\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n i = 0\n j = 1\n k = 0\n n = len(s)\n while j + k < n:\n if s[i + k] == s[j + k]:\n k += 1\n elif s[i + k] > s[j + k]:\n j += k + 1\n k = 0\n ... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
2-line solution in Python with explanation | last-substring-in-lexicographical-order | 0 | 1 | # Intuition\nThe answer will have the largest initial letter `z`. In addition, the longer the answer is the better. In other words, only the substrings `s[i:]` with `s[i] == z` ending at the end of `s` should be considered as candidates. \n\nA candidate substring `s[i:]` is always better than `s[i+1:]` where `s[i+1] ==... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
python3 + fast + very easy | last-substring-in-lexicographical-order | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def lastSubstring(self, s: str) -> str:\n max = 97\n for e in s:\n if ord(e) > max:\n max = ord(e)\n \n maxstr = \'\'\n for i in range(len(s)):\n if ord(s[i]) == max:\n if s[i:] > maxstr:\n ... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
Python Brute Force Solution | last-substring-in-lexicographical-order | 0 | 1 | # Intuition\n- The answer is always suffix of the given string\n- what if store the indices of largest character and compare the substring starting from the indeces to the end of the string\n\n# Approach\n- store the indices of largest character\n- for each index in indices take the largest substring by comparing subst... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
Python very easy solution, Please upvote and add to your favourites. | last-substring-in-lexicographical-order | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
Python Efficient Solution | Easy to Understand | Beats 70% | last-substring-in-lexicographical-order | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to find optimal index of maximum element. ```s[maxIndex:]``` is the answer\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo the Basis of this kindof solution is the fact that the input string may not only... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
Intutive Approach with detailed explanation | last-substring-in-lexicographical-order | 0 | 1 | # Intuition\n1. Answer will must start with the biggest character in string\n\n\n# Approach\n1. Traverse string in reverse order\n2. Keep track of biggest element till that specific index also keep track of the index of that biggest element.\n3. if new character is greater than the previous big character then will upda... | 0 | Given a string `s`, return _the last substring of_ `s` _in lexicographical order_.
**Example 1:**
**Input:** s = "abab "
**Output:** "bab "
**Explanation:** The substrings are \[ "a ", "ab ", "aba ", "abab ", "b ", "ba ", "bab "\]. The lexicographically maximum substring is "bab ".
**Example 2:**
**Input:*... | null |
Simple Python Solution with Explanation | Beats 88% of Submissions | invalid-transactions | 0 | 1 | **Source**: https://leetcode.com/problems/invalid-transactions/description/\n**Author**: Hassan Abioye\n**Notes**: [[Leetcode Algorithm Notes]]\n**Date**: 2023-11-29\n**Time**: 01:39\n**Tags**: #Array #HashTable #String #Sorting \n\n---\n\n### Solution:\n```python\nclass Solution:\n def invalidTransactions(self, tra... | 1 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
Python Solution | Hashmap | Set | invalid-transactions | 0 | 1 | ```\nclass Solution:\n def invalidTransactions(self, transactions: List[str]) -> List[str]:\n hashmap = {}\n\t\t#Hashset is used to skip redudant transactions being added to the result\n\t\t#We will only store index of the transaction because the same transaction can repeat.\n result = set()\n f... | 6 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
Python3 | Beats 98% | O(N) O(N) | invalid-transactions | 0 | 1 | # Complexity\n- Time complexity: $$O(N)$$\n\n- Space complexity: $$O(N)$$\n\n# Code\n```\nclass Solution:\n def invalidTransactions(self, transactions: List[str]) -> List[str]:\n transactions.sort(key=lambda t: int(t.split(\',\')[1]))\n ans = []\n invalid = [False]*len(transactions)\n nam... | 1 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
O(N) ?? using HashTable/HashMap | Comments added | invalid-transactions | 0 | 1 | https://github.com/paulonteri/data-structures-and-algorithms\n\n- Record all transactions done at a particular time. Recording the person and the location. \n\t```\n\t{time: {person: {location}, person2: {location1, location2}}, time: {person: {location}}}\n\t```\n\tExample:\n\t```\n\t[\'alice,20,800,mtv\', \'bob,50,12... | 19 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
[Python3] - Linear time Solution O(N) | invalid-transactions | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAt first we save all the transactions in a structure where we can quickly find them again.\n\nAs we are interested in checking for transactions with the same name and for a given point in time we use a nested dictionary with exactly these... | 6 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
Python using hashmap, tricky question | invalid-transactions | 0 | 1 | \tdef invalidTransactions(self, transactions: List[str]) -> List[str]:\n out = [] #list of all the invalid transactions to return \n names = defaultdict(lambda: defaultdict(set)) #{name: {time: city}}\n \n \n for t in transactions:\n name,time,amount,city = t.split(",")\n ... | 6 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
Python: very simple and straightforward solution | invalid-transactions | 0 | 1 | ```\nclass Solution:\n def invalidTransactions(self, transactions: List[str]) -> List[str]:\n cities = defaultdict(lambda: defaultdict(list))\n output = []\n \n\t\t#build city map. \n for t in transactions:\n name, time, amount, city = t.split(\',\')\n cities[city][n... | 4 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
Python easy to understand solution with explanation using Dictionary | invalid-transactions | 0 | 1 | ```\nclass Solution(object):\n def invalidTransactions(self, transactions):\n """\n :type transactions: List[str]\n :rtype: List[str]\n \n memo = dictionary --> create a dictionary to keep track of previous transaction \n invalid_tran = set --> to store invalid transaction /... | 10 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
Simple clean python - only 10 lines | invalid-transactions | 0 | 1 | ```python\nclass Solution:\n def invalidTransactions(self, transactions: List[str]) -> List[str]:\n invalid = []\n \n for i, t1 in enumerate(transactions):\n name1, time1, amount1, city1 = t1.split(\',\')\n if int(amount1) > 1000:\n invalid.append(t1)\n ... | 9 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
Python Solution Using Class, O(N^2) Complexity | invalid-transactions | 0 | 1 | # Intuition\nStore the invalid transaction using set but later figured this won\'t work as there are duplicate transactions.\n\n# Approach\nUse class to store information and add a property called valid so that I can mark a transaction to be valid or invalid.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space compl... | 0 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
Python3, FT 97%: Group by Name, Two-Pointer 60 Minute Window | invalid-transactions | 0 | 1 | # Intuition\n\nThe criteria involve\n* individual transactions\n* pairs of transactions with the same name\n\nSo we first realize that we can partition/group by name to simplify the problem.\n\nThen within the transactions for each name:\n* if transaction `i` exceeds 1000, we flag it\n* if transaction `i` is within 60 ... | 0 | A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing ... | Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table. |
Solution Space (Binary Search) in Python3 / TypeScript | compare-strings-by-frequency-of-the-smallest-character | 0 | 1 | # Intuition\nFor this problem we\'re going to use **Binary Search** (Solution Space).\n\nLet\'s briefly explain why:\n```\n# 1. there are \'words\' and \'queries\'\n\n# 2. both of them contains only English lowercase letters\n\n# 3. there\'s a definition F(s), that represents\n# frequency of the smallest lexicographica... | 1 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
✔ Python3 Solution | 3 Line Solution | Binary Search | compare-strings-by-frequency-of-the-smallest-character | 0 | 1 | # Complexity\n- Time complexity: $$O((n + m) * logm)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def numSmallerByFrequency(self, Q, W):\n f = lambda x: x.count(min(x))\n W = sorted(list(map(f, W)))\n return [len(W) - bisect_right(W, i) for i in map(f, Q)]\n``` | 2 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
Python3 | Solved Using Binary Search By Translating Each and Every word into Function Value | compare-strings-by-frequency-of-the-smallest-character | 0 | 1 | ```\nclass Solution:\n #Let n = len(queries) and m = len(words)\n #Time-Complexity: O(m + mlog(m) + n*log(m)) -> O(mlog(m) + nlog(m))\n #Space-Complexity: O(10*m + n*10 + m) -> O(n + m)\n def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n \n #Approach: Traver... | 1 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
Python Simple Code Memory efficient | compare-strings-by-frequency-of-the-smallest-character | 0 | 1 | \tclass Solution:\n\t\tdef numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n\t\t\tdef f(s):\n\t\t\t\tt = sorted(list(s))[0]\n\t\t\t\treturn s.count(t)\n\t\t\tquery = [f(x) for x in queries]\n\t\t\tword = [f(x) for x in words]\n\t\t\tm = []\n\t\t\tfor x in query:\n\t\t\t\tcount = 0\n\t\t\... | 17 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
Easy to understand Python3 solution | compare-strings-by-frequency-of-the-smallest-character | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
Binary Search | Sorting | compare-strings-by-frequency-of-the-smallest-character | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
Python Simple Solution | compare-strings-by-frequency-of-the-smallest-character | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$O(Q * W * (n + avg_w))$$\n\n Q is the number of queries.\n W is the number of words.\n n is the average length of the qu... | 0 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
python3 naive simple sol | compare-strings-by-frequency-of-the-smallest-character | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:\n freq = []\n for e in words:\n min = \'z\'\n for k in e:\n if k < min:\n min = k\n c = 0\n for k in e:\n ... | 0 | Let the function `f(s)` be the **frequency of the lexicographically smallest character** in a non-empty string `s`. For example, if `s = "dcce "` then `f(s) = 2` because the lexicographically smallest character is `'c'`, which has a frequency of 2.
You are given an array of strings `words` and another array of query s... | We can find the length of the longest common subsequence between str1[i:] and str2[j:] (for all (i, j)) by using dynamic programming. We can use this information to recover the longest common supersequence. |
📌📌 Easiest Approach || Clean & Concise || Well-Explained 🐍 | remove-zero-sum-consecutive-nodes-from-linked-list | 0 | 1 | ## IDEA :\n*If we see with little focus we will come to know that we are removing the nodes with sum value 0.*\nBut here the question is how we will come to know that sum of subset nodes is 0. For this we can use **prefix sum**. If we are having sum which has already appeared once before it means that we are having su... | 15 | Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)... | Do a breadth first search to find the shortest path. |
📌📌 Easiest Approach || Clean & Concise || Well-Explained 🐍 | remove-zero-sum-consecutive-nodes-from-linked-list | 0 | 1 | ## IDEA :\n*If we see with little focus we will come to know that we are removing the nodes with sum value 0.*\nBut here the question is how we will come to know that sum of subset nodes is 0. For this we can use **prefix sum**. If we are having sum which has already appeared once before it means that we are having su... | 15 | You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any o... | Convert the linked list into an array. While you can find a non-empty subarray with sum = 0, erase it. Convert the array into a linked list. |
[Python3] O(n) time solution with hashmap | remove-zero-sum-consecutive-nodes-from-linked-list | 0 | 1 | ```\nclass Solution:\n def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n fake = ListNode(0, head)\n \n d = {0: fake}\n \n prefix_sum = 0\n while head:\n prefix_sum += head.val\n d[prefix_sum] = head\n head = h... | 5 | Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)... | Do a breadth first search to find the shortest path. |
[Python3] O(n) time solution with hashmap | remove-zero-sum-consecutive-nodes-from-linked-list | 0 | 1 | ```\nclass Solution:\n def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n fake = ListNode(0, head)\n \n d = {0: fake}\n \n prefix_sum = 0\n while head:\n prefix_sum += head.val\n d[prefix_sum] = head\n head = h... | 5 | You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any o... | Convert the linked list into an array. While you can find a non-empty subarray with sum = 0, erase it. Convert the array into a linked list. |
python3 (easy and clean) | remove-zero-sum-consecutive-nodes-from-linked-list | 0 | 1 | ```\n def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n fake = ListNode(0, head)\n \n seen = {0: fake} \n prev = 0\n \n while head:\n prev += head.val \n seen[prev] = head\n \n hea... | 5 | Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)... | Do a breadth first search to find the shortest path. |
python3 (easy and clean) | remove-zero-sum-consecutive-nodes-from-linked-list | 0 | 1 | ```\n def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n fake = ListNode(0, head)\n \n seen = {0: fake} \n prev = 0\n \n while head:\n prev += head.val \n seen[prev] = head\n \n hea... | 5 | You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any o... | Convert the linked list into an array. While you can find a non-empty subarray with sum = 0, erase it. Convert the array into a linked list. |
| PYTHON SOL | WELL EXPLAINED | HASHMAP + PREFIX SUM| EASY | FAST | remove-zero-sum-consecutive-nodes-from-linked-list | 0 | 1 | # EXPLANATION\n```\n1. How do we know that any substring will have sum = 0\n2. The idea is if any prefix sum that had occured before occurs again we know that sum of substring\nbetween them is = 0\nexample [ 1,4,2,5,-7]\nsum will be [ 1,5,7,12,5] \nSO 5 occurs twice i.e. sum of [2,5,-7] is 0\nso we simply make... | 1 | Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.
(Note that in the examples below, all sequences are serializations of `ListNode` objects.)... | Do a breadth first search to find the shortest path. |
| PYTHON SOL | WELL EXPLAINED | HASHMAP + PREFIX SUM| EASY | FAST | remove-zero-sum-consecutive-nodes-from-linked-list | 0 | 1 | # EXPLANATION\n```\n1. How do we know that any substring will have sum = 0\n2. The idea is if any prefix sum that had occured before occurs again we know that sum of substring\nbetween them is = 0\nexample [ 1,4,2,5,-7]\nsum will be [ 1,5,7,12,5] \nSO 5 occurs twice i.e. sum of [2,5,-7] is 0\nso we simply make... | 1 | You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any o... | Convert the linked list into an array. While you can find a non-empty subarray with sum = 0, erase it. Convert the array into a linked list. |
Python Easy Solution | dinner-plate-stacks | 0 | 1 | # Code\n```\nclass DinnerPlates:\n def __init__(self, capacity):\n self.c = capacity\n self.q = [] # record the available stack, will use heap to quickly find the smallest available stack\n # if you are Java or C++ users, tree map is another good option.\n self.stacks = [] # record values... | 2 | You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity.
Implement the `DinnerPlates` class:
* `DinnerPlates(int capacity)` Initializes the object with the maximum capacity of the stacks `capacity`.
* `void push(int val)` Push... | null |
Heap + Hash Set Python3 Solution with Commented explanation | dinner-plate-stacks | 0 | 1 | ```\nclass DinnerPlates:\n \n \'\'\'\n \n design\n free slots: heap\n avoid repeated slots: hash set\n \n \n actions:\n push:\n - check leftmost free slot, add\n - if no free slot => create one and add to free slots\n - if curr s... | 0 | You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity.
Implement the `DinnerPlates` class:
* `DinnerPlates(int capacity)` Initializes the object with the maximum capacity of the stacks `capacity`.
* `void push(int val)` Push... | null |
Brain fck mode | dinner-plate-stacks | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity.
Implement the `DinnerPlates` class:
* `DinnerPlates(int capacity)` Initializes the object with the maximum capacity of the stacks `capacity`.
* `void push(int val)` Push... | null |
TreeSet Abstraction | Commented and Explained | dinner-plate-stacks | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor this set up, we have a mapped tree set as the desired set up, where we can modify a set of tree sets as needed. Then, if a lazy update is used, we can get an O(1) for push with a seeming O(N) for pop at worst and O(N) for popAtStack. ... | 0 | You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity.
Implement the `DinnerPlates` class:
* `DinnerPlates(int capacity)` Initializes the object with the maximum capacity of the stacks `capacity`.
* `void push(int val)` Push... | null |
Beats 98.89% No Heapq! | dinner-plate-stacks | 0 | 1 | # Code\n```\nfrom bisect import bisect\nclass DinnerPlates:\n\n def __init__(self, capacity: int):\n self.capacity = capacity\n self.can_put = []\n self.max = -1\n self.my_dict = defaultdict(int)\n\n def push(self, val: int) -> None:\n if not self.can_put:\n self.max ... | 0 | You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity.
Implement the `DinnerPlates` class:
* `DinnerPlates(int capacity)` Initializes the object with the maximum capacity of the stacks `capacity`.
* `void push(int val)` Push... | null |
Python (Simple Heap) | dinner-plate-stacks | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity.
Implement the `DinnerPlates` class:
* `DinnerPlates(int capacity)` Initializes the object with the maximum capacity of the stacks `capacity`.
* `void push(int val)` Push... | null |
One heap, 98.7 speed 84.7 mem 839 ms | dinner-plate-stacks | 0 | 1 | # Approach\nCreate a heap of non full stacks, \npush a new value at first to the non full stack and only if there no such stacks, create a new stack.\n\n# Complexity\n- Time complexity:\nO(logn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass DinnerPlates:\n\n def __init__(self, capacity: int):\n self.arr ... | 1 | You have an infinite number of stacks arranged in a row and numbered (left to right) from `0`, each of the stacks has the same maximum capacity.
Implement the `DinnerPlates` class:
* `DinnerPlates(int capacity)` Initializes the object with the maximum capacity of the stacks `capacity`.
* `void push(int val)` Push... | null |
Python Simple Intuitive Solution | prime-arrangements | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFactorial comes into mind and then concept of number of prime numbers from [2, n] inclusive is to be dealt with. Remember 1 is not prime.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDefine an isPrime() function... | 2 | Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)
_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_
Since the answer may be large, return the answer **modulo `10... | Try to simulate the process. For every iteration, find the new array using the old one and the given rules. |
optimal | prime-arrangements | 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: 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. $... | 0 | Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)
_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_
Since the answer may be large, return the answer **modulo `10... | Try to simulate the process. For every iteration, find the new array using the old one and the given rules. |
python code simple strategy...! | prime-arrangements | 0 | 1 | \n\n# Code\n```\nimport math\nclass Solution:\n def numPrimeArrangements(self, n: int) -> int:\n primelist=[2,3]\n ans=1\n if (n<3):\n return 1\n elif (n==3):\n return 2\n else:\n for i in range(4,n+1):\n for j in range(2,i//2+1):\n ... | 0 | Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)
_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_
Since the answer may be large, return the answer **modulo `10... | Try to simulate the process. For every iteration, find the new array using the old one and the given rules. |
prime-arrangements | prime-arrangements | 0 | 1 | # Code\n```\nclass Solution:\n def numPrimeArrangements(self, n: int) -> int:\n l = []\n for i in range(2,n+1):\n count = 0\n for j in range(len(l)):\n if i%l[j]==0:\n count+=1\n break\n if count==0:\n ... | 0 | Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)
_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_
Since the answer may be large, return the answer **modulo `10... | Try to simulate the process. For every iteration, find the new array using the old one and the given rules. |
Python 3: Combinatorics, TC O(n**(3/2)), SC O(1) | prime-arrangements | 0 | 1 | # Intuition\n\nUsually, order questions can be solved using combinatorics. If you\'re unfamiliar, do some studying on\n* factorial\n * you have `n` items, and you want all ways to arrange them on a line\n* the choose operation, `n choose k == n!//((n-k)!*k!)\n * you have n slots, and you want the ways to choose k of ... | 0 | Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)
_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_
Since the answer may be large, return the answer **modulo `10... | Try to simulate the process. For every iteration, find the new array using the old one and the given rules. |
Runtime Beats 98.88% and Memory Beats 96.25% | prime-arrangements | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)
_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_
Since the answer may be large, return the answer **modulo `10... | Try to simulate the process. For every iteration, find the new array using the old one and the given rules. |
[Python 3 | beats 98.92% in time | easy solution] | prime-arrangements | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are only 25 primes for $n \\le 100$, so we can make a list of primes. We can easily check how many primes less than equal to $n$ there are. If there are i primes in the first $n$ numbers, combinatorics tells us that there are $i! \\... | 0 | Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)
_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_
Since the answer may be large, return the answer **modulo `10... | Try to simulate the process. For every iteration, find the new array using the old one and the given rules. |
PYTHON | Simple Solution | Math & Counting | prime-arrangements | 0 | 1 | # 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```python\ndef factorial(n: int, to_divide: int) -> int:\n fact = 1\n while n > 0:\n fact = (fact * n) % to_divide\n ... | 0 | Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)
_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_
Since the answer may be large, return the answer **modulo `10... | Try to simulate the process. For every iteration, find the new array using the old one and the given rules. |
Ezreal | prime-arrangements | 0 | 1 | # Code\n```\nclass Solution:\n def numPrimeArrangements(self, n: int) -> int:\n primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n p = bisect.bisect(primes,n)\n Output = factorial(p) * factorial(n - p)\n\n return Output % ( 10 ** 9 ... | 0 | Return the number of permutations of 1 to `n` so that prime numbers are at prime indices (1-indexed.)
_(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)_
Since the answer may be large, return the answer **modulo `10... | Try to simulate the process. For every iteration, find the new array using the old one and the given rules. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.