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
Solution
shifting-letters
1
1
```C++ []\nclass Solution {\npublic:\n Solution() {\n ios::sync_with_stdio(false); \n cin.tie(nullptr);\n cout.tie(nullptr);\n }\n string shiftingLetters(string s, vector<int>& shifts) {\n long long ps=0;\n for(int i=s.length()-1;i>=0;i--){\n ps+=shifts[i];\n ...
3
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shif...
null
Solution
shifting-letters
1
1
```C++ []\nclass Solution {\npublic:\n Solution() {\n ios::sync_with_stdio(false); \n cin.tie(nullptr);\n cout.tie(nullptr);\n }\n string shiftingLetters(string s, vector<int>& shifts) {\n long long ps=0;\n for(int i=s.length()-1;i>=0;i--){\n ps+=shifts[i];\n ...
3
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = ...
null
One Line Beats 96% Python
shifting-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust use a reverse previx sum, add the offset, and mod the letter position.\n\n# Code\n```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n return (lambda offsets : "".join([chr(ord(\'a\') + (off...
1
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shif...
null
One Line Beats 96% Python
shifting-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust use a reverse previx sum, add the offset, and mod the letter position.\n\n# Code\n```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n return (lambda offsets : "".join([chr(ord(\'a\') + (off...
1
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = ...
null
80% Tc and 66% Sc easy python solution
shifting-letters
0
1
```\ndef shiftingLetters(self, s: str, shifts: List[int]) -> str:\n\tcurr = 0\n\tans = [i for i in shifts]\n\tfor i in range(len(s)-1, -1, -1):\n\t\tcurr = (curr + shifts[i]) % 26\n\t\tans[i] = chr(97 + (ord(s[i])-97 + curr)%26)\n\treturn "".join(ans)\n```
1
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shif...
null
80% Tc and 66% Sc easy python solution
shifting-letters
0
1
```\ndef shiftingLetters(self, s: str, shifts: List[int]) -> str:\n\tcurr = 0\n\tans = [i for i in shifts]\n\tfor i in range(len(s)-1, -1, -1):\n\t\tcurr = (curr + shifts[i]) % 26\n\t\tans[i] = chr(97 + (ord(s[i])-97 + curr)%26)\n\treturn "".join(ans)\n```
1
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = ...
null
Python Simple Logic
shifting-letters
0
1
# Intuition\nThink of no.of letters in English.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIf the limit exceeds 25 then take the remainder.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g....
1
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shif...
null
Python Simple Logic
shifting-letters
0
1
# Intuition\nThink of no.of letters in English.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nIf the limit exceeds 25 then take the remainder.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g....
1
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = ...
null
Beats 99% Python Beginner Friendly
shifting-letters
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shif...
null
Beats 99% Python Beginner Friendly
shifting-letters
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 positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = ...
null
python: easy to understand, 3 situations
maximize-distance-to-closest-person
0
1
\n\n# Code\n```\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n #initialization, starting index is 0, result is res\n left,res,index = -1,0,0\n while index != len(seats):\n # only right is 1\n if left == -1 and seats[index] == 1:\n r...
2
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance b...
null
python: easy to understand, 3 situations
maximize-distance-to-closest-person
0
1
\n\n# Code\n```\nclass Solution:\n def maxDistToClosest(self, seats: List[int]) -> int:\n #initialization, starting index is 0, result is res\n left,res,index = -1,0,0\n while index != len(seats):\n # only right is 1\n if left == -1 and seats[index] == 1:\n r...
2
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these cr...
null
[Python 3] - Greedy easy to understand
maximize-distance-to-closest-person
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here...
3
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance b...
null
[Python 3] - Greedy easy to understand
maximize-distance-to-closest-person
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here...
3
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these cr...
null
[Python 3] Two pointers + visualisation || beats 99.8% || 112ms 🥷🏼
maximize-distance-to-closest-person
0
1
The main idea it\'s to save last busy seat, and when we meet a next busy seat, then distance will be `(current - previous)//2` => `(4 - 0) // 2` it\'s works either for even or odd distance between seats.\n![Screenshot 2023-08-01 at 01.32.37.png](https://assets.leetcode.com/users/images/2295e8ae-b7c0-4c55-8e2a-cc8258ecd...
7
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance b...
null
[Python 3] Two pointers + visualisation || beats 99.8% || 112ms 🥷🏼
maximize-distance-to-closest-person
0
1
The main idea it\'s to save last busy seat, and when we meet a next busy seat, then distance will be `(current - previous)//2` => `(4 - 0) // 2` it\'s works either for even or odd distance between seats.\n![Screenshot 2023-08-01 at 01.32.37.png](https://assets.leetcode.com/users/images/2295e8ae-b7c0-4c55-8e2a-cc8258ecd...
7
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these cr...
null
✔️ [Python3] 5 LINES ( ˘ ³˘)ノ°゚º❍。, Explained
maximize-distance-to-closest-person
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThis problem is easy to solve, if notice that the max distance to the closest person can be calculated as numbers of empty spaces devided by two and rounded to ceil: `ceil(dist/2)`. For example: `[1, 0, 0, 0, 1]` => ...
23
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance b...
null
✔️ [Python3] 5 LINES ( ˘ ³˘)ノ°゚º❍。, Explained
maximize-distance-to-closest-person
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThis problem is easy to solve, if notice that the max distance to the closest person can be calculated as numbers of empty spaces devided by two and rounded to ceil: `ceil(dist/2)`. For example: `[1, 0, 0, 0, 1]` => ...
23
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these cr...
null
maxDistToClosest
maximize-distance-to-closest-person
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance b...
null
maxDistToClosest
maximize-distance-to-closest-person
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
There is a group of `n` members, and a list of various crimes they could commit. The `ith` crime generates a `profit[i]` and requires `group[i]` members to participate in it. If a member participates in one crime, that member can't participate in another crime. Let's call a **profitable scheme** any subset of these cr...
null
Solution
rectangle-area-ii
1
1
```C++ []\nclass Solution {\npublic:\n #define ll long long\n ll MOD=1e9+7;\n static bool cmp(vector<int>&v1,vector<int>&v2){\n if(v1[0]==v2[0]){\n return v1[2]<v2[2];\n }\n return v1[0]<v2[0];\n }\n int rectangleArea(vector<vector<int>>& rectangles) {\n ll n=rectan...
3
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**. Calculate the **total area** covered by all `rectangles` ...
null
Solution
rectangle-area-ii
1
1
```C++ []\nclass Solution {\npublic:\n #define ll long long\n ll MOD=1e9+7;\n static bool cmp(vector<int>&v1,vector<int>&v2){\n if(v1[0]==v2[0]){\n return v1[2]<v2[2];\n }\n return v1[0]<v2[0];\n }\n int rectangleArea(vector<vector<int>>& rectangles) {\n ll n=rectan...
3
You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: * If the character read is a letter, that letter is written onto the tape. * If the character read is a digit `d`, the entire current tape is repeatedly written...
null
Grid
rectangle-area-ii
0
1
# Intuition\nSeperate x into grids based on distinct values of x1 and x2. For each grid, calculate the vertical area in that grid. Sum up areas from all grids.\n\n# Code\n```\nclass Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n area = 0\n rectangles.sort(key=lambda x: x[1])...
0
You are given a 2D array of axis-aligned `rectangles`. Each `rectangle[i] = [xi1, yi1, xi2, yi2]` denotes the `ith` rectangle where `(xi1, yi1)` are the coordinates of the **bottom-left corner**, and `(xi2, yi2)` are the coordinates of the **top-right corner**. Calculate the **total area** covered by all `rectangles` ...
null
Grid
rectangle-area-ii
0
1
# Intuition\nSeperate x into grids based on distinct values of x1 and x2. For each grid, calculate the vertical area in that grid. Sum up areas from all grids.\n\n# Code\n```\nclass Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n area = 0\n rectangles.sort(key=lambda x: x[1])...
0
You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken: * If the character read is a letter, that letter is written onto the tape. * If the character read is a digit `d`, the entire current tape is repeatedly written...
null
Python 3 || 8 lines, cached dfs || T/M: 74% / 44%
loud-and-rich
0
1
```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n \n n = len(quiet)\n g, f = defaultdict(list), lambda x: list(map(dfs,x)) \n for u, v in richer: g[v].append(u)\n\n @lru_cache(2000)\n def dfs(node):\n return mi...
3
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of th...
null
Python 3 || 8 lines, cached dfs || T/M: 74% / 44%
loud-and-rich
0
1
```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n \n n = len(quiet)\n g, f = defaultdict(list), lambda x: list(map(dfs,x)) \n for u, v in richer: g[v].append(u)\n\n @lru_cache(2000)\n def dfs(node):\n return mi...
3
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum n...
null
FASTEST PYTHON SOLUTION
loud-and-rich
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+LENGTH OF RICHER)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(N*LENGTH OF RICHER)$$\n<!...
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of th...
null
FASTEST PYTHON SOLUTION
loud-and-rich
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+LENGTH OF RICHER)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(N*LENGTH OF RICHER)$$\n<!...
1
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum n...
null
SIMPLE PYTHON SOLUTION
loud-and-rich
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+length of richer)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N*length of richer)$$\n<...
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of th...
null
SIMPLE PYTHON SOLUTION
loud-and-rich
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+length of richer)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N*length of richer)$$\n<...
1
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum n...
null
Beginner-friendly, Readable Python, Black-boxes, Topological Sort
loud-and-rich
0
1
# Intuition\nFind the topological sort order, then iterate through the nodes in the the topological sort order, keeping track of every node\'s minimum value/node compared to its most recent predecessors.\n\nThe topological sort allows us to use a dynamic programming technique of using previously calculated results to f...
1
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of th...
null
Beginner-friendly, Readable Python, Black-boxes, Topological Sort
loud-and-rich
0
1
# Intuition\nFind the topological sort order, then iterate through the nodes in the the topological sort order, keeping track of every node\'s minimum value/node compared to its most recent predecessors.\n\nThe topological sort allows us to use a dynamic programming technique of using previously calculated results to f...
1
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum n...
null
Solution
loud-and-rich
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {\n int n = quiet.size();\n vector<int> indg(n,0), ans(n,INT_MAX);\n vector<vector<int>> g(n);\n queue<int> q;\n for(int i=0;i<richer.size();i++){\n g[richer[i...
2
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of th...
null
Solution
loud-and-rich
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {\n int n = quiet.size();\n vector<int> indg(n,0), ans(n,INT_MAX);\n vector<vector<int>> g(n);\n queue<int> q;\n for(int i=0;i<richer.size();i++){\n g[richer[i...
2
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum n...
null
[PYTHON 3] DFS | Recursive Solution
loud-and-rich
0
1
```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n @lru_cache(None)\n def dfs(node):\n if node not in graph:\n return node\n minimum = node\n for neighbour in graph[node]:\n candidate = d...
6
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of th...
null
[PYTHON 3] DFS | Recursive Solution
loud-and-rich
0
1
```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n @lru_cache(None)\n def dfs(node):\n if node not in graph:\n return node\n minimum = node\n for neighbour in graph[node]:\n candidate = d...
6
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum n...
null
Python3 Solution
loud-and-rich
0
1
# Time Complexity:\n\nO(k * n) where n is the number of nodes and k is the number of nodes with zero in-degree where k will be less than n. \n\n# Code\n```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n graph = collections.defaultdict(list)\n n = len...
0
There is a group of `n` people labeled from `0` to `n - 1` where each person has a different amount of money and a different level of quietness. You are given an array `richer` where `richer[i] = [ai, bi]` indicates that `ai` has more money than `bi` and an integer array `quiet` where `quiet[i]` is the quietness of th...
null
Python3 Solution
loud-and-rich
0
1
# Time Complexity:\n\nO(k * n) where n is the number of nodes and k is the number of nodes with zero in-degree where k will be less than n. \n\n# Code\n```\nclass Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n graph = collections.defaultdict(list)\n n = len...
0
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum n...
null
Python Easy Solution || Binary Search || 1 Liner
peak-index-in-a-mountain-array
0
1
***Using In-built Functions:***\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n return arr.index(max(arr))\n```\n\n***By Binary Search:***\n# Code\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n left,right=0,len(arr)-1\n ...
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` su...
null
Python Easy Solution || Binary Search || 1 Liner
peak-index-in-a-mountain-array
0
1
***Using In-built Functions:***\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n return arr.index(max(arr))\n```\n\n***By Binary Search:***\n# Code\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n left,right=0,len(arr)-1\n ...
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indic...
null
Easy
peak-index-in-a-mountain-array
0
1
\n\n# Code\n```\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n """\n :type arr: List[int]\n :rtype: int\n """\n return max(range(len(arr)), key=arr.__getitem__)\n```
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` su...
null
Easy
peak-index-in-a-mountain-array
0
1
\n\n# Code\n```\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n """\n :type arr: List[int]\n :rtype: int\n """\n return max(range(len(arr)), key=arr.__getitem__)\n```
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indic...
null
Python Binary Search beats 92%
peak-index-in-a-mountain-array
0
1
\n# Code\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n left = 0\n right = len(arr) - 1\n while left <= right:\n mid = (left + right) // 2\n if mid == 0:\n return mid + 1\n if mid == len(arr) - 1:\n ...
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` su...
null
Python Binary Search beats 92%
peak-index-in-a-mountain-array
0
1
\n# Code\n```\nclass Solution:\n def peakIndexInMountainArray(self, arr: List[int]) -> int:\n left = 0\n right = len(arr) - 1\n while left <= right:\n mid = (left + right) // 2\n if mid == 0:\n return mid + 1\n if mid == len(arr) - 1:\n ...
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indic...
null
Python short and clean. BinarySearch.
peak-index-in-a-mountain-array
0
1
# Approach\nTL;DR, Similar to [Editorial solution. Approach 2](https://leetcode.com/problems/peak-index-in-a-mountain-array/editorial/) but shorter.\n\n# Complexity\n- Time complexity: $$O(log_2(n))$$\n\n- Space complexity: $$O(1)$$\n\nwhere, `n is length of arr`.\n\n# Code\n```python\nclass Solution:\n def peakInde...
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` su...
null
Python short and clean. BinarySearch.
peak-index-in-a-mountain-array
0
1
# Approach\nTL;DR, Similar to [Editorial solution. Approach 2](https://leetcode.com/problems/peak-index-in-a-mountain-array/editorial/) but shorter.\n\n# Complexity\n- Time complexity: $$O(log_2(n))$$\n\n- Space complexity: $$O(1)$$\n\nwhere, `n is length of arr`.\n\n# Code\n```python\nclass Solution:\n def peakInde...
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indic...
null
Python | Easy to Understand | Medium Problem | 852. Peak Index in a Mountain Array
peak-index-in-a-mountain-array
0
1
# Python | Easy to Understand | Medium Problem | 852. Peak Index in a Mountain Array\n```\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n """\n :type arr: List[int]\n :rtype: int\n """\n for i in range(len(arr)-1):\n if arr[i] < arr[i+1]:\n ...
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` su...
null
Python | Easy to Understand | Medium Problem | 852. Peak Index in a Mountain Array
peak-index-in-a-mountain-array
0
1
# Python | Easy to Understand | Medium Problem | 852. Peak Index in a Mountain Array\n```\nclass Solution(object):\n def peakIndexInMountainArray(self, arr):\n """\n :type arr: List[int]\n :rtype: int\n """\n for i in range(len(arr)-1):\n if arr[i] < arr[i+1]:\n ...
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indic...
null
Python Simple Binary Search
peak-index-in-a-mountain-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary search on the "lower boundary of $A[i] > A[i+1]$" instead of $A[i-1] < A[i] > A[i+1]$.\n\n# Complexity\n- Time complexity: $$O(logN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add...
1
An array `arr` a **mountain** if the following properties hold: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given a mountain array `arr`, return the index `i` su...
null
Python Simple Binary Search
peak-index-in-a-mountain-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBinary search on the "lower boundary of $A[i] > A[i+1]$" instead of $A[i-1] < A[i] > A[i+1]$.\n\n# Complexity\n- Time complexity: $$O(logN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add...
1
You are given an undirected graph (the **"original graph "**) with `n` nodes labeled from `0` to `n - 1`. You decide to **subdivide** each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indic...
null
Easy Python solution (detailed explanation) | O(nlogn)
car-fleet
0
1
# Intuition\nThe problem requires finding the number of car fleets that will reach a given target position. Initially, one might consider calculating the time each car takes to reach the target and then group cars into fleets based on their arrival times.\n\n# Approach\nThe approach is to create pairs of positions and ...
11
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can n...
null
Easy Python solution (detailed explanation) | O(nlogn)
car-fleet
0
1
# Intuition\nThe problem requires finding the number of car fleets that will reach a given target position. Initially, one might consider calculating the time each car takes to reach the target and then group cars into fleets based on their arrival times.\n\n# Approach\nThe approach is to create pairs of positions and ...
11
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is ...
null
Python3 Simple Solution | 95% | stacks | Easy And Elegant With Explanation
car-fleet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- To form a car fleet, cars must be at the same target position at some point in the future.\n- Sort the cars based on their starting positions in descending order.\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the proble...
3
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can n...
null
Python3 Simple Solution | 95% | stacks | Easy And Elegant With Explanation
car-fleet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- To form a car fleet, cars must be at the same target position at some point in the future.\n- Sort the cars based on their starting positions in descending order.\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the proble...
3
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is ...
null
Stack Solution | O(nlogn) | Python3
car-fleet
0
1
# Intuition\nWhen first approaching the car fleet problem, the key is to recognize that cars form fleets when a faster car catches up to a slower one. Since cars cannot overtake each other, once they form a fleet, they stay together until the destination. The primary challenge lies in determining these fleet formations...
1
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can n...
null
Stack Solution | O(nlogn) | Python3
car-fleet
0
1
# Intuition\nWhen first approaching the car fleet problem, the key is to recognize that cars form fleets when a faster car catches up to a slower one. Since cars cannot overtake each other, once they form a fleet, they stay together until the destination. The primary challenge lies in determining these fleet formations...
1
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is ...
null
Gk's python soln
car-fleet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith speed, distance can get time to reach target. Time is always a monotonic value -> increasing or decreasing\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMonotonic stack\n# Complexity\n- Time complexity:\n<!-...
1
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can n...
null
Gk's python soln
car-fleet
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith speed, distance can get time to reach target. Time is always a monotonic value -> increasing or decreasing\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMonotonic stack\n# Complexity\n- Time complexity:\n<!-...
1
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is ...
null
🔥BEATS 100% | [ Python / Java / C++ / JavaScript / C#/ Go/TypeScript ]
car-fleet
1
1
```Python []\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n n = len(speed)\n v = [(position[i], speed[i]) for i in range(n)]\n v.sort()\n time = [float(target - v[i][0]) / v[i][1] for i in range(n)]\n\n curr = float(\'-inf\')\n ...
3
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can n...
null
🔥BEATS 100% | [ Python / Java / C++ / JavaScript / C#/ Go/TypeScript ]
car-fleet
1
1
```Python []\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n n = len(speed)\n v = [(position[i], speed[i]) for i in range(n)]\n v.sort()\n time = [float(target - v[i][0]) / v[i][1] for i in range(n)]\n\n curr = float(\'-inf\')\n ...
3
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is ...
null
🚀Beats 97% Time, 98% Space: Python Solution Races to Efficiency! O(nlogn) time
car-fleet
0
1
# Intuition\nmy initial thought was to establish a connection between the cars\' positions, speeds, and the time it takes to reach the destination. This line of thinking led me to consider a sorting-based approach combined with time comparison, which ultimately aligned well with the solution provided in the code.\n\n# ...
1
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can n...
null
🚀Beats 97% Time, 98% Space: Python Solution Races to Efficiency! O(nlogn) time
car-fleet
0
1
# Intuition\nmy initial thought was to establish a connection between the cars\' positions, speeds, and the time it takes to reach the destination. This line of thinking led me to consider a sorting-based approach combined with time comparison, which ultimately aligned well with the solution provided in the code.\n\n# ...
1
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is ...
null
[Python3] Increasing stack
car-fleet
0
1
```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n """\n sort the start position.\n the car behind can only catch up no exceed.\n so if the car start late and speed is faster, it will catch up the car ahead of itself and they become a f...
23
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can n...
null
[Python3] Increasing stack
car-fleet
0
1
```\nclass Solution:\n def carFleet(self, target: int, position: List[int], speed: List[int]) -> int:\n """\n sort the start position.\n the car behind can only catch up no exceed.\n so if the car start late and speed is faster, it will catch up the car ahead of itself and they become a f...
23
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is ...
null
Solution
car-fleet
1
1
```C++ []\nclass Solution {\npublic:\n int carFleet(int target, vector<int>& position, vector<int>& speed) {\n std::ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n \n int len = position.size();\n\n vector<pair<int, double>> v(len);\n for(int i = 0; i < len; i++)\n ...
2
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can n...
null
Solution
car-fleet
1
1
```C++ []\nclass Solution {\npublic:\n int carFleet(int target, vector<int>& position, vector<int>& speed) {\n std::ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);\n \n int len = position.size();\n\n vector<pair<int, double>> v(len);\n for(int i = 0; i < len; i++)\n ...
2
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is ...
null
[Python3] greedy O(NlogN)
car-fleet
0
1
Algo \nSort the position-speed pair in reverse order. Compute the times for the cars to arrive at target. If a car located further away from target arrives at target with less time compared to cars closer to target. They will bump into a group. \n\nImplementation (156ms, 94.92%)\n```\nclass Solution:\n def carFleet(...
28
There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer array `position` and `speed`, both of length `n`, where `position[i]` is the position of the `ith` car and `speed[i]` is the speed of the `ith` car (in miles per hour). A car can n...
null
[Python3] greedy O(NlogN)
car-fleet
0
1
Algo \nSort the position-speed pair in reverse order. Compute the times for the cars to arrive at target. If a car located further away from target arrives at target with less time compared to cars closer to target. They will bump into a group. \n\nImplementation (156ms, 94.92%)\n```\nclass Solution:\n def carFleet(...
28
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is ...
null
Solution
k-similar-strings
1
1
```C++ []\nclass Solution {\npublic:\n vector<pair<int, int> > edges;\n int n, m;\n map<tuple<int, int, int>, int> memo;\n int dfs(int bitmask, int v, int start) {\n if (v == -1) {\n for (int i = 0; i < m; ++i) {\n if (!(bitmask >> i & 1)) {\n return dfs(b...
1
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
Solution
k-similar-strings
1
1
```C++ []\nclass Solution {\npublic:\n vector<pair<int, int> > edges;\n int n, m;\n map<tuple<int, int, int>, int> memo;\n int dfs(int bitmask, int v, int start) {\n if (v == -1) {\n for (int i = 0; i < m; ++i) {\n if (!(bitmask >> i & 1)) {\n return dfs(b...
1
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_....
null
Python BFS Solution (fully explained & commented)
k-similar-strings
0
1
# **Intuition**\n\nFirst, let\'s understand how the BFS works with some examples.\n\n\ts1: "aaabcbea"\n\ts2: "aaaebcba"\n\nA **swap** is when we switch two letters, s1[i] and s1[j]. Not all **swaps** are useful to us. In the above example, we don\'t want to swap s1[0] with any s1[j].\n\n**Swaps** are only useful if the...
27
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
Python BFS Solution (fully explained & commented)
k-similar-strings
0
1
# **Intuition**\n\nFirst, let\'s understand how the BFS works with some examples.\n\n\ts1: "aaabcbea"\n\ts2: "aaaebcba"\n\nA **swap** is when we switch two letters, s1[i] and s1[j]. Not all **swaps** are useful to us. In the above example, we don\'t want to swap s1[0] with any s1[j].\n\n**Swaps** are only useful if the...
27
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_....
null
three solutions of this problem, good for understanding DFS, DFS with memo and BFS
k-similar-strings
0
1
In this problem, we use string `A` as a target, all we need to do is modify string `B` from left to right to make it the same as `A`.\nHow to modify? If `A[i] != B[i]`, we try to swap `B[i]` with all `B[j]` where `i < j <= len(B) && B[j]==A[i] && B[j] != A[j]` \nNaturally, it can be solved with DFS(backtracking) or BFS...
23
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
three solutions of this problem, good for understanding DFS, DFS with memo and BFS
k-similar-strings
0
1
In this problem, we use string `A` as a target, all we need to do is modify string `B` from left to right to make it the same as `A`.\nHow to modify? If `A[i] != B[i]`, we try to swap `B[i]` with all `B[j]` where `i < j <= len(B) && B[j]==A[i] && B[j] != A[j]` \nNaturally, it can be solved with DFS(backtracking) or BFS...
23
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_....
null
[Python3] bfs
k-similar-strings
0
1
\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n ans = 0\n seen = {s1}\n queue = deque([s1])\n while queue: \n for _ in range(len(queue)): \n s = queue.popleft()\n if s == s2: return ans \n for i in range(le...
3
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
[Python3] bfs
k-similar-strings
0
1
\n```\nclass Solution:\n def kSimilarity(self, s1: str, s2: str) -> int:\n ans = 0\n seen = {s1}\n queue = deque([s1])\n while queue: \n for _ in range(len(queue)): \n s = queue.popleft()\n if s == s2: return ans \n for i in range(le...
3
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_....
null
Simple python recursion
k-similar-strings
0
1
# Intuition\nWe want to get the minimum by trying every swap combination. There\'s lot of BFS solutions out there, but it flew past my head. \n\n# Approach\nUse recursion and get the min from all the combinations. Use a cache of solved combinations because python so slow. Not the fastest or memory efficient, but it pas...
0
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
Simple python recursion
k-similar-strings
0
1
# Intuition\nWe want to get the minimum by trying every swap combination. There\'s lot of BFS solutions out there, but it flew past my head. \n\n# Approach\nUse recursion and get the min from all the combinations. Use a cache of solved combinations because python so slow. Not the fastest or memory efficient, but it pas...
0
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_....
null
Python Greedy Solution: Beats 99%
k-similar-strings
0
1
# Intuition\n\nThis is the solution I came up with. It works by finding the fewest swaps needed to get all elements involved in the swaps into place.\n\nFor example, if you had the strings "ababcd" and "badabc", it would take these steps:\n\n1. Swap the first 2 elements to get "ababcd" and "abdabc" with 1 swap.\n2. No ...
0
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
Python Greedy Solution: Beats 99%
k-similar-strings
0
1
# Intuition\n\nThis is the solution I came up with. It works by finding the fewest swaps needed to get all elements involved in the swaps into place.\n\nFor example, if you had the strings "ababcd" and "badabc", it would take these steps:\n\n1. Swap the first 2 elements to get "ababcd" and "abdabc" with 1 swap.\n2. No ...
0
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_....
null
BFS Approach (Python)
k-similar-strings
0
1
# Intuition\nWhen you have two strings s1 and s2, and if at position i, s1[i] != s2[i], then you ideally want to find some position j (where j > i) such that s2[j] == s1[i]. Swapping these positions could help both positions (or at least one) to match the respective characters in s1. \n\n# Approach\nBFS\n\n# Complexity...
0
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
BFS Approach (Python)
k-similar-strings
0
1
# Intuition\nWhen you have two strings s1 and s2, and if at position i, s1[i] != s2[i], then you ideally want to find some position j (where j > i) such that s2[j] == s1[i]. Swapping these positions could help both positions (or at least one) to match the respective characters in s1. \n\n# Approach\nBFS\n\n# Complexity...
0
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_....
null
[Python] BFS with pruning
k-similar-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nTo find the smallest k, we can model the problem as finding the shortest path in a graph where nodes `u` and `v` have an undirected edge if `v` can be constructed by swapping two characters in `u`. Naively, each node `u` could have up t...
0
Strings `s1` and `s2` are `k`**\-similar** (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`**\-similar**. **Example 1:** **Input...
null
[Python] BFS with pruning
k-similar-strings
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nTo find the smallest k, we can model the problem as finding the shortest path in a graph where nodes `u` and `v` have an undirected edge if `v` can be constructed by swapping two characters in `u`. Naively, each node `u` could have up t...
0
A **sentence** is a string of single-space separated words where each word consists only of lowercase letters. A word is **uncommon** if it appears exactly once in one of the sentences, and **does not appear** in the other sentence. Given two **sentences** `s1` and `s2`, return _a list of all the **uncommon words**_....
null
Python 3 || w/ comments || T/M 40% / 89%
exam-room
0
1
```\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n, self.room = n, []\n\n\n def seat(self) -> int:\n if not self.room: ans = 0 # sit at 0 if empty room \n\n else:\n dist, prev, ans = self.room[0], self.room[0], 0 # set best between door and firs...
3
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits a...
null
Python 3 || w/ comments || T/M 40% / 89%
exam-room
0
1
```\nclass ExamRoom:\n\n def __init__(self, n: int):\n self.n, self.room = n, []\n\n\n def seat(self) -> int:\n if not self.room: ans = 0 # sit at 0 if empty room \n\n else:\n dist, prev, ans = self.room[0], self.room[0], 0 # set best between door and firs...
3
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's bo...
null
Solution
exam-room
1
1
```C++ []\nclass ExamRoom {\npublic:\n\tstruct gap_t {\n\t\tint get_best_seat(int n) const {\n\t\t\tif (start == 0) {\n\t\t\t\treturn 0;\n\t\t\t} if (start + size == n) {\n\t\t\t\treturn n - 1;\n\t\t\t} return start + size / 2 - (size % 2 ^ 1);\n\t\t}\n\t\tint max_seat_dist(int n) const {\n\t\t\tif (start == 0) {\n\t\t...
1
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits a...
null
Solution
exam-room
1
1
```C++ []\nclass ExamRoom {\npublic:\n\tstruct gap_t {\n\t\tint get_best_seat(int n) const {\n\t\t\tif (start == 0) {\n\t\t\t\treturn 0;\n\t\t\t} if (start + size == n) {\n\t\t\t\treturn n - 1;\n\t\t\t} return start + size / 2 - (size % 2 ^ 1);\n\t\t}\n\t\tint max_seat_dist(int n) const {\n\t\t\tif (start == 0) {\n\t\t...
1
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's bo...
null
Magic SortedList 🪄
exam-room
0
1
# Complexity\n- Time complexity: $$O(log(n))$$ for one call.\n\n- Space complexity: $$O(1)$$ for one call.\n\n# Code\n```\nfrom sortedcontainers import SortedList\n\nclass ExamRoom:\n def __init__(self, n: int):\n self.n = n\n self.intervals = SortedList(key=lambda x: ((x[1]-x[0])//2, -x[0]))\n ...
0
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits a...
null
Magic SortedList 🪄
exam-room
0
1
# Complexity\n- Time complexity: $$O(log(n))$$ for one call.\n\n- Space complexity: $$O(1)$$ for one call.\n\n# Code\n```\nfrom sortedcontainers import SortedList\n\nclass ExamRoom:\n def __init__(self, n: int):\n self.n = n\n self.intervals = SortedList(key=lambda x: ((x[1]-x[0])//2, -x[0]))\n ...
0
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's bo...
null
Easiest Solution
exam-room
1
1
\n\n# Code\n```java []\nclass ExamRoom {\n int n;\n ArrayList<Integer> list = new ArrayList<>();\n public ExamRoom(int n) {\n this.n = n;\n }\n \n public int seat() {\n if (list.size() == 0){\n list.add(0);\n return 0;\n }\n int dist = Math.max(list.ge...
0
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits a...
null
Easiest Solution
exam-room
1
1
\n\n# Code\n```java []\nclass ExamRoom {\n int n;\n ArrayList<Integer> list = new ArrayList<>();\n public ExamRoom(int n) {\n this.n = n;\n }\n \n public int seat() {\n if (list.size() == 0){\n list.add(0);\n return 0;\n }\n int dist = Math.max(list.ge...
0
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's bo...
null
Possibly Easier to Understand: SortedSet, FT 50%, O(N*log(N)) total time and O(N) total space
exam-room
0
1
# Intuition\n\nThe intuition is reasonably straightforward because the problem statement gives it to us\n* we want to seat the next student as far away from others as possible\n* ase a tie-breaker, seat the student as close as possible\n\nThe intuition about how to approach the problem is HARD though - if we don\'t com...
0
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits a...
null
Possibly Easier to Understand: SortedSet, FT 50%, O(N*log(N)) total time and O(N) total space
exam-room
0
1
# Intuition\n\nThe intuition is reasonably straightforward because the problem statement gives it to us\n* we want to seat the next student as far away from others as possible\n* ase a tie-breaker, seat the student as close as possible\n\nThe intuition about how to approach the problem is HARD though - if we don\'t com...
0
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's bo...
null
python3
exam-room
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nWhen a student enters the examination room, there are three situations:\n\n1. If there is no one in the room, then the student can only sit in the seat 0\n\n2. There are more than two students in the examination room, and it is better t...
0
There is an exam room with `n` seats in a single row labeled from `0` to `n - 1`. When a student enters the room, they must sit in the seat that maximizes the distance to the closest person. If there are multiple such seats, they sit in the seat with the lowest number. If no one is in the room, then the student sits a...
null
python3
exam-room
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nWhen a student enters the examination room, there are three situations:\n\n1. If there is no one in the room, then the student can only sit in the seat 0\n\n2. There are more than two students in the examination room, and it is better t...
0
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column. You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's bo...
null
Solution
score-of-parentheses
1
1
```C++ []\nclass Solution {\npublic:\n int scoreOfParentheses(string s) {\n int ans=0;\n stack<int> st;\n for(int i=0;i<s.length();i++){\n if(s[i]==\'(\'){\n st.push(-1);\n }\n else if(st.top()==-1){\n st.pop();\n st.pus...
2
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced ...
null
Solution
score-of-parentheses
1
1
```C++ []\nclass Solution {\npublic:\n int scoreOfParentheses(string s) {\n int ans=0;\n stack<int> st;\n for(int i=0;i<s.length();i++){\n if(s[i]==\'(\'){\n st.push(-1);\n }\n else if(st.top()==-1){\n st.pop();\n st.pus...
2
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the...
null
Easy + Efficient Stack Solution - Beats 100 %
score-of-parentheses
0
1
# Intuition\n\nThe question involves calculating the score of a string consisting of balanced parentheses. The scoring rule is as follows: \n\n- `()` has a score of 1.\n- `AB` has a score of \\(A + B\\), where \\(A\\) and \\(B\\) are balanced parentheses strings.\n- `(A)` has a score of 2 * \\(A\\), where \\(A\\) is a ...
1
Given a balanced parentheses string `s`, return _the **score** of the string_. The **score** of a balanced parentheses string is based on the following rule: * `"() "` has score `1`. * `AB` has score `A + B`, where `A` and `B` are balanced parentheses strings. * `(A)` has score `2 * A`, where `A` is a balanced ...
null
Easy + Efficient Stack Solution - Beats 100 %
score-of-parentheses
0
1
# Intuition\n\nThe question involves calculating the score of a string consisting of balanced parentheses. The scoring rule is as follows: \n\n- `()` has a score of 1.\n- `AB` has a score of \\(A + B\\), where \\(A\\) and \\(B\\) are balanced parentheses strings.\n- `(A)` has a score of 2 * \\(A\\), where \\(A\\) is a ...
1
We want to split a group of `n` people (labeled from `1` to `n`) into two groups of **any size**. Each person may dislike some other people, and they should not go into the same group. Given the integer `n` and the array `dislikes` where `dislikes[i] = [ai, bi]` indicates that the person labeled `ai` does not like the...
null