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
🦧 PYTHON3 BEATS 80% 🦧 Recursion + Caching Solution
all-possible-full-binary-trees
0
1
# Intuition\n1. The first important thing to realize about this problem is that there are various repeated sub problems. \n2. For example, if we have n = 7, we know that we must recursively try every odd split from the root note ((1, 5), (3, 3), (5, 1)), which means starting from the root node, we collect all combinati...
1
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tr...
null
🦧 PYTHON3 BEATS 80% 🦧 Recursion + Caching Solution
all-possible-full-binary-trees
0
1
# Intuition\n1. The first important thing to realize about this problem is that there are various repeated sub problems. \n2. For example, if we have n = 7, we know that we must recursively try every odd split from the root note ((1, 5), (3, 3), (5, 1)), which means starting from the root node, we collect all combinati...
1
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0...
null
🥳 Runtime 1ms | Beats 98.7% | Recursion | Memoization
all-possible-full-binary-trees
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe recursion works by first generating all possible full binary trees with i nodes, and then all possible full binary trees with n - i - 1 nodes. For each pair of trees, a new tree is created with the first tree as the left subtree and t...
58
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tr...
null
🥳 Runtime 1ms | Beats 98.7% | Recursion | Memoization
all-possible-full-binary-trees
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe recursion works by first generating all possible full binary trees with i nodes, and then all possible full binary trees with n - i - 1 nodes. For each pair of trees, a new tree is created with the first tree as the left subtree and t...
58
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0...
null
Recursion+DP+Video Explanation in depth || Very Easy to Understand || C++ || Java || Python
all-possible-full-binary-trees
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTake every odd node from 1 to n as a tree and make a full binary tree.\nNote: if there are even nodes then we cant make a full binary tree.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\nhttps://youtu.be...
38
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tr...
null
Recursion+DP+Video Explanation in depth || Very Easy to Understand || C++ || Java || Python
all-possible-full-binary-trees
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTake every odd node from 1 to n as a tree and make a full binary tree.\nNote: if there are even nodes then we cant make a full binary tree.\n\nFor detailed explanation you can refer to my youtube channel (hindi Language)\nhttps://youtu.be...
38
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0...
null
🔥One Line Solution🔥
all-possible-full-binary-trees
0
1
# Complexity\n- Time complexity: $$O(2^{n/2})$$.\n\n- Space complexity: $$O(n*2^{n/2})$$.\n\n# Code in One Line\n```\nclass Solution:\n @cache\n def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n return [TreeNode(0, left, right) for k in range(1, n-1, 2) for left in self.allPossibleFBT(k) for ...
14
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tr...
null
🔥One Line Solution🔥
all-possible-full-binary-trees
0
1
# Complexity\n- Time complexity: $$O(2^{n/2})$$.\n\n- Space complexity: $$O(n*2^{n/2})$$.\n\n# Code in One Line\n```\nclass Solution:\n @cache\n def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n return [TreeNode(0, left, right) for k in range(1, n-1, 2) for left in self.allPossibleFBT(k) for ...
14
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0...
null
Easy, detailed Python solution, beats 96%. Recursion + dictionary
all-possible-full-binary-trees
0
1
![image.png](https://assets.leetcode.com/users/images/09dfd2b9-7886-4f18-b5df-265d6a346402_1690130728.287268.png)\n\n\nInspired by this Java solution: [https://leetcode.com/problems/all-possible-full-binary-trees/solutions/216853/java-easy-with-examples/]()\n\n# Approach\n<!-- Describe your approach to solving the prob...
2
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tr...
null
Easy, detailed Python solution, beats 96%. Recursion + dictionary
all-possible-full-binary-trees
0
1
![image.png](https://assets.leetcode.com/users/images/09dfd2b9-7886-4f18-b5df-265d6a346402_1690130728.287268.png)\n\n\nInspired by this Java solution: [https://leetcode.com/problems/all-possible-full-binary-trees/solutions/216853/java-easy-with-examples/]()\n\n# Approach\n<!-- Describe your approach to solving the prob...
2
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0...
null
🚀 [ VIDEO] Master Full Binary Trees 🌳 | Step-by-Step LeetCode Guide
all-possible-full-binary-trees
1
1
# Intuition\nAt first glance, this problem might seem complex due to its requirement for generating all possible full binary trees. However, it\'s clear that the problem can be approached via dynamic programming, breaking down the larger problem into smaller sub-problems and using memoization to prevent redundant compu...
7
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tr...
null
🚀 [ VIDEO] Master Full Binary Trees 🌳 | Step-by-Step LeetCode Guide
all-possible-full-binary-trees
1
1
# Intuition\nAt first glance, this problem might seem complex due to its requirement for generating all possible full binary trees. However, it\'s clear that the problem can be approached via dynamic programming, breaking down the larger problem into smaller sub-problems and using memoization to prevent redundant compu...
7
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0...
null
🐍 python, dynamic programming solutions || faster than 100%
all-possible-full-binary-trees
0
1
# Approach\nI highly recommend that you solve [96. Unique Binary Search Trees\n](https://leetcode.com/problems/unique-binary-search-trees/solutions/2947716/python-two-approaches-1-recursive-2-iterative-both-o-n-faster-than-97-with-explanation/) and [95. Unique Binary Search Trees II](https://leetcode.com/problems/uniqu...
1
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tr...
null
🐍 python, dynamic programming solutions || faster than 100%
all-possible-full-binary-trees
0
1
# Approach\nI highly recommend that you solve [96. Unique Binary Search Trees\n](https://leetcode.com/problems/unique-binary-search-trees/solutions/2947716/python-two-approaches-1-recursive-2-iterative-both-o-n-faster-than-97-with-explanation/) and [95. Unique Binary Search Trees II](https://leetcode.com/problems/uniqu...
1
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0...
null
Solution
all-possible-full-binary-trees
1
1
```C++ []\nclass Solution {\npublic:\n unordered_map<int, vector<TreeNode *>> dp;\n vector<TreeNode*> allPossibleFBT(int n) {\n vector<TreeNode*> ans;\n if(n%2==0)return {};\n if(n==1){\n ans.push_back(new TreeNode(0));\n return dp[1]=ans;\n }\n if(dp.find(...
2
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tr...
null
Solution
all-possible-full-binary-trees
1
1
```C++ []\nclass Solution {\npublic:\n unordered_map<int, vector<TreeNode *>> dp;\n vector<TreeNode*> allPossibleFBT(int n) {\n vector<TreeNode*> ans;\n if(n%2==0)return {};\n if(n==1){\n ans.push_back(new TreeNode(0));\n return dp[1]=ans;\n }\n if(dp.find(...
2
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0...
null
FAST Solution With DP
all-possible-full-binary-trees
0
1
# Code\n```python []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n trees = ...
3
Given an integer `n`, return _a list of all possible **full binary trees** with_ `n` _nodes_. Each node of each tree in the answer must have `Node.val == 0`. Each element of the answer is the root node of one possible tree. You may return the final list of trees in **any order**. A **full binary tree** is a binary tr...
null
FAST Solution With DP
all-possible-full-binary-trees
0
1
# Code\n```python []\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:\n trees = ...
3
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0...
null
Solution
maximum-frequency-stack
1
1
```C++ []\nclass FreqStack {\npublic:\n unordered_map<int,int> freq;\n unordered_map<int,stack<int>> m;\n int maxFreq;\n FreqStack() {\n maxFreq=0;\n }\n void push(int val) {\n maxFreq=max(maxFreq,++freq[val]);\n m[freq[val]].push(val);\n }\n int pop() {\n int ele = m...
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
Solution
maximum-frequency-stack
1
1
```C++ []\nclass FreqStack {\npublic:\n unordered_map<int,int> freq;\n unordered_map<int,stack<int>> m;\n int maxFreq;\n FreqStack() {\n maxFreq=0;\n }\n void push(int val) {\n maxFreq=max(maxFreq,++freq[val]);\n m[freq[val]].push(val);\n }\n int pop() {\n int ele = m...
1
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro...
null
Solution with Stack in Python3
maximum-frequency-stack
0
1
# Intuition\nHere we need to implement **Frequency Stack**.\nAccording to a problem definition it has **two methods**:\n- `push` to insert a val into `stack`\n- `pop` to extract **most frequent** element in stack \n\nThe first way to maintain an order with frequency is **Max Priority Queue (MPQ)**.\nThough this solutio...
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 with Stack in Python3
maximum-frequency-stack
0
1
# Intuition\nHere we need to implement **Frequency Stack**.\nAccording to a problem definition it has **two methods**:\n- `push` to insert a val into `stack`\n- `pop` to extract **most frequent** element in stack \n\nThe first way to maintain an order with frequency is **Max Priority Queue (MPQ)**.\nThough this solutio...
2
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro...
null
67% Tc and 76% Sc easy python solution
maximum-frequency-stack
0
1
```\nclass FreqStack:\n\tdef __init__(self):\n\t\tself.freq = defaultdict(int)\n\t\tself.freqEle = defaultdict(list)\n\t\tself.maxx = -1\n\n\tdef push(self, val: int) -> None:\n\t\tself.freq[val] += 1\n\t\tself.freqEle[self.freq[val]].append(val)\n\t\tself.maxx = max(self.maxx, self.freq[val])\n\n\tdef pop(self) -> int...
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
67% Tc and 76% Sc easy python solution
maximum-frequency-stack
0
1
```\nclass FreqStack:\n\tdef __init__(self):\n\t\tself.freq = defaultdict(int)\n\t\tself.freqEle = defaultdict(list)\n\t\tself.maxx = -1\n\n\tdef push(self, val: int) -> None:\n\t\tself.freq[val] += 1\n\t\tself.freqEle[self.freq[val]].append(val)\n\t\tself.maxx = max(self.maxx, self.freq[val])\n\n\tdef pop(self) -> int...
1
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro...
null
Python O(1) Solution using two dictionaries with explanation
maximum-frequency-stack
0
1
Initialise two dictionaries **set** and **freq** and a variable **max_freq**.\n**freq** is used to store the frequency of the elements provided, i.e., Key: Element; Value: Count of that element\n**set** is used to store the group of elements having the same frequency. Key: Count; Value: List of elements\n**max_freq** i...
16
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 O(1) Solution using two dictionaries with explanation
maximum-frequency-stack
0
1
Initialise two dictionaries **set** and **freq** and a variable **max_freq**.\n**freq** is used to store the frequency of the elements provided, i.e., Key: Element; Value: Count of that element\n**set** is used to store the group of elements having the same frequency. Key: Count; Value: List of elements\n**max_freq** i...
16
Given an `n x n` array of integers `matrix`, return _the **minimum sum** of any **falling path** through_ `matrix`. A **falling path** starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position `(ro...
null
NOOB CODE : Easy to understand
monotonic-array
0
1
\n# Approach\n1. `o` is initialized to `False`. This variable will be used to store the result indicating whether the list is monotonic.\n\n2. An empty list `k` is initialized.\n\n3. A loop is used to iterate through each element `i` in the input list `nums`. Inside the loop, each element `i` is appended to the list `k...
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
NOOB CODE : Easy to understand
monotonic-array
0
1
\n# Approach\n1. `o` is initialized to `False`. This variable will be used to store the result indicating whether the list is monotonic.\n\n2. An empty list `k` is initialized.\n\n3. A loop is used to iterate through each element `i` in the input list `nums`. Inside the loop, each element `i` is appended to the list `k...
3
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
✅ Detailed Explanation with Solution using Two Pointer Approach (O(n)) - with 100% Acceptance Rate
monotonic-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this code is to determine whether the given array is monotonic, i.e., either monotone increasing or monotone decreasing. It uses a two-pointer approach to skip identical elements at the beginning and end of the array ...
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
✅ Detailed Explanation with Solution using Two Pointer Approach (O(n)) - with 100% Acceptance Rate
monotonic-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this code is to determine whether the given array is monotonic, i.e., either monotone increasing or monotone decreasing. It uses a two-pointer approach to skip identical elements at the beginning and end of the array ...
3
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
✅97.44%🔥Increasing & Decreasing🔥1 line code🔥
monotonic-array
1
1
# Problem\n#### The problem statement asks you to determine whether a given array nums is monotonic. An array is considered monotonic if it is either monotone increasing or monotone decreasing.\n\n **1.** **Monotone Increasing :** An array is considered monotone increasing if for all indices i and j where i <= j, the...
94
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
✅97.44%🔥Increasing & Decreasing🔥1 line code🔥
monotonic-array
1
1
# Problem\n#### The problem statement asks you to determine whether a given array nums is monotonic. An array is considered monotonic if it is either monotone increasing or monotone decreasing.\n\n **1.** **Monotone Increasing :** An array is considered monotone increasing if for all indices i and j where i <= j, the...
94
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
Python 3 || O(n) time, O(1) Space
monotonic-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
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
Python 3 || O(n) time, O(1) Space
monotonic-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
Python 3 || Sorting
monotonic-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
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
Python 3 || Sorting
monotonic-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
Simple map reduce
monotonic-array
0
1
# Intuition\nCould check `nums[0]` and `nums[len(nums)-1]` to determine increasing / decreasing / constant upfront, but there is no meaningful difference.\n\n# Approach\n- Create an iterator for `is_increasing` and `is_decreasing`.\n- Use `all()` to reduce them.\n- Return `True` if either of them reduces to `True`.\n\n...
1
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
Simple map reduce
monotonic-array
0
1
# Intuition\nCould check `nums[0]` and `nums[len(nums)-1]` to determine increasing / decreasing / constant upfront, but there is no meaningful difference.\n\n# Approach\n- Create an iterator for `is_increasing` and `is_decreasing`.\n- Use `all()` to reduce them.\n- Return `True` if either of them reduces to `True`.\n\n...
1
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
🔥 Easy solution in 1 line | Python 3 🔥
monotonic-array
0
1
# Intuition\nA list is considered monotonic if it is entirely non-increasing (every element is less than or equal to the next) or entirely non-decreasing (every element is greater than or equal to the next)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. The function defines a sin...
1
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
🔥 Easy solution in 1 line | Python 3 🔥
monotonic-array
0
1
# Intuition\nA list is considered monotonic if it is entirely non-increasing (every element is less than or equal to the next) or entirely non-decreasing (every element is greater than or equal to the next)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. The function defines a sin...
1
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
✅ 95.15% Single Pass Check
monotonic-array
1
1
# Interview Guide: "Check Monotonic Array" Problem\n\n## Problem Understanding\n\nThe "Check Monotonic Array" problem requires evaluating whether a given array is either entirely non-decreasing (monotonically increasing) or non-increasing (monotonically decreasing). The objective is to return a boolean value indicating...
112
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
✅ 95.15% Single Pass Check
monotonic-array
1
1
# Interview Guide: "Check Monotonic Array" Problem\n\n## Problem Understanding\n\nThe "Check Monotonic Array" problem requires evaluating whether a given array is either entirely non-decreasing (monotonically increasing) or non-increasing (monotonically decreasing). The objective is to return a boolean value indicating...
112
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
Monotonic Solution in Python3 with one liner also
monotonic-array
0
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere\'s a step-by-step explanation of the code:\n\n1. increasing_index and decreasing_index are initialized as True. These variables will be used to keep track of whether the list is increasing or decreasing.\n\n2. A for loop iterates through the ...
1
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
Monotonic Solution in Python3 with one liner also
monotonic-array
0
1
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere\'s a step-by-step explanation of the code:\n\n1. increasing_index and decreasing_index are initialized as True. These variables will be used to keep track of whether the list is increasing or decreasing.\n\n2. A for loop iterates through the ...
1
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
Monotonic Array
monotonic-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is a simple monotonic array, So there is no intuition for this problem this is direct approach problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitally initate two terms that is increasing and decreasin...
1
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
Monotonic Array
monotonic-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is a simple monotonic array, So there is no intuition for this problem this is direct approach problem.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitally initate two terms that is increasing and decreasin...
1
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
Python two-liner
monotonic-array
0
1
# Complexity\n- Time complexity:\n $$O(n)$$\n\n- Space complexity:\n $$O(1)$$\n\n# Code\n```\nclass Solution:\n def isMonotonic(self, nums: List[int]) -> bool:\n op = operator.le if nums[0] <= nums[-1] else operator.ge\n return all(op(nums[i], nums[i + 1]) for i in range(len(nums) - 1))\n```
1
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
Python two-liner
monotonic-array
0
1
# Complexity\n- Time complexity:\n $$O(n)$$\n\n- Space complexity:\n $$O(1)$$\n\n# Code\n```\nclass Solution:\n def isMonotonic(self, nums: List[int]) -> bool:\n op = operator.le if nums[0] <= nums[-1] else operator.ge\n return all(op(nums[i], nums[i + 1]) for i in range(len(nums) - 1))\n```
1
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
100% - ONE LINE TRAVERSAL APPROACH IN C++/JAVA/PYTHON/PYTHON3( TIME - O(N) SPACE - O(1))
monotonic-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n \n Empty or Single-Element Array:\n The function first checks if the array has fewer than or equal to 1 element. In such cases, an array of this size is considered monotonic (both non-increasing and non-decreasing). This is a base ...
1
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
100% - ONE LINE TRAVERSAL APPROACH IN C++/JAVA/PYTHON/PYTHON3( TIME - O(N) SPACE - O(1))
monotonic-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n \n Empty or Single-Element Array:\n The function first checks if the array has fewer than or equal to 1 element. In such cases, an array of this size is considered monotonic (both non-increasing and non-decreasing). This is a base ...
1
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
Easy to understand approach
monotonic-array
0
1
\n```python []\nclass Solution:\n def isMonotonic(self, nums: List[int]) -> bool:\n m = 1 # Initialize the monotonicity variable\n \n # Check for non-increasing monotonicity\n for i in range(1, len(nums)):\n if nums[i - 1] >= nums[i]: # If the previous element is greater or e...
1
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
Easy to understand approach
monotonic-array
0
1
\n```python []\nclass Solution:\n def isMonotonic(self, nums: List[int]) -> bool:\n m = 1 # Initialize the monotonicity variable\n \n # Check for non-increasing monotonicity\n for i in range(1, len(nums)):\n if nums[i - 1] >= nums[i]: # If the previous element is greater or e...
1
An array `nums` of length `n` is **beautiful** if: * `nums` is a permutation of the integers in the range `[1, n]`. * For every `0 <= i < j < n`, there is no index `k` with `i < k < j` where `2 * nums[k] == nums[i] + nums[j]`. Given the integer `n`, return _any **beautiful** array_ `nums` _of length_ `n`. There w...
null
Python3 One Pass beat 94.57% 26ms Iterative BFS
increasing-order-search-tree
0
1
\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, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# s...
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
Python3 One Pass beat 94.57% 26ms Iterative BFS
increasing-order-search-tree
0
1
\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, e.g. $$O(n)$$ -->\n\n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# s...
1
You have a `RecentCounter` class which counts the number of recent requests within a certain time frame. Implement the `RecentCounter` class: * `RecentCounter()` Initializes the counter with zero recent requests. * `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a...
null
Morris In-order traversal (Python 3, O(n) time / O(1) space)
increasing-order-search-tree
0
1
Hi everyone and thank you for showing interest in reading this article \uD83D\uDE4C.\n\n**Morris In-order traversal algorithm**\nHave you ever asked yourself why do we use the stack when it comes to traversing a tree? Lets answer to this question! Stacks are used in [traversal algorithms](https://en.wikipedia.org/wiki/...
51
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
Morris In-order traversal (Python 3, O(n) time / O(1) space)
increasing-order-search-tree
0
1
Hi everyone and thank you for showing interest in reading this article \uD83D\uDE4C.\n\n**Morris In-order traversal algorithm**\nHave you ever asked yourself why do we use the stack when it comes to traversing a tree? Lets answer to this question! Stacks are used in [traversal algorithms](https://en.wikipedia.org/wiki/...
51
You have a `RecentCounter` class which counts the number of recent requests within a certain time frame. Implement the `RecentCounter` class: * `RecentCounter()` Initializes the counter with zero recent requests. * `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a...
null
Solution
increasing-order-search-tree
1
1
```C++ []\nclass Solution {\n public:\n TreeNode* increasingBST(TreeNode* root, TreeNode* tail = nullptr) {\n if (root == nullptr)\n return tail;\n TreeNode* ans = increasingBST(root->left, root);\n root->left = nullptr;\n root->right = increasingBST(root->right, tail);\n return ans;\n }\n};\n```\...
4
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
Solution
increasing-order-search-tree
1
1
```C++ []\nclass Solution {\n public:\n TreeNode* increasingBST(TreeNode* root, TreeNode* tail = nullptr) {\n if (root == nullptr)\n return tail;\n TreeNode* ans = increasingBST(root->left, root);\n root->left = nullptr;\n root->right = increasingBST(root->right, tail);\n return ans;\n }\n};\n```\...
4
You have a `RecentCounter` class which counts the number of recent requests within a certain time frame. Implement the `RecentCounter` class: * `RecentCounter()` Initializes the counter with zero recent requests. * `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a...
null
Easy Python Solution beats 90% with Comments!
increasing-order-search-tree
0
1
```\nclass Solution:\n def increasingBST(self, root: TreeNode) -> TreeNode:\n \n vals = []\n # Easy recursive Inorder Traversal to get our values to insert.\n def inord(node):\n if not node:\n return\n inord(node.left)\n vals.append(node.val...
36
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 Python Solution beats 90% with Comments!
increasing-order-search-tree
0
1
```\nclass Solution:\n def increasingBST(self, root: TreeNode) -> TreeNode:\n \n vals = []\n # Easy recursive Inorder Traversal to get our values to insert.\n def inord(node):\n if not node:\n return\n inord(node.left)\n vals.append(node.val...
36
You have a `RecentCounter` class which counts the number of recent requests within a certain time frame. Implement the `RecentCounter` class: * `RecentCounter()` Initializes the counter with zero recent requests. * `int ping(int t)` Adds a new request at time `t`, where `t` represents some time in milliseconds, a...
null
Solution
bitwise-ors-of-subarrays
1
1
```C++ []\nclass Solution {\npublic:\n int subarrayBitwiseORs(vector<int>& arr) {\n vector<int> or_results;\n int i = 0, j = 0;\n int start,a2;\n for (auto a: arr) {\n start = or_results.size();\n or_results.emplace_back(a);\n for (int k = i; k < j; k++) {\n a2 = or_result...
1
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!
Solution
bitwise-ors-of-subarrays
1
1
```C++ []\nclass Solution {\npublic:\n int subarrayBitwiseORs(vector<int>& arr) {\n vector<int> or_results;\n int i = 0, j = 0;\n int start,a2;\n for (auto a: arr) {\n start = or_results.size();\n or_results.emplace_back(a);\n for (int k = i; k < j; k++) {\n a2 = or_result...
1
You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water. An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`. You may change `0`'s to `1`'s to connect the two islands to form **one island**. ...
null
Simple approach with Example
bitwise-ors-of-subarrays
0
1
# Intuition\nFind all possible subarraies and get the number of unique sums for those subarraies\n\n# Approach\nIterate the array and built all possible subarrys with unique OR sums\n\n\n# Code\n```\nclass Solution(object):\n def subarrayBitwiseORs(self, arr):\n """\n :type arr: List[int]\n :rty...
0
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!
Simple approach with Example
bitwise-ors-of-subarrays
0
1
# Intuition\nFind all possible subarraies and get the number of unique sums for those subarraies\n\n# Approach\nIterate the array and built all possible subarrys with unique OR sums\n\n\n# Code\n```\nclass Solution(object):\n def subarrayBitwiseORs(self, arr):\n """\n :type arr: List[int]\n :rty...
0
You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water. An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`. You may change `0`'s to `1`'s to connect the two islands to form **one island**. ...
null
set
bitwise-ors-of-subarrays
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe idea is dynamic programing\n- ans = {n | i for i in ans} | {n}\n- {n} for current number\n- ans is the previous set before n\n- [1, 2, 3], while i = 2, ans = {2, 2 | 1}\n# Approach\n<!-- Describe your approach to solving the problem. ...
0
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!
set
bitwise-ors-of-subarrays
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe idea is dynamic programing\n- ans = {n | i for i in ans} | {n}\n- {n} for current number\n- ans is the previous set before n\n- [1, 2, 3], while i = 2, ans = {2, 2 | 1}\n# Approach\n<!-- Describe your approach to solving the problem. ...
0
You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water. An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`. You may change `0`'s to `1`'s to connect the two islands to form **one island**. ...
null
🚀 Time: O(n * w) Space: O(n * w) | 📚 Detailed Explanations
bitwise-ors-of-subarrays
0
1
# Intuition\nWe need to find the number of distinct bitwise ORs of all non-empty subarrays of the input array. A brute-force approach would be to iterate through all possible subarrays, calculate their bitwise OR, and store unique results in a set. However, this approach will have a high time complexity. We can optimiz...
0
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!
🚀 Time: O(n * w) Space: O(n * w) | 📚 Detailed Explanations
bitwise-ors-of-subarrays
0
1
# Intuition\nWe need to find the number of distinct bitwise ORs of all non-empty subarrays of the input array. A brute-force approach would be to iterate through all possible subarrays, calculate their bitwise OR, and store unique results in a set. However, this approach will have a high time complexity. We can optimiz...
0
You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water. An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`. You may change `0`'s to `1`'s to connect the two islands to form **one island**. ...
null
Python short and clean solution
bitwise-ors-of-subarrays
0
1
```\nclass Solution:\n def subarrayBitwiseORs(self, A: List[int]) -> int:\n my_set = set(A)\n curr = 0\n prev = set()\n prev.add(A[0])\n for num in A[1:]:\n temp = set()\n for p in prev:\n temp.add(num | p)\n my_set.add(num | p)\n...
8
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!
Python short and clean solution
bitwise-ors-of-subarrays
0
1
```\nclass Solution:\n def subarrayBitwiseORs(self, A: List[int]) -> int:\n my_set = set(A)\n curr = 0\n prev = set()\n prev.add(A[0])\n for num in A[1:]:\n temp = set()\n for p in prev:\n temp.add(num | p)\n my_set.add(num | p)\n...
8
You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water. An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`. You may change `0`'s to `1`'s to connect the two islands to form **one island**. ...
null
Very Simple Approach, Beginner Friendly!!!!!!
orderly-queue
0
1
# Intuition\nThe questions seems to be very tricky at first but its all about recognizing the pattern. My initial thoughts were to sort the string for k > 1 and think of a way to write a solution for k == 1.\n\n# Approach\n1. for k == 1 we can try generating all the variations and store it in a set until the strings be...
2
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. **Example 1:** **Input:** s = "cba ", k = 1 **Output:** "ac...
null
Very Simple Approach, Beginner Friendly!!!!!!
orderly-queue
0
1
# Intuition\nThe questions seems to be very tricky at first but its all about recognizing the pattern. My initial thoughts were to sort the string for k > 1 and think of a way to write a solution for k == 1.\n\n# Approach\n1. for k == 1 we can try generating all the variations and store it in a set until the strings be...
2
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the che...
null
Simple Solution beats 97%
orderly-queue
0
1
# Code\n```\nclass Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n if k > 1: return \'\'.join(sorted(s))\n m = s\n for i in range(1, len(s)):\n # print(s[i: ]+s[: i])\n m = min(m, s[i: ]+s[: i])\n return m\n```
1
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. **Example 1:** **Input:** s = "cba ", k = 1 **Output:** "ac...
null
Simple Solution beats 97%
orderly-queue
0
1
# Code\n```\nclass Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n if k > 1: return \'\'.join(sorted(s))\n m = s\n for i in range(1, len(s)):\n # print(s[i: ]+s[: i])\n m = min(m, s[i: ]+s[: i])\n return m\n```
1
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the che...
null
Solution
orderly-queue
1
1
```C++ []\n#pragma once\n#include <algorithm>\n#include <string>\n\nclass Solution {\nprivate:\n static bool less(const std::string &s, size_t l, size_t r) {\n for (size_t i = 0; i < s.size(); ++i) {\n const auto s1 = s[(l + i) % s.size()];\n const auto s2 = s[(r + i) % s.size()];\n if (s1 != s2) {\n...
1
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. **Example 1:** **Input:** s = "cba ", k = 1 **Output:** "ac...
null
Solution
orderly-queue
1
1
```C++ []\n#pragma once\n#include <algorithm>\n#include <string>\n\nclass Solution {\nprivate:\n static bool less(const std::string &s, size_t l, size_t r) {\n for (size_t i = 0; i < s.size(); ++i) {\n const auto s1 = s[(l + i) % s.size()];\n const auto s2 = s[(r + i) % s.size()];\n if (s1 != s2) {\n...
1
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the che...
null
This is not a hard problem [no ds or algorithm applied]
orderly-queue
0
1
# Intuition\nI posted this so that you don\'t waste time, as I did behind this problem using heapq or any fancy algorithm.\n\n# Approach\nJust return sorted string if k > 1: yes, they should remove "hard" badge!\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n ...
1
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. **Example 1:** **Input:** s = "cba ", k = 1 **Output:** "ac...
null
This is not a hard problem [no ds or algorithm applied]
orderly-queue
0
1
# Intuition\nI posted this so that you don\'t waste time, as I did behind this problem using heapq or any fancy algorithm.\n\n# Approach\nJust return sorted string if k > 1: yes, they should remove "hard" badge!\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n ...
1
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the che...
null
Easy python solution using queue || TC: O(K^2+Nlog(N)), SC: O(N)
orderly-queue
0
1
```\nclass Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n st=""\n lst=list(s)\n lst.sort()\n queue=list(s)\n flg=defaultdict(lambda :0)\n if k==1:\n pt=[z for z in range(len(lst)) if s[z]==lst[0]]\n mn=s[pt[0]:]+s[:pt[0]]\n for ...
6
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. **Example 1:** **Input:** s = "cba ", k = 1 **Output:** "ac...
null
Easy python solution using queue || TC: O(K^2+Nlog(N)), SC: O(N)
orderly-queue
0
1
```\nclass Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n st=""\n lst=list(s)\n lst.sort()\n queue=list(s)\n flg=defaultdict(lambda :0)\n if k==1:\n pt=[z for z in range(len(lst)) if s[z]==lst[0]]\n mn=s[pt[0]:]+s[:pt[0]]\n for ...
6
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the che...
null
Python Easy Solution : Expalined
orderly-queue
0
1
```\nclass Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n if k>1:\n return \'\'.join(sorted(s))\n n=len(s)\n t=s*2 # t=cbacba\n ans=s # ans=cba\n for i in range(1,n):\n s1=t[i:i+n] # 1st move : s1=t[1:1+3] = bac\n ans=min(ans,...
1
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string.. Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_. **Example 1:** **Input:** s = "cba ", k = 1 **Output:** "ac...
null
Python Easy Solution : Expalined
orderly-queue
0
1
```\nclass Solution:\n def orderlyQueue(self, s: str, k: int) -> str:\n if k>1:\n return \'\'.join(sorted(s))\n n=len(s)\n t=s*2 # t=cbacba\n ans=s # ans=cba\n for i in range(1,n):\n s1=t[i:i+n] # 1st move : s1=t[1:1+3] = bac\n ans=min(ans,...
1
The chess knight has a **unique movement**, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an **L**). The possible movements of chess knight are shown in this diagaram: A chess knight can move as indicated in the che...
null
Solution
rle-iterator
1
1
```C++ []\nclass RLEIterator {\npublic:\n RLEIterator(const std::vector<int>& encoding)\n {\n m_encodings.reserve(encoding.size() / 2);\n for (int i = 0; i < encoding.size(); i += 2) {\n const int count = encoding[i];\n const int number = encoding[i + 1];\n m_encodin...
1
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the ...
null
Solution
rle-iterator
1
1
```C++ []\nclass RLEIterator {\npublic:\n RLEIterator(const std::vector<int>& encoding)\n {\n m_encodings.reserve(encoding.size() / 2);\n for (int i = 0; i < encoding.size(); i += 2) {\n const int count = encoding[i];\n const int number = encoding[i + 1];\n m_encodin...
1
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, t...
null
Easy python solution
rle-iterator
0
1
```\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.lst=encoding\n\n def next(self, n: int) -> int:\n num=-1\n while self.lst and n>0:\n if n<=self.lst[0]:\n self.lst[0]-=n \n n=0\n num=self.lst[1]\n e...
1
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the ...
null
Easy python solution
rle-iterator
0
1
```\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.lst=encoding\n\n def next(self, n: int) -> int:\n num=-1\n while self.lst and n>0:\n if n<=self.lst[0]:\n self.lst[0]-=n \n n=0\n num=self.lst[1]\n e...
1
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, t...
null
fastest solution possible in python
rle-iterator
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\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:1\n<!-- Add your space complexity here, e.g. $$O(n)$$ ...
5
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the ...
null
fastest solution possible in python
rle-iterator
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\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:1\n<!-- Add your space complexity here, e.g. $$O(n)$$ ...
5
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, t...
null
Python3 simple solution - RLE Iterator
rle-iterator
0
1
```\nclass RLEIterator:\n\n def __init__(self, A: List[int]):\n self.A = A[::-1]\n\n def next(self, n: int) -> int:\n acc = 0\n while acc < n:\n if not self.A:\n return -1\n times, num = self.A.pop(), self.A.pop()\n acc += times\n if acc ...
6
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the ...
null
Python3 simple solution - RLE Iterator
rle-iterator
0
1
```\nclass RLEIterator:\n\n def __init__(self, A: List[int]):\n self.A = A[::-1]\n\n def next(self, n: int) -> int:\n acc = 0\n while acc < n:\n if not self.A:\n return -1\n times, num = self.A.pop(), self.A.pop()\n acc += times\n if acc ...
6
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, t...
null
Keep a global pointer and handle three separate cases
rle-iterator
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIndexing and edge cases need to be handled correctly. Keep an idx pointer on which val we are currently. If n required is greater than current cnt, move idx and decrement leftover with diff, else decrement current cnt. We stay at the same...
0
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the ...
null
Keep a global pointer and handle three separate cases
rle-iterator
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIndexing and edge cases need to be handled correctly. Keep an idx pointer on which val we are currently. If n required is greater than current cnt, move idx and decrement leftover with diff, else decrement current cnt. We stay at the same...
0
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, t...
null
Noob simple solution
rle-iterator
0
1
# Intuition\nThe encoding allows 0s, so we\'ll leverage that.\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)$$ -->\n\n# Code\n```\nc...
0
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the ...
null
Noob simple solution
rle-iterator
0
1
# Intuition\nThe encoding allows 0s, so we\'ll leverage that.\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)$$ -->\n\n# Code\n```\nc...
0
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, t...
null
✅ Simple Python Solution | O(1) space
rle-iterator
0
1
- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.encoding = encoding\n i = 0\n while i < len(encoding):\n if encoding[i] == 0:\n encoding.pop(i)\n encoding.pop(i)\n else:\n ...
0
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the ...
null
✅ Simple Python Solution | O(1) space
rle-iterator
0
1
- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass RLEIterator:\n\n def __init__(self, encoding: List[int]):\n self.encoding = encoding\n i = 0\n while i < len(encoding):\n if encoding[i] == 0:\n encoding.pop(i)\n encoding.pop(i)\n else:\n ...
0
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, t...
null
Python Prefix Sum Binary Search
rle-iterator
0
1
# Intuition \n<!-- Describe your first thoughts on how to solve this problem. --> Similar to random pick with weight leetcode problem. Build the prefix sum on the frequencies. And perform binary search.\n\n\n# Complexity\n- Time complexity: O(logn) each call.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- ...
0
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the ...
null
Python Prefix Sum Binary Search
rle-iterator
0
1
# Intuition \n<!-- Describe your first thoughts on how to solve this problem. --> Similar to random pick with weight leetcode problem. Build the prefix sum on the frequencies. And perform binary search.\n\n\n# Complexity\n- Time complexity: O(logn) each call.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- ...
0
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, t...
null
Readable Python; knowing the problem is 90% of the battle!
rle-iterator
0
1
# Intuition\nAt first, I thought what would happen if I expanded the RLE out. Iterating through the decoded data is straightforward. Well, the tests have diabolical inputs and run out of memory! That is, the repeated elements could be in the hundreds of thousands or millions!\n\nSo you can operate on the encoded input ...
0
We can use run-length encoding (i.e., **RLE**) to encode a sequence of integers. In a run-length encoded array of even length `encoding` (**0-indexed**), for all even `i`, `encoding[i]` tells us the number of times that the non-negative integer value `encoding[i + 1]` is repeated in the sequence. * For example, the ...
null
Readable Python; knowing the problem is 90% of the battle!
rle-iterator
0
1
# Intuition\nAt first, I thought what would happen if I expanded the RLE out. Iterating through the decoded data is straightforward. Well, the tests have diabolical inputs and run out of memory! That is, the repeated elements could be in the hundreds of thousands or millions!\n\nSo you can operate on the encoded input ...
0
You are given two strings `stamp` and `target`. Initially, there is a string `s` of length `target.length` with all `s[i] == '?'`. In one turn, you can place `stamp` over `s` and replace every letter in the `s` with the corresponding letter from `stamp`. * For example, if `stamp = "abc "` and `target = "abcba "`, t...
null