title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python | faster than 83% | easy-understanding | explaining with comments
score-of-parentheses
0
1
```\nclass Solution:\n def scoreOfParentheses(self, s: str) -> int:\n stk = [0] # temp value to help us\n\n for char in s:\n if char == \'(\':\n stk.append(0) # new parent: current sum = 0\n else:\n # An expression will be closed\n ...
8
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
Python | faster than 83% | easy-understanding | explaining with comments
score-of-parentheses
0
1
```\nclass Solution:\n def scoreOfParentheses(self, s: str) -> int:\n stk = [0] # temp value to help us\n\n for char in s:\n if char == \'(\':\n stk.append(0) # new parent: current sum = 0\n else:\n # An expression will be closed\n ...
8
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
Solution
minimum-cost-to-hire-k-workers
1
1
```C++ []\nclass Solution {\npublic:\n double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int k) {\n struct Worker\n {\n int quality;\n int wage;\n Worker() : quality(0), wage(0) {}\n Worker(int q, int w) : quality(q), wage(w) {}\n ...
1
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to ...
null
Solution
minimum-cost-to-hire-k-workers
1
1
```C++ []\nclass Solution {\npublic:\n double mincostToHireWorkers(vector<int>& quality, vector<int>& wage, int k) {\n struct Worker\n {\n int quality;\n int wage;\n Worker() : quality(0), wage(0) {}\n Worker(int q, int w) : quality(q), wage(w) {}\n ...
1
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, y...
null
Here I use simple Priority heapq and sorting method which beats 100%
minimum-cost-to-hire-k-workers
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# **o**(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e....
1
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to ...
null
Here I use simple Priority heapq and sorting method which beats 100%
minimum-cost-to-hire-k-workers
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# **o**(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e....
1
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, y...
null
[Python3] | Priority Queue
minimum-cost-to-hire-k-workers
0
1
```\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n n=len(wage)\n arr=[[wage[i]/quality[i],quality[i]] for i in range(n)]\n arr.sort(key=lambda x:x[0])\n kSmallest=0\n pq=[]\n for i in range(k):\n heapq.he...
1
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to ...
null
[Python3] | Priority Queue
minimum-cost-to-hire-k-workers
0
1
```\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n n=len(wage)\n arr=[[wage[i]/quality[i],quality[i]] for i in range(n)]\n arr.sort(key=lambda x:x[0])\n kSmallest=0\n pq=[]\n for i in range(k):\n heapq.he...
1
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, y...
null
Python -- Faster than 99%, Memory < 86%
minimum-cost-to-hire-k-workers
0
1
```python\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n \n # --- Sort Workers by Ratio\n workers = [(w/q, q) for w, q in zip(wage, quality)]\n workers.sort()\n\n # --- Initialize Quality Max-Heap\n paid_group = [-1*q for r, q in wo...
1
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to ...
null
Python -- Faster than 99%, Memory < 86%
minimum-cost-to-hire-k-workers
0
1
```python\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n \n # --- Sort Workers by Ratio\n workers = [(w/q, q) for w, q in zip(wage, quality)]\n workers.sort()\n\n # --- Initialize Quality Max-Heap\n paid_group = [-1*q for r, q in wo...
1
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, y...
null
O(n log n) solution with a detailed explanation and commented code
minimum-cost-to-hire-k-workers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe first make the observation that in an optimal solution of $k$ workers there is at least one worker that gets paid exactly their minimum wage requirement.\nIf that would not be the case and all $k$ workers get paid more, we could constr...
0
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to ...
null
O(n log n) solution with a detailed explanation and commented code
minimum-cost-to-hire-k-workers
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe first make the observation that in an optimal solution of $k$ workers there is at least one worker that gets paid exactly their minimum wage requirement.\nIf that would not be the case and all $k$ workers get paid more, we could constr...
0
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, y...
null
Using heap and sorting of wage/quality | Explained
minimum-cost-to-hire-k-workers
0
1
```\nimport heapq\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n """\n This is a mind f**k problem\n Problem Statement:\n Given the quality of workers and minimum wage, we need to hire k workers using least \n amount of mo...
0
There are `n` workers. You are given two integer arrays `quality` and `wage` where `quality[i]` is the quality of the `ith` worker and `wage[i]` is the minimum wage expectation for the `ith` worker. We want to hire exactly `k` workers to form a paid group. To hire a group of `k` workers, we must pay them according to ...
null
Using heap and sorting of wage/quality | Explained
minimum-cost-to-hire-k-workers
0
1
```\nimport heapq\nclass Solution:\n def mincostToHireWorkers(self, quality: List[int], wage: List[int], k: int) -> float:\n """\n This is a mind f**k problem\n Problem Statement:\n Given the quality of workers and minimum wage, we need to hire k workers using least \n amount of mo...
0
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, y...
null
Solution
mirror-reflection
1
1
```C++ []\nclass Solution {\n public:\n int mirrorReflection(int p, int q) {\n while (p % 2 == 0 && q % 2 == 0) {\n p /= 2;\n q /= 2;\n }\n if (p % 2 == 0)\n return 2;\n if (q % 2 == 0)\n return 0;\n return 1;\n }\n};\n```\n\n```Python3 []\nimport math\n\nclass Solution:\n def mi...
1
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
Solution
mirror-reflection
1
1
```C++ []\nclass Solution {\n public:\n int mirrorReflection(int p, int q) {\n while (p % 2 == 0 && q % 2 == 0) {\n p /= 2;\n q /= 2;\n }\n if (p % 2 == 0)\n return 2;\n if (q % 2 == 0)\n return 0;\n return 1;\n }\n};\n```\n\n```Python3 []\nimport math\n\nclass Solution:\n def mi...
1
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they wo...
null
Python3 || 4 lines, geometry, w/ explanation || T/M: 92%/81%
mirror-reflection
0
1
Instead of imagining one room with mirrored walls, imagine an infinite cluster of rooms with glass walls; the light passes through to the next room and on and on until it evenually hits a corner. \n\n Suppose for example: p = 6, q = 4, which is demonstrated in the figure below.\n\t \n![image](https://assets.leetco...
78
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
Python3 || 4 lines, geometry, w/ explanation || T/M: 92%/81%
mirror-reflection
0
1
Instead of imagining one room with mirrored walls, imagine an infinite cluster of rooms with glass walls; the light passes through to the next room and on and on until it evenually hits a corner. \n\n Suppose for example: p = 6, q = 4, which is demonstrated in the figure below.\n\t \n![image](https://assets.leetco...
78
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they wo...
null
Simple O(log n) Easy to understand Solution
mirror-reflection
0
1
```\n#####################################################################################################################\n# Problem: Mirror Reflection\n# Solution : Maths\n# Time Complexity : O(log n) \n# Space Complexity : O(1)\n#######################################################################################...
4
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
Simple O(log n) Easy to understand Solution
mirror-reflection
0
1
```\n#####################################################################################################################\n# Problem: Mirror Reflection\n# Solution : Maths\n# Time Complexity : O(log n) \n# Space Complexity : O(1)\n#######################################################################################...
4
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they wo...
null
Faster than 100%πŸ˜πŸŽ† python users || Easy Python SolutionπŸ€‘ || GCD ,LCM Solution😎
mirror-reflection
0
1
\n![image](https://assets.leetcode.com/users/images/c2a4ceb6-3dfd-4092-90cc-92be1f142131_1659604263.6835797.png)\n\n\n\n![image](https://assets.leetcode.com/users/images/9c3d742c-3ca0-422f-a622-feac0c6384ed_1659606424.5373335.png)\n![image](https://assets.leetcode.com/users/images/5d0d6dc9-b429-4d52-9bde-4306957d93f4_1...
3
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from th...
null
Faster than 100%πŸ˜πŸŽ† python users || Easy Python SolutionπŸ€‘ || GCD ,LCM Solution😎
mirror-reflection
0
1
\n![image](https://assets.leetcode.com/users/images/c2a4ceb6-3dfd-4092-90cc-92be1f142131_1659604263.6835797.png)\n\n\n\n![image](https://assets.leetcode.com/users/images/9c3d742c-3ca0-422f-a622-feac0c6384ed_1659606424.5373335.png)\n![image](https://assets.leetcode.com/users/images/5d0d6dc9-b429-4d52-9bde-4306957d93f4_1...
3
Alice and Bob have a different total number of candies. You are given two integer arrays `aliceSizes` and `bobSizes` where `aliceSizes[i]` is the number of candies of the `ith` box of candy that Alice has and `bobSizes[j]` is the number of candies of the `jth` box of candy that Bob has. Since they are friends, they wo...
null
βœ…Beat's 100% || C++ || JAVA || PYTHON || Beginner FriendlyπŸ”₯πŸ”₯πŸ”₯
buddy-strings
1
1
# Intuition:\nThe Intuition is to check if it is possible to swap two characters in string `s` to make it equal to string `goal`. It first handles the case where `s` and `goal` are identical by checking for duplicate characters. If they are not identical, it looks for the first pair of mismatched characters and tries s...
206
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
βœ…Beat's 100% || C++ || JAVA || PYTHON || Beginner FriendlyπŸ”₯πŸ”₯πŸ”₯
buddy-strings
1
1
# Intuition:\nThe Intuition is to check if it is possible to swap two characters in string `s` to make it equal to string `goal`. It first handles the case where `s` and `goal` are identical by checking for duplicate characters. If they are not identical, it looks for the first pair of mismatched characters and tries s...
206
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. If there exist multiple answers, you can **return any** of them. **Example 1:**...
null
Python3 Solution
buddy-strings
0
1
\n```\nclass Solution:\n def buddyStrings(self, s: str, goal: str) -> bool:\n c1=Counter(s)\n c2=Counter(goal)\n if c1!=c2:\n return False\n\n diff=sum([1 for i in range(len(s)) if s[i]!=goal[i]])\n if diff==2:\n return True\n\n elif diff==0:\n ...
1
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
Python3 Solution
buddy-strings
0
1
\n```\nclass Solution:\n def buddyStrings(self, s: str, goal: str) -> bool:\n c1=Counter(s)\n c2=Counter(goal)\n if c1!=c2:\n return False\n\n diff=sum([1 for i in range(len(s)) if s[i]!=goal[i]])\n if diff==2:\n return True\n\n elif diff==0:\n ...
1
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. If there exist multiple answers, you can **return any** of them. **Example 1:**...
null
Easy code 100% fast | Strings |Explanation in video| C++ Java Python
buddy-strings
1
1
For detailed explanation you can refer to my youtube channel (Hindi Language)\nhttps://youtube.com/@LetsCodeTogether72?sub_confirmation=1\n or link in comment.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise expl...
30
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swappi...
null
Easy code 100% fast | Strings |Explanation in video| C++ Java Python
buddy-strings
1
1
For detailed explanation you can refer to my youtube channel (Hindi Language)\nhttps://youtube.com/@LetsCodeTogether72?sub_confirmation=1\n or link in comment.Here,you can find any solution in playlists monthwise from june 2023 with detailed explanation.i upload daily leetcode solution video with short and precise expl...
30
Given two integer arrays, `preorder` and `postorder` where `preorder` is the preorder traversal of a binary tree of **distinct** values and `postorder` is the postorder traversal of the same tree, reconstruct and return _the binary tree_. If there exist multiple answers, you can **return any** of them. **Example 1:**...
null
Python self explanatory solution
lemonade-change
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n exchange = {5:0, 10:0}\n for bill in bills:\n if bill == 5 : \n exchange[5] +=1\n eli...
1
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Python self explanatory solution
lemonade-change
0
1
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n exchange = {5:0, 10:0}\n for bill in bills:\n if bill == 5 : \n exchange[5] +=1\n eli...
1
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word....
null
Python 97.19% faster | Simplest solution with explanation | Beg to Adv | Greedy
lemonade-change
0
1
```python\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n count5 = 0 # taking counter for $5\n count10 = 0 # taking counter for $10\n for b in bills: # treversing the list of bills.\n if b == 5: \n count5+=1 # if the bill is 5, incresing the 5 c...
15
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Python 97.19% faster | Simplest solution with explanation | Beg to Adv | Greedy
lemonade-change
0
1
```python\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n count5 = 0 # taking counter for $5\n count10 = 0 # taking counter for $10\n for b in bills: # treversing the list of bills.\n if b == 5: \n count5+=1 # if the bill is 5, incresing the 5 c...
15
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word....
null
Python3
lemonade-change
0
1
\n\n# Code\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n salary = {5: 0, 10: 0}\n\n for i in bills:\n if i == 5:\n salary[5] += 1\n elif i == 10:\n if salary[5] == 0:\n return False\n s...
1
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Python3
lemonade-change
0
1
\n\n# Code\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n salary = {5: 0, 10: 0}\n\n for i in bills:\n if i == 5:\n salary[5] += 1\n elif i == 10:\n if salary[5] == 0:\n return False\n s...
1
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word....
null
Python3 O(n) || O(1) # Runtime: 1159ms 49.65% Memory: 18mb 49.96%
lemonade-change
0
1
```\nclass Solution:\n# O(n) || O(1)\n# Runtime: 1159ms 49.65% Memory: 18mb 49.96%\n def lemonadeChange(self, bills: List[int]) -> bool:\n fiveBills, tenBills = 0, 0\n\n for i in bills:\n if i == 5:\n fiveBills += 1\n elif i == 10:\n tenBills += 1...
2
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Python3 O(n) || O(1) # Runtime: 1159ms 49.65% Memory: 18mb 49.96%
lemonade-change
0
1
```\nclass Solution:\n# O(n) || O(1)\n# Runtime: 1159ms 49.65% Memory: 18mb 49.96%\n def lemonadeChange(self, bills: List[int]) -> bool:\n fiveBills, tenBills = 0, 0\n\n for i in bills:\n if i == 5:\n fiveBills += 1\n elif i == 10:\n tenBills += 1...
2
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word....
null
βœ…βœ…βœ… very easy solution. 97% on memory and 89% on time
lemonade-change
0
1
![Screenshot 2022-12-29 at 15.37.20.png](https://assets.leetcode.com/users/images/b2dbad3c-f459-4320-b752-60e7edc172a6_1672310256.9510431.png)\n\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n a, b = 0, 0\n for i in bills:\n if i==5: a+=1\n elif i==10...
2
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
βœ…βœ…βœ… very easy solution. 97% on memory and 89% on time
lemonade-change
0
1
![Screenshot 2022-12-29 at 15.37.20.png](https://assets.leetcode.com/users/images/b2dbad3c-f459-4320-b752-60e7edc172a6_1672310256.9510431.png)\n\n```\nclass Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n a, b = 0, 0\n for i in bills:\n if i==5: a+=1\n elif i==10...
2
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word....
null
Solution
lemonade-change
1
1
```C++ []\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int cnt1 = 0, cnt2 = 0;\n for(int a : bills)\n {\n if(a == 5) cnt1++;\n else if(a == 10)\n {\n if(cnt1 < 1) return false;\n cnt2++; cnt1--;\n ...
2
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Solution
lemonade-change
1
1
```C++ []\nclass Solution {\npublic:\n bool lemonadeChange(vector<int>& bills) {\n int cnt1 = 0, cnt2 = 0;\n for(int a : bills)\n {\n if(a == 5) cnt1++;\n else if(a == 10)\n {\n if(cnt1 < 1) return false;\n cnt2++; cnt1--;\n ...
2
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word....
null
Python - Beats 93%
lemonade-change
0
1
class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n \n change = {5:0, 10:0}\n\n for bill in bills:\n if bill == 5:\n change[5] += 1\n elif bill == 10:\n if change[5] > 0:\n change[5] -= 1\n ...
1
At a lemonade stand, each lemonade costs `$5`. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a `$5`, `$10`, or `$20` bill. You must provide the correct change to each customer so that the net tran...
null
Python - Beats 93%
lemonade-change
0
1
class Solution:\n def lemonadeChange(self, bills: List[int]) -> bool:\n \n change = {5:0, 10:0}\n\n for bill in bills:\n if bill == 5:\n change[5] += 1\n elif bill == 10:\n if change[5] > 0:\n change[5] -= 1\n ...
1
Given a list of strings `words` and a string `pattern`, return _a list of_ `words[i]` _that match_ `pattern`. You may return the answer in **any order**. A word matches the pattern if there exists a permutation of letters `p` so that after replacing every letter `x` in the pattern with `p(x)`, we get the desired word....
null
Solution
score-after-flipping-matrix
1
1
```C++ []\nclass Solution {\npublic:\n int matrixScore(vector<vector<int>>& grid) {\n int rows=grid.size();\n int cols=grid[0].size();\n for(int i=0;i<rows;i++){\n if(grid[i][0]==0){\n for(int j=0;j<cols;j++){\n if(grid[i][j]==0) grid[i][j]=1;\n ...
1
You are given an `m x n` binary matrix `grid`. A **move** consists of choosing any row or column and toggling each value in that row or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s). Every row of the matrix is interpreted as a binary number, and the **score** of the matrix is the sum of these num...
null
Solution
score-after-flipping-matrix
1
1
```C++ []\nclass Solution {\npublic:\n int matrixScore(vector<vector<int>>& grid) {\n int rows=grid.size();\n int cols=grid[0].size();\n for(int i=0;i<rows;i++){\n if(grid[i][0]==0){\n for(int j=0;j<cols;j++){\n if(grid[i][j]==0) grid[i][j]=1;\n ...
1
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequ...
null
Simple Approach beats 97% O(n)
score-after-flipping-matrix
0
1
# Code\n```\nclass Solution:\n def matrixScore(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n ans = [0] * n\n for r in grid:\n if r[0]:\n for i in range(n):\n ans[i] += r[i]\n else:\n for i in range(n...
2
You are given an `m x n` binary matrix `grid`. A **move** consists of choosing any row or column and toggling each value in that row or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s). Every row of the matrix is interpreted as a binary number, and the **score** of the matrix is the sum of these num...
null
Simple Approach beats 97% O(n)
score-after-flipping-matrix
0
1
# Code\n```\nclass Solution:\n def matrixScore(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n ans = [0] * n\n for r in grid:\n if r[0]:\n for i in range(n):\n ans[i] += r[i]\n else:\n for i in range(n...
2
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequ...
null
[Python3] Greedy O(MN)
score-after-flipping-matrix
0
1
**Algo** \nTwo key observations\nIf a row starts with 0, you should flip the row;\nIf a column has more 0 than 1, you shold flip the column. \n\n**Implementation**\n```\nclass Solution:\n def matrixScore(self, A: List[List[int]]) -> int:\n m, n = len(A), len(A[0])\n for i in range(m):\n if A...
16
You are given an `m x n` binary matrix `grid`. A **move** consists of choosing any row or column and toggling each value in that row or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s). Every row of the matrix is interpreted as a binary number, and the **score** of the matrix is the sum of these num...
null
[Python3] Greedy O(MN)
score-after-flipping-matrix
0
1
**Algo** \nTwo key observations\nIf a row starts with 0, you should flip the row;\nIf a column has more 0 than 1, you shold flip the column. \n\n**Implementation**\n```\nclass Solution:\n def matrixScore(self, A: List[List[int]]) -> int:\n m, n = len(A), len(A[0])\n for i in range(m):\n if A...
16
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequ...
null
[Python3] Good enough
score-after-flipping-matrix
0
1
``` Python3 []\nclass Solution:\n def matrixScore(self, grid: List[List[int]]) -> int:\n for i in range(len(grid)):\n if not grid[i][0]:\n for j in range(len(grid[i])):\n grid[i][j] = abs(grid[i][j]-1)\n \n for j in range(len(grid[0])):\n o...
0
You are given an `m x n` binary matrix `grid`. A **move** consists of choosing any row or column and toggling each value in that row or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s). Every row of the matrix is interpreted as a binary number, and the **score** of the matrix is the sum of these num...
null
[Python3] Good enough
score-after-flipping-matrix
0
1
``` Python3 []\nclass Solution:\n def matrixScore(self, grid: List[List[int]]) -> int:\n for i in range(len(grid)):\n if not grid[i][0]:\n for j in range(len(grid[i])):\n grid[i][j] = abs(grid[i][j]-1)\n \n for j in range(len(grid[0])):\n o...
0
The **width** of a sequence is the difference between the maximum and minimum elements in the sequence. Given an array of integers `nums`, return _the sum of the **widths** of all the non-empty **subsequences** of_ `nums`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** is a sequ...
null
Solution
shortest-subarray-with-sum-at-least-k
1
1
```C++ []\n#pragma GCC optimize("Ofast","inline","-ffast-math")\n#pragma GCC target("avx,mmx,sse2,sse3,sse4")\n\nclass Solution {\npublic:\n int shortestSubarray(vector<int>& nums, int k) {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n int n = nums.size();\n ...
1
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[1\], k = 1 **Output:** 1 **Examp...
null
Solution
shortest-subarray-with-sum-at-least-k
1
1
```C++ []\n#pragma GCC optimize("Ofast","inline","-ffast-math")\n#pragma GCC target("avx,mmx,sse2,sse3,sse4")\n\nclass Solution {\npublic:\n int shortestSubarray(vector<int>& nums, int k) {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n int n = nums.size();\n ...
1
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the tota...
null
Queue with Explanation
shortest-subarray-with-sum-at-least-k
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNeeds a monotonic queue as we are going to find the minimal length and need to care about the value reaching k. As such, we are bounded on two sides so that sliding window / two pointer is not going to cut it. \n\n# Approach\n<!-- Describ...
1
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[1\], k = 1 **Output:** 1 **Examp...
null
Queue with Explanation
shortest-subarray-with-sum-at-least-k
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNeeds a monotonic queue as we are going to find the minimal length and need to care about the value reaching k. As such, we are bounded on two sides so that sliding window / two pointer is not going to cut it. \n\n# Approach\n<!-- Describ...
1
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the tota...
null
Python - using deque- with explaination
shortest-subarray-with-sum-at-least-k
0
1
At first, I used sliding window, but got TLE - O(N^2)\nAnd then I look into the discuss and thinking how can use deque to achieve O(N).\n\nSome Tips:\n1. dealing with sum, construct sum array may help.\n2. using deque may leads to a O(N) solution.\n\nusing deque:\n\t\t1. think about that should it be increasing or dec...
14
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[1\], k = 1 **Output:** 1 **Examp...
null
Python - using deque- with explaination
shortest-subarray-with-sum-at-least-k
0
1
At first, I used sliding window, but got TLE - O(N^2)\nAnd then I look into the discuss and thinking how can use deque to achieve O(N).\n\nSome Tips:\n1. dealing with sum, construct sum array may help.\n2. using deque may leads to a O(N) solution.\n\nusing deque:\n\t\t1. think about that should it be increasing or dec...
14
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the tota...
null
Explained why is works
shortest-subarray-with-sum-at-least-k
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSo I could\'t come up with this approach , read some post and spend way to long to understand does this works.\n\nQ : What would we do if the question was to find the Sortest sub array and we had only position integer.\nA : We can tak...
1
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[1\], k = 1 **Output:** 1 **Examp...
null
Explained why is works
shortest-subarray-with-sum-at-least-k
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSo I could\'t come up with this approach , read some post and spend way to long to understand does this works.\n\nQ : What would we do if the question was to find the Sortest sub array and we had only position integer.\nA : We can tak...
1
You are given an `n x n` `grid` where you have placed some `1 x 1 x 1` cubes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of cell `(i, j)`. After placing these cubes, you have decided to glue any directly adjacent cubes to each other, forming several irregular 3D shapes. Return _the tota...
null
EASY PYTHON SOLUTION || BINARY TREE
all-nodes-distance-k-in-binary-tree
0
1
\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def getTarget(self,root,target):\n if root is None:\n return float("infinity"),\'\'\n if ...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
EASY PYTHON SOLUTION || BINARY TREE
all-nodes-distance-k-in-binary-tree
0
1
\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def getTarget(self,root,target):\n if root is None:\n return float("infinity"),\'\'\n if ...
1
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example,...
null
Solution
all-nodes-distance-k-in-binary-tree
1
1
```C++ []\n#define pp pair<int, TreeNode*>\n\nclass Solution {\npublic:\n unordered_map<TreeNode*, TreeNode*> nodeParent;\n void makeParent(TreeNode* root, TreeNode* parent){\n nodeParent[root] = parent; \n if(root->left) makeParent(root->left, root);\n if(root->right) makeParent(root->rig...
1
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
Solution
all-nodes-distance-k-in-binary-tree
1
1
```C++ []\n#define pp pair<int, TreeNode*>\n\nclass Solution {\npublic:\n unordered_map<TreeNode*, TreeNode*> nodeParent;\n void makeParent(TreeNode* root, TreeNode* parent){\n nodeParent[root] = parent; \n if(root->left) makeParent(root->left, root);\n if(root->right) makeParent(root->rig...
1
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example,...
null
βœ…Two BFS || C++ || JAVA || PYTHON || Beginner FriendlyπŸ”₯πŸ”₯πŸ”₯
all-nodes-distance-k-in-binary-tree
1
1
# Intuition:\nThe Intuition is to perform two BFS traversals: one to build the parent-child relationship and another to find all nodes at a distance of k from the target node.\n\n# Explanation:\n\n1. Start a BFS from the root node of the binary tree. We will use a queue to perform the BFS traversal. Initialize an empty...
104
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **O...
null
βœ…Two BFS || C++ || JAVA || PYTHON || Beginner FriendlyπŸ”₯πŸ”₯πŸ”₯
all-nodes-distance-k-in-binary-tree
1
1
# Intuition:\nThe Intuition is to perform two BFS traversals: one to build the parent-child relationship and another to find all nodes at a distance of k from the target node.\n\n# Explanation:\n\n1. Start a BFS from the root node of the binary tree. We will use a queue to perform the BFS traversal. Initialize an empty...
104
You are given an array of strings of the same length `words`. In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`. Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`. * For example,...
null
Python3 Solution
shortest-path-to-get-all-keys
0
1
\n```\nclass Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n m=len(grid)\n n=len(grid[0])\n arr=deque([])\n numOfKeys=0\n keys={\'a\':0,\'b\':1,\'c\':2,\'d\':3,\'e\':4,\'f\':5}\n locks={\'A\':0,\'B\':1,\'C\':2,\'D\':3,\'E\':4,\'F\':5}\n for i in r...
15
You are given an `m x n` grid `grid` where: * `'.'` is an empty cell. * `'#'` is a wall. * `'@'` is the starting point. * Lowercase letters represent keys. * Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. ...
null
Python3 Solution
shortest-path-to-get-all-keys
0
1
\n```\nclass Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n m=len(grid)\n n=len(grid[0])\n arr=deque([])\n numOfKeys=0\n keys={\'a\':0,\'b\':1,\'c\':2,\'d\':3,\'e\':4,\'f\':5}\n locks={\'A\':0,\'B\':1,\'C\':2,\'D\':3,\'E\':4,\'F\':5}\n for i in r...
15
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the `FreqStack` class: * `FreqStack()` constructs an empty frequency stack. * `void push(int val)` pushes an integer `val` onto the top of the stack. * `int pop()` removes and returns the...
null
Python | Contract to weighted component graph then djikstra's
shortest-path-to-get-all-keys
0
1
# Intuition\n\nThe original idea I had came from a comment left on the leetcode editorial. Someone said you might be able to use the connected components graph. This is true, but you end up having to solve the same problem as the original, but with a weighted graph instead of an unweighted graph.\n\n# Approach\nThe app...
1
You are given an `m x n` grid `grid` where: * `'.'` is an empty cell. * `'#'` is a wall. * `'@'` is the starting point. * Lowercase letters represent keys. * Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. ...
null
Python | Contract to weighted component graph then djikstra's
shortest-path-to-get-all-keys
0
1
# Intuition\n\nThe original idea I had came from a comment left on the leetcode editorial. Someone said you might be able to use the connected components graph. This is true, but you end up having to solve the same problem as the original, but with a weighted graph instead of an unweighted graph.\n\n# Approach\nThe app...
1
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the `FreqStack` class: * `FreqStack()` constructs an empty frequency stack. * `void push(int val)` pushes an integer `val` onto the top of the stack. * `int pop()` removes and returns the...
null
python 3 - bfs + bitmask
shortest-path-to-get-all-keys
0
1
# Intuition\nThis question is BFS question but allowing you to go back. The question is: you can\'t revisit the same cell infinitely.\n\nIf you think about the key_state and unlocked_state, you should take these 2 into account. For a certain cell, it can\'t be revisited with the same (key_state, unlocked_state).\n\n# A...
1
You are given an `m x n` grid `grid` where: * `'.'` is an empty cell. * `'#'` is a wall. * `'@'` is the starting point. * Lowercase letters represent keys. * Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. ...
null
python 3 - bfs + bitmask
shortest-path-to-get-all-keys
0
1
# Intuition\nThis question is BFS question but allowing you to go back. The question is: you can\'t revisit the same cell infinitely.\n\nIf you think about the key_state and unlocked_state, you should take these 2 into account. For a certain cell, it can\'t be revisited with the same (key_state, unlocked_state).\n\n# A...
1
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the `FreqStack` class: * `FreqStack()` constructs an empty frequency stack. * `void push(int val)` pushes an integer `val` onto the top of the stack. * `int pop()` removes and returns the...
null
Python short and clean. Functional programming.
shortest-path-to-get-all-keys
0
1
# Approach\nTL;DR, Similar to [Editorial solution](https://leetcode.com/problems/shortest-path-to-get-all-keys/editorial/) but clean and functional.\n\n# Complexity\n- Time complexity: $$O(2^6 \\cdot m \\cdot n)$$\n\n- Space complexity: $$O(m \\cdot n)$$\n\nwhere, `m x n is the dimensions of grid`.\n\n# Code\n```python...
2
You are given an `m x n` grid `grid` where: * `'.'` is an empty cell. * `'#'` is a wall. * `'@'` is the starting point. * Lowercase letters represent keys. * Uppercase letters represent locks. You start at the starting point and one move consists of walking one space in one of the four cardinal directions. ...
null
Python short and clean. Functional programming.
shortest-path-to-get-all-keys
0
1
# Approach\nTL;DR, Similar to [Editorial solution](https://leetcode.com/problems/shortest-path-to-get-all-keys/editorial/) but clean and functional.\n\n# Complexity\n- Time complexity: $$O(2^6 \\cdot m \\cdot n)$$\n\n- Space complexity: $$O(m \\cdot n)$$\n\nwhere, `m x n is the dimensions of grid`.\n\n# Code\n```python...
2
Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack. Implement the `FreqStack` class: * `FreqStack()` constructs an empty frequency stack. * `void push(int val)` pushes an integer `val` onto the top of the stack. * `int pop()` removes and returns the...
null
Solution
smallest-subtree-with-all-the-deepest-nodes
1
1
```C++ []\nclass Solution {\npublic:\n int height(TreeNode* root) {\n if (!root) return 0;\n return max(height(root->left) + 1, height(root->right) + 1); \n }\n TreeNode* subtreeWithAllDeepest(TreeNode* root) {\n if (!root) return NULL;\n\n int left = height(root->left); \n ...
3
Given the `root` of a binary tree, the depth of each node is **the shortest distance to the root**. Return _the smallest subtree_ such that it contains **all the deepest nodes** in the original tree. A node is called **the deepest** if it has the largest depth possible among any node in the entire tree. The **subtre...
null
Solution
smallest-subtree-with-all-the-deepest-nodes
1
1
```C++ []\nclass Solution {\npublic:\n int height(TreeNode* root) {\n if (!root) return 0;\n return max(height(root->left) + 1, height(root->right) + 1); \n }\n TreeNode* subtreeWithAllDeepest(TreeNode* root) {\n if (!root) return NULL;\n\n int left = height(root->left); \n ...
3
An array is **monotonic** if it is either monotone increasing or monotone decreasing. An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`. Given an integer array `nums`, return `true` _if the given array is ...
null
Solution
prime-palindrome
1
1
```C++ []\nclass Solution {\n bool isPrime(int val){\n if(val == 1 ) \n return false ;\n if(val == 2)\n return true ;\n int limit = sqrt(val) ;\n for(int i = 2; i <= limit; i++){\n if(val % i == 0)\n return false ;\n }\n return...
1
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a **palindrome** if it reads the ...
null
Solution
prime-palindrome
1
1
```C++ []\nclass Solution {\n bool isPrime(int val){\n if(val == 1 ) \n return false ;\n if(val == 2)\n return true ;\n int limit = sqrt(val) ;\n for(int i = 2; i <= limit; i++){\n if(val % i == 0)\n return false ;\n }\n return...
1
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,nul...
null
Python Simple Solution
prime-palindrome
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1>Check if n is a palindrome. If it is, check if it is a prime number. If it is, return n.\n2>Otherwise, increment n by 1 and repeat step 1 until a palindrome prime is found.\n\n# Complexity\n- Time complexity:\nThe time com...
2
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a **palindrome** if it reads the ...
null
Python Simple Solution
prime-palindrome
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1>Check if n is a palindrome. If it is, check if it is a prime number. If it is, return n.\n2>Otherwise, increment n by 1 and repeat step 1 until a palindrome prime is found.\n\n# Complexity\n- Time complexity:\nThe time com...
2
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,nul...
null
Who did? GOD DID
prime-palindrome
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a **palindrome** if it reads the ...
null
Who did? GOD DID
prime-palindrome
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,nul...
null
Easiest Solution
prime-palindrome
1
1
\n\n# Code\n```java []\nclass Solution {\n public int primePalindrome(int n) {\n \n \n boolean l=false;\n\n if(n==1||n==0)\n return 2;\n\n\n while(l!=true)\n {\n\n if( n > 11 && n < 100 )\n {\n n = 101 ;\n }\n if( n > ...
0
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a **palindrome** if it reads the ...
null
Easiest Solution
prime-palindrome
1
1
\n\n# Code\n```java []\nclass Solution {\n public int primePalindrome(int n) {\n \n \n boolean l=false;\n\n if(n==1||n==0)\n return 2;\n\n\n while(l!=true)\n {\n\n if( n > 11 && n < 100 )\n {\n n = 101 ;\n }\n if( n > ...
0
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,nul...
null
Python 100%, Light
prime-palindrome
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a **palindrome** if it reads the ...
null
Python 100%, Light
prime-palindrome
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,nul...
null
by PRODONiK (py)
prime-palindrome
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given an integer n, return _the smallest **prime palindrome** greater than or equal to_ `n`. An integer is **prime** if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a **palindrome** if it reads the ...
null
by PRODONiK (py)
prime-palindrome
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,nul...
null
Easy transpose C/C++/Python->zip 1 line
transpose-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust the definition t[i][j]=m[j][i]\n# Approach\n<!-- Describe your approach to solving the problem. -->\nC/C++/Python codes are implemented.\n\nFor the reason of mallocating memory, the order for outer loop & inner loop in C code is dif...
17
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Easy transpose C/C++/Python->zip 1 line
transpose-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust the definition t[i][j]=m[j][i]\n# Approach\n<!-- Describe your approach to solving the problem. -->\nC/C++/Python codes are implemented.\n\nFor the reason of mallocating memory, the order for outer loop & inner loop in C code is dif...
17
Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A **subarray** is a contiguous non-empty sequence of elements ...
We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!
【Video】Give me 5 minutes - 2 solutions - How we think about a solution.
transpose-matrix
1
1
# Intuition\nIterate the matrix vertically.\n\n# Approach\n\n---\n\n# Solution Video\n\nhttps://youtu.be/lsAZepsNRPo\n\n\u25A0 Timeline of the video\n\n`0:04` Explain algorithm of Solution 1\n`1:12` Coding of solution 1\n`2:30` Time Complexity and Space Complexity of solution 1\n`2:54` Explain algorithm of Solution 2\n...
28
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
【Video】Give me 5 minutes - 2 solutions - How we think about a solution.
transpose-matrix
1
1
# Intuition\nIterate the matrix vertically.\n\n# Approach\n\n---\n\n# Solution Video\n\nhttps://youtu.be/lsAZepsNRPo\n\n\u25A0 Timeline of the video\n\n`0:04` Explain algorithm of Solution 1\n`1:12` Coding of solution 1\n`2:30` Time Complexity and Space Complexity of solution 1\n`2:54` Explain algorithm of Solution 2\n...
28
Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A **subarray** is a contiguous non-empty sequence of elements ...
We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!
πŸš€πŸš€ 867. π•Ώπ–—π–†π–“π–˜π–•π–”π–˜π–Š π•Έπ–†π–™π–—π–Žπ– | π•­π–Šπ–†π–™π–˜ 100% | π•±π–šπ–‘π–‘π–ž π•°π–π–•π–‘π–†π–Žπ–“π–Šπ–‰ πŸ”₯πŸ’–
transpose-matrix
1
1
# Intuition\nThe task is to find the transpose of a given matrix, which is like doing a dance move with the rows and columns, switching their positions. Imagine a joyful matrix flip!\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. \uD83D\uDD75\uFE0F\u200D\u2642\uFE0F **Investigate...
3
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
πŸš€πŸš€ 867. π•Ώπ–—π–†π–“π–˜π–•π–”π–˜π–Š π•Έπ–†π–™π–—π–Žπ– | π•­π–Šπ–†π–™π–˜ 100% | π•±π–šπ–‘π–‘π–ž π•°π–π–•π–‘π–†π–Žπ–“π–Šπ–‰ πŸ”₯πŸ’–
transpose-matrix
1
1
# Intuition\nThe task is to find the transpose of a given matrix, which is like doing a dance move with the rows and columns, switching their positions. Imagine a joyful matrix flip!\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. \uD83D\uDD75\uFE0F\u200D\u2642\uFE0F **Investigate...
3
Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A **subarray** is a contiguous non-empty sequence of elements ...
We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!
Straightforward transpose!
transpose-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Straightforward transpose!
transpose-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A **subarray** is a contiguous non-empty sequence of elements ...
We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!
βœ…β˜‘[C++/Java/Python/JavaScript] || Beats 100% || EXPLAINEDπŸ”₯
transpose-matrix
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n1. **Input:** It takes a 2D vector `matrix` as input, representing the original matrix.\n\n1. **Output:** Returns a new 2D vector `ans`, which stores the transposed elements.\n\n1. **Transposing the Matrix:** It iterates through ...
3
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
βœ…β˜‘[C++/Java/Python/JavaScript] || Beats 100% || EXPLAINEDπŸ”₯
transpose-matrix
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n1. **Input:** It takes a 2D vector `matrix` as input, representing the original matrix.\n\n1. **Output:** Returns a new 2D vector `ans`, which stores the transposed elements.\n\n1. **Transposing the Matrix:** It iterates through ...
3
Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A **subarray** is a contiguous non-empty sequence of elements ...
We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!
Python3 Solution
transpose-matrix
0
1
\n```\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n n=len(matrix)\n m=len(matrix[0])\n ans=[[0]*n for _ in range(m)]\n for i in range(m):\n for j in range(n):\n ans[i][j]=matrix[j][i]\n return ans \n \n...
2
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
Python3 Solution
transpose-matrix
0
1
\n```\nclass Solution:\n def transpose(self, matrix: List[List[int]]) -> List[List[int]]:\n n=len(matrix)\n m=len(matrix[0])\n ans=[[0]*n for _ in range(m)]\n for i in range(m):\n for j in range(n):\n ans[i][j]=matrix[j][i]\n return ans \n \n...
2
Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A **subarray** is a contiguous non-empty sequence of elements ...
We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!
πŸ”₯|| BEGINNER FRIENDLY || EXPLAINED || 9ms || OPTIMAL || πŸ”₯
transpose-matrix
1
1
# INTUTION\n![image.png](https://assets.leetcode.com/users/images/8995f4f6-5467-4878-817a-378d66061723_1702183391.8344903.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCertainly! Here\'s an explanation of the provided ...
2
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **E...
null
πŸ”₯|| BEGINNER FRIENDLY || EXPLAINED || 9ms || OPTIMAL || πŸ”₯
transpose-matrix
1
1
# INTUTION\n![image.png](https://assets.leetcode.com/users/images/8995f4f6-5467-4878-817a-378d66061723_1702183391.8344903.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCertainly! Here\'s an explanation of the provided ...
2
Given an integer array `arr`, return _the number of distinct bitwise ORs of all the non-empty subarrays of_ `arr`. The bitwise OR of a subarray is the bitwise OR of each integer in the subarray. The bitwise OR of a subarray of one integer is that integer. A **subarray** is a contiguous non-empty sequence of elements ...
We don't need any special algorithms to do this. You just need to know what the transpose of a matrix looks like. Rows become columns and vice versa!