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 simple solution both recursive and iterative | calculate-digit-sum-of-a-string | 0 | 1 | ***Recursive:***\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n def str_sum(s):\n return str(sum([int(i) for i in s]))\n\n if len(s) <= k:\n return s\n tmp = []\n for i in range(0, len(s), k):\n tmp.append(str_sum(s[i:i + k]))\n ... | 1 | You are given a string `s` consisting of digits and an integer `k`.
A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following:
1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i... | You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer. s should not have any occurrences of “ba” as a substring. |
Python3 O(n+k) || O(n) Runtime: 52ms 41.96% || Memory: 13.0mb 70.32% | calculate-digit-sum-of-a-string | 0 | 1 | Hope I didn\'t coded this in hardcore.\n```\nclass Solution:\n# O(n+k) where n is the elements present in the string\n# and k is the number of steps\n# O(N) space\n# Runtime: 52ms 41.96% || Memory: 13.0mb 70.32%\n def digitSum(self, string: str, k: int) -> str:\n if not string:\n return string\... | 1 | You are given a string `s` consisting of digits and an integer `k`.
A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following:
1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i... | You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer. s should not have any occurrences of “ba” as a substring. |
Python easy iterative solution for beginners | calculate-digit-sum-of-a-string | 0 | 1 | ```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n groups = [s[x:x+k] for x in range(0, len(s), k)]\n temp = ""\n for i in groups:\n dig = [int(y) for y in i]\n temp += str(sum(dig))\n s = temp\n ... | 2 | You are given a string `s` consisting of digits and an integer `k`.
A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following:
1. **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are i... | You can check the opposite: check if there is a ‘b’ before an ‘a’. Then, negate and return that answer. s should not have any occurrences of “ba” as a substring. |
Easy and very short solution | minimum-rounds-to-complete-all-tasks | 0 | 1 | # Intuition\nOnly one case the result will be -1. If frequency of any number is 1. If not then the answer is always \n\n ```\n int((frequency+2)/3)\n```\nFor example:\n if 2 then answer is (2+2)/3 => 1 same for others\n- 3 (3+2)/3 => 1\n- 4 (4+2)/3 => 2\n- 5 (5+2)/3 => 3\n<!-- Describe your first thoughts ... | 2 | You are given a **0-indexed** integer array `tasks`, where `tasks[i]` represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the **same difficulty level**.
Return _the **minimum** rounds required to complete all the tasks, or_ `-1` _if it is not possible to complete all the t... | What is the commonality between security devices on the same row? Each device on the same row has the same number of beams pointing towards the devices on the next row with devices. If you were given an integer array where each element is the number of security devices on each row, can you solve it? Convert the input t... |
✅ ✅ Python Greedy Solution | Dictionary ✅ ✅ | minimum-rounds-to-complete-all-tasks | 0 | 1 | # Intuition\nWhenever we encounter with frequency 1 then we can\'t able finish our task any number of rounds. While in other cases we see that every three number there minimum is always comes same.\nEx - for 2 with freq 4,5,6, we always get minimum round is 2\n for 2 with freq 7,8,9, we always get minimum round i... | 2 | You are given a **0-indexed** integer array `tasks`, where `tasks[i]` represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the **same difficulty level**.
Return _the **minimum** rounds required to complete all the tasks, or_ `-1` _if it is not possible to complete all the t... | What is the commonality between security devices on the same row? Each device on the same row has the same number of beams pointing towards the devices on the next row with devices. If you were given an integer array where each element is the number of security devices on each row, can you solve it? Convert the input t... |
[Python \ C++ \ Rust] | HashMap | minimum-rounds-to-complete-all-tasks | 0 | 1 | Python\n```\nclass Solution:\n def minimumRounds(self, tasks: List[int]) -> int:\n diffCount = defaultdict(int)\n for t in tasks:\n diffCount[t] += 1\n \n rounds = 0\n for v in diffCount.values():\n if v == 1:\n return -1\n rounds += ... | 1 | You are given a **0-indexed** integer array `tasks`, where `tasks[i]` represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the **same difficulty level**.
Return _the **minimum** rounds required to complete all the tasks, or_ `-1` _if it is not possible to complete all the t... | What is the commonality between security devices on the same row? Each device on the same row has the same number of beams pointing towards the devices on the next row with devices. If you were given an integer array where each element is the number of security devices on each row, can you solve it? Convert the input t... |
Python 3 || w/ some explanation || T/M: 94% / 93% | maximum-trailing-zeros-in-a-cornered-path | 0 | 1 | - We construct a prefix sum of 4-tuples, writing over`grid`as we go. For each cell, we determine `(up2, up5, left2, right5)`, the accummulated factors of two and five for the up-direction and the left-direction respectively.\n\n- We use the transformed`grid`to determine for each cell the count of zeros over the four pa... | 3 | You are given a 2D integer array `grid` of size `m x n`, where each cell contains a positive integer.
A **cornered path** is defined as a set of adjacent cells with **at most** one turn. More specifically, the path should exclusively move either **horizontally** or **vertically** up to the turn (if there is one), with... | Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the ast... |
[Python] Prefix Sum, O(m * n) | maximum-trailing-zeros-in-a-cornered-path | 0 | 1 | **Intuition**\nStore the prefix sum matrices of rows and columns, where each entry is `[a, b]` representing the cumulative count of (1) the factors of 2 and (2) the factors of 5.\n\n\n**Complexity**\nTime: `O(m * n)`\nSpace: `O(m * n)`\n\nBelow is my slightly-modified in-contest solution. Please upvote if you find this... | 7 | You are given a 2D integer array `grid` of size `m x n`, where each cell contains a positive integer.
A **cornered path** is defined as a set of adjacent cells with **at most** one turn. More specifically, the path should exclusively move either **horizontally** or **vertically** up to the turn (if there is one), with... | Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the ast... |
[Python] Self-explain code using Prefix sum | maximum-trailing-zeros-in-a-cornered-path | 0 | 1 | # Intuition\nSince product of numbers and its trailing zeros will never go down with additional numbers. The problem becomes "**for each point (i,j) in the grid, compute the max trailling zeros of product of 4 L-shape pathes(till boundary). Then find the max num of trailling zeros over all points**" That\'s definately ... | 0 | You are given a 2D integer array `grid` of size `m x n`, where each cell contains a positive integer.
A **cornered path** is defined as a set of adjacent cells with **at most** one turn. More specifically, the path should exclusively move either **horizontally** or **vertically** up to the turn (if there is one), with... | Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the ast... |
Python3 Vectorized Solution | maximum-trailing-zeros-in-a-cornered-path | 0 | 1 | I hope this answer is helpful to those who prefer more formal explanations (like myself).\n___\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI made the following two observations:\n1. Let $g(x)$ denote the number of trailing zeros of a number $x$. Then \n$g(x) = \\min_{p\\in\\{2,5\\... | 0 | You are given a 2D integer array `grid` of size `m x n`, where each cell contains a positive integer.
A **cornered path** is defined as a set of adjacent cells with **at most** one turn. More specifically, the path should exclusively move either **horizontally** or **vertically** up to the turn (if there is one), with... | Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the ast... |
Python | maximum-trailing-zeros-in-a-cornered-path | 0 | 1 | \n```\nclass Solution:\n def maxTrailingZeros(self, grid) :\n matrix = grid \n self.ans,prefix,suffix = 0,[i[:] for i in matrix ],[i[:] for i in matrix ]\n \n def f(n):\n x,y =0,0\n while n%2==0:\n n = n//2\n x+=1\n while n% 5==... | 0 | You are given a 2D integer array `grid` of size `m x n`, where each cell contains a positive integer.
A **cornered path** is defined as a set of adjacent cells with **at most** one turn. More specifically, the path should exclusively move either **horizontally** or **vertically** up to the turn (if there is one), with... | Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the ast... |
Python | Simple Solution | O(mn) | maximum-trailing-zeros-in-a-cornered-path | 0 | 1 | # Code\n```\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n def factors(num):\n res = [0,0]\n while num > 1 and num%2 == 0:\n num //= 2\n res[0] += 1\n while num > 1 and num%5 == 0:\n num //= 5\n ... | 0 | You are given a 2D integer array `grid` of size `m x n`, where each cell contains a positive integer.
A **cornered path** is defined as a set of adjacent cells with **at most** one turn. More specifically, the path should exclusively move either **horizontally** or **vertically** up to the turn (if there is one), with... | Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the ast... |
[Python3] prefix sums | maximum-trailing-zeros-in-a-cornered-path | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/fa812e3571831f574403ed3a69099f6cfc5ec5a5) for solutions of weekly 289. \n\n```\nclass Solution:\n def maxTrailingZeros(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n f2 = [[0]*n for _ in range(m)]\n ... | 1 | You are given a 2D integer array `grid` of size `m x n`, where each cell contains a positive integer.
A **cornered path** is defined as a set of adjacent cells with **at most** one turn. More specifically, the path should exclusively move either **horizontally** or **vertically** up to the turn (if there is one), with... | Choosing the asteroid to collide with can be done greedily. If an asteroid will destroy the planet, then every bigger asteroid will also destroy the planet. You only need to check the smallest asteroid at each collision. If it will destroy the planet, then every other asteroid will also destroy the planet. Sort the ast... |
[python3] dfs solution for reference | longest-path-with-different-adjacent-characters | 0 | 1 | At every node, there are three strings to consider.\n- Longest child string whose last char == parent_char\n- Longest child string whose last char != parent_char\n- Two longest child strings whose last char != parent_char - joined by parent char in the middle.\n\nThe code below uses a dfs traversal in the graph, that ... | 3 | You are given a **tree** (i.e. a connected, undirected graph that has no cycles) **rooted** at node `0` consisting of `n` nodes numbered from `0` to `n - 1`. The tree is represented by a **0-indexed** array `parent` of size `n`, where `parent[i]` is the parent of node `i`. Since node `0` is the root, `parent[0] == -1`.... | From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by ... |
Simple Python Solution with explanation 🔥 | longest-path-with-different-adjacent-characters | 0 | 1 | # Approach\n\n* Create adjacency list since its easier to traverse with adjacency list\n\n* Lets solve this recursively using Depth First Search (DFS)\n\n \n \n\n * Lets assum... | 2 | You are given a **tree** (i.e. a connected, undirected graph that has no cycles) **rooted** at node `0` consisting of `n` nodes numbered from `0` to `n - 1`. The tree is represented by a **0-indexed** array `parent` of size `n`, where `parent[i]` is the parent of node `i`. Since node `0` is the root, `parent[0] == -1`.... | From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by ... |
DFS solution with explanations(What two options are for each recursive call). | longest-path-with-different-adjacent-characters | 0 | 1 | # Intuition\n1. The path here is counting the number of nodes on a path instead of edges.\n2. Similar to 543. Diameter of Binary Tree, the longest path may or may not pass through the root.\n3. This leaves us with two options: \n a . The longest path passes the current node, and in the subtree which is rooted by th... | 2 | You are given a **tree** (i.e. a connected, undirected graph that has no cycles) **rooted** at node `0` consisting of `n` nodes numbered from `0` to `n - 1`. The tree is represented by a **0-indexed** array `parent` of size `n`, where `parent[i]` is the parent of node `i`. Since node `0` is the root, `parent[0] == -1`.... | From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by ... |
Python, DFS | longest-path-with-different-adjacent-characters | 0 | 1 | ```\nclass Solution:\n def longestPath(self, parent: List[int], s: str) -> int:\n def dfs(node):\n node_char = s[node] \n longest = second_longest = 0\n for child in children[node]:\n child_path = dfs(child)\n if s[child] != node_char: ... | 2 | You are given a **tree** (i.e. a connected, undirected graph that has no cycles) **rooted** at node `0` consisting of `n` nodes numbered from `0` to `n - 1`. The tree is represented by a **0-indexed** array `parent` of size `n`, where `parent[i]` is the parent of node `i`. Since node `0` is the root, `parent[0] == -1`.... | From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by ... |
✅ python- EasySolution-BEATS 95% | longest-path-with-different-adjacent-characters | 0 | 1 | Easy Approach \uD83D\uDCAF. Enjoy the day.\n```\nclass Solution:\n def longestPath(self, parent: List[int], s: str) -> int:\n t={}\n for i in range(1,len(parent)):\n if parent[i] not in t:\n t[parent[i]]=[i]\n else:\n t[parent[i]].append(i)\n ... | 16 | You are given a **tree** (i.e. a connected, undirected graph that has no cycles) **rooted** at node `0` consisting of `n` nodes numbered from `0` to `n - 1`. The tree is represented by a **0-indexed** array `parent` of size `n`, where `parent[i]` is the parent of node `i`. Since node `0` is the root, `parent[0] == -1`.... | From the given array favorite, create a graph where for every index i, there is a directed edge from favorite[i] to i. The graph will be a combination of cycles and chains of acyclic edges. Now, what are the ways in which we can choose employees to sit at the table? The first way by which we can choose employees is by ... |
simple python solution | intersection-of-multiple-arrays | 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 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
[Python] good looking solution, easy to understand | intersection-of-multiple-arrays | 0 | 1 | \n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def intersection(self, nums: List[List[int]]) -> List[int]:\n\n ll = []\n sortedNums =... | 2 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
[Python3] - 1 LINE Solution || Simple Explanation | intersection-of-multiple-arrays | 0 | 1 | # **Idea**\n<br>\n\n##### To solve this question easily, we can take advantage of one of the specifications:\n\n*nums[i] is a non-empty array of **distinct** positive integers*\n\n<br>\n\n##### Since the integers in each sub-list of nums are distinct (i.e. unique), we can count the number of occurences of every integer... | 39 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
No set, sort, or hashmap: use Masks | intersection-of-multiple-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* It\'s highlighted that the integers in each sublist are **distinct**.\n* The result must be sorted in ascending order.\n * I think the point is to build your result in a way that it turns out to be ascending.\n * Not that you buil... | 1 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
94.58% faster using set and & operator in Python | intersection-of-multiple-arrays | 0 | 1 | \n\n```\nclass Solution:\n def intersection(self, nums: List[List[int]]) -> List[int]:\n res = set(nums[0])\n for i in range(1, len(nums)):\n res &= set(nums[i])\n res = list(... | 12 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
Python Solution || Hashmap | intersection-of-multiple-arrays | 0 | 1 | ```\nclass Solution:\n def intersection(self, nums: List[List[int]]) -> List[int]:\n d = {}\n \n for i in range(len(nums)):\n for j in nums[i]:\n if j not in d:\n d[j] = 1\n else:\n d[j]+=1\n \n ... | 6 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
Python - Short & Simple - Set | intersection-of-multiple-arrays | 0 | 1 | ```\ndef intersection(self, nums: List[List[int]]) -> List[int]:\n temp = set(nums[0])\n for i in range(1,len(nums)):\n temp = (temp & set(nums[i]))\n \n return list(sorted(temp))\n``` | 2 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
Python 2 beginner friendly approaches | intersection-of-multiple-arrays | 0 | 1 | ### Method 1\n```\nclass Solution:\n def intersection(self, nums: List[List[int]]) -> List[int]:\n res = []\n concat = []\n for i in range(len(nums)):\n concat += nums[i]\n for i in set(concat):\n if concat.count(i) == len(nums):\n res.append(i)\n ... | 4 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
97.81% faster using set and set.intersection | intersection-of-multiple-arrays | 0 | 1 | \n```\nclass Solution:\n def intersection(self, nums: List[List[int]]) -> List[int]:\n inter = set(nums[0])\n for i in range(1, len(nums)):\n inter = inter.intersection(set(nums[i]))... | 1 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
Python3 | intersection-of-multiple-arrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
Python solution 3 line | intersection-of-multiple-arrays | 0 | 1 | ```\nclass Solution:\n def intersection(self, nums: List[List[int]]) -> List[int]:\n a=set(nums[0])\n inters=a.intersection(*nums)\n return sorted(list(inters))\n\n\n``` | 3 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
Python Easy Understanding | intersection-of-multiple-arrays | 0 | 1 | ```\nclass Solution:\n def intersection(self, nums: List[List[int]]) -> List[int]:\n \n intersection = nums[0]\n \n for i in range(1,len(nums)):\n intersection = set(nums[i]) & set(intersection)\n \n return sorted(list(intersection))\n``` | 2 | Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.
**Example 1:**
**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Outpu... | If we consider costs from high to low, what is the maximum cost of a single candy that we can get for free? How can we generalize this approach to maximize the costs of the candies we get for free? Can “sorting” the array help us find the minimum cost? If we consider costs from high to low, what is the maximum cost of ... |
Worst Memory Solution|| Recursion Approach||Python | count-lattice-points-inside-a-circle | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI guess you already know the question , its quite understandable .\nI don\'t know why i am obsessed with recursion , the first approach came to my mind after seeing most question is if i can somehow use memoization. So here is result of t... | 1 | Given a 2D integer array `circles` where `circles[i] = [xi, yi, ri]` represents the center `(xi, yi)` and radius `ri` of the `ith` circle drawn on a grid, return _the **number of lattice points**_ _that are present inside **at least one** circle_.
**Note:**
* A **lattice point** is a point with integer coordinates.... | Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the val... |
[Java/C++/Python] O(1) Space | count-lattice-points-inside-a-circle | 1 | 1 | Updated this post, \nsince I noticed almost every solutions will use `set`,\nwith extra space complexity.\n<br>\n# **Solution 1: Set**\n## **Explanation**\nFor each circle `(x, y)`,\nenumerate `i` from `x - r` to `x + r`\nenumerate `j` from `y - r` to `y + r`\nCheck if `(i, j)` in this circle.\n\nIf so, add the point t... | 37 | Given a 2D integer array `circles` where `circles[i] = [xi, yi, ri]` represents the center `(xi, yi)` and radius `ri` of the `ith` circle drawn on a grid, return _the **number of lattice points**_ _that are present inside **at least one** circle_.
**Note:**
* A **lattice point** is a point with integer coordinates.... | Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the val... |
Python set solution, Easy | count-lattice-points-inside-a-circle | 0 | 1 | # Intuition\nThe "Count Lattice Points" problem involves counting the number of lattice points that lie within or on the boundary of a given set of circles. A lattice point is a point in the plane with integer coordinates. Our initial thoughts are to iterate through the lattice points and determine whether each point i... | 0 | Given a 2D integer array `circles` where `circles[i] = [xi, yi, ri]` represents the center `(xi, yi)` and radius `ri` of the `ith` circle drawn on a grid, return _the **number of lattice points**_ _that are present inside **at least one** circle_.
**Note:**
* A **lattice point** is a point with integer coordinates.... | Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the val... |
[Python] Optimized time/space complexity solution without using set | count-lattice-points-inside-a-circle | 0 | 1 | > **number of circles**: N\n**length of range of xi, yi and r**: M \n\n\n# Intuition\nThis problem can easily be solved by calculating points inside each circle and using Set to get union, or scan through all possible points and check each circle. However, the theoritical time complexity $$O(NM^2)$$ is not optimized. W... | 0 | Given a 2D integer array `circles` where `circles[i] = [xi, yi, ri]` represents the center `(xi, yi)` and radius `ri` of the `ith` circle drawn on a grid, return _the **number of lattice points**_ _that are present inside **at least one** circle_.
**Note:**
* A **lattice point** is a point with integer coordinates.... | Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the val... |
numpy is all you needed. | count-lattice-points-inside-a-circle | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nJust use numpy. np.mgrid\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\nO(n * 500 * 500)\n\n- Space complexity:\n<!-- ... | 0 | Given a 2D integer array `circles` where `circles[i] = [xi, yi, ri]` represents the center `(xi, yi)` and radius `ri` of the `ith` circle drawn on a grid, return _the **number of lattice points**_ _that are present inside **at least one** circle_.
**Note:**
* A **lattice point** is a point with integer coordinates.... | Fix the first element of the hidden sequence to any value x and ignore the given bounds. Notice that we can then determine all the other elements of the sequence by using the differences array. We will also be able to determine the difference between the minimum and maximum elements of the sequence. Notice that the val... |
Python BS O(n log n) | count-number-of-rectangles-containing-each-point | 0 | 1 | - Time complexity: O(n log n)\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:\n\n def bs(arr, a):\n left = 0\n right = len(arr) - 1\n\n while left <= right:\n ... | 1 | You are given a 2D integer array `rectangles` where `rectangles[i] = [li, hi]` indicates that `ith` rectangle has a length of `li` and a height of `hi`. You are also given a 2D integer array `points` where `points[j] = [xj, yj]` is a point with coordinates `(xj, yj)`.
The `ith` rectangle has its **bottom-left corner**... | Could you determine the rank of every item efficiently? We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item. Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as ... |
5-lines easy solution with explanation and analysis | count-number-of-rectangles-containing-each-point | 0 | 1 | Notice the constraints of y-axis: `1 <= hi, yj <= 100`.\nWe can sort rectangles by x-axis and separate them by y-axis.\nWhen we search for the answer of a point (x, y) we can search only in all lists with `height >= y`, and with the fact that lengths (x\'s) are already sorted, we can use binary search to find the numbe... | 4 | You are given a 2D integer array `rectangles` where `rectangles[i] = [li, hi]` indicates that `ith` rectangle has a length of `li` and a height of `hi`. You are also given a 2D integer array `points` where `points[j] = [xj, yj]` is a point with coordinates `(xj, yj)`.
The `ith` rectangle has its **bottom-left corner**... | Could you determine the rank of every item efficiently? We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item. Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as ... |
[Python3] binary search | count-number-of-rectangles-containing-each-point | 0 | 1 | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/c2730559a4a05cfc912d81e5d7a3d4d607079401) for solutions of weekly 290.\n\n```\nclass Solution:\n def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:\n mp = defaultdict(list)\n for l, h in r... | 3 | You are given a 2D integer array `rectangles` where `rectangles[i] = [li, hi]` indicates that `ith` rectangle has a length of `li` and a height of `hi`. You are also given a 2D integer array `points` where `points[j] = [xj, yj]` is a point with coordinates `(xj, yj)`.
The `ith` rectangle has its **bottom-left corner**... | Could you determine the rank of every item efficiently? We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item. Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as ... |
[Python] Binary Search (detailed explanation) | count-number-of-rectangles-containing-each-point | 0 | 1 | ### Idea\n\n- `Point (px, py)` should be counted when `px <= length and py <= height`\n- We can start with a simpler question -> If the point is not 2D, and it\'s just a 1D integer, how can we solve this?\n\n### Simpler question (1D)\n- Question: \n\t- Given a list of point `xi` and a list of rectangle\'s length `li`. ... | 8 | You are given a 2D integer array `rectangles` where `rectangles[i] = [li, hi]` indicates that `ith` rectangle has a length of `li` and a height of `hi`. You are also given a 2D integer array `points` where `points[j] = [xj, yj]` is a point with coordinates `(xj, yj)`.
The `ith` rectangle has its **bottom-left corner**... | Could you determine the rank of every item efficiently? We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item. Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as ... |
Python: Array dictionary and Binary search. beats 99 % other solutions. | count-number-of-rectangles-containing-each-point | 0 | 1 | # Intuition\nGroup rectangle widths by height ```h```. Height is chosen because the maximum value of ```h``` is 100. Thus it is easy to use array as dictionary. \n\nBinary search on the grouped widths.\n\n# Approach\n\n\n# Complexity\n- Time complexity: \n```n = len(rectangles), m = len(points), y = len(ydict[x])``` \n... | 0 | You are given a 2D integer array `rectangles` where `rectangles[i] = [li, hi]` indicates that `ith` rectangle has a length of `li` and a height of `hi`. You are also given a 2D integer array `points` where `points[j] = [xj, yj]` is a point with coordinates `(xj, yj)`.
The `ith` rectangle has its **bottom-left corner**... | Could you determine the rank of every item efficiently? We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item. Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as ... |
python3 binary search on heights | count-number-of-rectangles-containing-each-point | 0 | 1 | \n\n# Code\n```\nimport bisect\nclass Solution:\n def countRectangles(self, rectangles: List[List[int]], points: List[List[int]]) -> List[int]:\n heights = defaultdict(list)\n for x,y in rectangles:\n heights[y].append(x)\n for k,v in heights.items():\n heights[k] = sorted(... | 0 | You are given a 2D integer array `rectangles` where `rectangles[i] = [li, hi]` indicates that `ith` rectangle has a length of `li` and a height of `hi`. You are also given a 2D integer array `points` where `points[j] = [xj, yj]` is a point with coordinates `(xj, yj)`.
The `ith` rectangle has its **bottom-left corner**... | Could you determine the rank of every item efficiently? We can perform a breadth-first search from the starting position and know the length of the shortest path from start to every item. Sort all the items according to the conditions listed in the problem, and return the first k (or all if less than k exist) items as ... |
python3 Solution | number-of-flowers-in-full-bloom | 0 | 1 | \n```\nclass Solution:\n def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:\n start=sorted(flowers,key=lambda x:x[0])\n end=sorted(flowers,key=lambda x:x[1])\n ans=[]\n for man in people:\n i=bisect_left(end,man,key=lambda x:x[1])\n ... | 3 | You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
🚀 Priority Queue || Explained Intuition || Commented Code🚀 | number-of-flowers-in-full-bloom | 1 | 1 | # Problem Description\n\nThe problem involves processing data about the **bloom time** of flowers and the arrival times of people to determine the **number** of flowers in full bloom at each person\'s arrival time.\n\nGiven a 2D array `flowers` representing the bloom intervals for each flower and an array `people` repr... | 27 | You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
【Video】Give me 15 minutes - How we can think about a solution - Python, JavaScript, Java, C++ | number-of-flowers-in-full-bloom | 1 | 1 | Welcome to my post! This post starts with "How we think about a solution". In other words, that is my thought process to solve the question. This post explains how I get to my solution instead of just posting solution codes or out of blue algorithms. I hope it is helpful for someone.\n\n# Intuition\ncalculate how many ... | 48 | You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
✅100%🔥Easy Solution🔥With explanation🔥|| Binary Search || Beginner Friendly ✅ | number-of-flowers-in-full-bloom | 0 | 1 | # Intuition\n\nThe problem aims to determine the number of flowers that are in full bloom at specific dates. To achieve this, the code utilizes binary search to find the positions where the given dates fall in the flower blooming date ranges. The problem is solved by sorting the flowers by their bloom start and bloom e... | 2 | You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
|| Beginner Friendly || Easy Solution Line By Line Explanation || Beats 100 % || PYTHON || C++ || | number-of-flowers-in-full-bloom | 1 | 1 | # BEATS 100% Python And Ruby\n\n\n\n# Intuition\nThe intuition for this problem is to track the bloom intervals of flowers and determine the bloom status for each person. This involves processing the interva... | 24 | You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
Video Solution | Explanation With Drawings | In Depth | Java | C++ | Python 3 | number-of-flowers-in-full-bloom | 1 | 1 | # Intuition, approach and complexity discussed in detail in video solution\nhttps://youtu.be/s3pk2n_Fi3g\n\n# Code\nJava\n```\nclass Solution {\n public int[] fullBloomFlowers(int[][] flowers, int[] persons) {\n int n = flowers.length;\n int[] bloomStartTime = new int[n], bloomEndTime = new int[n];\n ... | 1 | You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
A True Classic Line Sweep Algo | number-of-flowers-in-full-bloom | 0 | 1 | \n# Code\n```\nclass Solution:\n def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:\n\n sweep = collections.defaultdict(int)\n\n for s,e in flowers:\n sweep[s]+=1\n sweep[e+1]-=1\n\n flowers_in_bloom = 0\n times = []\n for ti... | 1 | You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
🧩 "Blooming Flowers Problem: A Step-by-Step Guide with Simple Code Explanation 🌼📝" | number-of-flowers-in-full-bloom | 0 | 1 | # Intuition:\n\nIn simple terms, this code sorts the flowers by their start and end times and then counts how many flowers are blooming at the preferred times of each person. It returns a list of counts for each person. The time complexity is reasonably efficient, while the space complexity depends on the number of flo... | 1 | You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
Go/Python/JavaScript/Java O(n*log(n)) time | O(n) space | number-of-flowers-in-full-bloom | 1 | 1 | # Complexity\n- Time complexity: $$O(n*log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nfunc fullBloomFlowers(flowers [][]int, people []int) []int {\n starts := make([]int,len(flowers))\n ... | 1 | You are given a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
sweep line | number-of-flowers-in-full-bloom | 1 | 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 a **0-indexed** 2D integer array `flowers`, where `flowers[i] = [starti, endi]` means the `ith` flower will be in **full bloom** from `starti` to `endi` (**inclusive**). You are also given a **0-indexed** integer array `people` of size `n`, where `poeple[i]` is the time that the `ith` person will arrive t... | Divide the corridor into segments. Each segment has two seats, starts precisely with one seat, and ends precisely with the other seat. How many dividers can you install between two adjacent segments? You must install precisely one. Otherwise, you would have created a section with not exactly two seats. If there are k p... |
python ||O(N) | count-prefixes-of-a-given-string | 0 | 1 | Time Complexcity O(N)\nspace Complexcity O(1)\n```\nclass Solution:\n def countPrefixes(self, words: List[str], s: str) -> int:\n count=0\n for word in words:\n n=len(word)\n if s[0:n]==word:\n count+=1\n return count\n \n``` | 1 | You are given a string array `words` and a string `s`, where `words[i]` and `s` comprise only of **lowercase English letters**.
Return _the **number of strings** in_ `words` _that are a **prefix** of_ `s`.
A **prefix** of a string is a substring that occurs at the beginning of the string. A **substring** is a contigu... | Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of ... |
Python simple solution | count-prefixes-of-a-given-string | 0 | 1 | # Approach\nCheck for each word if is prefix of s.\n\n# Code\n```\nclass Solution:\n def countPrefixes(self, words: List[str], s: str) -> int:\n res = 0\n\n for word in words:\n if s.startswith(word):\n res += 1\n\n return res\n```\n\nLike it? Please upvote! | 6 | You are given a string array `words` and a string `s`, where `words[i]` and `s` comprise only of **lowercase English letters**.
Return _the **number of strings** in_ `words` _that are a **prefix** of_ `s`.
A **prefix** of a string is a substring that occurs at the beginning of the string. A **substring** is a contigu... | Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of ... |
Python one line solution | count-prefixes-of-a-given-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def countPrefixes(self, words: List[str], s: str) -> int:\n return len([i for i in words if s.startswith(i)])\n``` | 2 | You are given a string array `words` and a string `s`, where `words[i]` and `s` comprise only of **lowercase English letters**.
Return _the **number of strings** in_ `words` _that are a **prefix** of_ `s`.
A **prefix** of a string is a substring that occurs at the beginning of the string. A **substring** is a contigu... | Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of ... |
one line solution | count-prefixes-of-a-given-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def countPrefixes(self, words: List[str], s: str) -> int:\n return sum(1 for x in words if s.startswith(x))\n``` | 3 | You are given a string array `words` and a string `s`, where `words[i]` and `s` comprise only of **lowercase English letters**.
Return _the **number of strings** in_ `words` _that are a **prefix** of_ `s`.
A **prefix** of a string is a substring that occurs at the beginning of the string. A **substring** is a contigu... | Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of ... |
Easy python solution | count-prefixes-of-a-given-string | 0 | 1 | ```\nclass Solution:\n def countPrefixes(self, words: List[str], s: str) -> int:\n count=0\n for i in words:\n if (s[:len(i)]==i):\n count+=1\n return count\n``` | 15 | You are given a string array `words` and a string `s`, where `words[i]` and `s` comprise only of **lowercase English letters**.
Return _the **number of strings** in_ `words` _that are a **prefix** of_ `s`.
A **prefix** of a string is a substring that occurs at the beginning of the string. A **substring** is a contigu... | Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of ... |
Pyhton3 oneliner using startswith() | count-prefixes-of-a-given-string | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def countPrefixes(self, words: List[str], s: str) -> int:\n count = 0\n for i in words:\n if s.startswith(i):\n count += 1\n return count\n\n #One Liner\n\n return sum(1 for i in words if s.startswith(i))\n``` | 1 | You are given a string array `words` and a string `s`, where `words[i]` and `s` comprise only of **lowercase English letters**.
Return _the **number of strings** in_ `words` _that are a **prefix** of_ `s`.
A **prefix** of a string is a substring that occurs at the beginning of the string. A **substring** is a contigu... | Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of ... |
Easy Python solution | count-prefixes-of-a-given-string | 0 | 1 | ```\ndef countPrefixes(self, words: List[str], s: str) -> int:\n c=0\n for i in words:\n l=len(i)\n if i==s[:l]:\n c+=1\n return c\n``` | 3 | You are given a string array `words` and a string `s`, where `words[i]` and `s` comprise only of **lowercase English letters**.
Return _the **number of strings** in_ `words` _that are a **prefix** of_ `s`.
A **prefix** of a string is a substring that occurs at the beginning of the string. A **substring** is a contigu... | Notice that the number of 1’s to be grouped together is fixed. It is the number of 1's the whole array has. Call this number total. We should then check for every subarray of size total (possibly wrapped around), how many swaps are required to have the subarray be all 1’s. The number of swaps required is the number of ... |
💡Python O(n) simple solution | minimum-average-difference | 0 | 1 | # Intuition\nAccording to constraint `1 <= nums.length <= 10 ** 5` we cannot re-calculate avg values for sub-arrays every time.\n\n# Approach\n\n1. Right handside area\n 1. Calculate a sum for all elements in `nums` for the further tracking\n 2. Remember `nums` len\n2. Left handside area\n 1. Set placeholders bec... | 2 | You are given a **0-indexed** integer array `nums` of length `n`.
The **average difference** of the index `i` is the **absolute** **difference** between the average of the **first** `i + 1` elements of `nums` and the average of the **last** `n - i - 1` elements. Both averages should be **rounded down** to the nearest ... | Which data structure can be used to efficiently check if a string exists in startWords? After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords? |
Python || 91.23 % Faster || Prefix Sum || O(n) Solution | minimum-average-difference | 0 | 1 | ```\nclass Solution:\n def minimumAverageDifference(self, nums: List[int]) -> int:\n n=len(nums)\n pre,post=[nums[0]]*n,[nums[n-1]]*n\n for i in range(1,n):\n pre[i]=(nums[i]+pre[i-1])\n for i in range(n-2,-1,-1):\n post[i]=(nums[i]+post[i+1])\n m,f=1000000,n-... | 2 | You are given a **0-indexed** integer array `nums` of length `n`.
The **average difference** of the index `i` is the **absolute** **difference** between the average of the **first** `i + 1` elements of `nums` and the average of the **last** `n - i - 1` elements. Both averages should be **rounded down** to the nearest ... | Which data structure can be used to efficiently check if a string exists in startWords? After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords? |
Python | SImple iterative solution | minimum-average-difference | 0 | 1 | # Approach\n1) Calculate initial sum of all elements in array\n2) On each iteration step calculate prefix and suffix (initila sum - prefix) and recalculate answer!\n\n# Complexity\n- Time complexity: $$O(N)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution:\n def minimumAverageDifference(self, nums: L... | 1 | You are given a **0-indexed** integer array `nums` of length `n`.
The **average difference** of the index `i` is the **absolute** **difference** between the average of the **first** `i + 1` elements of `nums` and the average of the **last** `n - i - 1` elements. Both averages should be **rounded down** to the nearest ... | Which data structure can be used to efficiently check if a string exists in startWords? After appending a letter, all letters of a string can be rearranged in any possible way. How can we use this to reduce our search space while checking if a string in targetWords can be obtained from a string in startWords? |
[Python] DFS solution with explaination | count-unguarded-cells-in-the-grid | 0 | 1 | Idea is to mark all locations which the guard can see with \'X\' value. Then later just count the non marked cells.\n\nDefines a named tuple called "Directions" with two fields x and y, which represents the movement directions on a 2D grid.\n\n\nCreates a matrix with zeros of size m x n and fills it with \'G\' and \'W\... | 1 | You are given two integers `m` and `n` representing a **0-indexed** `m x n` grid. You are also given two 2D integer arrays `guards` and `walls` where `guards[i] = [rowi, coli]` and `walls[j] = [rowj, colj]` represent the positions of the `ith` guard and `jth` wall respectively.
A guard can see **every** cell in the fo... | List the planting like the diagram above shows, where a row represents the timeline of a seed. A row i is above another row j if the last day planting seed i is ahead of the last day for seed j. Does it have any advantage to spend some days to plant seed j before completely planting seed i? No. It does not help seed j ... |
Python solution using DFS. | count-unguarded-cells-in-the-grid | 0 | 1 | \n```\nclass Solution:\n def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int:\n \n #Create a matrix, hint from question\n mat = [[0 for _ in range(n)] for _ in range(m)] \n \n for [i,j] in guards:\n mat[i][j] = 1 \n f... | 1 | You are given two integers `m` and `n` representing a **0-indexed** `m x n` grid. You are also given two 2D integer arrays `guards` and `walls` where `guards[i] = [rowi, coli]` and `walls[j] = [rowj, colj]` represent the positions of the `ith` guard and `jth` wall respectively.
A guard can see **every** cell in the fo... | List the planting like the diagram above shows, where a row represents the timeline of a seed. A row i is above another row j if the last day planting seed i is ahead of the last day for seed j. Does it have any advantage to spend some days to plant seed j before completely planting seed i? No. It does not help seed j ... |
it works | count-unguarded-cells-in-the-grid | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You are given two integers `m` and `n` representing a **0-indexed** `m x n` grid. You are also given two 2D integer arrays `guards` and `walls` where `guards[i] = [rowi, coli]` and `walls[j] = [rowj, colj]` represent the positions of the `ith` guard and `jth` wall respectively.
A guard can see **every** cell in the fo... | List the planting like the diagram above shows, where a row represents the timeline of a seed. A row i is above another row j if the last day planting seed i is ahead of the last day for seed j. Does it have any advantage to spend some days to plant seed j before completely planting seed i? No. It does not help seed j ... |
27 lines easy to understand | count-unguarded-cells-in-the-grid | 0 | 1 | # Intuition\nThe usual walk in 4 directions from each guard and mark space as guarded.\n\nHowever, can optimise time by stopping the walk when you encounter a guard (and of course wall).\n\nTo avoid the final extra iteration over the space grid to count unguarded cells, can include a counter of empty space that is decr... | 0 | You are given two integers `m` and `n` representing a **0-indexed** `m x n` grid. You are also given two 2D integer arrays `guards` and `walls` where `guards[i] = [rowi, coli]` and `walls[j] = [rowj, colj]` represent the positions of the `ith` guard and `jth` wall respectively.
A guard can see **every** cell in the fo... | List the planting like the diagram above shows, where a row represents the timeline of a seed. A row i is above another row j if the last day planting seed i is ahead of the last day for seed j. Does it have any advantage to spend some days to plant seed j before completely planting seed i? No. It does not help seed j ... |
Solution + Intuition + Explanation with Pictures 🏞 | escape-the-spreading-fire | 1 | 1 | \n\n`, and you want to travel... | Try to find a pattern in how nums changes. Let m be the original length of nums. If time_i / m (integer division) is even, then nums is at its original size or decreasing in size. If it is odd, then it is empty, or increasing in size. time_i % m can be used to find how many elements are in nums at minute time_i. |
Useing binary search on the answer and BFS | escape-the-spreading-fire | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst try to solve this problem.\nSuppose you start without waiting. Can you find out if you will be able to reach destination? (Simple multisource BFS right?)\nNow notice this,\nIf you can escape from the fire after x minitues of waiting... | 0 | You are given a **0-indexed** 2D integer array `grid` of size `m x n` which represents a field. Each cell has one of three values:
* `0` represents grass,
* `1` represents fire,
* `2` represents a wall that you and fire cannot pass through.
You are situated in the top-left cell, `(0, 0)`, and you want to travel... | Try to find a pattern in how nums changes. Let m be the original length of nums. If time_i / m (integer division) is even, then nums is at its original size or decreasing in size. If it is odd, then it is empty, or increasing in size. time_i % m can be used to find how many elements are in nums at minute time_i. |
Escape set up with alternate test cases | Commented and Explained | escape-the-spreading-fire | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNice version of robot movement with changing terrain. Useful in a number of cases (imagine your battery gets less juice as time goes on instead of fires sprouting up... same idea different implementation details). \n\nAs such, we know tha... | 0 | You are given a **0-indexed** 2D integer array `grid` of size `m x n` which represents a field. Each cell has one of three values:
* `0` represents grass,
* `1` represents fire,
* `2` represents a wall that you and fire cannot pass through.
You are situated in the top-left cell, `(0, 0)`, and you want to travel... | Try to find a pattern in how nums changes. Let m be the original length of nums. If time_i / m (integer division) is even, then nums is at its original size or decreasing in size. If it is odd, then it is empty, or increasing in size. time_i % m can be used to find how many elements are in nums at minute time_i. |
Python BFS , NO BS , corner case explained FAST AF | escape-the-spreading-fire | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe use binary search to track distance of each cell\'s shortes pat from out desired locations : Fire and Agent.\n\nThe idea is at the location of the safehouse, we know time taken by the person and fire to reach there, so the wait time wo... | 0 | You are given a **0-indexed** 2D integer array `grid` of size `m x n` which represents a field. Each cell has one of three values:
* `0` represents grass,
* `1` represents fire,
* `2` represents a wall that you and fire cannot pass through.
You are situated in the top-left cell, `(0, 0)`, and you want to travel... | Try to find a pattern in how nums changes. Let m be the original length of nums. If time_i / m (integer division) is even, then nums is at its original size or decreasing in size. If it is odd, then it is empty, or increasing in size. time_i % m can be used to find how many elements are in nums at minute time_i. |
[Python3][BFS+Heap] Beats 95% Runtime | escape-the-spreading-fire | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst use BFS to calculate each cell\'s last day it can ba passed\nThen use a heap started from the last cell with the last day we can pass to the cell until reached the start point.\n\n# Approach\n<!-- Describe your approach to solving t... | 0 | You are given a **0-indexed** 2D integer array `grid` of size `m x n` which represents a field. Each cell has one of three values:
* `0` represents grass,
* `1` represents fire,
* `2` represents a wall that you and fire cannot pass through.
You are situated in the top-left cell, `(0, 0)`, and you want to travel... | Try to find a pattern in how nums changes. Let m be the original length of nums. If time_i / m (integer division) is even, then nums is at its original size or decreasing in size. If it is odd, then it is empty, or increasing in size. time_i % m can be used to find how many elements are in nums at minute time_i. |
2259. Checking the next digit | Beats 96.72% | remove-digit-from-number-to-maximize-result | 0 | 1 | # Code\n```\nclass Solution:\n def removeDigit(self, number: str, digit: str) -> str:\n n = len(number)\n for x in range(1, n):\n prev, cur = number[x-1], number[x]\n if prev == digit:\n last_ind = x-1\n if cur > prev:\n ind = x - 1... | 1 | You are given a string `number` representing a **positive integer** and a character `digit`.
Return _the resulting string after removing **exactly one occurrence** of_ `digit` _from_ `number` _such that the value of the resulting string in **decimal** form is **maximized**_. The test cases are generated such that `dig... | Consider each cell containing a 1 as a vertex whose neighbors are the cells 4-directionally connected to it. The grid then becomes a bipartite graph. You want to find the smallest set of vertices such that every edge in the graph has an endpoint in this set. If you remove every vertex in this set from the graph, then a... |
🔥🔥🔥Python O(N) solution || Faster than 99% submissions || Detailed explanation. | remove-digit-from-number-to-maximize-result | 0 | 1 | ***Please Upvote, comment and share if you like the detailed explanation and the solution***\n\nLet us understand with an example: \n`Number = 9515901 and digit = 9`\n\n1. Since the occurence of the number `9` is happening twice in the string(number), and we can only remove one `9` from the string, we can achieve the M... | 25 | You are given a string `number` representing a **positive integer** and a character `digit`.
Return _the resulting string after removing **exactly one occurrence** of_ `digit` _from_ `number` _such that the value of the resulting string in **decimal** form is **maximized**_. The test cases are generated such that `dig... | Consider each cell containing a 1 as a vertex whose neighbors are the cells 4-directionally connected to it. The grid then becomes a bipartite graph. You want to find the smallest set of vertices such that every edge in the graph has an endpoint in this set. If you remove every vertex in this set from the graph, then a... |
Python | Easy Solution✅ | remove-digit-from-number-to-maximize-result | 0 | 1 | ```\ndef removeDigit(self, number: str, digit: str) -> str:\n output = []\n for i in range(len(number)):\n if number[i] == digit:\n output.append(number[:i]+number[i+1:])\n return max(output)\n``` | 12 | You are given a string `number` representing a **positive integer** and a character `digit`.
Return _the resulting string after removing **exactly one occurrence** of_ `digit` _from_ `number` _such that the value of the resulting string in **decimal** form is **maximized**_. The test cases are generated such that `dig... | Consider each cell containing a 1 as a vertex whose neighbors are the cells 4-directionally connected to it. The grid then becomes a bipartite graph. You want to find the smallest set of vertices such that every edge in the graph has an endpoint in this set. If you remove every vertex in this set from the graph, then a... |
[Python 3] Brute Force Easy Solution | remove-digit-from-number-to-maximize-result | 0 | 1 | **Approach:** For all the occurences, remove it and find the maximum of all the possible numbers generated.\n\n**DO UPVOTE IF YOU FOUND IT HELPFUL.**\n\n```\nclass Solution:\n def removeDigit(self, number: str, digit: str) -> str:\n ans = 0\n for i, dig in enumerate(list(number)):\n if dig =... | 16 | You are given a string `number` representing a **positive integer** and a character `digit`.
Return _the resulting string after removing **exactly one occurrence** of_ `digit` _from_ `number` _such that the value of the resulting string in **decimal** form is **maximized**_. The test cases are generated such that `dig... | Consider each cell containing a 1 as a vertex whose neighbors are the cells 4-directionally connected to it. The grid then becomes a bipartite graph. You want to find the smallest set of vertices such that every edge in the graph has an endpoint in this set. If you remove every vertex in this set from the graph, then a... |
Python3 ✅✅✅ || 2-line Faster than 99.25% | remove-digit-from-number-to-maximize-result | 0 | 1 | # Code\n```\nclass Solution:\n def removeDigit(self, number: str, digit: str) -> str:\n nums = [ int(number[:n] + number[n+1:]) for n in range(len(number)) if number[n] == digit]\n return str(max(nums))\n```\n | remove-digit-from-number-to-maximize-result | 0 | 1 | ```\nclass Solution:\n def removeDigit(self, number: str, digit: str) -> str:\n l=[]\n for i in range(len(number)):\n if number[i]==digit:\n l.append(int(number[:i]+number[i+1:]))\n return str(max(l))\n``` | 2 | You are given a string `number` representing a **positive integer** and a character `digit`.
Return _the resulting string after removing **exactly one occurrence** of_ `digit` _from_ `number` _such that the value of the resulting string in **decimal** form is **maximized**_. The test cases are generated such that `dig... | Consider each cell containing a 1 as a vertex whose neighbors are the cells 4-directionally connected to it. The grid then becomes a bipartite graph. You want to find the smallest set of vertices such that every edge in the graph has an endpoint in this set. If you remove every vertex in this set from the graph, then a... |
Beating 85.16% Python Easiest Solution | minimum-consecutive-cards-to-pick-up | 0 | 1 | \n\n\n# Code\n```\nclass Solution:\n def minimumCardPickup(self, cards: List[int]) -> int:\n if len(set(cards))==len(cards):\n return -1\n dic={} \n ma=1000000\n ... | 1 | You are given an integer array `cards` where `cards[i]` represents the **value** of the `ith` card. A pair of cards are **matching** if the cards have the **same** value.
Return _the **minimum** number of **consecutive** cards you have to pick up to have a pair of **matching** cards among the picked cards._ If it is i... | Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group. |
🚀🚀🚀Three ways to solve(99 beating) | minimum-consecutive-cards-to-pick-up | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def minimumCardPickup(self, cards: List[int]) -> int:\n #enumerate; time O(n), space O(n)\n d = defaultdict(list)\n res = float(\'inf\')\n for i, val in enumerate(cards):\n if val in d:\n res = min(res, i - d[val] + 1)\n ... | 2 | You are given an integer array `cards` where `cards[i]` represents the **value** of the `ith` card. A pair of cards are **matching** if the cards have the **same** value.
Return _the **minimum** number of **consecutive** cards you have to pick up to have a pair of **matching** cards among the picked cards._ If it is i... | Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group. |
Hashing and then using the indexes(Algorithm) | minimum-consecutive-cards-to-pick-up | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirstly store the indexes the elements repeated and donnot forget to update the indexes...\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... | 2 | You are given an integer array `cards` where `cards[i]` represents the **value** of the `ith` card. A pair of cards are **matching** if the cards have the **same** value.
Return _the **minimum** number of **consecutive** cards you have to pick up to have a pair of **matching** cards among the picked cards._ If it is i... | Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group. |
Python3 | Beginner-friendly explained | | minimum-consecutive-cards-to-pick-up | 0 | 1 | **Thought Process:**\n\nSo we want to find the minimum difference between current character\'s position and previously seen position. And only keep the minimum!\n\n1.\tKeep the index of visiting number (We will always update the index to latest since we are looking for minimum length)\n2.\tIf your current number is see... | 29 | You are given an integer array `cards` where `cards[i]` represents the **value** of the `ith` card. A pair of cards are **matching** if the cards have the **same** value.
Return _the **minimum** number of **consecutive** cards you have to pick up to have a pair of **matching** cards among the picked cards._ If it is i... | Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group. |
[Python 3] Using dictionary || beats 99% || 694ms 🥷🏼 | minimum-consecutive-cards-to-pick-up | 0 | 1 | ```python3 []\nclass Solution:\n def minimumCardPickup(self, cards: List[int]) -> int:\n res, pos = 10**6+1, {}\n for i, c in enumerate(cards):\n if c in pos:\n res = min(res, i - pos[c] + 1)\n pos[c] = i\n \n return res % (10**6+1) or -1\n```\n![Scree... | 3 | You are given an integer array `cards` where `cards[i]` represents the **value** of the `ith` card. A pair of cards are **matching** if the cards have the **same** value.
Return _the **minimum** number of **consecutive** cards you have to pick up to have a pair of **matching** cards among the picked cards._ If it is i... | Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group. |
python solution | minimum-consecutive-cards-to-pick-up | 0 | 1 | # class Solution:\n def minimumCardPickup(self, cards: List[int]) -> int:\n d = {}\n ans = float(\'inf\')\n \n for i in range(len(cards)):\n if cards[i] not in d:\n d[cards[i]] = i\n else:\n ans = min(ans, i - d[cards[i]])\n ... | 3 | You are given an integer array `cards` where `cards[i]` represents the **value** of the `ith` card. A pair of cards are **matching** if the cards have the **same** value.
Return _the **minimum** number of **consecutive** cards you have to pick up to have a pair of **matching** cards among the picked cards._ If it is i... | Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group. |
Python3 | HashMaps | minimum-consecutive-cards-to-pick-up | 0 | 1 | ```\nclass Solution:\n def minimumCardPickup(self, cards: List[int]) -> int:\n HashMap={}\n lengths=[]\n for i,j in enumerate(cards):\n if j in HashMap:\n lengths.append(abs(HashMap[j]-i)+1)\n HashMap[j]=i\n else:\n HashMap[j]=i\... | 2 | You are given an integer array `cards` where `cards[i]` represents the **value** of the `ith` card. A pair of cards are **matching** if the cards have the **same** value.
Return _the **minimum** number of **consecutive** cards you have to pick up to have a pair of **matching** cards among the picked cards._ If it is i... | Using the length of the string and k, can you count the number of groups the string can be divided into? Try completing each group using characters from the string. If there aren’t enough characters for the last group, use the fill character to complete the group. |
✅ Python - Simple Count all combinations | k-divisible-elements-subarrays | 0 | 1 | ```\nclass Solution:\n def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n n = len(nums) \n sub_arrays = set()\n \n\t\t# generate all combinations of subarray\n for start in range(n):\n cnt = 0\n temp = \'\'\n for i in... | 23 | Given an integer array `nums` and two integers `k` and `p`, return _the number of **distinct subarrays** which have **at most**_ `k` _elements divisible by_ `p`.
Two arrays `nums1` and `nums2` are said to be **distinct** if:
* They are of **different** lengths, or
* There exists **at least** one index `i` where `... | When you iterate the array, maintain the number of zeros and ones on the left side. Can you quickly calculate the number of ones on the right side? The number of ones on the right side equals the number of ones in the whole array minus the number of ones on the left side. Alternatively, you can quickly calculate it by ... |
Easily implemented using Trie | k-divisible-elements-subarrays | 0 | 1 | ```\nclass Solution:\n def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n trie = {}\n cnt = 0\n for i in range(len(nums)):\n count = 0\n divis = 0 #contain count of element in array divisible by p\n d = trie\n for j in range(i,len(nu... | 2 | Given an integer array `nums` and two integers `k` and `p`, return _the number of **distinct subarrays** which have **at most**_ `k` _elements divisible by_ `p`.
Two arrays `nums1` and `nums2` are said to be **distinct** if:
* They are of **different** lengths, or
* There exists **at least** one index `i` where `... | When you iterate the array, maintain the number of zeros and ones on the left side. Can you quickly calculate the number of ones on the right side? The number of ones on the right side equals the number of ones in the whole array minus the number of ones on the left side. Alternatively, you can quickly calculate it by ... |
Sliding Window Technique: O(N^2) | k-divisible-elements-subarrays | 0 | 1 | # Intuition\nSince the problem is about subarrays, I felt like the sliding window method is great at dealing with subarrays.\n\n# Approach\nWe\'re gonna run through the list with two pointers, i and j. They both start at the beginning, but we keep moving j ahead until we hit more than k numbers in the nums[i:j+1] secti... | 2 | Given an integer array `nums` and two integers `k` and `p`, return _the number of **distinct subarrays** which have **at most**_ `k` _elements divisible by_ `p`.
Two arrays `nums1` and `nums2` are said to be **distinct** if:
* They are of **different** lengths, or
* There exists **at least** one index `i` where `... | When you iterate the array, maintain the number of zeros and ones on the left side. Can you quickly calculate the number of ones on the right side? The number of ones on the right side equals the number of ones in the whole array minus the number of ones on the left side. Alternatively, you can quickly calculate it by ... |
[Python3] Backtracking | k-divisible-elements-subarrays | 0 | 1 | ```\nclass Solution:\n def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n def dfs(idx, k, path):\n nonlocal res, visited\n if idx == len(nums):\n visited.add(tuple(path[:]))\n return\n \n if nums[idx] % p == 0 and k > 0:... | 2 | Given an integer array `nums` and two integers `k` and `p`, return _the number of **distinct subarrays** which have **at most**_ `k` _elements divisible by_ `p`.
Two arrays `nums1` and `nums2` are said to be **distinct** if:
* They are of **different** lengths, or
* There exists **at least** one index `i` where `... | When you iterate the array, maintain the number of zeros and ones on the left side. Can you quickly calculate the number of ones on the right side? The number of ones on the right side equals the number of ones in the whole array minus the number of ones on the left side. Alternatively, you can quickly calculate it by ... |
[Python3] Rolling Hash Simple Solution | k-divisible-elements-subarrays | 0 | 1 | ```python\nclass Solution:\n POW = 397\n MODULO = 100000000069\n def countDistinct(self, nums: List[int], k: int, p: int) -> int:\n arr = list(map(lambda x: 1 if x % p == 0 else 0, nums))\n ans_set = set[int]()\n for i in range(len(arr)):\n cnt_one = 0\n hash1 = 0\n ... | 3 | Given an integer array `nums` and two integers `k` and `p`, return _the number of **distinct subarrays** which have **at most**_ `k` _elements divisible by_ `p`.
Two arrays `nums1` and `nums2` are said to be **distinct** if:
* They are of **different** lengths, or
* There exists **at least** one index `i` where `... | When you iterate the array, maintain the number of zeros and ones on the left side. Can you quickly calculate the number of ones on the right side? The number of ones on the right side equals the number of ones in the whole array minus the number of ones on the left side. Alternatively, you can quickly calculate it by ... |
DP | total-appeal-of-a-string | 1 | 1 | > Note: there is even a simpler [combinatorics solution](https://leetcode.com/problems/total-appeal-of-a-string/discuss/1999226/Combinatorics), proposed by [geekykant](https://leetcode.com/geekykant/).\n\nWhat is the appeal of all substrings that end at `i`-th position?\n- It is the same as the appeal of all substrings... | 266 | The **appeal** of a string is the number of **distinct** characters found in the string.
* For example, the appeal of `"abbca "` is `3` because it has `3` distinct characters: `'a'`, `'b'`, and `'c'`.
Given a string `s`, return _the **total appeal of all of its **substrings**.**_
A **substring** is a contiguous se... | For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem? We store for each question the maximum points we can earn if we started the exam on that question. If we skip a question, then the answer for it will be the same as the answer for... |
Python3 | O(N) / O(1) | detail for beginners | total-appeal-of-a-string | 0 | 1 | **Thought Process**\n\nThe constraints of length of input is 10^5, then we would like to do it linear time.\nSo started filling this table to observe pattern. (to visually see what are my possible subarrays are as iterating only once)\n\nAssume our example input is **S = \'ababba\'**\n\n\n-*-(sz-i)). \n\nFrom that problem, we use the fact that each character appears in `(i + 1) * (n - i)` substrings. However, it does not contribute to the appeal of substrings on the left th... | 76 | The **appeal** of a string is the number of **distinct** characters found in the string.
* For example, the appeal of `"abbca "` is `3` because it has `3` distinct characters: `'a'`, `'b'`, and `'c'`.
Given a string `s`, return _the **total appeal of all of its **substrings**.**_
A **substring** is a contiguous se... | For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem? We store for each question the maximum points we can earn if we started the exam on that question. If we skip a question, then the answer for it will be the same as the answer for... |
Easy to Understand || Detailed solution || Combinatorics || O(N) | total-appeal-of-a-string | 0 | 1 | # Intuition\nThe intuition is to think about the **contribution** of each element in the **to the total appeal**. By contribution I mean how much appeal is the element going to bring from all the subarrays it is a part of.\n\n# Approach\nConsider the given testcase from the problem `"abbca"`. Let\'s consider two more t... | 1 | The **appeal** of a string is the number of **distinct** characters found in the string.
* For example, the appeal of `"abbca "` is `3` because it has `3` distinct characters: `'a'`, `'b'`, and `'c'`.
Given a string `s`, return _the **total appeal of all of its **substrings**.**_
A **substring** is a contiguous se... | For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem? We store for each question the maximum points we can earn if we started the exam on that question. If we skip a question, then the answer for it will be the same as the answer for... |
[Python] Hashmap O(N) Solution with Detailed Explanations, Clean & Concise | total-appeal-of-a-string | 0 | 1 | **Intuition**\nThe given constraint has `1 <= s.length <= 10^5`, indicating `O(N^2)` solutions would get TLE. A natural idea is to use 1-D DP.\n\n**Explanation**\nWe use an array `dp` of length `N`, where `dp[i]` represents the total appeal of all of substrings ending at index `i` of the original string `s`. We also us... | 7 | The **appeal** of a string is the number of **distinct** characters found in the string.
* For example, the appeal of `"abbca "` is `3` because it has `3` distinct characters: `'a'`, `'b'`, and `'c'`.
Given a string `s`, return _the **total appeal of all of its **substrings**.**_
A **substring** is a contiguous se... | For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem? We store for each question the maximum points we can earn if we started the exam on that question. If we skip a question, then the answer for it will be the same as the answer for... |
✔️ [Python3] 7-LINES DP (•̀ᴗ•́)و , Explained | total-appeal-of-a-string | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe idea is to iterate over all characters and for every one of them calculate the amount of substrings where this character contribute to the score. The formula is as follows:\n`X + Y - Z`, where\n* X - the amount o... | 8 | The **appeal** of a string is the number of **distinct** characters found in the string.
* For example, the appeal of `"abbca "` is `3` because it has `3` distinct characters: `'a'`, `'b'`, and `'c'`.
Given a string `s`, return _the **total appeal of all of its **substrings**.**_
A **substring** is a contiguous se... | For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem? We store for each question the maximum points we can earn if we started the exam on that question. If we skip a question, then the answer for it will be the same as the answer for... |
Python | Hashtable One Pass O(n) with Illustration | total-appeal-of-a-string | 0 | 1 | \n\n```\nclass Solution:\n def appealSum(self, s: str) -> int:\n prev = {}\n total, curr = 0, 0\n for i, c in enumerate(s):\n if c in prev:\n curr += i + 1 - (p... | 3 | The **appeal** of a string is the number of **distinct** characters found in the string.
* For example, the appeal of `"abbca "` is `3` because it has `3` distinct characters: `'a'`, `'b'`, and `'c'`.
Given a string `s`, return _the **total appeal of all of its **substrings**.**_
A **substring** is a contiguous se... | For each question, we can either solve it or skip it. How can we use Dynamic Programming to decide the most optimal option for each problem? We store for each question the maximum points we can earn if we started the exam on that question. If we skip a question, then the answer for it will be the same as the answer for... |
string & loop||0ms beats 100% | largest-3-same-digit-number-in-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIterate over the string `num` & look for 3 consecutive identical letters!\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOne pass & set `maxd` to record the max seen 3 consecutive identical letters.\n\nPython code i... | 7 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
✅☑[C++/Java/Python/JavaScript] || 3 Approaches || Beats 100% || EXPLAINED🔥 | largest-3-same-digit-number-in-string | 1 | 1 | # PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(With Basics)***\n1. It uses a flag `check` to verify if the condition of finding the triplet is met.\n1. The `temp` variable stores the largest digit found within the triplet.\n1. If a triplet is found (`check ... | 5 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
Python Solution | largest-3-same-digit-number-in-string | 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. $$O... | 4 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
Python3 Solution | largest-3-same-digit-number-in-string | 0 | 1 | \n```\nclass Solution:\n def largestGoodInteger(self, num: str) -> str:\n n=len(num)\n ans=""\n for i in range(n):\n if i+2<n and num[i]==num[i+1] and num[i]==num[i+2]:\n ans=max(ans,num[i:i+3])\n return ans \n``` | 3 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
Easy solution with comment on each line. TC = O(n), SC = O1 | largest-3-same-digit-number-in-string | 0 | 1 | # Complexity\n- Time complexity: O(n)\n\n- Space complexity: O1\n\n# Code\n```Python\nclass Solution:\n def largestGoodInteger(self, num: str) -> str:\n # Initialize max_num to -1, to track the largest triplet\n max_num = -1\n \n # Set the left pointer to the start of the string\n ... | 10 | You are given a string `num` representing a large integer. An integer is **good** if it meets the following conditions:
* It is a **substring** of `num` with length `3`.
* It consists of only one unique digit.
Return _the **maximum good** integer as a **string** or an empty string_ `" "` _if no such integer exist... | Notice that the most optimal way to obtain the minimum possible sum using 4 digits is by summing up two 2-digit numbers. We can use the two smallest digits out of the four as the digits found in the tens place respectively. Similarly, we use the final 2 larger digits as the digits found in the ones place. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.