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] Top down spaghetti solution - Authentic like Italian cuisine | paint-house-iii | 0 | 1 | # Intuition\nWe first need to understand the idea of having neighborhoods. It the most basic sense, it\'s the number of color switch between different neighbors plus 1.\n\nFor example, `houses = [1, 2, 2, 1, 1]`, number of `color` switchs are `2`, and we have `3` neighborhoods.\n\n# Approach\n<!-- Describe your approac... | 1 | You are given a list of `preferences` for `n` friends, where `n` is always **even**.
For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denot... | Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j. |
Python3 | Space Optimized | paint-house-iii | 0 | 1 | # Approach\n* Code is self-explanatory\n\n# Complexity\n- Time complexity: $$O(M \\cdot T \\cdot N^2)$$\n\n- Space complexity: $$O(T \\cdot N)$$\n\n# Code\n```\nclass Solution:\n def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:\n dp = [[+inf for _ in range(n)] f... | 1 | There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again.
A neighborhood is a maximal group of continuous houses that are painted with the same color.
* For example: `hous... | Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring. |
Python3 | Space Optimized | paint-house-iii | 0 | 1 | # Approach\n* Code is self-explanatory\n\n# Complexity\n- Time complexity: $$O(M \\cdot T \\cdot N^2)$$\n\n- Space complexity: $$O(T \\cdot N)$$\n\n# Code\n```\nclass Solution:\n def minCost(self, houses: List[int], cost: List[List[int]], m: int, n: int, target: int) -> int:\n dp = [[+inf for _ in range(n)] f... | 1 | You are given a list of `preferences` for `n` friends, where `n` is always **even**.
For each person `i`, `preferences[i]` contains a list of friends **sorted** in the **order of preference**. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denot... | Use Dynamic programming. Define dp[i][j][k] as the minimum cost where we have k neighborhoods in the first i houses and the i-th house is painted with the color j. |
Beats 54.86% || Final prices with a special discount in a shop | final-prices-with-a-special-discount-in-a-shop | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given an integer array `prices` where `prices[i]` is the price of the `ith` item in a shop.
There is a special discount for items in the shop. If you buy the `ith` item, then you will receive a discount equivalent to `prices[j]` where `j` is the minimum index such that `j > i` and `prices[j] <= prices[i]`. Oth... | Create a datastructure with 4 parameters: (sum, isBST, maxLeft, minLeft). In each node compute theses parameters, following the conditions of a Binary Search Tree. |
Python 3, One-pass, Visual explain, Monotonous stack | final-prices-with-a-special-discount-in-a-shop | 0 | 1 | At this point, when you see this post, you may have already know how to code using the Monotonous Increasing Stack stragegy. This post has the same code as you saw from other posts. However, as an engineer like me, I\'d like to actually see how the Monotonous Stack works visually. So here you go, below are some diagram... | 37 | You are given an integer array `prices` where `prices[i]` is the price of the `ith` item in a shop.
There is a special discount for items in the shop. If you buy the `ith` item, then you will receive a discount equivalent to `prices[j]` where `j` is the minimum index such that `j > i` and `prices[j] <= prices[i]`. Oth... | Create a datastructure with 4 parameters: (sum, isBST, maxLeft, minLeft). In each node compute theses parameters, following the conditions of a Binary Search Tree. |
[Python]||O(N^2) | final-prices-with-a-special-discount-in-a-shop | 0 | 1 | Time Complexcity O(N^2)\nSpace Complexcity O(N)\n```\nclass Solution:\n def finalPrices(self, prices: List[int]) -> List[int]:\n ans=[]\n for i in range(len(prices)-1):\n flag=False\n for j in range(i+1,len(prices)):\n if prices[i]>=prices[j]:\n a... | 3 | You are given an integer array `prices` where `prices[i]` is the price of the `ith` item in a shop.
There is a special discount for items in the shop. If you buy the `ith` item, then you will receive a discount equivalent to `prices[j]` where `j` is the minimum index such that `j > i` and `prices[j] <= prices[i]`. Oth... | Create a datastructure with 4 parameters: (sum, isBST, maxLeft, minLeft). In each node compute theses parameters, following the conditions of a Binary Search Tree. |
Python easy soln | subrectangle-queries | 0 | 1 | # Very easy soln\n\n# Code\n```\nclass SubrectangleQueries:\n\n def __init__(self, rectangle: List[List[int]]):\n self.r=rectangle\n\n def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:\n for i in range(row1,row2+1):\n for j in range(col1,col2... | 1 | Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods:
1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)`
* Updates all values with `newValue` in the subrectangle whose upper left coordinate i... | Use binary search for optimization or simply brute force. |
Python easy soln | subrectangle-queries | 0 | 1 | # Very easy soln\n\n# Code\n```\nclass SubrectangleQueries:\n\n def __init__(self, rectangle: List[List[int]]):\n self.r=rectangle\n\n def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:\n for i in range(row1,row2+1):\n for j in range(col1,col2... | 1 | Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
... | Use brute force to update a rectangle and, response to the queries in O(1). |
「🙏Python3」🧼Clean-Intuitive🧠 || O(R * C) || Thanks for reading | subrectangle-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou want to find the range of the 2D Matrix that you need to change to the `newValue`. The rectangle will be\n\n***Top-Left*** \n\u300C`(row1, col1)` -----------\n------------- `(row2, col2)`\u300D***Bot-Right***\n\n---\n\n# Complexity\n-... | 4 | Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods:
1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)`
* Updates all values with `newValue` in the subrectangle whose upper left coordinate i... | Use binary search for optimization or simply brute force. |
「🙏Python3」🧼Clean-Intuitive🧠 || O(R * C) || Thanks for reading | subrectangle-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou want to find the range of the 2D Matrix that you need to change to the `newValue`. The rectangle will be\n\n***Top-Left*** \n\u300C`(row1, col1)` -----------\n------------- `(row2, col2)`\u300D***Bot-Right***\n\n---\n\n# Complexity\n-... | 4 | Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
... | Use brute force to update a rectangle and, response to the queries in O(1). |
Easy, Intiutive Python, Faster than 99% | subrectangle-queries | 0 | 1 | Idea: Updating the rectangle is an expensive write operation. Instead we simply keep a store of all subsequent updates and look through the store to check whether the value has been updated. If not, we return the value from the original rectangle.\n```\nclass SubrectangleQueries:\n\n def __init__(self, rectangle: Li... | 9 | Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods:
1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)`
* Updates all values with `newValue` in the subrectangle whose upper left coordinate i... | Use binary search for optimization or simply brute force. |
Easy, Intiutive Python, Faster than 99% | subrectangle-queries | 0 | 1 | Idea: Updating the rectangle is an expensive write operation. Instead we simply keep a store of all subsequent updates and look through the store to check whether the value has been updated. If not, we return the value from the original rectangle.\n```\nclass SubrectangleQueries:\n\n def __init__(self, rectangle: Li... | 9 | Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
... | Use brute force to update a rectangle and, response to the queries in O(1). |
easy solution to understand python3 | subrectangle-queries | 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 | Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods:
1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)`
* Updates all values with `newValue` in the subrectangle whose upper left coordinate i... | Use binary search for optimization or simply brute force. |
easy solution to understand python3 | subrectangle-queries | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
... | Use brute force to update a rectangle and, response to the queries in O(1). |
Beating 95.53% Python Easiest Understandable Solution | subrectangle-queries | 0 | 1 | \n\n# Code\n```\nclass SubrectangleQueries:\n\n def __init__(self, rectangle: List[List[int]]):\n self.rectangle=rectangle\n self.ops=[]\n\n def updateSubrectangle(self, row1: int, col1:... | 2 | Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods:
1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)`
* Updates all values with `newValue` in the subrectangle whose upper left coordinate i... | Use binary search for optimization or simply brute force. |
Beating 95.53% Python Easiest Understandable Solution | subrectangle-queries | 0 | 1 | \n\n# Code\n```\nclass SubrectangleQueries:\n\n def __init__(self, rectangle: List[List[int]]):\n self.rectangle=rectangle\n self.ops=[]\n\n def updateSubrectangle(self, row1: int, col1:... | 2 | Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
... | Use brute force to update a rectangle and, response to the queries in O(1). |
[Python] Easier solution | subrectangle-queries | 0 | 1 | \n\n```\nclass SubrectangleQueries(object):\n\n def __init__(self, rectangle):\n self.rectangle = copy.deepcopy(rectangle)\n\n def updateSubrectangle(self, row1, col1, row2, col2, newValue):\n for i in range(row1, row2+1):\n for j in range(col1, col2+1):\n self.rectangle[i]... | 10 | Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods:
1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)`
* Updates all values with `newValue` in the subrectangle whose upper left coordinate i... | Use binary search for optimization or simply brute force. |
[Python] Easier solution | subrectangle-queries | 0 | 1 | \n\n```\nclass SubrectangleQueries(object):\n\n def __init__(self, rectangle):\n self.rectangle = copy.deepcopy(rectangle)\n\n def updateSubrectangle(self, row1, col1, row2, col2, newValue):\n for i in range(row1, row2+1):\n for j in range(col1, col2+1):\n self.rectangle[i]... | 10 | Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
... | Use brute force to update a rectangle and, response to the queries in O(1). |
Python + explanation | subrectangle-queries | 0 | 1 | ```\nclass SubrectangleQueries:\n\n def __init__(self, rectangle: List[List[int]]):\n\t\t# make a new dictionary\n self.rec = {}\n\t\t# with enumerate we can iterate through the list rectangle, \n\t\t# taking each row and its index\n for i, row in enumerate(rectangle):\n\t\t\t# we map each row to its i... | 8 | Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods:
1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)`
* Updates all values with `newValue` in the subrectangle whose upper left coordinate i... | Use binary search for optimization or simply brute force. |
Python + explanation | subrectangle-queries | 0 | 1 | ```\nclass SubrectangleQueries:\n\n def __init__(self, rectangle: List[List[int]]):\n\t\t# make a new dictionary\n self.rec = {}\n\t\t# with enumerate we can iterate through the list rectangle, \n\t\t# taking each row and its index\n for i, row in enumerate(rectangle):\n\t\t\t# we map each row to its i... | 8 | Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
... | Use brute force to update a rectangle and, response to the queries in O(1). |
[Python] Similar to BUY AND SELL STOCK 3, Simple DP Solution, Logic and Intuition explained. | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | ```\nclass Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n ## RC ##\n ## APPROACH : DP ## \n\t\t## Similar to Leetcode: 123 Best Time To Buy And Sell Stock III ##\n ## LOGIC ##\n ## 1. Like typical subarray sum problem, calculate the valid subarray leng... | 54 | You are given an array of integers `arr` and an integer `target`.
You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**.
Return _the minimum sum of the l... | Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products. |
[Python] Similar to BUY AND SELL STOCK 3, Simple DP Solution, Logic and Intuition explained. | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | ```\nclass Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n ## RC ##\n ## APPROACH : DP ## \n\t\t## Similar to Leetcode: 123 Best Time To Buy And Sell Stock III ##\n ## LOGIC ##\n ## 1. Like typical subarray sum problem, calculate the valid subarray leng... | 54 | Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`.
Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Inp... | Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.... |
Python - Sliding Window - O(n) with detail comments. | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | \n```python\nclass Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n l, windowSum, res = 0, 0, float(\'inf\')\n min_till = [float(\'inf\')] * len(arr) # records smallest lenth of subarry with target sum up till index i.\n for r, num in enumerate(arr): # r:right pointer... | 6 | You are given an array of integers `arr` and an integer `target`.
You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**.
Return _the minimum sum of the l... | Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products. |
Python - Sliding Window - O(n) with detail comments. | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | \n```python\nclass Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n l, windowSum, res = 0, 0, float(\'inf\')\n min_till = [float(\'inf\')] * len(arr) # records smallest lenth of subarry with target sum up till index i.\n for r, num in enumerate(arr): # r:right pointer... | 6 | Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`.
Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Inp... | Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.... |
sliding window with two sum idea | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | ```\n # sliding window\n # sliding right each round. then move left dynamically\n # just need two sum, we can use two sum + sliding window + dp\n # where dp is m[i] represent the prvious seen qualified interval length\n # this solves the problem of overlapping\n \n lef... | 0 | You are given an array of integers `arr` and an integer `target`.
You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**.
Return _the minimum sum of the l... | Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products. |
sliding window with two sum idea | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | ```\n # sliding window\n # sliding right each round. then move left dynamically\n # just need two sum, we can use two sum + sliding window + dp\n # where dp is m[i] represent the prvious seen qualified interval length\n # this solves the problem of overlapping\n \n lef... | 0 | Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`.
Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Inp... | Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.... |
python super easy to understand prefix + suffix | find-two-non-overlapping-sub-arrays-each-with-target-sum | 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 an array of integers `arr` and an integer `target`.
You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**.
Return _the minimum sum of the l... | Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products. |
python super easy to understand prefix + suffix | find-two-non-overlapping-sub-arrays-each-with-target-sum | 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 string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`.
Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Inp... | Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.... |
Python Solution O(n) | Sliding window + DP | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | # Intuition\nUse sliding window to find the substring == target, and use dp to store min length substring (which is equal to target) so far till current index (ie. right pointer of sliding window) \n\nnow lets say ,if you find substring == target, then u take \n\nprevious_min_sm = min(previous_min_sum , current_substri... | 0 | You are given an array of integers `arr` and an integer `target`.
You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**.
Return _the minimum sum of the l... | Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products. |
Python Solution O(n) | Sliding window + DP | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | # Intuition\nUse sliding window to find the substring == target, and use dp to store min length substring (which is equal to target) so far till current index (ie. right pointer of sliding window) \n\nnow lets say ,if you find substring == target, then u take \n\nprevious_min_sm = min(previous_min_sum , current_substri... | 0 | Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`.
Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Inp... | Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.... |
[Python3] Top-Down DP + Prefix Sum | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | can be shortened but wtv\n# Code\n```\nclass Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n \n forward = list(itertools.accumulate(arr)) \n rev = reversed(arr)\n backward = list(itertools.accumulate(rev))\n backward.reverse()\n\n\n fHm = default... | 0 | You are given an array of integers `arr` and an integer `target`.
You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**.
Return _the minimum sum of the l... | Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products. |
[Python3] Top-Down DP + Prefix Sum | find-two-non-overlapping-sub-arrays-each-with-target-sum | 0 | 1 | can be shortened but wtv\n# Code\n```\nclass Solution:\n def minSumOfLengths(self, arr: List[int], target: int) -> int:\n \n forward = list(itertools.accumulate(arr)) \n rev = reversed(arr)\n backward = list(itertools.accumulate(rev))\n backward.reverse()\n\n\n fHm = default... | 0 | Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`.
Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Inp... | Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.... |
✔ Python3 Solution | DP | O(n^3) | allocate-mailboxes | 0 | 1 | # Complexity\n- Time complexity: $$O(n^3)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def minDistance(self, A, K):\n A.sort()\n N = len(A)\n P = [0] + list(accumulate(A))\n dp = [0] + [float(\'inf\')] * N\n for i in range(K):\n for j in range(N - 1,... | 1 | Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
Python 3 || 7 lines, two-ptr, recursion w/ brief explanation || T/M: 100% / 54% | allocate-mailboxes | 0 | 1 | Here\'s the plan:\nFor a given interval `interval`, we "divide and conquer" until we encounter either one of these base cases:\n1. `k = 1`: If `len(interval)` is odd, we must place the box at the middle house. If `len(interval)` is even, we may place it anywhere at either of the two middle houses. The total distance an... | 3 | Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
Short and simple memoization in Python with explanation, faster than 91% | allocate-mailboxes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to divide the `n` houses into `m` groups so that the total distance between houses and mailboxes is minimized. The problem can be typically handled by dynamic programming to explore different ways to grouping. For a group of h... | 1 | Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
📌📌 Beginner-Friendly || Easy-to-understand || DP solution 🐍 | allocate-mailboxes | 0 | 1 | ## IDEA:\n* Firstly we will create cost[i][j]. \n* cost[i][j] = total travel distance by putting one mailbox in between i & j houses.\n* It means cost[i][j] is the total travel distance from between houses[i:j] to a mailbox when putting the mailbox among houses[i:j], the best way is put the mail box at median position ... | 4 | Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
python super easy to understand DP top down Dy | allocate-mailboxes | 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 the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
Dynamic Programming | allocate-mailboxes | 0 | 1 | # Complexity\n- Time complexity: $$O(n^2)$$, where $$n=\\mathrm{houses.length}$$.\n\n- Space complexity: $$O(n^2)$$\n\n# Code\n```\nclass Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n houses.sort()\n\n @cache\n def minDistanceOneMailbox(l: int, r: int) -> int:\n ... | 0 | Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
Dynamic programming | allocate-mailboxes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ndynamic programming\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)$$ -->\nO(mn^2)\n\n- Space complexity:\n<!-- Add your space com... | 0 | Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
[Python] Top - Down Memoization | allocate-mailboxes | 0 | 1 | # Code\n```\nclass Solution:\n def minDistance(self, houses: List[int], k: int) -> int:\n cost = [[0]*101 for _ in range(101)]\n houses.sort()\n\n n = len(houses)\n ## Finding the cummulative distance if I place a mailbox at position x\n ## Many clusers are possible, for each clust... | 0 | Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
Python (Simple DP) | allocate-mailboxes | 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 the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
[Python] Intuition for DP | O(N^3) | allocate-mailboxes | 0 | 1 | As always we need to realize one thing-\n1. Median will always be optimal choice.\n\nNow if you observe, these mail boxes forms a group having some assoicated cost.\nSo we just need to minimize cost to form such k groups. (classic dp problem)\nCost can be calculated using median.\n\n# Code\n```\nclass Solution:\n de... | 0 | Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
Fk this median shit Just Give shit to houses itself in a better way !!!!! | allocate-mailboxes | 0 | 1 | \n# Code\n```\nclass Solution:\n def minDistance(self, hs: List[int], kk: int) -> int:\n hs=[0]+hs\n hs.sort()\n n=len(hs)\n dp=[[-1]*(n+1) for i in range(kk+1)]\n def rec(id,i):\n nonlocal kk\n if i>=n:\n return float("inf")\n if id=... | 0 | Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street.
Return _the **minimum** total distance between each house and its nearest mailbox_.
The test cases are generated so that the answer fits in a 32-bit integer.
**Exampl... | Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in. |
Solutions in C++ and Python3✅ | running-sum-of-1d-array | 0 | 1 | # Solutions\n```C++ []\nclass Solution {\npublic:\n vector<int> runningSum(vector<int>& nums) {\n vector<int> answer;\n int running_sum = 0;\n for (int i = 0; i < nums.size(); i++){\n running_sum += nums[i];\n answer.push_back(running_sum);\n }\n return answer... | 1 | Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`.
Return the running sum of `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[1,3,6,10\]
**Explanation:** Running sum is obtained as follows: \[1, 1+2, 1+2+3, 1+2+3+4\].
**Example 2:**
**Input:** ... | null |
Solutions in C++ and Python3✅ | running-sum-of-1d-array | 0 | 1 | # Solutions\n```C++ []\nclass Solution {\npublic:\n vector<int> runningSum(vector<int>& nums) {\n vector<int> answer;\n int running_sum = 0;\n for (int i = 0; i < nums.size(); i++){\n running_sum += nums[i];\n answer.push_back(running_sum);\n }\n return answer... | 1 | Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the `ParkingSystem` class:
* `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slot... | Think about how we can calculate the i-th number in the running sum from the (i-1)-th number. |
Comprehensive Python Explanation, 4 methods | running-sum-of-1d-array | 0 | 1 | **Intuition**\nTo solve this problem we need to create an array that will store the running sum up to that index. There are many ways to do this, starting from the most basic brute force to a neat single pass.\n\n**Method 1: Pure Brute Force; Time: O(N^2), Space: O(N)**\n```\ndef runningSum(self, nums: List[int]) -> Li... | 270 | Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`.
Return the running sum of `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[1,3,6,10\]
**Explanation:** Running sum is obtained as follows: \[1, 1+2, 1+2+3, 1+2+3+4\].
**Example 2:**
**Input:** ... | null |
Comprehensive Python Explanation, 4 methods | running-sum-of-1d-array | 0 | 1 | **Intuition**\nTo solve this problem we need to create an array that will store the running sum up to that index. There are many ways to do this, starting from the most basic brute force to a neat single pass.\n\n**Method 1: Pure Brute Force; Time: O(N^2), Space: O(N)**\n```\ndef runningSum(self, nums: List[int]) -> Li... | 270 | Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the `ParkingSystem` class:
* `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slot... | Think about how we can calculate the i-th number in the running sum from the (i-1)-th number. |
Very Easy || 0 ms || 100% || Fully Explained || Java, C++, Python, JS, Python3 | running-sum-of-1d-array | 1 | 1 | # **Java Solution:**\n```\n// Runtime: 0 ms, faster than 100.00% of Java online submissions for Running Sum of 1d Array.\n// Time Complexity : O(n)\n// Space Complexity : O(n)\nclass Solution {\n public int[] runningSum(int[] nums) {\n // Create an output array of size equal to given nums size...\n int... | 183 | Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`.
Return the running sum of `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[1,3,6,10\]
**Explanation:** Running sum is obtained as follows: \[1, 1+2, 1+2+3, 1+2+3+4\].
**Example 2:**
**Input:** ... | null |
Very Easy || 0 ms || 100% || Fully Explained || Java, C++, Python, JS, Python3 | running-sum-of-1d-array | 1 | 1 | # **Java Solution:**\n```\n// Runtime: 0 ms, faster than 100.00% of Java online submissions for Running Sum of 1d Array.\n// Time Complexity : O(n)\n// Space Complexity : O(n)\nclass Solution {\n public int[] runningSum(int[] nums) {\n // Create an output array of size equal to given nums size...\n int... | 183 | Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the `ParkingSystem` class:
* `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slot... | Think about how we can calculate the i-th number in the running sum from the (i-1)-th number. |
Simple Python Approach | running-sum-of-1d-array | 0 | 1 | # Code\n```\nclass Solution:\n def runningSum(self, nums: List[int]) -> List[int]:\n # The variable that will have the running sum\n tot = 0\n # The array that will hold the running su,\n ans = []\n # For loop\n for ele in nums:\n # Adding the element\n ... | 8 | Given an array `nums`. We define a running sum of an array as `runningSum[i] = sum(nums[0]...nums[i])`.
Return the running sum of `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** \[1,3,6,10\]
**Explanation:** Running sum is obtained as follows: \[1, 1+2, 1+2+3, 1+2+3+4\].
**Example 2:**
**Input:** ... | null |
Simple Python Approach | running-sum-of-1d-array | 0 | 1 | # Code\n```\nclass Solution:\n def runningSum(self, nums: List[int]) -> List[int]:\n # The variable that will have the running sum\n tot = 0\n # The array that will hold the running su,\n ans = []\n # For loop\n for ele in nums:\n # Adding the element\n ... | 8 | Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the `ParkingSystem` class:
* `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slot... | Think about how we can calculate the i-th number in the running sum from the (i-1)-th number. |
[Java/Python 3] Greedy Alg.: 3 methods from O(nlogn) to O(n) w/ brief explanation and analysis. | least-number-of-unique-integers-after-k-removals | 1 | 1 | **[Summary]**\nRemove k least frequent elements to make the remaining ones as least unique ints set.\n\n----\n**Method 1: HashMap and PriorityQueue** -- credit to **@usamaten** and **@sparker123**.\nCount number then put the frequencies into a PriorityQueue/heap:\n\n```java\n public int findLeastNumOfUniqueInts(int... | 170 | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
*... | null |
[Java/Python 3] Greedy Alg.: 3 methods from O(nlogn) to O(n) w/ brief explanation and analysis. | least-number-of-unique-integers-after-k-removals | 1 | 1 | **[Summary]**\nRemove k least frequent elements to make the remaining ones as least unique ints set.\n\n----\n**Method 1: HashMap and PriorityQueue** -- credit to **@usamaten** and **@sparker123**.\nCount number then put the frequencies into a PriorityQueue/heap:\n\n```java\n public int findLeastNumOfUniqueInts(int... | 170 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `... | Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first. |
Python || 3 Line || Shortest, Simplest | least-number-of-unique-integers-after-k-removals | 0 | 1 | > Idea is to remove \\"elements which have least count\\" so remaining have least unique char.\n\n\n```\ndef findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n c = Counter(arr)\n s = sorted(arr,key = lambda x:(c[x],x))\n return len(set(s[k:]))\n \n```\nupvote if you find it... | 86 | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
*... | null |
Python || 3 Line || Shortest, Simplest | least-number-of-unique-integers-after-k-removals | 0 | 1 | > Idea is to remove \\"elements which have least count\\" so remaining have least unique char.\n\n\n```\ndef findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n c = Counter(arr)\n s = sorted(arr,key = lambda x:(c[x],x))\n return len(set(s[k:]))\n \n```\nupvote if you find it... | 86 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `... | Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first. |
[Python 3] Counter and commented | least-number-of-unique-integers-after-k-removals | 0 | 1 | ```\nclass Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n # Counter sort the element in the list from most common to least common and return as a dictionary\n counter = collections.Counter(arr)\n # use most_common() to show the first n element, but in this case,... | 1 | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
*... | null |
[Python 3] Counter and commented | least-number-of-unique-integers-after-k-removals | 0 | 1 | ```\nclass Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n # Counter sort the element in the list from most common to least common and return as a dictionary\n counter = collections.Counter(arr)\n # use most_common() to show the first n element, but in this case,... | 1 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `... | Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first. |
Python 97.55% faster [EXPLAINED] | breakdown | Hash table | least-number-of-unique-integers-after-k-removals | 0 | 1 | # Intuition\r\n- This problem is similar to [majority elements](https://leetcode.com/problems/majority-element/) problem in which we have to delete the digit whose `frequency >= length(array)/2`.\r\n- Similarly in this problem we will delete those elements whose `sum of frequencies >= k`.\r\n\r\n# Approach\r\n- First w... | 4 | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
*... | null |
Python 97.55% faster [EXPLAINED] | breakdown | Hash table | least-number-of-unique-integers-after-k-removals | 0 | 1 | # Intuition\r\n- This problem is similar to [majority elements](https://leetcode.com/problems/majority-element/) problem in which we have to delete the digit whose `frequency >= length(array)/2`.\r\n- Similarly in this problem we will delete those elements whose `sum of frequencies >= k`.\r\n\r\n# Approach\r\n- First w... | 4 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `... | Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first. |
94% TC and 65% SC easy python solution | least-number-of-unique-integers-after-k-removals | 0 | 1 | ```\ndef findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n\td = Counter(arr)\n\tans = len(d)\n\td = sorted(d.items(), key = lambda x:x[1])\n\tfor i, j in d:\n\t\tif(j <= k):\n\t\t\tans -= 1\n\t\t\tk -= j\n\t\telse:\n\t\t\tbreak\n\treturn ans\n``` | 3 | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
*... | null |
94% TC and 65% SC easy python solution | least-number-of-unique-integers-after-k-removals | 0 | 1 | ```\ndef findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n\td = Counter(arr)\n\tans = len(d)\n\td = sorted(d.items(), key = lambda x:x[1])\n\tfor i, j in d:\n\t\tif(j <= k):\n\t\t\tans -= 1\n\t\t\tk -= j\n\t\telse:\n\t\t\tbreak\n\treturn ans\n``` | 3 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `... | Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first. |
Faster than 96% 🥇 | least-number-of-unique-integers-after-k-removals | 0 | 1 | ```class Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n d={}\n for i in arr:\n if i not in d:\n d[i]=0\n d[i]+=1\n l=list(d.values())\n l.sort()\n for i in range(len(l)):\n if l[i]<=k:\n ... | 6 | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
*... | null |
Faster than 96% 🥇 | least-number-of-unique-integers-after-k-removals | 0 | 1 | ```class Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n d={}\n for i in arr:\n if i not in d:\n d[i]=0\n d[i]+=1\n l=list(d.values())\n l.sort()\n for i in range(len(l)):\n if l[i]<=k:\n ... | 6 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `... | Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first. |
Beats 99% runtime || 98% memory || python || easy | least-number-of-unique-integers-after-k-removals | 0 | 1 | ```\nclass Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n\n count = Counter(arr)\n ans = len(count)\n for i in sorted(count.values()):\n k -= i\n if k < 0:\n break\n ans -= 1\n return ans\n```\n\n**if you fi... | 18 | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
*... | null |
Beats 99% runtime || 98% memory || python || easy | least-number-of-unique-integers-after-k-removals | 0 | 1 | ```\nclass Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n\n count = Counter(arr)\n ans = len(count)\n for i in sorted(count.values()):\n k -= i\n if k < 0:\n break\n ans -= 1\n return ans\n```\n\n**if you fi... | 18 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `... | Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first. |
Simple O(n) Python | least-number-of-unique-integers-after-k-removals | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nCounter the occurence then go over the values in ascending order.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- O(n)\n- Space complexity:\n- O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n... | 0 | Given an array of integers `arr` and an integer `k`. Find the _least number of unique integers_ after removing **exactly** `k` elements**.**
**Example 1:**
**Input:** arr = \[5,5,4\], k = 1
**Output:** 1
**Explanation**: Remove the single 4, only 5 is left.
**Example 2:**
**Input:** arr = \[4,3,1,1,3,3,2\], k = 3
*... | null |
Simple O(n) Python | least-number-of-unique-integers-after-k-removals | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nCounter the occurence then go over the values in ascending order.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- O(n)\n- Space complexity:\n- O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n... | 0 | LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period.
You are given a list of strings `... | Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first. |
🔥[Python 3] Binary search, beats 95% 🥷🏼 | minimum-number-of-days-to-make-m-bouquets | 0 | 1 | ```python3 []\nclass Solution:\n def minDays(self, bloomDay: List[int], m: int, k: int) -> int:\n if len(bloomDay) < m * k: return -1\n\n def isEnoughDays(days):\n flowers, bouquets = 0, 0\n for d in bloomDay:\n flowers = flowers + 1 if d <= days else 0\n ... | 5 | You are given an integer array `bloomDay`, an integer `m` and an integer `k`.
You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden.
The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet... | Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element. |
🔥[Python 3] Binary search, beats 95% 🥷🏼 | minimum-number-of-days-to-make-m-bouquets | 0 | 1 | ```python3 []\nclass Solution:\n def minDays(self, bloomDay: List[int], m: int, k: int) -> int:\n if len(bloomDay) < m * k: return -1\n\n def isEnoughDays(days):\n flowers, bouquets = 0, 0\n for d in bloomDay:\n flowers = flowers + 1 if d <= days else 0\n ... | 5 | You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column... | If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x. |
Binary Search | Time: O(n*log(n)) | Space: O(1) | minimum-number-of-days-to-make-m-bouquets | 0 | 1 | # Intuition\nSince bloomDay[i] represents the day after flower will bloom. For example if bloomDay[i] = 2, the flower will be available after 2 days. Now we have to make bouquet of size "k", we need k adjacent flowers. From this we can conclude that we can form bouquet only in the range min(bloomDay) to max(bloomDay). ... | 2 | You are given an integer array `bloomDay`, an integer `m` and an integer `k`.
You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden.
The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet... | Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element. |
Binary Search | Time: O(n*log(n)) | Space: O(1) | minimum-number-of-days-to-make-m-bouquets | 0 | 1 | # Intuition\nSince bloomDay[i] represents the day after flower will bloom. For example if bloomDay[i] = 2, the flower will be available after 2 days. Now we have to make bouquet of size "k", we need k adjacent flowers. From this we can conclude that we can form bouquet only in the range min(bloomDay) to max(bloomDay). ... | 2 | You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column... | If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x. |
Most optimal solution with explanation using binary search | minimum-number-of-days-to-make-m-bouquets | 1 | 1 | \n\n# Approach\nThe solution uses binary search to find the minimum number of days needed to make m bouquets using k adjacent flowers from the garden. The key idea is to perform a binary search on the possible days within which the flowers can bloom, and then check whether it\'s possible to make at least m bouquets usi... | 5 | You are given an integer array `bloomDay`, an integer `m` and an integer `k`.
You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden.
The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet... | Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element. |
Most optimal solution with explanation using binary search | minimum-number-of-days-to-make-m-bouquets | 1 | 1 | \n\n# Approach\nThe solution uses binary search to find the minimum number of days needed to make m bouquets using k adjacent flowers from the garden. The key idea is to perform a binary search on the possible days within which the flowers can bloom, and then check whether it\'s possible to make at least m bouquets usi... | 5 | You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column... | If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x. |
Elegant solution, detailed explanation with illustrations!! C++, python3, python | kth-ancestor-of-a-tree-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thing that comes to mind is to just go up $k$ times for each $getKthAncestor$ query. But the time complexity of that approach would be $O(q*k)$ where $q$ is the number of queries. So going up 1 step at a time is too slow. So thi... | 9 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
Elegant solution, detailed explanation with illustrations!! C++, python3, python | kth-ancestor-of-a-tree-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thing that comes to mind is to just go up $k$ times for each $getKthAncestor$ query. But the time complexity of that approach would be $O(q*k)$ where $q$ is the number of queries. So going up 1 step at a time is too slow. So thi... | 9 | Given an array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can b... | The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way. |
[Python3] binary lifting (dp) | kth-ancestor-of-a-tree-node | 0 | 1 | Algo\nFor node 0, 1, ..., n-1, we define a matrix `self.dp[][]` whose `i, j`th element indicates the `i`th node\'s `2^j` parent. Here, `i = 0, 1, ..., n-1` and `j = 0, 1, ..., int(log2(n))`. An important recursive relationship is that \n\n`self.dp[i][j] = self.dp[self.dp[i][j-1]][j-1]`. \n\nIn other words, `i`th node\'... | 59 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
[Python3] binary lifting (dp) | kth-ancestor-of-a-tree-node | 0 | 1 | Algo\nFor node 0, 1, ..., n-1, we define a matrix `self.dp[][]` whose `i, j`th element indicates the `i`th node\'s `2^j` parent. Here, `i = 0, 1, ..., n-1` and `j = 0, 1, ..., int(log2(n))`. An important recursive relationship is that \n\n`self.dp[i][j] = self.dp[self.dp[i][j-1]][j-1]`. \n\nIn other words, `i`th node\'... | 59 | Given an array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can b... | The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way. |
python code | kth-ancestor-of-a-tree-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe can solve this question through precomputation of the ansestor if we will precomputate all the ansestors of all the node then time complextiy and space complextiy will be O(n^2). But we could do one thing as we know that we can write a... | 1 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
python code | kth-ancestor-of-a-tree-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nwe can solve this question through precomputation of the ansestor if we will precomputate all the ansestors of all the node then time complextiy and space complextiy will be O(n^2). But we could do one thing as we know that we can write a... | 1 | Given an array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can b... | The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way. |
[Python] Binary lifting with simple explanation | kth-ancestor-of-a-tree-node | 0 | 1 | \nFor each node, we can calculate the parent of the parent of the node (parent2) by \n```python\nparent2 = parent[parent[node]].\n```\nSimilary, we can calculate parent4 by calculating \n```python\nparent4 = parent2[parent2[node]]\n ```\nTherefore we can caculate parent 2^(k+1) of node v by parent 2^k of node v.\n (k,v... | 10 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
[Python] Binary lifting with simple explanation | kth-ancestor-of-a-tree-node | 0 | 1 | \nFor each node, we can calculate the parent of the parent of the node (parent2) by \n```python\nparent2 = parent[parent[node]].\n```\nSimilary, we can calculate parent4 by calculating \n```python\nparent4 = parent2[parent2[node]]\n ```\nTherefore we can caculate parent 2^(k+1) of node v by parent 2^k of node v.\n (k,v... | 10 | Given an array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can b... | The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way. |
Simple Python Binary Lifting | kth-ancestor-of-a-tree-node | 1 | 1 | \tclass TreeAncestor:\n\n\t\tdef __init__(self, n: int, parent: List[int]):\n\t\t\tself.mx = int(log2(n))+1\n\t\t\tself.table = [[-1 for _ in range(n)] for i in range(self.mx)]\n\t\t\tfor i in range(n):\n\t\t\t\tself.table[0][i]=parent[i]\n\t\t\tfor i in range(1,self.mx):\n\t\t\t\tfor j in range(n):\n\t\t\t\t\tif self.... | 2 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
Simple Python Binary Lifting | kth-ancestor-of-a-tree-node | 1 | 1 | \tclass TreeAncestor:\n\n\t\tdef __init__(self, n: int, parent: List[int]):\n\t\t\tself.mx = int(log2(n))+1\n\t\t\tself.table = [[-1 for _ in range(n)] for i in range(self.mx)]\n\t\t\tfor i in range(n):\n\t\t\t\tself.table[0][i]=parent[i]\n\t\t\tfor i in range(1,self.mx):\n\t\t\t\tfor j in range(n):\n\t\t\t\t\tif self.... | 2 | Given an array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can b... | The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way. |
Very simple python solution, faster than 99%, O(1) query time complexity | kth-ancestor-of-a-tree-node | 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 tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
Very simple python solution, faster than 99%, O(1) query time complexity | kth-ancestor-of-a-tree-node | 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 array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can b... | The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way. |
Clean and Simple intuitive solution in python | kth-ancestor-of-a-tree-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> Preprocess the tree by keeping 2,4,8,16,32... ancesstor for each node. after that given any query we can reach there by using binary number property in log(n) time. \n\nFor example, if we need to find 6th ancesstor of node A, we can find t... | 0 | You are given a tree with `n` nodes numbered from `0` to `n - 1` in the form of a parent array `parent` where `parent[i]` is the parent of `ith` node. The root of the tree is node `0`. Find the `kth` ancestor of a given node.
The `kth` ancestor of a tree node is the `kth` node in the path from that node to the root no... | Build array rank where rank[i][j] is the number of votes for team i to be the j-th rank. Sort the trams by rank array. if rank array is the same for two or more teams, sort them by the ID in ascending order. |
Clean and Simple intuitive solution in python | kth-ancestor-of-a-tree-node | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. --> Preprocess the tree by keeping 2,4,8,16,32... ancesstor for each node. after that given any query we can reach there by using binary number property in log(n) time. \n\nFor example, if we need to find 6th ancesstor of node A, we can find t... | 0 | Given an array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can b... | The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way. |
Pandas vs SQL | Elegant & Short | All 30 Days of Pandas solutions ✅ | group-sold-products-by-the-date | 0 | 1 | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```Python []\ndef categorize_products(activities: pd.DataFrame) -> pd.DataFrame:\n return activities.groupby(\n \'sell_date\'\n )[\'product\'].agg([\n (\'num_sold\', \'nunique\'),\n (\'products\', lambda x: \',... | 62 | You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`.
You can apply either of the following two operations any number of times and in any order on `s`:
* Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example... | null |
Grouping With Aggregations 🏆 | group-sold-products-by-the-date | 0 | 1 | # My SQL\n\nFirst, we group the data by the `sell_date` column. This allows us to count the number of unique products sold on each sell date, which we store in the `num_sold` column.\n\nThe most challenging part is to sort and join all unique product names in each group to get the products column. We can use the `GROUP... | 7 | You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`.
You can apply either of the following two operations any number of times and in any order on `s`:
* Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example... | null |
xor-operation-in-an-array | xor-operation-in-an-array | 0 | 1 | # Code\n```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n l = [start]\n count = start\n for i in range(1,n):\n l.append(start + 2*i)\n count^= l[-1]\n return count\n \n``` | 1 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] w... | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
xor-operation-in-an-array | xor-operation-in-an-array | 0 | 1 | # Code\n```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n l = [start]\n count = start\n for i in range(1,n):\n l.append(start + 2*i)\n count^= l[-1]\n return count\n \n``` | 1 | You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane.
Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe... | Simulate the process, create an array nums and return the Bitwise XOR of all elements of it. |
Python || Simple Solution || Beginner Friendly | xor-operation-in-an-array | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n xor = 0\n for i in range(n):\n xor = xor ^ start\n start+=2\n return xor\n``` | 3 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] w... | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
Python || Simple Solution || Beginner Friendly | xor-operation-in-an-array | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n xor = 0\n for i in range(n):\n xor = xor ^ start\n start+=2\n return xor\n``` | 3 | You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane.
Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe... | Simulate the process, create an array nums and return the Bitwise XOR of all elements of it. |
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ easiest code | xor-operation-in-an-array | 0 | 1 | ***UPVOTE*** if it is helpful\n``` \nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n ans = 0\n for i in range(n):\n ans ^= start\n start+=2\n return ans\n``` | 2 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] w... | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
✅✔ SIMPLE PYTHON3 SOLUTION ✅✔ easiest code | xor-operation-in-an-array | 0 | 1 | ***UPVOTE*** if it is helpful\n``` \nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n ans = 0\n for i in range(n):\n ans ^= start\n start+=2\n return ans\n``` | 2 | You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane.
Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe... | Simulate the process, create an array nums and return the Bitwise XOR of all elements of it. |
[Python] Simple Solution | xor-operation-in-an-array | 0 | 1 | ```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n ## RC ##\n ## APPROACH : MATH ##\n res = 0\n for i in range(n):\n res ^= start + 2 * i\n return res\n``` | 23 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] w... | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
[Python] Simple Solution | xor-operation-in-an-array | 0 | 1 | ```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n ## RC ##\n ## APPROACH : MATH ##\n res = 0\n for i in range(n):\n res ^= start + 2 * i\n return res\n``` | 23 | You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane.
Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe... | Simulate the process, create an array nums and return the Bitwise XOR of all elements of it. |
Python3 || Beats 94.67% | xor-operation-in-an-array | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n s1=[]\n r = 0\n for i in range(n):\n s=start+(i*2)\n s1.append(s)\n ... | 3 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] w... | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
Python3 || Beats 94.67% | xor-operation-in-an-array | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n s1=[]\n r = 0\n for i in range(n):\n s=start+(i*2)\n s1.append(s)\n ... | 3 | You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane.
Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe... | Simulate the process, create an array nums and return the Bitwise XOR of all elements of it. |
Simple Python Solution | xor-operation-in-an-array | 0 | 1 | Time Complexcity O(N)\nSpace Complexcity O(1)\n```\nclass Solution:\n def xorOperation(self, n: int, start: int) -> int:\n re=start\n for i in range(1,n):\n ne=start+2*i\n re^=ne\n return re\n``` | 1 | You are given an integer `n` and an integer `start`.
Define an array `nums` where `nums[i] = start + 2 * i` (**0-indexed**) and `n == nums.length`.
Return _the bitwise XOR of all elements of_ `nums`.
**Example 1:**
**Input:** n = 5, start = 0
**Output:** 8
**Explanation:** Array nums is equal to \[0, 2, 4, 6, 8\] w... | Sort 'arr2' and use binary search to get the closest element for each 'arr1[i]', it gives a time complexity of O(nlogn). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.