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
BFS Using Queue
jump-game-iv
0
1
\n\n# Code\n```\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n\n # set pos[x][0] = True as unvisited indicator\n pos = collections.defaultdict(lambda: [True])\n\n # Store positions i based on value x=arr[i]\n # reverse is essential as we are finding shortest path backward...
1
Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` where: `arr[i] == arr[j]` and `i != j`. Return _the minimum number of steps_ to reach the...
Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
BFS Using Queue
jump-game-iv
0
1
\n\n# Code\n```\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n\n # set pos[x][0] = True as unvisited indicator\n pos = collections.defaultdict(lambda: [True])\n\n # Store positions i based on value x=arr[i]\n # reverse is essential as we are finding shortest path backward...
1
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
✔️✔️✔️ BFS - beats 94% - Python 3 - Solution 🔥🔥🔥
jump-game-iv
0
1
\n\n# Approach\nThis code finds the minimum number of jumps needed to reach the end of an array by performing a breadth-first search. It uses a dictionary to store indices of elements with the same value, a queue to track indices to visit, and a set to track visited indices. It returns the number of steps required to r...
1
Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` where: `arr[i] == arr[j]` and `i != j`. Return _the minimum number of steps_ to reach the...
Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
✔️✔️✔️ BFS - beats 94% - Python 3 - Solution 🔥🔥🔥
jump-game-iv
0
1
\n\n# Approach\nThis code finds the minimum number of jumps needed to reach the end of an array by performing a breadth-first search. It uses a dictionary to store indices of elements with the same value, a queue to track indices to visit, and a set to track visited indices. It returns the number of steps required to r...
1
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Clean Codes🔥🔥|| Full Explanation✅|| Breadth First Search✅|| C++|| Java|| Python3
jump-game-iv
1
1
# Intuition :\n- We ha ve to find the minimum number of jumps needed to reach the last index of an array. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach :\n- The idea is to use a **Breadth First Search** approach to explore all the possible paths starting from the first index.\n\n--...
18
Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` where: `arr[i] == arr[j]` and `i != j`. Return _the minimum number of steps_ to reach the...
Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
Clean Codes🔥🔥|| Full Explanation✅|| Breadth First Search✅|| C++|| Java|| Python3
jump-game-iv
1
1
# Intuition :\n- We ha ve to find the minimum number of jumps needed to reach the last index of an array. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach :\n- The idea is to use a **Breadth First Search** approach to explore all the possible paths starting from the first index.\n\n--...
18
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Python3 Solution ||Faster than 56% ||BFS|| Bahut TEZ
jump-game-iv
0
1
```\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n h={}\n for i,e in enumerate(arr):\n if e not in h:\n h[e] = []\n h[e].append(i)\n q = [(0,0)]\n while q:\n n,d = q.pop(0)\n if n == len(arr)-1:\n r...
4
Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` where: `arr[i] == arr[j]` and `i != j`. Return _the minimum number of steps_ to reach the...
Intuitively performing all shift operations is acceptable due to the constraints. You may notice that left shift cancels the right shift, so count the total left shift times (may be negative if the final result is right shift), and perform it once.
Python3 Solution ||Faster than 56% ||BFS|| Bahut TEZ
jump-game-iv
0
1
```\nclass Solution:\n def minJumps(self, arr: List[int]) -> int:\n h={}\n for i,e in enumerate(arr):\n if e not in h:\n h[e] = []\n h[e].append(i)\n q = [(0,0)]\n while q:\n n,d = q.pop(0)\n if n == len(arr)-1:\n r...
4
Given an integer `n`, return _a list of all **simplified** fractions between_ `0` _and_ `1` _(exclusive) such that the denominator is less-than-or-equal-to_ `n`. You can return the answer in **any order**. **Example 1:** **Input:** n = 2 **Output:** \[ "1/2 "\] **Explanation:** "1/2 " is the only unique fraction wit...
Build a graph of n nodes where nodes are the indices of the array and edges for node i are nodes i+1, i-1, j where arr[i] == arr[j]. Start bfs from node 0 and keep distance. The answer is the distance when you reach node n-1.
Python3 || Simple Binary Search approach
check-if-n-and-its-double-exist
0
1
![image.png](https://assets.leetcode.com/users/images/6128ee21-1f40-477e-9fba-01f9bb922a2a_1679885453.0123944.png)\n# Code\n```\nclass Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n arr.sort()\n for i in range(len(arr)):\n product = arr[i]*2\n lo,hi = 0,len(arr)-1\n...
21
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that : * `i != j` * `0 <= i, j < arr.length` * `arr[i] == 2 * arr[j]` **Example 1:** **Input:** arr = \[10,2,5,3\] **Output:** true **Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\] **Example 2:**...
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
Haven't Seen this Solution Yet | Easy! | Python
check-if-n-and-its-double-exist
0
1
I am checking if `2*i` or `i/2` exists in `tmp`. I would note the \n`(i%2 == 0 and i/2 in tmp)` as we want to make sure our answer is a whole number, other no point in putting it in the array.\n# Code\n```\nclass Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n tmp = set()\n\n for i in arr...
1
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that : * `i != j` * `0 <= i, j < arr.length` * `arr[i] == 2 * arr[j]` **Example 1:** **Input:** arr = \[10,2,5,3\] **Output:** true **Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\] **Example 2:**...
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
4 LINES || PYTHON SOLUTION || USING SETS|| 40 MS||EASY
check-if-n-and-its-double-exist
0
1
```\nclass Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n if arr.count(0) > 1: return 1\n S = set(arr) - {0}\n for i in arr:\n if 2*i in S: return 1\n return 0\n
3
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that : * `i != j` * `0 <= i, j < arr.length` * `arr[i] == 2 * arr[j]` **Example 1:** **Input:** arr = \[10,2,5,3\] **Output:** true **Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\] **Example 2:**...
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
Easy O(n) solution with HashMap
check-if-n-and-its-double-exist
0
1
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n ans = set()\n\n for n in arr:\n if n in ans:\n return True\n\n ans.add(n * 2)\n\n # We can skip...
1
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that : * `i != j` * `0 <= i, j < arr.length` * `arr[i] == 2 * arr[j]` **Example 1:** **Input:** arr = \[10,2,5,3\] **Output:** true **Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\] **Example 2:**...
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
PYTHON || O( n logn ) || Binary Search
check-if-n-and-its-double-exist
0
1
Sort the array -> **n logn**\n\nIterate each element and search for its double usig binary search -> **n * log n**\n\n**OVERALL COMPLEXITY = O ( n logn )**\n\n```\nclass Solution:\n def checkIfExist(self, arr: List[int]) -> bool:\n arr.sort()\n n=len(arr)\n for i in range(n):\n k=arr...
5
Given an array `arr` of integers, check if there exist two indices `i` and `j` such that : * `i != j` * `0 <= i, j < arr.length` * `arr[i] == 2 * arr[j]` **Example 1:** **Input:** arr = \[10,2,5,3\] **Output:** true **Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\] **Example 2:**...
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
python3, beat 85% ; 5 lines code
check-if-n-and-its-double-exist
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 an array `arr` of integers, check if there exist two indices `i` and `j` such that : * `i != j` * `0 <= i, j < arr.length` * `arr[i] == 2 * arr[j]` **Example 1:** **Input:** arr = \[10,2,5,3\] **Output:** true **Explanation:** For i = 0 and j = 2, arr\[i\] == 10 == 2 \* 5 == 2 \* arr\[j\] **Example 2:**...
For each index i, how can we check if nums[i] can be present at the top of the pile or not after k moves? For which conditions will we end up with an empty pile?
Easy Solution in python | using Counter
minimum-number-of-steps-to-make-two-strings-anagram
0
1
\n# Code\n```\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n cnt1=Counter(s)\n cnt2=Counter(t)\n sm=0\n for i,j in cnt2.items():\n if i in cnt1 and j>cnt1[i]:\n sm+=abs(j-cnt1[i])\n elif i not in cnt1:\n sm+=j\n r...
3
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the...
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the ...
[Python 3] 1 line with Counter || beats 99% || 104ms 🥷🏼
minimum-number-of-steps-to-make-two-strings-anagram
0
1
```python3 []\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n return (Counter(s) - Counter(t)).total()\n```\n![Screenshot 2023-07-28 at 05.28.54.png](https://assets.leetcode.com/users/images/34a9cbb7-d2ea-4436-976b-690eaa4b7a61_1690511451.477379.png)\n\n[2186. Minimum Number of Steps to Make T...
5
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the...
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the ...
Python easy solution with explanation o(n) time and space: faster 97%
minimum-number-of-steps-to-make-two-strings-anagram
0
1
##### Idea: the strings are equal in length \n* ##### Replacing is the only operation \n* ##### Find how many characters t and s shares \n* ##### And the remining would be the needed replacment \n\t1. * ##### count the letter occurance in the s \n\t1. ...
33
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the...
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the ...
PYTHON SOLUTION - HASHMAP || EXPLAINED✔
minimum-number-of-steps-to-make-two-strings-anagram
0
1
```\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n d1={}\n d2={}\n c=0\n #frequency of s\n for i in s:\n if i in d1:\n d1[i]+=1\n else:\n d1[i]=1\n #frequency of t \n for i in t:\n ...
4
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the...
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the ...
Very Easy one-liner Python Solution
minimum-number-of-steps-to-make-two-strings-anagram
0
1
\n\n# Approach\nAdd the differences in the frequencies of characters in t and s.\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minSteps(self, s: st...
2
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the...
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the ...
Python || easy solution || beat~99% || using counter
minimum-number-of-steps-to-make-two-strings-anagram
0
1
# if you like the solution, Please upvote!!\n\tclass Solution:\n\t\tdef minSteps(self, s: str, t: str) -> int:\n\n\t\t\tcommon = Counter(s) & Counter(t)\n\t\t\tcount = sum(common.values())\n\n\t\t\treturn len(s) - count
5
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the...
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the ...
78% TC and 79% SC easy python solution
minimum-number-of-steps-to-make-two-strings-anagram
0
1
```\ndef minSteps(self, s: str, t: str) -> int:\n\ts = Counter(s)\n\tt = Counter(t)\n\tans = 0\n\tfor i in t:\n\t\tif(i not in s):\n\t\t\tans += t[i]\n\t\telif(t[i] > s[i]):\n\t\t\tans += t[i]-s[i]\n\treturn ans\n```
2
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the...
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the ...
Python solution
minimum-number-of-steps-to-make-two-strings-anagram
0
1
Delete the common characters in s and t; Number of remaining characters in t is the answer. \n\n```\nclass Solution:\n def minSteps(self, s: str, t: str) -> int:\n for ch in s:\n\t\t # Find and replace only one occurence of this character in t\n t = t.replace(ch, \'\', 1)\n \n ...
19
You are given two strings of the same length `s` and `t`. In one step you can choose **any character** of `t` and replace it with **another character**. Return _the minimum number of steps_ to make `t` an anagram of `s`. An **Anagram** of a string is a string that contains the same characters with a different (or the...
This problem can be broken down into two parts: finding the cycle, and finding the distance between each node and the cycle. How can we find the cycle? We can use DFS and keep track of the nodes we’ve seen, and the order that we see them in. Once we see a node we’ve already visited, we know that the cycle contains the ...
[Python3] linear scan
tweet-counts-per-frequency
0
1
Algorithm:\nScan through the time for a given `tweetName` and add the count in the corresponding interval. \n\nImplementation: \n```\nclass TweetCounts:\n\n def __init__(self):\n self.tweets = dict()\n\n def recordTweet(self, tweetName: str, time: int) -> None:\n self.tweets.setdefault(tweetName, []...
39
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). For example, the period `[10, 10000]` (in **sec...
null
[Python3] linear scan
tweet-counts-per-frequency
0
1
Algorithm:\nScan through the time for a given `tweetName` and add the count in the corresponding interval. \n\nImplementation: \n```\nclass TweetCounts:\n\n def __init__(self):\n self.tweets = dict()\n\n def recordTweet(self, tweetName: str, time: int) -> None:\n self.tweets.setdefault(tweetName, []...
39
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Easy to Read Python Solution
tweet-counts-per-frequency
0
1
```\nclass TweetCounts:\n\n def __init__(self):\n self.dict = {}\n \n\n def recordTweet(self, tweetName: str, time: int) -> None:\n if(tweetName not in self.dict):\n self.dict[tweetName] = [time]\n else:\n self.dict[tweetName].append(time)\n \n\n def get...
21
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). For example, the period `[10, 10000]` (in **sec...
null
Easy to Read Python Solution
tweet-counts-per-frequency
0
1
```\nclass TweetCounts:\n\n def __init__(self):\n self.dict = {}\n \n\n def recordTweet(self, tweetName: str, time: int) -> None:\n if(tweetName not in self.dict):\n self.dict[tweetName] = [time]\n else:\n self.dict[tweetName].append(time)\n \n\n def get...
21
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Clean Python bisect solution
tweet-counts-per-frequency
0
1
```\nimport bisect\nclass TweetCounts:\n FREQS = {\n \'minute\': 60,\n \'hour\': 60 * 60,\n \'day\': 60 * 60 * 24\n }\n\n def __init__(self):\n self.tweets = defaultdict(list)\n\n def recordTweet(self, tweetName: str, time: int) -> None:\n bisect.insort(self.tweets[tweetNa...
5
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). For example, the period `[10, 10000]` (in **sec...
null
Clean Python bisect solution
tweet-counts-per-frequency
0
1
```\nimport bisect\nclass TweetCounts:\n FREQS = {\n \'minute\': 60,\n \'hour\': 60 * 60,\n \'day\': 60 * 60 * 24\n }\n\n def __init__(self):\n self.tweets = defaultdict(list)\n\n def recordTweet(self, tweetName: str, time: int) -> None:\n bisect.insort(self.tweets[tweetNa...
5
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Python. Beats 99% of solutions. Best data structures (Ordered lists and binary searches)
tweet-counts-per-frequency
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith this problem, I was definitely aiming for a really nice solution but was blown away when my solution came in the top 1%. I was aiming to ensure that I kept things ordered where possible and possibly aimed for a bit of a production so...
0
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). For example, the period `[10, 10000]` (in **sec...
null
Python. Beats 99% of solutions. Best data structures (Ordered lists and binary searches)
tweet-counts-per-frequency
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith this problem, I was definitely aiming for a really nice solution but was blown away when my solution came in the top 1%. I was aiming to ensure that I kept things ordered where possible and possibly aimed for a bit of a production so...
0
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Concise Python: SortedList + BinarySearch
tweet-counts-per-frequency
0
1
# Intuition\nsimulate the timeline fo the tweet records\n# Approach\nUse hashmap + sortedlist to \n\n# Complexity\n- Time complexity:\nadd record O(log(n))\ncountChunkFreq O(klog(n)) k = (endTime - startTime) / chunkSize\n\n- Space complexity:\nO(n) (n = number of records)\n\n# Code\n```\nfrom sortedcontainers import S...
0
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). For example, the period `[10, 10000]` (in **sec...
null
Concise Python: SortedList + BinarySearch
tweet-counts-per-frequency
0
1
# Intuition\nsimulate the timeline fo the tweet records\n# Approach\nUse hashmap + sortedlist to \n\n# Complexity\n- Time complexity:\nadd record O(log(n))\ncountChunkFreq O(klog(n)) k = (endTime - startTime) / chunkSize\n\n- Space complexity:\nO(n) (n = number of records)\n\n# Code\n```\nfrom sortedcontainers import S...
0
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Real World Optimized | Commented and Explained
tweet-counts-per-frequency
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want a map of a tweetName to a dictionary of time frequencies\nWe want to be able to do chunk sizes of seconds based on different larger intervals \nWe want to be able to determine an interval based on an ending and start time per chun...
0
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). For example, the period `[10, 10000]` (in **sec...
null
Real World Optimized | Commented and Explained
tweet-counts-per-frequency
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want a map of a tweetName to a dictionary of time frequencies\nWe want to be able to do chunk sizes of seconds based on different larger intervals \nWe want to be able to determine an interval based on an ending and start time per chun...
0
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Python 3 using binary search
tweet-counts-per-frequency
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
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). For example, the period `[10, 10000]` (in **sec...
null
Python 3 using binary search
tweet-counts-per-frequency
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Binary Search python3 Solution
tweet-counts-per-frequency
0
1
```\n\nclass TweetCounts:\n \n # O(1) time,\n # O(1) space,\n # Approach: hashtable, \n def __init__(self):\n self.records = defaultdict(list)\n self.time_mapping = {"minute": 59, "hour": 3599, "day": 86399}\n\n \n # O(1) time,\n # O(1) space,\n # Approach: hashtable, \n def ...
0
A social media company is trying to monitor activity on their site by analyzing the number of tweets that occur in select periods of time. These periods can be partitioned into smaller **time chunks** based on a certain frequency (every **minute**, **hour**, or **day**). For example, the period `[10, 10000]` (in **sec...
null
Binary Search python3 Solution
tweet-counts-per-frequency
0
1
```\n\nclass TweetCounts:\n \n # O(1) time,\n # O(1) space,\n # Approach: hashtable, \n def __init__(self):\n self.records = defaultdict(list)\n self.time_mapping = {"minute": 59, "hour": 3599, "day": 86399}\n\n \n # O(1) time,\n # O(1) space,\n # Approach: hashtable, \n def ...
0
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer ...
null
Python Easy Solution | Bitmask DP | Faster than 65%
maximum-students-taking-exam
0
1
# Code\n```python []\nclass Solution:\n def maxStudents(self, seats: List[List[str]]) -> int:\n numRows, numCols = len(seats), len(seats[0])\n\n def check(col: int, prevMask: int) -> bool:\n if col <= 0:\n if prevMask & (1 << (col + 1)):\n return False\n ...
2
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s...
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
[python] BitMask the seats, previous row state, and the current row state
maximum-students-taking-exam
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. -->\nPut everythng into bitmask for easy comparisons. \nnew_mask & seat_mask[row] == 0. check if seats are not broken\n(mask << 1) & new_mask == (mask >> 1) & new_mask == 0...
0
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s...
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
DFS + bitmask with memoization in python3
maximum-students-taking-exam
0
1
This is basically a backtracking question. First bitmask question I solved myself...\n\n# Code\n```\nclass Solution:\n def maxStudents(self, seats: List[List[str]]) -> int:\n m = len(seats)\n n = len(seats[0])\n self.res = 0\n @cache \n def dp(i,premask,j,currmask,stu):\n ...
0
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s...
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
Python 95% + intuition
maximum-students-taking-exam
0
1
# Intuition\nWe start with a brute force approach. This involves recursively backtracking over the entire set of states and choosing to place or not place children in seats. This will result in a cost of about O(2^(mn)).\n\nWhen it comes to recursive problems, a good question is to ask: is it possible to memoize, bound...
0
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s...
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
Primal Dual Solution | Commented and Explained
maximum-students-taking-exam
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe are asked to find how many students we can maximally seat. We can instead consider what is the minimal number of seats that have an invalid placement. From this, we can then take our total number of seats and reduce it by the total of ...
0
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s...
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
DP bitmask python3
maximum-students-taking-exam
0
1
# Intuition\nplain back-tracking\nO(2^(n*n)) TLE\n```\nclass Solution:\n def maxStudents(self, seats: List[List[str]]) -> int:\n def can_place(i, j):\n if seats[i][j]==\'#\':\n return False\n for x, y in [(i, j-1), (i, j+1), (i-1,j+1), (i-1, j-1)]:\n if 0<=x...
0
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s...
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
Short solution with memoization in Python, with explanation
maximum-students-taking-exam
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor every seat, we have two choices: to assign or not to assign a student. To assign a student, the seat should be not broken and no students assigned in its four neighboring seats (i.e., left, right, upper-left, and upper-right). The inp...
0
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s...
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
Recursive Bitmask DP with Memoization | Python
maximum-students-taking-exam
0
1
# Intuition\nThe ```mask``` that has been used in this solution is for a row, mask of a row shows the seats that has a student on them(1 if there is a student on a seat and 0 otherwise)\n\nwe are filling rows from last to first(from ```m-1``` to 0). ```dfs(row, index, curr_mask, prev_mask)``` return the number of maxim...
0
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the s...
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
Brute force simple solution in python.
count-negative-numbers-in-a-sorted-matrix
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 `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. **Example 1:** **Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\] **Output:** 8 **Explanation:** There are 8 negatives number in the ma...
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
Brute force simple solution in python.
count-negative-numbers-in-a-sorted-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods: 1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)` * Updates all values with `newValue` in the subrectangle whose upper left coordinate i...
Use binary search for optimization or simply brute force.
izi
count-negative-numbers-in-a-sorted-matrix
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 `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. **Example 1:** **Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\] **Output:** 8 **Explanation:** There are 8 negatives number in the ma...
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
izi
count-negative-numbers-in-a-sorted-matrix
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
Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods: 1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)` * Updates all values with `newValue` in the subrectangle whose upper left coordinate i...
Use binary search for optimization or simply brute force.
Python 3: (Easy) modificated Binary search
count-negative-numbers-in-a-sorted-matrix
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 `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. **Example 1:** **Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\] **Output:** 8 **Explanation:** There are 8 negatives number in the ma...
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
Python 3: (Easy) modificated Binary search
count-negative-numbers-in-a-sorted-matrix
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
Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods: 1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)` * Updates all values with `newValue` in the subrectangle whose upper left coordinate i...
Use binary search for optimization or simply brute force.
Solution that is 99% better in speed and memory
count-negative-numbers-in-a-sorted-matrix
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 `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. **Example 1:** **Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\] **Output:** 8 **Explanation:** There are 8 negatives number in the ma...
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
Solution that is 99% better in speed and memory
count-negative-numbers-in-a-sorted-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods: 1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)` * Updates all values with `newValue` in the subrectangle whose upper left coordinate i...
Use binary search for optimization or simply brute force.
C++ O(N) 4 LINES Solution 🔥Beats 100%🔥NO Binary Search
count-negative-numbers-in-a-sorted-matrix
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStart!\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Start from the bottom of the row (it will -ve);\n- NO need to check column if the first element is -ve;(sorted)\n- move up directly, if first is +ve then check...
8
Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. **Example 1:** **Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\] **Output:** 8 **Explanation:** There are 8 negatives number in the ma...
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
C++ O(N) 4 LINES Solution 🔥Beats 100%🔥NO Binary Search
count-negative-numbers-in-a-sorted-matrix
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nStart!\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Start from the bottom of the row (it will -ve);\n- NO need to check column if the first element is -ve;(sorted)\n- move up directly, if first is +ve then check...
8
Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods: 1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)` * Updates all values with `newValue` in the subrectangle whose upper left coordinate i...
Use binary search for optimization or simply brute force.
Bruteforce Easiest Solution C++ 🔥
count-negative-numbers-in-a-sorted-matrix
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSTART\n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust trivese in each row and column and done\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2)\n- Space complexity:...
3
Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. **Example 1:** **Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\] **Output:** 8 **Explanation:** There are 8 negatives number in the ma...
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
Bruteforce Easiest Solution C++ 🔥
count-negative-numbers-in-a-sorted-matrix
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSTART\n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust trivese in each row and column and done\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N^2)\n- Space complexity:...
3
Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods: 1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)` * Updates all values with `newValue` in the subrectangle whose upper left coordinate i...
Use binary search for optimization or simply brute force.
Simple Solution with both Brute Force and Optimal approaches in three languages
count-negative-numbers-in-a-sorted-matrix
1
1
# Brute Force\n## Intuition\nBrute force approach is easy just go through the matrix and find the number is less than zero or not ,if less than zero then increase your count variable.\n\n## Approach\n<!-- Describe your approach to solving the problem. -->\nApproach is same as I discussed in intution section \n\n## Comp...
3
Given a `m x n` matrix `grid` which is sorted in non-increasing order both row-wise and column-wise, return _the number of **negative** numbers in_ `grid`. **Example 1:** **Input:** grid = \[\[4,3,2,-1\],\[3,2,1,-1\],\[1,1,-1,-2\],\[-1,-1,-2,-3\]\] **Output:** 8 **Explanation:** There are 8 negatives number in the ma...
Use 2-pointers algorithm to make sure all amount of characters outside the 2 pointers are smaller or equal to n/4. That means you need to count the amount of each letter and make sure the amount is enough.
Simple Solution with both Brute Force and Optimal approaches in three languages
count-negative-numbers-in-a-sorted-matrix
1
1
# Brute Force\n## Intuition\nBrute force approach is easy just go through the matrix and find the number is less than zero or not ,if less than zero then increase your count variable.\n\n## Approach\n<!-- Describe your approach to solving the problem. -->\nApproach is same as I discussed in intution section \n\n## Comp...
3
Implement the class `SubrectangleQueries` which receives a `rows x cols` rectangle as a matrix of integers in the constructor and supports two methods: 1. `updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)` * Updates all values with `newValue` in the subrectangle whose upper left coordinate i...
Use binary search for optimization or simply brute force.
Python3 97% solution
product-of-the-last-k-numbers
0
1
```python\nclass ProductOfNumbers:\n def __init__(self):\n self.data = []\n self.product = 1\n\n def add(self, num: int) -> None:\n if num != 0:\n self.product *= num\n self.data.append(self.product)\n else:\n self.data = []\n self.product = ...
29
Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream. Implement the `ProductOfNumbers` class: * `ProductOfNumbers()` Initializes the object with an empty stream. * `void add(int num)` Appends the integer `num` to the stream. * `int getProduct(int...
Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.
Python3 97% solution
product-of-the-last-k-numbers
0
1
```python\nclass ProductOfNumbers:\n def __init__(self):\n self.data = []\n self.product = 1\n\n def add(self, num: int) -> None:\n if num != 0:\n self.product *= num\n self.data.append(self.product)\n else:\n self.data = []\n self.product = ...
29
You are given an array of integers `arr` and an integer `target`. You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**. Return _the minimum sum of the l...
Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products.
87% beats. very easy
product-of-the-last-k-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
4
Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream. Implement the `ProductOfNumbers` class: * `ProductOfNumbers()` Initializes the object with an empty stream. * `void add(int num)` Appends the integer `num` to the stream. * `int getProduct(int...
Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.
87% beats. very easy
product-of-the-last-k-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
4
You are given an array of integers `arr` and an integer `target`. You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**. Return _the minimum sum of the l...
Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products.
Python solution. With explanation. BEATS 99%
product-of-the-last-k-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is to use a list to store the numbers that have been added, and use the last k elements of the list to calculate the product. However, I also need to consider the case where a zero is added to the list, which would make t...
3
Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream. Implement the `ProductOfNumbers` class: * `ProductOfNumbers()` Initializes the object with an empty stream. * `void add(int num)` Appends the integer `num` to the stream. * `int getProduct(int...
Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.
Python solution. With explanation. BEATS 99%
product-of-the-last-k-numbers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is to use a list to store the numbers that have been added, and use the last k elements of the list to calculate the product. However, I also need to consider the case where a zero is added to the list, which would make t...
3
You are given an array of integers `arr` and an integer `target`. You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**. Return _the minimum sum of the l...
Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products.
[Python3] - Easy to Understand Prefix Product
product-of-the-last-k-numbers
0
1
This approach is similar to the one for prefix sum, where we keep a list of all the products up to index = i:\ne.g. If the given input of numbers is: ```[3, 4, 5]```, the prefix product list that we keep will be: ```[3, 3x4, 3x4x5] => [3, 12, 60]```\n\nEvery time we are fed with a zero, say at index i, we know that if ...
4
Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream. Implement the `ProductOfNumbers` class: * `ProductOfNumbers()` Initializes the object with an empty stream. * `void add(int num)` Appends the integer `num` to the stream. * `int getProduct(int...
Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.
[Python3] - Easy to Understand Prefix Product
product-of-the-last-k-numbers
0
1
This approach is similar to the one for prefix sum, where we keep a list of all the products up to index = i:\ne.g. If the given input of numbers is: ```[3, 4, 5]```, the prefix product list that we keep will be: ```[3, 3x4, 3x4x5] => [3, 12, 60]```\n\nEvery time we are fed with a zero, say at index i, we know that if ...
4
You are given an array of integers `arr` and an integer `target`. You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**. Return _the minimum sum of the l...
Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products.
Easy Python Code in O(n)
product-of-the-last-k-numbers
0
1
# Code\n```\nclass ProductOfNumbers:\n\n def __init__(self):\n self.p = []\n self.prod = 1\n\n def add(self, num: int) -> None:\n if(num != 0):\n self.prod *= num\n self.p.append(self.prod)\n else:\n self.p = []\n self.prod = 1\n \n\n ...
0
Design an algorithm that accepts a stream of integers and retrieves the product of the last `k` integers of the stream. Implement the `ProductOfNumbers` class: * `ProductOfNumbers()` Initializes the object with an empty stream. * `void add(int num)` Appends the integer `num` to the stream. * `int getProduct(int...
Think on DP. Sort the elements by starting time, then define the dp[i] as the maximum profit taking elements from the suffix starting at i. Use binarySearch (lower_bound/upper_bound on C++) to get the next index for the DP transition.
Easy Python Code in O(n)
product-of-the-last-k-numbers
0
1
# Code\n```\nclass ProductOfNumbers:\n\n def __init__(self):\n self.p = []\n self.prod = 1\n\n def add(self, num: int) -> None:\n if(num != 0):\n self.prod *= num\n self.p.append(self.prod)\n else:\n self.p = []\n self.prod = 1\n \n\n ...
0
You are given an array of integers `arr` and an integer `target`. You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**. Return _the minimum sum of the l...
Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products.
Simple and optimal python3 solution | 871 ms - faster than 99% solutions
maximum-number-of-events-that-can-be-attended
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 \\cdot log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- ...
1
You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`. You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one event at any time `d`. Return _the maximum number of events you can attend_....
null
Simple and optimal python3 solution | 871 ms - faster than 99% solutions
maximum-number-of-events-that-can-be-attended
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 \\cdot log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- ...
1
Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street. Return _the **minimum** total distance between each house and its nearest mailbox_. The test cases are generated so that the answer fits in a 32-bit integer. **Exampl...
Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in.
[Python] Faster than 90%, Low-space, Simple, Min-Heap, Explained
maximum-number-of-events-that-can-be-attended
0
1
Please feel free to ask questions or give suggestions. **Upvote** if you liked the solution.\n**Idea**:\n1. Sort events by startDay.\n2. Keep track of endDays for started events in a min-heap based on current day.\n3. Greedily attend started event with lowest endDay. Move to the next viable day. \n4. Repeat steps 2 and...
23
You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`. You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one event at any time `d`. Return _the maximum number of events you can attend_....
null
[Python] Faster than 90%, Low-space, Simple, Min-Heap, Explained
maximum-number-of-events-that-can-be-attended
0
1
Please feel free to ask questions or give suggestions. **Upvote** if you liked the solution.\n**Idea**:\n1. Sort events by startDay.\n2. Keep track of endDays for started events in a min-heap based on current day.\n3. Greedily attend started event with lowest endDay. Move to the next viable day. \n4. Repeat steps 2 and...
23
Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street. Return _the **minimum** total distance between each house and its nearest mailbox_. The test cases are generated so that the answer fits in a 32-bit integer. **Exampl...
Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in.
[Python3] Heap
maximum-number-of-events-that-can-be-attended
0
1
```\nclass Solution:\n def maxEvents(self, events: List[List[int]]) -> int:\n # 1. person can only attend one event per day, even if there are multiple events on that day.\n # 2. if there are multiple events happen at one day,\n # person attend the event ends close to current day.\n #....
8
You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`. You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one event at any time `d`. Return _the maximum number of events you can attend_....
null
[Python3] Heap
maximum-number-of-events-that-can-be-attended
0
1
```\nclass Solution:\n def maxEvents(self, events: List[List[int]]) -> int:\n # 1. person can only attend one event per day, even if there are multiple events on that day.\n # 2. if there are multiple events happen at one day,\n # person attend the event ends close to current day.\n #....
8
Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street. Return _the **minimum** total distance between each house and its nearest mailbox_. The test cases are generated so that the answer fits in a 32-bit integer. **Exampl...
Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in.
📌📌 Well-Coded & Explained || Heap || For Beignners 🐍
maximum-number-of-events-that-can-be-attended
0
1
## IDEA :\n1. Person can only attend one event per day, even if there are multiple events on that day.\n2. if there are multiple events happen at one day, then person attend the event that ends close to current day. so we need a data structure hold all the event happend today, and sorted ascedningly. \n\n3. Minimum hea...
13
You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`. You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one event at any time `d`. Return _the maximum number of events you can attend_....
null
📌📌 Well-Coded & Explained || Heap || For Beignners 🐍
maximum-number-of-events-that-can-be-attended
0
1
## IDEA :\n1. Person can only attend one event per day, even if there are multiple events on that day.\n2. if there are multiple events happen at one day, then person attend the event that ends close to current day. so we need a data structure hold all the event happend today, and sorted ascedningly. \n\n3. Minimum hea...
13
Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street. Return _the **minimum** total distance between each house and its nearest mailbox_. The test cases are generated so that the answer fits in a 32-bit integer. **Exampl...
Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in.
Python3 solution with detailed explanation
maximum-number-of-events-that-can-be-attended
0
1
When I first tried to solve this problem, a bunch of `for` loops came to my mind where I\'d probably go over the `events` and add them to a list called `visited` and go forward until there\'s no further `event` in the `events`. [@bharadwaj6](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/di...
17
You are given an array of `events` where `events[i] = [startDayi, endDayi]`. Every event `i` starts at `startDayi` and ends at `endDayi`. You can attend an event `i` at any day `d` where `startTimei <= d <= endTimei`. You can only attend one event at any time `d`. Return _the maximum number of events you can attend_....
null
Python3 solution with detailed explanation
maximum-number-of-events-that-can-be-attended
0
1
When I first tried to solve this problem, a bunch of `for` loops came to my mind where I\'d probably go over the `events` and add them to a list called `visited` and go forward until there\'s no further `event` in the `events`. [@bharadwaj6](https://leetcode.com/problems/maximum-number-of-events-that-can-be-attended/di...
17
Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street. Return _the **minimum** total distance between each house and its nearest mailbox_. The test cases are generated so that the answer fits in a 32-bit integer. **Exampl...
Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in.
Python Easy Solution || Less Line Of Code || Heapify
construct-target-array-with-multiple-sums
0
1
**Please Upvote If you find Useful**\n```\nclass Solution:\n\tdef isPossible(self, target: List[int]) -> bool:\n\n\t\theapq._heapify_max(target)\n\t\ts = sum(target)\n\n\t\twhile target[0] != 1:\n\t\t\tsub = s - target[0]\n\t\t\tif sub == 0: return False\n\t\t\tn = max((target[0] - 1) // sub, 1)\n\t\t\ts -= n * sub\n\t...
14
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat thi...
Count the number of times a player loses while iterating through the matches.
Bucket sort vs sort with Lambda->1 line||0ms Beats 100%
sort-integers-by-the-number-of-1-bits
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDefine the lambda function as the third parameter in sort function\n```\n [](int x, int y){\n if (__builtin_popcount(x)==__builtin_popcount(y))\n return x<y;\n else \n return __bu...
7
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Bucket sort vs sort with Lambda->1 line||0ms Beats 100%
sort-integers-by-the-number-of-1-bits
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDefine the lambda function as the third parameter in sort function\n```\n [](int x, int y){\n if (__builtin_popcount(x)==__builtin_popcount(y))\n return x<y;\n else \n return __bu...
7
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
Python sort using lambda
sort-integers-by-the-number-of-1-bits
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe simply pass the soring criteria in the lambda function for the key used for sorting.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMake use of inbuilt sort method.\n\n# Complexity\n- Time complexity: $O(n * lo...
4
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Python sort using lambda
sort-integers-by-the-number-of-1-bits
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe simply pass the soring criteria in the lambda function for the key used for sorting.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMake use of inbuilt sort method.\n\n# Complexity\n- Time complexity: $O(n * lo...
4
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
✅ 89.93% Sort Bit
sort-integers-by-the-number-of-1-bits
1
1
# Intuition\nUpon reading the problem, our first observation is that the sorting criteria is twofold:\n1. First, by the count of 1\'s in the binary representation.\n2. If there\'s a tie, by the actual integer value.\n\nGiven this, we can leverage Python\'s built-in sorting mechanism which supports multi-criteria sortin...
41
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
✅ 89.93% Sort Bit
sort-integers-by-the-number-of-1-bits
1
1
# Intuition\nUpon reading the problem, our first observation is that the sorting criteria is twofold:\n1. First, by the count of 1\'s in the binary representation.\n2. If there\'s a tie, by the actual integer value.\n\nGiven this, we can leverage Python\'s built-in sorting mechanism which supports multi-criteria sortin...
41
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
✅1 Liner (sorting only)✅
sort-integers-by-the-number-of-1-bits
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)$$ --...
3
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
✅1 Liner (sorting only)✅
sort-integers-by-the-number-of-1-bits
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)$$ --...
3
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
✅☑[C++/Java/Python/JavaScript] || Beats 95% || 3 Approaches || EXPLAINED🔥
sort-integers-by-the-number-of-1-bits
1
1
\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Built-in function)***\n1. **Static Comparison Function:** The code defines a static comparison function named `compare`. This function takes two integers, `a` and `b`, as input parameters and returns a boo...
2
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
✅☑[C++/Java/Python/JavaScript] || Beats 95% || 3 Approaches || EXPLAINED🔥
sort-integers-by-the-number-of-1-bits
1
1
\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1 (Built-in function)***\n1. **Static Comparison Function:** The code defines a static comparison function named `compare`. This function takes two integers, `a` and `b`, as input parameters and returns a boo...
2
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
🚀 96.58% || Built-in Functions & Brian Kerninghan's Algorithm || Explained Intuition 🚀
sort-integers-by-the-number-of-1-bits
1
1
# Problem Description\n\nGiven an integer array, **arrange** the integers in **ascending** order based on the **count** of `1s` in their **binary** representation. \nIn case of a **tie** (two or more integers with the **same** number of 1s), sort them in `ascending numerical order`. Return the **sorted** array.\n\n- Co...
88
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
🚀 96.58% || Built-in Functions & Brian Kerninghan's Algorithm || Explained Intuition 🚀
sort-integers-by-the-number-of-1-bits
1
1
# Problem Description\n\nGiven an integer array, **arrange** the integers in **ascending** order based on the **count** of `1s` in their **binary** representation. \nIn case of a **tie** (two or more integers with the **same** number of 1s), sort them in `ascending numerical order`. Return the **sorted** array.\n\n- Co...
88
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
【Video】Give me 10 minutes - Using Heap without build-in function such as sort or bit count
sort-integers-by-the-number-of-1-bits
1
1
# Intuition\nUsing Heap\n\n---\n\n# Solution Video\n\nhttps://youtu.be/oqV8Ai0_UWA\n\n\u25A0 Timeline\n`0:05` Solution code with build-in function\n`0:26` Two difficulties to solve the question\n`0:41` How do you count 1 bits?\n`1:05` Understanding to count 1 bits with an example\n`3:02` How do you keep numbers in asce...
21
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
【Video】Give me 10 minutes - Using Heap without build-in function such as sort or bit count
sort-integers-by-the-number-of-1-bits
1
1
# Intuition\nUsing Heap\n\n---\n\n# Solution Video\n\nhttps://youtu.be/oqV8Ai0_UWA\n\n\u25A0 Timeline\n`0:05` Solution code with build-in function\n`0:26` Two difficulties to solve the question\n`0:41` How do you count 1 bits?\n`1:05` Understanding to count 1 bits with an example\n`3:02` How do you keep numbers in asce...
21
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
Python3 Solution
sort-integers-by-the-number-of-1-bits
0
1
\n```\nclass Solution:\n def sortByBits(self, arr: List[int]) -> List[int]:\n return sorted(arr,key=lambda x:(bin(x).count("1"),x))\n```
1
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Python3 Solution
sort-integers-by-the-number-of-1-bits
0
1
\n```\nclass Solution:\n def sortByBits(self, arr: List[int]) -> List[int]:\n return sorted(arr,key=lambda x:(bin(x).count("1"),x))\n```
1
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
Simple one line solution
sort-integers-by-the-number-of-1-bits
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nUse the built-in sorting mechanism, but specify a custom function to sort based on the given criteria.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nConvert each integer to its binary representation, then sor...
1
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.
Simple one line solution
sort-integers-by-the-number-of-1-bits
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nUse the built-in sorting mechanism, but specify a custom function to sort based on the given criteria.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nConvert each integer to its binary representation, then sor...
1
Given two arrays `nums1` and `nums2`. Return the maximum dot product between **non-empty** subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of...
Simulate the problem. Count the number of 1's in the binary representation of each integer. Sort by the number of 1's ascending and by the value in case of tie.
Python 1L / Rust 2-3 L / Go a lot.
sort-integers-by-the-number-of-1-bits
0
1
# Intuition\nAll you need is to count the number of ones, create tules of `(cnt, v)` and then do sorting. Many languages allow to do this in one line\n\n# Complexity\n- Time complexity: $O(n \\log n)$\n- Space complexity: $O(n)$\n\n# Code\n```Rust []\nimpl Solution {\n pub fn sort_by_bits(arr: Vec<i32>) -> Vec<i32> {\...
1
You are given an integer array `arr`. Sort the integers in the array in ascending order by the number of `1`'s in their binary representation and in case of two or more integers have the same number of `1`'s you have to sort them in ascending order. Return _the array after sorting it_. **Example 1:** **Input:** arr ...
Consider a greedy strategy. Let’s start by making the leftmost and rightmost characters match with some number of swaps. If we figure out how to do that using the minimum number of swaps, then we can delete the leftmost and rightmost characters and solve the problem recursively.