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
✅C++|| Java || Python || Solution using Backtracking (faster 80.39%(98 ms), memory 100%(8.6 mb))
maximum-number-of-achievable-transfer-requests
1
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n\nThe `maximumRequests` function initializes a vector `v` of size `n` with all elements initialized to 0. This vector represents the current state of the buildings. Each element in the vector represents the net change in the number of requests...
1
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to th...
Think brute force When is a subset of requests okay?
Backtracking Solution (Java, Python, C++)
maximum-number-of-achievable-transfer-requests
1
1
**Java**\n```\nclass Solution {\n int answer = 0;\n public int maximumRequests(int n, int[][] requests) {\n int[] inDegree = new int[n];\n helper(0,0,inDegree,requests);\n return answer;\n }\n private void helper(int index,int count, int[] indegree,int[][] requests) {\n if(index ...
1
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to bu...
null
Backtracking Solution (Java, Python, C++)
maximum-number-of-achievable-transfer-requests
1
1
**Java**\n```\nclass Solution {\n int answer = 0;\n public int maximumRequests(int n, int[][] requests) {\n int[] inDegree = new int[n];\n helper(0,0,inDegree,requests);\n return answer;\n }\n private void helper(int index,int count, int[] indegree,int[][] requests) {\n if(index ...
1
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to th...
Think brute force When is a subset of requests okay?
Python Solution || Backtracking
maximum-number-of-achievable-transfer-requests
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will maintain a list **out_in_degree** of length n.\nWhile traversing requests[i] = [fromi, toi], we will subtract -1 from out_in_degree[fromi] and add +1 to out_in_degree[toi] and when we reach to the end of requests then we will check if out_in_d...
1
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to bu...
null
Python Solution || Backtracking
maximum-number-of-achievable-transfer-requests
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nWe will maintain a list **out_in_degree** of length n.\nWhile traversing requests[i] = [fromi, toi], we will subtract -1 from out_in_degree[fromi] and add +1 to out_in_degree[toi] and when we reach to the end of requests then we will check if out_in_d...
1
You are given an integer array `jobs`, where `jobs[i]` is the amount of time it takes to complete the `ith` job. There are `k` workers that you can assign jobs to. Each job should be assigned to **exactly** one worker. The **working time** of a worker is the sum of the time it takes to complete all jobs assigned to th...
Think brute force When is a subset of requests okay?
Easy python soln beats 71.7% in memory
design-parking-system
0
1
# Easy python solution\n\n# Code\n```\nclass ParkingSystem(object):\n def __init__(self, big, medium, small):\n self.ar=[big,medium,small]\n def addCar(self, carType):\n if self.ar[carType-1]>0:\n self.ar[carType-1]-=1\n return True\n return False\n```
1
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slot...
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Python short and clean. 2-liner.
design-parking-system
0
1
# Approach\n1. Store the available `slots` in an array.\n\n2. For each call to `addCar`, decrement the count if `count > -1`. Return `True` if `count > -1` else `False`.\n\n# Complexity\n- Time complexity: $$O(1)$$\n\n- Space complexity: $$O(1)$$\n\nfor both `init` and `addCar` methods.\n\n# Code\n```python\nclass Park...
2
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slot...
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand
design-parking-system
1
1
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \u...
10
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slot...
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
python 3 - simple iteration
design-parking-system
0
1
# Complexity\n- Time complexity:\n__init__ : O(1)\naddCar: O(1)\n\n- Space complexity:\n__init__ : O(1)\naddCar: O(1)\n\n# Code\n```\nclass ParkingSystem:\n\n def __init__(self, big: int, medium: int, small: int):\n self.space = [0, big, medium, small]\n \n def addCar(self, carType: int) -> bool:\n ...
5
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slot...
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
[Python] Clean and Fast Solution
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
0
1
```python\nclass Solution:\n # 668 ms, 99.52%. Time: O(NlogN). Space: O(N)\n def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n \n def is_within_1hr(t1, t2):\n h1, m1 = t1.split(":")\n h2, m2 = t2.split(":")\n if int(h1) + 1 < int(h2): retur...
10
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
Beat 100% 650ms easy understanding hashtable python3
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
0
1
https://leetcode.com/problems/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period/submissions/933863150/?submissionId=933863150\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHashtable \n\n# Complexity\n- Time complexity: O(N log N)\n N = number of emplyees\n<!-- Add your time co...
3
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
Python3 | Dict + Sort
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
0
1
```\nclass Solution:\n def alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]:\n key_time = {}\n for index, name in enumerate(keyName):\n key_time[name] = key_time.get(name, [])\n key_time[name].append(int(keyTime[index].replace(":", "")))\n ans = []\n ...
4
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
python dict
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
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
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
Very simple easy for beginners using hashmap and sorting !!!!
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
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
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
[Python] Sliding Window, HashMap | Clean and Fast Solution
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGrouping the times by each person will make the check much easier.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe use a hashmap to group every person\'s time together and then check if any of them swiped more...
0
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
Python - Sorting and Min Heap
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nProcessing entries in increasing order of keyTime ensures that the timestamps to follow will always be greater and that\'s why the size of heap can be limited to 3 and the first timestamp can be deleted from the heap as that would never b...
0
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
Python 3 solution
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
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
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
Python Easy to Understand
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
0
1
\n# Code\n```\nclass Solution:\n def alertNames(self, keyname: List[str], keytime: List[str]) -> List[str]:\n keytime_mins=[]\n for i in keytime:\n h,m=i.split(\':\')\n keytime_mins.append(int(h)*60+int(m))\n d={}\n for i in range(len(keyname)):\n if keyna...
0
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
dict by name, sort and run sliding window of length 2
alert-using-same-key-card-three-or-more-times-in-a-one-hour-period
0
1
\n# Code\n```\ndef alertNames(self, name: List[str], time: List[str]) -> List[str]:\n n = len(name)\n def time2int(time):\n h, m = time.split(":")\n return int(h)*60 + int(m)\n data = defaultdict(list)\n for i in range(n):\n data[name[i]].append(time2int(time[i]))\n ret = []\n for...
0
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an **alert** if any worker uses the key-card **three or more times** in a one-hour period. You are given a list of strings `...
Use a map to count the frequencies of the numbers in the array. An optimal strategy is to remove the numbers with the smallest count first.
[Python & C++] (Greedy) Easy python solution. { Explained using images}
find-valid-matrix-given-row-and-column-sums
0
1
\nIntuition : To fill matrix, based on the fact of making, the total sum on both of the row and column to zero.\nLets take this example: RowSum = [14, 9] and ColSum = [ 6 , 9 , 8 ]\nso create a empty matrix initially with zero filled.\n![image](https://assets.leetcode.com/users/images/7e053317-be36-452e-b937-281ce4bf20...
61
You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column...
If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.
[Python & C++] (Greedy) Easy python solution. { Explained using images}
find-valid-matrix-given-row-and-column-sums
0
1
\nIntuition : To fill matrix, based on the fact of making, the total sum on both of the row and column to zero.\nLets take this example: RowSum = [14, 9] and ColSum = [ 6 , 9 , 8 ]\nso create a empty matrix initially with zero filled.\n![image](https://assets.leetcode.com/users/images/7e053317-be36-452e-b937-281ce4bf20...
61
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of fo...
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Python Beats 99.83% with Illustration
find-valid-matrix-given-row-and-column-sums
0
1
**The example are there to just confuse you so forget about the example.**\n![image](https://assets.leetcode.com/users/images/c7eef2f3-ac62-4df7-b302-c18c85745589_1608146253.6067042.png)\n![image](https://assets.leetcode.com/users/images/e259ac76-dda2-4da9-9702-eedd1342118b_1608146255.9752257.png)\n![image](https://ass...
35
You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column...
If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.
Python Beats 99.83% with Illustration
find-valid-matrix-given-row-and-column-sums
0
1
**The example are there to just confuse you so forget about the example.**\n![image](https://assets.leetcode.com/users/images/c7eef2f3-ac62-4df7-b302-c18c85745589_1608146253.6067042.png)\n![image](https://assets.leetcode.com/users/images/e259ac76-dda2-4da9-9702-eedd1342118b_1608146255.9752257.png)\n![image](https://ass...
35
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of fo...
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
[C++/Python3] Greedy | Fill Minimum Element Left | O(n*m)
find-valid-matrix-given-row-and-column-sums
0
1
**Thought Process**\n\nIterate through each row and column one by one, for each `i` (row) and `j` (column) pick the minimum element between `rowSum[i]` and `colSum[j]` and assign `el = min(rowSum[i], colSum[j])` and reduce this `el` from both sum entries respectively.\n\nTada!\n\n**Time Complexity** : `O(n*m)`\n**Space...
12
You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column...
If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.
[C++/Python3] Greedy | Fill Minimum Element Left | O(n*m)
find-valid-matrix-given-row-and-column-sums
0
1
**Thought Process**\n\nIterate through each row and column one by one, for each `i` (row) and `j` (column) pick the minimum element between `rowSum[i]` and `colSum[j]` and assign `el = min(rowSum[i], colSum[j])` and reduce this `el` from both sum entries respectively.\n\nTada!\n\n**Time Complexity** : `O(n*m)`\n**Space...
12
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of fo...
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
50% TC and 67% SC easy python solution
find-valid-matrix-given-row-and-column-sums
0
1
```\ndef restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:\n\tr = len(rowSum)\n\tc = len(colSum)\n\tans = [[-1 for _ in range(c)] for _ in range(r)]\n\tfor i in range(r):\n\t\tfor j in range(c):\n\t\t\tif(rowSum[i] <= colSum[j]):\n\t\t\t\tans[i][j] = rowSum[i]\n\t\t\t\tcolSum[j] -= rowSum[i]...
1
You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column...
If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.
50% TC and 67% SC easy python solution
find-valid-matrix-given-row-and-column-sums
0
1
```\ndef restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:\n\tr = len(rowSum)\n\tc = len(colSum)\n\tans = [[-1 for _ in range(c)] for _ in range(r)]\n\tfor i in range(r):\n\t\tfor j in range(c):\n\t\t\tif(rowSum[i] <= colSum[j]):\n\t\t\t\tans[i][j] = rowSum[i]\n\t\t\t\tcolSum[j] -= rowSum[i]...
1
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of fo...
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
[Python3] Good enough
find-valid-matrix-given-row-and-column-sums
0
1
``` Python3 []\nclass Solution:\n def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:\n matrix = [[0]*len(colSum) for _ in range(len(rowSum))]\n \n rows = []\n for i,x in enumerate(rowSum):\n heapq.heappush(rows, (x,i))\n \n cols = []...
0
You are given two arrays `rowSum` and `colSum` of non-negative integers where `rowSum[i]` is the sum of the elements in the `ith` row and `colSum[j]` is the sum of the elements of the `jth` column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column...
If we can make m or more bouquets at day x, then we can still make m or more bouquets at any day y > x. We can check easily if we can make enough bouquets at day x if we can get group adjacent flowers at day x.
[Python3] Good enough
find-valid-matrix-given-row-and-column-sums
0
1
``` Python3 []\nclass Solution:\n def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]:\n matrix = [[0]*len(colSum) for _ in range(len(rowSum))]\n \n rows = []\n for i,x in enumerate(rowSum):\n heapq.heappush(rows, (x,i))\n \n cols = []...
0
A **good meal** is a meal that contains **exactly two different food items** with a sum of deliciousness equal to a power of two. You can pick **any** two different foods to make a good meal. Given an array of integers `deliciousness` where `deliciousness[i]` is the deliciousness of the `i​​​​​​th​​​​`​​​​ item of fo...
Find the smallest rowSum or colSum, and let it be x. Place that number in the grid, and subtract x from rowSum and colSum. Continue until all the sums are satisfied.
Python3 fast solution with mathematical derivation
find-servers-that-handled-most-number-of-requests
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. -->\nwe need to sort server_id in range: [i, i+k)\nso we have:\ni <= server_id + m*k < i+k\n-> server_id + m*k = i + x where x in range[0, k)\n-> server_id % k + 0 = i % k...
2
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
Python3 fast solution with mathematical derivation
find-servers-that-handled-most-number-of-requests
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. -->\nwe need to sort server_id in range: [i, i+k)\nso we have:\ni <= server_id + m*k < i+k\n-> server_id + m*k = i + x where x in range[0, k)\n-> server_id % k + 0 = i % k...
2
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
Python, using only heaps
find-servers-that-handled-most-number-of-requests
0
1
Solution using three heaps. First heap is used to quickly free up the nodes. Then we split the servers to those that come after the `server_id` which is current server and those that come before, for loopback.\n```\ndef busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:\n\tbusy_jobs = [] #...
90
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
Python, using only heaps
find-servers-that-handled-most-number-of-requests
0
1
Solution using three heaps. First heap is used to quickly free up the nodes. Then we split the servers to those that come after the `server_id` which is current server and those that come before, for loopback.\n```\ndef busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:\n\tbusy_jobs = [] #...
90
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
Python, Two PriorityQueue back and forth O(n log k)
find-servers-that-handled-most-number-of-requests
0
1
Idea is simple:\n\nUse a priority queue `available` to keep track of the available servers. When a server get a job, remove it from `available` and put it in another PriorityQueue `busy` whose priority is given by the done time. \n\nOn the arrival each job, check if any of the jobs in `busy` are done. If so, put them b...
44
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
Python, Two PriorityQueue back and forth O(n log k)
find-servers-that-handled-most-number-of-requests
0
1
Idea is simple:\n\nUse a priority queue `available` to keep track of the available servers. When a server get a job, remove it from `available` and put it in another PriorityQueue `busy` whose priority is given by the done time. \n\nOn the arrival each job, check if any of the jobs in `busy` are done. If so, put them b...
44
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
Python - super readable solution - SortedList + Heap
find-servers-that-handled-most-number-of-requests
0
1
#### The basic approach to this question is:\n* iterate arrival and load values\n\t* Identify all available servers\n\t* Find the next available server and increase its handle count\n\t* Mark it is busy\n\n* return all servers that reached the same request handled count\n\n#### The main problem here is find an efficien...
2
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
Python - super readable solution - SortedList + Heap
find-servers-that-handled-most-number-of-requests
0
1
#### The basic approach to this question is:\n* iterate arrival and load values\n\t* Identify all available servers\n\t* Find the next available server and increase its handle count\n\t* Mark it is busy\n\n* return all servers that reached the same request handled count\n\n#### The main problem here is find an efficien...
2
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
[Python3] summarizing 3 approaches
find-servers-that-handled-most-number-of-requests
0
1
**Approach 1** - heap only \nI was completely amazed to learn this solution from @warmr0bot in this [post](https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/discuss/876883/Python-using-only-heaps). Here, the trick is to relocate a freed server to a later place by circularly adjusting its i...
16
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
[Python3] summarizing 3 approaches
find-servers-that-handled-most-number-of-requests
0
1
**Approach 1** - heap only \nI was completely amazed to learn this solution from @warmr0bot in this [post](https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/discuss/876883/Python-using-only-heaps). Here, the trick is to relocate a freed server to a later place by circularly adjusting its i...
16
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
Python3 - simulate servers using sorted list and heap
find-servers-that-handled-most-number-of-requests
0
1
```\nfrom sortedcontainers import SortedList\nfrom heapq import heappush, heappop\n\nclass Solution:\n def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:\n processed = [0]*k\n ready = SortedList(list(range(k)))\n processing = [] # (ready time, server number)\n ...
0
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
Python3 - simulate servers using sorted list and heap
find-servers-that-handled-most-number-of-requests
0
1
```\nfrom sortedcontainers import SortedList\nfrom heapq import heappush, heappop\n\nclass Solution:\n def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:\n processed = [0]*k\n ready = SortedList(list(range(k)))\n processing = [] # (ready time, server number)\n ...
0
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
Intuitive, straightforward solution with binary search tree in Python with explaination
find-servers-that-handled-most-number-of-requests
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem can be solved by using heaps with some tricky properties. The heap solution is good and smart, but less intuitive and not that easy to understand. Fortunately, this problem can also be solved in a very intuitive approach in t...
0
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
Intuitive, straightforward solution with binary search tree in Python with explaination
find-servers-that-handled-most-number-of-requests
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem can be solved by using heaps with some tricky properties. The heap solution is good and smart, but less intuitive and not that easy to understand. Fortunately, this problem can also be solved in a very intuitive approach in t...
0
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
Python3 | binary search tree solution
find-servers-that-handled-most-number-of-requests
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing Binary search Tree though it looks big logic is pretty simple for all operations\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space co...
0
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
Python3 | binary search tree solution
find-servers-that-handled-most-number-of-requests
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUsing Binary search Tree though it looks big logic is pretty simple for all operations\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space co...
0
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
Python (Simple Heap)
find-servers-that-handled-most-number-of-requests
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
Python (Simple Heap)
find-servers-that-handled-most-number-of-requests
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 assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
Python3 | Two Heap Solution | Explained and Commented
find-servers-that-handled-most-number-of-requests
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to prioritize our useage of the servers in a set range. This is similar to modular arithmetic, so we should look for a priority queue solution that can use a modular approach, like a circular priority queue. In this case, we arriv...
0
You have `k` servers numbered from `0` to `k-1` that are being used to handle multiple requests simultaneously. Each server has infinite computational capacity but **cannot handle more than one request at a time**. The requests are assigned to servers according to a specific algorithm: * The `ith` (0-indexed) reques...
null
Python3 | Two Heap Solution | Explained and Commented
find-servers-that-handled-most-number-of-requests
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to prioritize our useage of the servers in a set range. This is similar to modular arithmetic, so we should look for a priority queue solution that can use a modular approach, like a circular priority queue. In this case, we arriv...
0
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`: * `numberOfBoxesi` is the number of boxes of type `i`. * `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`. You are also given...
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to th...
Easiest solution in python.
special-array-with-x-elements-greater-than-or-equal-x
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 an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`. Notice that `x` **does not** have to be an element in `nums`. Return `x` _if the array is **special**, ...
null
Easiest solution in python.
special-array-with-x-elements-greater-than-or-equal-x
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 starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell. You are given an `m x n` character matrix, `grid`, of these different types of cells: * `'*'` is your location. There is **exactly one** `'*'` cell. * `'#'` is a food cell. There may be...
Count the number of elements greater than or equal to x for each x in the range [0, nums.length]. If for any x, the condition satisfies, return that x. Otherwise, there is no answer.
Python Brute Force 62.06% Faster
special-array-with-x-elements-greater-than-or-equal-x
0
1
```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n c=0\n for i in range(1,1001):\n c=0\n for j in nums:\n if i<=j:\n c+=1\n if i==c:\n return i\n \n return -1\n```
1
You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`. Notice that `x` **does not** have to be an element in `nums`. Return `x` _if the array is **special**, ...
null
Python Brute Force 62.06% Faster
special-array-with-x-elements-greater-than-or-equal-x
0
1
```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n c=0\n for i in range(1,1001):\n c=0\n for j in nums:\n if i<=j:\n c+=1\n if i==c:\n return i\n \n return -1\n```
1
You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell. You are given an `m x n` character matrix, `grid`, of these different types of cells: * `'*'` is your location. There is **exactly one** `'*'` cell. * `'#'` is a food cell. There may be...
Count the number of elements greater than or equal to x for each x in the range [0, nums.length]. If for any x, the condition satisfies, return that x. Otherwise, there is no answer.
Basic binary search with two pointers
special-array-with-x-elements-greater-than-or-equal-x
0
1
\n# Code\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n n = len(nums)\n l, r = 0, n\n while(l<=r):\n mid = (l+r)//2\n count = 0 \n for i in nums:\n if(i>=mid):\n count +=1\n\n if (count == mi...
1
You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`. Notice that `x` **does not** have to be an element in `nums`. Return `x` _if the array is **special**, ...
null
Basic binary search with two pointers
special-array-with-x-elements-greater-than-or-equal-x
0
1
\n# Code\n```\nclass Solution:\n def specialArray(self, nums: List[int]) -> int:\n n = len(nums)\n l, r = 0, n\n while(l<=r):\n mid = (l+r)//2\n count = 0 \n for i in nums:\n if(i>=mid):\n count +=1\n\n if (count == mi...
1
You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell. You are given an `m x n` character matrix, `grid`, of these different types of cells: * `'*'` is your location. There is **exactly one** `'*'` cell. * `'#'` is a food cell. There may be...
Count the number of elements greater than or equal to x for each x in the range [0, nums.length]. If for any x, the condition satisfies, return that x. Otherwise, there is no answer.
🐍🏋️‍♂️ The GigaChad Pythonista's Solution 🏋️‍♂️ Bitwise Blast! 💥 Explanation 🚀
even-odd-tree
0
1
# Intuition\n> "Always determine evenness using bitwise operations." - Jason Statham.\n\nBitwise operations are often overlooked, but they can offer neat solutions to certain problems. In our case, we\'re dealing with binary trees and odd/even numbers, which makes it a perfect fit for bit manipulation. Let\'s briefly d...
8
A binary tree is named **Even-Odd** if it meets the following conditions: * The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. * For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increa...
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
Python solution using breadth search first algorithm
even-odd-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn this approach we travel the tree using breadth first search algorithm. We store each node with it\'s index level in the queue. We go through the node and if this is...
1
A binary tree is named **Even-Odd** if it meets the following conditions: * The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. * For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increa...
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
Python3 Runtime:838ms 44.05% || Memory: 40.8mb 57.22% # O(n) || O(h)
even-odd-tree
0
1
I added prev = 0 because we can\'t campare with NoneType at `comparison` variable\n```\nfrom collections import deque\n# Runtime:838ms 44.05% || Memory: 40.8mb 57.22%\n# O(n) || O(h); where h is the height of the tree\n\nclass Solution:\n def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:\n if not roo...
1
A binary tree is named **Even-Odd** if it meets the following conditions: * The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. * For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increa...
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
even-odd-tree
even-odd-tree
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
A binary tree is named **Even-Odd** if it meets the following conditions: * The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. * For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increa...
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
Solution using BFS
even-odd-tree
0
1
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import deque\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0,...
0
A binary tree is named **Even-Odd** if it meets the following conditions: * The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc. * For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increa...
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
[Python / C++] 3 Simple Steps
maximum-number-of-visible-points
0
1
```html5\n<b>Time Complexity: O(n&middot;log(n))\nSpace Complexity: O(n)</b>\n```\n<iframe src="https://leetcode.com/playground/YyWmsvj7/shared" frameBorder="0" width="100%" height="750"></iframe>\n\n**Notes:**\n1. ```math.atan2(y,x)``` is used instead of ```math.atan``` because it accounts for the sign of x and y. \n...
43
You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane. Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe...
Simulate the process, create an array nums and return the Bitwise XOR of all elements of it.
[Python / C++] 3 Simple Steps
maximum-number-of-visible-points
0
1
```html5\n<b>Time Complexity: O(n&middot;log(n))\nSpace Complexity: O(n)</b>\n```\n<iframe src="https://leetcode.com/playground/YyWmsvj7/shared" frameBorder="0" width="100%" height="750"></iframe>\n\n**Notes:**\n1. ```math.atan2(y,x)``` is used instead of ```math.atan``` because it accounts for the sign of x and y. \n...
43
On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer `n`, an array `languages`, and an array `friendships` where: * There are `n` languages numbered `1` through `n`, * `languages[i]` is th...
Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, it’d be helpful to append the point list to itself after sorting.
Angle sliding window (intuition behind polar coordinates)
maximum-number-of-visible-points
0
1
# Intuition\nThe maximum number of points within the given Field Of View (FOV) is the maximum of the number of points contained in the interval window $$[\\theta, \\theta+ FOV]$$ of size $$FOV$$, which starts at angle $$x$$ and considers the angle range up to $$x+FOV$$ inclusive.\nTo attain this, every point has to be ...
5
You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane. Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe...
Simulate the process, create an array nums and return the Bitwise XOR of all elements of it.
Angle sliding window (intuition behind polar coordinates)
maximum-number-of-visible-points
0
1
# Intuition\nThe maximum number of points within the given Field Of View (FOV) is the maximum of the number of points contained in the interval window $$[\\theta, \\theta+ FOV]$$ of size $$FOV$$, which starts at angle $$x$$ and considers the angle range up to $$x+FOV$$ inclusive.\nTo attain this, every point has to be ...
5
On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer `n`, an array `languages`, and an array `friendships` where: * There are `n` languages numbered `1` through `n`, * `languages[i]` is th...
Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, it’d be helpful to append the point list to itself after sorting.
[Hashmap + Prefix sum + Sliding window] Runtime beats 99% of users with Python3
maximum-number-of-visible-points
0
1
# Intuition\n1. Use hashmap to record the same angle and number of itmes.\n2. Sort unique angles in the hashmap.\n3. Calculate the num of points from first angle to the last angle: sum_list. Then the point number between i-th angle and j-th angle will be: \n * ```if j > i: num = sum_list[j] - sum_list[i]```\n * `...
0
You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane. Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe...
Simulate the process, create an array nums and return the Bitwise XOR of all elements of it.
[Hashmap + Prefix sum + Sliding window] Runtime beats 99% of users with Python3
maximum-number-of-visible-points
0
1
# Intuition\n1. Use hashmap to record the same angle and number of itmes.\n2. Sort unique angles in the hashmap.\n3. Calculate the num of points from first angle to the last angle: sum_list. Then the point number between i-th angle and j-th angle will be: \n * ```if j > i: num = sum_list[j] - sum_list[i]```\n * `...
0
On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer `n`, an array `languages`, and an array `friendships` where: * There are `n` languages numbered `1` through `n`, * `languages[i]` is th...
Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, it’d be helpful to append the point list to itself after sorting.
1610. Maximum Number of Visible Points
maximum-number-of-visible-points
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane. Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe...
Simulate the process, create an array nums and return the Bitwise XOR of all elements of it.
1610. Maximum Number of Visible Points
maximum-number-of-visible-points
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
On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer `n`, an array `languages`, and an array `friendships` where: * There are `n` languages numbered `1` through `n`, * `languages[i]` is th...
Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, it’d be helpful to append the point list to itself after sorting.
Sliding Window on a circle
maximum-number-of-visible-points
0
1
\n# Code\n```\nclass Solution:\n def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:\n vectors = [(p1-location[0],p2-location[1]) for p1,p2 in points]\n pi = 3.141592653589793238462643383279502884197\n def myatan(a1,a2):\n if a1 > 0:\n ...
0
You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane. Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In othe...
Simulate the process, create an array nums and return the Bitwise XOR of all elements of it.
Sliding Window on a circle
maximum-number-of-visible-points
0
1
\n# Code\n```\nclass Solution:\n def visiblePoints(self, points: List[List[int]], angle: int, location: List[int]) -> int:\n vectors = [(p1-location[0],p2-location[1]) for p1,p2 in points]\n pi = 3.141592653589793238462643383279502884197\n def myatan(a1,a2):\n if a1 > 0:\n ...
0
On a social network consisting of `m` users and some friendships between users, two users can communicate with each other if they know a common language. You are given an integer `n`, an array `languages`, and an array `friendships` where: * There are `n` languages numbered `1` through `n`, * `languages[i]` is th...
Sort the points by polar angle with the original position. Now only a consecutive collection of points would be visible from any coordinate. We can use two pointers to keep track of visible points for each start point For handling the cyclic condition, it’d be helpful to append the point list to itself after sorting.
🥇 C++ | PYTHON | JAVA || EXPLAINED || ; ] ✅
minimum-one-bit-operations-to-make-integers-zero
1
1
**UPVOTE IF HELPFuuL**\n\n# Intuition\nAssume a number `1101001`\nStarting from left to right to save number of operations\n`1000000->0` takes 2^7-1 = 127 steps \n`0100000->0` takes 2^6-1 = 63 steps \n`0001000->0` takes 2^4-1 = 15 steps \n`0000001->0` takes 2^1-1 = 1 step \n\nHence Can be said\n`1 -> 0` needs `1` o...
91
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set...
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
🥇 C++ | PYTHON | JAVA || EXPLAINED || ; ] ✅
minimum-one-bit-operations-to-make-integers-zero
1
1
**UPVOTE IF HELPFuuL**\n\n# Intuition\nAssume a number `1101001`\nStarting from left to right to save number of operations\n`1000000->0` takes 2^7-1 = 127 steps \n`0100000->0` takes 2^6-1 = 63 steps \n`0001000->0` takes 2^4-1 = 15 steps \n`0000001->0` takes 2^1-1 = 1 step \n\nHence Can be said\n`1 -> 0` needs `1` o...
91
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <=...
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Python3 Solution
minimum-one-bit-operations-to-make-integers-zero
0
1
\n```\nclass Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n ans=0\n while n:\n ans=-ans-(n^(n-1))\n n&=n-1\n return abs(ans) \n```
7
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set...
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
Python3 Solution
minimum-one-bit-operations-to-make-integers-zero
0
1
\n```\nclass Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n ans=0\n while n:\n ans=-ans-(n^(n-1))\n n&=n-1\n return abs(ans) \n```
7
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <=...
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Simple Pattern Recognition + Recursion
minimum-one-bit-operations-to-make-integers-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this problem you have to observe pattern.\nThinking for this problem makes it HARD...\nbut as soon as you decode the logic, it is EASY to code.\n\nI have mentioned some testcases with the output in the code.\n\n**TIP :**\nFor every ***...
2
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set...
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
Simple Pattern Recognition + Recursion
minimum-one-bit-operations-to-make-integers-zero
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn this problem you have to observe pattern.\nThinking for this problem makes it HARD...\nbut as soon as you decode the logic, it is EASY to code.\n\nI have mentioned some testcases with the output in the code.\n\n**TIP :**\nFor every ***...
2
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <=...
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
[Python 3]Two DPs
minimum-one-bit-operations-to-make-integers-zero
0
1
For each bit, in order to convert it to zero, we should have the right bits set to `1000...` and call it R. thus it takes 1 + ones(n[1:]) + zero(R)\nwhere one is to transform the string to `1000...` and zero is to transform the string to all zeros.\n\n```\nclass Solution:\n def minimumOneBitOperations(self, n: int) ...
2
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set...
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
[Python 3]Two DPs
minimum-one-bit-operations-to-make-integers-zero
0
1
For each bit, in order to convert it to zero, we should have the right bits set to `1000...` and call it R. thus it takes 1 + ones(n[1:]) + zero(R)\nwhere one is to transform the string to `1000...` and zero is to transform the string to all zeros.\n\n```\nclass Solution:\n def minimumOneBitOperations(self, n: int) ...
2
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <=...
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Python3: Math and Dynamic Programming
minimum-one-bit-operations-to-make-integers-zero
0
1
# Intuition\n\nI found this problem to be brutal, it took me literally HOURS to come up with it. So I guess I won\'t work at Oracle where this is asked apparently.\n\nIMO this is one of the hardest problems because you have to spend a LOT of time getting the alternating moves insight, then figure out that the move sequ...
1
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set...
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
Python3: Math and Dynamic Programming
minimum-one-bit-operations-to-make-integers-zero
0
1
# Intuition\n\nI found this problem to be brutal, it took me literally HOURS to come up with it. So I guess I won\'t work at Oracle where this is asked apparently.\n\nIMO this is one of the hardest problems because you have to spend a LOT of time getting the alternating moves insight, then figure out that the move sequ...
1
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <=...
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
A step-by-step understandable (but longer) solution
minimum-one-bit-operations-to-make-integers-zero
0
1
# Intuition\nThe intuition is to break the whole conversion process into four core operations (AnyToZero, AnyToPower, PowerToZero, and ZeroToPower) based on the two given basic operations.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nFor example, if we want to convert any n-bit string ?????...
1
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set...
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
A step-by-step understandable (but longer) solution
minimum-one-bit-operations-to-make-integers-zero
0
1
# Intuition\nThe intuition is to break the whole conversion process into four core operations (AnyToZero, AnyToPower, PowerToZero, and ZeroToPower) based on the two given basic operations.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nFor example, if we want to convert any n-bit string ?????...
1
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <=...
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
[We💕Simple] One Liner! - Explanations.
minimum-one-bit-operations-to-make-integers-zero
0
1
```Kotlin []\nclass Solution {\n fun minimumOneBitOperations(n: Int): Int =\n if (n != 0) n.takeHighestOneBit() * 2 - 1 - minimumOneBitOperations(n - n.takeHighestOneBit()) else 0\n}\n```\n```Python []\nclass Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n return 2**n.bit_length()-1 ...
1
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set...
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
[We💕Simple] One Liner! - Explanations.
minimum-one-bit-operations-to-make-integers-zero
0
1
```Kotlin []\nclass Solution {\n fun minimumOneBitOperations(n: Int): Int =\n if (n != 0) n.takeHighestOneBit() * 2 - 1 - minimumOneBitOperations(n - n.takeHighestOneBit()) else 0\n}\n```\n```Python []\nclass Solution:\n def minimumOneBitOperations(self, n: int) -> int:\n return 2**n.bit_length()-1 ...
1
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <=...
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
A very simple solution. O(n) Time, O(1) Space
maximum-nesting-depth-of-the-parentheses
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere isnt any need to use stack to solve this. You just need to observe that the deepest VPS has the highest consecutive opening brackets. So the max value that V(variable defined in my code) takes, is our answer.\n\n\n# Complexity\n- Ti...
0
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following: * It is an empty string `" "`, or a single character not equal to `"( "` or `") "`, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or * It can be written as `(A)`, where `A` i...
null
A very simple solution. O(n) Time, O(1) Space
maximum-nesting-depth-of-the-parentheses
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere isnt any need to use stack to solve this. You just need to observe that the deepest VPS has the highest consecutive opening brackets. So the max value that V(variable defined in my code) takes, is our answer.\n\n\n# Complexity\n- Ti...
0
You are given two strings `a` and `b` that consist of lowercase letters. In one operation, you can change any character in `a` or `b` to **any lowercase letter**. Your goal is to satisfy **one** of the following three conditions: * **Every** letter in `a` is **strictly less** than **every** letter in `b` in the alp...
The depth of any character in the VPS is the ( number of left brackets before it ) - ( number of right brackets before it )
Simple stack solution
maximum-nesting-depth-of-the-parentheses
0
1
\n# Code\n```\nclass Solution:\n def maxDepth(self, s: str) -> int:\n stack = []\n maxi = 0\n for char in s:\n if char == \'(\':\n stack.append(char)\n if len(stack) > maxi:\n maxi = len(stack)\n elif char == \')\':\n ...
1
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following: * It is an empty string `" "`, or a single character not equal to `"( "` or `") "`, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or * It can be written as `(A)`, where `A` i...
null
Simple stack solution
maximum-nesting-depth-of-the-parentheses
0
1
\n# Code\n```\nclass Solution:\n def maxDepth(self, s: str) -> int:\n stack = []\n maxi = 0\n for char in s:\n if char == \'(\':\n stack.append(char)\n if len(stack) > maxi:\n maxi = len(stack)\n elif char == \')\':\n ...
1
You are given two strings `a` and `b` that consist of lowercase letters. In one operation, you can change any character in `a` or `b` to **any lowercase letter**. Your goal is to satisfy **one** of the following three conditions: * **Every** letter in `a` is **strictly less** than **every** letter in `b` in the alp...
The depth of any character in the VPS is the ( number of left brackets before it ) - ( number of right brackets before it )
C++/Python adjacent Matrix and degree array->O(V+E)
maximal-network-rank
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith the hint "The network rank of two vertices is almost the sum of their degrees", it is a little bit clearer. But\n"almost" means that is not exactly, so what is the exception?\n\n1.The edge that connecting these both vertices.\n2.It c...
6
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either...
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
C++/Python adjacent Matrix and degree array->O(V+E)
maximal-network-rank
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith the hint "The network rank of two vertices is almost the sum of their degrees", it is a little bit clearer. But\n"almost" means that is not exactly, so what is the exception?\n\n1.The edge that connecting these both vertices.\n2.It c...
6
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`. The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**. Find the `kth` largest value **(1-indexed)** of all th...
Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?
Python3 Solution
maximal-network-rank
0
1
\n```\nclass Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n g=[[False]*n for _ in range(n)]\n for x,y in roads:\n g[x][y]=g[y][x]=True\n\n ans=0\n for i in range(n):\n for j in range(n):\n if i==j:\n ...
3
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either...
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
Python3 Solution
maximal-network-rank
0
1
\n```\nclass Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n g=[[False]*n for _ in range(n)]\n for x,y in roads:\n g[x][y]=g[y][x]=True\n\n ans=0\n for i in range(n):\n for j in range(n):\n if i==j:\n ...
3
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`. The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**. Find the `kth` largest value **(1-indexed)** of all th...
Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?
Python Elegant & Short | Vertex Degrees
maximal-network-rank
0
1
# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n^2)$$\n\n# Code\n```\nclass Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n graph = defaultdict(set)\n\n for u, v in roads:\n graph[u].add(v)\n graph[v].add(u)\n\n retur...
2
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either...
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
Python Elegant & Short | Vertex Degrees
maximal-network-rank
0
1
# Complexity\n- Time complexity: $$O(n^2)$$\n- Space complexity: $$O(n^2)$$\n\n# Code\n```\nclass Solution:\n def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:\n graph = defaultdict(set)\n\n for u, v in roads:\n graph[u].add(v)\n graph[v].add(u)\n\n retur...
2
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`. The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**. Find the `kth` largest value **(1-indexed)** of all th...
Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?
Optimized Solution | C++, Java, Python | With Explanation
maximal-network-rank
1
1
# Intuition\nCounting degree for all cities and checking for all possible pairs of cities also gives us a AC but do we really need to check for all pairs of cities?\n\n# Approach\nThere are just 2 cases to consider here.\n\n##### **Case 1: Multiple Cities with Max Degree:**\nIf all of maxDegree cities are directly conn...
6
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either...
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
Optimized Solution | C++, Java, Python | With Explanation
maximal-network-rank
1
1
# Intuition\nCounting degree for all cities and checking for all possible pairs of cities also gives us a AC but do we really need to check for all pairs of cities?\n\n# Approach\nThere are just 2 cases to consider here.\n\n##### **Case 1: Multiple Cities with Max Degree:**\nIf all of maxDegree cities are directly conn...
6
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`. The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**. Find the `kth` largest value **(1-indexed)** of all th...
Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?
✅ 100% 2-Approaches - O(n+r) & O(n^2) - Iterative Pairwise Comparison & Direct Connection Check
maximal-network-rank
1
1
# Problem Understanding\n\nIn the "Maximal Network Rank" problem, we are given an integer `n` representing the number of cities and a list of roads connecting these cities. Each road connects two distinct cities and is bidirectional. The task is to compute the maximal network rank of the infrastructure, which is defin...
82
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either...
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
✅ 100% 2-Approaches - O(n+r) & O(n^2) - Iterative Pairwise Comparison & Direct Connection Check
maximal-network-rank
1
1
# Problem Understanding\n\nIn the "Maximal Network Rank" problem, we are given an integer `n` representing the number of cities and a list of roads connecting these cities. Each road connects two distinct cities and is bidirectional. The task is to compute the maximal network rank of the infrastructure, which is defin...
82
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`. The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**. Find the `kth` largest value **(1-indexed)** of all th...
Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?
Python 85%
maximal-network-rank
0
1
# Code\n```\nclass Solution:\n def maximalNetworkRank(self, n: int, A: List[List[int]]) -> int:\n\n # Create connection dict and store edges in "edgesSet"\n conn = defaultdict(list)\n edgesSet = set()\n for a, b in A:\n conn[a] += [b]\n conn[b] += [a]\n ed...
1
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either...
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
Python 85%
maximal-network-rank
0
1
# Code\n```\nclass Solution:\n def maximalNetworkRank(self, n: int, A: List[List[int]]) -> int:\n\n # Create connection dict and store edges in "edgesSet"\n conn = defaultdict(list)\n edgesSet = set()\n for a, b in A:\n conn[a] += [b]\n conn[b] += [a]\n ed...
1
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`. The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**. Find the `kth` largest value **(1-indexed)** of all th...
Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?