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 solution - queue
number-of-recent-calls
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:0(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n)\n\n# Code\n```\nclass RecentCounter:\n\n de...
2
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake f...
null
Most brute force solution in Python---------------------------------------------------------------->
number-of-recent-calls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You 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
Most brute force solution in Python---------------------------------------------------------------->
number-of-recent-calls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake f...
null
Python Solution using queue
number-of-recent-calls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $...
2
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
Python Solution using queue
number-of-recent-calls
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $...
2
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake f...
null
[Python and C++] Multiple approaches Binary search, Dequeue
number-of-recent-calls
0
1
Python \n```\n# USING DEQUE\nclass RecentCounter:\n\n def __init__(self):\n self.queue = deque()\n\n def ping(self, t: int) -> int:\n queue = self.queue\n start = t - 3000\n queue.append(t)\n while(queue and queue[0] < start):\n queue.popleft()\n return len(que...
14
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
[Python and C++] Multiple approaches Binary search, Dequeue
number-of-recent-calls
0
1
Python \n```\n# USING DEQUE\nclass RecentCounter:\n\n def __init__(self):\n self.queue = deque()\n\n def ping(self, t: int) -> int:\n queue = self.queue\n start = t - 3000\n queue.append(t)\n while(queue and queue[0] < start):\n queue.popleft()\n return len(que...
14
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake f...
null
Python3 O(n) || O(n) with explanation
number-of-recent-calls
0
1
ERROR: type should be string, got "https://photos.app.goo.gl/sFqFttroBwRzf7MaA couldn\\'t upload it here dont know \\n\\n```\\nclass RecentCounter:\\n# O(n) || O(n)\\n# Runtime: 310ms 78.53% || memory: 19.6mb 46.67%\\n\\n def __init__(self):\\n self.queue = []\\n\\n def ping(self, t: int) -> int:\\n self.queue.append(t)\\n \\n while (t - self.queue[0]) > 3000:\\n self.queue.pop(0)\\n \\n return self.queue.__len__()\\n\\n\\n# Your RecentCounter object will be instantiated and called as such:\\n# obj = RecentCounter()\\n# param_1 = obj.ping(t)\\n```"
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
Python3 O(n) || O(n) with explanation
number-of-recent-calls
0
1
ERROR: type should be string, got "https://photos.app.goo.gl/sFqFttroBwRzf7MaA couldn\\'t upload it here dont know \\n\\n```\\nclass RecentCounter:\\n# O(n) || O(n)\\n# Runtime: 310ms 78.53% || memory: 19.6mb 46.67%\\n\\n def __init__(self):\\n self.queue = []\\n\\n def ping(self, t: int) -> int:\\n self.queue.append(t)\\n \\n while (t - self.queue[0]) > 3000:\\n self.queue.pop(0)\\n \\n return self.queue.__len__()\\n\\n\\n# Your RecentCounter object will be instantiated and called as such:\\n# obj = RecentCounter()\\n# param_1 = obj.ping(t)\\n```"
1
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake f...
null
Python3 Solution
shortest-bridge
0
1
\n```\nclass Solution:\n def shortestBridge(self, grid: List[List[int]]) -> int:\n \n directions = [(0,1), (0,-1), (1,0), (-1,0)] # right, left, up, down\n \n n = len(grid)\n m = len(grid[0])\n \n # find one point of a land\n def one_land(grid):\n for in_x...
2
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
Python3 Solution
shortest-bridge
0
1
\n```\nclass Solution:\n def shortestBridge(self, grid: List[List[int]]) -> int:\n \n directions = [(0,1), (0,-1), (1,0), (-1,0)] # right, left, up, down\n \n n = len(grid)\n m = len(grid[0])\n \n # find one point of a land\n def one_land(grid):\n for in_x...
2
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the bi...
null
Python O(hw) by BFS [w/ Visualization]
shortest-bridge
0
1
[Tutorial video in Chinese [ \u4E2D\u6587\u8A73\u89E3\u5F71\u7247 ]](https://youtu.be/S4oAouCWGgM)\n\n# Visualization\n![image.png](https://i.imgur.com/QtNCFpv.png)\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen it comes to **shortest path in graph** or in grid cells, think ...
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
Python O(hw) by BFS [w/ Visualization]
shortest-bridge
0
1
[Tutorial video in Chinese [ \u4E2D\u6587\u8A73\u89E3\u5F71\u7247 ]](https://youtu.be/S4oAouCWGgM)\n\n# Visualization\n![image.png](https://i.imgur.com/QtNCFpv.png)\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen it comes to **shortest path in graph** or in grid cells, think ...
1
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the bi...
null
Python BFS
shortest-bridge
0
1
```python []\nclass Solution:\n def shortestBridge(self, grid: List[List[int]]) -> int:\n N = len(grid)\n\n def get_neighbors(i, j):\n for ni, nj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):\n if 0 <= ni < N and 0 <= nj < N:\n yield ni, nj\n\n ...
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
Python BFS
shortest-bridge
0
1
```python []\nclass Solution:\n def shortestBridge(self, grid: List[List[int]]) -> int:\n N = len(grid)\n\n def get_neighbors(i, j):\n for ni, nj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):\n if 0 <= ni < N and 0 <= nj < N:\n yield ni, nj\n\n ...
1
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the bi...
null
Solution
shortest-bridge
1
1
```C++ []\nclass Solution {\npublic:\nvoid dfs(int r,int c,queue<pair<int,int>>&q,vector<vector<int>>&grid,int n){\n if(r<0 or c<0 or r>=n or c>=n or grid[r][c]==-1)return ;\n if(grid[r][c]==0)return ;\n q.push({r,c});\n grid[r][c]=-1;\n dfs(r-1,c,q,grid,n);\n dfs(r+1,c,q,grid,n);\n dfs(r,c-1,q,...
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
Solution
shortest-bridge
1
1
```C++ []\nclass Solution {\npublic:\nvoid dfs(int r,int c,queue<pair<int,int>>&q,vector<vector<int>>&grid,int n){\n if(r<0 or c<0 or r>=n or c>=n or grid[r][c]==-1)return ;\n if(grid[r][c]==0)return ;\n q.push({r,c});\n grid[r][c]=-1;\n dfs(r-1,c,q,grid,n);\n dfs(r+1,c,q,grid,n);\n dfs(r,c-1,q,...
1
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the bi...
null
Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand
shortest-bridge
1
1
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \u...
21
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🔥Java🔥C++🔥Simple Solution🔥Easy to Understand
shortest-bridge
1
1
**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers. This is only for first 10,000 Subscribers. **DON\'T FORGET** to Subscribe\n\n# Search \u...
21
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the bi...
null
Python BFS Solution with Brief Explanation
shortest-bridge
0
1
# Approach\nThis problem is simply a` multi-source BFS` problem where all nodes on `Island 1` are treated as if they are on the same level.\n<!-- Describe your approach to solving the problem. -->\n### The solution to this problem is :\nget all the components of `Island 1` and treate `Island one` components as if there...
2
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 BFS Solution with Brief Explanation
shortest-bridge
0
1
# Approach\nThis problem is simply a` multi-source BFS` problem where all nodes on `Island 1` are treated as if they are on the same level.\n<!-- Describe your approach to solving the problem. -->\n### The solution to this problem is :\nget all the components of `Island 1` and treate `Island one` components as if there...
2
You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree. Any node in the bi...
null
🚀 Easy Iterative Approach || Explained Intuition 🚀
knight-dialer
1
1
# Problem Description\n\nGiven a chess knight with its unique **L-shaped** movement, and a phone pad represented by numeric cells, determine the number of **distinct** phone numbers of length `n` that can be dialed. The knight starts on any numeric cell and performs `n - 1` valid knight jumps to create a number of leng...
41
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 Iterative Approach || Explained Intuition 🚀
knight-dialer
1
1
# Problem Description\n\nGiven a chess knight with its unique **L-shaped** movement, and a phone pad represented by numeric cells, determine the number of **distinct** phone numbers of length `n` that can be dialed. The knight starts on any numeric cell and performs `n - 1` valid knight jumps to create a number of leng...
41
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
Simple Solution || Beginner Friendly || Easy to Understand ✅
knight-dialer
1
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n###### The approach of this code is based on dynamic programming to compute the number of distinct phone numbers of length `n` that a knight can dial, starting from any digit. The knight moves according to the valid knight moves on a phone pad, and th...
60
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 || Beginner Friendly || Easy to Understand ✅
knight-dialer
1
1
# Approach\n<!-- Describe your approach to solving the problem. -->\n###### The approach of this code is based on dynamic programming to compute the number of distinct phone numbers of length `n` that a knight can dial, starting from any digit. The knight moves according to the valid knight moves on a phone pad, and th...
60
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
dp based on movement options
knight-dialer
0
1
The contributions to a digit in higher string length will follow the pattern below which is based on knight movement.\n\n0 -> 4,6\n1 -> 6,8\n2 -> 7,9\n3 -> 4,8\n4 -> 3,9,0\n5 -> \n6 -> 1,7,0\n7 -> 2,6\n8 -> 1,3\n9 -> 2,4\n\n```\nclass Solution:\n def knightDialer(self, n: int) -> int: \n arr = [1 for _...
13
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
dp based on movement options
knight-dialer
0
1
The contributions to a digit in higher string length will follow the pattern below which is based on knight movement.\n\n0 -> 4,6\n1 -> 6,8\n2 -> 7,9\n3 -> 4,8\n4 -> 3,9,0\n5 -> \n6 -> 1,7,0\n7 -> 2,6\n8 -> 1,3\n9 -> 2,4\n\n```\nclass Solution:\n def knightDialer(self, n: int) -> int: \n arr = [1 for _...
13
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
DP.py🫥
knight-dialer
0
1
# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n $$O(1)$$ \n# Code\n```js\nclass Solution:\n def knightDialer(self, n: int) -> int:\n arr=[1 for i in range(10)]\n for i in range(n-1):arr=[arr[4]+arr[6],arr[6]+arr[8],arr[7]+arr[9],arr[4]+arr[8],arr[3]+arr[9]+arr[0],0,arr[1]+...
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
DP.py🫥
knight-dialer
0
1
# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n $$O(1)$$ \n# Code\n```js\nclass Solution:\n def knightDialer(self, n: int) -> int:\n arr=[1 for i in range(10)]\n for i in range(n-1):arr=[arr[4]+arr[6],arr[6]+arr[8],arr[7]+arr[9],arr[4]+arr[8],arr[3]+arr[9]+arr[0],0,arr[1]+...
6
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
Python3 Solution
knight-dialer
0
1
\n```\nclass Solution:\n def knightDialer(self, n: int) -> int:\n dp=[1]*10\n mod=10**9+7\n \n for i in range(2,n+1):\n old_dp=dp.copy()\n \n dp[0]=old_dp[4]+old_dp[6]\n dp[1]=old_dp[6]+old_dp[8]\n dp[2]=old_dp[7]+old_dp[9]\n ...
3
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
Python3 Solution
knight-dialer
0
1
\n```\nclass Solution:\n def knightDialer(self, n: int) -> int:\n dp=[1]*10\n mod=10**9+7\n \n for i in range(2,n+1):\n old_dp=dp.copy()\n \n dp[0]=old_dp[4]+old_dp[6]\n dp[1]=old_dp[6]+old_dp[8]\n dp[2]=old_dp[7]+old_dp[9]\n ...
3
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
Easy Solution Optimized
knight-dialer
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
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 Solution Optimized
knight-dialer
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
3
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
✅☑[C++/Java/Python/JavaScript] || 6 Approaches || EXPLAINED🔥
knight-dialer
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Using Maps)***\n1. This code is trying to find the number of unique paths a knight can take on a phone dial pad for a given number of steps (`n`).\n1. Each digit on the dial pad represents a key/button, and the...
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
✅☑[C++/Java/Python/JavaScript] || 6 Approaches || EXPLAINED🔥
knight-dialer
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n#### ***Approach 1(Using Maps)***\n1. This code is trying to find the number of unique paths a knight can take on a phone dial pad for a given number of steps (`n`).\n1. Each digit on the dial pad represents a key/button, and the...
2
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
Fast🚀 & Easy🍼 to understand yet Naive?
knight-dialer
0
1
# Idea\nSo how many unique numbers can we get if we needed a number of length 1(n == 1).\n`0, 1, 2, 3, 4, 5, 6, 7, 8, 9`\n\nWhat about n == 2?\nObserve we cannot go to any other key from `5` or come to `5`.\nWhat does that mean from n == 2 we can never have a number which contains 5.\n\nFrom where can i come to 0, hmm,...
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
Fast🚀 & Easy🍼 to understand yet Naive?
knight-dialer
0
1
# Idea\nSo how many unique numbers can we get if we needed a number of length 1(n == 1).\n`0, 1, 2, 3, 4, 5, 6, 7, 8, 9`\n\nWhat about n == 2?\nObserve we cannot go to any other key from `5` or come to `5`.\nWhat does that mean from n == 2 we can never have a number which contains 5.\n\nFrom where can i come to 0, hmm,...
2
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
Python || Easy solution with dp || Beginner-friendly with explanations
knight-dialer
0
1
# Intuition\nWe are given a telephone numeric keypad and a chess piece - a knight; we need to count the number of unique digital combinations of length **n** that we can enter using this keyboard and a knight starting from any number - while the keyboard is limited only to numbers from 0 to 9 and we can only do correct...
5
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 with dp || Beginner-friendly with explanations
knight-dialer
0
1
# Intuition\nWe are given a telephone numeric keypad and a chess piece - a knight; we need to count the number of unique digital combinations of length **n** that we can enter using this keyboard and a knight starting from any number - while the keyboard is limited only to numbers from 0 to 9 and we can only do correct...
5
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
Python3 solution beats 100%
knight-dialer
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $...
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
Python3 solution beats 100%
knight-dialer
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $...
1
Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number. A **rational number** can be represented using up to three parts: , , and a . The num...
null
Solution
stamping-the-sequence
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> movesToStamp(string stamp, string target) {\n vector<int> res;\n vector<int> st;\n int szt = target.size();\n int szsp = stamp.size();\n for (int idx = 0; idx < target.size();) {\n int i = idx, p = 0;\n for (;...
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
Solution
stamping-the-sequence
1
1
```C++ []\nclass Solution {\npublic:\n vector<int> movesToStamp(string stamp, string target) {\n vector<int> res;\n vector<int> st;\n int szt = target.size();\n int szsp = stamp.size();\n for (int idx = 0; idx < target.size();) {\n int i = idx, p = 0;\n for (;...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`). You may return the answer in **an...
null
PYTHON SOL || WELL EXPLAINED || SIMPLE ITERATION || EASIEST YOU WILL FIND EVER !! ||
stamping-the-sequence
0
1
# EXPLANATION\n```\nThere can be two ways either starting from "?????" to target or we can start from target to "?????"\n\nNow why exactly is going from target to "?????" better ?\n\nSee we can get the answer more easily this way . Try for an example by yourself (pen-paper) and do both ways you\'ll get the answer\n\nN...
8
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 SOL || WELL EXPLAINED || SIMPLE ITERATION || EASIEST YOU WILL FIND EVER !! ||
stamping-the-sequence
0
1
# EXPLANATION\n```\nThere can be two ways either starting from "?????" to target or we can start from target to "?????"\n\nNow why exactly is going from target to "?????" better ?\n\nSee we can get the answer more easily this way . Try for an example by yourself (pen-paper) and do both ways you\'ll get the answer\n\nN...
8
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`). You may return the answer in **an...
null
[Python] Fastest solution with explanations (beats 100%)
stamping-the-sequence
0
1
# Preliminary notes:\n- For things to be possible:\n - The stamp and the target must start with the same letter.\n - The stamp and the target must end with the same letter.\n - The target must contain at least one occurrence of the full stamp.\n\n- Multiple solutions may be possible.\n Here, we try to build a so...
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
[Python] Fastest solution with explanations (beats 100%)
stamping-the-sequence
0
1
# Preliminary notes:\n- For things to be possible:\n - The stamp and the target must start with the same letter.\n - The stamp and the target must end with the same letter.\n - The target must contain at least one occurrence of the full stamp.\n\n- Multiple solutions may be possible.\n Here, we try to build a so...
1
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`. The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`). You may return the answer in **an...
null
[Python 3] Custom sort || beats 99,9% || 37ms 🥷🏼
reorder-data-in-log-files
0
1
```python3 []\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n def customSort(log):\n idx = log.index(\' \') + 1\n if log[idx].isalpha():\n return (0, log[idx:], log[:idx])\n return (1,)\n\n return sorted(logs, key=customSort)...
4
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits...
null
[Python 3] Custom sort || beats 99,9% || 37ms 🥷🏼
reorder-data-in-log-files
0
1
```python3 []\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n def customSort(log):\n idx = log.index(\' \') + 1\n if log[idx].isalpha():\n return (0, log[idx:], log[:idx])\n return (1,)\n\n return sorted(logs, key=customSort)...
4
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible b...
null
Python Custom Sort Solution With Explanation
reorder-data-in-log-files
0
1
```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n def sorting_algorithm(log):\n\t\t\t# Is a numerical log, make sure these entries appear on the right side without further sorting.\n\t\t\tif log[-1].isnumeric():\n\t\t\t\t# A tuple of one element. One element tuples need a trail...
104
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits...
null
Python Custom Sort Solution With Explanation
reorder-data-in-log-files
0
1
```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n def sorting_algorithm(log):\n\t\t\t# Is a numerical log, make sure these entries appear on the right side without further sorting.\n\t\t\tif log[-1].isnumeric():\n\t\t\t\t# A tuple of one element. One element tuples need a trail...
104
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible b...
null
Python solution with binary search
reorder-data-in-log-files
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate `Log` class with `__lt__` and `__gt__` methods.\nUse binary search to insert the new letter log.\n\n\n# Complexity\n- Time complexity: `O(nlogn)` \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(n)`...
1
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits...
null
Python solution with binary search
reorder-data-in-log-files
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCreate `Log` class with `__lt__` and `__gt__` methods.\nUse binary search to insert the new letter log.\n\n\n# Complexity\n- Time complexity: `O(nlogn)` \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: `O(n)`...
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible b...
null
[Python3] Sort the list use key
reorder-data-in-log-files
0
1
* define a function to label the item in logs with 0 if the rest is alphabet, with 1 if the rest is number.\n* sort the list according to the label.\n```\n#Python String | split()\nsplit() method returns a list of strings after breaking the given string by the specified separator.\nSyntax :\nstr.split(separator, maxs...
113
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits...
null
[Python3] Sort the list use key
reorder-data-in-log-files
0
1
* define a function to label the item in logs with 0 if the rest is alphabet, with 1 if the rest is number.\n* sort the list according to the label.\n```\n#Python String | split()\nsplit() method returns a list of strings after breaking the given string by the specified separator.\nSyntax :\nstr.split(separator, maxs...
113
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible b...
null
Python Solution
reorder-data-in-log-files
0
1
```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n digit = []\n letter = []\n \n for log in logs:\n if log[-1].isdigit():\n digit.append(log)\n else:\n letter.append(log)\n \n letter =...
1
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits...
null
Python Solution
reorder-data-in-log-files
0
1
```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n digit = []\n letter = []\n \n for log in logs:\n if log[-1].isdigit():\n digit.append(log)\n else:\n letter.append(log)\n \n letter =...
1
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible b...
null
Python3 simple solution
reorder-data-in-log-files
0
1
```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n l = []\n d = []\n for i in logs:\n if i.split()[1].isdigit():\n d.append(i)\n else:\n l.append(i)\n l.sort(key = lambda x : x.split()[0])\n l.sort(k...
13
You are given an array of `logs`. Each log is a space-delimited string of words, where the first word is the **identifier**. There are two types of logs: * **Letter-logs**: All words (except the identifier) consist of lowercase English letters. * **Digit-logs**: All words (except the identifier) consist of digits...
null
Python3 simple solution
reorder-data-in-log-files
0
1
```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n l = []\n d = []\n for i in logs:\n if i.split()[1].isdigit():\n d.append(i)\n else:\n l.append(i)\n l.sort(key = lambda x : x.split()[0])\n l.sort(k...
13
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible b...
null
Range Sum of Binary Search Tree
range-sum-of-bst
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the ra...
null
Range Sum of Binary Search Tree
range-sum-of-bst
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices. You...
null
[Java/Python 3] 3 similar recursive and 1 iterative methods w/ comment & analysis.
range-sum-of-bst
1
1
Three similar recursive and one iterative methods, choose one you like.\n\n**Method 1:**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) return 0; // base case.\n if (root.val < L) return rangeSumBST(root.right, L, R); // left branch excluded.\n if (root.val > R)...
385
Given the `root` node of a binary search tree and two integers `low` and `high`, return _the sum of values of all nodes with a value in the **inclusive** range_ `[low, high]`. **Example 1:** **Input:** root = \[10,5,15,3,7,null,18\], low = 7, high = 15 **Output:** 32 **Explanation:** Nodes 7, 10, and 15 are in the ra...
null
[Java/Python 3] 3 similar recursive and 1 iterative methods w/ comment & analysis.
range-sum-of-bst
1
1
Three similar recursive and one iterative methods, choose one you like.\n\n**Method 1:**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) return 0; // base case.\n if (root.val < L) return rangeSumBST(root.right, L, R); // left branch excluded.\n if (root.val > R)...
385
You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices. You...
null
Solution
minimum-area-rectangle
1
1
```C++ []\nclass Solution {\npublic:\n int minAreaRect(vector<vector<int>>& points) {\n unordered_map<int, vector<int>> u;\n for (auto &p: points)\n u[p[0]].push_back(p[1]);\n for (auto &[x,line]: u)\n sort(line.begin(), line.end());\n int ret = INT_MAX;\n for...
1
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\]...
null
Solution
minimum-area-rectangle
1
1
```C++ []\nclass Solution {\npublic:\n int minAreaRect(vector<vector<int>>& points) {\n unordered_map<int, vector<int>> u;\n for (auto &p: points)\n u[p[0]].push_back(p[1]);\n for (auto &[x,line]: u)\n sort(line.begin(), line.end());\n int ret = INT_MAX;\n for...
1
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three si...
null
Python - 2 Solutions with Explanation - O(N^2) - Beats 94%
minimum-area-rectangle
0
1
**Solution 1**\nConsider any 2 points `(x1, y1)`, `(x2, y2)` where `(x1, y1)` is the lower left and `(x2, y2)` is the upper right.\nIf there also exists points `(x1, y2)` and `(x2, y1)`, then we have a valid rectangle.\n`O(N^2)` @ 1200ms, beat 70%.\n```\ndef minAreaRect(self, points: List[List[int]]) -> int:\n point...
23
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\]...
null
Python - 2 Solutions with Explanation - O(N^2) - Beats 94%
minimum-area-rectangle
0
1
**Solution 1**\nConsider any 2 points `(x1, y1)`, `(x2, y2)` where `(x1, y1)` is the lower left and `(x2, y2)` is the upper right.\nIf there also exists points `(x1, y2)` and `(x2, y1)`, then we have a valid rectangle.\n`O(N^2)` @ 1200ms, beat 70%.\n```\ndef minAreaRect(self, points: List[List[int]]) -> int:\n point...
23
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three si...
null
PYTHON SOLUTION || PASSED ALL CASES || WELL EXPLAINED || EASY SOL ||
minimum-area-rectangle
0
1
# EXPLANATION\n```\n How is a rectangle is formed ?\n We have four points (x1,y1) , (x1,y2) , (x2,y1) , (x2,y2) :\n Here x1 != x2\n y1 != y2\n\t\t \nSo for every point in points i.e. say (x1,y1)\n First find every y2 --> y2 will be in the form (x1,y2)\n Then with the help of y2 find every x2 ...
1
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\]...
null
PYTHON SOLUTION || PASSED ALL CASES || WELL EXPLAINED || EASY SOL ||
minimum-area-rectangle
0
1
# EXPLANATION\n```\n How is a rectangle is formed ?\n We have four points (x1,y1) , (x1,y2) , (x2,y1) , (x2,y2) :\n Here x1 != x2\n y1 != y2\n\t\t \nSo for every point in points i.e. say (x1,y1)\n First find every y2 --> y2 will be in the form (x1,y2)\n Then with the help of y2 find every x2 ...
1
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three si...
null
✅ Simple O(n^2) brute force. 99% less mem. EXPLAINED
minimum-area-rectangle
0
1
# Intuition\nSimple $$O(n^2)$$ brute force\n# Approach\nConsider each two points pair (main diagonal).\nIf points on the other diagonal ware seen then we have a box, so update hte minimum area.\nRemember each point in `seen` set while iterating.\n\nIt turns to be 99% less mem and 40% faster.\n\nIf you find it anyhow us...
4
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\]...
null
✅ Simple O(n^2) brute force. 99% less mem. EXPLAINED
minimum-area-rectangle
0
1
# Intuition\nSimple $$O(n^2)$$ brute force\n# Approach\nConsider each two points pair (main diagonal).\nIf points on the other diagonal ware seen then we have a box, so update hte minimum area.\nRemember each point in `seen` set while iterating.\n\nIt turns to be 99% less mem and 40% faster.\n\nIf you find it anyhow us...
4
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three si...
null
Dictionary for x, set for y, 91% speed
minimum-area-rectangle
0
1
Runtime: 584 ms, faster than 91.32%\nMemory Usage: 14.7 MB, less than 30.81%\n```\nclass Solution:\n def minAreaRect(self, points) -> int:\n min_area = inf\n dict_x = defaultdict(set)\n for x, y in points:\n dict_x[x].add(y)\n dict_x = {x: set_y for x, set_y in dict_x.items() i...
7
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\]...
null
Dictionary for x, set for y, 91% speed
minimum-area-rectangle
0
1
Runtime: 584 ms, faster than 91.32%\nMemory Usage: 14.7 MB, less than 30.81%\n```\nclass Solution:\n def minAreaRect(self, points) -> int:\n min_area = inf\n dict_x = defaultdict(set)\n for x, y in points:\n dict_x[x].add(y)\n dict_x = {x: set_y for x, set_y in dict_x.items() i...
7
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three si...
null
✅ PYTHON || Beginner Friendly || O(n^2) 🔥🔥🔥
minimum-area-rectangle
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The idea is to iterate through all pairs of points in the given list and check if there exists a rectangle with those two points as diagonal vertices. \n- If a rectangle is found, calculate its area and update the minimum area found so ...
0
You are given an array of points in the **X-Y** plane `points` where `points[i] = [xi, yi]`. Return _the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes_. If there is not any such rectangle, return `0`. **Example 1:** **Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\]...
null
✅ PYTHON || Beginner Friendly || O(n^2) 🔥🔥🔥
minimum-area-rectangle
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The idea is to iterate through all pairs of points in the given list and check if there exists a rectangle with those two points as diagonal vertices. \n- If a rectangle is found, calculate its area and update the minimum area found so ...
0
Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. **Example 1:** **Input:** nums = \[2,1,2\] **Output:** 5 **Explanation:** You can form a triangle with three si...
null
Solution
distinct-subsequences-ii
1
1
```C++ []\nclass Solution {\n static constexpr int MOD = 1e9 + 7;\npublic:\n int distinctSubseqII(string s) {\n std::vector<int> last(26, -1);\n std::vector<long long> dp(s.size() + 1);\n dp[0] = 1;\n for(int i = 1; i <= s.size(); i++){\n dp[i] = 2 * dp[i-1];\n\n ...
1
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative...
null
Solution
distinct-subsequences-ii
1
1
```C++ []\nclass Solution {\n static constexpr int MOD = 1e9 + 7;\npublic:\n int distinctSubseqII(string s) {\n std::vector<int> last(26, -1);\n std::vector<long long> dp(s.size() + 1);\n dp[0] = 1;\n for(int i = 1; i <= s.size(); i++){\n dp[i] = 2 * dp[i-1];\n\n ...
1
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it be...
null
Python Hard
distinct-subsequences-ii
0
1
```\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n MOD = 10 ** 9 + 7\n N = len(s)\n\n @cache\n def calc(index, valid):\n if index == N:\n return int(valid)\n\n best = calc(index + 1, valid) \n best += calc(index + 1, True)\n...
0
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative...
null
Python Hard
distinct-subsequences-ii
0
1
```\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n MOD = 10 ** 9 + 7\n N = len(s)\n\n @cache\n def calc(index, valid):\n if index == N:\n return int(valid)\n\n best = calc(index + 1, valid) \n best += calc(index + 1, True)\n...
0
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it be...
null
🌟[PYTHON] Simple Code Explained In Detail 🌟
distinct-subsequences-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this problem efficiently, the code uses dynamic programming. The basic idea revolves around keeping track of the last index of occurrence of each character in a string. This makes it possible to calculate the number of different ...
0
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative...
null
🌟[PYTHON] Simple Code Explained In Detail 🌟
distinct-subsequences-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve this problem efficiently, the code uses dynamic programming. The basic idea revolves around keeping track of the last index of occurrence of each character in a string. This makes it possible to calculate the number of different ...
0
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it be...
null
python DP solution
distinct-subsequences-ii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
Given a string s, return _the number of **distinct non-empty subsequences** of_ `s`. Since the answer may be very large, return it **modulo** `109 + 7`. A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative...
null
python DP solution
distinct-subsequences-ii
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 array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it be...
null
Solution
valid-mountain-array
1
1
```C++ []\nclass Solution {\npublic:\n bool validMountainArray(vector<int>& arr) {\n int max=0;\n int index=0;\n\n int n=arr.size();\n\n for(int i=0; i<n; i++){\n if(max<arr[i]){\n max=arr[i];\n index=i;\n }\n }\n if(index==0 || index==n-1){\n...
1
Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_. Recall that arr is a mountain array if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1]...
null
Solution
valid-mountain-array
1
1
```C++ []\nclass Solution {\npublic:\n bool validMountainArray(vector<int>& arr) {\n int max=0;\n int index=0;\n\n int n=arr.size();\n\n for(int i=0; i<n; i++){\n if(max<arr[i]){\n max=arr[i];\n index=i;\n }\n }\n if(index==0 || index==n-1){\n...
1
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i...
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo...
✔️ [Python3] DOUBLE BARREL (*˘︶˘*).。.:*💕, Explained
valid-mountain-array
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe idea is to scan the array two times: First time we scan it from the start and the second - from the end. For every element we check the condition that the next element is greater than the current one. In the end,...
27
Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_. Recall that arr is a mountain array if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1]...
null
✔️ [Python3] DOUBLE BARREL (*˘︶˘*).。.:*💕, Explained
valid-mountain-array
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe idea is to scan the array two times: First time we scan it from the start and the second - from the end. For every element we check the condition that the next element is greater than the current one. In the end,...
27
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i...
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo...
easy solution
valid-mountain-array
0
1
\n# Complexity\n- Time complexity:$$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n n = len(arr)\n if n < 3:\n ...
1
Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_. Recall that arr is a mountain array if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1]...
null
easy solution
valid-mountain-array
0
1
\n# Complexity\n- Time complexity:$$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n n = len(arr)\n if n < 3:\n ...
1
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i...
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo...
Explanatory code in Python
valid-mountain-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck if the array is strictly increasing. If we reach a point where aray starts strictly decreasing, check if the elements in the array previously iterated are strictly increasing or not.\n\n# Approach\n<!-- Describe your approach to sol...
1
Given an array of integers `arr`, return _`true` if and only if it is a valid mountain array_. Recall that arr is a mountain array if and only if: * `arr.length >= 3` * There exists some `i` with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1]...
null
Explanatory code in Python
valid-mountain-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCheck if the array is strictly increasing. If we reach a point where aray starts strictly decreasing, check if the elements in the array previously iterated are strictly increasing or not.\n\n# Approach\n<!-- Describe your approach to sol...
1
Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`. A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray. More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i...
It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo...
Di String Match
di-string-match
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are ...
null
Di String Match
di-string-match
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Re...
null
Easy Python3 Solution
di-string-match
0
1
# Code\n```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n L,ic,dc=[],0,len(s)\n for i in s:\n if i==\'I\':\n L.append(ic)\n ic+=1\n else:\n L.append(dc)\n dc-=1\n if s[-1]==\'I\':L.append(ic)\n...
1
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are ...
null
Easy Python3 Solution
di-string-match
0
1
# Code\n```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n L,ic,dc=[],0,len(s)\n for i in s:\n if i==\'I\':\n L.append(ic)\n ic+=1\n else:\n L.append(dc)\n dc-=1\n if s[-1]==\'I\':L.append(ic)\n...
1
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Re...
null
easiest solution in python3 #mindblownaway
di-string-match
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
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are ...
null
easiest solution in python3 #mindblownaway
di-string-match
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Re...
null
Python Solution | Very Easy Explanation | Simple approach
di-string-match
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. -->\nThe diStringMatch function takes in a string arr containing only the characters "I" and "D", and returns a list of integers such that the first element is the smallest...
2
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are ...
null
Python Solution | Very Easy Explanation | Simple approach
di-string-match
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. -->\nThe diStringMatch function takes in a string arr containing only the characters "I" and "D", and returns a list of integers such that the first element is the smallest...
2
You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Re...
null
Python Solution with 92% better Time Complexity
di-string-match
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are ...
null