title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
[Python 3] - Easy to understand COMMENTED solution.
maximum-number-of-balls-in-a-box
0
1
Approach:\n\nIterate through the ```lowLimit``` and ```highLimit```. While doing so, compute the sum of all the elements of the current number and update it\'s count in the frequency table. \nBasically, ```boxes[sum(element)] += 1```, (boxes is my frequency table). Finally, return ```max(boxes)```.\n```\nclass Solution...
7
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) =...
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
simple python solution
maximum-number-of-balls-in-a-box
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
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits ...
Try sorting the points Think is the y-axis of a point relevant
simple python solution
maximum-number-of-balls-in-a-box
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
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) =...
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Python simple and short solution
maximum-number-of-balls-in-a-box
0
1
**Python :**\n\n```\ndef countBalls(self, lowLimit: int, highLimit: int) -> int:\n\tballBox = collections.defaultdict(int)\n\n\tfor i in range(lowLimit, highLimit + 1):\n\t\tballSum = sum([int(i) for i in str(i)])\n\t\tballBox[ballSum] += 1\n\n\treturn max(ballBox.values())\n```\n\n**Like it ? please upvote !**
6
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits ...
Try sorting the points Think is the y-axis of a point relevant
Python simple and short solution
maximum-number-of-balls-in-a-box
0
1
**Python :**\n\n```\ndef countBalls(self, lowLimit: int, highLimit: int) -> int:\n\tballBox = collections.defaultdict(int)\n\n\tfor i in range(lowLimit, highLimit + 1):\n\t\tballSum = sum([int(i) for i in str(i)])\n\t\tballBox[ballSum] += 1\n\n\treturn max(ballBox.values())\n```\n\n**Like it ? please upvote !**
6
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) =...
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Python3 frequency hash table
maximum-number-of-balls-in-a-box
0
1
# Intuition\n\nAlthough the problem description was fairly confusing, in essence, you need find the most frequent digit sum. For other problems like this, I\'ve used a hash table to store frequencies.\n\n# Approach\n\nFor each number in the range of the lower limit and the higher limit +1 (to include the higher limit)...
0
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits ...
Try sorting the points Think is the y-axis of a point relevant
Python3 frequency hash table
maximum-number-of-balls-in-a-box
0
1
# Intuition\n\nAlthough the problem description was fairly confusing, in essence, you need find the most frequent digit sum. For other problems like this, I\'ve used a hash table to store frequencies.\n\n# Approach\n\nFor each number in the range of the lower limit and the higher limit +1 (to include the higher limit)...
0
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) =...
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Python 83ms || Beginner || Dictionary
maximum-number-of-balls-in-a-box
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 working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits ...
Try sorting the points Think is the y-axis of a point relevant
Python 83ms || Beginner || Dictionary
maximum-number-of-balls-in-a-box
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) =...
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
python simple solution, dictionary, for and while loop
maximum-number-of-balls-in-a-box
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 working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits ...
Try sorting the points Think is the y-axis of a point relevant
python simple solution, dictionary, for and while loop
maximum-number-of-balls-in-a-box
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) =...
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
【Video】Give me 5 minutes - O(n) time and space - How we think about a solution
restore-the-array-from-adjacent-pairs
1
1
# Intuition\nTry to find numbers that have only one adjacent number.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/P14SbuALeJ8\n\n\u25A0 Timeline of the video\n\n`0:04` A key point to solve this question\n`1:09` How do you know adjacent number of each number?\n`2:33` Demonstrate how it works\n`6:07` Coding\n`9:07` Tim...
95
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` a...
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
【Video】Give me 5 minutes - O(n) time and space - How we think about a solution
restore-the-array-from-adjacent-pairs
1
1
# Intuition\nTry to find numbers that have only one adjacent number.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/P14SbuALeJ8\n\n\u25A0 Timeline of the video\n\n`0:04` A key point to solve this question\n`1:09` How do you know adjacent number of each number?\n`2:33` Demonstrate how it works\n`6:07` Coding\n`9:07` Tim...
95
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Iterative Python solution
restore-the-array-from-adjacent-pairs
0
1
The key observation is that except for the first and the last numbers of the array which has only 1 adjacent vertex, the #adjacent vertices will be 2. (In graph theory language, this is a path.)\nTherefore, we can start from either end, and iteratively traverse along the path.\n# Code\n```\nclass Solution:\n def res...
2
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` a...
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Iterative Python solution
restore-the-array-from-adjacent-pairs
0
1
The key observation is that except for the first and the last numbers of the array which has only 1 adjacent vertex, the #adjacent vertices will be 2. (In graph theory language, this is a path.)\nTherefore, we can start from either end, and iteratively traverse along the path.\n# Code\n```\nclass Solution:\n def res...
2
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
restore-the-array-from-adjacent-pairs
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(DFS)***\n1. **Graph Representation:**\n\n - The code uses an unordered map (`graph`) to represent an undirected graph.\n - Keys of the map are integers representing nodes, and values are vectors of intege...
2
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` a...
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
restore-the-array-from-adjacent-pairs
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(DFS)***\n1. **Graph Representation:**\n\n - The code uses an unordered map (`graph`) to represent an undirected graph.\n - Keys of the map are integers representing nodes, and values are vectors of intege...
2
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Python3 Solution
restore-the-array-from-adjacent-pairs
0
1
\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n adjs=collections.defaultdict(set)\n for i,j in adjacentPairs:\n adjs[i].add(j)\n adjs[j].add(i)\n\n for node,adj in adjs.items():\n if len(adj)==1:\n br...
11
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` a...
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Python3 Solution
restore-the-array-from-adjacent-pairs
0
1
\n```\nclass Solution:\n def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:\n adjs=collections.defaultdict(set)\n for i,j in adjacentPairs:\n adjs[i].add(j)\n adjs[j].add(i)\n\n for node,adj in adjs.items():\n if len(adj)==1:\n br...
11
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Solution with Graph/HashTable in TypeScript/Python3
restore-the-array-from-adjacent-pairs
0
1
\n# Intuition\nHere we have:\n- list of integers `adj`, that represent neighbours in `adj`\n- our goal is to **reconstruct** an **original** array of integers\n\nThe logic is straightforward and let\'s imagine, that we\'ve already done a task:\n- here is the list, for example `[1,2,3,4]`\n- according to the task descri...
1
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` a...
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Solution with Graph/HashTable in TypeScript/Python3
restore-the-array-from-adjacent-pairs
0
1
\n# Intuition\nHere we have:\n- list of integers `adj`, that represent neighbours in `adj`\n- our goal is to **reconstruct** an **original** array of integers\n\nThe logic is straightforward and let\'s imagine, that we\'ve already done a task:\n- here is the list, for example `[1,2,3,4]`\n- according to the task descri...
1
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Basic graph DFS approach!😸
restore-the-array-from-adjacent-pairs
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
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` a...
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Basic graph DFS approach!😸
restore-the-array-from-adjacent-pairs
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
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
DFS Solution O(n) Time O(n) Space
restore-the-array-from-adjacent-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBecause all the members of our final list are unique, we can use DFS to pick one of the ending elements and utilize an adjacency list to contiously find the next element\n# Approach\n<!-- Describe your approach to solving the problem. -->...
1
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` a...
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
DFS Solution O(n) Time O(n) Space
restore-the-array-from-adjacent-pairs
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBecause all the members of our final list are unique, we can use DFS to pick one of the ending elements and utilize an adjacency list to contiously find the next element\n# Approach\n<!-- Describe your approach to solving the problem. -->...
1
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Python Unroll elements one by one
restore-the-array-from-adjacent-pairs
0
1
# Intuition\nIf the elements are none repeating then we can unroll them one by one creating a chain.\n\nIf we will look at a chaing `v1 - v2 - v3 - v4` you can see that all the elements have 2 neighbours except of two (first and a second). \n\nSo we need to create a dictionary which has nodes as keys set of childrens a...
1
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` a...
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
Python Unroll elements one by one
restore-the-array-from-adjacent-pairs
0
1
# Intuition\nIf the elements are none repeating then we can unroll them one by one creating a chain.\n\nIf we will look at a chaing `v1 - v2 - v3 - v4` you can see that all the elements have 2 neighbours except of two (first and a second). \n\nSo we need to create a dictionary which has nodes as keys set of childrens a...
1
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
dfs traversal
restore-the-array-from-adjacent-pairs
0
1
A possible solution could do the following three steps. \n- Construct a graph with either sides nodes as array elements (n) and hold traversal visited info (v).\n- Find the starting point of the list.\n- Traverse the graph from the start to find the list.\n\n```\nclass Solution:\n def restoreArray(self, adjacentPair...
1
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`. You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` a...
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
dfs traversal
restore-the-array-from-adjacent-pairs
0
1
A possible solution could do the following three steps. \n- Construct a graph with either sides nodes as array elements (n) and hold traversal visited info (v).\n- Find the starting point of the list.\n- Traverse the graph from the start to find the list.\n\n```\nclass Solution:\n def restoreArray(self, adjacentPair...
1
There are `n` uniquely-sized sticks whose lengths are integers from `1` to `n`. You want to arrange the sticks such that **exactly** `k` sticks are **visible** from the left. A stick is **visible** from the left if there are no **longer** sticks to the **left** of it. * For example, if the sticks are arranged `[1,3,...
Find the first element of nums - it will only appear once in adjacentPairs. The adjacent pairs are like edges of a graph. Perform a depth-first search from the first element.
Python 3 || 2 lines, prefix || T/M: 97% / 26%
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n \n pref = list(accumulate(candiesCount, initial = 0)) \n \n return [pref[candy]//cap <= day < pref[candy + 1]\n ...
3
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start ...
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
Python 3 || 2 lines, prefix || T/M: 97% / 26%
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n \n pref = list(accumulate(candiesCount, initial = 0)) \n \n return [pref[candy]//cap <= day < pref[candy + 1]\n ...
3
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
[Python3] greedy
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
**Algo**\nCompute the prefix sum of `candiesCount`. For a given query (`t`, `day` and `cap`), the condition for `True` is \n`prefix[t] < (day + 1) * cap and day < prefix[t+1]`\nwhere the first half reflects the fact that if we eat maximum candies every day we can reach the preferred one and the second half means that i...
6
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start ...
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
[Python3] greedy
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
**Algo**\nCompute the prefix sum of `candiesCount`. For a given query (`t`, `day` and `cap`), the condition for `True` is \n`prefix[t] < (day + 1) * cap and day < prefix[t+1]`\nwhere the first half reflects the fact that if we eat maximum candies every day we can reach the preferred one and the second half means that i...
6
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
Python - clear explanation and simple code
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
**Explanation:**\n\nLets take the below test case\n```\ncandiesCount = [7, 4, 5, 3, 8]\nqueries = [[0, 2, 2], [4, 2, 4], [2, 13, 1000000000]]\n```\n\nWe need to know the total number of candies available till ```i-1``` for each type ```i``` as we will have to eat all candies before ```i```th type. So we use accumulate....
7
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start ...
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
Python - clear explanation and simple code
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
**Explanation:**\n\nLets take the below test case\n```\ncandiesCount = [7, 4, 5, 3, 8]\nqueries = [[0, 2, 2], [4, 2, 4], [2, 13, 1000000000]]\n```\n\nWe need to know the total number of candies available till ```i-1``` for each type ```i``` as we will have to eat all candies before ```i```th type. So we use accumulate....
7
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
✅prefix sum || python
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
\n# Code\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n for i in range(len(candiesCount)):\n if(i==0):continue\n candiesCount[i]+=candiesCount[i-1]\n ans=[]\n for q in queries:\n last=candiesCount[q[0]...
0
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start ...
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
✅prefix sum || python
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
\n# Code\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n for i in range(len(candiesCount)):\n if(i==0):continue\n candiesCount[i]+=candiesCount[i-1]\n ans=[]\n for q in queries:\n last=candiesCount[q[0]...
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
python3 beats 98%
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
\n\n# Code\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n presum = []\n res = []\n tot = 0\n presum.append(0)\n for e in candiesCount:\n tot+=e\n presum.append(tot)\n for type,day,cap in quer...
0
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start ...
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
python3 beats 98%
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
\n\n# Code\n```\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n presum = []\n res = []\n tot = 0\n presum.append(0)\n for e in candiesCount:\n tot+=e\n presum.append(tot)\n for type,day,cap in quer...
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
Python | Prefix Sum | O(n) | 100% Faster
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
# Code\n```\nfrom itertools import accumulate\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n prefix = list(accumulate(candiesCount,initial = 0))\n res = []\n for t, d, c in queries:\n if prefix[t]//c <= d < prefix[t+1]:\n ...
0
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start ...
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
Python | Prefix Sum | O(n) | 100% Faster
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
# Code\n```\nfrom itertools import accumulate\nclass Solution:\n def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]:\n prefix = list(accumulate(candiesCount,initial = 0))\n res = []\n for t, d, c in queries:\n if prefix[t]//c <= d < prefix[t+1]:\n ...
0
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
Python O(N) Solution
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
Find the maximum number of candies you can eat before eating on the favorite day, and check if you can eat atleast 1 of your favorite candy on the favorite day.\nThe two hurdles to check are, \n* Overshooting the given targeting by eating the minimum number of candies (1) per day.\n* Undershooting it by not able to eat...
1
You are given a **(0-indexed)** array of positive integers `candiesCount` where `candiesCount[i]` represents the number of candies of the `ith` type you have. You are also given a 2D array `queries` where `queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]`. You play a game with the following rules: * You start ...
For each index i, store the frequency of each character in the ith row. Use dynamic programing to calculate the number of ways to get the target string using the frequency array,
Python O(N) Solution
can-you-eat-your-favorite-candy-on-your-favorite-day
0
1
Find the maximum number of candies you can eat before eating on the favorite day, and check if you can eat atleast 1 of your favorite candy on the favorite day.\nThe two hurdles to check are, \n* Overshooting the given targeting by eating the minimum number of candies (1) per day.\n* Undershooting it by not able to eat...
1
Alice and Bob take turns playing a game, with **Alice starting first**. There are `n` stones arranged in a row. On each player's turn, while the number of stones is **more than one**, they will do the following: 1. Choose an integer `x > 1`, and **remove** the leftmost `x` stones from the row. 2. Add the **sum** of...
The query is true if and only if your favorite day is in between the earliest and latest possible days to eat your favorite candy. To get the earliest day, you need to eat dailyCap candies every day. To get the latest day, you need to eat 1 candy every day. The latest possible day is the total number of candies with a ...
Beats 95%, Java
palindrome-partitioning-iv
1
1
# Intuition\n![Palindrome Partitioning IV - solution - Intuition 1.png](https://assets.leetcode.com/users/images/f587229c-1490-47ac-b758-f25d5362f365_1699694661.774286.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe are required to split the string into three parts, which m...
1
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd "...
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, ret...
Beats 95%, Java
palindrome-partitioning-iv
1
1
# Intuition\n![Palindrome Partitioning IV - solution - Intuition 1.png](https://assets.leetcode.com/users/images/f587229c-1490-47ac-b758-f25d5362f365_1699694661.774286.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe are required to split the string into three parts, which m...
1
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j]...
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
Simply Python O(N**2) | It is not hard
palindrome-partitioning-iv
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 string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd "...
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, ret...
Simply Python O(N**2) | It is not hard
palindrome-partitioning-iv
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
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j]...
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
Python (Simple Maths)
palindrome-partitioning-iv
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 string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd "...
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, ret...
Python (Simple Maths)
palindrome-partitioning-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j]...
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
✔ Python3 Solution | DP | Bit Manipulation | O(n^2)
palindrome-partitioning-iv
0
1
# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def checkPartitioning(self, S):\n N = len(S)\n dp = [1] + [0] * N\n for i in range(2 * N - 1):\n l = i // 2\n r = l + (i & 1)\n while 0 <= l and r < N and ...
2
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd "...
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, ret...
✔ Python3 Solution | DP | Bit Manipulation | O(n^2)
palindrome-partitioning-iv
0
1
# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def checkPartitioning(self, S):\n N = len(S)\n dp = [1] + [0] * N\n for i in range(2 * N - 1):\n l = i // 2\n r = l + (i & 1)\n while 0 <= l and r < N and ...
2
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j]...
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
[Python3] dp
palindrome-partitioning-iv
0
1
**Algo**\nDefine `fn(i, k)` to be `True` if `s[i:]` can be split into `k` palindromic substrings. Then, \n\n`fn(i, k) = any(fn(ii+1, k-1) where s[i:ii] == s[i:ii][::-1]`\n\nHere we create a mapping to memoize all palindromic substrings starting from any given `i`. \n\n**Implementation**\n```\nclass Solution:\n def c...
11
Given a string `s`, return `true` _if it is possible to split the string_ `s` _into three **non-empty** palindromic substrings. Otherwise, return_ `false`.​​​​​ A string is said to be palindrome if it the same string when reversed. **Example 1:** **Input:** s = "abcbdd " **Output:** true **Explanation: ** "abcbdd "...
Use BFS, traverse the tree level by level and always push the left node first When you reach the target node, mark a boolean variable true If you meet another node in the same level after marking the boolean true, return this node. If you did not meet new nodes in the same level and started traversing a new level, ret...
[Python3] dp
palindrome-partitioning-iv
0
1
**Algo**\nDefine `fn(i, k)` to be `True` if `s[i:]` can be split into `k` palindromic substrings. Then, \n\n`fn(i, k) = any(fn(ii+1, k-1) where s[i:ii] == s[i:ii][::-1]`\n\nHere we create a mapping to memoize all palindromic substrings starting from any given `i`. \n\n**Implementation**\n```\nclass Solution:\n def c...
11
You are given a **0-indexed** binary string `s` and two integers `minJump` and `maxJump`. In the beginning, you are standing at index `0`, which is equal to `'0'`. You can move from index `i` to index `j` if the following conditions are fulfilled: * `i + minJump <= j <= min(i + maxJump, s.length - 1)`, and * `s[j]...
Preprocess checking palindromes in O(1) Note that one string is a prefix and another one is a suffix you can try brute forcing the rest
Very simple approach ᕙ(▀̿ĺ̯▀̿ ̿)ᕗ
sum-of-unique-elements
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing a for loop and count.\n# Complexity\n- Time complexity: 35ms (Beats ***90.98%*** of users with Python3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.14 MB (Beats ***78.93%*** of users with Python3)\n<!-- Add y...
1
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. ...
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Very simple approach ᕙ(▀̿ĺ̯▀̿ ̿)ᕗ
sum-of-unique-elements
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing a for loop and count.\n# Complexity\n- Time complexity: 35ms (Beats ***90.98%*** of users with Python3)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.14 MB (Beats ***78.93%*** of users with Python3)\n<!-- Add y...
1
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
Easy solution using Hash Map !!
sum-of-unique-elements
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:\nO(N)\n\n- Space complexity:\nO(N)\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def sumOfUnique(self, nums: L...
1
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. ...
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Easy solution using Hash Map !!
sum-of-unique-elements
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:\nO(N)\n\n- Space complexity:\nO(N)\n# Code\n```\nfrom collections import Counter\nclass Solution:\n def sumOfUnique(self, nums: L...
1
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
Simple 1 liner Python
sum-of-unique-elements
0
1
\n\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n return sum([k for k,v in Counter(nums).items() if nums.count(k) == 1])\n```
2
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. ...
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Simple 1 liner Python
sum-of-unique-elements
0
1
\n\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n return sum([k for k,v in Counter(nums).items() if nums.count(k) == 1])\n```
2
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
Python3 | Easy Solution | No Libraries | No skill | Beats 7.40%
sum-of-unique-elements
0
1
\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n totalSum = 0\n timesSeen = {}\n for num in nums:\n if num not in timesSeen:\n totalSum += num\n timesSeen[num] = 1\n elif num in timesSeen:\n # Tur...
2
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array. Return _the **sum** of all the unique elements of_ `nums`. **Example 1:** **Input:** nums = \[1,2,3,2\] **Output:** 4 **Explanation:** The unique elements are \[1,3\], and the sum is 4. ...
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
Python3 | Easy Solution | No Libraries | No skill | Beats 7.40%
sum-of-unique-elements
0
1
\n# Code\n```\nclass Solution:\n def sumOfUnique(self, nums: List[int]) -> int:\n totalSum = 0\n timesSeen = {}\n for num in nums:\n if num not in timesSeen:\n totalSum += num\n timesSeen[num] = 1\n elif num in timesSeen:\n # Tur...
2
Given an integer array `nums` **(0-indexed)** and two integers `target` and `start`, find an index `i` such that `nums[i] == target` and `abs(i - start)` is **minimized**. Note that `abs(x)` is the absolute value of `x`. Return `abs(i - start)`. It is **guaranteed** that `target` exists in `nums`. **Example 1:** **...
Use a dictionary to count the frequency of each number.
Described easily with example and solution in C++, Java, Python3, JavaScript
maximum-absolute-sum-of-any-subarray
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst approach is to get all the subarray. Then get the sum of all elements and absolute it for each subarray and take the maximum of them.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBut problem is that we nee...
2
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative...
null
Described easily with example and solution in C++, Java, Python3, JavaScript
maximum-absolute-sum-of-any-subarray
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst approach is to get all the subarray. Then get the sum of all elements and absolute it for each subarray and take the maximum of them.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBut problem is that we nee...
2
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * Fo...
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
[Python3] Kadane's algo
maximum-absolute-sum-of-any-subarray
0
1
**Algo**\nExtend Kadane\'s algo by keeping track of max and min of subarray sum respectively. \n\n**Implementation**\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n ans = mx = mn = 0\n for x in nums: \n mx = max(mx + x, 0)\n mn = min(mn + x, 0)\n ...
14
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative...
null
[Python3] Kadane's algo
maximum-absolute-sum-of-any-subarray
0
1
**Algo**\nExtend Kadane\'s algo by keeping track of max and min of subarray sum respectively. \n\n**Implementation**\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n ans = mx = mn = 0\n for x in nums: \n mx = max(mx + x, 0)\n mn = min(mn + x, 0)\n ...
14
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * Fo...
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
📌📌 Greedy and Easy Approach 🐍
maximum-absolute-sum-of-any-subarray
0
1
## IDEA :\n*Our target is to find the maximum/minimum subarray sum and choose maximum absolute value between them.*\nThis situation is suited for adopting **Kadane\'s algorithm**.\n\n\'\'\'\n\n\tclass Solution:\n\t\tdef maxAbsoluteSum(self, A):\n\n\t\t\tma,mi,res = 0,0,0\n\t\t\tfor a in A:\n\t\t\t\tma = max(0,ma+a)\n\t...
4
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative...
null
📌📌 Greedy and Easy Approach 🐍
maximum-absolute-sum-of-any-subarray
0
1
## IDEA :\n*Our target is to find the maximum/minimum subarray sum and choose maximum absolute value between them.*\nThis situation is suited for adopting **Kadane\'s algorithm**.\n\n\'\'\'\n\n\tclass Solution:\n\t\tdef maxAbsoluteSum(self, A):\n\n\t\t\tma,mi,res = 0,0,0\n\t\t\tfor a in A:\n\t\t\t\tma = max(0,ma+a)\n\t...
4
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * Fo...
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
Python3 Double Kadane's
maximum-absolute-sum-of-any-subarray
0
1
Use of one kadane\'s algorithm to compute max absolute sum and anothe kadane\'s to compute min absolute sum, return max comparing both\n\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n min_sum = nums[0]\n curr_min = nums[0]\n \n max_sum = nums[0]\n curr_...
5
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative...
null
Python3 Double Kadane's
maximum-absolute-sum-of-any-subarray
0
1
Use of one kadane\'s algorithm to compute max absolute sum and anothe kadane\'s to compute min absolute sum, return max comparing both\n\n```\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n min_sum = nums[0]\n curr_min = nums[0]\n \n max_sum = nums[0]\n curr_...
5
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * Fo...
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
O(N) solution with intution for how to arrive to it from the naive solution using logical steps
maximum-absolute-sum-of-any-subarray
0
1
# Intuition & Approach\nfirst, we see the most obvious algorithm:\n\n```py\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n m = 0\n for i in range(len(nums)):\n for j in range(i, len(nums)):\n m = max(m, sum(nums[i:j]))\n return m\n```\n\nThis algo...
0
You are given an integer array `nums`. The **absolute sum** of a subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is `abs(numsl + numsl+1 + ... + numsr-1 + numsr)`. Return _the **maximum** absolute sum of any **(possibly empty)** subarray of_ `nums`. Note that `abs(x)` is defined as follows: * If `x` is a negative...
null
O(N) solution with intution for how to arrive to it from the naive solution using logical steps
maximum-absolute-sum-of-any-subarray
0
1
# Intuition & Approach\nfirst, we see the most obvious algorithm:\n\n```py\nclass Solution:\n def maxAbsoluteSum(self, nums: List[int]) -> int:\n m = 0\n for i in range(len(nums)):\n for j in range(i, len(nums)):\n m = max(m, sum(nums[i:j]))\n return m\n```\n\nThis algo...
0
You are given a string `s` that consists of only digits. Check if we can split `s` into **two or more non-empty substrings** such that the **numerical values** of the substrings are in **descending order** and the **difference** between numerical values of every two **adjacent** **substrings** is equal to `1`. * Fo...
What if we asked for maximum sum, not absolute sum? It's a standard problem that can be solved by Kadane's algorithm. The key idea is the max absolute sum will be either the max sum or the min sum. So just run kadane twice, once calculating the max sum and once calculating the min sum.
Python easy sol. using two pointers
minimum-length-of-string-after-deleting-similar-ends
0
1
# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n f,r=0,len(s)-1\n while f<=r:\n if f==r and s[f]==s[r]:\n return 1\n if s[f]!=s[r]:\n return r-f+1\n e1,e2=f,r\n while e1<r and s[e1]==s[f]:\n ...
1
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all...
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python easy sol. using two pointers
minimum-length-of-string-after-deleting-similar-ends
0
1
# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n f,r=0,len(s)-1\n while f<=r:\n if f==r and s[f]==s[r]:\n return 1\n if s[f]!=s[r]:\n return r-f+1\n e1,e2=f,r\n while e1<r and s[e1]==s[f]:\n ...
1
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, ...
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
C++ / Python simple solution
minimum-length-of-string-after-deleting-similar-ends
0
1
**C++ :**\n\n```\nint minimumLength(string s) {\n\tif(s.length() <= 1)\n\t\treturn s.length();\n\n\tint l = 0, r = s.length() - 1;\n\n\twhile(l < r && s[l] == s[r])\n\t{\n\t\tchar ch = s[l];\n\n\t\twhile(l <= r && s[l] == ch)\n\t\t\t++l;\n\n\t\twhile(l <= r && s[r] == ch)\n\t\t\t--r;\n\n\t}\n\n\treturn r - l + 1;\n}\n`...
9
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all...
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
C++ / Python simple solution
minimum-length-of-string-after-deleting-similar-ends
0
1
**C++ :**\n\n```\nint minimumLength(string s) {\n\tif(s.length() <= 1)\n\t\treturn s.length();\n\n\tint l = 0, r = s.length() - 1;\n\n\twhile(l < r && s[l] == s[r])\n\t{\n\t\tchar ch = s[l];\n\n\t\twhile(l <= r && s[l] == ch)\n\t\t\t++l;\n\n\t\twhile(l <= r && s[r] == ch)\n\t\t\t--r;\n\n\t}\n\n\treturn r - l + 1;\n}\n`...
9
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, ...
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Python || 96.67% Faster || Two Pointers || O(n) Solution
minimum-length-of-string-after-deleting-similar-ends
0
1
```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n i,j=0,len(s)-1\n while i<j and s[i]==s[j]:\n t=s[i]\n while i<len(s) and s[i]==t:\n i+=1\n while j>=0 and s[j]==t:\n j-=1\n if j<i:\n return 0\n retur...
5
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all...
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python || 96.67% Faster || Two Pointers || O(n) Solution
minimum-length-of-string-after-deleting-similar-ends
0
1
```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n i,j=0,len(s)-1\n while i<j and s[i]==s[j]:\n t=s[i]\n while i<len(s) and s[i]==t:\n i+=1\n while j>=0 and s[j]==t:\n j-=1\n if j<i:\n return 0\n retur...
5
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, ...
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Exactly as the hint says | commented and explained
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBuild your algorithm off of the hints and examples \nMake a can run algorithm checker with the edge cases to prevent need to check in the algorithm itself \nMake an algorithm function that given a string to modify and knowing that it can ...
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all...
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Exactly as the hint says | commented and explained
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBuild your algorithm off of the hints and examples \nMake a can run algorithm checker with the edge cases to prevent need to check in the algorithm itself \nMake an algorithm function that given a string to modify and knowing that it can ...
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, ...
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Python easy two pointer solution with explanation
minimum-length-of-string-after-deleting-similar-ends
0
1
\n# Approach\nUse 2 pointers, `i` and `j`, initialize at 0 and `n-1` respectively\nWe also need to keep track of `currChar` which is the char at which both pointers last matched \n\n`if` chars at i and j are equal:\n- move both pointers\n\n`else:` \n- If either of the pointers is equal to `currChar` move that pointer,...
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all...
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python easy two pointer solution with explanation
minimum-length-of-string-after-deleting-similar-ends
0
1
\n# Approach\nUse 2 pointers, `i` and `j`, initialize at 0 and `n-1` respectively\nWe also need to keep track of `currChar` which is the char at which both pointers last matched \n\n`if` chars at i and j are equal:\n- move both pointers\n\n`else:` \n- If either of the pointers is equal to `currChar` move that pointer,...
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, ...
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Python Efficient Two Pointer
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all...
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python Efficient Two Pointer
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, ...
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Beats 99.4 % in python O(N) TC & O(1) SC
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nprefix and suffix need to be same \n# Approach\n<!-- Describe your approach to solving the problem. -->\n2 pointer\n* l and r pointer at extreme ends\n* hold right pointer until left get mismatched and inrease l\n* same for left inc...
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all...
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Beats 99.4 % in python O(N) TC & O(1) SC
minimum-length-of-string-after-deleting-similar-ends
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nprefix and suffix need to be same \n# Approach\n<!-- Describe your approach to solving the problem. -->\n2 pointer\n* l and r pointer at extreme ends\n* hold right pointer until left get mismatched and inrease l\n* same for left inc...
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, ...
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
Python Easy Solution || Two Pointer
minimum-length-of-string-after-deleting-similar-ends
0
1
# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n start=0\n end=len(s)-1\n if len(set(s))==1 and len(s)>1:\n return 0\n while(start<end):\n if s[start]==s[end]:\n while(s[start]==s[start+1]):\n start+=1\n ...
0
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all...
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Python Easy Solution || Two Pointer
minimum-length-of-string-after-deleting-similar-ends
0
1
# Code\n```\nclass Solution:\n def minimumLength(self, s: str) -> int:\n start=0\n end=len(s)-1\n if len(set(s))==1 and len(s)>1:\n return 0\n while(start<end):\n if s[start]==s[end]:\n while(s[start]==s[start+1]):\n start+=1\n ...
0
You are given a string `num`, representing a large integer, and an integer `k`. We call some integer **wonderful** if it is a **permutation** of the digits in `num` and is **greater in value** than `num`. There can be many wonderful integers. However, we only care about the **smallest-valued** ones. * For example, ...
If both ends have distinct characters, no more operations can be made. Otherwise, the only operation is to remove all of the same characters from both ends. We will do this as many times as we can. Note that if the length is equal 1 the answer is 1
EASY PYTHON SOLUTION USING DP || GREEDY || SORTING
maximum-number-of-events-that-can-be-attended-ii
0
1
# Intuition\nThe question is similar to what we do in meeting problems in greedy but the catch here is that now it has some reward attached to it which makes it a dp problem. Now we have to look for time a meeting ends as well as the value it brings on attending it. \n\n# Approach\nSorting and DP\n\n# Complexity\n- Tim...
3
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can o...
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
EASY PYTHON SOLUTION USING DP || GREEDY || SORTING
maximum-number-of-events-that-can-be-attended-ii
0
1
# Intuition\nThe question is similar to what we do in meeting problems in greedy but the catch here is that now it has some reward attached to it which makes it a dp problem. Now we have to look for time a meeting ends as well as the value it brings on attending it. \n\n# Approach\nSorting and DP\n\n# Complexity\n- Tim...
3
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an intege...
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Python3 Solution
maximum-number-of-events-that-can-be-attended-ii
0
1
\n```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n events.sort(key=lambda ans:ans[1])\n dp=[[0,0]]\n dp2=[[0,0]]\n for x in range(k):\n for s,e,v in events:\n i=bisect.bisect(dp,[s])-1\n if dp[i][1]+v>dp2[-1][1]:...
2
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can o...
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Python3 Solution
maximum-number-of-events-that-can-be-attended-ii
0
1
\n```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n events.sort(key=lambda ans:ans[1])\n dp=[[0,0]]\n dp2=[[0,0]]\n for x in range(k):\n for s,e,v in events:\n i=bisect.bisect(dp,[s])-1\n if dp[i][1]+v>dp2[-1][1]:...
2
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an intege...
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Leave it or take it DP
maximum-number-of-events-that-can-be-attended-ii
0
1
T: O(nlogn+nk)\ns:O(nk)\n\n# Code\n```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n events.sort()\n n=len(events)\n dp=[[-1]*n for _ in range(k)]\n def choice(index,count,end):\n if count==k or index==n:\n return 0\n ...
1
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can o...
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Leave it or take it DP
maximum-number-of-events-that-can-be-attended-ii
0
1
T: O(nlogn+nk)\ns:O(nk)\n\n# Code\n```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n events.sort()\n n=len(events)\n dp=[[-1]*n for _ in range(k)]\n def choice(index,count,end):\n if count==k or index==n:\n return 0\n ...
1
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an intege...
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Python Hard
maximum-number-of-events-that-can-be-attended-ii
0
1
```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n\n\n events.sort(key = lambda x: x[0])\n N = len(events)\n\n\n @cache\n def calc(index, currentDay, currentK):\n if index == N or currentK == 0:\n return 0\n\n while in...
1
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can o...
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Python Hard
maximum-number-of-events-that-can-be-attended-ii
0
1
```\nclass Solution:\n def maxValue(self, events: List[List[int]], k: int) -> int:\n\n\n events.sort(key = lambda x: x[0])\n N = len(events)\n\n\n @cache\n def calc(index, currentDay, currentK):\n if index == N or currentK == 0:\n return 0\n\n while in...
1
You are given a 2D integer array `intervals`, where `intervals[i] = [lefti, righti]` describes the `ith` interval starting at `lefti` and ending at `righti` **(inclusive)**. The **size** of an interval is defined as the number of integers it contains, or more formally `righti - lefti + 1`. You are also given an intege...
Sort the events by its startTime. For every event, you can either choose it and consider the next event available, or you can ignore it. You can efficiently find the next event that is available using binary search.
Python Easy solution beats 99% users in Runtime and Space
check-if-array-is-sorted-and-rotated
0
1
# Intuition\nThe problem asks whether an array was originally sorted in non-decreasing order and then possibly rotated some number of positions (including zero). We need to check if the given array can be sorted by rotating it. If it can be, we return True; otherwise, we return False.\n\n# Approach\nThe provided code t...
2
Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`. There may be **duplicates** in the original array. **Note:** An array `A` rotated by `x` positions results in an array `B` of the sa...
To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arith...
Python Easy solution beats 99% users in Runtime and Space
check-if-array-is-sorted-and-rotated
0
1
# Intuition\nThe problem asks whether an array was originally sorted in non-decreasing order and then possibly rotated some number of positions (including zero). We need to check if the given array can be sorted by rotating it. If it can be, we return True; otherwise, we return False.\n\n# Approach\nThe provided code t...
2
You are given an `m x n` integer matrix `grid`​​​. A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus ...
Brute force and check if it is possible for a sorted array to start from each position.
Efficient Python Solution for Checking if an Array is Sorted and Possibly Rotated
check-if-array-is-sorted-and-rotated
0
1
\n# Intuition\nThe problem asks whether an array was originally sorted in non-decreasing order and then possibly rotated some number of positions (including zero). We need to check if the given array can be sorted by rotating it. If it can be, we return True; otherwise, we return False.\n\n# Approach\nThe code uses an ...
1
Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`. There may be **duplicates** in the original array. **Note:** An array `A` rotated by `x` positions results in an array `B` of the sa...
To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arith...
Efficient Python Solution for Checking if an Array is Sorted and Possibly Rotated
check-if-array-is-sorted-and-rotated
0
1
\n# Intuition\nThe problem asks whether an array was originally sorted in non-decreasing order and then possibly rotated some number of positions (including zero). We need to check if the given array can be sorted by rotating it. If it can be, we return True; otherwise, we return False.\n\n# Approach\nThe code uses an ...
1
You are given an `m x n` integer matrix `grid`​​​. A **rhombus sum** is the sum of the elements that form **the** **border** of a regular rhombus shape in `grid`​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus ...
Brute force and check if it is possible for a sorted array to start from each position.
Is Array Sorted and Rotated, Python code made easy
check-if-array-is-sorted-and-rotated
0
1
```\nclass Solution:\n def check(self, nums: List[int]) -> bool:\n count = 0\n for i in range(len(nums) - 1):\n if nums[i] > nums[i+1]:\n count += 1\n \n if nums[0] < nums[len(nums)-1]:\n count += 1\n \n return count <= 1\n```
4
Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`. There may be **duplicates** in the original array. **Note:** An array `A` rotated by `x` positions results in an array `B` of the sa...
To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arith...